client.py 107 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193
  1. # client.py -- Implementation of the client side git protocols
  2. # Copyright (C) 2008-2013 Jelmer Vernooij <jelmer@jelmer.uk>
  3. #
  4. # SPDX-License-Identifier: Apache-2.0 OR GPL-2.0-or-later
  5. # Dulwich is dual-licensed under the Apache License, Version 2.0 and the GNU
  6. # General Public License as public by the Free Software Foundation; version 2.0
  7. # or (at your option) any later version. You can redistribute it and/or
  8. # modify it under the terms of either of these two licenses.
  9. #
  10. # Unless required by applicable law or agreed to in writing, software
  11. # distributed under the License is distributed on an "AS IS" BASIS,
  12. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  13. # See the License for the specific language governing permissions and
  14. # limitations under the License.
  15. #
  16. # You should have received a copy of the licenses; if not, see
  17. # <http://www.gnu.org/licenses/> for a copy of the GNU General Public License
  18. # and <http://www.apache.org/licenses/LICENSE-2.0> for a copy of the Apache
  19. # License, Version 2.0.
  20. #
  21. """Client side support for the Git protocol.
  22. The Dulwich client supports the following capabilities:
  23. * thin-pack
  24. * multi_ack_detailed
  25. * multi_ack
  26. * side-band-64k
  27. * ofs-delta
  28. * quiet
  29. * report-status
  30. * delete-refs
  31. * shallow
  32. Known capabilities that are not supported:
  33. * no-progress
  34. * include-tag
  35. """
  36. import copy
  37. import logging
  38. import os
  39. import select
  40. import socket
  41. import subprocess
  42. import sys
  43. from collections.abc import Iterable, Iterator
  44. from contextlib import closing
  45. from io import BufferedReader, BytesIO
  46. from typing import (
  47. IO,
  48. TYPE_CHECKING,
  49. Callable,
  50. ClassVar,
  51. Optional,
  52. Union,
  53. )
  54. from urllib.parse import quote as urlquote
  55. from urllib.parse import unquote as urlunquote
  56. from urllib.parse import urljoin, urlparse, urlunparse, urlunsplit
  57. if TYPE_CHECKING:
  58. import urllib3
  59. import dulwich
  60. from .config import Config, apply_instead_of, get_xdg_config_home_path
  61. from .errors import GitProtocolError, NotGitRepository, SendPackError
  62. from .pack import (
  63. PACK_SPOOL_FILE_MAX_SIZE,
  64. PackChunkGenerator,
  65. UnpackedObject,
  66. write_pack_from_container,
  67. )
  68. from .protocol import (
  69. _RBUFSIZE,
  70. CAPABILITIES_REF,
  71. CAPABILITY_AGENT,
  72. CAPABILITY_DELETE_REFS,
  73. CAPABILITY_FETCH,
  74. CAPABILITY_FILTER,
  75. CAPABILITY_INCLUDE_TAG,
  76. CAPABILITY_MULTI_ACK,
  77. CAPABILITY_MULTI_ACK_DETAILED,
  78. CAPABILITY_OFS_DELTA,
  79. CAPABILITY_QUIET,
  80. CAPABILITY_REPORT_STATUS,
  81. CAPABILITY_SHALLOW,
  82. CAPABILITY_SIDE_BAND_64K,
  83. CAPABILITY_SYMREF,
  84. CAPABILITY_THIN_PACK,
  85. COMMAND_DEEPEN,
  86. COMMAND_DONE,
  87. COMMAND_HAVE,
  88. COMMAND_SHALLOW,
  89. COMMAND_UNSHALLOW,
  90. COMMAND_WANT,
  91. DEFAULT_GIT_PROTOCOL_VERSION_FETCH,
  92. DEFAULT_GIT_PROTOCOL_VERSION_SEND,
  93. GIT_PROTOCOL_VERSIONS,
  94. KNOWN_RECEIVE_CAPABILITIES,
  95. KNOWN_UPLOAD_CAPABILITIES,
  96. SIDE_BAND_CHANNEL_DATA,
  97. SIDE_BAND_CHANNEL_FATAL,
  98. SIDE_BAND_CHANNEL_PROGRESS,
  99. TCP_GIT_PORT,
  100. ZERO_SHA,
  101. HangupException,
  102. PktLineParser,
  103. Protocol,
  104. agent_string,
  105. capability_agent,
  106. extract_capabilities,
  107. extract_capability_names,
  108. filter_ref_prefix,
  109. parse_capability,
  110. pkt_line,
  111. pkt_seq,
  112. )
  113. from .refs import (
  114. PEELED_TAG_SUFFIX,
  115. SYMREF,
  116. Ref,
  117. _import_remote_refs,
  118. _set_default_branch,
  119. _set_head,
  120. _set_origin_head,
  121. read_info_refs,
  122. split_peeled_refs,
  123. )
  124. from .repo import BaseRepo, Repo
  125. # Default ref prefix, used if none is specified.
  126. # GitHub defaults to just sending HEAD if no ref-prefix is
  127. # specified, so explicitly request all refs to match
  128. # behaviour with v1 when no ref-prefix is specified.
  129. DEFAULT_REF_PREFIX = [b"HEAD", b"refs/"]
  130. ObjectID = bytes
  131. logger = logging.getLogger(__name__)
  132. class InvalidWants(Exception):
  133. """Invalid wants."""
  134. def __init__(self, wants) -> None:
  135. Exception.__init__(
  136. self, f"requested wants not in server provided refs: {wants!r}"
  137. )
  138. class HTTPUnauthorized(Exception):
  139. """Raised when authentication fails."""
  140. def __init__(self, www_authenticate, url) -> None:
  141. Exception.__init__(self, "No valid credentials provided")
  142. self.www_authenticate = www_authenticate
  143. self.url = url
  144. class HTTPProxyUnauthorized(Exception):
  145. """Raised when proxy authentication fails."""
  146. def __init__(self, proxy_authenticate, url) -> None:
  147. Exception.__init__(self, "No valid proxy credentials provided")
  148. self.proxy_authenticate = proxy_authenticate
  149. self.url = url
  150. def _fileno_can_read(fileno):
  151. """Check if a file descriptor is readable."""
  152. return len(select.select([fileno], [], [], 0)[0]) > 0
  153. def _win32_peek_avail(handle):
  154. """Wrapper around PeekNamedPipe to check how many bytes are available."""
  155. from ctypes import byref, windll, wintypes
  156. c_avail = wintypes.DWORD()
  157. c_message = wintypes.DWORD()
  158. success = windll.kernel32.PeekNamedPipe(
  159. handle, None, 0, None, byref(c_avail), byref(c_message)
  160. )
  161. if not success:
  162. raise OSError(wintypes.GetLastError())
  163. return c_avail.value
  164. COMMON_CAPABILITIES = [CAPABILITY_OFS_DELTA, CAPABILITY_SIDE_BAND_64K]
  165. UPLOAD_CAPABILITIES = [
  166. CAPABILITY_THIN_PACK,
  167. CAPABILITY_MULTI_ACK,
  168. CAPABILITY_MULTI_ACK_DETAILED,
  169. CAPABILITY_SHALLOW,
  170. *COMMON_CAPABILITIES,
  171. ]
  172. RECEIVE_CAPABILITIES = [
  173. CAPABILITY_REPORT_STATUS,
  174. CAPABILITY_DELETE_REFS,
  175. *COMMON_CAPABILITIES,
  176. ]
  177. class ReportStatusParser:
  178. """Handle status as reported by servers with 'report-status' capability."""
  179. def __init__(self) -> None:
  180. self._done = False
  181. self._pack_status = None
  182. self._ref_statuses: list[bytes] = []
  183. def check(self):
  184. """Check if there were any errors and, if so, raise exceptions.
  185. Raises:
  186. SendPackError: Raised when the server could not unpack
  187. Returns:
  188. iterator over refs
  189. """
  190. if self._pack_status not in (b"unpack ok", None):
  191. raise SendPackError(self._pack_status)
  192. for status in self._ref_statuses:
  193. try:
  194. status, rest = status.split(b" ", 1)
  195. except ValueError:
  196. # malformed response, move on to the next one
  197. continue
  198. if status == b"ng":
  199. ref, error = rest.split(b" ", 1)
  200. yield ref, error.decode("utf-8")
  201. elif status == b"ok":
  202. yield rest, None
  203. else:
  204. raise GitProtocolError(f"invalid ref status {status!r}")
  205. def handle_packet(self, pkt) -> None:
  206. """Handle a packet.
  207. Raises:
  208. GitProtocolError: Raised when packets are received after a flush
  209. packet.
  210. """
  211. if self._done:
  212. raise GitProtocolError("received more data after status report")
  213. if pkt is None:
  214. self._done = True
  215. return
  216. if self._pack_status is None:
  217. self._pack_status = pkt.strip()
  218. else:
  219. ref_status = pkt.strip()
  220. self._ref_statuses.append(ref_status)
  221. def negotiate_protocol_version(proto) -> int:
  222. pkt = proto.read_pkt_line()
  223. if pkt is not None and pkt.strip() == b"version 2":
  224. return 2
  225. proto.unread_pkt_line(pkt)
  226. return 0
  227. def read_server_capabilities(pkt_seq):
  228. server_capabilities = []
  229. for pkt in pkt_seq:
  230. server_capabilities.append(pkt)
  231. return set(server_capabilities)
  232. def read_pkt_refs_v2(
  233. pkt_seq,
  234. ) -> tuple[dict[bytes, bytes], dict[bytes, bytes], dict[bytes, bytes]]:
  235. refs = {}
  236. symrefs = {}
  237. peeled = {}
  238. # Receive refs from server
  239. for pkt in pkt_seq:
  240. parts = pkt.rstrip(b"\n").split(b" ")
  241. sha = parts[0]
  242. if sha == b"unborn":
  243. sha = None
  244. ref = parts[1]
  245. for part in parts[2:]:
  246. if part.startswith(b"peeled:"):
  247. peeled[ref] = part[7:]
  248. elif part.startswith(b"symref-target:"):
  249. symrefs[ref] = part[14:]
  250. else:
  251. logging.warning("unknown part in pkt-ref: %s", part)
  252. refs[ref] = sha
  253. return refs, symrefs, peeled
  254. def read_pkt_refs_v1(pkt_seq) -> tuple[dict[bytes, bytes], set[bytes]]:
  255. server_capabilities = None
  256. refs = {}
  257. # Receive refs from server
  258. for pkt in pkt_seq:
  259. (sha, ref) = pkt.rstrip(b"\n").split(None, 1)
  260. if sha == b"ERR":
  261. raise GitProtocolError(ref.decode("utf-8", "replace"))
  262. if server_capabilities is None:
  263. (ref, server_capabilities) = extract_capabilities(ref)
  264. refs[ref] = sha
  265. if len(refs) == 0:
  266. return {}, set()
  267. if refs == {CAPABILITIES_REF: ZERO_SHA}:
  268. refs = {}
  269. assert server_capabilities is not None
  270. return refs, set(server_capabilities)
  271. class FetchPackResult:
  272. """Result of a fetch-pack operation.
  273. Attributes:
  274. refs: Dictionary with all remote refs
  275. symrefs: Dictionary with remote symrefs
  276. agent: User agent string
  277. """
  278. _FORWARDED_ATTRS: ClassVar[set[str]] = {
  279. "clear",
  280. "copy",
  281. "fromkeys",
  282. "get",
  283. "items",
  284. "keys",
  285. "pop",
  286. "popitem",
  287. "setdefault",
  288. "update",
  289. "values",
  290. "viewitems",
  291. "viewkeys",
  292. "viewvalues",
  293. }
  294. def __init__(
  295. self, refs, symrefs, agent, new_shallow=None, new_unshallow=None
  296. ) -> None:
  297. self.refs = refs
  298. self.symrefs = symrefs
  299. self.agent = agent
  300. self.new_shallow = new_shallow
  301. self.new_unshallow = new_unshallow
  302. def _warn_deprecated(self) -> None:
  303. import warnings
  304. warnings.warn(
  305. "Use FetchPackResult.refs instead.",
  306. DeprecationWarning,
  307. stacklevel=3,
  308. )
  309. def __eq__(self, other):
  310. if isinstance(other, dict):
  311. self._warn_deprecated()
  312. return self.refs == other
  313. return (
  314. self.refs == other.refs
  315. and self.symrefs == other.symrefs
  316. and self.agent == other.agent
  317. )
  318. def __contains__(self, name) -> bool:
  319. self._warn_deprecated()
  320. return name in self.refs
  321. def __getitem__(self, name):
  322. self._warn_deprecated()
  323. return self.refs[name]
  324. def __len__(self) -> int:
  325. self._warn_deprecated()
  326. return len(self.refs)
  327. def __iter__(self):
  328. self._warn_deprecated()
  329. return iter(self.refs)
  330. def __getattribute__(self, name):
  331. if name in type(self)._FORWARDED_ATTRS:
  332. self._warn_deprecated()
  333. return getattr(self.refs, name)
  334. return super().__getattribute__(name)
  335. def __repr__(self) -> str:
  336. return f"{self.__class__.__name__}({self.refs!r}, {self.symrefs!r}, {self.agent!r})"
  337. class LsRemoteResult:
  338. """Result of a ls-remote operation.
  339. Attributes:
  340. refs: Dictionary with all remote refs
  341. symrefs: Dictionary with remote symrefs
  342. """
  343. _FORWARDED_ATTRS: ClassVar[set[str]] = {
  344. "clear",
  345. "copy",
  346. "fromkeys",
  347. "get",
  348. "items",
  349. "keys",
  350. "pop",
  351. "popitem",
  352. "setdefault",
  353. "update",
  354. "values",
  355. "viewitems",
  356. "viewkeys",
  357. "viewvalues",
  358. }
  359. def __init__(self, refs, symrefs) -> None:
  360. self.refs = refs
  361. self.symrefs = symrefs
  362. def _warn_deprecated(self) -> None:
  363. import warnings
  364. warnings.warn(
  365. "Treating LsRemoteResult as a dictionary is deprecated. "
  366. "Use result.refs instead.",
  367. DeprecationWarning,
  368. stacklevel=3,
  369. )
  370. def __eq__(self, other):
  371. if isinstance(other, dict):
  372. self._warn_deprecated()
  373. return self.refs == other
  374. return self.refs == other.refs and self.symrefs == other.symrefs
  375. def __contains__(self, name) -> bool:
  376. self._warn_deprecated()
  377. return name in self.refs
  378. def __getitem__(self, name):
  379. self._warn_deprecated()
  380. return self.refs[name]
  381. def __len__(self) -> int:
  382. self._warn_deprecated()
  383. return len(self.refs)
  384. def __iter__(self):
  385. self._warn_deprecated()
  386. return iter(self.refs)
  387. def __getattribute__(self, name):
  388. if name in type(self)._FORWARDED_ATTRS:
  389. self._warn_deprecated()
  390. return getattr(self.refs, name)
  391. return super().__getattribute__(name)
  392. def __repr__(self) -> str:
  393. return f"{self.__class__.__name__}({self.refs!r}, {self.symrefs!r})"
  394. class SendPackResult:
  395. """Result of a upload-pack operation.
  396. Attributes:
  397. refs: Dictionary with all remote refs
  398. agent: User agent string
  399. ref_status: Optional dictionary mapping ref name to error message (if it
  400. failed to update), or None if it was updated successfully
  401. """
  402. _FORWARDED_ATTRS: ClassVar[set[str]] = {
  403. "clear",
  404. "copy",
  405. "fromkeys",
  406. "get",
  407. "items",
  408. "keys",
  409. "pop",
  410. "popitem",
  411. "setdefault",
  412. "update",
  413. "values",
  414. "viewitems",
  415. "viewkeys",
  416. "viewvalues",
  417. }
  418. def __init__(self, refs, agent=None, ref_status=None) -> None:
  419. self.refs = refs
  420. self.agent = agent
  421. self.ref_status = ref_status
  422. def _warn_deprecated(self) -> None:
  423. import warnings
  424. warnings.warn(
  425. "Use SendPackResult.refs instead.",
  426. DeprecationWarning,
  427. stacklevel=3,
  428. )
  429. def __eq__(self, other):
  430. if isinstance(other, dict):
  431. self._warn_deprecated()
  432. return self.refs == other
  433. return self.refs == other.refs and self.agent == other.agent
  434. def __contains__(self, name) -> bool:
  435. self._warn_deprecated()
  436. return name in self.refs
  437. def __getitem__(self, name):
  438. self._warn_deprecated()
  439. return self.refs[name]
  440. def __len__(self) -> int:
  441. self._warn_deprecated()
  442. return len(self.refs)
  443. def __iter__(self):
  444. self._warn_deprecated()
  445. return iter(self.refs)
  446. def __getattribute__(self, name):
  447. if name in type(self)._FORWARDED_ATTRS:
  448. self._warn_deprecated()
  449. return getattr(self.refs, name)
  450. return super().__getattribute__(name)
  451. def __repr__(self) -> str:
  452. return f"{self.__class__.__name__}({self.refs!r}, {self.agent!r})"
  453. def _read_shallow_updates(pkt_seq):
  454. new_shallow = set()
  455. new_unshallow = set()
  456. for pkt in pkt_seq:
  457. if pkt == b"shallow-info\n": # Git-protocol v2
  458. continue
  459. try:
  460. cmd, sha = pkt.split(b" ", 1)
  461. except ValueError:
  462. raise GitProtocolError(f"unknown command {pkt}")
  463. if cmd == COMMAND_SHALLOW:
  464. new_shallow.add(sha.strip())
  465. elif cmd == COMMAND_UNSHALLOW:
  466. new_unshallow.add(sha.strip())
  467. else:
  468. raise GitProtocolError(f"unknown command {pkt}")
  469. return (new_shallow, new_unshallow)
  470. class _v1ReceivePackHeader:
  471. def __init__(self, capabilities, old_refs, new_refs) -> None:
  472. self.want: list[bytes] = []
  473. self.have: list[bytes] = []
  474. self._it = self._handle_receive_pack_head(capabilities, old_refs, new_refs)
  475. self.sent_capabilities = False
  476. def __iter__(self):
  477. return self._it
  478. def _handle_receive_pack_head(self, capabilities, old_refs, new_refs):
  479. """Handle the head of a 'git-receive-pack' request.
  480. Args:
  481. capabilities: List of negotiated capabilities
  482. old_refs: Old refs, as received from the server
  483. new_refs: Refs to change
  484. Returns:
  485. (have, want) tuple
  486. """
  487. self.have = [x for x in old_refs.values() if not x == ZERO_SHA]
  488. for refname in new_refs:
  489. if not isinstance(refname, bytes):
  490. raise TypeError(f"refname is not a bytestring: {refname!r}")
  491. old_sha1 = old_refs.get(refname, ZERO_SHA)
  492. if not isinstance(old_sha1, bytes):
  493. raise TypeError(
  494. f"old sha1 for {refname!r} is not a bytestring: {old_sha1!r}"
  495. )
  496. new_sha1 = new_refs.get(refname, ZERO_SHA)
  497. if not isinstance(new_sha1, bytes):
  498. raise TypeError(
  499. f"old sha1 for {refname!r} is not a bytestring {new_sha1!r}"
  500. )
  501. if old_sha1 != new_sha1:
  502. logger.debug(
  503. "Sending updated ref %r: %r -> %r", refname, old_sha1, new_sha1
  504. )
  505. if self.sent_capabilities:
  506. yield old_sha1 + b" " + new_sha1 + b" " + refname
  507. else:
  508. yield (
  509. old_sha1
  510. + b" "
  511. + new_sha1
  512. + b" "
  513. + refname
  514. + b"\0"
  515. + b" ".join(sorted(capabilities))
  516. )
  517. self.sent_capabilities = True
  518. if new_sha1 not in self.have and new_sha1 != ZERO_SHA:
  519. self.want.append(new_sha1)
  520. yield None
  521. def _read_side_band64k_data(pkt_seq: Iterable[bytes]) -> Iterator[tuple[int, bytes]]:
  522. """Read per-channel data.
  523. This requires the side-band-64k capability.
  524. Args:
  525. pkt_seq: Sequence of packets to read
  526. """
  527. for pkt in pkt_seq:
  528. channel = ord(pkt[:1])
  529. yield channel, pkt[1:]
  530. def find_capability(capabilities, key, value):
  531. for capability in capabilities:
  532. k, v = parse_capability(capability)
  533. if k != key:
  534. continue
  535. if value and value not in v.split(b" "):
  536. continue
  537. return capability
  538. def _handle_upload_pack_head(
  539. proto,
  540. capabilities,
  541. graph_walker,
  542. wants,
  543. can_read,
  544. depth: Optional[int],
  545. protocol_version,
  546. ):
  547. """Handle the head of a 'git-upload-pack' request.
  548. Args:
  549. proto: Protocol object to read from
  550. capabilities: List of negotiated capabilities
  551. graph_walker: GraphWalker instance to call .ack() on
  552. wants: List of commits to fetch
  553. can_read: function that returns a boolean that indicates
  554. whether there is extra graph data to read on proto
  555. depth: Depth for request
  556. protocol_version: Neogiated Git protocol version.
  557. """
  558. assert isinstance(wants, list) and isinstance(wants[0], bytes)
  559. wantcmd = COMMAND_WANT + b" " + wants[0]
  560. if protocol_version is None:
  561. protocol_version = DEFAULT_GIT_PROTOCOL_VERSION_SEND
  562. if protocol_version != 2:
  563. wantcmd += b" " + b" ".join(sorted(capabilities))
  564. wantcmd += b"\n"
  565. proto.write_pkt_line(wantcmd)
  566. for want in wants[1:]:
  567. proto.write_pkt_line(COMMAND_WANT + b" " + want + b"\n")
  568. if depth not in (0, None) or getattr(graph_walker, "shallow", None):
  569. if protocol_version == 2:
  570. if not find_capability(capabilities, CAPABILITY_FETCH, CAPABILITY_SHALLOW):
  571. raise GitProtocolError(
  572. "server does not support shallow capability required for depth"
  573. )
  574. elif CAPABILITY_SHALLOW not in capabilities:
  575. raise GitProtocolError(
  576. "server does not support shallow capability required for depth"
  577. )
  578. for sha in graph_walker.shallow:
  579. proto.write_pkt_line(COMMAND_SHALLOW + b" " + sha + b"\n")
  580. if depth is not None:
  581. proto.write_pkt_line(
  582. COMMAND_DEEPEN + b" " + str(depth).encode("ascii") + b"\n"
  583. )
  584. if protocol_version == 2:
  585. proto.write_pkt_line(None)
  586. if protocol_version != 2:
  587. proto.write_pkt_line(None)
  588. if depth not in (0, None):
  589. if can_read is not None:
  590. (new_shallow, new_unshallow) = _read_shallow_updates(proto.read_pkt_seq())
  591. else:
  592. new_shallow = new_unshallow = None
  593. else:
  594. new_shallow = new_unshallow = set()
  595. have = next(graph_walker)
  596. while have:
  597. proto.write_pkt_line(COMMAND_HAVE + b" " + have + b"\n")
  598. if can_read is not None and can_read():
  599. pkt = proto.read_pkt_line()
  600. parts = pkt.rstrip(b"\n").split(b" ")
  601. if parts[0] == b"ACK":
  602. graph_walker.ack(parts[1])
  603. if parts[2] in (b"continue", b"common"):
  604. pass
  605. elif parts[2] == b"ready":
  606. break
  607. else:
  608. raise AssertionError(
  609. f"{parts[2]} not in ('continue', 'ready', 'common)"
  610. )
  611. have = next(graph_walker)
  612. proto.write_pkt_line(COMMAND_DONE + b"\n")
  613. if protocol_version == 2:
  614. proto.write_pkt_line(None)
  615. return (new_shallow, new_unshallow)
  616. def _handle_upload_pack_tail(
  617. proto,
  618. capabilities: set[bytes],
  619. graph_walker,
  620. pack_data: Callable[[bytes], None],
  621. progress: Optional[Callable[[bytes], None]] = None,
  622. rbufsize=_RBUFSIZE,
  623. protocol_version=0,
  624. ) -> None:
  625. """Handle the tail of a 'git-upload-pack' request.
  626. Args:
  627. proto: Protocol object to read from
  628. capabilities: List of negotiated capabilities
  629. graph_walker: GraphWalker instance to call .ack() on
  630. pack_data: Function to call with pack data
  631. progress: Optional progress reporting function
  632. rbufsize: Read buffer size
  633. protocol_version: Neogiated Git protocol version.
  634. """
  635. pkt = proto.read_pkt_line()
  636. while pkt:
  637. parts = pkt.rstrip(b"\n").split(b" ")
  638. if protocol_version == 2 and parts[0] != "packfile":
  639. break
  640. else:
  641. if parts[0] == b"ACK":
  642. graph_walker.ack(parts[1])
  643. if parts[0] == b"NAK":
  644. graph_walker.nak()
  645. if len(parts) < 3 or parts[2] not in (
  646. b"ready",
  647. b"continue",
  648. b"common",
  649. ):
  650. break
  651. pkt = proto.read_pkt_line()
  652. if CAPABILITY_SIDE_BAND_64K in capabilities or protocol_version == 2:
  653. if progress is None:
  654. # Just ignore progress data
  655. def progress(x) -> None:
  656. pass
  657. for chan, data in _read_side_band64k_data(proto.read_pkt_seq()):
  658. if chan == SIDE_BAND_CHANNEL_DATA:
  659. pack_data(data)
  660. elif chan == SIDE_BAND_CHANNEL_PROGRESS:
  661. progress(data)
  662. else:
  663. raise AssertionError(f"Invalid sideband channel {chan}")
  664. else:
  665. while True:
  666. data = proto.read(rbufsize)
  667. if data == b"":
  668. break
  669. pack_data(data)
  670. def _extract_symrefs_and_agent(capabilities):
  671. """Extract symrefs and agent from capabilities.
  672. Args:
  673. capabilities: List of capabilities
  674. Returns:
  675. (symrefs, agent) tuple
  676. """
  677. symrefs = {}
  678. agent = None
  679. for capability in capabilities:
  680. k, v = parse_capability(capability)
  681. if k == CAPABILITY_SYMREF:
  682. (src, dst) = v.split(b":", 1)
  683. symrefs[src] = dst
  684. if k == CAPABILITY_AGENT:
  685. agent = v
  686. return (symrefs, agent)
  687. # TODO(durin42): this doesn't correctly degrade if the server doesn't
  688. # support some capabilities. This should work properly with servers
  689. # that don't support multi_ack.
  690. class GitClient:
  691. """Git smart server client."""
  692. def __init__(
  693. self,
  694. thin_packs=True,
  695. report_activity=None,
  696. quiet=False,
  697. include_tags=False,
  698. **kwargs,
  699. ) -> None:
  700. """Create a new GitClient instance.
  701. Args:
  702. thin_packs: Whether or not thin packs should be retrieved
  703. report_activity: Optional callback for reporting transport
  704. activity.
  705. include_tags: send annotated tags when sending the objects they point
  706. to
  707. """
  708. self._report_activity = report_activity
  709. self._report_status_parser: Optional[ReportStatusParser] = None
  710. self._fetch_capabilities = set(UPLOAD_CAPABILITIES)
  711. self._fetch_capabilities.add(capability_agent())
  712. self._send_capabilities = set(RECEIVE_CAPABILITIES)
  713. self._send_capabilities.add(capability_agent())
  714. if quiet:
  715. self._send_capabilities.add(CAPABILITY_QUIET)
  716. if not thin_packs:
  717. self._fetch_capabilities.remove(CAPABILITY_THIN_PACK)
  718. if include_tags:
  719. self._fetch_capabilities.add(CAPABILITY_INCLUDE_TAG)
  720. self.protocol_version = 0 # will be overridden later
  721. def get_url(self, path) -> str:
  722. """Retrieves full url to given path.
  723. Args:
  724. path: Repository path (as string)
  725. Returns:
  726. Url to path (as string)
  727. """
  728. raise NotImplementedError(self.get_url)
  729. @classmethod
  730. def from_parsedurl(cls, parsedurl, **kwargs) -> "GitClient":
  731. """Create an instance of this client from a urlparse.parsed object.
  732. Args:
  733. parsedurl: Result of urlparse()
  734. Returns:
  735. A `GitClient` object
  736. """
  737. raise NotImplementedError(cls.from_parsedurl)
  738. def send_pack(
  739. self,
  740. path: str,
  741. update_refs,
  742. generate_pack_data: Callable[
  743. [set[bytes], set[bytes], bool], tuple[int, Iterator[UnpackedObject]]
  744. ],
  745. progress=None,
  746. ) -> SendPackResult:
  747. """Upload a pack to a remote repository.
  748. Args:
  749. path: Repository path (as bytestring)
  750. update_refs: Function to determine changes to remote refs. Receive
  751. dict with existing remote refs, returns dict with
  752. changed refs (name -> sha, where sha=ZERO_SHA for deletions)
  753. generate_pack_data: Function that can return a tuple
  754. with number of objects and list of pack data to include
  755. progress: Optional progress function
  756. Returns:
  757. SendPackResult object
  758. Raises:
  759. SendPackError: if server rejects the pack data
  760. """
  761. raise NotImplementedError(self.send_pack)
  762. def clone(
  763. self,
  764. path,
  765. target_path,
  766. mkdir: bool = True,
  767. bare: bool = False,
  768. origin: Optional[str] = "origin",
  769. checkout=None,
  770. branch=None,
  771. progress=None,
  772. depth: Optional[int] = None,
  773. ref_prefix: Optional[list[Ref]] = None,
  774. filter_spec=None,
  775. protocol_version: Optional[int] = None,
  776. ) -> Repo:
  777. """Clone a repository."""
  778. if mkdir:
  779. os.mkdir(target_path)
  780. try:
  781. target = None
  782. if not bare:
  783. target = Repo.init(target_path)
  784. if checkout is None:
  785. checkout = True
  786. else:
  787. if checkout:
  788. raise ValueError("checkout and bare are incompatible")
  789. target = Repo.init_bare(target_path)
  790. # TODO(jelmer): abstract method for get_location?
  791. if isinstance(self, (LocalGitClient, SubprocessGitClient)):
  792. encoded_path = path.encode("utf-8")
  793. else:
  794. encoded_path = self.get_url(path).encode("utf-8")
  795. assert target is not None
  796. if origin is not None:
  797. target_config = target.get_config()
  798. target_config.set(
  799. (b"remote", origin.encode("utf-8")), b"url", encoded_path
  800. )
  801. target_config.set(
  802. (b"remote", origin.encode("utf-8")),
  803. b"fetch",
  804. b"+refs/heads/*:refs/remotes/" + origin.encode("utf-8") + b"/*",
  805. )
  806. target_config.write_to_path()
  807. ref_message = b"clone: from " + encoded_path
  808. result = self.fetch(
  809. path,
  810. target,
  811. progress=progress,
  812. depth=depth,
  813. ref_prefix=ref_prefix,
  814. filter_spec=filter_spec,
  815. protocol_version=protocol_version,
  816. )
  817. if origin is not None:
  818. _import_remote_refs(
  819. target.refs, origin, result.refs, message=ref_message
  820. )
  821. origin_head = result.symrefs.get(b"HEAD")
  822. origin_sha = result.refs.get(b"HEAD")
  823. if origin is None or (origin_sha and not origin_head):
  824. # set detached HEAD
  825. target.refs[b"HEAD"] = origin_sha
  826. head = origin_sha
  827. else:
  828. _set_origin_head(target.refs, origin.encode("utf-8"), origin_head)
  829. head_ref = _set_default_branch(
  830. target.refs,
  831. origin.encode("utf-8"),
  832. origin_head,
  833. branch,
  834. ref_message,
  835. )
  836. # Update target head
  837. if head_ref:
  838. head = _set_head(target.refs, head_ref, ref_message)
  839. else:
  840. head = None
  841. if checkout and head is not None:
  842. target.reset_index()
  843. except BaseException:
  844. if target is not None:
  845. target.close()
  846. if mkdir:
  847. import shutil
  848. shutil.rmtree(target_path)
  849. raise
  850. return target
  851. def fetch(
  852. self,
  853. path: str,
  854. target: BaseRepo,
  855. determine_wants: Optional[
  856. Callable[[dict[bytes, bytes], Optional[int]], list[bytes]]
  857. ] = None,
  858. progress: Optional[Callable[[bytes], None]] = None,
  859. depth: Optional[int] = None,
  860. ref_prefix: Optional[list[Ref]] = None,
  861. filter_spec: Optional[bytes] = None,
  862. protocol_version: Optional[int] = None,
  863. ) -> FetchPackResult:
  864. """Fetch into a target repository.
  865. Args:
  866. path: Path to fetch from (as bytestring)
  867. target: Target repository to fetch into
  868. determine_wants: Optional function to determine what refs to fetch.
  869. Receives dictionary of name->sha, should return
  870. list of shas to fetch. Defaults to all shas.
  871. progress: Optional progress function
  872. depth: Depth to fetch at
  873. ref_prefix: List of prefixes of desired references, as a list of
  874. bytestrings. Filtering is done by the server if supported, and
  875. client side otherwise.
  876. filter_spec: A git-rev-list-style object filter spec, as bytestring.
  877. Only used if the server supports the Git protocol-v2 'filter'
  878. feature, and ignored otherwise.
  879. protocol_version: Desired Git protocol version. By default the highest
  880. mutually supported protocol version will be used.
  881. Returns:
  882. Dictionary with all remote refs (not just those fetched)
  883. """
  884. if determine_wants is None:
  885. determine_wants = target.object_store.determine_wants_all
  886. if CAPABILITY_THIN_PACK in self._fetch_capabilities:
  887. from tempfile import SpooledTemporaryFile
  888. f: IO[bytes] = SpooledTemporaryFile(
  889. max_size=PACK_SPOOL_FILE_MAX_SIZE,
  890. prefix="incoming-",
  891. dir=getattr(target.object_store, "path", None),
  892. )
  893. def commit() -> None:
  894. if f.tell():
  895. f.seek(0)
  896. target.object_store.add_thin_pack(f.read, None, progress=progress) # type: ignore
  897. f.close()
  898. def abort() -> None:
  899. f.close()
  900. else:
  901. f, commit, abort = target.object_store.add_pack()
  902. try:
  903. result = self.fetch_pack(
  904. path,
  905. determine_wants,
  906. target.get_graph_walker(),
  907. f.write,
  908. progress=progress,
  909. depth=depth,
  910. ref_prefix=ref_prefix,
  911. filter_spec=filter_spec,
  912. protocol_version=protocol_version,
  913. )
  914. except BaseException:
  915. abort()
  916. raise
  917. else:
  918. commit()
  919. target.update_shallow(result.new_shallow, result.new_unshallow)
  920. return result
  921. def fetch_pack(
  922. self,
  923. path: str,
  924. determine_wants,
  925. graph_walker,
  926. pack_data,
  927. *,
  928. progress: Optional[Callable[[bytes], None]] = None,
  929. depth: Optional[int] = None,
  930. ref_prefix: Optional[list[Ref]] = None,
  931. filter_spec=None,
  932. protocol_version: Optional[int] = None,
  933. ) -> FetchPackResult:
  934. """Retrieve a pack from a git smart server.
  935. Args:
  936. path: Remote path to fetch from
  937. determine_wants: Function determine what refs
  938. to fetch. Receives dictionary of name->sha, should return
  939. list of shas to fetch.
  940. graph_walker: Object with next() and ack().
  941. pack_data: Callback called for each bit of data in the pack
  942. progress: Callback for progress reports (strings)
  943. depth: Shallow fetch depth
  944. ref_prefix: List of prefixes of desired references, as a list of
  945. bytestrings. Filtering is done by the server if supported, and
  946. client side otherwise.
  947. filter_spec: A git-rev-list-style object filter spec, as bytestring.
  948. Only used if the server supports the Git protocol-v2 'filter'
  949. feature, and ignored otherwise.
  950. protocol_version: Desired Git protocol version. By default the highest
  951. mutually supported protocol version will be used.
  952. Returns:
  953. FetchPackResult object
  954. """
  955. raise NotImplementedError(self.fetch_pack)
  956. def get_refs(
  957. self,
  958. path,
  959. protocol_version: Optional[int] = None,
  960. ref_prefix: Optional[list[Ref]] = None,
  961. ) -> LsRemoteResult:
  962. """Retrieve the current refs from a git smart server.
  963. Args:
  964. path: Path to the repo to fetch from. (as bytestring)
  965. protocol_version: Desired Git protocol version.
  966. ref_prefix: Prefix filter for refs.
  967. Returns:
  968. LsRemoteResult object with refs and symrefs
  969. """
  970. raise NotImplementedError(self.get_refs)
  971. @staticmethod
  972. def _should_send_pack(new_refs):
  973. # The packfile MUST NOT be sent if the only command used is delete.
  974. return any(sha != ZERO_SHA for sha in new_refs.values())
  975. def _negotiate_receive_pack_capabilities(self, server_capabilities):
  976. negotiated_capabilities = self._send_capabilities & server_capabilities
  977. (agent, _symrefs) = _extract_symrefs_and_agent(server_capabilities)
  978. (extract_capability_names(server_capabilities) - KNOWN_RECEIVE_CAPABILITIES)
  979. # TODO(jelmer): warn about unknown capabilities
  980. return negotiated_capabilities, agent
  981. def _handle_receive_pack_tail(
  982. self,
  983. proto: Protocol,
  984. capabilities: set[bytes],
  985. progress: Optional[Callable[[bytes], None]] = None,
  986. ) -> Optional[dict[bytes, Optional[str]]]:
  987. """Handle the tail of a 'git-receive-pack' request.
  988. Args:
  989. proto: Protocol object to read from
  990. capabilities: List of negotiated capabilities
  991. progress: Optional progress reporting function
  992. Returns:
  993. dict mapping ref name to:
  994. error message if the ref failed to update
  995. None if it was updated successfully
  996. """
  997. if CAPABILITY_SIDE_BAND_64K in capabilities or self.protocol_version == 2:
  998. if progress is None:
  999. def progress(x) -> None:
  1000. pass
  1001. if CAPABILITY_REPORT_STATUS in capabilities:
  1002. assert self._report_status_parser is not None
  1003. pktline_parser = PktLineParser(self._report_status_parser.handle_packet)
  1004. for chan, data in _read_side_band64k_data(proto.read_pkt_seq()):
  1005. if chan == SIDE_BAND_CHANNEL_DATA:
  1006. if CAPABILITY_REPORT_STATUS in capabilities:
  1007. pktline_parser.parse(data)
  1008. elif chan == SIDE_BAND_CHANNEL_PROGRESS:
  1009. progress(data)
  1010. else:
  1011. raise AssertionError(f"Invalid sideband channel {chan}")
  1012. else:
  1013. if CAPABILITY_REPORT_STATUS in capabilities:
  1014. assert self._report_status_parser
  1015. for pkt in proto.read_pkt_seq():
  1016. self._report_status_parser.handle_packet(pkt)
  1017. if self._report_status_parser is not None:
  1018. return dict(self._report_status_parser.check())
  1019. return None
  1020. def _negotiate_upload_pack_capabilities(self, server_capabilities):
  1021. (extract_capability_names(server_capabilities) - KNOWN_UPLOAD_CAPABILITIES)
  1022. # TODO(jelmer): warn about unknown capabilities
  1023. fetch_capa = None
  1024. for capability in server_capabilities:
  1025. k, v = parse_capability(capability)
  1026. if self.protocol_version == 2 and k == CAPABILITY_FETCH:
  1027. fetch_capa = CAPABILITY_FETCH
  1028. fetch_features = []
  1029. v = v.strip().split(b" ")
  1030. if b"shallow" in v:
  1031. fetch_features.append(CAPABILITY_SHALLOW)
  1032. if b"filter" in v:
  1033. fetch_features.append(CAPABILITY_FILTER)
  1034. for i in range(len(fetch_features)):
  1035. if i == 0:
  1036. fetch_capa += b"="
  1037. else:
  1038. fetch_capa += b" "
  1039. fetch_capa += fetch_features[i]
  1040. (symrefs, agent) = _extract_symrefs_and_agent(server_capabilities)
  1041. negotiated_capabilities = self._fetch_capabilities & server_capabilities
  1042. if fetch_capa:
  1043. negotiated_capabilities.add(fetch_capa)
  1044. return (negotiated_capabilities, symrefs, agent)
  1045. def archive(
  1046. self,
  1047. path,
  1048. committish,
  1049. write_data,
  1050. progress=None,
  1051. write_error=None,
  1052. format=None,
  1053. subdirs=None,
  1054. prefix=None,
  1055. ) -> None:
  1056. """Retrieve an archive of the specified tree."""
  1057. raise NotImplementedError(self.archive)
  1058. @staticmethod
  1059. def _warn_filter_objects() -> None:
  1060. import warnings
  1061. warnings.warn(
  1062. "object filtering not recognized by server, ignoring",
  1063. UserWarning,
  1064. )
  1065. def check_wants(wants, refs) -> None:
  1066. """Check that a set of wants is valid.
  1067. Args:
  1068. wants: Set of object SHAs to fetch
  1069. refs: Refs dictionary to check against
  1070. """
  1071. missing = set(wants) - {
  1072. v for (k, v) in refs.items() if not k.endswith(PEELED_TAG_SUFFIX)
  1073. }
  1074. if missing:
  1075. raise InvalidWants(missing)
  1076. def _remote_error_from_stderr(stderr):
  1077. if stderr is None:
  1078. return HangupException()
  1079. lines = [line.rstrip(b"\n") for line in stderr.readlines()]
  1080. for line in lines:
  1081. if line.startswith(b"ERROR: "):
  1082. return GitProtocolError(line[len(b"ERROR: ") :].decode("utf-8", "replace"))
  1083. return HangupException(lines)
  1084. class TraditionalGitClient(GitClient):
  1085. """Traditional Git client."""
  1086. DEFAULT_ENCODING = "utf-8"
  1087. def __init__(self, path_encoding=DEFAULT_ENCODING, **kwargs) -> None:
  1088. self._remote_path_encoding = path_encoding
  1089. super().__init__(**kwargs)
  1090. def _connect(
  1091. self,
  1092. cmd: bytes,
  1093. path: Union[str, bytes],
  1094. protocol_version: Optional[int] = None,
  1095. ) -> tuple[Protocol, Callable[[], bool], Optional[IO[bytes]]]:
  1096. """Create a connection to the server.
  1097. This method is abstract - concrete implementations should
  1098. implement their own variant which connects to the server and
  1099. returns an initialized Protocol object with the service ready
  1100. for use and a can_read function which may be used to see if
  1101. reads would block.
  1102. Args:
  1103. cmd: The git service name to which we should connect.
  1104. path: The path we should pass to the service. (as bytestirng)
  1105. protocol_version: Desired Git protocol version. By default the highest
  1106. mutually supported protocol version will be used.
  1107. """
  1108. raise NotImplementedError
  1109. def send_pack(self, path, update_refs, generate_pack_data, progress=None):
  1110. """Upload a pack to a remote repository.
  1111. Args:
  1112. path: Repository path (as bytestring)
  1113. update_refs: Function to determine changes to remote refs.
  1114. Receive dict with existing remote refs, returns dict with
  1115. changed refs (name -> sha, where sha=ZERO_SHA for deletions)
  1116. generate_pack_data: Function that can return a tuple with
  1117. number of objects and pack data to upload.
  1118. progress: Optional callback called with progress updates
  1119. Returns:
  1120. SendPackResult
  1121. Raises:
  1122. SendPackError: if server rejects the pack data
  1123. """
  1124. self.protocol_version = DEFAULT_GIT_PROTOCOL_VERSION_SEND
  1125. proto, unused_can_read, stderr = self._connect(b"receive-pack", path)
  1126. with proto:
  1127. try:
  1128. old_refs, server_capabilities = read_pkt_refs_v1(proto.read_pkt_seq())
  1129. except HangupException as exc:
  1130. raise _remote_error_from_stderr(stderr) from exc
  1131. (
  1132. negotiated_capabilities,
  1133. agent,
  1134. ) = self._negotiate_receive_pack_capabilities(server_capabilities)
  1135. if CAPABILITY_REPORT_STATUS in negotiated_capabilities:
  1136. self._report_status_parser = ReportStatusParser()
  1137. report_status_parser = self._report_status_parser
  1138. try:
  1139. new_refs = orig_new_refs = update_refs(dict(old_refs))
  1140. except BaseException:
  1141. proto.write_pkt_line(None)
  1142. raise
  1143. if set(new_refs.items()).issubset(set(old_refs.items())):
  1144. proto.write_pkt_line(None)
  1145. return SendPackResult(new_refs, agent=agent, ref_status={})
  1146. if CAPABILITY_DELETE_REFS not in server_capabilities:
  1147. # Server does not support deletions. Fail later.
  1148. new_refs = dict(orig_new_refs)
  1149. for ref, sha in orig_new_refs.items():
  1150. if sha == ZERO_SHA:
  1151. if CAPABILITY_REPORT_STATUS in negotiated_capabilities:
  1152. report_status_parser._ref_statuses.append(
  1153. b"ng " + ref + b" remote does not support deleting refs"
  1154. )
  1155. report_status_parser._ref_status_ok = False
  1156. del new_refs[ref]
  1157. if new_refs is None:
  1158. proto.write_pkt_line(None)
  1159. return SendPackResult(old_refs, agent=agent, ref_status={})
  1160. if len(new_refs) == 0 and orig_new_refs:
  1161. # NOOP - Original new refs filtered out by policy
  1162. proto.write_pkt_line(None)
  1163. if report_status_parser is not None:
  1164. ref_status = dict(report_status_parser.check())
  1165. else:
  1166. ref_status = None
  1167. return SendPackResult(old_refs, agent=agent, ref_status=ref_status)
  1168. header_handler = _v1ReceivePackHeader(
  1169. negotiated_capabilities, old_refs, new_refs
  1170. )
  1171. for pkt in header_handler:
  1172. proto.write_pkt_line(pkt)
  1173. pack_data_count, pack_data = generate_pack_data(
  1174. header_handler.have,
  1175. header_handler.want,
  1176. ofs_delta=(CAPABILITY_OFS_DELTA in negotiated_capabilities),
  1177. progress=progress,
  1178. )
  1179. if self._should_send_pack(new_refs):
  1180. for chunk in PackChunkGenerator(
  1181. pack_data_count, pack_data, progress=progress
  1182. ):
  1183. proto.write(chunk)
  1184. ref_status = self._handle_receive_pack_tail(
  1185. proto, negotiated_capabilities, progress
  1186. )
  1187. return SendPackResult(new_refs, agent=agent, ref_status=ref_status)
  1188. def fetch_pack(
  1189. self,
  1190. path,
  1191. determine_wants,
  1192. graph_walker,
  1193. pack_data,
  1194. progress=None,
  1195. depth: Optional[int] = None,
  1196. ref_prefix: Optional[list[Ref]] = None,
  1197. filter_spec=None,
  1198. protocol_version: Optional[int] = None,
  1199. ):
  1200. """Retrieve a pack from a git smart server.
  1201. Args:
  1202. path: Remote path to fetch from
  1203. determine_wants: Function determine what refs
  1204. to fetch. Receives dictionary of name->sha, should return
  1205. list of shas to fetch.
  1206. graph_walker: Object with next() and ack().
  1207. pack_data: Callback called for each bit of data in the pack
  1208. progress: Callback for progress reports (strings)
  1209. depth: Shallow fetch depth
  1210. ref_prefix: List of prefixes of desired references, as a list of
  1211. bytestrings. Filtering is done by the server if supported, and
  1212. client side otherwise.
  1213. filter_spec: A git-rev-list-style object filter spec, as bytestring.
  1214. Only used if the server supports the Git protocol-v2 'filter'
  1215. feature, and ignored otherwise.
  1216. protocol_version: Desired Git protocol version. By default the highest
  1217. mutually supported protocol version will be used.
  1218. Returns:
  1219. FetchPackResult object
  1220. """
  1221. if (
  1222. protocol_version is not None
  1223. and protocol_version not in GIT_PROTOCOL_VERSIONS
  1224. ):
  1225. raise ValueError(f"unknown Git protocol version {protocol_version}")
  1226. proto, can_read, stderr = self._connect(b"upload-pack", path, protocol_version)
  1227. server_protocol_version = negotiate_protocol_version(proto)
  1228. if server_protocol_version not in GIT_PROTOCOL_VERSIONS:
  1229. raise ValueError(
  1230. f"unknown Git protocol version {server_protocol_version} used by server"
  1231. )
  1232. if protocol_version and server_protocol_version > protocol_version:
  1233. raise ValueError(
  1234. f"bad Git protocol version {server_protocol_version} used by server"
  1235. )
  1236. self.protocol_version = server_protocol_version
  1237. with proto:
  1238. if self.protocol_version == 2:
  1239. try:
  1240. server_capabilities = read_server_capabilities(proto.read_pkt_seq())
  1241. except HangupException as exc:
  1242. raise _remote_error_from_stderr(stderr) from exc
  1243. (
  1244. negotiated_capabilities,
  1245. symrefs,
  1246. agent,
  1247. ) = self._negotiate_upload_pack_capabilities(server_capabilities)
  1248. proto.write_pkt_line(b"command=ls-refs\n")
  1249. proto.write(b"0001") # delim-pkt
  1250. proto.write_pkt_line(b"symrefs")
  1251. proto.write_pkt_line(b"peel")
  1252. if ref_prefix is None:
  1253. ref_prefix = DEFAULT_REF_PREFIX
  1254. for prefix in ref_prefix:
  1255. proto.write_pkt_line(b"ref-prefix " + prefix)
  1256. proto.write_pkt_line(None)
  1257. refs, symrefs, _peeled = read_pkt_refs_v2(proto.read_pkt_seq())
  1258. else:
  1259. try:
  1260. refs, server_capabilities = read_pkt_refs_v1(proto.read_pkt_seq())
  1261. except HangupException as exc:
  1262. raise _remote_error_from_stderr(stderr) from exc
  1263. (
  1264. negotiated_capabilities,
  1265. symrefs,
  1266. agent,
  1267. ) = self._negotiate_upload_pack_capabilities(server_capabilities)
  1268. if ref_prefix is not None:
  1269. refs = filter_ref_prefix(refs, ref_prefix)
  1270. if refs is None:
  1271. proto.write_pkt_line(None)
  1272. return FetchPackResult(refs, symrefs, agent)
  1273. try:
  1274. if depth is not None:
  1275. wants = determine_wants(refs, depth=depth)
  1276. else:
  1277. wants = determine_wants(refs)
  1278. except BaseException:
  1279. proto.write_pkt_line(None)
  1280. raise
  1281. if wants is not None:
  1282. wants = [cid for cid in wants if cid != ZERO_SHA]
  1283. if not wants:
  1284. proto.write_pkt_line(None)
  1285. return FetchPackResult(refs, symrefs, agent)
  1286. if self.protocol_version == 2:
  1287. proto.write_pkt_line(b"command=fetch\n")
  1288. proto.write(b"0001") # delim-pkt
  1289. if CAPABILITY_THIN_PACK in self._fetch_capabilities:
  1290. proto.write(pkt_line(b"thin-pack\n"))
  1291. if (
  1292. find_capability(
  1293. negotiated_capabilities, CAPABILITY_FETCH, CAPABILITY_FILTER
  1294. )
  1295. and filter_spec
  1296. ):
  1297. proto.write(pkt_line(b"filter %s\n" % filter_spec))
  1298. elif filter_spec:
  1299. self._warn_filter_objects()
  1300. elif filter_spec:
  1301. self._warn_filter_objects()
  1302. (new_shallow, new_unshallow) = _handle_upload_pack_head(
  1303. proto,
  1304. negotiated_capabilities,
  1305. graph_walker,
  1306. wants,
  1307. can_read,
  1308. depth=depth,
  1309. protocol_version=self.protocol_version,
  1310. )
  1311. _handle_upload_pack_tail(
  1312. proto,
  1313. negotiated_capabilities,
  1314. graph_walker,
  1315. pack_data,
  1316. progress,
  1317. protocol_version=self.protocol_version,
  1318. )
  1319. return FetchPackResult(refs, symrefs, agent, new_shallow, new_unshallow)
  1320. def get_refs(
  1321. self,
  1322. path,
  1323. protocol_version: Optional[int] = None,
  1324. ref_prefix: Optional[list[Ref]] = None,
  1325. ):
  1326. """Retrieve the current refs from a git smart server."""
  1327. # stock `git ls-remote` uses upload-pack
  1328. if (
  1329. protocol_version is not None
  1330. and protocol_version not in GIT_PROTOCOL_VERSIONS
  1331. ):
  1332. raise ValueError(f"unknown Git protocol version {protocol_version}")
  1333. proto, _, stderr = self._connect(b"upload-pack", path, protocol_version)
  1334. server_protocol_version = negotiate_protocol_version(proto)
  1335. if server_protocol_version not in GIT_PROTOCOL_VERSIONS:
  1336. raise ValueError(
  1337. f"unknown Git protocol version {server_protocol_version} used by server"
  1338. )
  1339. if protocol_version and server_protocol_version > protocol_version:
  1340. raise ValueError(
  1341. f"bad Git protocol version {server_protocol_version} used by server"
  1342. )
  1343. self.protocol_version = server_protocol_version
  1344. if self.protocol_version == 2:
  1345. server_capabilities = read_server_capabilities(proto.read_pkt_seq())
  1346. proto.write_pkt_line(b"command=ls-refs\n")
  1347. proto.write(b"0001") # delim-pkt
  1348. proto.write_pkt_line(b"symrefs")
  1349. proto.write_pkt_line(b"peel")
  1350. if ref_prefix is None:
  1351. ref_prefix = DEFAULT_REF_PREFIX
  1352. for prefix in ref_prefix:
  1353. proto.write_pkt_line(b"ref-prefix " + prefix)
  1354. proto.write_pkt_line(None)
  1355. with proto:
  1356. try:
  1357. refs, symrefs, peeled = read_pkt_refs_v2(proto.read_pkt_seq())
  1358. except HangupException as exc:
  1359. raise _remote_error_from_stderr(stderr) from exc
  1360. proto.write_pkt_line(None)
  1361. for refname, refvalue in peeled.items():
  1362. refs[refname + PEELED_TAG_SUFFIX] = refvalue
  1363. return LsRemoteResult(refs, symrefs)
  1364. else:
  1365. with proto:
  1366. try:
  1367. refs, server_capabilities = read_pkt_refs_v1(proto.read_pkt_seq())
  1368. except HangupException as exc:
  1369. raise _remote_error_from_stderr(stderr) from exc
  1370. proto.write_pkt_line(None)
  1371. (symrefs, _agent) = _extract_symrefs_and_agent(server_capabilities)
  1372. if ref_prefix is not None:
  1373. refs = filter_ref_prefix(refs, ref_prefix)
  1374. return LsRemoteResult(refs, symrefs)
  1375. def archive(
  1376. self,
  1377. path,
  1378. committish,
  1379. write_data,
  1380. progress=None,
  1381. write_error=None,
  1382. format=None,
  1383. subdirs=None,
  1384. prefix=None,
  1385. ) -> None:
  1386. proto, can_read, stderr = self._connect(b"upload-archive", path)
  1387. with proto:
  1388. if format is not None:
  1389. proto.write_pkt_line(b"argument --format=" + format)
  1390. proto.write_pkt_line(b"argument " + committish)
  1391. if subdirs is not None:
  1392. for subdir in subdirs:
  1393. proto.write_pkt_line(b"argument " + subdir)
  1394. if prefix is not None:
  1395. proto.write_pkt_line(b"argument --prefix=" + prefix)
  1396. proto.write_pkt_line(None)
  1397. try:
  1398. pkt = proto.read_pkt_line()
  1399. except HangupException as exc:
  1400. raise _remote_error_from_stderr(stderr) from exc
  1401. if pkt == b"NACK\n" or pkt == b"NACK":
  1402. return
  1403. elif pkt == b"ACK\n" or pkt == b"ACK":
  1404. pass
  1405. elif pkt and pkt.startswith(b"ERR "):
  1406. raise GitProtocolError(pkt[4:].rstrip(b"\n").decode("utf-8", "replace"))
  1407. else:
  1408. raise AssertionError(f"invalid response {pkt!r}")
  1409. ret = proto.read_pkt_line()
  1410. if ret is not None:
  1411. raise AssertionError("expected pkt tail")
  1412. for chan, data in _read_side_band64k_data(proto.read_pkt_seq()):
  1413. if chan == SIDE_BAND_CHANNEL_DATA:
  1414. write_data(data)
  1415. elif chan == SIDE_BAND_CHANNEL_PROGRESS:
  1416. progress(data)
  1417. elif chan == SIDE_BAND_CHANNEL_FATAL:
  1418. write_error(data)
  1419. else:
  1420. raise AssertionError(f"Invalid sideband channel {chan}")
  1421. class TCPGitClient(TraditionalGitClient):
  1422. """A Git Client that works over TCP directly (i.e. git://)."""
  1423. def __init__(self, host, port=None, **kwargs) -> None:
  1424. if port is None:
  1425. port = TCP_GIT_PORT
  1426. self._host = host
  1427. self._port = port
  1428. super().__init__(**kwargs)
  1429. @classmethod
  1430. def from_parsedurl(cls, parsedurl, **kwargs):
  1431. return cls(parsedurl.hostname, port=parsedurl.port, **kwargs)
  1432. def get_url(self, path):
  1433. netloc = self._host
  1434. if self._port is not None and self._port != TCP_GIT_PORT:
  1435. netloc += f":{self._port}"
  1436. return urlunsplit(("git", netloc, path, "", ""))
  1437. def _connect(
  1438. self,
  1439. cmd: bytes,
  1440. path: Union[str, bytes],
  1441. protocol_version: Optional[int] = None,
  1442. ) -> tuple[Protocol, Callable[[], bool], Optional[IO[bytes]]]:
  1443. if not isinstance(cmd, bytes):
  1444. raise TypeError(cmd)
  1445. if not isinstance(path, bytes):
  1446. path = path.encode(self._remote_path_encoding)
  1447. sockaddrs = socket.getaddrinfo(
  1448. self._host, self._port, socket.AF_UNSPEC, socket.SOCK_STREAM
  1449. )
  1450. s = None
  1451. err = OSError(f"no address found for {self._host}")
  1452. for family, socktype, protof, canonname, sockaddr in sockaddrs:
  1453. s = socket.socket(family, socktype, protof)
  1454. s.setsockopt(socket.IPPROTO_TCP, socket.TCP_NODELAY, 1)
  1455. try:
  1456. s.connect(sockaddr)
  1457. break
  1458. except OSError as e:
  1459. err = e
  1460. if s is not None:
  1461. s.close()
  1462. s = None
  1463. if s is None:
  1464. raise err
  1465. # -1 means system default buffering
  1466. rfile = s.makefile("rb", -1)
  1467. # 0 means unbuffered
  1468. wfile = s.makefile("wb", 0)
  1469. def close() -> None:
  1470. rfile.close()
  1471. wfile.close()
  1472. s.close()
  1473. proto = Protocol(
  1474. rfile.read,
  1475. wfile.write,
  1476. close,
  1477. report_activity=self._report_activity,
  1478. )
  1479. if path.startswith(b"/~"):
  1480. path = path[1:]
  1481. if cmd == b"upload-pack":
  1482. if protocol_version is None:
  1483. self.protocol_version = DEFAULT_GIT_PROTOCOL_VERSION_FETCH
  1484. else:
  1485. self.protocol_version = protocol_version
  1486. else:
  1487. self.protocol_version = DEFAULT_GIT_PROTOCOL_VERSION_SEND
  1488. if cmd == b"upload-pack" and self.protocol_version == 2:
  1489. # Git protocol version advertisement is hidden behind two NUL bytes
  1490. # for compatibility with older Git server implementations, which
  1491. # would crash if something other than a "host=" header was found
  1492. # after the first NUL byte.
  1493. version_str = b"\0\0version=%d\0" % self.protocol_version
  1494. else:
  1495. version_str = b""
  1496. # TODO(jelmer): Alternative to ascii?
  1497. proto.send_cmd(
  1498. b"git-" + cmd, path, b"host=" + self._host.encode("ascii") + version_str
  1499. )
  1500. return proto, lambda: _fileno_can_read(s), None
  1501. class SubprocessWrapper:
  1502. """A socket-like object that talks to a subprocess via pipes."""
  1503. def __init__(self, proc) -> None:
  1504. self.proc = proc
  1505. self.read = BufferedReader(proc.stdout).read
  1506. self.write = proc.stdin.write
  1507. @property
  1508. def stderr(self):
  1509. return self.proc.stderr
  1510. def can_read(self):
  1511. if sys.platform == "win32":
  1512. from msvcrt import get_osfhandle
  1513. handle = get_osfhandle(self.proc.stdout.fileno())
  1514. return _win32_peek_avail(handle) != 0
  1515. else:
  1516. return _fileno_can_read(self.proc.stdout.fileno())
  1517. def close(self, timeout: Optional[int] = 60) -> None:
  1518. self.proc.stdin.close()
  1519. self.proc.stdout.close()
  1520. if self.proc.stderr:
  1521. self.proc.stderr.close()
  1522. try:
  1523. self.proc.wait(timeout=timeout)
  1524. except subprocess.TimeoutExpired as e:
  1525. self.proc.kill()
  1526. self.proc.wait()
  1527. raise GitProtocolError(
  1528. f"Git subprocess did not terminate within {timeout} seconds; killed it."
  1529. ) from e
  1530. def find_git_command() -> list[str]:
  1531. """Find command to run for system Git (usually C Git)."""
  1532. if sys.platform == "win32": # support .exe, .bat and .cmd
  1533. try: # to avoid overhead
  1534. import pywintypes
  1535. import win32api
  1536. except ImportError: # run through cmd.exe with some overhead
  1537. return ["cmd", "/c", "git"]
  1538. else:
  1539. try:
  1540. status, git = win32api.FindExecutable("git")
  1541. return [git]
  1542. except pywintypes.error:
  1543. return ["cmd", "/c", "git"]
  1544. else:
  1545. return ["git"]
  1546. class SubprocessGitClient(TraditionalGitClient):
  1547. """Git client that talks to a server using a subprocess."""
  1548. @classmethod
  1549. def from_parsedurl(cls, parsedurl, **kwargs):
  1550. return cls(**kwargs)
  1551. git_command = None
  1552. def _connect(
  1553. self,
  1554. service: bytes,
  1555. path: Union[bytes, str],
  1556. protocol_version: Optional[int] = None,
  1557. ) -> tuple[Protocol, Callable[[], bool], Optional[IO[bytes]]]:
  1558. if not isinstance(service, bytes):
  1559. raise TypeError(service)
  1560. if isinstance(path, bytes):
  1561. path = path.decode(self._remote_path_encoding)
  1562. if self.git_command is None:
  1563. git_command = find_git_command()
  1564. argv = [*git_command, service.decode("ascii"), path]
  1565. p = subprocess.Popen(
  1566. argv,
  1567. bufsize=0,
  1568. stdin=subprocess.PIPE,
  1569. stdout=subprocess.PIPE,
  1570. stderr=subprocess.PIPE,
  1571. )
  1572. pw = SubprocessWrapper(p)
  1573. return (
  1574. Protocol(
  1575. pw.read,
  1576. pw.write,
  1577. pw.close,
  1578. report_activity=self._report_activity,
  1579. ),
  1580. pw.can_read,
  1581. p.stderr,
  1582. )
  1583. class LocalGitClient(GitClient):
  1584. """Git Client that just uses a local on-disk repository."""
  1585. def __init__(
  1586. self,
  1587. thin_packs: bool = True,
  1588. report_activity=None,
  1589. config: Optional[Config] = None,
  1590. ) -> None:
  1591. """Create a new LocalGitClient instance.
  1592. Args:
  1593. thin_packs: Whether or not thin packs should be retrieved
  1594. report_activity: Optional callback for reporting transport
  1595. activity.
  1596. """
  1597. self._report_activity = report_activity
  1598. # Ignore the thin_packs argument
  1599. def get_url(self, path):
  1600. return urlunsplit(("file", "", path, "", ""))
  1601. @classmethod
  1602. def from_parsedurl(cls, parsedurl, **kwargs):
  1603. return cls(**kwargs)
  1604. @classmethod
  1605. def _open_repo(cls, path):
  1606. if not isinstance(path, str):
  1607. path = os.fsdecode(path)
  1608. return closing(Repo(path))
  1609. def send_pack(self, path, update_refs, generate_pack_data, progress=None):
  1610. """Upload a pack to a local on-disk repository.
  1611. Args:
  1612. path: Repository path (as bytestring)
  1613. update_refs: Function to determine changes to remote refs.
  1614. Receive dict with existing remote refs, returns dict with
  1615. changed refs (name -> sha, where sha=ZERO_SHA for deletions)
  1616. with number of items and pack data to upload.
  1617. progress: Optional progress function
  1618. Returns:
  1619. SendPackResult
  1620. Raises:
  1621. SendPackError: if server rejects the pack data
  1622. """
  1623. if not progress:
  1624. def progress(x) -> None:
  1625. pass
  1626. with self._open_repo(path) as target:
  1627. old_refs = target.get_refs()
  1628. new_refs = update_refs(dict(old_refs))
  1629. have = [sha1 for sha1 in old_refs.values() if sha1 != ZERO_SHA]
  1630. want = []
  1631. for refname, new_sha1 in new_refs.items():
  1632. if (
  1633. new_sha1 not in have
  1634. and new_sha1 not in want
  1635. and new_sha1 != ZERO_SHA
  1636. ):
  1637. want.append(new_sha1)
  1638. if not want and set(new_refs.items()).issubset(set(old_refs.items())):
  1639. return SendPackResult(new_refs, ref_status={})
  1640. target.object_store.add_pack_data(
  1641. *generate_pack_data(have, want, ofs_delta=True)
  1642. )
  1643. ref_status = {}
  1644. for refname, new_sha1 in new_refs.items():
  1645. old_sha1 = old_refs.get(refname, ZERO_SHA)
  1646. if new_sha1 != ZERO_SHA:
  1647. if not target.refs.set_if_equals(refname, old_sha1, new_sha1):
  1648. msg = f"unable to set {refname} to {new_sha1}"
  1649. progress(msg)
  1650. ref_status[refname] = msg
  1651. else:
  1652. if not target.refs.remove_if_equals(refname, old_sha1):
  1653. progress(f"unable to remove {refname}")
  1654. ref_status[refname] = "unable to remove"
  1655. return SendPackResult(new_refs, ref_status=ref_status)
  1656. def fetch(
  1657. self,
  1658. path: str,
  1659. target: BaseRepo,
  1660. determine_wants: Optional[
  1661. Callable[[dict[bytes, bytes], Optional[int]], list[bytes]]
  1662. ] = None,
  1663. progress: Optional[Callable[[bytes], None]] = None,
  1664. depth: Optional[int] = None,
  1665. ref_prefix: Optional[list[Ref]] = None,
  1666. filter_spec: Optional[bytes] = None,
  1667. protocol_version: Optional[int] = None,
  1668. **kwargs,
  1669. ):
  1670. """Fetch into a target repository.
  1671. Args:
  1672. path: Path to fetch from (as bytestring)
  1673. target: Target repository to fetch into
  1674. determine_wants: Optional function determine what refs
  1675. to fetch. Receives dictionary of name->sha, should return
  1676. list of shas to fetch. Defaults to all shas.
  1677. progress: Optional progress function
  1678. depth: Shallow fetch depth
  1679. ref_prefix: List of prefixes of desired references, as a list of
  1680. bytestrings. Filtering is done by the server if supported, and
  1681. client side otherwise.
  1682. filter_spec: A git-rev-list-style object filter spec, as bytestring.
  1683. Only used if the server supports the Git protocol-v2 'filter'
  1684. feature, and ignored otherwise.
  1685. Returns:
  1686. FetchPackResult object
  1687. """
  1688. with self._open_repo(path) as r:
  1689. refs = r.fetch(
  1690. target,
  1691. determine_wants=determine_wants,
  1692. progress=progress,
  1693. depth=depth,
  1694. )
  1695. return FetchPackResult(refs, r.refs.get_symrefs(), agent_string())
  1696. def fetch_pack(
  1697. self,
  1698. path,
  1699. determine_wants,
  1700. graph_walker,
  1701. pack_data,
  1702. progress=None,
  1703. depth: Optional[int] = None,
  1704. ref_prefix: Optional[list[Ref]] = None,
  1705. filter_spec: Optional[bytes] = None,
  1706. protocol_version: Optional[int] = None,
  1707. ) -> FetchPackResult:
  1708. """Retrieve a pack from a local on-disk repository.
  1709. Args:
  1710. path: Remote path to fetch from
  1711. determine_wants: Function determine what refs
  1712. to fetch. Receives dictionary of name->sha, should return
  1713. list of shas to fetch.
  1714. graph_walker: Object with next() and ack().
  1715. pack_data: Callback called for each bit of data in the pack
  1716. progress: Callback for progress reports (strings)
  1717. depth: Shallow fetch depth
  1718. ref_prefix: List of prefixes of desired references, as a list of
  1719. bytestrings. Filtering is done by the server if supported, and
  1720. client side otherwise.
  1721. filter_spec: A git-rev-list-style object filter spec, as bytestring.
  1722. Only used if the server supports the Git protocol-v2 'filter'
  1723. feature, and ignored otherwise.
  1724. Returns:
  1725. FetchPackResult object
  1726. """
  1727. with self._open_repo(path) as r:
  1728. missing_objects = r.find_missing_objects(
  1729. determine_wants, graph_walker, progress=progress, depth=depth
  1730. )
  1731. other_haves = missing_objects.get_remote_has()
  1732. object_ids = list(missing_objects)
  1733. symrefs = r.refs.get_symrefs()
  1734. agent = agent_string()
  1735. # Did the process short-circuit (e.g. in a stateless RPC call)?
  1736. # Note that the client still expects a 0-object pack in most cases.
  1737. if object_ids is None:
  1738. return FetchPackResult(None, symrefs, agent)
  1739. write_pack_from_container(
  1740. pack_data, r.object_store, object_ids, other_haves=other_haves
  1741. )
  1742. return FetchPackResult(r.get_refs(), symrefs, agent)
  1743. def get_refs(
  1744. self,
  1745. path,
  1746. protocol_version: Optional[int] = None,
  1747. ref_prefix: Optional[list[Ref]] = None,
  1748. ):
  1749. """Retrieve the current refs from a local on-disk repository."""
  1750. with self._open_repo(path) as target:
  1751. refs = target.get_refs()
  1752. # Extract symrefs from the local repository
  1753. symrefs = {}
  1754. for ref in refs:
  1755. try:
  1756. # Check if this ref is symbolic by reading it directly
  1757. ref_value = target.refs.read_ref(ref)
  1758. if ref_value and ref_value.startswith(SYMREF):
  1759. # Extract the target from the symref
  1760. symrefs[ref] = ref_value[len(SYMREF) :]
  1761. except (KeyError, ValueError):
  1762. # Not a symbolic ref or error reading it
  1763. pass
  1764. return LsRemoteResult(refs, symrefs)
  1765. # What Git client to use for local access
  1766. default_local_git_client_cls = LocalGitClient
  1767. class SSHVendor:
  1768. """A client side SSH implementation."""
  1769. def run_command(
  1770. self,
  1771. host,
  1772. command,
  1773. username=None,
  1774. port=None,
  1775. password=None,
  1776. key_filename=None,
  1777. ssh_command=None,
  1778. protocol_version: Optional[int] = None,
  1779. ):
  1780. """Connect to an SSH server.
  1781. Run a command remotely and return a file-like object for interaction
  1782. with the remote command.
  1783. Args:
  1784. host: Host name
  1785. command: Command to run (as argv array)
  1786. username: Optional ame of user to log in as
  1787. port: Optional SSH port to use
  1788. password: Optional ssh password for login or private key
  1789. key_filename: Optional path to private keyfile
  1790. ssh_command: Optional SSH command
  1791. protocol_version: Desired Git protocol version. By default the highest
  1792. mutually supported protocol version will be used.
  1793. """
  1794. raise NotImplementedError(self.run_command)
  1795. class StrangeHostname(Exception):
  1796. """Refusing to connect to strange SSH hostname."""
  1797. def __init__(self, hostname) -> None:
  1798. super().__init__(hostname)
  1799. class SubprocessSSHVendor(SSHVendor):
  1800. """SSH vendor that shells out to the local 'ssh' command."""
  1801. def run_command(
  1802. self,
  1803. host,
  1804. command,
  1805. username=None,
  1806. port=None,
  1807. password=None,
  1808. key_filename=None,
  1809. ssh_command=None,
  1810. protocol_version: Optional[int] = None,
  1811. ):
  1812. if password is not None:
  1813. raise NotImplementedError(
  1814. "Setting password not supported by SubprocessSSHVendor."
  1815. )
  1816. if ssh_command:
  1817. import shlex
  1818. args = [*shlex.split(ssh_command, posix=sys.platform != "win32"), "-x"]
  1819. else:
  1820. args = ["ssh", "-x"]
  1821. if port:
  1822. args.extend(["-p", str(port)])
  1823. if key_filename:
  1824. args.extend(["-i", str(key_filename)])
  1825. if protocol_version is None:
  1826. protocol_version = DEFAULT_GIT_PROTOCOL_VERSION_FETCH
  1827. if protocol_version > 0:
  1828. args.extend(["-o", f"SetEnv GIT_PROTOCOL=version={protocol_version}"])
  1829. if username:
  1830. host = f"{username}@{host}"
  1831. if host.startswith("-"):
  1832. raise StrangeHostname(hostname=host)
  1833. args.append(host)
  1834. proc = subprocess.Popen(
  1835. [*args, command],
  1836. bufsize=0,
  1837. stdin=subprocess.PIPE,
  1838. stdout=subprocess.PIPE,
  1839. stderr=subprocess.PIPE,
  1840. )
  1841. return SubprocessWrapper(proc)
  1842. class PLinkSSHVendor(SSHVendor):
  1843. """SSH vendor that shells out to the local 'plink' command."""
  1844. def run_command(
  1845. self,
  1846. host,
  1847. command,
  1848. username=None,
  1849. port=None,
  1850. password=None,
  1851. key_filename=None,
  1852. ssh_command=None,
  1853. protocol_version: Optional[int] = None,
  1854. ):
  1855. if ssh_command:
  1856. import shlex
  1857. args = [*shlex.split(ssh_command, posix=sys.platform != "win32"), "-ssh"]
  1858. elif sys.platform == "win32":
  1859. args = ["plink.exe", "-ssh"]
  1860. else:
  1861. args = ["plink", "-ssh"]
  1862. if password is not None:
  1863. import warnings
  1864. warnings.warn(
  1865. "Invoking PLink with a password exposes the password in the "
  1866. "process list."
  1867. )
  1868. args.extend(["-pw", str(password)])
  1869. if port:
  1870. args.extend(["-P", str(port)])
  1871. if key_filename:
  1872. args.extend(["-i", str(key_filename)])
  1873. if username:
  1874. host = f"{username}@{host}"
  1875. if host.startswith("-"):
  1876. raise StrangeHostname(hostname=host)
  1877. args.append(host)
  1878. # plink.exe does not provide a way to pass environment variables
  1879. # via the command line. The best we can do is set an environment
  1880. # variable and hope that plink will pass it to the server. If this
  1881. # does not work then the server should behave as if we had requested
  1882. # protocol version 0.
  1883. env = copy.deepcopy(os.environ)
  1884. if protocol_version is None:
  1885. protocol_version = DEFAULT_GIT_PROTOCOL_VERSION_FETCH
  1886. if protocol_version > 0:
  1887. env["GIT_PROTOCOL"] = f"version={protocol_version}"
  1888. proc = subprocess.Popen(
  1889. [*args, command],
  1890. bufsize=0,
  1891. stdin=subprocess.PIPE,
  1892. stdout=subprocess.PIPE,
  1893. stderr=subprocess.PIPE,
  1894. env=env,
  1895. )
  1896. return SubprocessWrapper(proc)
  1897. def ParamikoSSHVendor(**kwargs):
  1898. import warnings
  1899. warnings.warn(
  1900. "ParamikoSSHVendor has been moved to dulwich.contrib.paramiko_vendor.",
  1901. DeprecationWarning,
  1902. )
  1903. from .contrib.paramiko_vendor import ParamikoSSHVendor
  1904. return ParamikoSSHVendor(**kwargs)
  1905. # Can be overridden by users
  1906. get_ssh_vendor: Callable[[], SSHVendor] = SubprocessSSHVendor
  1907. class SSHGitClient(TraditionalGitClient):
  1908. def __init__(
  1909. self,
  1910. host,
  1911. port=None,
  1912. username=None,
  1913. vendor=None,
  1914. config=None,
  1915. password=None,
  1916. key_filename=None,
  1917. ssh_command=None,
  1918. **kwargs,
  1919. ) -> None:
  1920. self.host = host
  1921. self.port = port
  1922. self.username = username
  1923. self.password = password
  1924. self.key_filename = key_filename
  1925. # Priority: ssh_command parameter, then env vars, then core.sshCommand config
  1926. if ssh_command:
  1927. self.ssh_command = ssh_command
  1928. else:
  1929. # Check environment variables first
  1930. self.ssh_command = os.environ.get(
  1931. "GIT_SSH_COMMAND", os.environ.get("GIT_SSH")
  1932. )
  1933. # Fall back to config if no environment variable set
  1934. if not self.ssh_command and config is not None:
  1935. config_ssh_command = config.get((b"core",), b"sshCommand")
  1936. self.ssh_command = (
  1937. config_ssh_command.decode() if config_ssh_command else None
  1938. )
  1939. super().__init__(**kwargs)
  1940. self.alternative_paths: dict[bytes, bytes] = {}
  1941. if vendor is not None:
  1942. self.ssh_vendor = vendor
  1943. else:
  1944. self.ssh_vendor = get_ssh_vendor()
  1945. def get_url(self, path):
  1946. netloc = self.host
  1947. if self.port is not None:
  1948. netloc += f":{self.port}"
  1949. if self.username is not None:
  1950. netloc = urlquote(self.username, "@/:") + "@" + netloc
  1951. return urlunsplit(("ssh", netloc, path, "", ""))
  1952. @classmethod
  1953. def from_parsedurl(cls, parsedurl, **kwargs):
  1954. return cls(
  1955. host=parsedurl.hostname,
  1956. port=parsedurl.port,
  1957. username=parsedurl.username,
  1958. **kwargs,
  1959. )
  1960. def _get_cmd_path(self, cmd):
  1961. cmd = self.alternative_paths.get(cmd, b"git-" + cmd)
  1962. assert isinstance(cmd, bytes)
  1963. return cmd
  1964. def _connect(
  1965. self,
  1966. cmd: bytes,
  1967. path: Union[str, bytes],
  1968. protocol_version: Optional[int] = None,
  1969. ) -> tuple[Protocol, Callable[[], bool], Optional[IO[bytes]]]:
  1970. if not isinstance(cmd, bytes):
  1971. raise TypeError(cmd)
  1972. if isinstance(path, bytes):
  1973. path = path.decode(self._remote_path_encoding)
  1974. if path.startswith("/~"):
  1975. path = path[1:]
  1976. argv = (
  1977. self._get_cmd_path(cmd).decode(self._remote_path_encoding)
  1978. + " '"
  1979. + path
  1980. + "'"
  1981. )
  1982. kwargs = {}
  1983. if self.password is not None:
  1984. kwargs["password"] = self.password
  1985. if self.key_filename is not None:
  1986. kwargs["key_filename"] = self.key_filename
  1987. # GIT_SSH_COMMAND takes precedence over GIT_SSH
  1988. if self.ssh_command is not None:
  1989. kwargs["ssh_command"] = self.ssh_command
  1990. con = self.ssh_vendor.run_command(
  1991. self.host,
  1992. argv,
  1993. port=self.port,
  1994. username=self.username,
  1995. protocol_version=protocol_version,
  1996. **kwargs,
  1997. )
  1998. return (
  1999. Protocol(
  2000. con.read,
  2001. con.write,
  2002. con.close,
  2003. report_activity=self._report_activity,
  2004. ),
  2005. con.can_read,
  2006. getattr(con, "stderr", None),
  2007. )
  2008. def default_user_agent_string():
  2009. # Start user agent with "git/", because GitHub requires this. :-( See
  2010. # https://github.com/jelmer/dulwich/issues/562 for details.
  2011. return "git/dulwich/{}".format(".".join([str(x) for x in dulwich.__version__]))
  2012. def default_urllib3_manager(
  2013. config,
  2014. pool_manager_cls=None,
  2015. proxy_manager_cls=None,
  2016. base_url=None,
  2017. timeout=None,
  2018. **override_kwargs,
  2019. ) -> Union["urllib3.ProxyManager", "urllib3.PoolManager"]:
  2020. """Return urllib3 connection pool manager.
  2021. Honour detected proxy configurations.
  2022. Args:
  2023. config: `dulwich.config.ConfigDict` instance with Git configuration.
  2024. timeout: Timeout for HTTP requests in seconds
  2025. override_kwargs: Additional arguments for `urllib3.ProxyManager`
  2026. Returns:
  2027. Either pool_manager_cls (defaults to `urllib3.ProxyManager`) instance for
  2028. proxy configurations, proxy_manager_cls
  2029. (defaults to `urllib3.PoolManager`) instance otherwise
  2030. """
  2031. proxy_server = user_agent = None
  2032. ca_certs = ssl_verify = None
  2033. if proxy_server is None:
  2034. for proxyname in ("https_proxy", "http_proxy", "all_proxy"):
  2035. proxy_server = os.environ.get(proxyname)
  2036. if proxy_server:
  2037. break
  2038. if proxy_server:
  2039. if check_for_proxy_bypass(base_url):
  2040. proxy_server = None
  2041. if config is not None:
  2042. if proxy_server is None:
  2043. try:
  2044. proxy_server = config.get(b"http", b"proxy")
  2045. except KeyError:
  2046. pass
  2047. try:
  2048. user_agent = config.get(b"http", b"useragent")
  2049. except KeyError:
  2050. pass
  2051. # TODO(jelmer): Support per-host settings
  2052. try:
  2053. ssl_verify = config.get_boolean(b"http", b"sslVerify")
  2054. except KeyError:
  2055. ssl_verify = True
  2056. try:
  2057. ca_certs = config.get(b"http", b"sslCAInfo")
  2058. except KeyError:
  2059. ca_certs = None
  2060. # Check for timeout configuration
  2061. if timeout is None:
  2062. try:
  2063. timeout = config.get(b"http", b"timeout")
  2064. if timeout is not None:
  2065. timeout = int(timeout)
  2066. except KeyError:
  2067. pass
  2068. if user_agent is None:
  2069. user_agent = default_user_agent_string()
  2070. headers = {"User-agent": user_agent}
  2071. kwargs = {
  2072. "ca_certs": ca_certs,
  2073. }
  2074. # Add timeout if specified
  2075. if timeout is not None:
  2076. kwargs["timeout"] = timeout
  2077. if ssl_verify is True:
  2078. kwargs["cert_reqs"] = "CERT_REQUIRED"
  2079. elif ssl_verify is False:
  2080. kwargs["cert_reqs"] = "CERT_NONE"
  2081. else:
  2082. # Default to SSL verification
  2083. kwargs["cert_reqs"] = "CERT_REQUIRED"
  2084. kwargs.update(override_kwargs)
  2085. import urllib3
  2086. if proxy_server is not None:
  2087. if proxy_manager_cls is None:
  2088. proxy_manager_cls = urllib3.ProxyManager
  2089. if not isinstance(proxy_server, str):
  2090. proxy_server = proxy_server.decode()
  2091. proxy_server_url = urlparse(proxy_server)
  2092. if proxy_server_url.username is not None:
  2093. proxy_headers = urllib3.make_headers(
  2094. proxy_basic_auth=f"{proxy_server_url.username}:{proxy_server_url.password or ''}" # type: ignore
  2095. )
  2096. else:
  2097. proxy_headers = {}
  2098. manager = proxy_manager_cls(
  2099. proxy_server, proxy_headers=proxy_headers, headers=headers, **kwargs
  2100. )
  2101. else:
  2102. if pool_manager_cls is None:
  2103. pool_manager_cls = urllib3.PoolManager
  2104. manager = pool_manager_cls(headers=headers, **kwargs)
  2105. return manager
  2106. def check_for_proxy_bypass(base_url) -> bool:
  2107. # Check if a proxy bypass is defined with the no_proxy environment variable
  2108. if base_url: # only check if base_url is provided
  2109. no_proxy_str = os.environ.get("no_proxy")
  2110. if no_proxy_str:
  2111. # implementation based on curl behavior: https://curl.se/libcurl/c/CURLOPT_NOPROXY.html
  2112. # get hostname of provided parsed url
  2113. parsed_url = urlparse(base_url)
  2114. hostname = parsed_url.hostname
  2115. if hostname:
  2116. import ipaddress
  2117. # check if hostname is an ip address
  2118. try:
  2119. hostname_ip = ipaddress.ip_address(hostname)
  2120. except ValueError:
  2121. hostname_ip = None
  2122. no_proxy_values = no_proxy_str.split(",")
  2123. for no_proxy_value in no_proxy_values:
  2124. no_proxy_value = no_proxy_value.strip()
  2125. if no_proxy_value:
  2126. no_proxy_value = no_proxy_value.lower()
  2127. no_proxy_value = no_proxy_value.lstrip(
  2128. "."
  2129. ) # ignore leading dots
  2130. if hostname_ip:
  2131. # check if no_proxy_value is a ip network
  2132. try:
  2133. no_proxy_value_network = ipaddress.ip_network(
  2134. no_proxy_value, strict=False
  2135. )
  2136. except ValueError:
  2137. no_proxy_value_network = None
  2138. if no_proxy_value_network:
  2139. # if hostname is a ip address and no_proxy_value is a ip network -> check if ip address is part of network
  2140. if hostname_ip in no_proxy_value_network:
  2141. return True
  2142. if no_proxy_value == "*":
  2143. # '*' is special case for always bypass proxy
  2144. return True
  2145. if hostname == no_proxy_value:
  2146. return True
  2147. no_proxy_value = (
  2148. "." + no_proxy_value
  2149. ) # add a dot to only match complete domains
  2150. if hostname.endswith(no_proxy_value):
  2151. return True
  2152. return False
  2153. class AbstractHttpGitClient(GitClient):
  2154. """Abstract base class for HTTP Git Clients.
  2155. This is agonistic of the actual HTTP implementation.
  2156. Subclasses should provide an implementation of the
  2157. _http_request method.
  2158. """
  2159. def __init__(self, base_url, dumb=False, **kwargs) -> None:
  2160. self._base_url = base_url.rstrip("/") + "/"
  2161. self.dumb = dumb
  2162. GitClient.__init__(self, **kwargs)
  2163. def _http_request(self, url, headers=None, data=None):
  2164. """Perform HTTP request.
  2165. Args:
  2166. url: Request URL.
  2167. headers: Optional custom headers to override defaults.
  2168. data: Request data.
  2169. Returns:
  2170. Tuple (response, read), where response is an urllib3
  2171. response object with additional content_type and
  2172. redirect_location properties, and read is a consumable read
  2173. method for the response data.
  2174. Raises:
  2175. GitProtocolError
  2176. """
  2177. raise NotImplementedError(self._http_request)
  2178. def _discover_references(
  2179. self,
  2180. service,
  2181. base_url,
  2182. protocol_version: Optional[int] = None,
  2183. ref_prefix: Optional[list[Ref]] = None,
  2184. ) -> tuple[
  2185. dict[Ref, ObjectID], set[bytes], str, dict[Ref, Ref], dict[Ref, ObjectID]
  2186. ]:
  2187. if (
  2188. protocol_version is not None
  2189. and protocol_version not in GIT_PROTOCOL_VERSIONS
  2190. ):
  2191. raise ValueError(f"unknown Git protocol version {protocol_version}")
  2192. assert base_url[-1] == "/"
  2193. tail = "info/refs"
  2194. headers = {"Accept": "*/*"}
  2195. if self.dumb is not True:
  2196. tail += "?service={}".format(service.decode("ascii"))
  2197. # Enable protocol v2 only when fetching, not when pushing.
  2198. # Git does not yet implement push over protocol v2, and as of
  2199. # git version 2.37.3 git-http-backend's behaviour is erratic if
  2200. # we try: It responds with a Git-protocol-v1-style ref listing
  2201. # which lacks the "001f# service=git-receive-pack" marker.
  2202. if service == b"git-upload-pack":
  2203. if protocol_version is None:
  2204. self.protocol_version = DEFAULT_GIT_PROTOCOL_VERSION_FETCH
  2205. else:
  2206. self.protocol_version = protocol_version
  2207. if self.protocol_version == 2:
  2208. headers["Git-Protocol"] = "version=2"
  2209. else:
  2210. self.protocol_version = DEFAULT_GIT_PROTOCOL_VERSION_SEND
  2211. url = urljoin(base_url, tail)
  2212. resp, read = self._http_request(url, headers)
  2213. if resp.redirect_location:
  2214. # Something changed (redirect!), so let's update the base URL
  2215. if not resp.redirect_location.endswith(tail):
  2216. raise GitProtocolError(
  2217. f"Redirected from URL {url} to URL {resp.redirect_location} without {tail}"
  2218. )
  2219. base_url = urljoin(url, resp.redirect_location[: -len(tail)])
  2220. try:
  2221. self.dumb = resp.content_type is None or not resp.content_type.startswith(
  2222. "application/x-git-"
  2223. )
  2224. if not self.dumb:
  2225. def begin_protocol_v2(proto):
  2226. nonlocal ref_prefix
  2227. server_capabilities = read_server_capabilities(proto.read_pkt_seq())
  2228. if ref_prefix is None:
  2229. ref_prefix = DEFAULT_REF_PREFIX
  2230. pkts = [
  2231. b"symrefs",
  2232. b"peel",
  2233. ]
  2234. for prefix in ref_prefix:
  2235. pkts.append(b"ref-prefix " + prefix)
  2236. body = b"".join(
  2237. [pkt_line(b"command=ls-refs\n"), b"0001", pkt_seq(*pkts)]
  2238. )
  2239. resp, read = self._smart_request(
  2240. service.decode("ascii"), base_url, body
  2241. )
  2242. proto = Protocol(read, None)
  2243. return server_capabilities, resp, read, proto
  2244. proto = Protocol(read, None) # type: ignore
  2245. server_protocol_version = negotiate_protocol_version(proto)
  2246. if server_protocol_version not in GIT_PROTOCOL_VERSIONS:
  2247. raise ValueError(
  2248. f"unknown Git protocol version {server_protocol_version} used by server"
  2249. )
  2250. if protocol_version and server_protocol_version > protocol_version:
  2251. raise ValueError(
  2252. f"bad Git protocol version {server_protocol_version} used by server"
  2253. )
  2254. self.protocol_version = server_protocol_version
  2255. if self.protocol_version == 2:
  2256. server_capabilities, resp, read, proto = begin_protocol_v2(proto)
  2257. (refs, symrefs, peeled) = read_pkt_refs_v2(proto.read_pkt_seq())
  2258. return refs, server_capabilities, base_url, symrefs, peeled
  2259. else:
  2260. try:
  2261. [pkt] = list(proto.read_pkt_seq())
  2262. except ValueError as exc:
  2263. raise GitProtocolError(
  2264. "unexpected number of packets received"
  2265. ) from exc
  2266. if pkt.rstrip(b"\n") != (b"# service=" + service):
  2267. raise GitProtocolError(
  2268. f"unexpected first line {pkt!r} from smart server"
  2269. )
  2270. # Github sends "version 2" after sending the service name.
  2271. # Try to negotiate protocol version 2 again.
  2272. server_protocol_version = negotiate_protocol_version(proto)
  2273. if server_protocol_version not in GIT_PROTOCOL_VERSIONS:
  2274. raise ValueError(
  2275. f"unknown Git protocol version {server_protocol_version} used by server"
  2276. )
  2277. if protocol_version and server_protocol_version > protocol_version:
  2278. raise ValueError(
  2279. f"bad Git protocol version {server_protocol_version} used by server"
  2280. )
  2281. self.protocol_version = server_protocol_version
  2282. if self.protocol_version == 2:
  2283. server_capabilities, resp, read, proto = begin_protocol_v2(
  2284. proto
  2285. )
  2286. (refs, symrefs, peeled) = read_pkt_refs_v2(proto.read_pkt_seq())
  2287. else:
  2288. (
  2289. refs,
  2290. server_capabilities,
  2291. ) = read_pkt_refs_v1(proto.read_pkt_seq())
  2292. (refs, peeled) = split_peeled_refs(refs)
  2293. (symrefs, agent) = _extract_symrefs_and_agent(
  2294. server_capabilities
  2295. )
  2296. if ref_prefix is not None:
  2297. refs = filter_ref_prefix(refs, ref_prefix)
  2298. return refs, server_capabilities, base_url, symrefs, peeled
  2299. else:
  2300. self.protocol_version = 0 # dumb servers only support protocol v0
  2301. # Read all the response data
  2302. data = b""
  2303. while True:
  2304. chunk = read(4096)
  2305. if not chunk:
  2306. break
  2307. data += chunk
  2308. (refs, peeled) = split_peeled_refs(read_info_refs(BytesIO(data)))
  2309. if ref_prefix is not None:
  2310. refs = filter_ref_prefix(refs, ref_prefix)
  2311. return refs, set(), base_url, {}, peeled
  2312. finally:
  2313. resp.close()
  2314. def _smart_request(self, service, url, data):
  2315. """Send a 'smart' HTTP request.
  2316. This is a simple wrapper around _http_request that sets
  2317. a couple of extra headers.
  2318. """
  2319. assert url[-1] == "/"
  2320. url = urljoin(url, service)
  2321. result_content_type = f"application/x-{service}-result"
  2322. headers = {
  2323. "Content-Type": f"application/x-{service}-request",
  2324. "Accept": result_content_type,
  2325. }
  2326. if self.protocol_version == 2:
  2327. headers["Git-Protocol"] = "version=2"
  2328. if isinstance(data, bytes):
  2329. headers["Content-Length"] = str(len(data))
  2330. resp, read = self._http_request(url, headers, data)
  2331. if resp.content_type.split(";")[0] != result_content_type:
  2332. raise GitProtocolError(
  2333. f"Invalid content-type from server: {resp.content_type}"
  2334. )
  2335. return resp, read
  2336. def send_pack(self, path, update_refs, generate_pack_data, progress=None):
  2337. """Upload a pack to a remote repository.
  2338. Args:
  2339. path: Repository path (as bytestring)
  2340. update_refs: Function to determine changes to remote refs.
  2341. Receives dict with existing remote refs, returns dict with
  2342. changed refs (name -> sha, where sha=ZERO_SHA for deletions)
  2343. generate_pack_data: Function that can return a tuple
  2344. with number of elements and pack data to upload.
  2345. progress: Optional progress function
  2346. Returns:
  2347. SendPackResult
  2348. Raises:
  2349. SendPackError: if server rejects the pack data
  2350. """
  2351. url = self._get_url(path)
  2352. old_refs, server_capabilities, url, symrefs, peeled = self._discover_references(
  2353. b"git-receive-pack", url
  2354. )
  2355. (
  2356. negotiated_capabilities,
  2357. agent,
  2358. ) = self._negotiate_receive_pack_capabilities(server_capabilities)
  2359. negotiated_capabilities.add(capability_agent())
  2360. if CAPABILITY_REPORT_STATUS in negotiated_capabilities:
  2361. self._report_status_parser = ReportStatusParser()
  2362. new_refs = update_refs(dict(old_refs))
  2363. if new_refs is None:
  2364. # Determine wants function is aborting the push.
  2365. return SendPackResult(old_refs, agent=agent, ref_status={})
  2366. if set(new_refs.items()).issubset(set(old_refs.items())):
  2367. return SendPackResult(new_refs, agent=agent, ref_status={})
  2368. if self.dumb:
  2369. raise NotImplementedError(self.fetch_pack)
  2370. def body_generator():
  2371. header_handler = _v1ReceivePackHeader(
  2372. negotiated_capabilities, old_refs, new_refs
  2373. )
  2374. for pkt in header_handler:
  2375. yield pkt_line(pkt)
  2376. pack_data_count, pack_data = generate_pack_data(
  2377. header_handler.have,
  2378. header_handler.want,
  2379. ofs_delta=(CAPABILITY_OFS_DELTA in negotiated_capabilities),
  2380. )
  2381. if self._should_send_pack(new_refs):
  2382. yield from PackChunkGenerator(pack_data_count, pack_data)
  2383. resp, read = self._smart_request("git-receive-pack", url, data=body_generator())
  2384. try:
  2385. resp_proto = Protocol(read, None)
  2386. ref_status = self._handle_receive_pack_tail(
  2387. resp_proto, negotiated_capabilities, progress
  2388. )
  2389. return SendPackResult(new_refs, agent=agent, ref_status=ref_status)
  2390. finally:
  2391. resp.close()
  2392. def fetch_pack(
  2393. self,
  2394. path,
  2395. determine_wants,
  2396. graph_walker,
  2397. pack_data,
  2398. progress=None,
  2399. depth: Optional[int] = None,
  2400. ref_prefix: Optional[list[Ref]] = None,
  2401. filter_spec=None,
  2402. protocol_version: Optional[int] = None,
  2403. ):
  2404. """Retrieve a pack from a git smart server.
  2405. Args:
  2406. path: Path to fetch from
  2407. determine_wants: Callback that returns list of commits to fetch
  2408. graph_walker: Object with next() and ack().
  2409. pack_data: Callback called for each bit of data in the pack
  2410. progress: Callback for progress reports (strings)
  2411. depth: Depth for request
  2412. ref_prefix: List of prefixes of desired references, as a list of
  2413. bytestrings. Filtering is done by the server if supported, and
  2414. client side otherwise.
  2415. filter_spec: A git-rev-list-style object filter spec, as bytestring.
  2416. Only used if the server supports the Git protocol-v2 'filter'
  2417. feature, and ignored otherwise.
  2418. protocol_version: Desired Git protocol version. By default the highest
  2419. mutually supported protocol version will be used.
  2420. Returns:
  2421. FetchPackResult object
  2422. """
  2423. url = self._get_url(path)
  2424. refs, server_capabilities, url, symrefs, peeled = self._discover_references(
  2425. b"git-upload-pack",
  2426. url,
  2427. protocol_version=protocol_version,
  2428. ref_prefix=ref_prefix,
  2429. )
  2430. (
  2431. negotiated_capabilities,
  2432. capa_symrefs,
  2433. agent,
  2434. ) = self._negotiate_upload_pack_capabilities(server_capabilities)
  2435. if not symrefs and capa_symrefs:
  2436. symrefs = capa_symrefs
  2437. if depth is not None:
  2438. wants = determine_wants(refs, depth=depth)
  2439. else:
  2440. wants = determine_wants(refs)
  2441. if wants is not None:
  2442. wants = [cid for cid in wants if cid != ZERO_SHA]
  2443. if not wants:
  2444. return FetchPackResult(refs, symrefs, agent)
  2445. if self.dumb:
  2446. # Use dumb HTTP protocol
  2447. from .dumb import DumbRemoteHTTPRepo
  2448. # Pass http_request function
  2449. dumb_repo = DumbRemoteHTTPRepo(url, self._http_request)
  2450. # Fetch pack data from dumb remote
  2451. pack_data_list = list(
  2452. dumb_repo.fetch_pack_data(
  2453. graph_walker, lambda refs: wants, progress=progress, depth=depth
  2454. )
  2455. )
  2456. # Write pack data
  2457. if pack_data:
  2458. from .pack import write_pack_data
  2459. # Write pack data directly using the unpacked objects
  2460. write_pack_data(
  2461. pack_data,
  2462. iter(pack_data_list),
  2463. num_records=len(pack_data_list),
  2464. progress=progress,
  2465. )
  2466. return FetchPackResult(refs, symrefs, agent)
  2467. req_data = BytesIO()
  2468. req_proto = Protocol(None, req_data.write) # type: ignore
  2469. (new_shallow, new_unshallow) = _handle_upload_pack_head(
  2470. req_proto,
  2471. negotiated_capabilities,
  2472. graph_walker,
  2473. wants,
  2474. can_read=None,
  2475. depth=depth,
  2476. protocol_version=self.protocol_version,
  2477. )
  2478. if self.protocol_version == 2:
  2479. data = pkt_line(b"command=fetch\n") + b"0001"
  2480. if CAPABILITY_THIN_PACK in self._fetch_capabilities:
  2481. data += pkt_line(b"thin-pack\n")
  2482. if (
  2483. find_capability(
  2484. negotiated_capabilities, CAPABILITY_FETCH, CAPABILITY_FILTER
  2485. )
  2486. and filter_spec
  2487. ):
  2488. data += pkt_line(b"filter %s\n" % filter_spec)
  2489. elif filter_spec:
  2490. self._warn_filter_objects()
  2491. data += req_data.getvalue()
  2492. else:
  2493. if filter_spec:
  2494. self._warn_filter_objects()
  2495. data = req_data.getvalue()
  2496. resp, read = self._smart_request("git-upload-pack", url, data)
  2497. try:
  2498. resp_proto = Protocol(read, None) # type: ignore
  2499. if new_shallow is None and new_unshallow is None:
  2500. (new_shallow, new_unshallow) = _read_shallow_updates(
  2501. resp_proto.read_pkt_seq()
  2502. )
  2503. _handle_upload_pack_tail(
  2504. resp_proto,
  2505. negotiated_capabilities,
  2506. graph_walker,
  2507. pack_data,
  2508. progress,
  2509. protocol_version=self.protocol_version,
  2510. )
  2511. return FetchPackResult(refs, symrefs, agent, new_shallow, new_unshallow)
  2512. finally:
  2513. resp.close()
  2514. def get_refs(
  2515. self,
  2516. path,
  2517. protocol_version: Optional[int] = None,
  2518. ref_prefix: Optional[list[Ref]] = None,
  2519. ):
  2520. """Retrieve the current refs from a git smart server."""
  2521. url = self._get_url(path)
  2522. refs, _, _, symrefs, peeled = self._discover_references(
  2523. b"git-upload-pack",
  2524. url,
  2525. protocol_version=protocol_version,
  2526. ref_prefix=ref_prefix,
  2527. )
  2528. for refname, refvalue in peeled.items():
  2529. refs[refname + PEELED_TAG_SUFFIX] = refvalue
  2530. return LsRemoteResult(refs, symrefs)
  2531. def get_url(self, path):
  2532. return self._get_url(path).rstrip("/")
  2533. def _get_url(self, path):
  2534. return urljoin(self._base_url, path).rstrip("/") + "/"
  2535. @classmethod
  2536. def from_parsedurl(cls, parsedurl, **kwargs):
  2537. password = parsedurl.password
  2538. if password is not None:
  2539. kwargs["password"] = urlunquote(password)
  2540. username = parsedurl.username
  2541. if username is not None:
  2542. kwargs["username"] = urlunquote(username)
  2543. return cls(urlunparse(parsedurl), **kwargs)
  2544. def __repr__(self) -> str:
  2545. return f"{type(self).__name__}({self._base_url!r}, dumb={self.dumb!r})"
  2546. def _wrap_urllib3_exceptions(func):
  2547. from urllib3.exceptions import ProtocolError
  2548. def wrapper(*args, **kwargs):
  2549. try:
  2550. return func(*args, **kwargs)
  2551. except ProtocolError as error:
  2552. raise GitProtocolError(str(error)) from error
  2553. return wrapper
  2554. class Urllib3HttpGitClient(AbstractHttpGitClient):
  2555. def __init__(
  2556. self,
  2557. base_url,
  2558. dumb=None,
  2559. pool_manager=None,
  2560. config=None,
  2561. username=None,
  2562. password=None,
  2563. timeout=None,
  2564. **kwargs,
  2565. ) -> None:
  2566. self._username = username
  2567. self._password = password
  2568. self._timeout = timeout
  2569. if pool_manager is None:
  2570. self.pool_manager = default_urllib3_manager(
  2571. config, base_url=base_url, timeout=timeout
  2572. )
  2573. else:
  2574. self.pool_manager = pool_manager
  2575. if username is not None:
  2576. # No escaping needed: ":" is not allowed in username:
  2577. # https://tools.ietf.org/html/rfc2617#section-2
  2578. credentials = f"{username}:{password or ''}"
  2579. import urllib3.util
  2580. basic_auth = urllib3.util.make_headers(basic_auth=credentials)
  2581. self.pool_manager.headers.update(basic_auth) # type: ignore
  2582. self.config = config
  2583. super().__init__(base_url=base_url, dumb=dumb, **kwargs)
  2584. def _get_url(self, path):
  2585. if not isinstance(path, str):
  2586. # urllib3.util.url._encode_invalid_chars() converts the path back
  2587. # to bytes using the utf-8 codec.
  2588. path = path.decode("utf-8")
  2589. return urljoin(self._base_url, path).rstrip("/") + "/"
  2590. def _http_request(self, url, headers=None, data=None):
  2591. import urllib3.exceptions
  2592. req_headers = self.pool_manager.headers.copy()
  2593. if headers is not None:
  2594. req_headers.update(headers)
  2595. req_headers["Pragma"] = "no-cache"
  2596. try:
  2597. request_kwargs = {
  2598. "headers": req_headers,
  2599. "preload_content": False,
  2600. }
  2601. if self._timeout is not None:
  2602. request_kwargs["timeout"] = self._timeout
  2603. if data is None:
  2604. resp = self.pool_manager.request("GET", url, **request_kwargs)
  2605. else:
  2606. request_kwargs["body"] = data
  2607. resp = self.pool_manager.request("POST", url, **request_kwargs)
  2608. except urllib3.exceptions.HTTPError as e:
  2609. raise GitProtocolError(str(e)) from e
  2610. if resp.status == 404:
  2611. raise NotGitRepository
  2612. if resp.status == 401:
  2613. raise HTTPUnauthorized(resp.headers.get("WWW-Authenticate"), url)
  2614. if resp.status == 407:
  2615. raise HTTPProxyUnauthorized(resp.headers.get("Proxy-Authenticate"), url)
  2616. if resp.status != 200:
  2617. raise GitProtocolError(f"unexpected http resp {resp.status} for {url}")
  2618. resp.content_type = resp.headers.get("Content-Type")
  2619. # Check if geturl() is available (urllib3 version >= 1.23)
  2620. try:
  2621. resp_url = resp.geturl()
  2622. except AttributeError:
  2623. # get_redirect_location() is available for urllib3 >= 1.1
  2624. resp.redirect_location = resp.get_redirect_location()
  2625. else:
  2626. resp.redirect_location = resp_url if resp_url != url else ""
  2627. return resp, _wrap_urllib3_exceptions(resp.read)
  2628. HttpGitClient = Urllib3HttpGitClient
  2629. def _win32_url_to_path(parsed) -> str:
  2630. """Convert a file: URL to a path.
  2631. https://datatracker.ietf.org/doc/html/rfc8089
  2632. """
  2633. assert parsed.scheme == "file"
  2634. _, netloc, path, _, _, _ = parsed
  2635. if netloc == "localhost" or not netloc:
  2636. netloc = ""
  2637. elif (
  2638. netloc
  2639. and len(netloc) >= 2
  2640. and netloc[0].isalpha()
  2641. and netloc[1:2] in (":", ":/")
  2642. ):
  2643. # file://C:/foo.bar/baz or file://C://foo.bar//baz
  2644. netloc = netloc[:2]
  2645. else:
  2646. raise NotImplementedError("Non-local file URLs are not supported")
  2647. from nturl2path import url2pathname
  2648. return url2pathname(netloc + path)
  2649. def get_transport_and_path_from_url(
  2650. url: str, config: Optional[Config] = None, operation: Optional[str] = None, **kwargs
  2651. ) -> tuple[GitClient, str]:
  2652. """Obtain a git client from a URL.
  2653. Args:
  2654. url: URL to open (a unicode string)
  2655. config: Optional config object
  2656. operation: Kind of operation that'll be performed; "pull" or "push"
  2657. Keyword Args:
  2658. thin_packs: Whether or not thin packs should be retrieved
  2659. report_activity: Optional callback for reporting transport
  2660. activity.
  2661. Returns:
  2662. Tuple with client instance and relative path.
  2663. """
  2664. if config is not None:
  2665. url = apply_instead_of(config, url, push=(operation == "push"))
  2666. return _get_transport_and_path_from_url(
  2667. url, config=config, operation=operation, **kwargs
  2668. )
  2669. def _get_transport_and_path_from_url(url, config, operation, **kwargs):
  2670. parsed = urlparse(url)
  2671. if parsed.scheme == "git":
  2672. return (TCPGitClient.from_parsedurl(parsed, **kwargs), parsed.path)
  2673. elif parsed.scheme in ("git+ssh", "ssh"):
  2674. return SSHGitClient.from_parsedurl(parsed, config=config, **kwargs), parsed.path
  2675. elif parsed.scheme in ("http", "https"):
  2676. return (
  2677. HttpGitClient.from_parsedurl(parsed, config=config, **kwargs),
  2678. parsed.path,
  2679. )
  2680. elif parsed.scheme == "file":
  2681. if sys.platform == "win32" or os.name == "nt":
  2682. return default_local_git_client_cls(**kwargs), _win32_url_to_path(parsed)
  2683. return (
  2684. default_local_git_client_cls.from_parsedurl(parsed, **kwargs),
  2685. parsed.path,
  2686. )
  2687. raise ValueError(f"unknown scheme '{parsed.scheme}'")
  2688. def parse_rsync_url(location: str) -> tuple[Optional[str], str, str]:
  2689. """Parse a rsync-style URL."""
  2690. if ":" in location and "@" not in location:
  2691. # SSH with no user@, zero or one leading slash.
  2692. (host, path) = location.split(":", 1)
  2693. user = None
  2694. elif ":" in location:
  2695. # SSH with user@host:foo.
  2696. user_host, path = location.split(":", 1)
  2697. if "@" in user_host:
  2698. user, host = user_host.rsplit("@", 1)
  2699. else:
  2700. user = None
  2701. host = user_host
  2702. else:
  2703. raise ValueError("not a valid rsync-style URL")
  2704. return (user, host, path)
  2705. def get_transport_and_path(
  2706. location: str,
  2707. config: Optional[Config] = None,
  2708. operation: Optional[str] = None,
  2709. **kwargs,
  2710. ) -> tuple[GitClient, str]:
  2711. """Obtain a git client from a URL.
  2712. Args:
  2713. location: URL or path (a string)
  2714. config: Optional config object
  2715. operation: Kind of operation that'll be performed; "pull" or "push"
  2716. Keyword Args:
  2717. thin_packs: Whether or not thin packs should be retrieved
  2718. report_activity: Optional callback for reporting transport
  2719. activity.
  2720. Returns:
  2721. Tuple with client instance and relative path.
  2722. """
  2723. if config is not None:
  2724. location = apply_instead_of(config, location, push=(operation == "push"))
  2725. # First, try to parse it as a URL
  2726. try:
  2727. return _get_transport_and_path_from_url(
  2728. location, config=config, operation=operation, **kwargs
  2729. )
  2730. except ValueError:
  2731. pass
  2732. if sys.platform == "win32" and location[0].isalpha() and location[1:3] == ":\\":
  2733. # Windows local path
  2734. return default_local_git_client_cls(**kwargs), location
  2735. try:
  2736. (username, hostname, path) = parse_rsync_url(location)
  2737. except ValueError:
  2738. # Otherwise, assume it's a local path.
  2739. return default_local_git_client_cls(**kwargs), location
  2740. else:
  2741. return SSHGitClient(hostname, username=username, config=config, **kwargs), path
  2742. DEFAULT_GIT_CREDENTIALS_PATHS = [
  2743. os.path.expanduser("~/.git-credentials"),
  2744. get_xdg_config_home_path("git", "credentials"),
  2745. ]
  2746. def get_credentials_from_store(
  2747. scheme, hostname, username=None, fnames=DEFAULT_GIT_CREDENTIALS_PATHS
  2748. ):
  2749. for fname in fnames:
  2750. try:
  2751. with open(fname, "rb") as f:
  2752. for line in f:
  2753. parsed_line = urlparse(line.strip())
  2754. if (
  2755. parsed_line.scheme == scheme
  2756. and parsed_line.hostname == hostname
  2757. and (username is None or parsed_line.username == username)
  2758. ):
  2759. return parsed_line.username, parsed_line.password
  2760. except FileNotFoundError:
  2761. # If the file doesn't exist, try the next one.
  2762. continue