client.py 106 KB

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