client.py 168 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749
  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. _set_origin_head(target.refs, origin.encode("utf-8"), origin_head)
  1012. head_ref = _set_default_branch(
  1013. target.refs,
  1014. origin.encode("utf-8"),
  1015. origin_head,
  1016. branch.encode("utf-8") if branch is not None else None,
  1017. ref_message,
  1018. )
  1019. # Update target head
  1020. if head_ref:
  1021. head = _set_head(target.refs, head_ref, ref_message)
  1022. else:
  1023. head = None
  1024. if checkout and head is not None:
  1025. target.get_worktree().reset_index()
  1026. except BaseException:
  1027. if target is not None:
  1028. target.close()
  1029. if mkdir:
  1030. import shutil
  1031. shutil.rmtree(target_path)
  1032. raise
  1033. return target
  1034. def fetch(
  1035. self,
  1036. path: bytes | str,
  1037. target: BaseRepo,
  1038. determine_wants: "DetermineWantsFunc | None" = None,
  1039. progress: Callable[[bytes], None] | None = None,
  1040. depth: int | None = None,
  1041. ref_prefix: Sequence[bytes] | None = None,
  1042. filter_spec: bytes | None = None,
  1043. protocol_version: int | None = None,
  1044. shallow_since: str | None = None,
  1045. shallow_exclude: list[str] | None = None,
  1046. ) -> FetchPackResult:
  1047. """Fetch into a target repository.
  1048. Args:
  1049. path: Path to fetch from (as bytestring)
  1050. target: Target repository to fetch into
  1051. determine_wants: Optional function to determine what refs to fetch.
  1052. Receives dictionary of name->sha, should return
  1053. list of shas to fetch. Defaults to all shas.
  1054. progress: Optional progress function
  1055. depth: Depth to fetch at
  1056. ref_prefix: List of prefixes of desired references, as a list of
  1057. bytestrings. Filtering is done by the server if supported, and
  1058. client side otherwise.
  1059. filter_spec: A git-rev-list-style object filter spec, as bytestring.
  1060. Only used if the server supports the Git protocol-v2 'filter'
  1061. feature, and ignored otherwise.
  1062. protocol_version: Desired Git protocol version. By default the highest
  1063. mutually supported protocol version will be used.
  1064. shallow_since: Deepen the history to include commits after this date
  1065. shallow_exclude: Deepen the history to exclude commits reachable from these refs
  1066. Returns:
  1067. Dictionary with all remote refs (not just those fetched)
  1068. """
  1069. if determine_wants is None:
  1070. determine_wants = target.object_store.determine_wants_all
  1071. if CAPABILITY_THIN_PACK in self._fetch_capabilities:
  1072. from tempfile import SpooledTemporaryFile
  1073. f: IO[bytes] = SpooledTemporaryFile(
  1074. max_size=PACK_SPOOL_FILE_MAX_SIZE,
  1075. prefix="incoming-",
  1076. dir=getattr(target.object_store, "path", None),
  1077. )
  1078. def commit() -> None:
  1079. if f.tell():
  1080. f.seek(0)
  1081. target.object_store.add_thin_pack(f.read, None, progress=progress) # type: ignore
  1082. f.close()
  1083. def abort() -> None:
  1084. f.close()
  1085. else:
  1086. f, commit, abort = target.object_store.add_pack()
  1087. try:
  1088. result = self.fetch_pack(
  1089. path,
  1090. determine_wants,
  1091. target.get_graph_walker(),
  1092. f.write,
  1093. progress=progress,
  1094. depth=depth,
  1095. ref_prefix=ref_prefix,
  1096. filter_spec=filter_spec,
  1097. protocol_version=protocol_version,
  1098. shallow_since=shallow_since,
  1099. shallow_exclude=shallow_exclude,
  1100. )
  1101. # Fix object format if needed
  1102. if (
  1103. result.object_format
  1104. and result.object_format != target.object_format.name
  1105. ):
  1106. # Change the target repo's format if it's empty
  1107. target._change_object_format(result.object_format)
  1108. except BaseException:
  1109. abort()
  1110. raise
  1111. else:
  1112. commit()
  1113. target.update_shallow(result.new_shallow, result.new_unshallow)
  1114. return result
  1115. def fetch_pack(
  1116. self,
  1117. path: bytes | str,
  1118. determine_wants: "DetermineWantsFunc",
  1119. graph_walker: GraphWalker,
  1120. pack_data: Callable[[bytes], int],
  1121. *,
  1122. progress: Callable[[bytes], None] | None = None,
  1123. depth: int | None = None,
  1124. ref_prefix: Sequence[bytes] | None = None,
  1125. filter_spec: bytes | None = None,
  1126. protocol_version: int | None = None,
  1127. shallow_since: str | None = None,
  1128. shallow_exclude: list[str] | None = None,
  1129. ) -> FetchPackResult:
  1130. """Retrieve a pack from a git smart server.
  1131. Args:
  1132. path: Remote path to fetch from
  1133. determine_wants: Function determine what refs
  1134. to fetch. Receives dictionary of name->sha, should return
  1135. list of shas to fetch.
  1136. graph_walker: Object with next() and ack().
  1137. pack_data: Callback called for each bit of data in the pack
  1138. progress: Callback for progress reports (strings)
  1139. depth: Shallow fetch depth
  1140. ref_prefix: List of prefixes of desired references, as a list of
  1141. bytestrings. Filtering is done by the server if supported, and
  1142. client side otherwise.
  1143. filter_spec: A git-rev-list-style object filter spec, as bytestring.
  1144. Only used if the server supports the Git protocol-v2 'filter'
  1145. feature, and ignored otherwise.
  1146. protocol_version: Desired Git protocol version. By default the highest
  1147. mutually supported protocol version will be used.
  1148. shallow_since: Deepen the history to include commits after this date
  1149. shallow_exclude: Deepen the history to exclude commits reachable from these refs
  1150. Returns:
  1151. FetchPackResult object
  1152. """
  1153. raise NotImplementedError(self.fetch_pack)
  1154. def get_refs(
  1155. self,
  1156. path: bytes,
  1157. protocol_version: int | None = None,
  1158. ref_prefix: Sequence[bytes] | None = None,
  1159. ) -> LsRemoteResult:
  1160. """Retrieve the current refs from a git smart server.
  1161. Args:
  1162. path: Path to the repo to fetch from. (as bytestring)
  1163. protocol_version: Desired Git protocol version.
  1164. ref_prefix: Prefix filter for refs.
  1165. Returns:
  1166. LsRemoteResult object with refs and symrefs
  1167. """
  1168. raise NotImplementedError(self.get_refs)
  1169. @staticmethod
  1170. def _should_send_pack(new_refs: Mapping[Ref, ObjectID]) -> bool:
  1171. # The packfile MUST NOT be sent if the only command used is delete.
  1172. return any(sha != ZERO_SHA for sha in new_refs.values())
  1173. def _negotiate_receive_pack_capabilities(
  1174. self, server_capabilities: set[bytes]
  1175. ) -> tuple[set[bytes], bytes | None]:
  1176. negotiated_capabilities = self._send_capabilities & server_capabilities
  1177. (_symrefs, agent) = _extract_symrefs_and_agent(server_capabilities)
  1178. (extract_capability_names(server_capabilities) - KNOWN_RECEIVE_CAPABILITIES)
  1179. # TODO(jelmer): warn about unknown capabilities
  1180. return (negotiated_capabilities, agent)
  1181. def _handle_receive_pack_tail(
  1182. self,
  1183. proto: Protocol,
  1184. capabilities: Set[bytes],
  1185. progress: Callable[[bytes], None] | None = None,
  1186. ) -> dict[bytes, str | None] | None:
  1187. """Handle the tail of a 'git-receive-pack' request.
  1188. Args:
  1189. proto: Protocol object to read from
  1190. capabilities: List of negotiated capabilities
  1191. progress: Optional progress reporting function
  1192. Returns:
  1193. dict mapping ref name to:
  1194. error message if the ref failed to update
  1195. None if it was updated successfully
  1196. """
  1197. if CAPABILITY_SIDE_BAND_64K in capabilities or self.protocol_version == 2:
  1198. if progress is None:
  1199. def progress(x: bytes) -> None:
  1200. pass
  1201. if CAPABILITY_REPORT_STATUS in capabilities:
  1202. assert self._report_status_parser is not None
  1203. pktline_parser = PktLineParser(self._report_status_parser.handle_packet)
  1204. for chan, data in _read_side_band64k_data(proto.read_pkt_seq()):
  1205. if chan == SIDE_BAND_CHANNEL_DATA:
  1206. if CAPABILITY_REPORT_STATUS in capabilities:
  1207. pktline_parser.parse(data)
  1208. elif chan == SIDE_BAND_CHANNEL_PROGRESS:
  1209. progress(data)
  1210. else:
  1211. raise AssertionError(f"Invalid sideband channel {chan}")
  1212. else:
  1213. if CAPABILITY_REPORT_STATUS in capabilities:
  1214. assert self._report_status_parser
  1215. for pkt in proto.read_pkt_seq():
  1216. self._report_status_parser.handle_packet(pkt)
  1217. if self._report_status_parser is not None:
  1218. return dict(self._report_status_parser.check())
  1219. return None
  1220. def _negotiate_upload_pack_capabilities(
  1221. self, server_capabilities: set[bytes]
  1222. ) -> tuple[set[bytes], dict[Ref, Ref], bytes | None]:
  1223. (extract_capability_names(server_capabilities) - KNOWN_UPLOAD_CAPABILITIES)
  1224. # TODO(jelmer): warn about unknown capabilities
  1225. fetch_capa = None
  1226. for capability in server_capabilities:
  1227. k, v = parse_capability(capability)
  1228. if self.protocol_version == 2 and k == CAPABILITY_FETCH:
  1229. fetch_capa = CAPABILITY_FETCH
  1230. fetch_features = []
  1231. assert v is not None
  1232. v_list = v.strip().split(b" ")
  1233. if b"shallow" in v_list:
  1234. fetch_features.append(CAPABILITY_SHALLOW)
  1235. if b"filter" in v_list:
  1236. fetch_features.append(CAPABILITY_FILTER)
  1237. for i in range(len(fetch_features)):
  1238. if i == 0:
  1239. fetch_capa += b"="
  1240. else:
  1241. fetch_capa += b" "
  1242. fetch_capa += fetch_features[i]
  1243. (symrefs, agent) = _extract_symrefs_and_agent(server_capabilities)
  1244. negotiated_capabilities = self._fetch_capabilities & server_capabilities
  1245. if fetch_capa:
  1246. negotiated_capabilities.add(fetch_capa)
  1247. return (negotiated_capabilities, symrefs, agent)
  1248. def archive(
  1249. self,
  1250. path: bytes,
  1251. committish: bytes,
  1252. write_data: Callable[[bytes], None],
  1253. progress: Callable[[bytes], None] | None = None,
  1254. write_error: Callable[[bytes], None] | None = None,
  1255. format: bytes | None = None,
  1256. subdirs: Sequence[bytes] | None = None,
  1257. prefix: bytes | None = None,
  1258. ) -> None:
  1259. """Retrieve an archive of the specified tree."""
  1260. raise NotImplementedError(self.archive)
  1261. @staticmethod
  1262. def _warn_filter_objects() -> None:
  1263. import warnings
  1264. warnings.warn(
  1265. "object filtering not recognized by server, ignoring",
  1266. UserWarning,
  1267. )
  1268. def check_wants(wants: Set[bytes], refs: Mapping[bytes, bytes]) -> None:
  1269. """Check that a set of wants is valid.
  1270. Args:
  1271. wants: Set of object SHAs to fetch
  1272. refs: Refs dictionary to check against
  1273. """
  1274. missing = set(wants) - {
  1275. v for (k, v) in refs.items() if not k.endswith(PEELED_TAG_SUFFIX)
  1276. }
  1277. if missing:
  1278. raise InvalidWants(missing)
  1279. def _remote_error_from_stderr(stderr: IO[bytes] | None) -> Exception:
  1280. if stderr is None:
  1281. return HangupException()
  1282. lines = [line.rstrip(b"\n") for line in stderr.readlines()]
  1283. for line in lines:
  1284. if line.startswith(b"ERROR: "):
  1285. return GitProtocolError(line[len(b"ERROR: ") :].decode("utf-8", "replace"))
  1286. return HangupException(lines)
  1287. class TraditionalGitClient(GitClient):
  1288. """Traditional Git client."""
  1289. DEFAULT_ENCODING = "utf-8"
  1290. def __init__(
  1291. self,
  1292. path_encoding: str = DEFAULT_ENCODING,
  1293. thin_packs: bool = True,
  1294. report_activity: Callable[[int, str], None] | None = None,
  1295. quiet: bool = False,
  1296. include_tags: bool = False,
  1297. ) -> None:
  1298. """Initialize a TraditionalGitClient.
  1299. Args:
  1300. path_encoding: Encoding for paths (default: utf-8)
  1301. thin_packs: Whether or not thin packs should be retrieved
  1302. report_activity: Optional callback for reporting transport activity
  1303. quiet: Whether to suppress progress output
  1304. include_tags: Whether to include tags
  1305. """
  1306. self._remote_path_encoding = path_encoding
  1307. super().__init__(
  1308. thin_packs=thin_packs,
  1309. report_activity=report_activity,
  1310. quiet=quiet,
  1311. include_tags=include_tags,
  1312. )
  1313. def _connect(
  1314. self,
  1315. cmd: bytes,
  1316. path: str | bytes,
  1317. protocol_version: int | None = None,
  1318. ) -> tuple[Protocol, Callable[[], bool], IO[bytes] | None]:
  1319. """Create a connection to the server.
  1320. This method is abstract - concrete implementations should
  1321. implement their own variant which connects to the server and
  1322. returns an initialized Protocol object with the service ready
  1323. for use and a can_read function which may be used to see if
  1324. reads would block.
  1325. Args:
  1326. cmd: The git service name to which we should connect.
  1327. path: The path we should pass to the service. (as bytestirng)
  1328. protocol_version: Desired Git protocol version. By default the highest
  1329. mutually supported protocol version will be used.
  1330. """
  1331. raise NotImplementedError
  1332. def send_pack(
  1333. self,
  1334. path: bytes,
  1335. update_refs: Callable[[dict[Ref, ObjectID]], dict[Ref, ObjectID]],
  1336. generate_pack_data: "GeneratePackDataFunc",
  1337. progress: Callable[[bytes], None] | None = None,
  1338. ) -> SendPackResult:
  1339. """Upload a pack to a remote repository.
  1340. Args:
  1341. path: Repository path (as bytestring)
  1342. update_refs: Function to determine changes to remote refs.
  1343. Receive dict with existing remote refs, returns dict with
  1344. changed refs (name -> sha, where sha=ZERO_SHA for deletions)
  1345. generate_pack_data: Function that can return a tuple with
  1346. number of objects and pack data to upload.
  1347. progress: Optional callback called with progress updates
  1348. Returns:
  1349. SendPackResult
  1350. Raises:
  1351. SendPackError: if server rejects the pack data
  1352. """
  1353. self.protocol_version = DEFAULT_GIT_PROTOCOL_VERSION_SEND
  1354. proto, _unused_can_read, stderr = self._connect(b"receive-pack", path)
  1355. with proto:
  1356. try:
  1357. old_refs, server_capabilities = read_pkt_refs_v1(proto.read_pkt_seq())
  1358. except HangupException as exc:
  1359. raise _remote_error_from_stderr(stderr) from exc
  1360. (
  1361. negotiated_capabilities,
  1362. agent,
  1363. ) = self._negotiate_receive_pack_capabilities(server_capabilities)
  1364. if CAPABILITY_REPORT_STATUS in negotiated_capabilities:
  1365. self._report_status_parser = ReportStatusParser()
  1366. report_status_parser = self._report_status_parser
  1367. try:
  1368. new_refs = orig_new_refs = update_refs(old_refs)
  1369. except BaseException:
  1370. proto.write_pkt_line(None)
  1371. raise
  1372. if set(new_refs.items()).issubset(set(old_refs.items())):
  1373. proto.write_pkt_line(None)
  1374. # Convert new_refs to match SendPackResult expected type
  1375. return SendPackResult(
  1376. _to_optional_dict(new_refs), agent=agent, ref_status={}
  1377. )
  1378. if CAPABILITY_DELETE_REFS not in server_capabilities:
  1379. # Server does not support deletions. Fail later.
  1380. new_refs = dict(orig_new_refs)
  1381. for ref, sha in orig_new_refs.items():
  1382. if sha == ZERO_SHA:
  1383. if CAPABILITY_REPORT_STATUS in negotiated_capabilities:
  1384. assert report_status_parser is not None
  1385. report_status_parser._ref_statuses.append(
  1386. b"ng " + ref + b" remote does not support deleting refs"
  1387. )
  1388. del new_refs[ref]
  1389. if new_refs is None:
  1390. proto.write_pkt_line(None)
  1391. return SendPackResult(old_refs, agent=agent, ref_status={})
  1392. if len(new_refs) == 0 and orig_new_refs:
  1393. # NOOP - Original new refs filtered out by policy
  1394. proto.write_pkt_line(None)
  1395. if report_status_parser is not None:
  1396. ref_status = dict(report_status_parser.check())
  1397. else:
  1398. ref_status = None
  1399. # Convert to Optional type for SendPackResult
  1400. return SendPackResult(
  1401. _to_optional_dict(old_refs), agent=agent, ref_status=ref_status
  1402. )
  1403. header_handler = _v1ReceivePackHeader(
  1404. list(negotiated_capabilities),
  1405. old_refs,
  1406. new_refs,
  1407. )
  1408. for pkt in header_handler:
  1409. proto.write_pkt_line(pkt)
  1410. pack_data_count, pack_data = generate_pack_data(
  1411. header_handler.have,
  1412. header_handler.want,
  1413. ofs_delta=(CAPABILITY_OFS_DELTA in negotiated_capabilities),
  1414. progress=progress,
  1415. )
  1416. if self._should_send_pack(new_refs):
  1417. for chunk in PackChunkGenerator(
  1418. num_records=pack_data_count,
  1419. records=pack_data,
  1420. object_format=DEFAULT_OBJECT_FORMAT,
  1421. ):
  1422. proto.write(chunk)
  1423. ref_status = self._handle_receive_pack_tail(
  1424. proto, negotiated_capabilities, progress
  1425. )
  1426. return SendPackResult(
  1427. _to_optional_dict(new_refs), agent=agent, ref_status=ref_status
  1428. )
  1429. def fetch_pack(
  1430. self,
  1431. path: bytes | str,
  1432. determine_wants: "DetermineWantsFunc",
  1433. graph_walker: GraphWalker,
  1434. pack_data: Callable[[bytes], int],
  1435. progress: Callable[[bytes], None] | None = None,
  1436. depth: int | None = None,
  1437. ref_prefix: Sequence[bytes] | None = None,
  1438. filter_spec: bytes | None = None,
  1439. protocol_version: int | None = None,
  1440. shallow_since: str | None = None,
  1441. shallow_exclude: list[str] | None = None,
  1442. ) -> FetchPackResult:
  1443. """Retrieve a pack from a git smart server.
  1444. Args:
  1445. path: Remote path to fetch from
  1446. determine_wants: Function determine what refs
  1447. to fetch. Receives dictionary of name->sha, should return
  1448. list of shas to fetch.
  1449. graph_walker: Object with next() and ack().
  1450. pack_data: Callback called for each bit of data in the pack
  1451. progress: Callback for progress reports (strings)
  1452. depth: Shallow fetch depth
  1453. ref_prefix: List of prefixes of desired references, as a list of
  1454. bytestrings. Filtering is done by the server if supported, and
  1455. client side otherwise.
  1456. filter_spec: A git-rev-list-style object filter spec, as bytestring.
  1457. Only used if the server supports the Git protocol-v2 'filter'
  1458. feature, and ignored otherwise.
  1459. protocol_version: Desired Git protocol version. By default the highest
  1460. mutually supported protocol version will be used.
  1461. shallow_since: Deepen the history to include commits after this date
  1462. shallow_exclude: Deepen the history to exclude commits reachable from these refs
  1463. Returns:
  1464. FetchPackResult object
  1465. """
  1466. if (
  1467. protocol_version is not None
  1468. and protocol_version not in GIT_PROTOCOL_VERSIONS
  1469. ):
  1470. raise ValueError(f"unknown Git protocol version {protocol_version}")
  1471. proto, can_read, stderr = self._connect(b"upload-pack", path, protocol_version)
  1472. server_protocol_version = negotiate_protocol_version(proto)
  1473. if server_protocol_version not in GIT_PROTOCOL_VERSIONS:
  1474. raise ValueError(
  1475. f"unknown Git protocol version {server_protocol_version} used by server"
  1476. )
  1477. if protocol_version and server_protocol_version > protocol_version:
  1478. raise ValueError(
  1479. f"bad Git protocol version {server_protocol_version} used by server"
  1480. )
  1481. self.protocol_version = server_protocol_version
  1482. with proto:
  1483. # refs may have None values in v2 but not in v1
  1484. refs: dict[Ref, ObjectID | None]
  1485. symrefs: dict[Ref, Ref]
  1486. agent: bytes | None
  1487. object_format: str | None
  1488. if self.protocol_version == 2:
  1489. try:
  1490. server_capabilities = read_server_capabilities(proto.read_pkt_seq())
  1491. except HangupException as exc:
  1492. raise _remote_error_from_stderr(stderr) from exc
  1493. (
  1494. negotiated_capabilities,
  1495. symrefs,
  1496. agent,
  1497. ) = self._negotiate_upload_pack_capabilities(server_capabilities)
  1498. object_format = extract_object_format_from_capabilities(
  1499. server_capabilities
  1500. )
  1501. proto.write_pkt_line(b"command=ls-refs\n")
  1502. proto.write(b"0001") # delim-pkt
  1503. proto.write_pkt_line(b"symrefs")
  1504. proto.write_pkt_line(b"peel")
  1505. if ref_prefix is None:
  1506. ref_prefix = DEFAULT_REF_PREFIX
  1507. for prefix in ref_prefix:
  1508. proto.write_pkt_line(b"ref-prefix " + prefix)
  1509. proto.write_pkt_line(None)
  1510. refs, symrefs, _peeled = read_pkt_refs_v2(proto.read_pkt_seq())
  1511. else:
  1512. try:
  1513. refs_v1, server_capabilities = read_pkt_refs_v1(
  1514. proto.read_pkt_seq()
  1515. )
  1516. # v1 refs never have None values, but we need Optional type for compatibility
  1517. refs = _to_optional_dict(refs_v1)
  1518. except HangupException as exc:
  1519. raise _remote_error_from_stderr(stderr) from exc
  1520. (
  1521. negotiated_capabilities,
  1522. symrefs,
  1523. agent,
  1524. ) = self._negotiate_upload_pack_capabilities(server_capabilities)
  1525. object_format = extract_object_format_from_capabilities(
  1526. server_capabilities
  1527. )
  1528. if ref_prefix is not None:
  1529. refs = filter_ref_prefix(refs, ref_prefix)
  1530. if refs is None:
  1531. proto.write_pkt_line(None)
  1532. return FetchPackResult(
  1533. refs, symrefs, agent, object_format=object_format
  1534. )
  1535. try:
  1536. # Filter out None values (shouldn't be any in v1 protocol)
  1537. refs_no_none = {k: v for k, v in refs.items() if v is not None}
  1538. # Handle both old and new style determine_wants
  1539. try:
  1540. wants = determine_wants(refs_no_none, depth)
  1541. except TypeError:
  1542. # Old-style determine_wants that doesn't accept depth
  1543. wants = determine_wants(refs_no_none)
  1544. except BaseException:
  1545. proto.write_pkt_line(None)
  1546. raise
  1547. if wants is not None:
  1548. wants = [cid for cid in wants if cid != ZERO_SHA]
  1549. if not wants:
  1550. proto.write_pkt_line(None)
  1551. return FetchPackResult(
  1552. refs, symrefs, agent, object_format=object_format
  1553. )
  1554. if self.protocol_version == 2:
  1555. proto.write_pkt_line(b"command=fetch\n")
  1556. proto.write(b"0001") # delim-pkt
  1557. if CAPABILITY_THIN_PACK in self._fetch_capabilities:
  1558. proto.write(pkt_line(b"thin-pack\n"))
  1559. if (
  1560. find_capability(
  1561. list(negotiated_capabilities),
  1562. CAPABILITY_FETCH,
  1563. CAPABILITY_FILTER,
  1564. )
  1565. and filter_spec
  1566. ):
  1567. proto.write(pkt_line(b"filter %s\n" % filter_spec))
  1568. elif filter_spec:
  1569. self._warn_filter_objects()
  1570. elif filter_spec:
  1571. self._warn_filter_objects()
  1572. (new_shallow, new_unshallow) = _handle_upload_pack_head(
  1573. proto,
  1574. list(negotiated_capabilities),
  1575. graph_walker,
  1576. wants,
  1577. can_read,
  1578. depth=depth,
  1579. protocol_version=self.protocol_version,
  1580. shallow_since=shallow_since,
  1581. shallow_exclude=shallow_exclude,
  1582. )
  1583. _handle_upload_pack_tail(
  1584. proto,
  1585. negotiated_capabilities,
  1586. graph_walker,
  1587. pack_data,
  1588. progress,
  1589. protocol_version=self.protocol_version,
  1590. )
  1591. return FetchPackResult(
  1592. refs, symrefs, agent, new_shallow, new_unshallow, object_format
  1593. )
  1594. def get_refs(
  1595. self,
  1596. path: bytes,
  1597. protocol_version: int | None = None,
  1598. ref_prefix: Sequence[bytes] | None = None,
  1599. ) -> LsRemoteResult:
  1600. """Retrieve the current refs from a git smart server."""
  1601. # stock `git ls-remote` uses upload-pack
  1602. if (
  1603. protocol_version is not None
  1604. and protocol_version not in GIT_PROTOCOL_VERSIONS
  1605. ):
  1606. raise ValueError(f"unknown Git protocol version {protocol_version}")
  1607. proto, _, stderr = self._connect(b"upload-pack", path, protocol_version)
  1608. server_protocol_version = negotiate_protocol_version(proto)
  1609. if server_protocol_version not in GIT_PROTOCOL_VERSIONS:
  1610. raise ValueError(
  1611. f"unknown Git protocol version {server_protocol_version} used by server"
  1612. )
  1613. if protocol_version and server_protocol_version > protocol_version:
  1614. raise ValueError(
  1615. f"bad Git protocol version {server_protocol_version} used by server"
  1616. )
  1617. self.protocol_version = server_protocol_version
  1618. if self.protocol_version == 2:
  1619. server_capabilities = read_server_capabilities(proto.read_pkt_seq())
  1620. object_format = extract_object_format_from_capabilities(server_capabilities)
  1621. proto.write_pkt_line(b"command=ls-refs\n")
  1622. proto.write(b"0001") # delim-pkt
  1623. proto.write_pkt_line(b"symrefs")
  1624. proto.write_pkt_line(b"peel")
  1625. if ref_prefix is None:
  1626. ref_prefix = DEFAULT_REF_PREFIX
  1627. for prefix in ref_prefix:
  1628. proto.write_pkt_line(b"ref-prefix " + prefix)
  1629. proto.write_pkt_line(None)
  1630. with proto:
  1631. try:
  1632. refs, symrefs, peeled = read_pkt_refs_v2(proto.read_pkt_seq())
  1633. except HangupException as exc:
  1634. raise _remote_error_from_stderr(stderr) from exc
  1635. proto.write_pkt_line(None)
  1636. for refname, refvalue in peeled.items():
  1637. refs[Ref(refname + PEELED_TAG_SUFFIX)] = refvalue
  1638. return LsRemoteResult(refs, symrefs, object_format=object_format)
  1639. else:
  1640. with proto:
  1641. try:
  1642. refs_v1, server_capabilities = read_pkt_refs_v1(
  1643. proto.read_pkt_seq()
  1644. )
  1645. # v1 refs never have None values, but we need Optional type for compatibility
  1646. refs = _to_optional_dict(refs_v1)
  1647. except HangupException as exc:
  1648. raise _remote_error_from_stderr(stderr) from exc
  1649. proto.write_pkt_line(None)
  1650. object_format = extract_object_format_from_capabilities(
  1651. server_capabilities
  1652. )
  1653. (symrefs, _agent) = _extract_symrefs_and_agent(server_capabilities)
  1654. if ref_prefix is not None:
  1655. refs = filter_ref_prefix(refs, ref_prefix)
  1656. return LsRemoteResult(refs, symrefs, object_format=object_format)
  1657. def archive(
  1658. self,
  1659. path: bytes,
  1660. committish: bytes,
  1661. write_data: Callable[[bytes], None],
  1662. progress: Callable[[bytes], None] | None = None,
  1663. write_error: Callable[[bytes], None] | None = None,
  1664. format: bytes | None = None,
  1665. subdirs: Sequence[bytes] | None = None,
  1666. prefix: bytes | None = None,
  1667. ) -> None:
  1668. """Request an archive of a specific commit.
  1669. Args:
  1670. path: Repository path
  1671. committish: Commit ID or ref to archive
  1672. write_data: Function to write archive data
  1673. progress: Optional progress callback
  1674. write_error: Optional error callback
  1675. format: Optional archive format
  1676. subdirs: Optional subdirectories to include
  1677. prefix: Optional prefix for archived files
  1678. """
  1679. proto, _can_read, stderr = self._connect(b"upload-archive", path)
  1680. with proto:
  1681. if format is not None:
  1682. proto.write_pkt_line(b"argument --format=" + format)
  1683. proto.write_pkt_line(b"argument " + committish)
  1684. if subdirs is not None:
  1685. for subdir in subdirs:
  1686. proto.write_pkt_line(b"argument " + subdir)
  1687. if prefix is not None:
  1688. proto.write_pkt_line(b"argument --prefix=" + prefix)
  1689. proto.write_pkt_line(None)
  1690. try:
  1691. pkt = proto.read_pkt_line()
  1692. except HangupException as exc:
  1693. raise _remote_error_from_stderr(stderr) from exc
  1694. if pkt == b"NACK\n" or pkt == b"NACK":
  1695. return
  1696. elif pkt == b"ACK\n" or pkt == b"ACK":
  1697. pass
  1698. elif pkt and pkt.startswith(b"ERR "):
  1699. raise GitProtocolError(pkt[4:].rstrip(b"\n").decode("utf-8", "replace"))
  1700. else:
  1701. raise AssertionError(f"invalid response {pkt!r}")
  1702. ret = proto.read_pkt_line()
  1703. if ret is not None:
  1704. raise AssertionError("expected pkt tail")
  1705. for chan, data in _read_side_band64k_data(proto.read_pkt_seq()):
  1706. if chan == SIDE_BAND_CHANNEL_DATA:
  1707. write_data(data)
  1708. elif chan == SIDE_BAND_CHANNEL_PROGRESS:
  1709. if progress is not None:
  1710. progress(data)
  1711. elif chan == SIDE_BAND_CHANNEL_FATAL:
  1712. if write_error is not None:
  1713. write_error(data)
  1714. else:
  1715. raise AssertionError(f"Invalid sideband channel {chan}")
  1716. class TCPGitClient(TraditionalGitClient):
  1717. """A Git Client that works over TCP directly (i.e. git://)."""
  1718. def __init__(
  1719. self,
  1720. host: str,
  1721. port: int | None = None,
  1722. thin_packs: bool = True,
  1723. report_activity: Callable[[int, str], None] | None = None,
  1724. quiet: bool = False,
  1725. include_tags: bool = False,
  1726. ) -> None:
  1727. """Initialize a TCPGitClient.
  1728. Args:
  1729. host: Hostname or IP address to connect to
  1730. port: Port number (defaults to TCP_GIT_PORT)
  1731. thin_packs: Whether or not thin packs should be retrieved
  1732. report_activity: Optional callback for reporting transport activity
  1733. quiet: Whether to suppress progress output
  1734. include_tags: Whether to include tags
  1735. """
  1736. if port is None:
  1737. port = TCP_GIT_PORT
  1738. self._host = host
  1739. self._port = port
  1740. super().__init__(
  1741. thin_packs=thin_packs,
  1742. report_activity=report_activity,
  1743. quiet=quiet,
  1744. include_tags=include_tags,
  1745. )
  1746. @classmethod
  1747. def from_parsedurl(
  1748. cls,
  1749. parsedurl: ParseResult,
  1750. thin_packs: bool = True,
  1751. report_activity: Callable[[int, str], None] | None = None,
  1752. quiet: bool = False,
  1753. include_tags: bool = False,
  1754. dumb: bool = False,
  1755. username: str | None = None,
  1756. password: str | None = None,
  1757. config: Config | None = None,
  1758. ) -> "TCPGitClient":
  1759. """Create an instance of TCPGitClient from a parsed URL.
  1760. Args:
  1761. parsedurl: Result of urlparse()
  1762. thin_packs: Whether or not thin packs should be retrieved
  1763. report_activity: Optional callback for reporting transport activity
  1764. quiet: Whether to suppress progress output
  1765. include_tags: Whether to include tags
  1766. dumb: Whether to use dumb protocol (not used for TCPGitClient)
  1767. username: Username for authentication (not used for TCPGitClient)
  1768. password: Password for authentication (not used for TCPGitClient)
  1769. config: Configuration object (not used for TCPGitClient)
  1770. Returns:
  1771. A TCPGitClient instance
  1772. """
  1773. assert parsedurl.hostname is not None
  1774. return cls(
  1775. parsedurl.hostname,
  1776. port=parsedurl.port,
  1777. thin_packs=thin_packs,
  1778. report_activity=report_activity,
  1779. quiet=quiet,
  1780. include_tags=include_tags,
  1781. )
  1782. def get_url(self, path: str) -> str:
  1783. r"""Get the URL for a TCP git connection.
  1784. Args:
  1785. path: Repository path
  1786. Returns:
  1787. ``git://`` URL for the path
  1788. """
  1789. # IPv6 addresses contain colons and need to be wrapped in brackets
  1790. if ":" in self._host:
  1791. netloc = f"[{self._host}]"
  1792. else:
  1793. netloc = self._host
  1794. if self._port is not None and self._port != TCP_GIT_PORT:
  1795. netloc += f":{self._port}"
  1796. return urlunsplit(("git", netloc, path, "", ""))
  1797. def _connect(
  1798. self,
  1799. cmd: bytes,
  1800. path: str | bytes,
  1801. protocol_version: int | None = None,
  1802. ) -> tuple[Protocol, Callable[[], bool], IO[bytes] | None]:
  1803. if not isinstance(cmd, bytes):
  1804. raise TypeError(cmd)
  1805. if not isinstance(path, bytes):
  1806. path = path.encode(self._remote_path_encoding)
  1807. sockaddrs = socket.getaddrinfo(
  1808. self._host, self._port, socket.AF_UNSPEC, socket.SOCK_STREAM
  1809. )
  1810. s = None
  1811. err = OSError(f"no address found for {self._host}")
  1812. for family, socktype, protof, canonname, sockaddr in sockaddrs:
  1813. s = socket.socket(family, socktype, protof)
  1814. s.setsockopt(socket.IPPROTO_TCP, socket.TCP_NODELAY, 1)
  1815. try:
  1816. s.connect(sockaddr)
  1817. break
  1818. except OSError as e:
  1819. err = e
  1820. if s is not None:
  1821. s.close()
  1822. s = None
  1823. if s is None:
  1824. raise err
  1825. # -1 means system default buffering
  1826. rfile = s.makefile("rb", -1)
  1827. # 0 means unbuffered
  1828. wfile = s.makefile("wb", 0)
  1829. def close() -> None:
  1830. rfile.close()
  1831. wfile.close()
  1832. s.close()
  1833. proto = Protocol(
  1834. rfile.read,
  1835. wfile.write,
  1836. close,
  1837. report_activity=self._report_activity,
  1838. )
  1839. if path.startswith(b"/~"):
  1840. path = path[1:]
  1841. if cmd == b"upload-pack":
  1842. if protocol_version is None:
  1843. self.protocol_version = DEFAULT_GIT_PROTOCOL_VERSION_FETCH
  1844. else:
  1845. self.protocol_version = protocol_version
  1846. else:
  1847. self.protocol_version = DEFAULT_GIT_PROTOCOL_VERSION_SEND
  1848. if cmd == b"upload-pack" and self.protocol_version == 2:
  1849. # Git protocol version advertisement is hidden behind two NUL bytes
  1850. # for compatibility with older Git server implementations, which
  1851. # would crash if something other than a "host=" header was found
  1852. # after the first NUL byte.
  1853. version_str = b"\0\0version=%d\0" % self.protocol_version
  1854. else:
  1855. version_str = b""
  1856. # TODO(jelmer): Alternative to ascii?
  1857. proto.send_cmd(
  1858. b"git-" + cmd, path, b"host=" + self._host.encode("ascii") + version_str
  1859. )
  1860. return proto, lambda: _fileno_can_read(s.fileno()), None
  1861. class SubprocessWrapper:
  1862. """A socket-like object that talks to a subprocess via pipes."""
  1863. def __init__(self, proc: subprocess.Popen[bytes]) -> None:
  1864. """Initialize a SubprocessWrapper.
  1865. Args:
  1866. proc: Subprocess.Popen instance to wrap
  1867. """
  1868. self.proc = proc
  1869. assert proc.stdout is not None
  1870. assert proc.stdin is not None
  1871. self.read = BufferedReader(proc.stdout).read # type: ignore[type-var]
  1872. self.write = proc.stdin.write
  1873. @property
  1874. def stderr(self) -> IO[bytes] | None:
  1875. """Return the stderr stream of the subprocess."""
  1876. return self.proc.stderr
  1877. def can_read(self) -> bool:
  1878. """Check if there is data available to read.
  1879. Returns: True if data is available, False otherwise
  1880. """
  1881. if sys.platform == "win32":
  1882. from msvcrt import get_osfhandle
  1883. assert self.proc.stdout is not None
  1884. handle = get_osfhandle(self.proc.stdout.fileno())
  1885. return _win32_peek_avail(handle) != 0
  1886. else:
  1887. assert self.proc.stdout is not None
  1888. return _fileno_can_read(self.proc.stdout.fileno())
  1889. def close(self, timeout: int | None = 60) -> None:
  1890. """Close the subprocess and wait for it to terminate.
  1891. Args:
  1892. timeout: Maximum time to wait for subprocess to terminate (seconds)
  1893. Raises:
  1894. GitProtocolError: If subprocess doesn't terminate within timeout
  1895. """
  1896. if self.proc.stdin:
  1897. self.proc.stdin.close()
  1898. if self.proc.stdout:
  1899. self.proc.stdout.close()
  1900. if self.proc.stderr:
  1901. self.proc.stderr.close()
  1902. try:
  1903. self.proc.wait(timeout=timeout)
  1904. except subprocess.TimeoutExpired as e:
  1905. self.proc.kill()
  1906. self.proc.wait()
  1907. raise GitProtocolError(
  1908. f"Git subprocess did not terminate within {timeout} seconds; killed it."
  1909. ) from e
  1910. def find_git_command() -> list[str]:
  1911. """Find command to run for system Git (usually C Git)."""
  1912. if sys.platform == "win32": # support .exe, .bat and .cmd
  1913. try: # to avoid overhead
  1914. import pywintypes
  1915. import win32api
  1916. except ImportError: # run through cmd.exe with some overhead
  1917. return ["cmd", "/c", "git"]
  1918. else:
  1919. try:
  1920. _status, git = win32api.FindExecutable("git")
  1921. return [git]
  1922. except pywintypes.error:
  1923. return ["cmd", "/c", "git"]
  1924. else:
  1925. return ["git"]
  1926. class SubprocessGitClient(TraditionalGitClient):
  1927. """Git client that talks to a server using a subprocess."""
  1928. @classmethod
  1929. def from_parsedurl(
  1930. cls,
  1931. parsedurl: ParseResult,
  1932. thin_packs: bool = True,
  1933. report_activity: Callable[[int, str], None] | None = None,
  1934. quiet: bool = False,
  1935. include_tags: bool = False,
  1936. dumb: bool = False,
  1937. username: str | None = None,
  1938. password: str | None = None,
  1939. config: Config | None = None,
  1940. ) -> "SubprocessGitClient":
  1941. """Create an instance of SubprocessGitClient from a parsed URL.
  1942. Args:
  1943. parsedurl: Result of urlparse()
  1944. thin_packs: Whether or not thin packs should be retrieved
  1945. report_activity: Optional callback for reporting transport activity
  1946. quiet: Whether to suppress progress output
  1947. include_tags: Whether to include tags
  1948. dumb: Whether to use dumb protocol (not used for SubprocessGitClient)
  1949. username: Username for authentication (not used for SubprocessGitClient)
  1950. password: Password for authentication (not used for SubprocessGitClient)
  1951. config: Configuration object (not used for SubprocessGitClient)
  1952. Returns:
  1953. A SubprocessGitClient instance
  1954. """
  1955. return cls(
  1956. thin_packs=thin_packs,
  1957. report_activity=report_activity,
  1958. quiet=quiet,
  1959. include_tags=include_tags,
  1960. )
  1961. git_command: str | None = None
  1962. def _connect(
  1963. self,
  1964. service: bytes,
  1965. path: bytes | str,
  1966. protocol_version: int | None = None,
  1967. ) -> tuple[Protocol, Callable[[], bool], IO[bytes] | None]:
  1968. if not isinstance(service, bytes):
  1969. raise TypeError(service)
  1970. if isinstance(path, bytes):
  1971. path = path.decode(self._remote_path_encoding)
  1972. if self.git_command is None:
  1973. git_command = find_git_command()
  1974. argv = [*git_command, service.decode("ascii"), path]
  1975. p = subprocess.Popen(
  1976. argv,
  1977. bufsize=0,
  1978. stdin=subprocess.PIPE,
  1979. stdout=subprocess.PIPE,
  1980. stderr=subprocess.PIPE,
  1981. )
  1982. pw = SubprocessWrapper(p)
  1983. return (
  1984. Protocol(
  1985. pw.read,
  1986. pw.write,
  1987. pw.close,
  1988. report_activity=self._report_activity,
  1989. ),
  1990. pw.can_read,
  1991. p.stderr,
  1992. )
  1993. class LocalGitClient(GitClient):
  1994. """Git Client that just uses a local on-disk repository."""
  1995. def __init__(
  1996. self,
  1997. thin_packs: bool = True,
  1998. report_activity: Callable[[int, str], None] | None = None,
  1999. config: Config | None = None,
  2000. quiet: bool = False,
  2001. include_tags: bool = False,
  2002. ) -> None:
  2003. """Create a new LocalGitClient instance.
  2004. Args:
  2005. thin_packs: Whether or not thin packs should be retrieved
  2006. report_activity: Optional callback for reporting transport
  2007. activity.
  2008. config: Optional configuration object
  2009. quiet: Whether to suppress progress output
  2010. include_tags: Whether to include tags
  2011. """
  2012. self._report_activity = report_activity
  2013. self._quiet = quiet
  2014. self._include_tags = include_tags
  2015. # Ignore the thin_packs argument
  2016. def get_url(self, path: str) -> str:
  2017. """Get the URL for a local file path.
  2018. Args:
  2019. path: Local file path
  2020. Returns:
  2021. file:// URL for the path
  2022. """
  2023. return urlunsplit(("file", "", path, "", ""))
  2024. @classmethod
  2025. def from_parsedurl(
  2026. cls,
  2027. parsedurl: ParseResult,
  2028. thin_packs: bool = True,
  2029. report_activity: Callable[[int, str], None] | None = None,
  2030. quiet: bool = False,
  2031. include_tags: bool = False,
  2032. dumb: bool = False,
  2033. username: str | None = None,
  2034. password: str | None = None,
  2035. config: Config | None = None,
  2036. ) -> "LocalGitClient":
  2037. """Create an instance of LocalGitClient from a parsed URL.
  2038. Args:
  2039. parsedurl: Result of urlparse()
  2040. thin_packs: Whether or not thin packs should be retrieved
  2041. report_activity: Optional callback for reporting transport activity
  2042. quiet: Whether to suppress progress output
  2043. include_tags: Whether to include tags
  2044. dumb: Whether to use dumb protocol (not used for LocalGitClient)
  2045. username: Username for authentication (not used for LocalGitClient)
  2046. password: Password for authentication (not used for LocalGitClient)
  2047. config: Optional configuration object
  2048. Returns:
  2049. A LocalGitClient instance
  2050. """
  2051. return cls(
  2052. thin_packs=thin_packs,
  2053. report_activity=report_activity,
  2054. quiet=quiet,
  2055. include_tags=include_tags,
  2056. config=config,
  2057. )
  2058. @classmethod
  2059. def _open_repo(cls, path: str | bytes) -> "closing[Repo]":
  2060. """Open a local repository.
  2061. Args:
  2062. path: Repository path (as bytes or str)
  2063. Returns:
  2064. Repo instance wrapped in a closing context manager
  2065. """
  2066. if not isinstance(path, str):
  2067. path = os.fsdecode(path)
  2068. return closing(Repo(path))
  2069. def send_pack(
  2070. self,
  2071. path: str | bytes,
  2072. update_refs: Callable[[dict[Ref, ObjectID]], dict[Ref, ObjectID]],
  2073. generate_pack_data: "GeneratePackDataFunc",
  2074. progress: Callable[[bytes], None] | None = None,
  2075. ) -> SendPackResult:
  2076. """Upload a pack to a local on-disk repository.
  2077. Args:
  2078. path: Repository path (as bytestring)
  2079. update_refs: Function to determine changes to remote refs.
  2080. Receive dict with existing remote refs, returns dict with
  2081. changed refs (name -> sha, where sha=ZERO_SHA for deletions)
  2082. with number of items and pack data to upload.
  2083. generate_pack_data: Function that generates pack data given
  2084. have and want object sets
  2085. progress: Optional progress function
  2086. Returns:
  2087. SendPackResult
  2088. Raises:
  2089. SendPackError: if server rejects the pack data
  2090. """
  2091. if not progress:
  2092. def progress(x: bytes) -> None:
  2093. pass
  2094. with self._open_repo(path) as target:
  2095. old_refs = target.get_refs()
  2096. new_refs = update_refs(dict(old_refs))
  2097. have = [sha1 for sha1 in old_refs.values() if sha1 != ZERO_SHA]
  2098. want = []
  2099. for refname, new_sha1 in new_refs.items():
  2100. if (
  2101. new_sha1 not in have
  2102. and new_sha1 not in want
  2103. and new_sha1 != ZERO_SHA
  2104. ):
  2105. want.append(new_sha1)
  2106. if not want and set(new_refs.items()).issubset(set(old_refs.items())):
  2107. return SendPackResult(_to_optional_dict(new_refs), ref_status={})
  2108. target.object_store.add_pack_data(
  2109. *generate_pack_data(
  2110. set(have), set(want), ofs_delta=True, progress=progress
  2111. )
  2112. )
  2113. ref_status: dict[bytes, str | None] = {}
  2114. for refname, new_sha1 in new_refs.items():
  2115. old_sha1 = old_refs.get(refname, ZERO_SHA)
  2116. if new_sha1 != ZERO_SHA:
  2117. if not target.refs.set_if_equals(refname, old_sha1, new_sha1):
  2118. msg = f"unable to set {refname!r} to {new_sha1!r}"
  2119. progress(msg.encode())
  2120. ref_status[refname] = msg
  2121. else:
  2122. if not target.refs.remove_if_equals(refname, old_sha1):
  2123. progress(f"unable to remove {refname!r}".encode())
  2124. ref_status[refname] = "unable to remove"
  2125. return SendPackResult(_to_optional_dict(new_refs), ref_status=ref_status)
  2126. def fetch(
  2127. self,
  2128. path: bytes | str,
  2129. target: BaseRepo,
  2130. determine_wants: "DetermineWantsFunc | None" = None,
  2131. progress: Callable[[bytes], None] | None = None,
  2132. depth: int | None = None,
  2133. ref_prefix: Sequence[bytes] | None = None,
  2134. filter_spec: bytes | None = None,
  2135. protocol_version: int | None = None,
  2136. shallow_since: str | None = None,
  2137. shallow_exclude: list[str] | None = None,
  2138. ) -> FetchPackResult:
  2139. """Fetch into a target repository.
  2140. Args:
  2141. path: Path to fetch from (as bytestring)
  2142. target: Target repository to fetch into
  2143. determine_wants: Optional function determine what refs
  2144. to fetch. Receives dictionary of name->sha, should return
  2145. list of shas to fetch. Defaults to all shas.
  2146. progress: Optional progress function
  2147. depth: Shallow fetch depth
  2148. ref_prefix: List of prefixes of desired references, as a list of
  2149. bytestrings. Filtering is done by the server if supported, and
  2150. client side otherwise.
  2151. filter_spec: A git-rev-list-style object filter spec, as bytestring.
  2152. Only used if the server supports the Git protocol-v2 'filter'
  2153. feature, and ignored otherwise.
  2154. protocol_version: Optional Git protocol version
  2155. shallow_since: Deepen the history to include commits after this date
  2156. shallow_exclude: Deepen the history to exclude commits reachable from these refs
  2157. Returns:
  2158. FetchPackResult object
  2159. """
  2160. with self._open_repo(path) as r:
  2161. refs = r.fetch(
  2162. target,
  2163. determine_wants=determine_wants,
  2164. progress=progress,
  2165. depth=depth,
  2166. )
  2167. return FetchPackResult(
  2168. _to_optional_dict(refs),
  2169. r.refs.get_symrefs(),
  2170. agent_string(),
  2171. object_format=r.object_format.name,
  2172. )
  2173. def fetch_pack(
  2174. self,
  2175. path: str | bytes,
  2176. determine_wants: "DetermineWantsFunc",
  2177. graph_walker: GraphWalker,
  2178. pack_data: Callable[[bytes], int],
  2179. progress: Callable[[bytes], None] | None = None,
  2180. depth: int | None = None,
  2181. ref_prefix: Sequence[bytes] | None = None,
  2182. filter_spec: bytes | None = None,
  2183. protocol_version: int | None = None,
  2184. shallow_since: str | None = None,
  2185. shallow_exclude: list[str] | None = None,
  2186. ) -> FetchPackResult:
  2187. """Retrieve a pack from a local on-disk repository.
  2188. Args:
  2189. path: Remote path to fetch from
  2190. determine_wants: Function determine what refs
  2191. to fetch. Receives dictionary of name->sha, should return
  2192. list of shas to fetch.
  2193. graph_walker: Object with next() and ack().
  2194. pack_data: Callback called for each bit of data in the pack
  2195. progress: Callback for progress reports (strings)
  2196. depth: Shallow fetch depth
  2197. ref_prefix: List of prefixes of desired references, as a list of
  2198. bytestrings. Filtering is done by the server if supported, and
  2199. client side otherwise.
  2200. filter_spec: A git-rev-list-style object filter spec, as bytestring.
  2201. Only used if the server supports the Git protocol-v2 'filter'
  2202. feature, and ignored otherwise.
  2203. protocol_version: Optional Git protocol version
  2204. shallow_since: Deepen the history to include commits after this date
  2205. shallow_exclude: Deepen the history to exclude commits reachable from these refs
  2206. Returns:
  2207. FetchPackResult object
  2208. """
  2209. with self._open_repo(path) as r:
  2210. missing_objects = r.find_missing_objects(
  2211. determine_wants, graph_walker, progress=progress, depth=depth
  2212. )
  2213. if missing_objects is None:
  2214. other_haves = set()
  2215. object_ids = []
  2216. else:
  2217. other_haves = missing_objects.get_remote_has()
  2218. object_ids = list(missing_objects)
  2219. symrefs = r.refs.get_symrefs()
  2220. agent = agent_string()
  2221. # Did the process short-circuit (e.g. in a stateless RPC call)?
  2222. # Note that the client still expects a 0-object pack in most cases.
  2223. if object_ids is None:
  2224. return FetchPackResult(
  2225. None, symrefs, agent, object_format=r.object_format.name
  2226. )
  2227. write_pack_from_container(
  2228. pack_data, # type: ignore[arg-type]
  2229. r.object_store,
  2230. object_ids,
  2231. other_haves=other_haves,
  2232. object_format=r.object_format,
  2233. )
  2234. # Convert refs to Optional type for FetchPackResult
  2235. return FetchPackResult(
  2236. _to_optional_dict(r.get_refs()),
  2237. symrefs,
  2238. agent,
  2239. object_format=r.object_format.name,
  2240. )
  2241. def get_refs(
  2242. self,
  2243. path: str | bytes,
  2244. protocol_version: int | None = None,
  2245. ref_prefix: Sequence[bytes] | None = None,
  2246. ) -> LsRemoteResult:
  2247. """Retrieve the current refs from a local on-disk repository."""
  2248. with self._open_repo(path) as target:
  2249. refs_dict = target.get_refs()
  2250. refs = _to_optional_dict(refs_dict)
  2251. # Extract symrefs from the local repository
  2252. from dulwich.refs import Ref
  2253. symrefs: dict[Ref, Ref] = {}
  2254. for ref in refs:
  2255. try:
  2256. # Check if this ref is symbolic by reading it directly
  2257. ref_value = target.refs.read_ref(ref)
  2258. if ref_value and ref_value.startswith(SYMREF):
  2259. # Extract the target from the symref
  2260. symrefs[ref] = Ref(ref_value[len(SYMREF) :])
  2261. except (KeyError, ValueError):
  2262. # Not a symbolic ref or error reading it
  2263. pass
  2264. return LsRemoteResult(
  2265. refs, symrefs, object_format=target.object_format.name
  2266. )
  2267. def clone(
  2268. self,
  2269. path: str,
  2270. target_path: str,
  2271. mkdir: bool = True,
  2272. bare: bool = False,
  2273. origin: str | None = "origin",
  2274. checkout: bool | None = None,
  2275. branch: str | None = None,
  2276. progress: Callable[[bytes], None] | None = None,
  2277. depth: int | None = None,
  2278. ref_prefix: Sequence[bytes] | None = None,
  2279. filter_spec: bytes | None = None,
  2280. protocol_version: int | None = None,
  2281. ) -> Repo:
  2282. """Clone a local repository.
  2283. For local clones, we can detect the object format before creating
  2284. the target repository.
  2285. """
  2286. # Detect the object format from the source repository
  2287. with self._open_repo(path) as source_repo:
  2288. object_format_name = source_repo.object_format.name
  2289. if mkdir:
  2290. os.mkdir(target_path)
  2291. try:
  2292. # Create repository with the correct object format from the start
  2293. target = None
  2294. if not bare:
  2295. target = Repo.init(target_path, object_format=object_format_name)
  2296. if checkout is None:
  2297. checkout = True
  2298. else:
  2299. if checkout:
  2300. raise ValueError("checkout and bare are incompatible")
  2301. target = Repo.init_bare(target_path, object_format=object_format_name)
  2302. encoded_path = path.encode("utf-8")
  2303. assert target is not None
  2304. if origin is not None:
  2305. target_config = target.get_config()
  2306. target_config.set(
  2307. (b"remote", origin.encode("utf-8")), b"url", encoded_path
  2308. )
  2309. target_config.set(
  2310. (b"remote", origin.encode("utf-8")),
  2311. b"fetch",
  2312. b"+refs/heads/*:refs/remotes/" + origin.encode("utf-8") + b"/*",
  2313. )
  2314. target_config.write_to_path()
  2315. ref_message = b"clone: from " + encoded_path
  2316. result = self.fetch(
  2317. path.encode("utf-8"),
  2318. target,
  2319. progress=progress,
  2320. depth=depth,
  2321. ref_prefix=ref_prefix,
  2322. filter_spec=filter_spec,
  2323. protocol_version=protocol_version,
  2324. )
  2325. if origin is not None:
  2326. _import_remote_refs(
  2327. target.refs, origin, result.refs, message=ref_message
  2328. )
  2329. origin_head = result.symrefs.get(HEADREF)
  2330. origin_sha = result.refs.get(HEADREF)
  2331. if origin is None or (origin_sha and not origin_head):
  2332. # set detached HEAD
  2333. if origin_sha is not None:
  2334. target.refs[HEADREF] = origin_sha
  2335. head = origin_sha
  2336. else:
  2337. head = None
  2338. else:
  2339. _set_origin_head(target.refs, origin.encode("utf-8"), origin_head)
  2340. head_ref = _set_default_branch(
  2341. target.refs,
  2342. origin.encode("utf-8"),
  2343. origin_head,
  2344. branch.encode("utf-8") if branch is not None else None,
  2345. ref_message,
  2346. )
  2347. # Update target head
  2348. if head_ref:
  2349. head = _set_head(target.refs, head_ref, ref_message)
  2350. else:
  2351. head = None
  2352. if checkout and head is not None:
  2353. target.get_worktree().reset_index()
  2354. except BaseException:
  2355. if target is not None:
  2356. target.close()
  2357. if mkdir:
  2358. import shutil
  2359. shutil.rmtree(target_path)
  2360. raise
  2361. return target
  2362. class BundleClient(GitClient):
  2363. """Git Client that reads from a bundle file."""
  2364. def __init__(
  2365. self,
  2366. thin_packs: bool = True,
  2367. report_activity: Callable[[int, str], None] | None = None,
  2368. config: Config | None = None,
  2369. quiet: bool = False,
  2370. include_tags: bool = False,
  2371. ) -> None:
  2372. """Create a new BundleClient instance.
  2373. Args:
  2374. thin_packs: Whether or not thin packs should be retrieved
  2375. report_activity: Optional callback for reporting transport
  2376. activity.
  2377. config: Optional configuration object
  2378. quiet: Whether to suppress progress output
  2379. include_tags: Whether to include tags
  2380. """
  2381. self._report_activity = report_activity
  2382. self._quiet = quiet
  2383. self._include_tags = include_tags
  2384. def get_url(self, path: str) -> str:
  2385. """Get the URL for a bundle file path.
  2386. Args:
  2387. path: Bundle file path
  2388. Returns:
  2389. The path unchanged (bundle files use local paths)
  2390. """
  2391. return path
  2392. @classmethod
  2393. def from_parsedurl(
  2394. cls,
  2395. parsedurl: ParseResult,
  2396. thin_packs: bool = True,
  2397. report_activity: Callable[[int, str], None] | None = None,
  2398. quiet: bool = False,
  2399. include_tags: bool = False,
  2400. dumb: bool = False,
  2401. username: str | None = None,
  2402. password: str | None = None,
  2403. config: Config | None = None,
  2404. ) -> "BundleClient":
  2405. """Create an instance of BundleClient from a parsed URL.
  2406. Args:
  2407. parsedurl: Result of urlparse()
  2408. thin_packs: Whether or not thin packs should be retrieved
  2409. report_activity: Optional callback for reporting transport activity
  2410. quiet: Whether to suppress progress output
  2411. include_tags: Whether to include tags
  2412. dumb: Whether to use dumb protocol (not used for BundleClient)
  2413. username: Username for authentication (not used for BundleClient)
  2414. password: Password for authentication (not used for BundleClient)
  2415. config: Configuration object (not used for BundleClient)
  2416. Returns:
  2417. A BundleClient instance
  2418. """
  2419. return cls(
  2420. thin_packs=thin_packs,
  2421. report_activity=report_activity,
  2422. quiet=quiet,
  2423. include_tags=include_tags,
  2424. )
  2425. @classmethod
  2426. def _is_bundle_file(cls, path: str) -> bool:
  2427. """Check if a file is a git bundle by reading the first line."""
  2428. try:
  2429. with open(path, "rb") as f:
  2430. first_line = f.readline()
  2431. return first_line in (b"# v2 git bundle\n", b"# v3 git bundle\n")
  2432. except OSError:
  2433. return False
  2434. @classmethod
  2435. def _open_bundle(cls, path: str | bytes) -> "Bundle":
  2436. """Open and parse a bundle file.
  2437. Args:
  2438. path: Path to the bundle file (bytes or str)
  2439. Returns:
  2440. Bundle object with parsed metadata
  2441. Raises:
  2442. AssertionError: If bundle format is unsupported
  2443. """
  2444. if not isinstance(path, str):
  2445. path = os.fsdecode(path)
  2446. # Read bundle metadata without PackData to avoid file handle issues
  2447. with open(path, "rb") as f:
  2448. from dulwich.bundle import Bundle
  2449. version = None
  2450. firstline = f.readline()
  2451. if firstline == b"# v2 git bundle\n":
  2452. version = 2
  2453. elif firstline == b"# v3 git bundle\n":
  2454. version = 3
  2455. else:
  2456. raise AssertionError(f"unsupported bundle format header: {firstline!r}")
  2457. capabilities: dict[str, str | None] = {}
  2458. prerequisites: list[tuple[ObjectID, bytes]] = []
  2459. references: dict[Ref, ObjectID] = {}
  2460. line = f.readline()
  2461. if version >= 3:
  2462. while line.startswith(b"@"):
  2463. line = line[1:].rstrip(b"\n")
  2464. try:
  2465. key, value_bytes = line.split(b"=", 1)
  2466. value = value_bytes.decode("utf-8")
  2467. except ValueError:
  2468. key = line
  2469. value = None
  2470. capabilities[key.decode("utf-8")] = value
  2471. line = f.readline()
  2472. while line.startswith(b"-"):
  2473. (obj_id, comment) = line[1:].rstrip(b"\n").split(b" ", 1)
  2474. prerequisites.append((ObjectID(obj_id), comment))
  2475. line = f.readline()
  2476. while line != b"\n":
  2477. (obj_id, ref) = line.rstrip(b"\n").split(b" ", 1)
  2478. references[Ref(ref)] = ObjectID(obj_id)
  2479. line = f.readline()
  2480. # Don't read PackData here, we'll do it later
  2481. bundle = Bundle()
  2482. bundle.version = version
  2483. bundle.capabilities = capabilities
  2484. bundle.prerequisites = prerequisites
  2485. bundle.references = references
  2486. bundle.pack_data = None # Will be read on demand
  2487. return bundle
  2488. @staticmethod
  2489. def _skip_to_pack_data(f: IO[bytes], version: int) -> None:
  2490. """Skip to the pack data section in a bundle file.
  2491. Args:
  2492. f: File object positioned at the beginning of the bundle
  2493. version: Bundle format version (2 or 3)
  2494. Raises:
  2495. AssertionError: If bundle header is invalid
  2496. """
  2497. # Skip header
  2498. header = f.readline()
  2499. if header not in (b"# v2 git bundle\n", b"# v3 git bundle\n"):
  2500. raise AssertionError(f"Invalid bundle header: {header!r}")
  2501. line = f.readline()
  2502. # Skip capabilities (v3 only)
  2503. if version >= 3:
  2504. while line.startswith(b"@"):
  2505. line = f.readline()
  2506. # Skip prerequisites
  2507. while line.startswith(b"-"):
  2508. line = f.readline()
  2509. # Skip references
  2510. while line != b"\n":
  2511. line = f.readline()
  2512. # Now at pack data
  2513. def send_pack(
  2514. self,
  2515. path: str | bytes,
  2516. update_refs: Callable[[dict[Ref, ObjectID]], dict[Ref, ObjectID]],
  2517. generate_pack_data: "GeneratePackDataFunc",
  2518. progress: Callable[[bytes], None] | None = None,
  2519. ) -> SendPackResult:
  2520. """Upload is not supported for bundle files."""
  2521. raise NotImplementedError("Bundle files are read-only")
  2522. def fetch(
  2523. self,
  2524. path: bytes | str,
  2525. target: BaseRepo,
  2526. determine_wants: "DetermineWantsFunc | None" = None,
  2527. progress: Callable[[bytes], None] | None = None,
  2528. depth: int | None = None,
  2529. ref_prefix: Sequence[bytes] | None = None,
  2530. filter_spec: bytes | None = None,
  2531. protocol_version: int | None = None,
  2532. shallow_since: str | None = None,
  2533. shallow_exclude: list[str] | None = None,
  2534. ) -> FetchPackResult:
  2535. """Fetch into a target repository from a bundle file."""
  2536. bundle = self._open_bundle(path)
  2537. # Get references from bundle
  2538. refs = dict(bundle.references)
  2539. # Determine what we want to fetch
  2540. if determine_wants is None:
  2541. _ = list(refs.values())
  2542. else:
  2543. _ = determine_wants(refs, None)
  2544. # Add pack data to target repository
  2545. # Need to reopen the file for pack data access
  2546. with open(path, "rb") as pack_file:
  2547. # Skip to pack data section
  2548. assert bundle.version is not None
  2549. BundleClient._skip_to_pack_data(pack_file, bundle.version)
  2550. # Read pack data into memory to avoid file positioning issues
  2551. pack_bytes = pack_file.read()
  2552. # Create PackData from in-memory bytes
  2553. from io import BytesIO
  2554. pack_io = BytesIO(pack_bytes)
  2555. pack_data = PackData.from_file(pack_io, object_format=DEFAULT_OBJECT_FORMAT)
  2556. target.object_store.add_pack_data(len(pack_data), pack_data.iter_unpacked())
  2557. # Apply ref filtering if specified
  2558. if ref_prefix:
  2559. filtered_refs = {}
  2560. for ref_name, ref_value in refs.items():
  2561. for prefix in ref_prefix:
  2562. if ref_name.startswith(prefix):
  2563. filtered_refs[ref_name] = ref_value
  2564. break
  2565. refs = filtered_refs
  2566. return FetchPackResult(_to_optional_dict(refs), {}, agent_string())
  2567. def fetch_pack(
  2568. self,
  2569. path: str | bytes,
  2570. determine_wants: "DetermineWantsFunc",
  2571. graph_walker: GraphWalker,
  2572. pack_data: Callable[[bytes], int],
  2573. progress: Callable[[bytes], None] | None = None,
  2574. depth: int | None = None,
  2575. ref_prefix: Sequence[bytes] | None = None,
  2576. filter_spec: bytes | None = None,
  2577. protocol_version: int | None = None,
  2578. shallow_since: str | None = None,
  2579. shallow_exclude: list[str] | None = None,
  2580. ) -> FetchPackResult:
  2581. """Retrieve a pack from a bundle file."""
  2582. bundle = self._open_bundle(path)
  2583. # Get references from bundle
  2584. refs = dict(bundle.references)
  2585. # Determine what we want to fetch
  2586. try:
  2587. _ = determine_wants(refs, depth)
  2588. except TypeError:
  2589. # Old-style determine_wants that doesn't accept depth
  2590. _ = determine_wants(refs)
  2591. # Write pack data to the callback
  2592. # Need to reopen the file for pack data access
  2593. with open(path, "rb") as pack_file:
  2594. # Skip to pack data section
  2595. assert bundle.version is not None
  2596. BundleClient._skip_to_pack_data(pack_file, bundle.version)
  2597. # Read pack data and write it to the callback
  2598. pack_bytes = pack_file.read()
  2599. pack_data(pack_bytes)
  2600. # Apply ref filtering if specified
  2601. if ref_prefix:
  2602. filtered_refs = {}
  2603. for ref_name, ref_value in refs.items():
  2604. for prefix in ref_prefix:
  2605. if ref_name.startswith(prefix):
  2606. filtered_refs[ref_name] = ref_value
  2607. break
  2608. refs = filtered_refs
  2609. return FetchPackResult(_to_optional_dict(refs), {}, agent_string())
  2610. def get_refs(
  2611. self,
  2612. path: str | bytes,
  2613. protocol_version: int | None = None,
  2614. ref_prefix: Sequence[bytes] | None = None,
  2615. ) -> LsRemoteResult:
  2616. """Retrieve the current refs from a bundle file."""
  2617. bundle = self._open_bundle(path)
  2618. refs = dict(bundle.references)
  2619. # Apply ref filtering if specified
  2620. if ref_prefix:
  2621. filtered_refs = {}
  2622. for ref_name, ref_value in refs.items():
  2623. for prefix in ref_prefix:
  2624. if ref_name.startswith(prefix):
  2625. filtered_refs[ref_name] = ref_value
  2626. break
  2627. refs = filtered_refs
  2628. # Bundle refs are always concrete (never None), but LsRemoteResult expects Optional
  2629. return LsRemoteResult(_to_optional_dict(refs), {})
  2630. # What Git client to use for local access
  2631. default_local_git_client_cls = LocalGitClient
  2632. class SSHVendor:
  2633. """A client side SSH implementation."""
  2634. def run_command(
  2635. self,
  2636. host: str,
  2637. command: bytes,
  2638. username: str | None = None,
  2639. port: int | None = None,
  2640. password: str | None = None,
  2641. key_filename: str | None = None,
  2642. ssh_command: str | None = None,
  2643. protocol_version: int | None = None,
  2644. ) -> SubprocessWrapper:
  2645. """Connect to an SSH server.
  2646. Run a command remotely and return a file-like object for interaction
  2647. with the remote command.
  2648. Args:
  2649. host: Host name
  2650. command: Command to run (as argv array)
  2651. username: Optional ame of user to log in as
  2652. port: Optional SSH port to use
  2653. password: Optional ssh password for login or private key
  2654. key_filename: Optional path to private keyfile
  2655. ssh_command: Optional SSH command
  2656. protocol_version: Desired Git protocol version. By default the highest
  2657. mutually supported protocol version will be used.
  2658. """
  2659. raise NotImplementedError(self.run_command)
  2660. class StrangeHostname(Exception):
  2661. """Refusing to connect to strange SSH hostname."""
  2662. def __init__(self, hostname: str) -> None:
  2663. """Initialize StrangeHostname exception.
  2664. Args:
  2665. hostname: The strange hostname that was rejected
  2666. """
  2667. super().__init__(hostname)
  2668. class SubprocessSSHVendor(SSHVendor):
  2669. """SSH vendor that shells out to the local 'ssh' command."""
  2670. def run_command(
  2671. self,
  2672. host: str,
  2673. command: bytes,
  2674. username: str | None = None,
  2675. port: int | None = None,
  2676. password: str | None = None,
  2677. key_filename: str | None = None,
  2678. ssh_command: str | None = None,
  2679. protocol_version: int | None = None,
  2680. ) -> SubprocessWrapper:
  2681. """Run a git command over SSH.
  2682. Args:
  2683. host: SSH host to connect to
  2684. command: Git command to run
  2685. username: Optional username
  2686. port: Optional port number
  2687. password: Optional password (not supported)
  2688. key_filename: Optional SSH key file
  2689. ssh_command: Optional custom SSH command
  2690. protocol_version: Optional Git protocol version
  2691. Returns:
  2692. Tuple of (subprocess.Popen, Protocol, stderr_stream)
  2693. """
  2694. if password is not None:
  2695. raise NotImplementedError(
  2696. "Setting password not supported by SubprocessSSHVendor."
  2697. )
  2698. if ssh_command:
  2699. import shlex
  2700. args = [*shlex.split(ssh_command, posix=sys.platform != "win32"), "-x"]
  2701. else:
  2702. args = ["ssh", "-x"]
  2703. if port:
  2704. args.extend(["-p", str(port)])
  2705. if key_filename:
  2706. args.extend(["-i", str(key_filename)])
  2707. if protocol_version is None:
  2708. protocol_version = DEFAULT_GIT_PROTOCOL_VERSION_FETCH
  2709. if protocol_version > 0:
  2710. args.extend(["-o", f"SetEnv GIT_PROTOCOL=version={protocol_version}"])
  2711. if username:
  2712. host = f"{username}@{host}"
  2713. if host.startswith("-"):
  2714. raise StrangeHostname(hostname=host)
  2715. args.append(host)
  2716. proc = subprocess.Popen(
  2717. [*args, command],
  2718. bufsize=0,
  2719. stdin=subprocess.PIPE,
  2720. stdout=subprocess.PIPE,
  2721. stderr=subprocess.PIPE,
  2722. )
  2723. return SubprocessWrapper(proc)
  2724. class PLinkSSHVendor(SSHVendor):
  2725. """SSH vendor that shells out to the local 'plink' command."""
  2726. def run_command(
  2727. self,
  2728. host: str,
  2729. command: bytes,
  2730. username: str | None = None,
  2731. port: int | None = None,
  2732. password: str | None = None,
  2733. key_filename: str | None = None,
  2734. ssh_command: str | None = None,
  2735. protocol_version: int | None = None,
  2736. ) -> SubprocessWrapper:
  2737. """Run a git command over SSH using PLink.
  2738. Args:
  2739. host: SSH host to connect to
  2740. command: Git command to run
  2741. username: Optional username
  2742. port: Optional port number
  2743. password: Optional password
  2744. key_filename: Optional SSH key file
  2745. ssh_command: Optional custom SSH command
  2746. protocol_version: Optional Git protocol version
  2747. Returns:
  2748. Tuple of (subprocess.Popen, Protocol, stderr_stream)
  2749. """
  2750. if ssh_command:
  2751. import shlex
  2752. args = [*shlex.split(ssh_command, posix=sys.platform != "win32"), "-ssh"]
  2753. elif sys.platform == "win32":
  2754. args = ["plink.exe", "-ssh"]
  2755. else:
  2756. args = ["plink", "-ssh"]
  2757. if password is not None:
  2758. import warnings
  2759. warnings.warn(
  2760. "Invoking PLink with a password exposes the password in the "
  2761. "process list."
  2762. )
  2763. args.extend(["-pw", str(password)])
  2764. if port:
  2765. args.extend(["-P", str(port)])
  2766. if key_filename:
  2767. args.extend(["-i", str(key_filename)])
  2768. if username:
  2769. host = f"{username}@{host}"
  2770. if host.startswith("-"):
  2771. raise StrangeHostname(hostname=host)
  2772. args.append(host)
  2773. # plink.exe does not provide a way to pass environment variables
  2774. # via the command line. The best we can do is set an environment
  2775. # variable and hope that plink will pass it to the server. If this
  2776. # does not work then the server should behave as if we had requested
  2777. # protocol version 0.
  2778. env = copy.deepcopy(os.environ)
  2779. if protocol_version is None:
  2780. protocol_version = DEFAULT_GIT_PROTOCOL_VERSION_FETCH
  2781. if protocol_version > 0:
  2782. env["GIT_PROTOCOL"] = f"version={protocol_version}"
  2783. proc = subprocess.Popen(
  2784. [*args, command],
  2785. bufsize=0,
  2786. stdin=subprocess.PIPE,
  2787. stdout=subprocess.PIPE,
  2788. stderr=subprocess.PIPE,
  2789. env=env,
  2790. )
  2791. return SubprocessWrapper(proc)
  2792. # Can be overridden by users
  2793. get_ssh_vendor: Callable[[], SSHVendor] = SubprocessSSHVendor
  2794. class SSHGitClient(TraditionalGitClient):
  2795. """Git client that connects over SSH."""
  2796. def __init__(
  2797. self,
  2798. host: str,
  2799. port: int | None = None,
  2800. username: str | None = None,
  2801. vendor: SSHVendor | None = None,
  2802. config: Config | None = None,
  2803. password: str | None = None,
  2804. key_filename: str | None = None,
  2805. ssh_command: str | None = None,
  2806. path_encoding: str = TraditionalGitClient.DEFAULT_ENCODING,
  2807. thin_packs: bool = True,
  2808. report_activity: Callable[[int, str], None] | None = None,
  2809. quiet: bool = False,
  2810. include_tags: bool = False,
  2811. ) -> None:
  2812. """Initialize SSHGitClient.
  2813. Args:
  2814. host: SSH hostname
  2815. port: Optional SSH port
  2816. username: Optional username
  2817. vendor: Optional SSH vendor
  2818. config: Optional configuration
  2819. password: Optional password
  2820. key_filename: Optional SSH key file
  2821. ssh_command: Optional custom SSH command
  2822. path_encoding: Encoding for paths (default: utf-8)
  2823. thin_packs: Whether or not thin packs should be retrieved
  2824. report_activity: Optional callback for reporting transport activity
  2825. quiet: Whether to suppress output
  2826. include_tags: Send annotated tags when sending the objects they point to
  2827. """
  2828. self.host = host
  2829. self.port = port
  2830. self.username = username
  2831. self.password = password
  2832. self.key_filename = key_filename
  2833. # Priority: ssh_command parameter, then env vars, then core.sshCommand config
  2834. if ssh_command:
  2835. self.ssh_command = ssh_command
  2836. else:
  2837. # Check environment variables first
  2838. env_ssh_command = os.environ.get("GIT_SSH_COMMAND")
  2839. if env_ssh_command:
  2840. self.ssh_command = env_ssh_command
  2841. else:
  2842. env_ssh = os.environ.get("GIT_SSH")
  2843. if env_ssh:
  2844. self.ssh_command = env_ssh
  2845. else:
  2846. # Fall back to config if no environment variable set
  2847. if config is not None:
  2848. try:
  2849. config_ssh_command = config.get((b"core",), b"sshCommand")
  2850. self.ssh_command = (
  2851. config_ssh_command.decode()
  2852. if config_ssh_command
  2853. else "ssh"
  2854. )
  2855. except KeyError:
  2856. self.ssh_command = "ssh"
  2857. else:
  2858. self.ssh_command = "ssh"
  2859. super().__init__(
  2860. path_encoding=path_encoding,
  2861. thin_packs=thin_packs,
  2862. report_activity=report_activity,
  2863. quiet=quiet,
  2864. include_tags=include_tags,
  2865. )
  2866. self.alternative_paths: dict[bytes, bytes] = {}
  2867. if vendor is not None:
  2868. self.ssh_vendor = vendor
  2869. else:
  2870. self.ssh_vendor = get_ssh_vendor()
  2871. def get_url(self, path: str) -> str:
  2872. """Get the SSH URL for a path."""
  2873. netloc = self.host
  2874. if self.port is not None:
  2875. netloc += f":{self.port}"
  2876. if self.username is not None:
  2877. netloc = urlquote(self.username, "@/:") + "@" + netloc
  2878. return urlunsplit(("ssh", netloc, path, "", ""))
  2879. @classmethod
  2880. def from_parsedurl(
  2881. cls,
  2882. parsedurl: ParseResult,
  2883. thin_packs: bool = True,
  2884. report_activity: Callable[[int, str], None] | None = None,
  2885. quiet: bool = False,
  2886. include_tags: bool = False,
  2887. dumb: bool = False,
  2888. username: str | None = None,
  2889. password: str | None = None,
  2890. config: Config | None = None,
  2891. path_encoding: str = TraditionalGitClient.DEFAULT_ENCODING,
  2892. vendor: SSHVendor | None = None,
  2893. key_filename: str | None = None,
  2894. ssh_command: str | None = None,
  2895. ) -> "SSHGitClient":
  2896. """Create an SSHGitClient from a parsed URL.
  2897. Args:
  2898. parsedurl: Result of urlparse()
  2899. thin_packs: Whether or not thin packs should be retrieved
  2900. report_activity: Optional callback for reporting transport activity
  2901. quiet: Whether to suppress progress output
  2902. include_tags: Whether to include tags
  2903. dumb: Whether to use dumb protocol (not used for SSHGitClient)
  2904. username: SSH username
  2905. password: SSH password
  2906. config: Configuration object
  2907. path_encoding: Encoding for paths
  2908. vendor: SSH implementation to use
  2909. key_filename: Optional SSH key file
  2910. ssh_command: Optional custom SSH command
  2911. Returns:
  2912. An SSHGitClient instance
  2913. """
  2914. if parsedurl.hostname is None:
  2915. raise ValueError("SSH URL must have a hostname")
  2916. return cls(
  2917. host=parsedurl.hostname,
  2918. port=parsedurl.port,
  2919. username=username or parsedurl.username,
  2920. thin_packs=thin_packs,
  2921. report_activity=report_activity,
  2922. quiet=quiet,
  2923. include_tags=include_tags,
  2924. path_encoding=path_encoding,
  2925. vendor=vendor,
  2926. config=config,
  2927. password=password,
  2928. key_filename=key_filename,
  2929. ssh_command=ssh_command,
  2930. )
  2931. def _get_cmd_path(self, cmd: bytes) -> bytes:
  2932. cmd = self.alternative_paths.get(cmd, b"git-" + cmd)
  2933. assert isinstance(cmd, bytes)
  2934. return cmd
  2935. def _connect(
  2936. self,
  2937. cmd: bytes,
  2938. path: str | bytes,
  2939. protocol_version: int | None = None,
  2940. ) -> tuple[Protocol, Callable[[], bool], IO[bytes] | None]:
  2941. if not isinstance(cmd, bytes):
  2942. raise TypeError(cmd)
  2943. if isinstance(path, bytes):
  2944. path = path.decode(self._remote_path_encoding)
  2945. if path.startswith("/~"):
  2946. path = path[1:]
  2947. argv = (
  2948. self._get_cmd_path(cmd)
  2949. + b" '"
  2950. + path.encode(self._remote_path_encoding)
  2951. + b"'"
  2952. )
  2953. kwargs = {}
  2954. if self.password is not None:
  2955. kwargs["password"] = self.password
  2956. if self.key_filename is not None:
  2957. kwargs["key_filename"] = self.key_filename
  2958. # GIT_SSH_COMMAND takes precedence over GIT_SSH
  2959. if self.ssh_command is not None:
  2960. kwargs["ssh_command"] = self.ssh_command
  2961. con = self.ssh_vendor.run_command(
  2962. self.host,
  2963. argv,
  2964. port=self.port,
  2965. username=self.username,
  2966. protocol_version=protocol_version,
  2967. **kwargs,
  2968. )
  2969. return (
  2970. Protocol(
  2971. con.read,
  2972. con.write,
  2973. con.close,
  2974. report_activity=self._report_activity,
  2975. ),
  2976. con.can_read,
  2977. getattr(con, "stderr", None),
  2978. )
  2979. def default_user_agent_string() -> str:
  2980. """Return the default user agent string for Dulwich."""
  2981. # Start user agent with "git/", because GitHub requires this. :-( See
  2982. # https://github.com/jelmer/dulwich/issues/562 for details.
  2983. return "git/dulwich/{}".format(".".join([str(x) for x in dulwich.__version__]))
  2984. def _urlmatch_http_sections(
  2985. config: Config, url: str | None
  2986. ) -> Iterator[tuple[bytes, ...]]:
  2987. """Yield http config sections matching the given URL, ordered by specificity.
  2988. Yields sections from least specific to most specific, so callers can
  2989. apply settings in order with more specific settings overriding less specific ones.
  2990. Args:
  2991. config: Git configuration object
  2992. url: URL to match against config sections (if None, only yields global http section)
  2993. Yields:
  2994. Config section tuples that match the URL, ordered by specificity
  2995. """
  2996. encoding = getattr(config, "encoding", None) or sys.getdefaultencoding()
  2997. parsed_url = urlparse(url) if url else None
  2998. # Collect all matching sections with their specificity
  2999. # (specificity is based on URL path length - longer = more specific)
  3000. matching_sections: list[tuple[int, tuple[bytes, ...]]] = []
  3001. for config_section in config.sections():
  3002. if config_section[0] != b"http":
  3003. continue
  3004. if len(config_section) < 2:
  3005. # Global http section (least specific)
  3006. matching_sections.append((0, config_section))
  3007. elif parsed_url is not None:
  3008. # URL-specific http section - only match if we have a URL
  3009. config_url = config_section[1].decode(encoding)
  3010. parsed_config_url = urlparse(config_url)
  3011. is_match = False
  3012. if parsed_config_url.scheme and parsed_config_url.netloc:
  3013. is_match = match_urls(parsed_url, parsed_config_url)
  3014. else:
  3015. is_match = match_partial_url(parsed_url, config_url)
  3016. if is_match:
  3017. # Calculate specificity based on URL path length
  3018. specificity = len(parsed_config_url.path.rstrip("/"))
  3019. matching_sections.append((specificity, config_section))
  3020. # Sort by specificity (least specific first)
  3021. matching_sections.sort(key=lambda x: x[0])
  3022. for _, section in matching_sections:
  3023. yield section
  3024. def default_urllib3_manager(
  3025. config: Config | None,
  3026. pool_manager_cls: type | None = None,
  3027. proxy_manager_cls: type | None = None,
  3028. base_url: str | None = None,
  3029. timeout: float | None = None,
  3030. cert_reqs: str | None = None,
  3031. ) -> "urllib3.ProxyManager | urllib3.PoolManager":
  3032. """Return urllib3 connection pool manager.
  3033. Honour detected proxy configurations.
  3034. Args:
  3035. config: `dulwich.config.ConfigDict` instance with Git configuration.
  3036. pool_manager_cls: Pool manager class to use
  3037. proxy_manager_cls: Proxy manager class to use
  3038. base_url: Base URL for proxy bypass checks
  3039. timeout: Timeout for HTTP requests in seconds
  3040. cert_reqs: SSL certificate requirements (e.g. "CERT_REQUIRED", "CERT_NONE")
  3041. Returns:
  3042. Either pool_manager_cls (defaults to ``urllib3.ProxyManager``) instance for
  3043. proxy configurations, proxy_manager_cls
  3044. (defaults to ``urllib3.PoolManager``) instance otherwise
  3045. """
  3046. proxy_server: str | None = None
  3047. user_agent: str | None = None
  3048. ca_certs: str | None = None
  3049. ssl_verify: bool | None = None
  3050. if proxy_server is None:
  3051. for proxyname in ("https_proxy", "http_proxy", "all_proxy"):
  3052. proxy_server = os.environ.get(proxyname)
  3053. if proxy_server:
  3054. break
  3055. if proxy_server:
  3056. if check_for_proxy_bypass(base_url):
  3057. proxy_server = None
  3058. if config is not None:
  3059. # Iterate through all matching http sections from least to most specific
  3060. # More specific settings will override less specific ones
  3061. for section in _urlmatch_http_sections(config, base_url):
  3062. if proxy_server is None:
  3063. try:
  3064. proxy_server_bytes = config.get(section, b"proxy")
  3065. except KeyError:
  3066. pass
  3067. else:
  3068. if proxy_server_bytes is not None:
  3069. proxy_server = proxy_server_bytes.decode("utf-8")
  3070. try:
  3071. user_agent_bytes = config.get(section, b"useragent")
  3072. except KeyError:
  3073. pass
  3074. else:
  3075. if user_agent_bytes is not None:
  3076. user_agent = user_agent_bytes.decode("utf-8")
  3077. try:
  3078. ssl_verify_value = config.get_boolean(section, b"sslVerify")
  3079. except KeyError:
  3080. pass
  3081. else:
  3082. if ssl_verify_value is not None:
  3083. ssl_verify = ssl_verify_value
  3084. try:
  3085. ca_certs_bytes = config.get(section, b"sslCAInfo")
  3086. except KeyError:
  3087. pass
  3088. else:
  3089. if ca_certs_bytes is not None:
  3090. ca_certs = ca_certs_bytes.decode("utf-8")
  3091. if timeout is None:
  3092. try:
  3093. timeout_bytes = config.get(section, b"timeout")
  3094. except KeyError:
  3095. pass
  3096. else:
  3097. if timeout_bytes is not None:
  3098. timeout = float(timeout_bytes.decode("utf-8"))
  3099. # Default ssl_verify to True if not set
  3100. if ssl_verify is None:
  3101. ssl_verify = True
  3102. if user_agent is None:
  3103. user_agent = default_user_agent_string()
  3104. headers = {"User-agent": user_agent}
  3105. # Check for extra headers in config with URL matching
  3106. if config is not None:
  3107. # Apply extra headers from least specific to most specific
  3108. for section in _urlmatch_http_sections(config, base_url):
  3109. try:
  3110. extra_headers = config.get_multivar(section, b"extraHeader")
  3111. except KeyError:
  3112. continue
  3113. for extra_header in extra_headers:
  3114. if not extra_header:
  3115. logger.warning("Ignoring empty http.extraHeader value")
  3116. continue
  3117. if b": " not in extra_header:
  3118. logger.warning(
  3119. "Ignoring invalid http.extraHeader value %r (missing ': ' separator)",
  3120. extra_header,
  3121. )
  3122. continue
  3123. # Parse the header (format: "Header-Name: value")
  3124. header_name, header_value = extra_header.split(b": ", 1)
  3125. try:
  3126. headers[header_name.decode("utf-8")] = header_value.decode("utf-8")
  3127. except UnicodeDecodeError as e:
  3128. logger.warning(
  3129. "Ignoring http.extraHeader with invalid UTF-8: %s", e
  3130. )
  3131. kwargs: dict[str, str | float | None] = {
  3132. "ca_certs": ca_certs,
  3133. }
  3134. # Add timeout if specified
  3135. if timeout is not None:
  3136. kwargs["timeout"] = timeout
  3137. # Handle cert_reqs - allow override from parameter
  3138. if cert_reqs is not None:
  3139. kwargs["cert_reqs"] = cert_reqs
  3140. elif ssl_verify is True:
  3141. kwargs["cert_reqs"] = "CERT_REQUIRED"
  3142. elif ssl_verify is False:
  3143. kwargs["cert_reqs"] = "CERT_NONE"
  3144. else:
  3145. # Default to SSL verification
  3146. kwargs["cert_reqs"] = "CERT_REQUIRED"
  3147. import urllib3
  3148. manager: urllib3.ProxyManager | urllib3.PoolManager
  3149. if proxy_server is not None:
  3150. if proxy_manager_cls is None:
  3151. proxy_manager_cls = urllib3.ProxyManager
  3152. if not isinstance(proxy_server, str):
  3153. proxy_server = proxy_server.decode()
  3154. proxy_server_url = urlparse(proxy_server)
  3155. if proxy_server_url.username is not None:
  3156. proxy_headers = urllib3.make_headers(
  3157. proxy_basic_auth=f"{proxy_server_url.username}:{proxy_server_url.password or ''}"
  3158. )
  3159. else:
  3160. proxy_headers = {}
  3161. manager = proxy_manager_cls(
  3162. proxy_server, proxy_headers=proxy_headers, headers=headers, **kwargs
  3163. )
  3164. else:
  3165. if pool_manager_cls is None:
  3166. pool_manager_cls = urllib3.PoolManager
  3167. manager = pool_manager_cls(headers=headers, **kwargs)
  3168. return manager
  3169. def check_for_proxy_bypass(base_url: str | None) -> bool:
  3170. """Check if proxy should be bypassed for the given URL."""
  3171. # Check if a proxy bypass is defined with the no_proxy environment variable
  3172. if base_url: # only check if base_url is provided
  3173. no_proxy_str = os.environ.get("no_proxy")
  3174. if no_proxy_str:
  3175. # implementation based on curl behavior: https://curl.se/libcurl/c/CURLOPT_NOPROXY.html
  3176. # get hostname of provided parsed url
  3177. parsed_url = urlparse(base_url)
  3178. hostname = parsed_url.hostname
  3179. if hostname:
  3180. import ipaddress
  3181. # check if hostname is an ip address
  3182. try:
  3183. hostname_ip = ipaddress.ip_address(hostname)
  3184. except ValueError:
  3185. hostname_ip = None
  3186. no_proxy_values = no_proxy_str.split(",")
  3187. for no_proxy_value in no_proxy_values:
  3188. no_proxy_value = no_proxy_value.strip()
  3189. if no_proxy_value:
  3190. no_proxy_value = no_proxy_value.lower()
  3191. no_proxy_value = no_proxy_value.lstrip(
  3192. "."
  3193. ) # ignore leading dots
  3194. if hostname_ip:
  3195. # check if no_proxy_value is a ip network
  3196. try:
  3197. no_proxy_value_network = ipaddress.ip_network(
  3198. no_proxy_value, strict=False
  3199. )
  3200. except ValueError:
  3201. no_proxy_value_network = None
  3202. if no_proxy_value_network:
  3203. # if hostname is a ip address and no_proxy_value is a ip network -> check if ip address is part of network
  3204. if hostname_ip in no_proxy_value_network:
  3205. return True
  3206. if no_proxy_value == "*":
  3207. # '*' is special case for always bypass proxy
  3208. return True
  3209. if hostname == no_proxy_value:
  3210. return True
  3211. no_proxy_value = (
  3212. "." + no_proxy_value
  3213. ) # add a dot to only match complete domains
  3214. if hostname.endswith(no_proxy_value):
  3215. return True
  3216. return False
  3217. class AbstractHttpGitClient(GitClient):
  3218. """Abstract base class for HTTP Git Clients.
  3219. This is agonistic of the actual HTTP implementation.
  3220. Subclasses should provide an implementation of the
  3221. _http_request method.
  3222. """
  3223. def __init__(
  3224. self,
  3225. base_url: str,
  3226. dumb: bool = False,
  3227. thin_packs: bool = True,
  3228. report_activity: Callable[[int, str], None] | None = None,
  3229. quiet: bool = False,
  3230. include_tags: bool = False,
  3231. username: str | None = None,
  3232. password: str | None = None,
  3233. ) -> None:
  3234. """Initialize AbstractHttpGitClient."""
  3235. self._base_url = base_url.rstrip("/") + "/"
  3236. self._username = username
  3237. self._password = password
  3238. # Track original URL with credentials (set by from_parsedurl when credentials come from URL)
  3239. self._url_with_auth: str | None = None
  3240. self.dumb = dumb
  3241. GitClient.__init__(
  3242. self,
  3243. thin_packs=thin_packs,
  3244. report_activity=report_activity,
  3245. quiet=quiet,
  3246. include_tags=include_tags,
  3247. )
  3248. def _http_request(
  3249. self,
  3250. url: str,
  3251. headers: dict[str, str] | None = None,
  3252. data: bytes | Iterator[bytes] | None = None,
  3253. raise_for_status: bool = True,
  3254. ) -> tuple["HTTPResponse", Callable[[int], bytes]]:
  3255. """Perform HTTP request.
  3256. Args:
  3257. url: Request URL.
  3258. headers: Optional custom headers to override defaults.
  3259. data: Request data.
  3260. raise_for_status: Whether to raise an exception for HTTP errors.
  3261. Returns:
  3262. Tuple (response, read), where response is an urllib3
  3263. response object with additional content_type and
  3264. redirect_location properties, and read is a consumable read
  3265. method for the response data.
  3266. Raises:
  3267. GitProtocolError
  3268. """
  3269. raise NotImplementedError(self._http_request)
  3270. def _discover_references(
  3271. self,
  3272. service: bytes,
  3273. base_url: str,
  3274. protocol_version: int | None = None,
  3275. ref_prefix: Sequence[bytes] | None = None,
  3276. ) -> tuple[
  3277. dict[Ref, ObjectID | None],
  3278. set[bytes],
  3279. str,
  3280. dict[Ref, Ref],
  3281. dict[Ref, ObjectID],
  3282. ]:
  3283. if (
  3284. protocol_version is not None
  3285. and protocol_version not in GIT_PROTOCOL_VERSIONS
  3286. ):
  3287. raise ValueError(f"unknown Git protocol version {protocol_version}")
  3288. assert base_url[-1] == "/"
  3289. tail = "info/refs"
  3290. headers = {"Accept": "*/*"}
  3291. if self.dumb is not True:
  3292. tail += "?service={}".format(service.decode("ascii"))
  3293. # Enable protocol v2 only when fetching, not when pushing.
  3294. # Git does not yet implement push over protocol v2, and as of
  3295. # git version 2.37.3 git-http-backend's behaviour is erratic if
  3296. # we try: It responds with a Git-protocol-v1-style ref listing
  3297. # which lacks the "001f# service=git-receive-pack" marker.
  3298. if service == b"git-upload-pack":
  3299. if protocol_version is None:
  3300. self.protocol_version = DEFAULT_GIT_PROTOCOL_VERSION_FETCH
  3301. else:
  3302. self.protocol_version = protocol_version
  3303. if self.protocol_version == 2:
  3304. headers["Git-Protocol"] = "version=2"
  3305. else:
  3306. self.protocol_version = DEFAULT_GIT_PROTOCOL_VERSION_SEND
  3307. url = urljoin(base_url, tail)
  3308. resp, read = self._http_request(url, headers)
  3309. if resp.redirect_location:
  3310. # Something changed (redirect!), so let's update the base URL
  3311. if not resp.redirect_location.endswith(tail):
  3312. raise GitProtocolError(
  3313. f"Redirected from URL {url} to URL {resp.redirect_location} without {tail}"
  3314. )
  3315. base_url = urljoin(url, resp.redirect_location[: -len(tail)])
  3316. try:
  3317. self.dumb = resp.content_type is None or not resp.content_type.startswith(
  3318. "application/x-git-"
  3319. )
  3320. if not self.dumb:
  3321. def begin_protocol_v2(
  3322. proto: Protocol,
  3323. ) -> tuple[set[bytes], Any, Callable[[int], bytes], Protocol]:
  3324. nonlocal ref_prefix
  3325. server_capabilities = read_server_capabilities(proto.read_pkt_seq())
  3326. if ref_prefix is None:
  3327. ref_prefix = DEFAULT_REF_PREFIX
  3328. pkts = [
  3329. b"symrefs",
  3330. b"peel",
  3331. ]
  3332. for prefix in ref_prefix:
  3333. pkts.append(b"ref-prefix " + prefix)
  3334. body = b"".join(
  3335. [pkt_line(b"command=ls-refs\n"), b"0001", pkt_seq(*pkts)]
  3336. )
  3337. resp, read = self._smart_request(
  3338. service.decode("ascii"), base_url, body
  3339. )
  3340. proto = Protocol(read, lambda data: None)
  3341. return server_capabilities, resp, read, proto
  3342. proto = Protocol(read, lambda data: None)
  3343. server_protocol_version = negotiate_protocol_version(proto)
  3344. if server_protocol_version not in GIT_PROTOCOL_VERSIONS:
  3345. raise ValueError(
  3346. f"unknown Git protocol version {server_protocol_version} used by server"
  3347. )
  3348. if protocol_version and server_protocol_version > protocol_version:
  3349. raise ValueError(
  3350. f"bad Git protocol version {server_protocol_version} used by server"
  3351. )
  3352. self.protocol_version = server_protocol_version
  3353. if self.protocol_version == 2:
  3354. server_capabilities, resp, read, proto = begin_protocol_v2(proto)
  3355. (refs, symrefs, peeled) = read_pkt_refs_v2(proto.read_pkt_seq())
  3356. return refs, server_capabilities, base_url, symrefs, peeled
  3357. else:
  3358. try:
  3359. [pkt] = list(proto.read_pkt_seq())
  3360. except ValueError as exc:
  3361. raise GitProtocolError(
  3362. "unexpected number of packets received"
  3363. ) from exc
  3364. if pkt.rstrip(b"\n") != (b"# service=" + service):
  3365. raise GitProtocolError(
  3366. f"unexpected first line {pkt!r} from smart server"
  3367. )
  3368. # Github sends "version 2" after sending the service name.
  3369. # Try to negotiate protocol version 2 again.
  3370. server_protocol_version = negotiate_protocol_version(proto)
  3371. if server_protocol_version not in GIT_PROTOCOL_VERSIONS:
  3372. raise ValueError(
  3373. f"unknown Git protocol version {server_protocol_version} used by server"
  3374. )
  3375. if protocol_version and server_protocol_version > protocol_version:
  3376. raise ValueError(
  3377. f"bad Git protocol version {server_protocol_version} used by server"
  3378. )
  3379. self.protocol_version = server_protocol_version
  3380. if self.protocol_version == 2:
  3381. server_capabilities, resp, read, proto = begin_protocol_v2(
  3382. proto
  3383. )
  3384. (refs, symrefs, peeled) = read_pkt_refs_v2(proto.read_pkt_seq())
  3385. else:
  3386. (
  3387. refs_v1,
  3388. server_capabilities,
  3389. ) = read_pkt_refs_v1(proto.read_pkt_seq())
  3390. # Convert v1 refs to Optional type
  3391. refs = _to_optional_dict(refs_v1)
  3392. # TODO: split_peeled_refs should accept Optional values
  3393. (refs, peeled) = split_peeled_refs(refs) # type: ignore[arg-type,assignment]
  3394. (symrefs, _agent) = _extract_symrefs_and_agent(
  3395. server_capabilities
  3396. )
  3397. if ref_prefix is not None:
  3398. refs = filter_ref_prefix(refs, ref_prefix)
  3399. return refs, server_capabilities, base_url, symrefs, peeled
  3400. else:
  3401. self.protocol_version = 0 # dumb servers only support protocol v0
  3402. # Read all the response data
  3403. data = b""
  3404. while True:
  3405. chunk = read(4096)
  3406. if not chunk:
  3407. break
  3408. data += chunk
  3409. from typing import cast
  3410. info_refs = read_info_refs(BytesIO(data))
  3411. (refs_nonopt, peeled) = split_peeled_refs(info_refs)
  3412. if ref_prefix is not None:
  3413. refs_nonopt = filter_ref_prefix(refs_nonopt, ref_prefix)
  3414. refs_result: dict[Ref, ObjectID | None] = cast(
  3415. dict[Ref, ObjectID | None], refs_nonopt
  3416. )
  3417. return refs_result, set(), base_url, {}, peeled
  3418. finally:
  3419. resp.close()
  3420. def _smart_request(
  3421. self, service: str, url: str, data: bytes | Iterator[bytes]
  3422. ) -> tuple["HTTPResponse", Callable[[int], bytes]]:
  3423. """Send a 'smart' HTTP request.
  3424. This is a simple wrapper around _http_request that sets
  3425. a couple of extra headers.
  3426. """
  3427. assert url[-1] == "/"
  3428. url = urljoin(url, service)
  3429. result_content_type = f"application/x-{service}-result"
  3430. headers = {
  3431. "Content-Type": f"application/x-{service}-request",
  3432. "Accept": result_content_type,
  3433. }
  3434. if self.protocol_version == 2:
  3435. headers["Git-Protocol"] = "version=2"
  3436. if isinstance(data, bytes):
  3437. headers["Content-Length"] = str(len(data))
  3438. resp, read = self._http_request(url, headers, data)
  3439. if (
  3440. not resp.content_type
  3441. or resp.content_type.split(";")[0] != result_content_type
  3442. ):
  3443. raise GitProtocolError(
  3444. f"Invalid content-type from server: {resp.content_type}"
  3445. )
  3446. return resp, read
  3447. def send_pack(
  3448. self,
  3449. path: str | bytes,
  3450. update_refs: Callable[[dict[Ref, ObjectID]], dict[Ref, ObjectID]],
  3451. generate_pack_data: "GeneratePackDataFunc",
  3452. progress: Callable[[bytes], None] | None = None,
  3453. ) -> SendPackResult:
  3454. """Upload a pack to a remote repository.
  3455. Args:
  3456. path: Repository path (as bytestring or string)
  3457. update_refs: Function to determine changes to remote refs.
  3458. Receives dict with existing remote refs, returns dict with
  3459. changed refs (name -> sha, where sha=ZERO_SHA for deletions)
  3460. generate_pack_data: Function that can return a tuple
  3461. with number of elements and pack data to upload.
  3462. progress: Optional progress function
  3463. Returns:
  3464. SendPackResult
  3465. Raises:
  3466. SendPackError: if server rejects the pack data
  3467. """
  3468. url = self._get_url(path)
  3469. old_refs, server_capabilities, url, _symrefs, _peeled = (
  3470. self._discover_references(b"git-receive-pack", url)
  3471. )
  3472. (
  3473. negotiated_capabilities,
  3474. agent,
  3475. ) = self._negotiate_receive_pack_capabilities(server_capabilities)
  3476. negotiated_capabilities.add(capability_agent())
  3477. if CAPABILITY_REPORT_STATUS in negotiated_capabilities:
  3478. self._report_status_parser = ReportStatusParser()
  3479. # Assert that old_refs has no None values
  3480. assert all(v is not None for v in old_refs.values()), (
  3481. "old_refs should not contain None values"
  3482. )
  3483. old_refs_typed: dict[Ref, ObjectID] = old_refs # type: ignore[assignment]
  3484. new_refs = update_refs(dict(old_refs_typed))
  3485. if new_refs is None:
  3486. # Determine wants function is aborting the push.
  3487. # Convert to Optional type for SendPackResult
  3488. return SendPackResult(
  3489. _to_optional_dict(old_refs_typed), agent=agent, ref_status={}
  3490. )
  3491. if set(new_refs.items()).issubset(set(old_refs_typed.items())):
  3492. # Convert to Optional type for SendPackResult
  3493. return SendPackResult(
  3494. _to_optional_dict(new_refs), agent=agent, ref_status={}
  3495. )
  3496. if self.dumb:
  3497. raise NotImplementedError(self.fetch_pack)
  3498. def body_generator() -> Iterator[bytes]:
  3499. header_handler = _v1ReceivePackHeader(
  3500. list(negotiated_capabilities), old_refs_typed, new_refs
  3501. )
  3502. for pkt in header_handler:
  3503. yield pkt_line(pkt)
  3504. pack_data_count, pack_data = generate_pack_data(
  3505. header_handler.have,
  3506. header_handler.want,
  3507. ofs_delta=(CAPABILITY_OFS_DELTA in negotiated_capabilities),
  3508. progress=progress,
  3509. )
  3510. if self._should_send_pack(new_refs):
  3511. yield from PackChunkGenerator(
  3512. # TODO: Don't hardcode object format
  3513. num_records=pack_data_count,
  3514. records=pack_data,
  3515. object_format=DEFAULT_OBJECT_FORMAT,
  3516. )
  3517. resp, read = self._smart_request("git-receive-pack", url, data=body_generator())
  3518. try:
  3519. resp_proto = Protocol(read, lambda data: None)
  3520. ref_status = self._handle_receive_pack_tail(
  3521. resp_proto, negotiated_capabilities, progress
  3522. )
  3523. # Convert to Optional type for SendPackResult
  3524. return SendPackResult(
  3525. _to_optional_dict(new_refs), agent=agent, ref_status=ref_status
  3526. )
  3527. finally:
  3528. resp.close()
  3529. def fetch_pack(
  3530. self,
  3531. path: str | bytes,
  3532. determine_wants: "DetermineWantsFunc",
  3533. graph_walker: GraphWalker,
  3534. pack_data: Callable[[bytes], int],
  3535. progress: Callable[[bytes], None] | None = None,
  3536. depth: int | None = None,
  3537. ref_prefix: Sequence[bytes] | None = None,
  3538. filter_spec: bytes | None = None,
  3539. protocol_version: int | None = None,
  3540. shallow_since: str | None = None,
  3541. shallow_exclude: list[str] | None = None,
  3542. ) -> FetchPackResult:
  3543. """Retrieve a pack from a git smart server.
  3544. Args:
  3545. path: Path to fetch from
  3546. determine_wants: Callback that returns list of commits to fetch
  3547. graph_walker: Object with next() and ack().
  3548. pack_data: Callback called for each bit of data in the pack
  3549. progress: Callback for progress reports (strings)
  3550. depth: Depth for request
  3551. ref_prefix: List of prefixes of desired references, as a list of
  3552. bytestrings. Filtering is done by the server if supported, and
  3553. client side otherwise.
  3554. filter_spec: A git-rev-list-style object filter spec, as bytestring.
  3555. Only used if the server supports the Git protocol-v2 'filter'
  3556. feature, and ignored otherwise.
  3557. protocol_version: Desired Git protocol version. By default the highest
  3558. mutually supported protocol version will be used.
  3559. shallow_since: Deepen the history to include commits after this date
  3560. shallow_exclude: Deepen the history to exclude commits reachable from these refs
  3561. Returns:
  3562. FetchPackResult object
  3563. """
  3564. url = self._get_url(path)
  3565. refs, server_capabilities, url, symrefs, _peeled = self._discover_references(
  3566. b"git-upload-pack",
  3567. url,
  3568. protocol_version=protocol_version,
  3569. ref_prefix=ref_prefix,
  3570. )
  3571. (
  3572. negotiated_capabilities,
  3573. capa_symrefs,
  3574. agent,
  3575. ) = self._negotiate_upload_pack_capabilities(server_capabilities)
  3576. object_format = extract_object_format_from_capabilities(server_capabilities)
  3577. if not symrefs and capa_symrefs:
  3578. symrefs = capa_symrefs
  3579. # Filter out None values from refs for determine_wants
  3580. refs_filtered = {k: v for k, v in refs.items() if v is not None}
  3581. if depth is not None:
  3582. wants = determine_wants(refs_filtered, depth=depth)
  3583. else:
  3584. wants = determine_wants(refs_filtered)
  3585. if wants is not None:
  3586. wants = [cid for cid in wants if cid != ZERO_SHA]
  3587. if not wants and not self.dumb:
  3588. return FetchPackResult(refs, symrefs, agent, object_format=object_format)
  3589. elif self.dumb:
  3590. # Use dumb HTTP protocol
  3591. from .dumb import DumbRemoteHTTPRepo
  3592. # Pass http_request function
  3593. dumb_repo = DumbRemoteHTTPRepo(
  3594. url, functools.partial(self._http_request, raise_for_status=False)
  3595. )
  3596. # Fetch pack data from dumb remote
  3597. pack_data_list = list(
  3598. dumb_repo.fetch_pack_data(
  3599. lambda refs, depth: wants,
  3600. graph_walker,
  3601. progress=progress,
  3602. depth=depth,
  3603. )
  3604. )
  3605. symrefs[HEADREF] = dumb_repo.get_head()
  3606. # Write pack data
  3607. if pack_data_list:
  3608. from .pack import write_pack_data
  3609. # Wrap pack_data to match expected signature
  3610. def write_fn(data: bytes) -> None:
  3611. pack_data(data)
  3612. # Write pack data directly using the unpacked objects
  3613. write_pack_data(
  3614. write_fn,
  3615. iter(pack_data_list),
  3616. num_records=len(pack_data_list),
  3617. progress=progress,
  3618. object_format=DEFAULT_OBJECT_FORMAT,
  3619. )
  3620. return FetchPackResult(refs, symrefs, agent, object_format=object_format)
  3621. req_data = BytesIO()
  3622. req_proto = Protocol(None, req_data.write) # type: ignore
  3623. (new_shallow, new_unshallow) = _handle_upload_pack_head(
  3624. req_proto,
  3625. negotiated_capabilities,
  3626. graph_walker,
  3627. wants,
  3628. can_read=None,
  3629. depth=depth,
  3630. protocol_version=self.protocol_version,
  3631. shallow_since=shallow_since,
  3632. shallow_exclude=shallow_exclude,
  3633. )
  3634. if self.protocol_version == 2:
  3635. data = pkt_line(b"command=fetch\n") + b"0001"
  3636. if CAPABILITY_THIN_PACK in self._fetch_capabilities:
  3637. data += pkt_line(b"thin-pack\n")
  3638. if (
  3639. find_capability(
  3640. negotiated_capabilities, CAPABILITY_FETCH, CAPABILITY_FILTER
  3641. )
  3642. and filter_spec
  3643. ):
  3644. data += pkt_line(b"filter %s\n" % filter_spec)
  3645. elif filter_spec:
  3646. self._warn_filter_objects()
  3647. data += req_data.getvalue()
  3648. else:
  3649. if filter_spec:
  3650. self._warn_filter_objects()
  3651. data = req_data.getvalue()
  3652. resp, read = self._smart_request("git-upload-pack", url, data)
  3653. try:
  3654. resp_proto = Protocol(read, None) # type: ignore
  3655. if new_shallow is None and new_unshallow is None:
  3656. (new_shallow, new_unshallow) = _read_shallow_updates(
  3657. resp_proto.read_pkt_seq()
  3658. )
  3659. _handle_upload_pack_tail(
  3660. resp_proto,
  3661. negotiated_capabilities,
  3662. graph_walker,
  3663. pack_data,
  3664. progress,
  3665. protocol_version=self.protocol_version,
  3666. )
  3667. return FetchPackResult(
  3668. refs, symrefs, agent, new_shallow, new_unshallow, object_format
  3669. )
  3670. finally:
  3671. resp.close()
  3672. def get_refs(
  3673. self,
  3674. path: str | bytes,
  3675. protocol_version: int | None = None,
  3676. ref_prefix: Sequence[bytes] | None = None,
  3677. ) -> LsRemoteResult:
  3678. """Retrieve the current refs from a git smart server."""
  3679. url = self._get_url(path)
  3680. refs, server_capabilities, _, symrefs, peeled = self._discover_references(
  3681. b"git-upload-pack",
  3682. url,
  3683. protocol_version=protocol_version,
  3684. ref_prefix=ref_prefix,
  3685. )
  3686. object_format = extract_object_format_from_capabilities(server_capabilities)
  3687. for refname, refvalue in peeled.items():
  3688. refs[Ref(refname + PEELED_TAG_SUFFIX)] = refvalue
  3689. return LsRemoteResult(refs, symrefs, object_format=object_format)
  3690. def get_url(self, path: str) -> str:
  3691. """Get the HTTP URL for a path."""
  3692. url = self._get_url(path).rstrip("/")
  3693. # Include credentials in the URL only if they came from a URL (not passed explicitly)
  3694. # This preserves credentials that were in the original URL for git config storage
  3695. if self._url_with_auth is not None:
  3696. from urllib.parse import quote, urlparse, urlunparse
  3697. assert self._username is not None
  3698. parsed = urlparse(url)
  3699. # Construct netloc with credentials
  3700. if self._password is not None:
  3701. netloc = f"{quote(self._username, safe='')}:{quote(self._password, safe='')}@{parsed.hostname}"
  3702. else:
  3703. netloc = f"{quote(self._username, safe='')}@{parsed.hostname}"
  3704. if parsed.port:
  3705. netloc += f":{parsed.port}"
  3706. # Reconstruct URL with credentials
  3707. url = urlunparse(
  3708. (
  3709. parsed.scheme,
  3710. netloc,
  3711. parsed.path,
  3712. parsed.params,
  3713. parsed.query,
  3714. parsed.fragment,
  3715. )
  3716. )
  3717. return url
  3718. def _get_url(self, path: str | bytes) -> str:
  3719. path_str = path if isinstance(path, str) else path.decode("utf-8")
  3720. return urljoin(self._base_url, path_str).rstrip("/") + "/"
  3721. @classmethod
  3722. def from_parsedurl(
  3723. cls,
  3724. parsedurl: ParseResult,
  3725. thin_packs: bool = True,
  3726. report_activity: Callable[[int, str], None] | None = None,
  3727. quiet: bool = False,
  3728. include_tags: bool = False,
  3729. dumb: bool = False,
  3730. username: str | None = None,
  3731. password: str | None = None,
  3732. config: Config | None = None,
  3733. pool_manager: "urllib3.PoolManager | None" = None,
  3734. ) -> "AbstractHttpGitClient":
  3735. """Create an AbstractHttpGitClient from a parsed URL.
  3736. Args:
  3737. parsedurl: Result of urlparse()
  3738. thin_packs: Whether or not thin packs should be retrieved
  3739. report_activity: Optional callback for reporting transport activity
  3740. quiet: Whether to suppress progress output
  3741. include_tags: Whether to include tags
  3742. dumb: Whether to use dumb HTTP transport
  3743. username: Optional username for authentication
  3744. password: Optional password for authentication
  3745. config: Configuration object
  3746. pool_manager: Optional urllib3 PoolManager for HTTP(S) connections
  3747. Returns:
  3748. An AbstractHttpGitClient instance
  3749. """
  3750. # Extract credentials from URL if present
  3751. # ParseResult.username and .password are URL-encoded, need to unquote them
  3752. from urllib.parse import unquote
  3753. url_username = unquote(parsedurl.username) if parsedurl.username else None
  3754. url_password = unquote(parsedurl.password) if parsedurl.password else None
  3755. # Explicit parameters take precedence over URL credentials
  3756. final_username = username if username is not None else url_username
  3757. final_password = password if password is not None else url_password
  3758. # Remove credentials from URL for base_url
  3759. hostname = parsedurl.hostname or ""
  3760. base_parsed = parsedurl._replace(netloc=hostname)
  3761. if parsedurl.port:
  3762. base_parsed = base_parsed._replace(netloc=f"{hostname}:{parsedurl.port}")
  3763. # Pass credentials to constructor if it's a subclass that supports them
  3764. if issubclass(cls, Urllib3HttpGitClient):
  3765. client: AbstractHttpGitClient = cls(
  3766. urlunparse(base_parsed),
  3767. dumb=dumb,
  3768. thin_packs=thin_packs,
  3769. report_activity=report_activity,
  3770. quiet=quiet,
  3771. include_tags=include_tags,
  3772. username=final_username,
  3773. password=final_password,
  3774. config=config,
  3775. pool_manager=pool_manager,
  3776. )
  3777. else:
  3778. # Base class now supports credentials in constructor
  3779. client = cls(
  3780. urlunparse(base_parsed),
  3781. dumb=dumb,
  3782. thin_packs=thin_packs,
  3783. report_activity=report_activity,
  3784. quiet=quiet,
  3785. include_tags=include_tags,
  3786. username=final_username,
  3787. password=final_password,
  3788. )
  3789. # Mark that credentials came from URL (not passed explicitly) if URL had credentials
  3790. if url_username is not None or url_password is not None:
  3791. client._url_with_auth = urlunparse(parsedurl)
  3792. return client
  3793. def __repr__(self) -> str:
  3794. """Return string representation of this client."""
  3795. return f"{type(self).__name__}({self._base_url!r}, dumb={self.dumb!r})"
  3796. def _wrap_urllib3_exceptions(
  3797. func: Callable[..., bytes],
  3798. ) -> Callable[..., bytes]:
  3799. from urllib3.exceptions import ProtocolError
  3800. def wrapper(*args: object, **kwargs: object) -> bytes:
  3801. try:
  3802. return func(*args, **kwargs)
  3803. except ProtocolError as error:
  3804. raise GitProtocolError(str(error)) from error
  3805. return wrapper
  3806. class Urllib3HttpGitClient(AbstractHttpGitClient):
  3807. """Git client that uses urllib3 for HTTP(S) connections."""
  3808. def __init__(
  3809. self,
  3810. base_url: str,
  3811. dumb: bool | None = None,
  3812. pool_manager: "urllib3.PoolManager | None" = None,
  3813. config: Config | None = None,
  3814. username: str | None = None,
  3815. password: str | None = None,
  3816. timeout: float | None = None,
  3817. extra_headers: dict[str, str] | None = None,
  3818. thin_packs: bool = True,
  3819. report_activity: Callable[[int, str], None] | None = None,
  3820. quiet: bool = False,
  3821. include_tags: bool = False,
  3822. ) -> None:
  3823. """Initialize Urllib3HttpGitClient."""
  3824. self._timeout = timeout
  3825. self._extra_headers = extra_headers or {}
  3826. if pool_manager is None:
  3827. self.pool_manager = default_urllib3_manager(
  3828. config, base_url=base_url, timeout=timeout
  3829. )
  3830. else:
  3831. self.pool_manager = pool_manager
  3832. if username is not None:
  3833. # No escaping needed: ":" is not allowed in username:
  3834. # https://tools.ietf.org/html/rfc2617#section-2
  3835. credentials = f"{username}:{password or ''}"
  3836. import urllib3.util
  3837. basic_auth = urllib3.util.make_headers(basic_auth=credentials)
  3838. self.pool_manager.headers.update(basic_auth) # type: ignore
  3839. self.config = config
  3840. super().__init__(
  3841. base_url=base_url,
  3842. dumb=dumb if dumb is not None else False,
  3843. thin_packs=thin_packs,
  3844. report_activity=report_activity,
  3845. quiet=quiet,
  3846. include_tags=include_tags,
  3847. username=username,
  3848. password=password,
  3849. )
  3850. def _get_url(self, path: str | bytes) -> str:
  3851. if not isinstance(path, str):
  3852. # urllib3.util.url._encode_invalid_chars() converts the path back
  3853. # to bytes using the utf-8 codec.
  3854. path = path.decode("utf-8")
  3855. return urljoin(self._base_url, path).rstrip("/") + "/"
  3856. def _http_request(
  3857. self,
  3858. url: str,
  3859. headers: dict[str, str] | None = None,
  3860. data: bytes | Iterator[bytes] | None = None,
  3861. raise_for_status: bool = True,
  3862. ) -> tuple["HTTPResponse", Callable[[int], bytes]]:
  3863. import urllib3.exceptions
  3864. req_headers = dict(self.pool_manager.headers)
  3865. if headers is not None:
  3866. req_headers.update(headers)
  3867. req_headers["Pragma"] = "no-cache"
  3868. try:
  3869. request_kwargs = {
  3870. "headers": req_headers,
  3871. "preload_content": False,
  3872. }
  3873. if self._timeout is not None:
  3874. request_kwargs["timeout"] = self._timeout
  3875. if data is None:
  3876. resp = self.pool_manager.request("GET", url, **request_kwargs) # type: ignore[arg-type]
  3877. else:
  3878. request_kwargs["body"] = data
  3879. resp = self.pool_manager.request("POST", url, **request_kwargs) # type: ignore[arg-type]
  3880. except urllib3.exceptions.HTTPError as e:
  3881. raise GitProtocolError(str(e)) from e
  3882. if raise_for_status:
  3883. if resp.status == 404:
  3884. raise NotGitRepository
  3885. if resp.status == 401:
  3886. raise HTTPUnauthorized(resp.headers.get("WWW-Authenticate"), url)
  3887. if resp.status == 407:
  3888. raise HTTPProxyUnauthorized(resp.headers.get("Proxy-Authenticate"), url)
  3889. if resp.status != 200:
  3890. raise GitProtocolError(f"unexpected http resp {resp.status} for {url}")
  3891. resp.content_type = resp.headers.get("Content-Type") # type: ignore[attr-defined]
  3892. # Check if geturl() is available (urllib3 version >= 1.23)
  3893. try:
  3894. resp_url = resp.geturl()
  3895. except AttributeError:
  3896. # get_redirect_location() is available for urllib3 >= 1.1
  3897. resp.redirect_location = resp.get_redirect_location() # type: ignore[attr-defined]
  3898. else:
  3899. resp.redirect_location = resp_url if resp_url != url else "" # type: ignore[attr-defined]
  3900. return resp, _wrap_urllib3_exceptions(resp.read) # type: ignore[return-value]
  3901. HttpGitClient = Urllib3HttpGitClient
  3902. def _win32_url_to_path(parsed: ParseResult) -> str:
  3903. """Convert a file: URL to a path.
  3904. https://datatracker.ietf.org/doc/html/rfc8089
  3905. """
  3906. assert parsed.scheme == "file"
  3907. _, netloc, path, _, _, _ = parsed
  3908. if netloc == "localhost" or not netloc:
  3909. netloc = ""
  3910. elif (
  3911. netloc
  3912. and len(netloc) >= 2
  3913. and netloc[0].isalpha()
  3914. and netloc[1:2] in (":", ":/")
  3915. ):
  3916. # file://C:/foo.bar/baz or file://C://foo.bar//baz
  3917. netloc = netloc[:2]
  3918. else:
  3919. raise NotImplementedError("Non-local file URLs are not supported")
  3920. from nturl2path import url2pathname
  3921. return url2pathname(netloc + path)
  3922. def get_transport_and_path_from_url(
  3923. url: str,
  3924. config: Config | None = None,
  3925. operation: str | None = None,
  3926. thin_packs: bool = True,
  3927. report_activity: Callable[[int, str], None] | None = None,
  3928. quiet: bool = False,
  3929. include_tags: bool = False,
  3930. username: str | None = None,
  3931. password: str | None = None,
  3932. key_filename: str | None = None,
  3933. ssh_command: str | None = None,
  3934. pool_manager: "urllib3.PoolManager | None" = None,
  3935. ) -> tuple[GitClient, str]:
  3936. """Obtain a git client from a URL.
  3937. Args:
  3938. url: URL to open (a unicode string)
  3939. config: Optional config object
  3940. operation: Kind of operation that'll be performed; "pull" or "push"
  3941. thin_packs: Whether or not thin packs should be retrieved
  3942. report_activity: Optional callback for reporting transport activity
  3943. quiet: Whether to suppress output
  3944. include_tags: Send annotated tags when sending the objects they point to
  3945. username: Optional username for authentication
  3946. password: Optional password for authentication
  3947. key_filename: Optional SSH key file
  3948. ssh_command: Optional custom SSH command
  3949. pool_manager: Optional urllib3 PoolManager for HTTP(S) connections
  3950. Returns:
  3951. Tuple with client instance and relative path.
  3952. """
  3953. if config is not None:
  3954. url = apply_instead_of(config, url, push=(operation == "push"))
  3955. return _get_transport_and_path_from_url(
  3956. url,
  3957. config=config,
  3958. operation=operation,
  3959. thin_packs=thin_packs,
  3960. report_activity=report_activity,
  3961. quiet=quiet,
  3962. include_tags=include_tags,
  3963. username=username,
  3964. password=password,
  3965. key_filename=key_filename,
  3966. ssh_command=ssh_command,
  3967. pool_manager=pool_manager,
  3968. )
  3969. def _get_transport_and_path_from_url(
  3970. url: str,
  3971. config: Config | None,
  3972. operation: str | None,
  3973. thin_packs: bool = True,
  3974. report_activity: Callable[[int, str], None] | None = None,
  3975. quiet: bool = False,
  3976. include_tags: bool = False,
  3977. username: str | None = None,
  3978. password: str | None = None,
  3979. key_filename: str | None = None,
  3980. ssh_command: str | None = None,
  3981. pool_manager: "urllib3.PoolManager | None" = None,
  3982. ) -> tuple[GitClient, str]:
  3983. parsed = urlparse(url)
  3984. if parsed.scheme == "git":
  3985. return (
  3986. TCPGitClient.from_parsedurl(
  3987. parsed,
  3988. thin_packs=thin_packs,
  3989. report_activity=report_activity,
  3990. quiet=quiet,
  3991. include_tags=include_tags,
  3992. ),
  3993. parsed.path,
  3994. )
  3995. elif parsed.scheme in ("git+ssh", "ssh"):
  3996. return SSHGitClient.from_parsedurl(
  3997. parsed,
  3998. config=config,
  3999. username=username,
  4000. password=password,
  4001. thin_packs=thin_packs,
  4002. report_activity=report_activity,
  4003. quiet=quiet,
  4004. include_tags=include_tags,
  4005. key_filename=key_filename,
  4006. ssh_command=ssh_command,
  4007. ), parsed.path
  4008. elif parsed.scheme in ("http", "https"):
  4009. return (
  4010. HttpGitClient.from_parsedurl(
  4011. parsed,
  4012. config=config,
  4013. username=username,
  4014. password=password,
  4015. thin_packs=thin_packs,
  4016. report_activity=report_activity,
  4017. quiet=quiet,
  4018. include_tags=include_tags,
  4019. pool_manager=pool_manager,
  4020. ),
  4021. parsed.path,
  4022. )
  4023. elif parsed.scheme == "file":
  4024. if sys.platform == "win32" or os.name == "nt":
  4025. return default_local_git_client_cls(
  4026. thin_packs=thin_packs,
  4027. report_activity=report_activity,
  4028. quiet=quiet,
  4029. include_tags=include_tags,
  4030. ), _win32_url_to_path(parsed)
  4031. return (
  4032. default_local_git_client_cls.from_parsedurl(
  4033. parsed,
  4034. thin_packs=thin_packs,
  4035. report_activity=report_activity,
  4036. quiet=quiet,
  4037. include_tags=include_tags,
  4038. ),
  4039. parsed.path,
  4040. )
  4041. raise ValueError(f"unknown scheme '{parsed.scheme}'")
  4042. def parse_rsync_url(location: str) -> tuple[str | None, str, str]:
  4043. """Parse a rsync-style URL."""
  4044. if ":" in location and "@" not in location:
  4045. # SSH with no user@, zero or one leading slash.
  4046. (host, path) = location.split(":", 1)
  4047. user = None
  4048. elif ":" in location:
  4049. # SSH with user@host:foo.
  4050. user_host, path = location.split(":", 1)
  4051. if "@" in user_host:
  4052. user, host = user_host.rsplit("@", 1)
  4053. else:
  4054. user = None
  4055. host = user_host
  4056. else:
  4057. raise ValueError("not a valid rsync-style URL")
  4058. return (user, host, path)
  4059. def get_transport_and_path(
  4060. location: str,
  4061. config: Config | None = None,
  4062. operation: str | None = None,
  4063. thin_packs: bool = True,
  4064. report_activity: Callable[[int, str], None] | None = None,
  4065. quiet: bool = False,
  4066. include_tags: bool = False,
  4067. username: str | None = None,
  4068. password: str | None = None,
  4069. key_filename: str | None = None,
  4070. ssh_command: str | None = None,
  4071. pool_manager: "urllib3.PoolManager | None" = None,
  4072. ) -> tuple[GitClient, str]:
  4073. """Obtain a git client from a URL.
  4074. Args:
  4075. location: URL or path (a string)
  4076. config: Optional config object
  4077. operation: Kind of operation that'll be performed; "pull" or "push"
  4078. thin_packs: Whether or not thin packs should be retrieved
  4079. report_activity: Optional callback for reporting transport activity
  4080. quiet: Whether to suppress output
  4081. include_tags: Send annotated tags when sending the objects they point to
  4082. username: Optional username for authentication
  4083. password: Optional password for authentication
  4084. key_filename: Optional SSH key file
  4085. ssh_command: Optional custom SSH command
  4086. pool_manager: Optional urllib3 PoolManager for HTTP(S) connections
  4087. Returns:
  4088. Tuple with client instance and relative path.
  4089. """
  4090. if config is not None:
  4091. location = apply_instead_of(config, location, push=(operation == "push"))
  4092. # First, try to parse it as a URL
  4093. try:
  4094. return _get_transport_and_path_from_url(
  4095. location,
  4096. config=config,
  4097. operation=operation,
  4098. thin_packs=thin_packs,
  4099. report_activity=report_activity,
  4100. quiet=quiet,
  4101. include_tags=include_tags,
  4102. username=username,
  4103. password=password,
  4104. key_filename=key_filename,
  4105. ssh_command=ssh_command,
  4106. pool_manager=pool_manager,
  4107. )
  4108. except ValueError:
  4109. pass
  4110. if sys.platform == "win32" and location[0].isalpha() and location[1:3] == ":\\":
  4111. # Windows local path - but check if it's a bundle file first
  4112. if BundleClient._is_bundle_file(location):
  4113. return BundleClient(
  4114. thin_packs=thin_packs,
  4115. report_activity=report_activity,
  4116. quiet=quiet,
  4117. include_tags=include_tags,
  4118. ), location
  4119. return default_local_git_client_cls(
  4120. thin_packs=thin_packs,
  4121. report_activity=report_activity,
  4122. quiet=quiet,
  4123. include_tags=include_tags,
  4124. ), location
  4125. try:
  4126. (rsync_username, hostname, path) = parse_rsync_url(location)
  4127. except ValueError:
  4128. # Check if it's a bundle file before assuming it's a local path
  4129. if BundleClient._is_bundle_file(location):
  4130. return BundleClient(
  4131. thin_packs=thin_packs,
  4132. report_activity=report_activity,
  4133. quiet=quiet,
  4134. include_tags=include_tags,
  4135. ), location
  4136. # Otherwise, assume it's a local path.
  4137. return default_local_git_client_cls(
  4138. thin_packs=thin_packs,
  4139. report_activity=report_activity,
  4140. quiet=quiet,
  4141. include_tags=include_tags,
  4142. ), location
  4143. else:
  4144. return SSHGitClient(
  4145. hostname,
  4146. username=rsync_username or username,
  4147. config=config,
  4148. password=password,
  4149. key_filename=key_filename,
  4150. ssh_command=ssh_command,
  4151. thin_packs=thin_packs,
  4152. report_activity=report_activity,
  4153. quiet=quiet,
  4154. include_tags=include_tags,
  4155. ), path
  4156. DEFAULT_GIT_CREDENTIALS_PATHS = [
  4157. os.path.expanduser("~/.git-credentials"),
  4158. get_xdg_config_home_path("git", "credentials"),
  4159. ]
  4160. def get_credentials_from_store(
  4161. scheme: str,
  4162. hostname: str,
  4163. username: str | None = None,
  4164. fnames: list[str] = DEFAULT_GIT_CREDENTIALS_PATHS,
  4165. ) -> Iterator[tuple[str, str]]:
  4166. """Read credentials from a Git credential store."""
  4167. for fname in fnames:
  4168. try:
  4169. with open(fname, "rb") as f:
  4170. for line in f:
  4171. line_str = line.strip().decode("utf-8")
  4172. parsed_line = urlparse(line_str)
  4173. if (
  4174. parsed_line.scheme == scheme
  4175. and parsed_line.hostname == hostname
  4176. and (username is None or parsed_line.username == username)
  4177. ):
  4178. if parsed_line.username and parsed_line.password:
  4179. yield parsed_line.username, parsed_line.password
  4180. except FileNotFoundError:
  4181. # If the file doesn't exist, try the next one.
  4182. continue