client.py 125 KB

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