client.py 159 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493
  1. # client.py -- Implementation of the client side git protocols
  2. # Copyright (C) 2008-2013 Jelmer Vernooij <jelmer@jelmer.uk>
  3. #
  4. # SPDX-License-Identifier: Apache-2.0 OR GPL-2.0-or-later
  5. # Dulwich is dual-licensed under the Apache License, Version 2.0 and the GNU
  6. # General Public License as published by the Free Software Foundation; version 2.0
  7. # or (at your option) any later version. You can redistribute it and/or
  8. # modify it under the terms of either of these two licenses.
  9. #
  10. # Unless required by applicable law or agreed to in writing, software
  11. # distributed under the License is distributed on an "AS IS" BASIS,
  12. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  13. # See the License for the specific language governing permissions and
  14. # limitations under the License.
  15. #
  16. # You should have received a copy of the licenses; if not, see
  17. # <http://www.gnu.org/licenses/> for a copy of the GNU General Public License
  18. # and <http://www.apache.org/licenses/LICENSE-2.0> for a copy of the Apache
  19. # License, Version 2.0.
  20. #
  21. """Client side support for the Git protocol.
  22. The Dulwich client supports the following capabilities:
  23. * thin-pack
  24. * multi_ack_detailed
  25. * multi_ack
  26. * side-band-64k
  27. * ofs-delta
  28. * quiet
  29. * report-status
  30. * delete-refs
  31. * shallow
  32. Known capabilities that are not supported:
  33. * no-progress
  34. * include-tag
  35. """
  36. import copy
  37. import functools
  38. import logging
  39. import os
  40. import select
  41. import socket
  42. import subprocess
  43. import sys
  44. from collections.abc import Callable, Iterable, Iterator, Mapping, Sequence, Set
  45. from contextlib import closing
  46. from io import BufferedReader, BytesIO
  47. from typing import (
  48. IO,
  49. TYPE_CHECKING,
  50. Any,
  51. ClassVar,
  52. Optional,
  53. Union,
  54. )
  55. from urllib.parse import ParseResult, urljoin, urlparse, urlunparse, urlunsplit
  56. from urllib.parse import quote as urlquote
  57. if TYPE_CHECKING:
  58. import urllib3
  59. import dulwich
  60. if TYPE_CHECKING:
  61. from typing import Protocol as TypingProtocol
  62. from .pack import UnpackedObject
  63. class HTTPResponse(TypingProtocol):
  64. """Protocol for HTTP response objects."""
  65. redirect_location: str | None
  66. content_type: str | None
  67. def close(self) -> None:
  68. """Close the response."""
  69. ...
  70. class GeneratePackDataFunc(TypingProtocol):
  71. """Protocol for generate_pack_data functions."""
  72. def __call__(
  73. self,
  74. have: Set[bytes],
  75. want: Set[bytes],
  76. *,
  77. ofs_delta: bool = False,
  78. progress: Callable[[bytes], None] | None = None,
  79. ) -> tuple[int, Iterator[UnpackedObject]]:
  80. """Generate pack data for the given have and want sets."""
  81. ...
  82. class DetermineWantsFunc(TypingProtocol):
  83. """Protocol for determine_wants functions."""
  84. def __call__(
  85. self,
  86. refs: Mapping[bytes, bytes],
  87. depth: int | None = None,
  88. ) -> list[bytes]:
  89. """Determine the objects to fetch from the given refs."""
  90. ...
  91. from .bundle import Bundle
  92. from .config import Config, apply_instead_of, get_xdg_config_home_path
  93. from .credentials import match_partial_url, match_urls
  94. from .errors import GitProtocolError, HangupException, NotGitRepository, SendPackError
  95. from .object_store import GraphWalker
  96. from .pack import (
  97. PACK_SPOOL_FILE_MAX_SIZE,
  98. PackChunkGenerator,
  99. PackData,
  100. write_pack_from_container,
  101. )
  102. from .protocol import (
  103. _RBUFSIZE,
  104. CAPABILITIES_REF,
  105. CAPABILITY_AGENT,
  106. CAPABILITY_DELETE_REFS,
  107. CAPABILITY_FETCH,
  108. CAPABILITY_FILTER,
  109. CAPABILITY_INCLUDE_TAG,
  110. CAPABILITY_MULTI_ACK,
  111. CAPABILITY_MULTI_ACK_DETAILED,
  112. CAPABILITY_OFS_DELTA,
  113. CAPABILITY_QUIET,
  114. CAPABILITY_REPORT_STATUS,
  115. CAPABILITY_SHALLOW,
  116. CAPABILITY_SIDE_BAND_64K,
  117. CAPABILITY_SYMREF,
  118. CAPABILITY_THIN_PACK,
  119. COMMAND_DEEPEN,
  120. COMMAND_DEEPEN_NOT,
  121. COMMAND_DEEPEN_SINCE,
  122. COMMAND_DONE,
  123. COMMAND_HAVE,
  124. COMMAND_SHALLOW,
  125. COMMAND_UNSHALLOW,
  126. COMMAND_WANT,
  127. DEFAULT_GIT_PROTOCOL_VERSION_FETCH,
  128. DEFAULT_GIT_PROTOCOL_VERSION_SEND,
  129. GIT_PROTOCOL_VERSIONS,
  130. KNOWN_RECEIVE_CAPABILITIES,
  131. KNOWN_UPLOAD_CAPABILITIES,
  132. SIDE_BAND_CHANNEL_DATA,
  133. SIDE_BAND_CHANNEL_FATAL,
  134. SIDE_BAND_CHANNEL_PROGRESS,
  135. TCP_GIT_PORT,
  136. ZERO_SHA,
  137. PktLineParser,
  138. Protocol,
  139. agent_string,
  140. capability_agent,
  141. extract_capabilities,
  142. extract_capability_names,
  143. parse_capability,
  144. pkt_line,
  145. pkt_seq,
  146. )
  147. from .refs import (
  148. PEELED_TAG_SUFFIX,
  149. SYMREF,
  150. Ref,
  151. _import_remote_refs,
  152. _set_default_branch,
  153. _set_head,
  154. _set_origin_head,
  155. filter_ref_prefix,
  156. read_info_refs,
  157. split_peeled_refs,
  158. )
  159. from .repo import BaseRepo, Repo
  160. # Default ref prefix, used if none is specified.
  161. # GitHub defaults to just sending HEAD if no ref-prefix is
  162. # specified, so explicitly request all refs to match
  163. # behaviour with v1 when no ref-prefix is specified.
  164. DEFAULT_REF_PREFIX = [b"HEAD", b"refs/"]
  165. ObjectID = bytes
  166. logger = logging.getLogger(__name__)
  167. class InvalidWants(Exception):
  168. """Invalid wants."""
  169. def __init__(self, wants: Set[bytes]) -> None:
  170. """Initialize InvalidWants exception.
  171. Args:
  172. wants: List of invalid wants
  173. """
  174. Exception.__init__(
  175. self, f"requested wants not in server provided refs: {wants!r}"
  176. )
  177. class HTTPUnauthorized(Exception):
  178. """Raised when authentication fails."""
  179. def __init__(self, www_authenticate: str | None, url: str) -> None:
  180. """Initialize HTTPUnauthorized exception.
  181. Args:
  182. www_authenticate: WWW-Authenticate header value
  183. url: URL that requires authentication
  184. """
  185. Exception.__init__(self, "No valid credentials provided")
  186. self.www_authenticate = www_authenticate
  187. self.url = url
  188. def _to_optional_dict(refs: Mapping[bytes, bytes]) -> dict[bytes, bytes | None]:
  189. """Convert a dict[bytes, bytes] to dict[bytes, Optional[bytes]].
  190. This is needed for compatibility with result types that expect Optional values.
  191. """
  192. return {k: v for k, v in refs.items()}
  193. class HTTPProxyUnauthorized(Exception):
  194. """Raised when proxy authentication fails."""
  195. def __init__(self, proxy_authenticate: str | None, url: str) -> None:
  196. """Initialize HTTPProxyUnauthorized exception.
  197. Args:
  198. proxy_authenticate: Proxy-Authenticate header value
  199. url: URL that requires proxy authentication
  200. """
  201. Exception.__init__(self, "No valid proxy credentials provided")
  202. self.proxy_authenticate = proxy_authenticate
  203. self.url = url
  204. def _fileno_can_read(fileno: int) -> bool:
  205. """Check if a file descriptor is readable."""
  206. return len(select.select([fileno], [], [], 0)[0]) > 0
  207. def _win32_peek_avail(handle: int) -> int:
  208. """Wrapper around PeekNamedPipe to check how many bytes are available."""
  209. from ctypes import ( # type: ignore[attr-defined,unused-ignore]
  210. byref,
  211. windll,
  212. wintypes,
  213. )
  214. c_avail = wintypes.DWORD()
  215. c_message = wintypes.DWORD()
  216. success = windll.kernel32.PeekNamedPipe(
  217. handle, None, 0, None, byref(c_avail), byref(c_message)
  218. )
  219. if not success:
  220. from ctypes import GetLastError # type: ignore[attr-defined,unused-ignore]
  221. raise OSError(GetLastError())
  222. return c_avail.value
  223. COMMON_CAPABILITIES = [CAPABILITY_OFS_DELTA, CAPABILITY_SIDE_BAND_64K]
  224. UPLOAD_CAPABILITIES = [
  225. CAPABILITY_THIN_PACK,
  226. CAPABILITY_MULTI_ACK,
  227. CAPABILITY_MULTI_ACK_DETAILED,
  228. CAPABILITY_SHALLOW,
  229. *COMMON_CAPABILITIES,
  230. ]
  231. RECEIVE_CAPABILITIES = [
  232. CAPABILITY_REPORT_STATUS,
  233. CAPABILITY_DELETE_REFS,
  234. *COMMON_CAPABILITIES,
  235. ]
  236. class ReportStatusParser:
  237. """Handle status as reported by servers with 'report-status' capability."""
  238. def __init__(self) -> None:
  239. """Initialize ReportStatusParser."""
  240. self._done = False
  241. self._pack_status: bytes | None = None
  242. self._ref_statuses: list[bytes] = []
  243. def check(self) -> Iterator[tuple[bytes, str | None]]:
  244. """Check if there were any errors and, if so, raise exceptions.
  245. Raises:
  246. SendPackError: Raised when the server could not unpack
  247. Returns:
  248. iterator over refs
  249. """
  250. if self._pack_status not in (b"unpack ok", None):
  251. raise SendPackError(self._pack_status)
  252. for status in self._ref_statuses:
  253. try:
  254. status, rest = status.split(b" ", 1)
  255. except ValueError:
  256. # malformed response, move on to the next one
  257. continue
  258. if status == b"ng":
  259. ref, error = rest.split(b" ", 1)
  260. yield ref, error.decode("utf-8")
  261. elif status == b"ok":
  262. yield rest, None
  263. else:
  264. raise GitProtocolError(f"invalid ref status {status!r}")
  265. def handle_packet(self, pkt: bytes | None) -> None:
  266. """Handle a packet.
  267. Raises:
  268. GitProtocolError: Raised when packets are received after a flush
  269. packet.
  270. """
  271. if self._done:
  272. raise GitProtocolError("received more data after status report")
  273. if pkt is None:
  274. self._done = True
  275. return
  276. if self._pack_status is None:
  277. self._pack_status = pkt.strip()
  278. else:
  279. ref_status = pkt.strip()
  280. self._ref_statuses.append(ref_status)
  281. def negotiate_protocol_version(proto: Protocol) -> int:
  282. """Negotiate protocol version with the server."""
  283. pkt = proto.read_pkt_line()
  284. if pkt is not None and pkt.strip() == b"version 2":
  285. return 2
  286. proto.unread_pkt_line(pkt)
  287. return 0
  288. def read_server_capabilities(pkt_seq: Iterable[bytes]) -> set[bytes]:
  289. """Read server capabilities from packet sequence."""
  290. server_capabilities = []
  291. for pkt in pkt_seq:
  292. server_capabilities.append(pkt)
  293. return set(server_capabilities)
  294. def read_pkt_refs_v2(
  295. pkt_seq: Iterable[bytes],
  296. ) -> tuple[dict[bytes, bytes | None], dict[bytes, bytes], dict[bytes, bytes]]:
  297. """Read references using protocol version 2."""
  298. refs: dict[bytes, bytes | None] = {}
  299. symrefs = {}
  300. peeled = {}
  301. # Receive refs from server
  302. for pkt in pkt_seq:
  303. parts = pkt.rstrip(b"\n").split(b" ")
  304. sha: bytes | None = parts[0]
  305. if sha == b"unborn":
  306. sha = None
  307. ref = parts[1]
  308. for part in parts[2:]:
  309. if part.startswith(b"peeled:"):
  310. peeled[ref] = part[7:]
  311. elif part.startswith(b"symref-target:"):
  312. symrefs[ref] = part[14:]
  313. else:
  314. logging.warning("unknown part in pkt-ref: %s", part)
  315. refs[ref] = sha
  316. return refs, symrefs, peeled
  317. def read_pkt_refs_v1(
  318. pkt_seq: Iterable[bytes],
  319. ) -> tuple[dict[bytes, bytes], set[bytes]]:
  320. """Read references using protocol version 1."""
  321. server_capabilities = None
  322. refs: dict[bytes, bytes] = {}
  323. # Receive refs from server
  324. for pkt in pkt_seq:
  325. (sha, ref) = pkt.rstrip(b"\n").split(None, 1)
  326. if sha == b"ERR":
  327. raise GitProtocolError(ref.decode("utf-8", "replace"))
  328. if server_capabilities is None:
  329. (ref, server_capabilities) = extract_capabilities(ref)
  330. refs[ref] = sha
  331. if len(refs) == 0:
  332. return {}, set()
  333. if refs == {CAPABILITIES_REF: ZERO_SHA}:
  334. refs = {}
  335. assert server_capabilities is not None
  336. return refs, set(server_capabilities)
  337. class _DeprecatedDictProxy:
  338. """Base class for result objects that provide deprecated dict-like interface."""
  339. refs: dict[bytes, bytes | None] # To be overridden by subclasses
  340. _FORWARDED_ATTRS: ClassVar[set[str]] = {
  341. "clear",
  342. "copy",
  343. "fromkeys",
  344. "get",
  345. "items",
  346. "keys",
  347. "pop",
  348. "popitem",
  349. "setdefault",
  350. "update",
  351. "values",
  352. "viewitems",
  353. "viewkeys",
  354. "viewvalues",
  355. }
  356. def _warn_deprecated(self) -> None:
  357. import warnings
  358. warnings.warn(
  359. f"Use {self.__class__.__name__}.refs instead.",
  360. DeprecationWarning,
  361. stacklevel=3,
  362. )
  363. def __contains__(self, name: bytes) -> bool:
  364. self._warn_deprecated()
  365. return name in self.refs
  366. def __getitem__(self, name: bytes) -> bytes | None:
  367. self._warn_deprecated()
  368. return self.refs[name]
  369. def __len__(self) -> int:
  370. self._warn_deprecated()
  371. return len(self.refs)
  372. def __iter__(self) -> Iterator[bytes]:
  373. self._warn_deprecated()
  374. return iter(self.refs)
  375. def __getattribute__(self, name: str) -> object:
  376. # Avoid infinite recursion by checking against class variable directly
  377. if name != "_FORWARDED_ATTRS" and name in type(self)._FORWARDED_ATTRS:
  378. self._warn_deprecated()
  379. # Direct attribute access to avoid recursion
  380. refs = object.__getattribute__(self, "refs")
  381. return getattr(refs, name)
  382. return super().__getattribute__(name)
  383. class FetchPackResult(_DeprecatedDictProxy):
  384. """Result of a fetch-pack operation.
  385. Attributes:
  386. refs: Dictionary with all remote refs
  387. symrefs: Dictionary with remote symrefs
  388. agent: User agent string
  389. """
  390. symrefs: dict[bytes, bytes]
  391. agent: bytes | None
  392. def __init__(
  393. self,
  394. refs: dict[bytes, bytes | None],
  395. symrefs: dict[bytes, bytes],
  396. agent: bytes | None,
  397. new_shallow: set[bytes] | None = None,
  398. new_unshallow: set[bytes] | None = None,
  399. ) -> None:
  400. """Initialize FetchPackResult.
  401. Args:
  402. refs: Dictionary with all remote refs
  403. symrefs: Dictionary with remote symrefs
  404. agent: User agent string
  405. new_shallow: New shallow commits
  406. new_unshallow: New unshallow commits
  407. """
  408. self.refs = refs
  409. self.symrefs = symrefs
  410. self.agent = agent
  411. self.new_shallow = new_shallow
  412. self.new_unshallow = new_unshallow
  413. def __eq__(self, other: object) -> bool:
  414. """Check equality with another object."""
  415. if isinstance(other, dict):
  416. self._warn_deprecated()
  417. return self.refs == other
  418. if not isinstance(other, FetchPackResult):
  419. return False
  420. return (
  421. self.refs == other.refs
  422. and self.symrefs == other.symrefs
  423. and self.agent == other.agent
  424. )
  425. def __repr__(self) -> str:
  426. """Return string representation of FetchPackResult."""
  427. return f"{self.__class__.__name__}({self.refs!r}, {self.symrefs!r}, {self.agent!r})"
  428. class LsRemoteResult(_DeprecatedDictProxy):
  429. """Result of a ls-remote operation.
  430. Attributes:
  431. refs: Dictionary with all remote refs
  432. symrefs: Dictionary with remote symrefs
  433. """
  434. symrefs: dict[bytes, bytes]
  435. def __init__(
  436. self, refs: dict[bytes, bytes | None], symrefs: dict[bytes, bytes]
  437. ) -> None:
  438. """Initialize LsRemoteResult.
  439. Args:
  440. refs: Dictionary with all remote refs
  441. symrefs: Dictionary with remote symrefs
  442. """
  443. self.refs = refs
  444. self.symrefs = symrefs
  445. def _warn_deprecated(self) -> None:
  446. import warnings
  447. warnings.warn(
  448. "Treating LsRemoteResult as a dictionary is deprecated. "
  449. "Use result.refs instead.",
  450. DeprecationWarning,
  451. stacklevel=3,
  452. )
  453. def __eq__(self, other: object) -> bool:
  454. """Check equality with another object."""
  455. if isinstance(other, dict):
  456. self._warn_deprecated()
  457. return self.refs == other
  458. if not isinstance(other, LsRemoteResult):
  459. return False
  460. return self.refs == other.refs and self.symrefs == other.symrefs
  461. def __repr__(self) -> str:
  462. """Return string representation of LsRemoteResult."""
  463. return f"{self.__class__.__name__}({self.refs!r}, {self.symrefs!r})"
  464. class SendPackResult(_DeprecatedDictProxy):
  465. """Result of a upload-pack operation.
  466. Attributes:
  467. refs: Dictionary with all remote refs
  468. agent: User agent string
  469. ref_status: Optional dictionary mapping ref name to error message (if it
  470. failed to update), or None if it was updated successfully
  471. """
  472. def __init__(
  473. self,
  474. refs: dict[bytes, bytes | None],
  475. agent: bytes | None = None,
  476. ref_status: dict[bytes, str | None] | None = None,
  477. ) -> None:
  478. """Initialize SendPackResult.
  479. Args:
  480. refs: Dictionary with all remote refs
  481. agent: User agent string
  482. ref_status: Optional dictionary mapping ref name to error message
  483. """
  484. self.refs = refs
  485. self.agent = agent
  486. self.ref_status = ref_status
  487. def __eq__(self, other: object) -> bool:
  488. """Check equality with another object."""
  489. if isinstance(other, dict):
  490. self._warn_deprecated()
  491. return self.refs == other
  492. if not isinstance(other, SendPackResult):
  493. return False
  494. return self.refs == other.refs and self.agent == other.agent
  495. def __repr__(self) -> str:
  496. """Return string representation of SendPackResult."""
  497. return f"{self.__class__.__name__}({self.refs!r}, {self.agent!r})"
  498. def _read_shallow_updates(pkt_seq: Iterable[bytes]) -> tuple[set[bytes], set[bytes]]:
  499. new_shallow = set()
  500. new_unshallow = set()
  501. for pkt in pkt_seq:
  502. if pkt == b"shallow-info\n": # Git-protocol v2
  503. continue
  504. try:
  505. cmd, sha = pkt.split(b" ", 1)
  506. except ValueError:
  507. raise GitProtocolError(f"unknown command {pkt!r}")
  508. if cmd == COMMAND_SHALLOW:
  509. new_shallow.add(sha.strip())
  510. elif cmd == COMMAND_UNSHALLOW:
  511. new_unshallow.add(sha.strip())
  512. else:
  513. raise GitProtocolError(f"unknown command {pkt!r}")
  514. return (new_shallow, new_unshallow)
  515. class _v1ReceivePackHeader:
  516. def __init__(
  517. self,
  518. capabilities: Sequence[bytes],
  519. old_refs: Mapping[bytes, bytes],
  520. new_refs: Mapping[bytes, bytes],
  521. ) -> None:
  522. self.want: set[bytes] = set()
  523. self.have: set[bytes] = set()
  524. self._it = self._handle_receive_pack_head(capabilities, old_refs, new_refs)
  525. self.sent_capabilities = False
  526. def __iter__(self) -> Iterator[bytes | None]:
  527. return self._it
  528. def _handle_receive_pack_head(
  529. self,
  530. capabilities: Sequence[bytes],
  531. old_refs: Mapping[bytes, bytes],
  532. new_refs: Mapping[bytes, bytes],
  533. ) -> Iterator[bytes | None]:
  534. """Handle the head of a 'git-receive-pack' request.
  535. Args:
  536. capabilities: List of negotiated capabilities
  537. old_refs: Old refs, as received from the server
  538. new_refs: Refs to change
  539. Returns:
  540. (have, want) tuple
  541. """
  542. self.have = {x for x in old_refs.values() if not x == ZERO_SHA}
  543. for refname in new_refs:
  544. if not isinstance(refname, bytes):
  545. raise TypeError(f"refname is not a bytestring: {refname!r}")
  546. old_sha1 = old_refs.get(refname, ZERO_SHA)
  547. if not isinstance(old_sha1, bytes):
  548. raise TypeError(
  549. f"old sha1 for {refname!r} is not a bytestring: {old_sha1!r}"
  550. )
  551. new_sha1 = new_refs.get(refname, ZERO_SHA)
  552. if not isinstance(new_sha1, bytes):
  553. raise TypeError(
  554. f"old sha1 for {refname!r} is not a bytestring {new_sha1!r}"
  555. )
  556. if old_sha1 != new_sha1:
  557. logger.debug(
  558. "Sending updated ref %r: %r -> %r", refname, old_sha1, new_sha1
  559. )
  560. if self.sent_capabilities:
  561. yield old_sha1 + b" " + new_sha1 + b" " + refname
  562. else:
  563. yield (
  564. old_sha1
  565. + b" "
  566. + new_sha1
  567. + b" "
  568. + refname
  569. + b"\0"
  570. + b" ".join(sorted(capabilities))
  571. )
  572. self.sent_capabilities = True
  573. if new_sha1 not in self.have and new_sha1 != ZERO_SHA:
  574. self.want.add(new_sha1)
  575. yield None
  576. def _read_side_band64k_data(pkt_seq: Iterable[bytes]) -> Iterator[tuple[int, bytes]]:
  577. """Read per-channel data.
  578. This requires the side-band-64k capability.
  579. Args:
  580. pkt_seq: Sequence of packets to read
  581. """
  582. for pkt in pkt_seq:
  583. channel = ord(pkt[:1])
  584. yield channel, pkt[1:]
  585. def find_capability(
  586. capabilities: Iterable[bytes], key: bytes, value: bytes | None
  587. ) -> bytes | None:
  588. """Find a capability with a specific key and value."""
  589. for capability in capabilities:
  590. k, v = parse_capability(capability)
  591. if k != key:
  592. continue
  593. if value and v and value not in v.split(b" "):
  594. continue
  595. return capability
  596. return None
  597. def _handle_upload_pack_head(
  598. proto: Protocol,
  599. capabilities: Iterable[bytes],
  600. graph_walker: GraphWalker,
  601. wants: list[bytes],
  602. can_read: Callable[[], bool] | None,
  603. depth: int | None,
  604. protocol_version: int | None,
  605. shallow_since: str | None = None,
  606. shallow_exclude: list[str] | None = None,
  607. ) -> tuple[set[bytes] | None, set[bytes] | None]:
  608. """Handle the head of a 'git-upload-pack' request.
  609. Args:
  610. proto: Protocol object to read from
  611. capabilities: List of negotiated capabilities
  612. graph_walker: GraphWalker instance to call .ack() on
  613. wants: List of commits to fetch
  614. can_read: function that returns a boolean that indicates
  615. whether there is extra graph data to read on proto
  616. depth: Depth for request
  617. protocol_version: Neogiated Git protocol version.
  618. shallow_since: Deepen the history to include commits after this date
  619. shallow_exclude: Deepen the history to exclude commits reachable from these refs
  620. """
  621. new_shallow: set[bytes] | None
  622. new_unshallow: set[bytes] | None
  623. assert isinstance(wants, list) and isinstance(wants[0], bytes)
  624. wantcmd = COMMAND_WANT + b" " + wants[0]
  625. if protocol_version is None:
  626. protocol_version = DEFAULT_GIT_PROTOCOL_VERSION_SEND
  627. if protocol_version != 2:
  628. wantcmd += b" " + b" ".join(sorted(capabilities))
  629. wantcmd += b"\n"
  630. proto.write_pkt_line(wantcmd)
  631. for want in wants[1:]:
  632. proto.write_pkt_line(COMMAND_WANT + b" " + want + b"\n")
  633. if (
  634. depth not in (0, None)
  635. or shallow_since is not None
  636. or shallow_exclude
  637. or (hasattr(graph_walker, "shallow") and graph_walker.shallow)
  638. ):
  639. if protocol_version == 2:
  640. if not find_capability(capabilities, CAPABILITY_FETCH, CAPABILITY_SHALLOW):
  641. raise GitProtocolError(
  642. "server does not support shallow capability required for depth"
  643. )
  644. elif CAPABILITY_SHALLOW not in capabilities:
  645. raise GitProtocolError(
  646. "server does not support shallow capability required for depth"
  647. )
  648. if hasattr(graph_walker, "shallow"):
  649. for sha in graph_walker.shallow:
  650. proto.write_pkt_line(COMMAND_SHALLOW + b" " + sha + b"\n")
  651. if depth is not None:
  652. proto.write_pkt_line(
  653. COMMAND_DEEPEN + b" " + str(depth).encode("ascii") + b"\n"
  654. )
  655. if shallow_since is not None:
  656. proto.write_pkt_line(
  657. COMMAND_DEEPEN_SINCE + b" " + shallow_since.encode("ascii") + b"\n"
  658. )
  659. if shallow_exclude:
  660. for ref in shallow_exclude:
  661. proto.write_pkt_line(
  662. COMMAND_DEEPEN_NOT + b" " + ref.encode("ascii") + b"\n"
  663. )
  664. if protocol_version != 2:
  665. proto.write_pkt_line(None)
  666. have = next(graph_walker)
  667. while have:
  668. proto.write_pkt_line(COMMAND_HAVE + b" " + have + b"\n")
  669. if can_read is not None and can_read():
  670. pkt = proto.read_pkt_line()
  671. assert pkt is not None
  672. parts = pkt.rstrip(b"\n").split(b" ")
  673. if parts[0] == b"ACK":
  674. graph_walker.ack(parts[1])
  675. if parts[2] in (b"continue", b"common"):
  676. pass
  677. elif parts[2] == b"ready":
  678. break
  679. else:
  680. raise AssertionError(
  681. f"{parts[2]!r} not in ('continue', 'ready', 'common)"
  682. )
  683. have = next(graph_walker)
  684. proto.write_pkt_line(COMMAND_DONE + b"\n")
  685. if protocol_version == 2:
  686. proto.write_pkt_line(None)
  687. if depth not in (0, None) or shallow_since is not None or shallow_exclude:
  688. if can_read is not None:
  689. (new_shallow, new_unshallow) = _read_shallow_updates(proto.read_pkt_seq())
  690. else:
  691. new_shallow = None
  692. new_unshallow = None
  693. else:
  694. new_shallow = new_unshallow = set()
  695. return (new_shallow, new_unshallow)
  696. def _handle_upload_pack_tail(
  697. proto: "Protocol",
  698. capabilities: Set[bytes],
  699. graph_walker: "GraphWalker",
  700. pack_data: Callable[[bytes], int],
  701. progress: Callable[[bytes], None] | None = None,
  702. rbufsize: int = _RBUFSIZE,
  703. protocol_version: int = 0,
  704. ) -> None:
  705. """Handle the tail of a 'git-upload-pack' request.
  706. Args:
  707. proto: Protocol object to read from
  708. capabilities: List of negotiated capabilities
  709. graph_walker: GraphWalker instance to call .ack() on
  710. pack_data: Function to call with pack data
  711. progress: Optional progress reporting function
  712. rbufsize: Read buffer size
  713. protocol_version: Neogiated Git protocol version.
  714. """
  715. pkt = proto.read_pkt_line()
  716. while pkt:
  717. parts = pkt.rstrip(b"\n").split(b" ")
  718. if protocol_version == 2 and parts[0] != b"packfile":
  719. break
  720. else:
  721. if parts[0] == b"ACK":
  722. graph_walker.ack(parts[1])
  723. if parts[0] == b"NAK":
  724. graph_walker.nak()
  725. if len(parts) < 3 or parts[2] not in (
  726. b"ready",
  727. b"continue",
  728. b"common",
  729. ):
  730. break
  731. pkt = proto.read_pkt_line()
  732. if CAPABILITY_SIDE_BAND_64K in capabilities or protocol_version == 2:
  733. if progress is None:
  734. # Just ignore progress data
  735. def progress(x: bytes) -> None:
  736. pass
  737. for chan, data in _read_side_band64k_data(proto.read_pkt_seq()):
  738. if chan == SIDE_BAND_CHANNEL_DATA:
  739. pack_data(data)
  740. elif chan == SIDE_BAND_CHANNEL_PROGRESS:
  741. progress(data)
  742. else:
  743. raise AssertionError(f"Invalid sideband channel {chan}")
  744. else:
  745. while True:
  746. data = proto.read(rbufsize)
  747. if data == b"":
  748. break
  749. pack_data(data)
  750. def _extract_symrefs_and_agent(
  751. capabilities: Iterable[bytes],
  752. ) -> tuple[dict[bytes, bytes], bytes | None]:
  753. """Extract symrefs and agent from capabilities.
  754. Args:
  755. capabilities: List of capabilities
  756. Returns:
  757. (symrefs, agent) tuple
  758. """
  759. symrefs = {}
  760. agent = None
  761. for capability in capabilities:
  762. k, v = parse_capability(capability)
  763. if k == CAPABILITY_SYMREF:
  764. assert v is not None
  765. (src, dst) = v.split(b":", 1)
  766. symrefs[src] = dst
  767. if k == CAPABILITY_AGENT:
  768. agent = v
  769. return (symrefs, agent)
  770. # TODO(durin42): this doesn't correctly degrade if the server doesn't
  771. # support some capabilities. This should work properly with servers
  772. # that don't support multi_ack.
  773. class GitClient:
  774. """Git smart server client."""
  775. def __init__(
  776. self,
  777. thin_packs: bool = True,
  778. report_activity: Callable[[int, str], None] | None = None,
  779. quiet: bool = False,
  780. include_tags: bool = False,
  781. ) -> None:
  782. """Create a new GitClient instance.
  783. Args:
  784. thin_packs: Whether or not thin packs should be retrieved
  785. report_activity: Optional callback for reporting transport
  786. activity.
  787. quiet: Whether to suppress output
  788. include_tags: send annotated tags when sending the objects they point
  789. to
  790. """
  791. self._report_activity = report_activity
  792. self._report_status_parser: ReportStatusParser | None = None
  793. self._fetch_capabilities = set(UPLOAD_CAPABILITIES)
  794. self._fetch_capabilities.add(capability_agent())
  795. self._send_capabilities = set(RECEIVE_CAPABILITIES)
  796. self._send_capabilities.add(capability_agent())
  797. if quiet:
  798. self._send_capabilities.add(CAPABILITY_QUIET)
  799. if not thin_packs:
  800. self._fetch_capabilities.remove(CAPABILITY_THIN_PACK)
  801. if include_tags:
  802. self._fetch_capabilities.add(CAPABILITY_INCLUDE_TAG)
  803. self.protocol_version = 0 # will be overridden later
  804. def get_url(self, path: str) -> str:
  805. """Retrieves full url to given path.
  806. Args:
  807. path: Repository path (as string)
  808. Returns:
  809. Url to path (as string)
  810. """
  811. raise NotImplementedError(self.get_url)
  812. @classmethod
  813. def from_parsedurl(
  814. cls,
  815. parsedurl: ParseResult,
  816. thin_packs: bool = True,
  817. report_activity: Callable[[int, str], None] | None = None,
  818. quiet: bool = False,
  819. include_tags: bool = False,
  820. dumb: bool = False,
  821. username: str | None = None,
  822. password: str | None = None,
  823. config: Config | None = None,
  824. ) -> "GitClient":
  825. """Create an instance of this client from a urlparse.parsed object.
  826. Args:
  827. parsedurl: Result of urlparse()
  828. thin_packs: Whether or not thin packs should be retrieved
  829. report_activity: Optional callback for reporting transport activity
  830. quiet: Whether to suppress progress output
  831. include_tags: Whether to include tags
  832. dumb: Whether to use dumb HTTP transport (only for HTTP)
  833. username: Optional username for authentication (only for HTTP)
  834. password: Optional password for authentication (only for HTTP)
  835. config: Optional configuration object
  836. Returns:
  837. A `GitClient` object
  838. """
  839. raise NotImplementedError(cls.from_parsedurl)
  840. def send_pack(
  841. self,
  842. path: bytes,
  843. update_refs: Callable[[dict[bytes, bytes]], dict[bytes, bytes]],
  844. generate_pack_data: "GeneratePackDataFunc",
  845. progress: Callable[[bytes], None] | None = None,
  846. ) -> SendPackResult:
  847. """Upload a pack to a remote repository.
  848. Args:
  849. path: Repository path (as bytestring)
  850. update_refs: Function to determine changes to remote refs. Receive
  851. dict with existing remote refs, returns dict with
  852. changed refs (name -> sha, where sha=ZERO_SHA for deletions)
  853. generate_pack_data: Function that can return a tuple
  854. with number of objects and list of pack data to include
  855. progress: Optional progress function
  856. Returns:
  857. SendPackResult object
  858. Raises:
  859. SendPackError: if server rejects the pack data
  860. """
  861. raise NotImplementedError(self.send_pack)
  862. def clone(
  863. self,
  864. path: str,
  865. target_path: str,
  866. mkdir: bool = True,
  867. bare: bool = False,
  868. origin: str | None = "origin",
  869. checkout: bool | None = None,
  870. branch: str | None = None,
  871. progress: Callable[[bytes], None] | None = None,
  872. depth: int | None = None,
  873. ref_prefix: Sequence[Ref] | None = None,
  874. filter_spec: bytes | None = None,
  875. protocol_version: int | None = None,
  876. ) -> Repo:
  877. """Clone a repository."""
  878. if mkdir:
  879. os.mkdir(target_path)
  880. try:
  881. target = None
  882. if not bare:
  883. target = Repo.init(target_path)
  884. if checkout is None:
  885. checkout = True
  886. else:
  887. if checkout:
  888. raise ValueError("checkout and bare are incompatible")
  889. target = Repo.init_bare(target_path)
  890. # TODO(jelmer): abstract method for get_location?
  891. if isinstance(self, (LocalGitClient, SubprocessGitClient)):
  892. encoded_path = path.encode("utf-8")
  893. else:
  894. encoded_path = self.get_url(path).encode("utf-8")
  895. assert target is not None
  896. if origin is not None:
  897. target_config = target.get_config()
  898. target_config.set(
  899. (b"remote", origin.encode("utf-8")), b"url", encoded_path
  900. )
  901. target_config.set(
  902. (b"remote", origin.encode("utf-8")),
  903. b"fetch",
  904. b"+refs/heads/*:refs/remotes/" + origin.encode("utf-8") + b"/*",
  905. )
  906. target_config.write_to_path()
  907. ref_message = b"clone: from " + encoded_path
  908. result = self.fetch(
  909. path.encode("utf-8"),
  910. target,
  911. progress=progress,
  912. depth=depth,
  913. ref_prefix=ref_prefix,
  914. filter_spec=filter_spec,
  915. protocol_version=protocol_version,
  916. )
  917. if origin is not None:
  918. _import_remote_refs(
  919. target.refs, origin, result.refs, message=ref_message
  920. )
  921. origin_head = result.symrefs.get(b"HEAD")
  922. origin_sha = result.refs.get(b"HEAD")
  923. if origin is None or (origin_sha and not origin_head):
  924. # set detached HEAD
  925. if origin_sha is not None:
  926. target.refs[b"HEAD"] = origin_sha
  927. head = origin_sha
  928. else:
  929. head = None
  930. else:
  931. _set_origin_head(target.refs, origin.encode("utf-8"), origin_head)
  932. head_ref = _set_default_branch(
  933. target.refs,
  934. origin.encode("utf-8"),
  935. origin_head,
  936. branch.encode("utf-8") if branch is not None else None,
  937. ref_message,
  938. )
  939. # Update target head
  940. if head_ref:
  941. head = _set_head(target.refs, head_ref, ref_message)
  942. else:
  943. head = None
  944. if checkout and head is not None:
  945. target.get_worktree().reset_index()
  946. except BaseException:
  947. if target is not None:
  948. target.close()
  949. if mkdir:
  950. import shutil
  951. shutil.rmtree(target_path)
  952. raise
  953. return target
  954. def fetch(
  955. self,
  956. path: bytes,
  957. target: BaseRepo,
  958. determine_wants: Optional["DetermineWantsFunc"] = None,
  959. progress: Callable[[bytes], None] | None = None,
  960. depth: int | None = None,
  961. ref_prefix: Sequence[Ref] | None = None,
  962. filter_spec: bytes | None = None,
  963. protocol_version: int | None = None,
  964. shallow_since: str | None = None,
  965. shallow_exclude: list[str] | None = None,
  966. ) -> FetchPackResult:
  967. """Fetch into a target repository.
  968. Args:
  969. path: Path to fetch from (as bytestring)
  970. target: Target repository to fetch into
  971. determine_wants: Optional function to determine what refs to fetch.
  972. Receives dictionary of name->sha, should return
  973. list of shas to fetch. Defaults to all shas.
  974. progress: Optional progress function
  975. depth: Depth to fetch at
  976. ref_prefix: List of prefixes of desired references, as a list of
  977. bytestrings. Filtering is done by the server if supported, and
  978. client side otherwise.
  979. filter_spec: A git-rev-list-style object filter spec, as bytestring.
  980. Only used if the server supports the Git protocol-v2 'filter'
  981. feature, and ignored otherwise.
  982. protocol_version: Desired Git protocol version. By default the highest
  983. mutually supported protocol version will be used.
  984. shallow_since: Deepen the history to include commits after this date
  985. shallow_exclude: Deepen the history to exclude commits reachable from these refs
  986. Returns:
  987. Dictionary with all remote refs (not just those fetched)
  988. """
  989. if determine_wants is None:
  990. determine_wants = target.object_store.determine_wants_all
  991. if CAPABILITY_THIN_PACK in self._fetch_capabilities:
  992. from tempfile import SpooledTemporaryFile
  993. f: IO[bytes] = SpooledTemporaryFile(
  994. max_size=PACK_SPOOL_FILE_MAX_SIZE,
  995. prefix="incoming-",
  996. dir=getattr(target.object_store, "path", None),
  997. )
  998. def commit() -> None:
  999. if f.tell():
  1000. f.seek(0)
  1001. target.object_store.add_thin_pack(f.read, None, progress=progress) # type: ignore
  1002. f.close()
  1003. def abort() -> None:
  1004. f.close()
  1005. else:
  1006. f, commit, abort = target.object_store.add_pack()
  1007. try:
  1008. result = self.fetch_pack(
  1009. path,
  1010. determine_wants,
  1011. target.get_graph_walker(),
  1012. f.write,
  1013. progress=progress,
  1014. depth=depth,
  1015. ref_prefix=ref_prefix,
  1016. filter_spec=filter_spec,
  1017. protocol_version=protocol_version,
  1018. shallow_since=shallow_since,
  1019. shallow_exclude=shallow_exclude,
  1020. )
  1021. except BaseException:
  1022. abort()
  1023. raise
  1024. else:
  1025. commit()
  1026. target.update_shallow(result.new_shallow, result.new_unshallow)
  1027. return result
  1028. def fetch_pack(
  1029. self,
  1030. path: bytes,
  1031. determine_wants: "DetermineWantsFunc",
  1032. graph_walker: GraphWalker,
  1033. pack_data: Callable[[bytes], int],
  1034. *,
  1035. progress: Callable[[bytes], None] | None = None,
  1036. depth: int | None = None,
  1037. ref_prefix: Sequence[Ref] | None = None,
  1038. filter_spec: bytes | None = None,
  1039. protocol_version: int | None = None,
  1040. shallow_since: str | None = None,
  1041. shallow_exclude: list[str] | None = None,
  1042. ) -> FetchPackResult:
  1043. """Retrieve a pack from a git smart server.
  1044. Args:
  1045. path: Remote path to fetch from
  1046. determine_wants: Function determine what refs
  1047. to fetch. Receives dictionary of name->sha, should return
  1048. list of shas to fetch.
  1049. graph_walker: Object with next() and ack().
  1050. pack_data: Callback called for each bit of data in the pack
  1051. progress: Callback for progress reports (strings)
  1052. depth: Shallow fetch depth
  1053. ref_prefix: List of prefixes of desired references, as a list of
  1054. bytestrings. Filtering is done by the server if supported, and
  1055. client side otherwise.
  1056. filter_spec: A git-rev-list-style object filter spec, as bytestring.
  1057. Only used if the server supports the Git protocol-v2 'filter'
  1058. feature, and ignored otherwise.
  1059. protocol_version: Desired Git protocol version. By default the highest
  1060. mutually supported protocol version will be used.
  1061. shallow_since: Deepen the history to include commits after this date
  1062. shallow_exclude: Deepen the history to exclude commits reachable from these refs
  1063. Returns:
  1064. FetchPackResult object
  1065. """
  1066. raise NotImplementedError(self.fetch_pack)
  1067. def get_refs(
  1068. self,
  1069. path: bytes,
  1070. protocol_version: int | None = None,
  1071. ref_prefix: Sequence[Ref] | None = None,
  1072. ) -> LsRemoteResult:
  1073. """Retrieve the current refs from a git smart server.
  1074. Args:
  1075. path: Path to the repo to fetch from. (as bytestring)
  1076. protocol_version: Desired Git protocol version.
  1077. ref_prefix: Prefix filter for refs.
  1078. Returns:
  1079. LsRemoteResult object with refs and symrefs
  1080. """
  1081. raise NotImplementedError(self.get_refs)
  1082. @staticmethod
  1083. def _should_send_pack(new_refs: Mapping[bytes, bytes]) -> bool:
  1084. # The packfile MUST NOT be sent if the only command used is delete.
  1085. return any(sha != ZERO_SHA for sha in new_refs.values())
  1086. def _negotiate_receive_pack_capabilities(
  1087. self, server_capabilities: set[bytes]
  1088. ) -> tuple[set[bytes], bytes | None]:
  1089. negotiated_capabilities = self._send_capabilities & server_capabilities
  1090. (_symrefs, agent) = _extract_symrefs_and_agent(server_capabilities)
  1091. (extract_capability_names(server_capabilities) - KNOWN_RECEIVE_CAPABILITIES)
  1092. # TODO(jelmer): warn about unknown capabilities
  1093. return (negotiated_capabilities, agent)
  1094. def _handle_receive_pack_tail(
  1095. self,
  1096. proto: Protocol,
  1097. capabilities: Set[bytes],
  1098. progress: Callable[[bytes], None] | None = None,
  1099. ) -> dict[bytes, str | None] | None:
  1100. """Handle the tail of a 'git-receive-pack' request.
  1101. Args:
  1102. proto: Protocol object to read from
  1103. capabilities: List of negotiated capabilities
  1104. progress: Optional progress reporting function
  1105. Returns:
  1106. dict mapping ref name to:
  1107. error message if the ref failed to update
  1108. None if it was updated successfully
  1109. """
  1110. if CAPABILITY_SIDE_BAND_64K in capabilities or self.protocol_version == 2:
  1111. if progress is None:
  1112. def progress(x: bytes) -> None:
  1113. pass
  1114. if CAPABILITY_REPORT_STATUS in capabilities:
  1115. assert self._report_status_parser is not None
  1116. pktline_parser = PktLineParser(self._report_status_parser.handle_packet)
  1117. for chan, data in _read_side_band64k_data(proto.read_pkt_seq()):
  1118. if chan == SIDE_BAND_CHANNEL_DATA:
  1119. if CAPABILITY_REPORT_STATUS in capabilities:
  1120. pktline_parser.parse(data)
  1121. elif chan == SIDE_BAND_CHANNEL_PROGRESS:
  1122. progress(data)
  1123. else:
  1124. raise AssertionError(f"Invalid sideband channel {chan}")
  1125. else:
  1126. if CAPABILITY_REPORT_STATUS in capabilities:
  1127. assert self._report_status_parser
  1128. for pkt in proto.read_pkt_seq():
  1129. self._report_status_parser.handle_packet(pkt)
  1130. if self._report_status_parser is not None:
  1131. return dict(self._report_status_parser.check())
  1132. return None
  1133. def _negotiate_upload_pack_capabilities(
  1134. self, server_capabilities: set[bytes]
  1135. ) -> tuple[set[bytes], dict[bytes, bytes], bytes | None]:
  1136. (extract_capability_names(server_capabilities) - KNOWN_UPLOAD_CAPABILITIES)
  1137. # TODO(jelmer): warn about unknown capabilities
  1138. fetch_capa = None
  1139. for capability in server_capabilities:
  1140. k, v = parse_capability(capability)
  1141. if self.protocol_version == 2 and k == CAPABILITY_FETCH:
  1142. fetch_capa = CAPABILITY_FETCH
  1143. fetch_features = []
  1144. assert v is not None
  1145. v_list = v.strip().split(b" ")
  1146. if b"shallow" in v_list:
  1147. fetch_features.append(CAPABILITY_SHALLOW)
  1148. if b"filter" in v_list:
  1149. fetch_features.append(CAPABILITY_FILTER)
  1150. for i in range(len(fetch_features)):
  1151. if i == 0:
  1152. fetch_capa += b"="
  1153. else:
  1154. fetch_capa += b" "
  1155. fetch_capa += fetch_features[i]
  1156. (symrefs, agent) = _extract_symrefs_and_agent(server_capabilities)
  1157. negotiated_capabilities = self._fetch_capabilities & server_capabilities
  1158. if fetch_capa:
  1159. negotiated_capabilities.add(fetch_capa)
  1160. return (negotiated_capabilities, symrefs, agent)
  1161. def archive(
  1162. self,
  1163. path: bytes,
  1164. committish: bytes,
  1165. write_data: Callable[[bytes], None],
  1166. progress: Callable[[bytes], None] | None = None,
  1167. write_error: Callable[[bytes], None] | None = None,
  1168. format: bytes | None = None,
  1169. subdirs: Sequence[bytes] | None = None,
  1170. prefix: bytes | None = None,
  1171. ) -> None:
  1172. """Retrieve an archive of the specified tree."""
  1173. raise NotImplementedError(self.archive)
  1174. @staticmethod
  1175. def _warn_filter_objects() -> None:
  1176. import warnings
  1177. warnings.warn(
  1178. "object filtering not recognized by server, ignoring",
  1179. UserWarning,
  1180. )
  1181. def check_wants(wants: Set[bytes], refs: Mapping[bytes, bytes]) -> None:
  1182. """Check that a set of wants is valid.
  1183. Args:
  1184. wants: Set of object SHAs to fetch
  1185. refs: Refs dictionary to check against
  1186. """
  1187. missing = set(wants) - {
  1188. v for (k, v) in refs.items() if not k.endswith(PEELED_TAG_SUFFIX)
  1189. }
  1190. if missing:
  1191. raise InvalidWants(missing)
  1192. def _remote_error_from_stderr(stderr: IO[bytes] | None) -> Exception:
  1193. if stderr is None:
  1194. return HangupException()
  1195. lines = [line.rstrip(b"\n") for line in stderr.readlines()]
  1196. for line in lines:
  1197. if line.startswith(b"ERROR: "):
  1198. return GitProtocolError(line[len(b"ERROR: ") :].decode("utf-8", "replace"))
  1199. return HangupException(lines)
  1200. class TraditionalGitClient(GitClient):
  1201. """Traditional Git client."""
  1202. DEFAULT_ENCODING = "utf-8"
  1203. def __init__(
  1204. self,
  1205. path_encoding: str = DEFAULT_ENCODING,
  1206. thin_packs: bool = True,
  1207. report_activity: Callable[[int, str], None] | None = None,
  1208. quiet: bool = False,
  1209. include_tags: bool = False,
  1210. ) -> None:
  1211. """Initialize a TraditionalGitClient.
  1212. Args:
  1213. path_encoding: Encoding for paths (default: utf-8)
  1214. thin_packs: Whether or not thin packs should be retrieved
  1215. report_activity: Optional callback for reporting transport activity
  1216. quiet: Whether to suppress progress output
  1217. include_tags: Whether to include tags
  1218. """
  1219. self._remote_path_encoding = path_encoding
  1220. super().__init__(
  1221. thin_packs=thin_packs,
  1222. report_activity=report_activity,
  1223. quiet=quiet,
  1224. include_tags=include_tags,
  1225. )
  1226. def _connect(
  1227. self,
  1228. cmd: bytes,
  1229. path: str | bytes,
  1230. protocol_version: int | None = None,
  1231. ) -> tuple[Protocol, Callable[[], bool], IO[bytes] | None]:
  1232. """Create a connection to the server.
  1233. This method is abstract - concrete implementations should
  1234. implement their own variant which connects to the server and
  1235. returns an initialized Protocol object with the service ready
  1236. for use and a can_read function which may be used to see if
  1237. reads would block.
  1238. Args:
  1239. cmd: The git service name to which we should connect.
  1240. path: The path we should pass to the service. (as bytestirng)
  1241. protocol_version: Desired Git protocol version. By default the highest
  1242. mutually supported protocol version will be used.
  1243. """
  1244. raise NotImplementedError
  1245. def send_pack(
  1246. self,
  1247. path: bytes,
  1248. update_refs: Callable[[dict[bytes, bytes]], dict[bytes, bytes]],
  1249. generate_pack_data: "GeneratePackDataFunc",
  1250. progress: Callable[[bytes], None] | None = None,
  1251. ) -> SendPackResult:
  1252. """Upload a pack to a remote repository.
  1253. Args:
  1254. path: Repository path (as bytestring)
  1255. update_refs: Function to determine changes to remote refs.
  1256. Receive dict with existing remote refs, returns dict with
  1257. changed refs (name -> sha, where sha=ZERO_SHA for deletions)
  1258. generate_pack_data: Function that can return a tuple with
  1259. number of objects and pack data to upload.
  1260. progress: Optional callback called with progress updates
  1261. Returns:
  1262. SendPackResult
  1263. Raises:
  1264. SendPackError: if server rejects the pack data
  1265. """
  1266. self.protocol_version = DEFAULT_GIT_PROTOCOL_VERSION_SEND
  1267. proto, _unused_can_read, stderr = self._connect(b"receive-pack", path)
  1268. with proto:
  1269. try:
  1270. old_refs, server_capabilities = read_pkt_refs_v1(proto.read_pkt_seq())
  1271. except HangupException as exc:
  1272. raise _remote_error_from_stderr(stderr) from exc
  1273. (
  1274. negotiated_capabilities,
  1275. agent,
  1276. ) = self._negotiate_receive_pack_capabilities(server_capabilities)
  1277. if CAPABILITY_REPORT_STATUS in negotiated_capabilities:
  1278. self._report_status_parser = ReportStatusParser()
  1279. report_status_parser = self._report_status_parser
  1280. try:
  1281. new_refs = orig_new_refs = update_refs(old_refs)
  1282. except BaseException:
  1283. proto.write_pkt_line(None)
  1284. raise
  1285. if set(new_refs.items()).issubset(set(old_refs.items())):
  1286. proto.write_pkt_line(None)
  1287. # Convert new_refs to match SendPackResult expected type
  1288. return SendPackResult(
  1289. _to_optional_dict(new_refs), agent=agent, ref_status={}
  1290. )
  1291. if CAPABILITY_DELETE_REFS not in server_capabilities:
  1292. # Server does not support deletions. Fail later.
  1293. new_refs = dict(orig_new_refs)
  1294. for ref, sha in orig_new_refs.items():
  1295. if sha == ZERO_SHA:
  1296. if CAPABILITY_REPORT_STATUS in negotiated_capabilities:
  1297. assert report_status_parser is not None
  1298. report_status_parser._ref_statuses.append(
  1299. b"ng " + ref + b" remote does not support deleting refs"
  1300. )
  1301. del new_refs[ref]
  1302. if new_refs is None:
  1303. proto.write_pkt_line(None)
  1304. return SendPackResult(old_refs, agent=agent, ref_status={})
  1305. if len(new_refs) == 0 and orig_new_refs:
  1306. # NOOP - Original new refs filtered out by policy
  1307. proto.write_pkt_line(None)
  1308. if report_status_parser is not None:
  1309. ref_status = dict(report_status_parser.check())
  1310. else:
  1311. ref_status = None
  1312. # Convert to Optional type for SendPackResult
  1313. return SendPackResult(
  1314. _to_optional_dict(old_refs), agent=agent, ref_status=ref_status
  1315. )
  1316. header_handler = _v1ReceivePackHeader(
  1317. list(negotiated_capabilities),
  1318. old_refs,
  1319. new_refs,
  1320. )
  1321. for pkt in header_handler:
  1322. proto.write_pkt_line(pkt)
  1323. pack_data_count, pack_data = generate_pack_data(
  1324. header_handler.have,
  1325. header_handler.want,
  1326. ofs_delta=(CAPABILITY_OFS_DELTA in negotiated_capabilities),
  1327. progress=progress,
  1328. )
  1329. if self._should_send_pack(new_refs):
  1330. for chunk in PackChunkGenerator(pack_data_count, pack_data):
  1331. proto.write(chunk)
  1332. ref_status = self._handle_receive_pack_tail(
  1333. proto, negotiated_capabilities, progress
  1334. )
  1335. refs_with_optional_2: dict[bytes, bytes | None] = {
  1336. k: v for k, v in new_refs.items()
  1337. }
  1338. return SendPackResult(
  1339. refs_with_optional_2, agent=agent, ref_status=ref_status
  1340. )
  1341. def fetch_pack(
  1342. self,
  1343. path: bytes,
  1344. determine_wants: "DetermineWantsFunc",
  1345. graph_walker: GraphWalker,
  1346. pack_data: Callable[[bytes], int],
  1347. progress: Callable[[bytes], None] | None = None,
  1348. depth: int | None = None,
  1349. ref_prefix: Sequence[Ref] | None = None,
  1350. filter_spec: bytes | None = None,
  1351. protocol_version: int | None = None,
  1352. shallow_since: str | None = None,
  1353. shallow_exclude: list[str] | None = None,
  1354. ) -> FetchPackResult:
  1355. """Retrieve a pack from a git smart server.
  1356. Args:
  1357. path: Remote path to fetch from
  1358. determine_wants: Function determine what refs
  1359. to fetch. Receives dictionary of name->sha, should return
  1360. list of shas to fetch.
  1361. graph_walker: Object with next() and ack().
  1362. pack_data: Callback called for each bit of data in the pack
  1363. progress: Callback for progress reports (strings)
  1364. depth: Shallow fetch depth
  1365. ref_prefix: List of prefixes of desired references, as a list of
  1366. bytestrings. Filtering is done by the server if supported, and
  1367. client side otherwise.
  1368. filter_spec: A git-rev-list-style object filter spec, as bytestring.
  1369. Only used if the server supports the Git protocol-v2 'filter'
  1370. feature, and ignored otherwise.
  1371. protocol_version: Desired Git protocol version. By default the highest
  1372. mutually supported protocol version will be used.
  1373. shallow_since: Deepen the history to include commits after this date
  1374. shallow_exclude: Deepen the history to exclude commits reachable from these refs
  1375. Returns:
  1376. FetchPackResult object
  1377. """
  1378. if (
  1379. protocol_version is not None
  1380. and protocol_version not in GIT_PROTOCOL_VERSIONS
  1381. ):
  1382. raise ValueError(f"unknown Git protocol version {protocol_version}")
  1383. proto, can_read, stderr = self._connect(b"upload-pack", path, protocol_version)
  1384. server_protocol_version = negotiate_protocol_version(proto)
  1385. if server_protocol_version not in GIT_PROTOCOL_VERSIONS:
  1386. raise ValueError(
  1387. f"unknown Git protocol version {server_protocol_version} used by server"
  1388. )
  1389. if protocol_version and server_protocol_version > protocol_version:
  1390. raise ValueError(
  1391. f"bad Git protocol version {server_protocol_version} used by server"
  1392. )
  1393. self.protocol_version = server_protocol_version
  1394. with proto:
  1395. # refs may have None values in v2 but not in v1
  1396. refs: dict[bytes, bytes | None]
  1397. if self.protocol_version == 2:
  1398. try:
  1399. server_capabilities = read_server_capabilities(proto.read_pkt_seq())
  1400. except HangupException as exc:
  1401. raise _remote_error_from_stderr(stderr) from exc
  1402. (
  1403. negotiated_capabilities,
  1404. symrefs,
  1405. agent,
  1406. ) = self._negotiate_upload_pack_capabilities(server_capabilities)
  1407. proto.write_pkt_line(b"command=ls-refs\n")
  1408. proto.write(b"0001") # delim-pkt
  1409. proto.write_pkt_line(b"symrefs")
  1410. proto.write_pkt_line(b"peel")
  1411. if ref_prefix is None:
  1412. ref_prefix = DEFAULT_REF_PREFIX
  1413. for prefix in ref_prefix:
  1414. proto.write_pkt_line(b"ref-prefix " + prefix)
  1415. proto.write_pkt_line(None)
  1416. refs, symrefs, _peeled = read_pkt_refs_v2(proto.read_pkt_seq())
  1417. else:
  1418. try:
  1419. refs_v1, server_capabilities = read_pkt_refs_v1(
  1420. proto.read_pkt_seq()
  1421. )
  1422. # v1 refs never have None values, but we need Optional type for compatibility
  1423. refs = _to_optional_dict(refs_v1)
  1424. except HangupException as exc:
  1425. raise _remote_error_from_stderr(stderr) from exc
  1426. (
  1427. negotiated_capabilities,
  1428. symrefs,
  1429. agent,
  1430. ) = self._negotiate_upload_pack_capabilities(server_capabilities)
  1431. if ref_prefix is not None:
  1432. refs = filter_ref_prefix(refs, ref_prefix)
  1433. if refs is None:
  1434. proto.write_pkt_line(None)
  1435. return FetchPackResult(refs, symrefs, agent)
  1436. try:
  1437. # Filter out None values (shouldn't be any in v1 protocol)
  1438. refs_no_none = {k: v for k, v in refs.items() if v is not None}
  1439. # Handle both old and new style determine_wants
  1440. try:
  1441. wants = determine_wants(refs_no_none, depth)
  1442. except TypeError:
  1443. # Old-style determine_wants that doesn't accept depth
  1444. wants = determine_wants(refs_no_none)
  1445. except BaseException:
  1446. proto.write_pkt_line(None)
  1447. raise
  1448. if wants is not None:
  1449. wants = [cid for cid in wants if cid != ZERO_SHA]
  1450. if not wants:
  1451. proto.write_pkt_line(None)
  1452. return FetchPackResult(refs, symrefs, agent)
  1453. if self.protocol_version == 2:
  1454. proto.write_pkt_line(b"command=fetch\n")
  1455. proto.write(b"0001") # delim-pkt
  1456. if CAPABILITY_THIN_PACK in self._fetch_capabilities:
  1457. proto.write(pkt_line(b"thin-pack\n"))
  1458. if (
  1459. find_capability(
  1460. list(negotiated_capabilities),
  1461. CAPABILITY_FETCH,
  1462. CAPABILITY_FILTER,
  1463. )
  1464. and filter_spec
  1465. ):
  1466. proto.write(pkt_line(b"filter %s\n" % filter_spec))
  1467. elif filter_spec:
  1468. self._warn_filter_objects()
  1469. elif filter_spec:
  1470. self._warn_filter_objects()
  1471. (new_shallow, new_unshallow) = _handle_upload_pack_head(
  1472. proto,
  1473. list(negotiated_capabilities),
  1474. graph_walker,
  1475. wants,
  1476. can_read,
  1477. depth=depth,
  1478. protocol_version=self.protocol_version,
  1479. shallow_since=shallow_since,
  1480. shallow_exclude=shallow_exclude,
  1481. )
  1482. _handle_upload_pack_tail(
  1483. proto,
  1484. negotiated_capabilities,
  1485. graph_walker,
  1486. pack_data,
  1487. progress,
  1488. protocol_version=self.protocol_version,
  1489. )
  1490. return FetchPackResult(refs, symrefs, agent, new_shallow, new_unshallow)
  1491. def get_refs(
  1492. self,
  1493. path: bytes,
  1494. protocol_version: int | None = None,
  1495. ref_prefix: Sequence[Ref] | None = None,
  1496. ) -> LsRemoteResult:
  1497. """Retrieve the current refs from a git smart server."""
  1498. # stock `git ls-remote` uses upload-pack
  1499. if (
  1500. protocol_version is not None
  1501. and protocol_version not in GIT_PROTOCOL_VERSIONS
  1502. ):
  1503. raise ValueError(f"unknown Git protocol version {protocol_version}")
  1504. proto, _, stderr = self._connect(b"upload-pack", path, protocol_version)
  1505. server_protocol_version = negotiate_protocol_version(proto)
  1506. if server_protocol_version not in GIT_PROTOCOL_VERSIONS:
  1507. raise ValueError(
  1508. f"unknown Git protocol version {server_protocol_version} used by server"
  1509. )
  1510. if protocol_version and server_protocol_version > protocol_version:
  1511. raise ValueError(
  1512. f"bad Git protocol version {server_protocol_version} used by server"
  1513. )
  1514. self.protocol_version = server_protocol_version
  1515. if self.protocol_version == 2:
  1516. server_capabilities = read_server_capabilities(proto.read_pkt_seq())
  1517. proto.write_pkt_line(b"command=ls-refs\n")
  1518. proto.write(b"0001") # delim-pkt
  1519. proto.write_pkt_line(b"symrefs")
  1520. proto.write_pkt_line(b"peel")
  1521. if ref_prefix is None:
  1522. ref_prefix = DEFAULT_REF_PREFIX
  1523. for prefix in ref_prefix:
  1524. proto.write_pkt_line(b"ref-prefix " + prefix)
  1525. proto.write_pkt_line(None)
  1526. with proto:
  1527. try:
  1528. refs, symrefs, peeled = read_pkt_refs_v2(proto.read_pkt_seq())
  1529. except HangupException as exc:
  1530. raise _remote_error_from_stderr(stderr) from exc
  1531. proto.write_pkt_line(None)
  1532. for refname, refvalue in peeled.items():
  1533. refs[refname + PEELED_TAG_SUFFIX] = refvalue
  1534. return LsRemoteResult(refs, symrefs)
  1535. else:
  1536. with proto:
  1537. try:
  1538. refs_v1, server_capabilities = read_pkt_refs_v1(
  1539. proto.read_pkt_seq()
  1540. )
  1541. # v1 refs never have None values, but we need Optional type for compatibility
  1542. refs = _to_optional_dict(refs_v1)
  1543. except HangupException as exc:
  1544. raise _remote_error_from_stderr(stderr) from exc
  1545. proto.write_pkt_line(None)
  1546. (symrefs, _agent) = _extract_symrefs_and_agent(server_capabilities)
  1547. if ref_prefix is not None:
  1548. refs = filter_ref_prefix(refs, ref_prefix)
  1549. return LsRemoteResult(refs, symrefs)
  1550. def archive(
  1551. self,
  1552. path: bytes,
  1553. committish: bytes,
  1554. write_data: Callable[[bytes], None],
  1555. progress: Callable[[bytes], None] | None = None,
  1556. write_error: Callable[[bytes], None] | None = None,
  1557. format: bytes | None = None,
  1558. subdirs: Sequence[bytes] | None = None,
  1559. prefix: bytes | None = None,
  1560. ) -> None:
  1561. """Request an archive of a specific commit.
  1562. Args:
  1563. path: Repository path
  1564. committish: Commit ID or ref to archive
  1565. write_data: Function to write archive data
  1566. progress: Optional progress callback
  1567. write_error: Optional error callback
  1568. format: Optional archive format
  1569. subdirs: Optional subdirectories to include
  1570. prefix: Optional prefix for archived files
  1571. """
  1572. proto, _can_read, stderr = self._connect(b"upload-archive", path)
  1573. with proto:
  1574. if format is not None:
  1575. proto.write_pkt_line(b"argument --format=" + format)
  1576. proto.write_pkt_line(b"argument " + committish)
  1577. if subdirs is not None:
  1578. for subdir in subdirs:
  1579. proto.write_pkt_line(b"argument " + subdir)
  1580. if prefix is not None:
  1581. proto.write_pkt_line(b"argument --prefix=" + prefix)
  1582. proto.write_pkt_line(None)
  1583. try:
  1584. pkt = proto.read_pkt_line()
  1585. except HangupException as exc:
  1586. raise _remote_error_from_stderr(stderr) from exc
  1587. if pkt == b"NACK\n" or pkt == b"NACK":
  1588. return
  1589. elif pkt == b"ACK\n" or pkt == b"ACK":
  1590. pass
  1591. elif pkt and pkt.startswith(b"ERR "):
  1592. raise GitProtocolError(pkt[4:].rstrip(b"\n").decode("utf-8", "replace"))
  1593. else:
  1594. raise AssertionError(f"invalid response {pkt!r}")
  1595. ret = proto.read_pkt_line()
  1596. if ret is not None:
  1597. raise AssertionError("expected pkt tail")
  1598. for chan, data in _read_side_band64k_data(proto.read_pkt_seq()):
  1599. if chan == SIDE_BAND_CHANNEL_DATA:
  1600. write_data(data)
  1601. elif chan == SIDE_BAND_CHANNEL_PROGRESS:
  1602. if progress is not None:
  1603. progress(data)
  1604. elif chan == SIDE_BAND_CHANNEL_FATAL:
  1605. if write_error is not None:
  1606. write_error(data)
  1607. else:
  1608. raise AssertionError(f"Invalid sideband channel {chan}")
  1609. class TCPGitClient(TraditionalGitClient):
  1610. """A Git Client that works over TCP directly (i.e. git://)."""
  1611. def __init__(
  1612. self,
  1613. host: str,
  1614. port: int | None = None,
  1615. thin_packs: bool = True,
  1616. report_activity: Callable[[int, str], None] | None = None,
  1617. quiet: bool = False,
  1618. include_tags: bool = False,
  1619. ) -> None:
  1620. """Initialize a TCPGitClient.
  1621. Args:
  1622. host: Hostname or IP address to connect to
  1623. port: Port number (defaults to TCP_GIT_PORT)
  1624. thin_packs: Whether or not thin packs should be retrieved
  1625. report_activity: Optional callback for reporting transport activity
  1626. quiet: Whether to suppress progress output
  1627. include_tags: Whether to include tags
  1628. """
  1629. if port is None:
  1630. port = TCP_GIT_PORT
  1631. self._host = host
  1632. self._port = port
  1633. super().__init__(
  1634. thin_packs=thin_packs,
  1635. report_activity=report_activity,
  1636. quiet=quiet,
  1637. include_tags=include_tags,
  1638. )
  1639. @classmethod
  1640. def from_parsedurl(
  1641. cls,
  1642. parsedurl: ParseResult,
  1643. thin_packs: bool = True,
  1644. report_activity: Callable[[int, str], None] | None = None,
  1645. quiet: bool = False,
  1646. include_tags: bool = False,
  1647. dumb: bool = False,
  1648. username: str | None = None,
  1649. password: str | None = None,
  1650. config: Config | None = None,
  1651. ) -> "TCPGitClient":
  1652. """Create an instance of TCPGitClient from a parsed URL.
  1653. Args:
  1654. parsedurl: Result of urlparse()
  1655. thin_packs: Whether or not thin packs should be retrieved
  1656. report_activity: Optional callback for reporting transport activity
  1657. quiet: Whether to suppress progress output
  1658. include_tags: Whether to include tags
  1659. dumb: Whether to use dumb protocol (not used for TCPGitClient)
  1660. username: Username for authentication (not used for TCPGitClient)
  1661. password: Password for authentication (not used for TCPGitClient)
  1662. config: Configuration object (not used for TCPGitClient)
  1663. Returns:
  1664. A TCPGitClient instance
  1665. """
  1666. assert parsedurl.hostname is not None
  1667. return cls(
  1668. parsedurl.hostname,
  1669. port=parsedurl.port,
  1670. thin_packs=thin_packs,
  1671. report_activity=report_activity,
  1672. quiet=quiet,
  1673. include_tags=include_tags,
  1674. )
  1675. def get_url(self, path: str) -> str:
  1676. r"""Get the URL for a TCP git connection.
  1677. Args:
  1678. path: Repository path
  1679. Returns:
  1680. ``git://`` URL for the path
  1681. """
  1682. # IPv6 addresses contain colons and need to be wrapped in brackets
  1683. if ":" in self._host:
  1684. netloc = f"[{self._host}]"
  1685. else:
  1686. netloc = self._host
  1687. if self._port is not None and self._port != TCP_GIT_PORT:
  1688. netloc += f":{self._port}"
  1689. return urlunsplit(("git", netloc, path, "", ""))
  1690. def _connect(
  1691. self,
  1692. cmd: bytes,
  1693. path: str | bytes,
  1694. protocol_version: int | None = None,
  1695. ) -> tuple[Protocol, Callable[[], bool], IO[bytes] | None]:
  1696. if not isinstance(cmd, bytes):
  1697. raise TypeError(cmd)
  1698. if not isinstance(path, bytes):
  1699. path = path.encode(self._remote_path_encoding)
  1700. sockaddrs = socket.getaddrinfo(
  1701. self._host, self._port, socket.AF_UNSPEC, socket.SOCK_STREAM
  1702. )
  1703. s = None
  1704. err = OSError(f"no address found for {self._host}")
  1705. for family, socktype, protof, canonname, sockaddr in sockaddrs:
  1706. s = socket.socket(family, socktype, protof)
  1707. s.setsockopt(socket.IPPROTO_TCP, socket.TCP_NODELAY, 1)
  1708. try:
  1709. s.connect(sockaddr)
  1710. break
  1711. except OSError as e:
  1712. err = e
  1713. if s is not None:
  1714. s.close()
  1715. s = None
  1716. if s is None:
  1717. raise err
  1718. # -1 means system default buffering
  1719. rfile = s.makefile("rb", -1)
  1720. # 0 means unbuffered
  1721. wfile = s.makefile("wb", 0)
  1722. def close() -> None:
  1723. rfile.close()
  1724. wfile.close()
  1725. s.close()
  1726. proto = Protocol(
  1727. rfile.read,
  1728. wfile.write,
  1729. close,
  1730. report_activity=self._report_activity,
  1731. )
  1732. if path.startswith(b"/~"):
  1733. path = path[1:]
  1734. if cmd == b"upload-pack":
  1735. if protocol_version is None:
  1736. self.protocol_version = DEFAULT_GIT_PROTOCOL_VERSION_FETCH
  1737. else:
  1738. self.protocol_version = protocol_version
  1739. else:
  1740. self.protocol_version = DEFAULT_GIT_PROTOCOL_VERSION_SEND
  1741. if cmd == b"upload-pack" and self.protocol_version == 2:
  1742. # Git protocol version advertisement is hidden behind two NUL bytes
  1743. # for compatibility with older Git server implementations, which
  1744. # would crash if something other than a "host=" header was found
  1745. # after the first NUL byte.
  1746. version_str = b"\0\0version=%d\0" % self.protocol_version
  1747. else:
  1748. version_str = b""
  1749. # TODO(jelmer): Alternative to ascii?
  1750. proto.send_cmd(
  1751. b"git-" + cmd, path, b"host=" + self._host.encode("ascii") + version_str
  1752. )
  1753. return proto, lambda: _fileno_can_read(s.fileno()), None
  1754. class SubprocessWrapper:
  1755. """A socket-like object that talks to a subprocess via pipes."""
  1756. def __init__(self, proc: subprocess.Popen[bytes]) -> None:
  1757. """Initialize a SubprocessWrapper.
  1758. Args:
  1759. proc: Subprocess.Popen instance to wrap
  1760. """
  1761. self.proc = proc
  1762. assert proc.stdout is not None
  1763. assert proc.stdin is not None
  1764. self.read = BufferedReader(proc.stdout).read # type: ignore[type-var]
  1765. self.write = proc.stdin.write
  1766. @property
  1767. def stderr(self) -> IO[bytes] | None:
  1768. """Return the stderr stream of the subprocess."""
  1769. return self.proc.stderr
  1770. def can_read(self) -> bool:
  1771. """Check if there is data available to read.
  1772. Returns: True if data is available, False otherwise
  1773. """
  1774. if sys.platform == "win32":
  1775. from msvcrt import get_osfhandle
  1776. assert self.proc.stdout is not None
  1777. handle = get_osfhandle(self.proc.stdout.fileno())
  1778. return _win32_peek_avail(handle) != 0
  1779. else:
  1780. assert self.proc.stdout is not None
  1781. return _fileno_can_read(self.proc.stdout.fileno())
  1782. def close(self, timeout: int | None = 60) -> None:
  1783. """Close the subprocess and wait for it to terminate.
  1784. Args:
  1785. timeout: Maximum time to wait for subprocess to terminate (seconds)
  1786. Raises:
  1787. GitProtocolError: If subprocess doesn't terminate within timeout
  1788. """
  1789. if self.proc.stdin:
  1790. self.proc.stdin.close()
  1791. if self.proc.stdout:
  1792. self.proc.stdout.close()
  1793. if self.proc.stderr:
  1794. self.proc.stderr.close()
  1795. try:
  1796. self.proc.wait(timeout=timeout)
  1797. except subprocess.TimeoutExpired as e:
  1798. self.proc.kill()
  1799. self.proc.wait()
  1800. raise GitProtocolError(
  1801. f"Git subprocess did not terminate within {timeout} seconds; killed it."
  1802. ) from e
  1803. def find_git_command() -> list[str]:
  1804. """Find command to run for system Git (usually C Git)."""
  1805. if sys.platform == "win32": # support .exe, .bat and .cmd
  1806. try: # to avoid overhead
  1807. import pywintypes
  1808. import win32api
  1809. except ImportError: # run through cmd.exe with some overhead
  1810. return ["cmd", "/c", "git"]
  1811. else:
  1812. try:
  1813. _status, git = win32api.FindExecutable("git")
  1814. return [git]
  1815. except pywintypes.error:
  1816. return ["cmd", "/c", "git"]
  1817. else:
  1818. return ["git"]
  1819. class SubprocessGitClient(TraditionalGitClient):
  1820. """Git client that talks to a server using a subprocess."""
  1821. @classmethod
  1822. def from_parsedurl(
  1823. cls,
  1824. parsedurl: ParseResult,
  1825. thin_packs: bool = True,
  1826. report_activity: Callable[[int, str], None] | None = None,
  1827. quiet: bool = False,
  1828. include_tags: bool = False,
  1829. dumb: bool = False,
  1830. username: str | None = None,
  1831. password: str | None = None,
  1832. config: Config | None = None,
  1833. ) -> "SubprocessGitClient":
  1834. """Create an instance of SubprocessGitClient from a parsed URL.
  1835. Args:
  1836. parsedurl: Result of urlparse()
  1837. thin_packs: Whether or not thin packs should be retrieved
  1838. report_activity: Optional callback for reporting transport activity
  1839. quiet: Whether to suppress progress output
  1840. include_tags: Whether to include tags
  1841. dumb: Whether to use dumb protocol (not used for SubprocessGitClient)
  1842. username: Username for authentication (not used for SubprocessGitClient)
  1843. password: Password for authentication (not used for SubprocessGitClient)
  1844. config: Configuration object (not used for SubprocessGitClient)
  1845. Returns:
  1846. A SubprocessGitClient instance
  1847. """
  1848. return cls(
  1849. thin_packs=thin_packs,
  1850. report_activity=report_activity,
  1851. quiet=quiet,
  1852. include_tags=include_tags,
  1853. )
  1854. git_command: str | None = None
  1855. def _connect(
  1856. self,
  1857. service: bytes,
  1858. path: bytes | str,
  1859. protocol_version: int | None = None,
  1860. ) -> tuple[Protocol, Callable[[], bool], IO[bytes] | None]:
  1861. if not isinstance(service, bytes):
  1862. raise TypeError(service)
  1863. if isinstance(path, bytes):
  1864. path = path.decode(self._remote_path_encoding)
  1865. if self.git_command is None:
  1866. git_command = find_git_command()
  1867. argv = [*git_command, service.decode("ascii"), path]
  1868. p = subprocess.Popen(
  1869. argv,
  1870. bufsize=0,
  1871. stdin=subprocess.PIPE,
  1872. stdout=subprocess.PIPE,
  1873. stderr=subprocess.PIPE,
  1874. )
  1875. pw = SubprocessWrapper(p)
  1876. return (
  1877. Protocol(
  1878. pw.read,
  1879. pw.write,
  1880. pw.close,
  1881. report_activity=self._report_activity,
  1882. ),
  1883. pw.can_read,
  1884. p.stderr,
  1885. )
  1886. class LocalGitClient(GitClient):
  1887. """Git Client that just uses a local on-disk repository."""
  1888. def __init__(
  1889. self,
  1890. thin_packs: bool = True,
  1891. report_activity: Callable[[int, str], None] | None = None,
  1892. config: Config | None = None,
  1893. quiet: bool = False,
  1894. include_tags: bool = False,
  1895. ) -> None:
  1896. """Create a new LocalGitClient instance.
  1897. Args:
  1898. thin_packs: Whether or not thin packs should be retrieved
  1899. report_activity: Optional callback for reporting transport
  1900. activity.
  1901. config: Optional configuration object
  1902. quiet: Whether to suppress progress output
  1903. include_tags: Whether to include tags
  1904. """
  1905. self._report_activity = report_activity
  1906. self._quiet = quiet
  1907. self._include_tags = include_tags
  1908. # Ignore the thin_packs argument
  1909. def get_url(self, path: str) -> str:
  1910. """Get the URL for a local file path.
  1911. Args:
  1912. path: Local file path
  1913. Returns:
  1914. file:// URL for the path
  1915. """
  1916. return urlunsplit(("file", "", path, "", ""))
  1917. @classmethod
  1918. def from_parsedurl(
  1919. cls,
  1920. parsedurl: ParseResult,
  1921. thin_packs: bool = True,
  1922. report_activity: Callable[[int, str], None] | None = None,
  1923. quiet: bool = False,
  1924. include_tags: bool = False,
  1925. dumb: bool = False,
  1926. username: str | None = None,
  1927. password: str | None = None,
  1928. config: Config | None = None,
  1929. ) -> "LocalGitClient":
  1930. """Create an instance of LocalGitClient from a parsed URL.
  1931. Args:
  1932. parsedurl: Result of urlparse()
  1933. thin_packs: Whether or not thin packs should be retrieved
  1934. report_activity: Optional callback for reporting transport activity
  1935. quiet: Whether to suppress progress output
  1936. include_tags: Whether to include tags
  1937. dumb: Whether to use dumb protocol (not used for LocalGitClient)
  1938. username: Username for authentication (not used for LocalGitClient)
  1939. password: Password for authentication (not used for LocalGitClient)
  1940. config: Optional configuration object
  1941. Returns:
  1942. A LocalGitClient instance
  1943. """
  1944. return cls(
  1945. thin_packs=thin_packs,
  1946. report_activity=report_activity,
  1947. quiet=quiet,
  1948. include_tags=include_tags,
  1949. config=config,
  1950. )
  1951. @classmethod
  1952. def _open_repo(cls, path: str | bytes) -> "closing[Repo]":
  1953. """Open a local repository.
  1954. Args:
  1955. path: Repository path (as bytes or str)
  1956. Returns:
  1957. Repo instance wrapped in a closing context manager
  1958. """
  1959. if not isinstance(path, str):
  1960. path = os.fsdecode(path)
  1961. return closing(Repo(path))
  1962. def send_pack(
  1963. self,
  1964. path: str | bytes,
  1965. update_refs: Callable[[dict[bytes, bytes]], dict[bytes, bytes]],
  1966. generate_pack_data: "GeneratePackDataFunc",
  1967. progress: Callable[[bytes], None] | None = None,
  1968. ) -> SendPackResult:
  1969. """Upload a pack to a local on-disk repository.
  1970. Args:
  1971. path: Repository path (as bytestring)
  1972. update_refs: Function to determine changes to remote refs.
  1973. Receive dict with existing remote refs, returns dict with
  1974. changed refs (name -> sha, where sha=ZERO_SHA for deletions)
  1975. with number of items and pack data to upload.
  1976. generate_pack_data: Function that generates pack data given
  1977. have and want object sets
  1978. progress: Optional progress function
  1979. Returns:
  1980. SendPackResult
  1981. Raises:
  1982. SendPackError: if server rejects the pack data
  1983. """
  1984. if not progress:
  1985. def progress(x: bytes) -> None:
  1986. pass
  1987. with self._open_repo(path) as target:
  1988. old_refs = target.get_refs()
  1989. new_refs = update_refs(dict(old_refs))
  1990. have = [sha1 for sha1 in old_refs.values() if sha1 != ZERO_SHA]
  1991. want = []
  1992. for refname, new_sha1 in new_refs.items():
  1993. if (
  1994. new_sha1 not in have
  1995. and new_sha1 not in want
  1996. and new_sha1 != ZERO_SHA
  1997. ):
  1998. want.append(new_sha1)
  1999. if not want and set(new_refs.items()).issubset(set(old_refs.items())):
  2000. return SendPackResult(_to_optional_dict(new_refs), ref_status={})
  2001. target.object_store.add_pack_data(
  2002. *generate_pack_data(
  2003. set(have), set(want), ofs_delta=True, progress=progress
  2004. )
  2005. )
  2006. ref_status: dict[bytes, str | None] = {}
  2007. for refname, new_sha1 in new_refs.items():
  2008. old_sha1 = old_refs.get(refname, ZERO_SHA)
  2009. if new_sha1 != ZERO_SHA:
  2010. if not target.refs.set_if_equals(refname, old_sha1, new_sha1):
  2011. msg = f"unable to set {refname!r} to {new_sha1!r}"
  2012. progress(msg.encode())
  2013. ref_status[refname] = msg
  2014. else:
  2015. if not target.refs.remove_if_equals(refname, old_sha1):
  2016. progress(f"unable to remove {refname!r}".encode())
  2017. ref_status[refname] = "unable to remove"
  2018. return SendPackResult(_to_optional_dict(new_refs), ref_status=ref_status)
  2019. def fetch(
  2020. self,
  2021. path: bytes,
  2022. target: BaseRepo,
  2023. determine_wants: Optional["DetermineWantsFunc"] = None,
  2024. progress: Callable[[bytes], None] | None = None,
  2025. depth: int | None = None,
  2026. ref_prefix: Sequence[bytes] | None = None,
  2027. filter_spec: bytes | None = None,
  2028. protocol_version: int | None = None,
  2029. shallow_since: str | None = None,
  2030. shallow_exclude: list[str] | None = None,
  2031. ) -> FetchPackResult:
  2032. """Fetch into a target repository.
  2033. Args:
  2034. path: Path to fetch from (as bytestring)
  2035. target: Target repository to fetch into
  2036. determine_wants: Optional function determine what refs
  2037. to fetch. Receives dictionary of name->sha, should return
  2038. list of shas to fetch. Defaults to all shas.
  2039. progress: Optional progress function
  2040. depth: Shallow fetch depth
  2041. ref_prefix: List of prefixes of desired references, as a list of
  2042. bytestrings. Filtering is done by the server if supported, and
  2043. client side otherwise.
  2044. filter_spec: A git-rev-list-style object filter spec, as bytestring.
  2045. Only used if the server supports the Git protocol-v2 'filter'
  2046. feature, and ignored otherwise.
  2047. protocol_version: Optional Git protocol version
  2048. shallow_since: Deepen the history to include commits after this date
  2049. shallow_exclude: Deepen the history to exclude commits reachable from these refs
  2050. Returns:
  2051. FetchPackResult object
  2052. """
  2053. with self._open_repo(path) as r:
  2054. refs = r.fetch(
  2055. target,
  2056. determine_wants=determine_wants,
  2057. progress=progress,
  2058. depth=depth,
  2059. )
  2060. return FetchPackResult(
  2061. _to_optional_dict(refs), r.refs.get_symrefs(), agent_string()
  2062. )
  2063. def fetch_pack(
  2064. self,
  2065. path: str | bytes,
  2066. determine_wants: "DetermineWantsFunc",
  2067. graph_walker: GraphWalker,
  2068. pack_data: Callable[[bytes], int],
  2069. progress: Callable[[bytes], None] | None = None,
  2070. depth: int | None = None,
  2071. ref_prefix: Sequence[Ref] | None = None,
  2072. filter_spec: bytes | None = None,
  2073. protocol_version: int | None = None,
  2074. shallow_since: str | None = None,
  2075. shallow_exclude: list[str] | None = None,
  2076. ) -> FetchPackResult:
  2077. """Retrieve a pack from a local on-disk repository.
  2078. Args:
  2079. path: Remote path to fetch from
  2080. determine_wants: Function determine what refs
  2081. to fetch. Receives dictionary of name->sha, should return
  2082. list of shas to fetch.
  2083. graph_walker: Object with next() and ack().
  2084. pack_data: Callback called for each bit of data in the pack
  2085. progress: Callback for progress reports (strings)
  2086. depth: Shallow fetch depth
  2087. ref_prefix: List of prefixes of desired references, as a list of
  2088. bytestrings. Filtering is done by the server if supported, and
  2089. client side otherwise.
  2090. filter_spec: A git-rev-list-style object filter spec, as bytestring.
  2091. Only used if the server supports the Git protocol-v2 'filter'
  2092. feature, and ignored otherwise.
  2093. protocol_version: Optional Git protocol version
  2094. shallow_since: Deepen the history to include commits after this date
  2095. shallow_exclude: Deepen the history to exclude commits reachable from these refs
  2096. Returns:
  2097. FetchPackResult object
  2098. """
  2099. with self._open_repo(path) as r:
  2100. missing_objects = r.find_missing_objects(
  2101. determine_wants, graph_walker, progress=progress, depth=depth
  2102. )
  2103. if missing_objects is None:
  2104. other_haves = set()
  2105. object_ids = []
  2106. else:
  2107. other_haves = missing_objects.get_remote_has()
  2108. object_ids = list(missing_objects)
  2109. symrefs = r.refs.get_symrefs()
  2110. agent = agent_string()
  2111. # Did the process short-circuit (e.g. in a stateless RPC call)?
  2112. # Note that the client still expects a 0-object pack in most cases.
  2113. if object_ids is None:
  2114. return FetchPackResult(None, symrefs, agent)
  2115. write_pack_from_container(
  2116. pack_data, # type: ignore[arg-type]
  2117. r.object_store,
  2118. object_ids,
  2119. other_haves=other_haves,
  2120. )
  2121. # Convert refs to Optional type for FetchPackResult
  2122. return FetchPackResult(_to_optional_dict(r.get_refs()), symrefs, agent)
  2123. def get_refs(
  2124. self,
  2125. path: str | bytes,
  2126. protocol_version: int | None = None,
  2127. ref_prefix: Sequence[Ref] | None = None,
  2128. ) -> LsRemoteResult:
  2129. """Retrieve the current refs from a local on-disk repository."""
  2130. with self._open_repo(path) as target:
  2131. refs_dict = target.get_refs()
  2132. refs = _to_optional_dict(refs_dict)
  2133. # Extract symrefs from the local repository
  2134. symrefs: dict[bytes, bytes] = {}
  2135. for ref in refs:
  2136. try:
  2137. # Check if this ref is symbolic by reading it directly
  2138. ref_value = target.refs.read_ref(ref)
  2139. if ref_value and ref_value.startswith(SYMREF):
  2140. # Extract the target from the symref
  2141. symrefs[ref] = ref_value[len(SYMREF) :]
  2142. except (KeyError, ValueError):
  2143. # Not a symbolic ref or error reading it
  2144. pass
  2145. return LsRemoteResult(refs, symrefs)
  2146. class BundleClient(GitClient):
  2147. """Git Client that reads from a bundle file."""
  2148. def __init__(
  2149. self,
  2150. thin_packs: bool = True,
  2151. report_activity: Callable[[int, str], None] | None = None,
  2152. config: Config | None = None,
  2153. quiet: bool = False,
  2154. include_tags: bool = False,
  2155. ) -> None:
  2156. """Create a new BundleClient instance.
  2157. Args:
  2158. thin_packs: Whether or not thin packs should be retrieved
  2159. report_activity: Optional callback for reporting transport
  2160. activity.
  2161. config: Optional configuration object
  2162. quiet: Whether to suppress progress output
  2163. include_tags: Whether to include tags
  2164. """
  2165. self._report_activity = report_activity
  2166. self._quiet = quiet
  2167. self._include_tags = include_tags
  2168. def get_url(self, path: str) -> str:
  2169. """Get the URL for a bundle file path.
  2170. Args:
  2171. path: Bundle file path
  2172. Returns:
  2173. The path unchanged (bundle files use local paths)
  2174. """
  2175. return path
  2176. @classmethod
  2177. def from_parsedurl(
  2178. cls,
  2179. parsedurl: ParseResult,
  2180. thin_packs: bool = True,
  2181. report_activity: Callable[[int, str], None] | None = None,
  2182. quiet: bool = False,
  2183. include_tags: bool = False,
  2184. dumb: bool = False,
  2185. username: str | None = None,
  2186. password: str | None = None,
  2187. config: Config | None = None,
  2188. ) -> "BundleClient":
  2189. """Create an instance of BundleClient from a parsed URL.
  2190. Args:
  2191. parsedurl: Result of urlparse()
  2192. thin_packs: Whether or not thin packs should be retrieved
  2193. report_activity: Optional callback for reporting transport activity
  2194. quiet: Whether to suppress progress output
  2195. include_tags: Whether to include tags
  2196. dumb: Whether to use dumb protocol (not used for BundleClient)
  2197. username: Username for authentication (not used for BundleClient)
  2198. password: Password for authentication (not used for BundleClient)
  2199. config: Configuration object (not used for BundleClient)
  2200. Returns:
  2201. A BundleClient instance
  2202. """
  2203. return cls(
  2204. thin_packs=thin_packs,
  2205. report_activity=report_activity,
  2206. quiet=quiet,
  2207. include_tags=include_tags,
  2208. )
  2209. @classmethod
  2210. def _is_bundle_file(cls, path: str) -> bool:
  2211. """Check if a file is a git bundle by reading the first line."""
  2212. try:
  2213. with open(path, "rb") as f:
  2214. first_line = f.readline()
  2215. return first_line in (b"# v2 git bundle\n", b"# v3 git bundle\n")
  2216. except OSError:
  2217. return False
  2218. @classmethod
  2219. def _open_bundle(cls, path: str | bytes) -> "Bundle":
  2220. """Open and parse a bundle file.
  2221. Args:
  2222. path: Path to the bundle file (bytes or str)
  2223. Returns:
  2224. Bundle object with parsed metadata
  2225. Raises:
  2226. AssertionError: If bundle format is unsupported
  2227. """
  2228. if not isinstance(path, str):
  2229. path = os.fsdecode(path)
  2230. # Read bundle metadata without PackData to avoid file handle issues
  2231. with open(path, "rb") as f:
  2232. from dulwich.bundle import Bundle
  2233. version = None
  2234. firstline = f.readline()
  2235. if firstline == b"# v2 git bundle\n":
  2236. version = 2
  2237. elif firstline == b"# v3 git bundle\n":
  2238. version = 3
  2239. else:
  2240. raise AssertionError(f"unsupported bundle format header: {firstline!r}")
  2241. capabilities = {}
  2242. prerequisites = []
  2243. references = {}
  2244. line = f.readline()
  2245. if version >= 3:
  2246. while line.startswith(b"@"):
  2247. line = line[1:].rstrip(b"\n")
  2248. try:
  2249. key, value_bytes = line.split(b"=", 1)
  2250. value = value_bytes.decode("utf-8")
  2251. except ValueError:
  2252. key = line
  2253. value = None
  2254. capabilities[key.decode("utf-8")] = value
  2255. line = f.readline()
  2256. while line.startswith(b"-"):
  2257. (obj_id, comment) = line[1:].rstrip(b"\n").split(b" ", 1)
  2258. prerequisites.append((obj_id, comment))
  2259. line = f.readline()
  2260. while line != b"\n":
  2261. (obj_id, ref) = line.rstrip(b"\n").split(b" ", 1)
  2262. references[ref] = obj_id
  2263. line = f.readline()
  2264. # Don't read PackData here, we'll do it later
  2265. bundle = Bundle()
  2266. bundle.version = version
  2267. bundle.capabilities = capabilities
  2268. bundle.prerequisites = prerequisites
  2269. bundle.references = references
  2270. bundle.pack_data = None # Will be read on demand
  2271. return bundle
  2272. @staticmethod
  2273. def _skip_to_pack_data(f: IO[bytes], version: int) -> None:
  2274. """Skip to the pack data section in a bundle file.
  2275. Args:
  2276. f: File object positioned at the beginning of the bundle
  2277. version: Bundle format version (2 or 3)
  2278. Raises:
  2279. AssertionError: If bundle header is invalid
  2280. """
  2281. # Skip header
  2282. header = f.readline()
  2283. if header not in (b"# v2 git bundle\n", b"# v3 git bundle\n"):
  2284. raise AssertionError(f"Invalid bundle header: {header!r}")
  2285. line = f.readline()
  2286. # Skip capabilities (v3 only)
  2287. if version >= 3:
  2288. while line.startswith(b"@"):
  2289. line = f.readline()
  2290. # Skip prerequisites
  2291. while line.startswith(b"-"):
  2292. line = f.readline()
  2293. # Skip references
  2294. while line != b"\n":
  2295. line = f.readline()
  2296. # Now at pack data
  2297. def send_pack(
  2298. self,
  2299. path: str | bytes,
  2300. update_refs: Callable[[dict[bytes, bytes]], dict[bytes, bytes]],
  2301. generate_pack_data: "GeneratePackDataFunc",
  2302. progress: Callable[[bytes], None] | None = None,
  2303. ) -> SendPackResult:
  2304. """Upload is not supported for bundle files."""
  2305. raise NotImplementedError("Bundle files are read-only")
  2306. def fetch(
  2307. self,
  2308. path: bytes,
  2309. target: BaseRepo,
  2310. determine_wants: Optional["DetermineWantsFunc"] = None,
  2311. progress: Callable[[bytes], None] | None = None,
  2312. depth: int | None = None,
  2313. ref_prefix: Sequence[Ref] | None = None,
  2314. filter_spec: bytes | None = None,
  2315. protocol_version: int | None = None,
  2316. shallow_since: str | None = None,
  2317. shallow_exclude: list[str] | None = None,
  2318. ) -> FetchPackResult:
  2319. """Fetch into a target repository from a bundle file."""
  2320. bundle = self._open_bundle(path)
  2321. # Get references from bundle
  2322. refs = dict(bundle.references)
  2323. # Determine what we want to fetch
  2324. if determine_wants is None:
  2325. _ = list(refs.values())
  2326. else:
  2327. _ = determine_wants(refs, None)
  2328. # Add pack data to target repository
  2329. # Need to reopen the file for pack data access
  2330. with open(path, "rb") as pack_file:
  2331. # Skip to pack data section
  2332. assert bundle.version is not None
  2333. BundleClient._skip_to_pack_data(pack_file, bundle.version)
  2334. # Read pack data into memory to avoid file positioning issues
  2335. pack_bytes = pack_file.read()
  2336. # Create PackData from in-memory bytes
  2337. from io import BytesIO
  2338. pack_io = BytesIO(pack_bytes)
  2339. pack_data = PackData.from_file(pack_io)
  2340. target.object_store.add_pack_data(len(pack_data), pack_data.iter_unpacked())
  2341. # Apply ref filtering if specified
  2342. if ref_prefix:
  2343. filtered_refs = {}
  2344. for ref_name, ref_value in refs.items():
  2345. for prefix in ref_prefix:
  2346. if ref_name.startswith(prefix):
  2347. filtered_refs[ref_name] = ref_value
  2348. break
  2349. refs = filtered_refs
  2350. return FetchPackResult(_to_optional_dict(refs), {}, agent_string())
  2351. def fetch_pack(
  2352. self,
  2353. path: str | bytes,
  2354. determine_wants: "DetermineWantsFunc",
  2355. graph_walker: GraphWalker,
  2356. pack_data: Callable[[bytes], int],
  2357. progress: Callable[[bytes], None] | None = None,
  2358. depth: int | None = None,
  2359. ref_prefix: Sequence[Ref] | None = None,
  2360. filter_spec: bytes | None = None,
  2361. protocol_version: int | None = None,
  2362. shallow_since: str | None = None,
  2363. shallow_exclude: list[str] | None = None,
  2364. ) -> FetchPackResult:
  2365. """Retrieve a pack from a bundle file."""
  2366. bundle = self._open_bundle(path)
  2367. # Get references from bundle
  2368. refs = dict(bundle.references)
  2369. # Determine what we want to fetch
  2370. try:
  2371. _ = determine_wants(refs, depth)
  2372. except TypeError:
  2373. # Old-style determine_wants that doesn't accept depth
  2374. _ = determine_wants(refs)
  2375. # Write pack data to the callback
  2376. # Need to reopen the file for pack data access
  2377. with open(path, "rb") as pack_file:
  2378. # Skip to pack data section
  2379. assert bundle.version is not None
  2380. BundleClient._skip_to_pack_data(pack_file, bundle.version)
  2381. # Read pack data and write it to the callback
  2382. pack_bytes = pack_file.read()
  2383. pack_data(pack_bytes)
  2384. # Apply ref filtering if specified
  2385. if ref_prefix:
  2386. filtered_refs = {}
  2387. for ref_name, ref_value in refs.items():
  2388. for prefix in ref_prefix:
  2389. if ref_name.startswith(prefix):
  2390. filtered_refs[ref_name] = ref_value
  2391. break
  2392. refs = filtered_refs
  2393. return FetchPackResult(_to_optional_dict(refs), {}, agent_string())
  2394. def get_refs(
  2395. self,
  2396. path: str | bytes,
  2397. protocol_version: int | None = None,
  2398. ref_prefix: Sequence[Ref] | None = None,
  2399. ) -> LsRemoteResult:
  2400. """Retrieve the current refs from a bundle file."""
  2401. bundle = self._open_bundle(path)
  2402. refs = dict(bundle.references)
  2403. # Apply ref filtering if specified
  2404. if ref_prefix:
  2405. filtered_refs = {}
  2406. for ref_name, ref_value in refs.items():
  2407. for prefix in ref_prefix:
  2408. if ref_name.startswith(prefix):
  2409. filtered_refs[ref_name] = ref_value
  2410. break
  2411. refs = filtered_refs
  2412. # Bundle refs are always concrete (never None), but LsRemoteResult expects Optional
  2413. return LsRemoteResult(_to_optional_dict(refs), {})
  2414. # What Git client to use for local access
  2415. default_local_git_client_cls = LocalGitClient
  2416. class SSHVendor:
  2417. """A client side SSH implementation."""
  2418. def run_command(
  2419. self,
  2420. host: str,
  2421. command: bytes,
  2422. username: str | None = None,
  2423. port: int | None = None,
  2424. password: str | None = None,
  2425. key_filename: str | None = None,
  2426. ssh_command: str | None = None,
  2427. protocol_version: int | None = None,
  2428. ) -> SubprocessWrapper:
  2429. """Connect to an SSH server.
  2430. Run a command remotely and return a file-like object for interaction
  2431. with the remote command.
  2432. Args:
  2433. host: Host name
  2434. command: Command to run (as argv array)
  2435. username: Optional ame of user to log in as
  2436. port: Optional SSH port to use
  2437. password: Optional ssh password for login or private key
  2438. key_filename: Optional path to private keyfile
  2439. ssh_command: Optional SSH command
  2440. protocol_version: Desired Git protocol version. By default the highest
  2441. mutually supported protocol version will be used.
  2442. """
  2443. raise NotImplementedError(self.run_command)
  2444. class StrangeHostname(Exception):
  2445. """Refusing to connect to strange SSH hostname."""
  2446. def __init__(self, hostname: str) -> None:
  2447. """Initialize StrangeHostname exception.
  2448. Args:
  2449. hostname: The strange hostname that was rejected
  2450. """
  2451. super().__init__(hostname)
  2452. class SubprocessSSHVendor(SSHVendor):
  2453. """SSH vendor that shells out to the local 'ssh' command."""
  2454. def run_command(
  2455. self,
  2456. host: str,
  2457. command: bytes,
  2458. username: str | None = None,
  2459. port: int | None = None,
  2460. password: str | None = None,
  2461. key_filename: str | None = None,
  2462. ssh_command: str | None = None,
  2463. protocol_version: int | None = None,
  2464. ) -> SubprocessWrapper:
  2465. """Run a git command over SSH.
  2466. Args:
  2467. host: SSH host to connect to
  2468. command: Git command to run
  2469. username: Optional username
  2470. port: Optional port number
  2471. password: Optional password (not supported)
  2472. key_filename: Optional SSH key file
  2473. ssh_command: Optional custom SSH command
  2474. protocol_version: Optional Git protocol version
  2475. Returns:
  2476. Tuple of (subprocess.Popen, Protocol, stderr_stream)
  2477. """
  2478. if password is not None:
  2479. raise NotImplementedError(
  2480. "Setting password not supported by SubprocessSSHVendor."
  2481. )
  2482. if ssh_command:
  2483. import shlex
  2484. args = [*shlex.split(ssh_command, posix=sys.platform != "win32"), "-x"]
  2485. else:
  2486. args = ["ssh", "-x"]
  2487. if port:
  2488. args.extend(["-p", str(port)])
  2489. if key_filename:
  2490. args.extend(["-i", str(key_filename)])
  2491. if protocol_version is None:
  2492. protocol_version = DEFAULT_GIT_PROTOCOL_VERSION_FETCH
  2493. if protocol_version > 0:
  2494. args.extend(["-o", f"SetEnv GIT_PROTOCOL=version={protocol_version}"])
  2495. if username:
  2496. host = f"{username}@{host}"
  2497. if host.startswith("-"):
  2498. raise StrangeHostname(hostname=host)
  2499. args.append(host)
  2500. proc = subprocess.Popen(
  2501. [*args, command],
  2502. bufsize=0,
  2503. stdin=subprocess.PIPE,
  2504. stdout=subprocess.PIPE,
  2505. stderr=subprocess.PIPE,
  2506. )
  2507. return SubprocessWrapper(proc)
  2508. class PLinkSSHVendor(SSHVendor):
  2509. """SSH vendor that shells out to the local 'plink' command."""
  2510. def run_command(
  2511. self,
  2512. host: str,
  2513. command: bytes,
  2514. username: str | None = None,
  2515. port: int | None = None,
  2516. password: str | None = None,
  2517. key_filename: str | None = None,
  2518. ssh_command: str | None = None,
  2519. protocol_version: int | None = None,
  2520. ) -> SubprocessWrapper:
  2521. """Run a git command over SSH using PLink.
  2522. Args:
  2523. host: SSH host to connect to
  2524. command: Git command to run
  2525. username: Optional username
  2526. port: Optional port number
  2527. password: Optional password
  2528. key_filename: Optional SSH key file
  2529. ssh_command: Optional custom SSH command
  2530. protocol_version: Optional Git protocol version
  2531. Returns:
  2532. Tuple of (subprocess.Popen, Protocol, stderr_stream)
  2533. """
  2534. if ssh_command:
  2535. import shlex
  2536. args = [*shlex.split(ssh_command, posix=sys.platform != "win32"), "-ssh"]
  2537. elif sys.platform == "win32":
  2538. args = ["plink.exe", "-ssh"]
  2539. else:
  2540. args = ["plink", "-ssh"]
  2541. if password is not None:
  2542. import warnings
  2543. warnings.warn(
  2544. "Invoking PLink with a password exposes the password in the "
  2545. "process list."
  2546. )
  2547. args.extend(["-pw", str(password)])
  2548. if port:
  2549. args.extend(["-P", str(port)])
  2550. if key_filename:
  2551. args.extend(["-i", str(key_filename)])
  2552. if username:
  2553. host = f"{username}@{host}"
  2554. if host.startswith("-"):
  2555. raise StrangeHostname(hostname=host)
  2556. args.append(host)
  2557. # plink.exe does not provide a way to pass environment variables
  2558. # via the command line. The best we can do is set an environment
  2559. # variable and hope that plink will pass it to the server. If this
  2560. # does not work then the server should behave as if we had requested
  2561. # protocol version 0.
  2562. env = copy.deepcopy(os.environ)
  2563. if protocol_version is None:
  2564. protocol_version = DEFAULT_GIT_PROTOCOL_VERSION_FETCH
  2565. if protocol_version > 0:
  2566. env["GIT_PROTOCOL"] = f"version={protocol_version}"
  2567. proc = subprocess.Popen(
  2568. [*args, command],
  2569. bufsize=0,
  2570. stdin=subprocess.PIPE,
  2571. stdout=subprocess.PIPE,
  2572. stderr=subprocess.PIPE,
  2573. env=env,
  2574. )
  2575. return SubprocessWrapper(proc)
  2576. # Can be overridden by users
  2577. get_ssh_vendor: Callable[[], SSHVendor] = SubprocessSSHVendor
  2578. class SSHGitClient(TraditionalGitClient):
  2579. """Git client that connects over SSH."""
  2580. def __init__(
  2581. self,
  2582. host: str,
  2583. port: int | None = None,
  2584. username: str | None = None,
  2585. vendor: SSHVendor | None = None,
  2586. config: Config | None = None,
  2587. password: str | None = None,
  2588. key_filename: str | None = None,
  2589. ssh_command: str | None = None,
  2590. path_encoding: str = TraditionalGitClient.DEFAULT_ENCODING,
  2591. thin_packs: bool = True,
  2592. report_activity: Callable[[int, str], None] | None = None,
  2593. quiet: bool = False,
  2594. include_tags: bool = False,
  2595. ) -> None:
  2596. """Initialize SSHGitClient.
  2597. Args:
  2598. host: SSH hostname
  2599. port: Optional SSH port
  2600. username: Optional username
  2601. vendor: Optional SSH vendor
  2602. config: Optional configuration
  2603. password: Optional password
  2604. key_filename: Optional SSH key file
  2605. ssh_command: Optional custom SSH command
  2606. path_encoding: Encoding for paths (default: utf-8)
  2607. thin_packs: Whether or not thin packs should be retrieved
  2608. report_activity: Optional callback for reporting transport activity
  2609. quiet: Whether to suppress output
  2610. include_tags: Send annotated tags when sending the objects they point to
  2611. """
  2612. self.host = host
  2613. self.port = port
  2614. self.username = username
  2615. self.password = password
  2616. self.key_filename = key_filename
  2617. # Priority: ssh_command parameter, then env vars, then core.sshCommand config
  2618. if ssh_command:
  2619. self.ssh_command = ssh_command
  2620. else:
  2621. # Check environment variables first
  2622. env_ssh_command = os.environ.get("GIT_SSH_COMMAND")
  2623. if env_ssh_command:
  2624. self.ssh_command = env_ssh_command
  2625. else:
  2626. env_ssh = os.environ.get("GIT_SSH")
  2627. if env_ssh:
  2628. self.ssh_command = env_ssh
  2629. else:
  2630. # Fall back to config if no environment variable set
  2631. if config is not None:
  2632. try:
  2633. config_ssh_command = config.get((b"core",), b"sshCommand")
  2634. self.ssh_command = (
  2635. config_ssh_command.decode()
  2636. if config_ssh_command
  2637. else "ssh"
  2638. )
  2639. except KeyError:
  2640. self.ssh_command = "ssh"
  2641. else:
  2642. self.ssh_command = "ssh"
  2643. super().__init__(
  2644. path_encoding=path_encoding,
  2645. thin_packs=thin_packs,
  2646. report_activity=report_activity,
  2647. quiet=quiet,
  2648. include_tags=include_tags,
  2649. )
  2650. self.alternative_paths: dict[bytes, bytes] = {}
  2651. if vendor is not None:
  2652. self.ssh_vendor = vendor
  2653. else:
  2654. self.ssh_vendor = get_ssh_vendor()
  2655. def get_url(self, path: str) -> str:
  2656. """Get the SSH URL for a path."""
  2657. netloc = self.host
  2658. if self.port is not None:
  2659. netloc += f":{self.port}"
  2660. if self.username is not None:
  2661. netloc = urlquote(self.username, "@/:") + "@" + netloc
  2662. return urlunsplit(("ssh", netloc, path, "", ""))
  2663. @classmethod
  2664. def from_parsedurl(
  2665. cls,
  2666. parsedurl: ParseResult,
  2667. thin_packs: bool = True,
  2668. report_activity: Callable[[int, str], None] | None = None,
  2669. quiet: bool = False,
  2670. include_tags: bool = False,
  2671. dumb: bool = False,
  2672. username: str | None = None,
  2673. password: str | None = None,
  2674. config: Config | None = None,
  2675. path_encoding: str = TraditionalGitClient.DEFAULT_ENCODING,
  2676. vendor: SSHVendor | None = None,
  2677. ) -> "SSHGitClient":
  2678. """Create an SSHGitClient from a parsed URL.
  2679. Args:
  2680. parsedurl: Result of urlparse()
  2681. thin_packs: Whether or not thin packs should be retrieved
  2682. report_activity: Optional callback for reporting transport activity
  2683. quiet: Whether to suppress progress output
  2684. include_tags: Whether to include tags
  2685. dumb: Whether to use dumb protocol (not used for SSHGitClient)
  2686. username: SSH username
  2687. password: SSH password
  2688. config: Configuration object
  2689. path_encoding: Encoding for paths
  2690. vendor: SSH implementation to use
  2691. Returns:
  2692. An SSHGitClient instance
  2693. """
  2694. if parsedurl.hostname is None:
  2695. raise ValueError("SSH URL must have a hostname")
  2696. return cls(
  2697. host=parsedurl.hostname,
  2698. port=parsedurl.port,
  2699. username=username or parsedurl.username,
  2700. thin_packs=thin_packs,
  2701. report_activity=report_activity,
  2702. quiet=quiet,
  2703. include_tags=include_tags,
  2704. path_encoding=path_encoding,
  2705. vendor=vendor,
  2706. config=config,
  2707. password=password,
  2708. )
  2709. def _get_cmd_path(self, cmd: bytes) -> bytes:
  2710. cmd = self.alternative_paths.get(cmd, b"git-" + cmd)
  2711. assert isinstance(cmd, bytes)
  2712. return cmd
  2713. def _connect(
  2714. self,
  2715. cmd: bytes,
  2716. path: str | bytes,
  2717. protocol_version: int | None = None,
  2718. ) -> tuple[Protocol, Callable[[], bool], IO[bytes] | None]:
  2719. if not isinstance(cmd, bytes):
  2720. raise TypeError(cmd)
  2721. if isinstance(path, bytes):
  2722. path = path.decode(self._remote_path_encoding)
  2723. if path.startswith("/~"):
  2724. path = path[1:]
  2725. argv = (
  2726. self._get_cmd_path(cmd)
  2727. + b" '"
  2728. + path.encode(self._remote_path_encoding)
  2729. + b"'"
  2730. )
  2731. kwargs = {}
  2732. if self.password is not None:
  2733. kwargs["password"] = self.password
  2734. if self.key_filename is not None:
  2735. kwargs["key_filename"] = self.key_filename
  2736. # GIT_SSH_COMMAND takes precedence over GIT_SSH
  2737. if self.ssh_command is not None:
  2738. kwargs["ssh_command"] = self.ssh_command
  2739. con = self.ssh_vendor.run_command(
  2740. self.host,
  2741. argv,
  2742. port=self.port,
  2743. username=self.username,
  2744. protocol_version=protocol_version,
  2745. **kwargs,
  2746. )
  2747. return (
  2748. Protocol(
  2749. con.read,
  2750. con.write,
  2751. con.close,
  2752. report_activity=self._report_activity,
  2753. ),
  2754. con.can_read,
  2755. getattr(con, "stderr", None),
  2756. )
  2757. def default_user_agent_string() -> str:
  2758. """Return the default user agent string for Dulwich."""
  2759. # Start user agent with "git/", because GitHub requires this. :-( See
  2760. # https://github.com/jelmer/dulwich/issues/562 for details.
  2761. return "git/dulwich/{}".format(".".join([str(x) for x in dulwich.__version__]))
  2762. def _urlmatch_http_sections(
  2763. config: Config, url: str | None
  2764. ) -> Iterator[tuple[bytes, ...]]:
  2765. """Yield http config sections matching the given URL, ordered by specificity.
  2766. Yields sections from least specific to most specific, so callers can
  2767. apply settings in order with more specific settings overriding less specific ones.
  2768. Args:
  2769. config: Git configuration object
  2770. url: URL to match against config sections (if None, only yields global http section)
  2771. Yields:
  2772. Config section tuples that match the URL, ordered by specificity
  2773. """
  2774. encoding = getattr(config, "encoding", None) or sys.getdefaultencoding()
  2775. parsed_url = urlparse(url) if url else None
  2776. # Collect all matching sections with their specificity
  2777. # (specificity is based on URL path length - longer = more specific)
  2778. matching_sections: list[tuple[int, tuple[bytes, ...]]] = []
  2779. for config_section in config.sections():
  2780. if config_section[0] != b"http":
  2781. continue
  2782. if len(config_section) < 2:
  2783. # Global http section (least specific)
  2784. matching_sections.append((0, config_section))
  2785. elif parsed_url is not None:
  2786. # URL-specific http section - only match if we have a URL
  2787. config_url = config_section[1].decode(encoding)
  2788. parsed_config_url = urlparse(config_url)
  2789. is_match = False
  2790. if parsed_config_url.scheme and parsed_config_url.netloc:
  2791. is_match = match_urls(parsed_url, parsed_config_url)
  2792. else:
  2793. is_match = match_partial_url(parsed_url, config_url)
  2794. if is_match:
  2795. # Calculate specificity based on URL path length
  2796. specificity = len(parsed_config_url.path.rstrip("/"))
  2797. matching_sections.append((specificity, config_section))
  2798. # Sort by specificity (least specific first)
  2799. matching_sections.sort(key=lambda x: x[0])
  2800. for _, section in matching_sections:
  2801. yield section
  2802. def default_urllib3_manager(
  2803. config: Config | None,
  2804. pool_manager_cls: type | None = None,
  2805. proxy_manager_cls: type | None = None,
  2806. base_url: str | None = None,
  2807. timeout: float | None = None,
  2808. cert_reqs: str | None = None,
  2809. ) -> Union["urllib3.ProxyManager", "urllib3.PoolManager"]:
  2810. """Return urllib3 connection pool manager.
  2811. Honour detected proxy configurations.
  2812. Args:
  2813. config: `dulwich.config.ConfigDict` instance with Git configuration.
  2814. pool_manager_cls: Pool manager class to use
  2815. proxy_manager_cls: Proxy manager class to use
  2816. base_url: Base URL for proxy bypass checks
  2817. timeout: Timeout for HTTP requests in seconds
  2818. cert_reqs: SSL certificate requirements (e.g. "CERT_REQUIRED", "CERT_NONE")
  2819. Returns:
  2820. Either pool_manager_cls (defaults to `urllib3.ProxyManager`) instance for
  2821. proxy configurations, proxy_manager_cls
  2822. (defaults to `urllib3.PoolManager`) instance otherwise
  2823. """
  2824. proxy_server: str | None = None
  2825. user_agent: str | None = None
  2826. ca_certs: str | None = None
  2827. ssl_verify: bool | None = None
  2828. if proxy_server is None:
  2829. for proxyname in ("https_proxy", "http_proxy", "all_proxy"):
  2830. proxy_server = os.environ.get(proxyname)
  2831. if proxy_server:
  2832. break
  2833. if proxy_server:
  2834. if check_for_proxy_bypass(base_url):
  2835. proxy_server = None
  2836. if config is not None:
  2837. # Iterate through all matching http sections from least to most specific
  2838. # More specific settings will override less specific ones
  2839. for section in _urlmatch_http_sections(config, base_url):
  2840. if proxy_server is None:
  2841. try:
  2842. proxy_server_bytes = config.get(section, b"proxy")
  2843. except KeyError:
  2844. pass
  2845. else:
  2846. if proxy_server_bytes is not None:
  2847. proxy_server = proxy_server_bytes.decode("utf-8")
  2848. try:
  2849. user_agent_bytes = config.get(section, b"useragent")
  2850. except KeyError:
  2851. pass
  2852. else:
  2853. if user_agent_bytes is not None:
  2854. user_agent = user_agent_bytes.decode("utf-8")
  2855. try:
  2856. ssl_verify_value = config.get_boolean(section, b"sslVerify")
  2857. except KeyError:
  2858. pass
  2859. else:
  2860. if ssl_verify_value is not None:
  2861. ssl_verify = ssl_verify_value
  2862. try:
  2863. ca_certs_bytes = config.get(section, b"sslCAInfo")
  2864. except KeyError:
  2865. pass
  2866. else:
  2867. if ca_certs_bytes is not None:
  2868. ca_certs = ca_certs_bytes.decode("utf-8")
  2869. if timeout is None:
  2870. try:
  2871. timeout_bytes = config.get(section, b"timeout")
  2872. except KeyError:
  2873. pass
  2874. else:
  2875. if timeout_bytes is not None:
  2876. timeout = float(timeout_bytes.decode("utf-8"))
  2877. # Default ssl_verify to True if not set
  2878. if ssl_verify is None:
  2879. ssl_verify = True
  2880. if user_agent is None:
  2881. user_agent = default_user_agent_string()
  2882. headers = {"User-agent": user_agent}
  2883. # Check for extra headers in config with URL matching
  2884. if config is not None:
  2885. # Apply extra headers from least specific to most specific
  2886. for section in _urlmatch_http_sections(config, base_url):
  2887. try:
  2888. extra_headers = config.get_multivar(section, b"extraHeader")
  2889. except KeyError:
  2890. continue
  2891. for extra_header in extra_headers:
  2892. if not extra_header:
  2893. logger.warning("Ignoring empty http.extraHeader value")
  2894. continue
  2895. if b": " not in extra_header:
  2896. logger.warning(
  2897. "Ignoring invalid http.extraHeader value %r (missing ': ' separator)",
  2898. extra_header,
  2899. )
  2900. continue
  2901. # Parse the header (format: "Header-Name: value")
  2902. header_name, header_value = extra_header.split(b": ", 1)
  2903. try:
  2904. headers[header_name.decode("utf-8")] = header_value.decode("utf-8")
  2905. except UnicodeDecodeError as e:
  2906. logger.warning(
  2907. "Ignoring http.extraHeader with invalid UTF-8: %s", e
  2908. )
  2909. kwargs: dict[str, str | float | None] = {
  2910. "ca_certs": ca_certs,
  2911. }
  2912. # Add timeout if specified
  2913. if timeout is not None:
  2914. kwargs["timeout"] = timeout
  2915. # Handle cert_reqs - allow override from parameter
  2916. if cert_reqs is not None:
  2917. kwargs["cert_reqs"] = cert_reqs
  2918. elif ssl_verify is True:
  2919. kwargs["cert_reqs"] = "CERT_REQUIRED"
  2920. elif ssl_verify is False:
  2921. kwargs["cert_reqs"] = "CERT_NONE"
  2922. else:
  2923. # Default to SSL verification
  2924. kwargs["cert_reqs"] = "CERT_REQUIRED"
  2925. import urllib3
  2926. manager: urllib3.ProxyManager | urllib3.PoolManager
  2927. if proxy_server is not None:
  2928. if proxy_manager_cls is None:
  2929. proxy_manager_cls = urllib3.ProxyManager
  2930. if not isinstance(proxy_server, str):
  2931. proxy_server = proxy_server.decode()
  2932. proxy_server_url = urlparse(proxy_server)
  2933. if proxy_server_url.username is not None:
  2934. proxy_headers = urllib3.make_headers(
  2935. proxy_basic_auth=f"{proxy_server_url.username}:{proxy_server_url.password or ''}"
  2936. )
  2937. else:
  2938. proxy_headers = {}
  2939. manager = proxy_manager_cls(
  2940. proxy_server, proxy_headers=proxy_headers, headers=headers, **kwargs
  2941. )
  2942. else:
  2943. if pool_manager_cls is None:
  2944. pool_manager_cls = urllib3.PoolManager
  2945. manager = pool_manager_cls(headers=headers, **kwargs)
  2946. return manager
  2947. def check_for_proxy_bypass(base_url: str | None) -> bool:
  2948. """Check if proxy should be bypassed for the given URL."""
  2949. # Check if a proxy bypass is defined with the no_proxy environment variable
  2950. if base_url: # only check if base_url is provided
  2951. no_proxy_str = os.environ.get("no_proxy")
  2952. if no_proxy_str:
  2953. # implementation based on curl behavior: https://curl.se/libcurl/c/CURLOPT_NOPROXY.html
  2954. # get hostname of provided parsed url
  2955. parsed_url = urlparse(base_url)
  2956. hostname = parsed_url.hostname
  2957. if hostname:
  2958. import ipaddress
  2959. # check if hostname is an ip address
  2960. try:
  2961. hostname_ip = ipaddress.ip_address(hostname)
  2962. except ValueError:
  2963. hostname_ip = None
  2964. no_proxy_values = no_proxy_str.split(",")
  2965. for no_proxy_value in no_proxy_values:
  2966. no_proxy_value = no_proxy_value.strip()
  2967. if no_proxy_value:
  2968. no_proxy_value = no_proxy_value.lower()
  2969. no_proxy_value = no_proxy_value.lstrip(
  2970. "."
  2971. ) # ignore leading dots
  2972. if hostname_ip:
  2973. # check if no_proxy_value is a ip network
  2974. try:
  2975. no_proxy_value_network = ipaddress.ip_network(
  2976. no_proxy_value, strict=False
  2977. )
  2978. except ValueError:
  2979. no_proxy_value_network = None
  2980. if no_proxy_value_network:
  2981. # if hostname is a ip address and no_proxy_value is a ip network -> check if ip address is part of network
  2982. if hostname_ip in no_proxy_value_network:
  2983. return True
  2984. if no_proxy_value == "*":
  2985. # '*' is special case for always bypass proxy
  2986. return True
  2987. if hostname == no_proxy_value:
  2988. return True
  2989. no_proxy_value = (
  2990. "." + no_proxy_value
  2991. ) # add a dot to only match complete domains
  2992. if hostname.endswith(no_proxy_value):
  2993. return True
  2994. return False
  2995. class AbstractHttpGitClient(GitClient):
  2996. """Abstract base class for HTTP Git Clients.
  2997. This is agonistic of the actual HTTP implementation.
  2998. Subclasses should provide an implementation of the
  2999. _http_request method.
  3000. """
  3001. def __init__(
  3002. self,
  3003. base_url: str,
  3004. dumb: bool = False,
  3005. thin_packs: bool = True,
  3006. report_activity: Callable[[int, str], None] | None = None,
  3007. quiet: bool = False,
  3008. include_tags: bool = False,
  3009. username: str | None = None,
  3010. password: str | None = None,
  3011. ) -> None:
  3012. """Initialize AbstractHttpGitClient."""
  3013. self._base_url = base_url.rstrip("/") + "/"
  3014. self._username = username
  3015. self._password = password
  3016. # Track original URL with credentials (set by from_parsedurl when credentials come from URL)
  3017. self._url_with_auth: str | None = None
  3018. self.dumb = dumb
  3019. GitClient.__init__(
  3020. self,
  3021. thin_packs=thin_packs,
  3022. report_activity=report_activity,
  3023. quiet=quiet,
  3024. include_tags=include_tags,
  3025. )
  3026. def _http_request(
  3027. self,
  3028. url: str,
  3029. headers: dict[str, str] | None = None,
  3030. data: bytes | Iterator[bytes] | None = None,
  3031. raise_for_status: bool = True,
  3032. ) -> tuple["HTTPResponse", Callable[[int], bytes]]:
  3033. """Perform HTTP request.
  3034. Args:
  3035. url: Request URL.
  3036. headers: Optional custom headers to override defaults.
  3037. data: Request data.
  3038. raise_for_status: Whether to raise an exception for HTTP errors.
  3039. Returns:
  3040. Tuple (response, read), where response is an urllib3
  3041. response object with additional content_type and
  3042. redirect_location properties, and read is a consumable read
  3043. method for the response data.
  3044. Raises:
  3045. GitProtocolError
  3046. """
  3047. raise NotImplementedError(self._http_request)
  3048. def _discover_references(
  3049. self,
  3050. service: bytes,
  3051. base_url: str,
  3052. protocol_version: int | None = None,
  3053. ref_prefix: Sequence[Ref] | None = None,
  3054. ) -> tuple[
  3055. dict[Ref, ObjectID | None],
  3056. set[bytes],
  3057. str,
  3058. dict[Ref, Ref],
  3059. dict[Ref, ObjectID],
  3060. ]:
  3061. if (
  3062. protocol_version is not None
  3063. and protocol_version not in GIT_PROTOCOL_VERSIONS
  3064. ):
  3065. raise ValueError(f"unknown Git protocol version {protocol_version}")
  3066. assert base_url[-1] == "/"
  3067. tail = "info/refs"
  3068. headers = {"Accept": "*/*"}
  3069. if self.dumb is not True:
  3070. tail += "?service={}".format(service.decode("ascii"))
  3071. # Enable protocol v2 only when fetching, not when pushing.
  3072. # Git does not yet implement push over protocol v2, and as of
  3073. # git version 2.37.3 git-http-backend's behaviour is erratic if
  3074. # we try: It responds with a Git-protocol-v1-style ref listing
  3075. # which lacks the "001f# service=git-receive-pack" marker.
  3076. if service == b"git-upload-pack":
  3077. if protocol_version is None:
  3078. self.protocol_version = DEFAULT_GIT_PROTOCOL_VERSION_FETCH
  3079. else:
  3080. self.protocol_version = protocol_version
  3081. if self.protocol_version == 2:
  3082. headers["Git-Protocol"] = "version=2"
  3083. else:
  3084. self.protocol_version = DEFAULT_GIT_PROTOCOL_VERSION_SEND
  3085. url = urljoin(base_url, tail)
  3086. resp, read = self._http_request(url, headers)
  3087. if resp.redirect_location:
  3088. # Something changed (redirect!), so let's update the base URL
  3089. if not resp.redirect_location.endswith(tail):
  3090. raise GitProtocolError(
  3091. f"Redirected from URL {url} to URL {resp.redirect_location} without {tail}"
  3092. )
  3093. base_url = urljoin(url, resp.redirect_location[: -len(tail)])
  3094. try:
  3095. self.dumb = resp.content_type is None or not resp.content_type.startswith(
  3096. "application/x-git-"
  3097. )
  3098. if not self.dumb:
  3099. def begin_protocol_v2(
  3100. proto: Protocol,
  3101. ) -> tuple[set[bytes], Any, Callable[[int], bytes], Protocol]:
  3102. nonlocal ref_prefix
  3103. server_capabilities = read_server_capabilities(proto.read_pkt_seq())
  3104. if ref_prefix is None:
  3105. ref_prefix = DEFAULT_REF_PREFIX
  3106. pkts = [
  3107. b"symrefs",
  3108. b"peel",
  3109. ]
  3110. for prefix in ref_prefix:
  3111. pkts.append(b"ref-prefix " + prefix)
  3112. body = b"".join(
  3113. [pkt_line(b"command=ls-refs\n"), b"0001", pkt_seq(*pkts)]
  3114. )
  3115. resp, read = self._smart_request(
  3116. service.decode("ascii"), base_url, body
  3117. )
  3118. proto = Protocol(read, lambda data: None)
  3119. return server_capabilities, resp, read, proto
  3120. proto = Protocol(read, lambda data: None)
  3121. server_protocol_version = negotiate_protocol_version(proto)
  3122. if server_protocol_version not in GIT_PROTOCOL_VERSIONS:
  3123. raise ValueError(
  3124. f"unknown Git protocol version {server_protocol_version} used by server"
  3125. )
  3126. if protocol_version and server_protocol_version > protocol_version:
  3127. raise ValueError(
  3128. f"bad Git protocol version {server_protocol_version} used by server"
  3129. )
  3130. self.protocol_version = server_protocol_version
  3131. if self.protocol_version == 2:
  3132. server_capabilities, resp, read, proto = begin_protocol_v2(proto)
  3133. (refs, symrefs, peeled) = read_pkt_refs_v2(proto.read_pkt_seq())
  3134. return refs, server_capabilities, base_url, symrefs, peeled
  3135. else:
  3136. try:
  3137. [pkt] = list(proto.read_pkt_seq())
  3138. except ValueError as exc:
  3139. raise GitProtocolError(
  3140. "unexpected number of packets received"
  3141. ) from exc
  3142. if pkt.rstrip(b"\n") != (b"# service=" + service):
  3143. raise GitProtocolError(
  3144. f"unexpected first line {pkt!r} from smart server"
  3145. )
  3146. # Github sends "version 2" after sending the service name.
  3147. # Try to negotiate protocol version 2 again.
  3148. server_protocol_version = negotiate_protocol_version(proto)
  3149. if server_protocol_version not in GIT_PROTOCOL_VERSIONS:
  3150. raise ValueError(
  3151. f"unknown Git protocol version {server_protocol_version} used by server"
  3152. )
  3153. if protocol_version and server_protocol_version > protocol_version:
  3154. raise ValueError(
  3155. f"bad Git protocol version {server_protocol_version} used by server"
  3156. )
  3157. self.protocol_version = server_protocol_version
  3158. if self.protocol_version == 2:
  3159. server_capabilities, resp, read, proto = begin_protocol_v2(
  3160. proto
  3161. )
  3162. (refs, symrefs, peeled) = read_pkt_refs_v2(proto.read_pkt_seq())
  3163. else:
  3164. (
  3165. refs_v1,
  3166. server_capabilities,
  3167. ) = read_pkt_refs_v1(proto.read_pkt_seq())
  3168. # Convert v1 refs to Optional type
  3169. refs = _to_optional_dict(refs_v1)
  3170. (refs, peeled) = split_peeled_refs(refs)
  3171. (symrefs, _agent) = _extract_symrefs_and_agent(
  3172. server_capabilities
  3173. )
  3174. if ref_prefix is not None:
  3175. refs = filter_ref_prefix(refs, ref_prefix)
  3176. return refs, server_capabilities, base_url, symrefs, peeled
  3177. else:
  3178. self.protocol_version = 0 # dumb servers only support protocol v0
  3179. # Read all the response data
  3180. data = b""
  3181. while True:
  3182. chunk = read(4096)
  3183. if not chunk:
  3184. break
  3185. data += chunk
  3186. from typing import cast
  3187. info_refs = read_info_refs(BytesIO(data))
  3188. (refs, peeled) = split_peeled_refs(
  3189. cast(dict[bytes, bytes | None], info_refs)
  3190. )
  3191. if ref_prefix is not None:
  3192. refs = filter_ref_prefix(refs, ref_prefix)
  3193. return refs, set(), base_url, {}, peeled
  3194. finally:
  3195. resp.close()
  3196. def _smart_request(
  3197. self, service: str, url: str, data: bytes | Iterator[bytes]
  3198. ) -> tuple["HTTPResponse", Callable[[int], bytes]]:
  3199. """Send a 'smart' HTTP request.
  3200. This is a simple wrapper around _http_request that sets
  3201. a couple of extra headers.
  3202. """
  3203. assert url[-1] == "/"
  3204. url = urljoin(url, service)
  3205. result_content_type = f"application/x-{service}-result"
  3206. headers = {
  3207. "Content-Type": f"application/x-{service}-request",
  3208. "Accept": result_content_type,
  3209. }
  3210. if self.protocol_version == 2:
  3211. headers["Git-Protocol"] = "version=2"
  3212. if isinstance(data, bytes):
  3213. headers["Content-Length"] = str(len(data))
  3214. resp, read = self._http_request(url, headers, data)
  3215. if (
  3216. not resp.content_type
  3217. or resp.content_type.split(";")[0] != result_content_type
  3218. ):
  3219. raise GitProtocolError(
  3220. f"Invalid content-type from server: {resp.content_type}"
  3221. )
  3222. return resp, read
  3223. def send_pack(
  3224. self,
  3225. path: str | bytes,
  3226. update_refs: Callable[[dict[bytes, bytes]], dict[bytes, bytes]],
  3227. generate_pack_data: "GeneratePackDataFunc",
  3228. progress: Callable[[bytes], None] | None = None,
  3229. ) -> SendPackResult:
  3230. """Upload a pack to a remote repository.
  3231. Args:
  3232. path: Repository path (as bytestring or string)
  3233. update_refs: Function to determine changes to remote refs.
  3234. Receives dict with existing remote refs, returns dict with
  3235. changed refs (name -> sha, where sha=ZERO_SHA for deletions)
  3236. generate_pack_data: Function that can return a tuple
  3237. with number of elements and pack data to upload.
  3238. progress: Optional progress function
  3239. Returns:
  3240. SendPackResult
  3241. Raises:
  3242. SendPackError: if server rejects the pack data
  3243. """
  3244. url = self._get_url(path)
  3245. old_refs, server_capabilities, url, _symrefs, _peeled = (
  3246. self._discover_references(b"git-receive-pack", url)
  3247. )
  3248. (
  3249. negotiated_capabilities,
  3250. agent,
  3251. ) = self._negotiate_receive_pack_capabilities(server_capabilities)
  3252. negotiated_capabilities.add(capability_agent())
  3253. if CAPABILITY_REPORT_STATUS in negotiated_capabilities:
  3254. self._report_status_parser = ReportStatusParser()
  3255. # Assert that old_refs has no None values
  3256. assert all(v is not None for v in old_refs.values()), (
  3257. "old_refs should not contain None values"
  3258. )
  3259. old_refs_typed: dict[bytes, bytes] = old_refs # type: ignore[assignment]
  3260. new_refs = update_refs(dict(old_refs_typed))
  3261. if new_refs is None:
  3262. # Determine wants function is aborting the push.
  3263. # Convert to Optional type for SendPackResult
  3264. old_refs_optional: dict[bytes, bytes | None] = old_refs
  3265. return SendPackResult(old_refs_optional, agent=agent, ref_status={})
  3266. if set(new_refs.items()).issubset(set(old_refs_typed.items())):
  3267. # Convert to Optional type for SendPackResult
  3268. return SendPackResult(
  3269. _to_optional_dict(new_refs), agent=agent, ref_status={}
  3270. )
  3271. if self.dumb:
  3272. raise NotImplementedError(self.fetch_pack)
  3273. def body_generator() -> Iterator[bytes]:
  3274. header_handler = _v1ReceivePackHeader(
  3275. list(negotiated_capabilities), old_refs_typed, new_refs
  3276. )
  3277. for pkt in header_handler:
  3278. yield pkt_line(pkt)
  3279. pack_data_count, pack_data = generate_pack_data(
  3280. header_handler.have,
  3281. header_handler.want,
  3282. ofs_delta=(CAPABILITY_OFS_DELTA in negotiated_capabilities),
  3283. progress=progress,
  3284. )
  3285. if self._should_send_pack(new_refs):
  3286. yield from PackChunkGenerator(pack_data_count, pack_data)
  3287. resp, read = self._smart_request("git-receive-pack", url, data=body_generator())
  3288. try:
  3289. resp_proto = Protocol(read, lambda data: None)
  3290. ref_status = self._handle_receive_pack_tail(
  3291. resp_proto, negotiated_capabilities, progress
  3292. )
  3293. # Convert to Optional type for SendPackResult
  3294. return SendPackResult(
  3295. _to_optional_dict(new_refs), agent=agent, ref_status=ref_status
  3296. )
  3297. finally:
  3298. resp.close()
  3299. def fetch_pack(
  3300. self,
  3301. path: str | bytes,
  3302. determine_wants: "DetermineWantsFunc",
  3303. graph_walker: GraphWalker,
  3304. pack_data: Callable[[bytes], int],
  3305. progress: Callable[[bytes], None] | None = None,
  3306. depth: int | None = None,
  3307. ref_prefix: Sequence[Ref] | None = None,
  3308. filter_spec: bytes | None = None,
  3309. protocol_version: int | None = None,
  3310. shallow_since: str | None = None,
  3311. shallow_exclude: list[str] | None = None,
  3312. ) -> FetchPackResult:
  3313. """Retrieve a pack from a git smart server.
  3314. Args:
  3315. path: Path to fetch from
  3316. determine_wants: Callback that returns list of commits to fetch
  3317. graph_walker: Object with next() and ack().
  3318. pack_data: Callback called for each bit of data in the pack
  3319. progress: Callback for progress reports (strings)
  3320. depth: Depth for request
  3321. ref_prefix: List of prefixes of desired references, as a list of
  3322. bytestrings. Filtering is done by the server if supported, and
  3323. client side otherwise.
  3324. filter_spec: A git-rev-list-style object filter spec, as bytestring.
  3325. Only used if the server supports the Git protocol-v2 'filter'
  3326. feature, and ignored otherwise.
  3327. protocol_version: Desired Git protocol version. By default the highest
  3328. mutually supported protocol version will be used.
  3329. shallow_since: Deepen the history to include commits after this date
  3330. shallow_exclude: Deepen the history to exclude commits reachable from these refs
  3331. Returns:
  3332. FetchPackResult object
  3333. """
  3334. url = self._get_url(path)
  3335. refs, server_capabilities, url, symrefs, _peeled = self._discover_references(
  3336. b"git-upload-pack",
  3337. url,
  3338. protocol_version=protocol_version,
  3339. ref_prefix=ref_prefix,
  3340. )
  3341. (
  3342. negotiated_capabilities,
  3343. capa_symrefs,
  3344. agent,
  3345. ) = self._negotiate_upload_pack_capabilities(server_capabilities)
  3346. if not symrefs and capa_symrefs:
  3347. symrefs = capa_symrefs
  3348. # Filter out None values from refs for determine_wants
  3349. refs_filtered = {k: v for k, v in refs.items() if v is not None}
  3350. if depth is not None:
  3351. wants = determine_wants(refs_filtered, depth=depth)
  3352. else:
  3353. wants = determine_wants(refs_filtered)
  3354. if wants is not None:
  3355. wants = [cid for cid in wants if cid != ZERO_SHA]
  3356. if not wants and not self.dumb:
  3357. return FetchPackResult(refs, symrefs, agent)
  3358. elif self.dumb:
  3359. # Use dumb HTTP protocol
  3360. from .dumb import DumbRemoteHTTPRepo
  3361. # Pass http_request function
  3362. dumb_repo = DumbRemoteHTTPRepo(
  3363. url, functools.partial(self._http_request, raise_for_status=False)
  3364. )
  3365. # Fetch pack data from dumb remote
  3366. pack_data_list = list(
  3367. dumb_repo.fetch_pack_data(
  3368. lambda refs, depth: wants,
  3369. graph_walker,
  3370. progress=progress,
  3371. depth=depth,
  3372. )
  3373. )
  3374. symrefs[b"HEAD"] = dumb_repo.get_head()
  3375. # Write pack data
  3376. if pack_data_list:
  3377. from .pack import write_pack_data
  3378. # Wrap pack_data to match expected signature
  3379. def write_fn(data: bytes) -> None:
  3380. pack_data(data)
  3381. # Write pack data directly using the unpacked objects
  3382. write_pack_data(
  3383. write_fn,
  3384. iter(pack_data_list),
  3385. num_records=len(pack_data_list),
  3386. progress=progress,
  3387. )
  3388. return FetchPackResult(refs, symrefs, agent)
  3389. req_data = BytesIO()
  3390. req_proto = Protocol(None, req_data.write) # type: ignore
  3391. (new_shallow, new_unshallow) = _handle_upload_pack_head(
  3392. req_proto,
  3393. negotiated_capabilities,
  3394. graph_walker,
  3395. wants,
  3396. can_read=None,
  3397. depth=depth,
  3398. protocol_version=self.protocol_version,
  3399. shallow_since=shallow_since,
  3400. shallow_exclude=shallow_exclude,
  3401. )
  3402. if self.protocol_version == 2:
  3403. data = pkt_line(b"command=fetch\n") + b"0001"
  3404. if CAPABILITY_THIN_PACK in self._fetch_capabilities:
  3405. data += pkt_line(b"thin-pack\n")
  3406. if (
  3407. find_capability(
  3408. negotiated_capabilities, CAPABILITY_FETCH, CAPABILITY_FILTER
  3409. )
  3410. and filter_spec
  3411. ):
  3412. data += pkt_line(b"filter %s\n" % filter_spec)
  3413. elif filter_spec:
  3414. self._warn_filter_objects()
  3415. data += req_data.getvalue()
  3416. else:
  3417. if filter_spec:
  3418. self._warn_filter_objects()
  3419. data = req_data.getvalue()
  3420. resp, read = self._smart_request("git-upload-pack", url, data)
  3421. try:
  3422. resp_proto = Protocol(read, None) # type: ignore
  3423. if new_shallow is None and new_unshallow is None:
  3424. (new_shallow, new_unshallow) = _read_shallow_updates(
  3425. resp_proto.read_pkt_seq()
  3426. )
  3427. _handle_upload_pack_tail(
  3428. resp_proto,
  3429. negotiated_capabilities,
  3430. graph_walker,
  3431. pack_data,
  3432. progress,
  3433. protocol_version=self.protocol_version,
  3434. )
  3435. return FetchPackResult(refs, symrefs, agent, new_shallow, new_unshallow)
  3436. finally:
  3437. resp.close()
  3438. def get_refs(
  3439. self,
  3440. path: str | bytes,
  3441. protocol_version: int | None = None,
  3442. ref_prefix: Sequence[Ref] | None = None,
  3443. ) -> LsRemoteResult:
  3444. """Retrieve the current refs from a git smart server."""
  3445. url = self._get_url(path)
  3446. refs, _, _, symrefs, peeled = self._discover_references(
  3447. b"git-upload-pack",
  3448. url,
  3449. protocol_version=protocol_version,
  3450. ref_prefix=ref_prefix,
  3451. )
  3452. for refname, refvalue in peeled.items():
  3453. refs[refname + PEELED_TAG_SUFFIX] = refvalue
  3454. return LsRemoteResult(refs, symrefs)
  3455. def get_url(self, path: str) -> str:
  3456. """Get the HTTP URL for a path."""
  3457. url = self._get_url(path).rstrip("/")
  3458. # Include credentials in the URL only if they came from a URL (not passed explicitly)
  3459. # This preserves credentials that were in the original URL for git config storage
  3460. if self._url_with_auth is not None:
  3461. from urllib.parse import quote, urlparse, urlunparse
  3462. assert self._username is not None
  3463. parsed = urlparse(url)
  3464. # Construct netloc with credentials
  3465. if self._password is not None:
  3466. netloc = f"{quote(self._username, safe='')}:{quote(self._password, safe='')}@{parsed.hostname}"
  3467. else:
  3468. netloc = f"{quote(self._username, safe='')}@{parsed.hostname}"
  3469. if parsed.port:
  3470. netloc += f":{parsed.port}"
  3471. # Reconstruct URL with credentials
  3472. url = urlunparse(
  3473. (
  3474. parsed.scheme,
  3475. netloc,
  3476. parsed.path,
  3477. parsed.params,
  3478. parsed.query,
  3479. parsed.fragment,
  3480. )
  3481. )
  3482. return url
  3483. def _get_url(self, path: str | bytes) -> str:
  3484. path_str = path if isinstance(path, str) else path.decode("utf-8")
  3485. return urljoin(self._base_url, path_str).rstrip("/") + "/"
  3486. @classmethod
  3487. def from_parsedurl(
  3488. cls,
  3489. parsedurl: ParseResult,
  3490. thin_packs: bool = True,
  3491. report_activity: Callable[[int, str], None] | None = None,
  3492. quiet: bool = False,
  3493. include_tags: bool = False,
  3494. dumb: bool = False,
  3495. username: str | None = None,
  3496. password: str | None = None,
  3497. config: Config | None = None,
  3498. pool_manager: Optional["urllib3.PoolManager"] = None,
  3499. ) -> "AbstractHttpGitClient":
  3500. """Create an AbstractHttpGitClient from a parsed URL.
  3501. Args:
  3502. parsedurl: Result of urlparse()
  3503. thin_packs: Whether or not thin packs should be retrieved
  3504. report_activity: Optional callback for reporting transport activity
  3505. quiet: Whether to suppress progress output
  3506. include_tags: Whether to include tags
  3507. dumb: Whether to use dumb HTTP transport
  3508. username: Optional username for authentication
  3509. password: Optional password for authentication
  3510. config: Configuration object
  3511. pool_manager: Optional urllib3 PoolManager for HTTP(S) connections
  3512. Returns:
  3513. An AbstractHttpGitClient instance
  3514. """
  3515. # Extract credentials from URL if present
  3516. # ParseResult.username and .password are URL-encoded, need to unquote them
  3517. from urllib.parse import unquote
  3518. url_username = unquote(parsedurl.username) if parsedurl.username else None
  3519. url_password = unquote(parsedurl.password) if parsedurl.password else None
  3520. # Explicit parameters take precedence over URL credentials
  3521. final_username = username if username is not None else url_username
  3522. final_password = password if password is not None else url_password
  3523. # Remove credentials from URL for base_url
  3524. hostname = parsedurl.hostname or ""
  3525. base_parsed = parsedurl._replace(netloc=hostname)
  3526. if parsedurl.port:
  3527. base_parsed = base_parsed._replace(netloc=f"{hostname}:{parsedurl.port}")
  3528. # Pass credentials to constructor if it's a subclass that supports them
  3529. if issubclass(cls, Urllib3HttpGitClient):
  3530. client: AbstractHttpGitClient = cls(
  3531. urlunparse(base_parsed),
  3532. dumb=dumb,
  3533. thin_packs=thin_packs,
  3534. report_activity=report_activity,
  3535. quiet=quiet,
  3536. include_tags=include_tags,
  3537. username=final_username,
  3538. password=final_password,
  3539. config=config,
  3540. pool_manager=pool_manager,
  3541. )
  3542. else:
  3543. # Base class now supports credentials in constructor
  3544. client = cls(
  3545. urlunparse(base_parsed),
  3546. dumb=dumb,
  3547. thin_packs=thin_packs,
  3548. report_activity=report_activity,
  3549. quiet=quiet,
  3550. include_tags=include_tags,
  3551. username=final_username,
  3552. password=final_password,
  3553. )
  3554. # Mark that credentials came from URL (not passed explicitly) if URL had credentials
  3555. if url_username is not None or url_password is not None:
  3556. client._url_with_auth = urlunparse(parsedurl)
  3557. return client
  3558. def __repr__(self) -> str:
  3559. """Return string representation of this client."""
  3560. return f"{type(self).__name__}({self._base_url!r}, dumb={self.dumb!r})"
  3561. def _wrap_urllib3_exceptions(
  3562. func: Callable[..., bytes],
  3563. ) -> Callable[..., bytes]:
  3564. from urllib3.exceptions import ProtocolError
  3565. def wrapper(*args: object, **kwargs: object) -> bytes:
  3566. try:
  3567. return func(*args, **kwargs)
  3568. except ProtocolError as error:
  3569. raise GitProtocolError(str(error)) from error
  3570. return wrapper
  3571. class Urllib3HttpGitClient(AbstractHttpGitClient):
  3572. """Git client that uses urllib3 for HTTP(S) connections."""
  3573. def __init__(
  3574. self,
  3575. base_url: str,
  3576. dumb: bool | None = None,
  3577. pool_manager: Optional["urllib3.PoolManager"] = None,
  3578. config: Config | None = None,
  3579. username: str | None = None,
  3580. password: str | None = None,
  3581. timeout: float | None = None,
  3582. extra_headers: dict[str, str] | None = None,
  3583. thin_packs: bool = True,
  3584. report_activity: Callable[[int, str], None] | None = None,
  3585. quiet: bool = False,
  3586. include_tags: bool = False,
  3587. ) -> None:
  3588. """Initialize Urllib3HttpGitClient."""
  3589. self._timeout = timeout
  3590. self._extra_headers = extra_headers or {}
  3591. if pool_manager is None:
  3592. self.pool_manager = default_urllib3_manager(
  3593. config, base_url=base_url, timeout=timeout
  3594. )
  3595. else:
  3596. self.pool_manager = pool_manager
  3597. if username is not None:
  3598. # No escaping needed: ":" is not allowed in username:
  3599. # https://tools.ietf.org/html/rfc2617#section-2
  3600. credentials = f"{username}:{password or ''}"
  3601. import urllib3.util
  3602. basic_auth = urllib3.util.make_headers(basic_auth=credentials)
  3603. self.pool_manager.headers.update(basic_auth) # type: ignore
  3604. self.config = config
  3605. super().__init__(
  3606. base_url=base_url,
  3607. dumb=dumb if dumb is not None else False,
  3608. thin_packs=thin_packs,
  3609. report_activity=report_activity,
  3610. quiet=quiet,
  3611. include_tags=include_tags,
  3612. username=username,
  3613. password=password,
  3614. )
  3615. def _get_url(self, path: str | bytes) -> str:
  3616. if not isinstance(path, str):
  3617. # urllib3.util.url._encode_invalid_chars() converts the path back
  3618. # to bytes using the utf-8 codec.
  3619. path = path.decode("utf-8")
  3620. return urljoin(self._base_url, path).rstrip("/") + "/"
  3621. def _http_request(
  3622. self,
  3623. url: str,
  3624. headers: dict[str, str] | None = None,
  3625. data: bytes | Iterator[bytes] | None = None,
  3626. raise_for_status: bool = True,
  3627. ) -> tuple["HTTPResponse", Callable[[int], bytes]]:
  3628. import urllib3.exceptions
  3629. req_headers = dict(self.pool_manager.headers)
  3630. if headers is not None:
  3631. req_headers.update(headers)
  3632. req_headers["Pragma"] = "no-cache"
  3633. try:
  3634. request_kwargs = {
  3635. "headers": req_headers,
  3636. "preload_content": False,
  3637. }
  3638. if self._timeout is not None:
  3639. request_kwargs["timeout"] = self._timeout
  3640. if data is None:
  3641. resp = self.pool_manager.request("GET", url, **request_kwargs) # type: ignore[arg-type]
  3642. else:
  3643. request_kwargs["body"] = data
  3644. resp = self.pool_manager.request("POST", url, **request_kwargs) # type: ignore[arg-type]
  3645. except urllib3.exceptions.HTTPError as e:
  3646. raise GitProtocolError(str(e)) from e
  3647. if raise_for_status:
  3648. if resp.status == 404:
  3649. raise NotGitRepository
  3650. if resp.status == 401:
  3651. raise HTTPUnauthorized(resp.headers.get("WWW-Authenticate"), url)
  3652. if resp.status == 407:
  3653. raise HTTPProxyUnauthorized(resp.headers.get("Proxy-Authenticate"), url)
  3654. if resp.status != 200:
  3655. raise GitProtocolError(f"unexpected http resp {resp.status} for {url}")
  3656. resp.content_type = resp.headers.get("Content-Type") # type: ignore[attr-defined]
  3657. # Check if geturl() is available (urllib3 version >= 1.23)
  3658. try:
  3659. resp_url = resp.geturl()
  3660. except AttributeError:
  3661. # get_redirect_location() is available for urllib3 >= 1.1
  3662. resp.redirect_location = resp.get_redirect_location() # type: ignore[attr-defined]
  3663. else:
  3664. resp.redirect_location = resp_url if resp_url != url else "" # type: ignore[attr-defined]
  3665. return resp, _wrap_urllib3_exceptions(resp.read) # type: ignore[return-value]
  3666. HttpGitClient = Urllib3HttpGitClient
  3667. def _win32_url_to_path(parsed: ParseResult) -> str:
  3668. """Convert a file: URL to a path.
  3669. https://datatracker.ietf.org/doc/html/rfc8089
  3670. """
  3671. assert parsed.scheme == "file"
  3672. _, netloc, path, _, _, _ = parsed
  3673. if netloc == "localhost" or not netloc:
  3674. netloc = ""
  3675. elif (
  3676. netloc
  3677. and len(netloc) >= 2
  3678. and netloc[0].isalpha()
  3679. and netloc[1:2] in (":", ":/")
  3680. ):
  3681. # file://C:/foo.bar/baz or file://C://foo.bar//baz
  3682. netloc = netloc[:2]
  3683. else:
  3684. raise NotImplementedError("Non-local file URLs are not supported")
  3685. from nturl2path import url2pathname
  3686. return url2pathname(netloc + path)
  3687. def get_transport_and_path_from_url(
  3688. url: str,
  3689. config: Config | None = None,
  3690. operation: str | None = None,
  3691. thin_packs: bool = True,
  3692. report_activity: Callable[[int, str], None] | None = None,
  3693. quiet: bool = False,
  3694. include_tags: bool = False,
  3695. username: str | None = None,
  3696. password: str | None = None,
  3697. key_filename: str | None = None,
  3698. ssh_command: str | None = None,
  3699. pool_manager: Optional["urllib3.PoolManager"] = None,
  3700. ) -> tuple[GitClient, str]:
  3701. """Obtain a git client from a URL.
  3702. Args:
  3703. url: URL to open (a unicode string)
  3704. config: Optional config object
  3705. operation: Kind of operation that'll be performed; "pull" or "push"
  3706. thin_packs: Whether or not thin packs should be retrieved
  3707. report_activity: Optional callback for reporting transport activity
  3708. quiet: Whether to suppress output
  3709. include_tags: Send annotated tags when sending the objects they point to
  3710. username: Optional username for authentication
  3711. password: Optional password for authentication
  3712. key_filename: Optional SSH key file
  3713. ssh_command: Optional custom SSH command
  3714. pool_manager: Optional urllib3 PoolManager for HTTP(S) connections
  3715. Returns:
  3716. Tuple with client instance and relative path.
  3717. """
  3718. if config is not None:
  3719. url = apply_instead_of(config, url, push=(operation == "push"))
  3720. return _get_transport_and_path_from_url(
  3721. url,
  3722. config=config,
  3723. operation=operation,
  3724. thin_packs=thin_packs,
  3725. report_activity=report_activity,
  3726. quiet=quiet,
  3727. include_tags=include_tags,
  3728. username=username,
  3729. password=password,
  3730. key_filename=key_filename,
  3731. ssh_command=ssh_command,
  3732. pool_manager=pool_manager,
  3733. )
  3734. def _get_transport_and_path_from_url(
  3735. url: str,
  3736. config: Config | None,
  3737. operation: str | None,
  3738. thin_packs: bool = True,
  3739. report_activity: Callable[[int, str], None] | None = None,
  3740. quiet: bool = False,
  3741. include_tags: bool = False,
  3742. username: str | None = None,
  3743. password: str | None = None,
  3744. key_filename: str | None = None,
  3745. ssh_command: str | None = None,
  3746. pool_manager: Optional["urllib3.PoolManager"] = None,
  3747. ) -> tuple[GitClient, str]:
  3748. parsed = urlparse(url)
  3749. if parsed.scheme == "git":
  3750. return (
  3751. TCPGitClient.from_parsedurl(
  3752. parsed,
  3753. thin_packs=thin_packs,
  3754. report_activity=report_activity,
  3755. quiet=quiet,
  3756. include_tags=include_tags,
  3757. ),
  3758. parsed.path,
  3759. )
  3760. elif parsed.scheme in ("git+ssh", "ssh"):
  3761. return SSHGitClient.from_parsedurl(
  3762. parsed,
  3763. config=config,
  3764. username=username,
  3765. password=password,
  3766. thin_packs=thin_packs,
  3767. report_activity=report_activity,
  3768. quiet=quiet,
  3769. include_tags=include_tags,
  3770. ), parsed.path
  3771. elif parsed.scheme in ("http", "https"):
  3772. return (
  3773. HttpGitClient.from_parsedurl(
  3774. parsed,
  3775. config=config,
  3776. username=username,
  3777. password=password,
  3778. thin_packs=thin_packs,
  3779. report_activity=report_activity,
  3780. quiet=quiet,
  3781. include_tags=include_tags,
  3782. pool_manager=pool_manager,
  3783. ),
  3784. parsed.path,
  3785. )
  3786. elif parsed.scheme == "file":
  3787. if sys.platform == "win32" or os.name == "nt":
  3788. return default_local_git_client_cls(
  3789. thin_packs=thin_packs,
  3790. report_activity=report_activity,
  3791. quiet=quiet,
  3792. include_tags=include_tags,
  3793. ), _win32_url_to_path(parsed)
  3794. return (
  3795. default_local_git_client_cls.from_parsedurl(
  3796. parsed,
  3797. thin_packs=thin_packs,
  3798. report_activity=report_activity,
  3799. quiet=quiet,
  3800. include_tags=include_tags,
  3801. ),
  3802. parsed.path,
  3803. )
  3804. raise ValueError(f"unknown scheme '{parsed.scheme}'")
  3805. def parse_rsync_url(location: str) -> tuple[str | None, str, str]:
  3806. """Parse a rsync-style URL."""
  3807. if ":" in location and "@" not in location:
  3808. # SSH with no user@, zero or one leading slash.
  3809. (host, path) = location.split(":", 1)
  3810. user = None
  3811. elif ":" in location:
  3812. # SSH with user@host:foo.
  3813. user_host, path = location.split(":", 1)
  3814. if "@" in user_host:
  3815. user, host = user_host.rsplit("@", 1)
  3816. else:
  3817. user = None
  3818. host = user_host
  3819. else:
  3820. raise ValueError("not a valid rsync-style URL")
  3821. return (user, host, path)
  3822. def get_transport_and_path(
  3823. location: str,
  3824. config: Config | None = None,
  3825. operation: str | None = None,
  3826. thin_packs: bool = True,
  3827. report_activity: Callable[[int, str], None] | None = None,
  3828. quiet: bool = False,
  3829. include_tags: bool = False,
  3830. username: str | None = None,
  3831. password: str | None = None,
  3832. key_filename: str | None = None,
  3833. ssh_command: str | None = None,
  3834. pool_manager: Optional["urllib3.PoolManager"] = None,
  3835. ) -> tuple[GitClient, str]:
  3836. """Obtain a git client from a URL.
  3837. Args:
  3838. location: URL or path (a string)
  3839. config: Optional config object
  3840. operation: Kind of operation that'll be performed; "pull" or "push"
  3841. thin_packs: Whether or not thin packs should be retrieved
  3842. report_activity: Optional callback for reporting transport activity
  3843. quiet: Whether to suppress output
  3844. include_tags: Send annotated tags when sending the objects they point to
  3845. username: Optional username for authentication
  3846. password: Optional password for authentication
  3847. key_filename: Optional SSH key file
  3848. ssh_command: Optional custom SSH command
  3849. pool_manager: Optional urllib3 PoolManager for HTTP(S) connections
  3850. Returns:
  3851. Tuple with client instance and relative path.
  3852. """
  3853. if config is not None:
  3854. location = apply_instead_of(config, location, push=(operation == "push"))
  3855. # First, try to parse it as a URL
  3856. try:
  3857. return _get_transport_and_path_from_url(
  3858. location,
  3859. config=config,
  3860. operation=operation,
  3861. thin_packs=thin_packs,
  3862. report_activity=report_activity,
  3863. quiet=quiet,
  3864. include_tags=include_tags,
  3865. username=username,
  3866. password=password,
  3867. key_filename=key_filename,
  3868. ssh_command=ssh_command,
  3869. pool_manager=pool_manager,
  3870. )
  3871. except ValueError:
  3872. pass
  3873. if sys.platform == "win32" and location[0].isalpha() and location[1:3] == ":\\":
  3874. # Windows local path - but check if it's a bundle file first
  3875. if BundleClient._is_bundle_file(location):
  3876. return BundleClient(
  3877. thin_packs=thin_packs,
  3878. report_activity=report_activity,
  3879. quiet=quiet,
  3880. include_tags=include_tags,
  3881. ), location
  3882. return default_local_git_client_cls(
  3883. thin_packs=thin_packs,
  3884. report_activity=report_activity,
  3885. quiet=quiet,
  3886. include_tags=include_tags,
  3887. ), location
  3888. try:
  3889. (rsync_username, hostname, path) = parse_rsync_url(location)
  3890. except ValueError:
  3891. # Check if it's a bundle file before assuming it's a local path
  3892. if BundleClient._is_bundle_file(location):
  3893. return BundleClient(
  3894. thin_packs=thin_packs,
  3895. report_activity=report_activity,
  3896. quiet=quiet,
  3897. include_tags=include_tags,
  3898. ), location
  3899. # Otherwise, assume it's a local path.
  3900. return default_local_git_client_cls(
  3901. thin_packs=thin_packs,
  3902. report_activity=report_activity,
  3903. quiet=quiet,
  3904. include_tags=include_tags,
  3905. ), location
  3906. else:
  3907. return SSHGitClient(
  3908. hostname,
  3909. username=rsync_username or username,
  3910. config=config,
  3911. password=password,
  3912. key_filename=key_filename,
  3913. ssh_command=ssh_command,
  3914. thin_packs=thin_packs,
  3915. report_activity=report_activity,
  3916. quiet=quiet,
  3917. include_tags=include_tags,
  3918. ), path
  3919. DEFAULT_GIT_CREDENTIALS_PATHS = [
  3920. os.path.expanduser("~/.git-credentials"),
  3921. get_xdg_config_home_path("git", "credentials"),
  3922. ]
  3923. def get_credentials_from_store(
  3924. scheme: str,
  3925. hostname: str,
  3926. username: str | None = None,
  3927. fnames: list[str] = DEFAULT_GIT_CREDENTIALS_PATHS,
  3928. ) -> Iterator[tuple[str, str]]:
  3929. """Read credentials from a Git credential store."""
  3930. for fname in fnames:
  3931. try:
  3932. with open(fname, "rb") as f:
  3933. for line in f:
  3934. line_str = line.strip().decode("utf-8")
  3935. parsed_line = urlparse(line_str)
  3936. if (
  3937. parsed_line.scheme == scheme
  3938. and parsed_line.hostname == hostname
  3939. and (username is None or parsed_line.username == username)
  3940. ):
  3941. if parsed_line.username and parsed_line.password:
  3942. yield parsed_line.username, parsed_line.password
  3943. except FileNotFoundError:
  3944. # If the file doesn't exist, try the next one.
  3945. continue