client.py 92 KB

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