client.py 159 KB

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