client.py 175 KB

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