2
0

client.py 114 KB

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