client.py 164 KB

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