client.py 102 KB

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