client.py 169 KB

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