client.py 160 KB

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