client.py 101 KB

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