client.py 102 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034
  1. # client.py -- Implementation of the client side git protocols
  2. # Copyright (C) 2008-2013 Jelmer Vernooij <jelmer@jelmer.uk>
  3. #
  4. # Dulwich is dual-licensed under the Apache License, Version 2.0 and the GNU
  5. # General Public License as public by the Free Software Foundation; version 2.0
  6. # or (at your option) any later version. You can redistribute it and/or
  7. # modify it under the terms of either of these two licenses.
  8. #
  9. # Unless required by applicable law or agreed to in writing, software
  10. # distributed under the License is distributed on an "AS IS" BASIS,
  11. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. # See the License for the specific language governing permissions and
  13. # limitations under the License.
  14. #
  15. # You should have received a copy of the licenses; if not, see
  16. # <http://www.gnu.org/licenses/> for a copy of the GNU General Public License
  17. # and <http://www.apache.org/licenses/LICENSE-2.0> for a copy of the Apache
  18. # License, Version 2.0.
  19. #
  20. """Client side support for the Git protocol.
  21. The Dulwich client supports the following capabilities:
  22. * thin-pack
  23. * multi_ack_detailed
  24. * multi_ack
  25. * side-band-64k
  26. * ofs-delta
  27. * quiet
  28. * report-status
  29. * delete-refs
  30. * shallow
  31. Known capabilities that are not supported:
  32. * no-progress
  33. * include-tag
  34. """
  35. import copy
  36. import logging
  37. import os
  38. import select
  39. import socket
  40. import subprocess
  41. import sys
  42. from collections.abc import Iterable, Iterator
  43. from contextlib import closing
  44. from io import BufferedReader, BytesIO
  45. from typing import (
  46. IO,
  47. TYPE_CHECKING,
  48. Callable,
  49. ClassVar,
  50. Optional,
  51. Union,
  52. )
  53. from urllib.parse import quote as urlquote
  54. from urllib.parse import unquote as urlunquote
  55. from urllib.parse import urljoin, urlparse, urlunparse, urlunsplit
  56. if TYPE_CHECKING:
  57. import urllib3
  58. import dulwich
  59. from .config import Config, apply_instead_of, get_xdg_config_home_path
  60. from .errors import GitProtocolError, NotGitRepository, SendPackError
  61. from .pack import (
  62. PACK_SPOOL_FILE_MAX_SIZE,
  63. PackChunkGenerator,
  64. UnpackedObject,
  65. write_pack_from_container,
  66. )
  67. from .protocol import (
  68. _RBUFSIZE,
  69. CAPABILITIES_REF,
  70. CAPABILITY_AGENT,
  71. CAPABILITY_DELETE_REFS,
  72. CAPABILITY_FETCH,
  73. CAPABILITY_FILTER,
  74. CAPABILITY_INCLUDE_TAG,
  75. CAPABILITY_MULTI_ACK,
  76. CAPABILITY_MULTI_ACK_DETAILED,
  77. CAPABILITY_OFS_DELTA,
  78. CAPABILITY_QUIET,
  79. CAPABILITY_REPORT_STATUS,
  80. CAPABILITY_SHALLOW,
  81. CAPABILITY_SIDE_BAND_64K,
  82. CAPABILITY_SYMREF,
  83. CAPABILITY_THIN_PACK,
  84. COMMAND_DEEPEN,
  85. COMMAND_DONE,
  86. COMMAND_HAVE,
  87. COMMAND_SHALLOW,
  88. COMMAND_UNSHALLOW,
  89. COMMAND_WANT,
  90. DEFAULT_GIT_PROTOCOL_VERSION_FETCH,
  91. DEFAULT_GIT_PROTOCOL_VERSION_SEND,
  92. GIT_PROTOCOL_VERSIONS,
  93. KNOWN_RECEIVE_CAPABILITIES,
  94. KNOWN_UPLOAD_CAPABILITIES,
  95. SIDE_BAND_CHANNEL_DATA,
  96. SIDE_BAND_CHANNEL_FATAL,
  97. SIDE_BAND_CHANNEL_PROGRESS,
  98. TCP_GIT_PORT,
  99. ZERO_SHA,
  100. HangupException,
  101. PktLineParser,
  102. Protocol,
  103. agent_string,
  104. capability_agent,
  105. extract_capabilities,
  106. extract_capability_names,
  107. filter_ref_prefix,
  108. parse_capability,
  109. pkt_line,
  110. pkt_seq,
  111. )
  112. from .refs import (
  113. PEELED_TAG_SUFFIX,
  114. Ref,
  115. _import_remote_refs,
  116. _set_default_branch,
  117. _set_head,
  118. _set_origin_head,
  119. read_info_refs,
  120. split_peeled_refs,
  121. )
  122. from .repo import Repo
  123. # Default ref prefix, used if none is specified.
  124. # GitHub defaults to just sending HEAD if no ref-prefix is
  125. # specified, so explicitly request all refs to match
  126. # behaviour with v1 when no ref-prefix is specified.
  127. DEFAULT_REF_PREFIX = [b"HEAD", b"refs/"]
  128. ObjectID = bytes
  129. # url2pathname is lazily imported
  130. url2pathname = None
  131. logger = logging.getLogger(__name__)
  132. class InvalidWants(Exception):
  133. """Invalid wants."""
  134. def __init__(self, wants) -> None:
  135. Exception.__init__(
  136. self, f"requested wants not in server provided refs: {wants!r}"
  137. )
  138. class HTTPUnauthorized(Exception):
  139. """Raised when authentication fails."""
  140. def __init__(self, www_authenticate, url) -> None:
  141. Exception.__init__(self, "No valid credentials provided")
  142. self.www_authenticate = www_authenticate
  143. self.url = url
  144. class HTTPProxyUnauthorized(Exception):
  145. """Raised when proxy authentication fails."""
  146. def __init__(self, proxy_authenticate, url) -> None:
  147. Exception.__init__(self, "No valid proxy credentials provided")
  148. self.proxy_authenticate = proxy_authenticate
  149. self.url = url
  150. def _fileno_can_read(fileno):
  151. """Check if a file descriptor is readable."""
  152. return len(select.select([fileno], [], [], 0)[0]) > 0
  153. def _win32_peek_avail(handle):
  154. """Wrapper around PeekNamedPipe to check how many bytes are available."""
  155. from ctypes import byref, windll, wintypes
  156. c_avail = wintypes.DWORD()
  157. c_message = wintypes.DWORD()
  158. success = windll.kernel32.PeekNamedPipe(
  159. handle, None, 0, None, byref(c_avail), byref(c_message)
  160. )
  161. if not success:
  162. raise OSError(wintypes.GetLastError())
  163. return c_avail.value
  164. COMMON_CAPABILITIES = [CAPABILITY_OFS_DELTA, CAPABILITY_SIDE_BAND_64K]
  165. UPLOAD_CAPABILITIES = [
  166. CAPABILITY_THIN_PACK,
  167. CAPABILITY_MULTI_ACK,
  168. CAPABILITY_MULTI_ACK_DETAILED,
  169. CAPABILITY_SHALLOW,
  170. *COMMON_CAPABILITIES,
  171. ]
  172. RECEIVE_CAPABILITIES = [
  173. CAPABILITY_REPORT_STATUS,
  174. CAPABILITY_DELETE_REFS,
  175. *COMMON_CAPABILITIES,
  176. ]
  177. class ReportStatusParser:
  178. """Handle status as reported by servers with 'report-status' capability."""
  179. def __init__(self) -> None:
  180. self._done = False
  181. self._pack_status = None
  182. self._ref_statuses: list[bytes] = []
  183. def check(self):
  184. """Check if there were any errors and, if so, raise exceptions.
  185. Raises:
  186. SendPackError: Raised when the server could not unpack
  187. Returns:
  188. iterator over refs
  189. """
  190. if self._pack_status not in (b"unpack ok", None):
  191. raise SendPackError(self._pack_status)
  192. for status in self._ref_statuses:
  193. try:
  194. status, rest = status.split(b" ", 1)
  195. except ValueError:
  196. # malformed response, move on to the next one
  197. continue
  198. if status == b"ng":
  199. ref, error = rest.split(b" ", 1)
  200. yield ref, error.decode("utf-8")
  201. elif status == b"ok":
  202. yield rest, None
  203. else:
  204. raise GitProtocolError(f"invalid ref status {status!r}")
  205. def handle_packet(self, pkt):
  206. """Handle a packet.
  207. Raises:
  208. GitProtocolError: Raised when packets are received after a flush
  209. packet.
  210. """
  211. if self._done:
  212. raise GitProtocolError("received more data after status report")
  213. if pkt is None:
  214. self._done = True
  215. return
  216. if self._pack_status is None:
  217. self._pack_status = pkt.strip()
  218. else:
  219. ref_status = pkt.strip()
  220. self._ref_statuses.append(ref_status)
  221. def negotiate_protocol_version(proto):
  222. pkt = proto.read_pkt_line()
  223. if pkt is not None and pkt.strip() == b"version 2":
  224. return 2
  225. proto.unread_pkt_line(pkt)
  226. return 0
  227. def read_server_capabilities(pkt_seq):
  228. server_capabilities = []
  229. for pkt in pkt_seq:
  230. server_capabilities.append(pkt)
  231. return set(server_capabilities)
  232. def read_pkt_refs_v2(
  233. pkt_seq,
  234. ) -> tuple[dict[bytes, bytes], dict[bytes, bytes], dict[bytes, bytes]]:
  235. refs = {}
  236. symrefs = {}
  237. peeled = {}
  238. # Receive refs from server
  239. for pkt in pkt_seq:
  240. parts = pkt.rstrip(b"\n").split(b" ")
  241. sha = parts[0]
  242. if sha == b"unborn":
  243. sha = None
  244. ref = parts[1]
  245. for part in parts[2:]:
  246. if part.startswith(b"peeled:"):
  247. peeled[ref] = part[7:]
  248. elif part.startswith(b"symref-target:"):
  249. symrefs[ref] = part[14:]
  250. else:
  251. logging.warning("unknown part in pkt-ref: %s", part)
  252. refs[ref] = sha
  253. return refs, symrefs, peeled
  254. def read_pkt_refs_v1(pkt_seq) -> tuple[dict[bytes, bytes], set[bytes]]:
  255. server_capabilities = None
  256. refs = {}
  257. # Receive refs from server
  258. for pkt in pkt_seq:
  259. (sha, ref) = pkt.rstrip(b"\n").split(None, 1)
  260. if sha == b"ERR":
  261. raise GitProtocolError(ref.decode("utf-8", "replace"))
  262. if server_capabilities is None:
  263. (ref, server_capabilities) = extract_capabilities(ref)
  264. refs[ref] = sha
  265. if len(refs) == 0:
  266. return {}, set()
  267. if refs == {CAPABILITIES_REF: ZERO_SHA}:
  268. refs = {}
  269. assert server_capabilities is not None
  270. return refs, set(server_capabilities)
  271. class FetchPackResult:
  272. """Result of a fetch-pack operation.
  273. Attributes:
  274. refs: Dictionary with all remote refs
  275. symrefs: Dictionary with remote symrefs
  276. agent: User agent string
  277. """
  278. _FORWARDED_ATTRS: ClassVar[set[str]] = {
  279. "clear",
  280. "copy",
  281. "fromkeys",
  282. "get",
  283. "items",
  284. "keys",
  285. "pop",
  286. "popitem",
  287. "setdefault",
  288. "update",
  289. "values",
  290. "viewitems",
  291. "viewkeys",
  292. "viewvalues",
  293. }
  294. def __init__(
  295. self, refs, symrefs, agent, new_shallow=None, new_unshallow=None
  296. ) -> None:
  297. self.refs = refs
  298. self.symrefs = symrefs
  299. self.agent = agent
  300. self.new_shallow = new_shallow
  301. self.new_unshallow = new_unshallow
  302. def _warn_deprecated(self):
  303. import warnings
  304. warnings.warn(
  305. "Use FetchPackResult.refs instead.",
  306. DeprecationWarning,
  307. stacklevel=3,
  308. )
  309. def __eq__(self, other):
  310. if isinstance(other, dict):
  311. self._warn_deprecated()
  312. return self.refs == other
  313. return (
  314. self.refs == other.refs
  315. and self.symrefs == other.symrefs
  316. and self.agent == other.agent
  317. )
  318. def __contains__(self, name) -> bool:
  319. self._warn_deprecated()
  320. return name in self.refs
  321. def __getitem__(self, name):
  322. self._warn_deprecated()
  323. return self.refs[name]
  324. def __len__(self) -> int:
  325. self._warn_deprecated()
  326. return len(self.refs)
  327. def __iter__(self):
  328. self._warn_deprecated()
  329. return iter(self.refs)
  330. def __getattribute__(self, name):
  331. if name in type(self)._FORWARDED_ATTRS:
  332. self._warn_deprecated()
  333. return getattr(self.refs, name)
  334. return super().__getattribute__(name)
  335. def __repr__(self) -> str:
  336. return f"{self.__class__.__name__}({self.refs!r}, {self.symrefs!r}, {self.agent!r})"
  337. class SendPackResult:
  338. """Result of a upload-pack operation.
  339. Attributes:
  340. refs: Dictionary with all remote refs
  341. agent: User agent string
  342. ref_status: Optional dictionary mapping ref name to error message (if it
  343. failed to update), or None if it was updated successfully
  344. """
  345. _FORWARDED_ATTRS: ClassVar[set[str]] = {
  346. "clear",
  347. "copy",
  348. "fromkeys",
  349. "get",
  350. "items",
  351. "keys",
  352. "pop",
  353. "popitem",
  354. "setdefault",
  355. "update",
  356. "values",
  357. "viewitems",
  358. "viewkeys",
  359. "viewvalues",
  360. }
  361. def __init__(self, refs, agent=None, ref_status=None) -> None:
  362. self.refs = refs
  363. self.agent = agent
  364. self.ref_status = ref_status
  365. def _warn_deprecated(self):
  366. import warnings
  367. warnings.warn(
  368. "Use SendPackResult.refs instead.",
  369. DeprecationWarning,
  370. stacklevel=3,
  371. )
  372. def __eq__(self, other):
  373. if isinstance(other, dict):
  374. self._warn_deprecated()
  375. return self.refs == other
  376. return self.refs == other.refs and self.agent == other.agent
  377. def __contains__(self, name) -> bool:
  378. self._warn_deprecated()
  379. return name in self.refs
  380. def __getitem__(self, name):
  381. self._warn_deprecated()
  382. return self.refs[name]
  383. def __len__(self) -> int:
  384. self._warn_deprecated()
  385. return len(self.refs)
  386. def __iter__(self):
  387. self._warn_deprecated()
  388. return iter(self.refs)
  389. def __getattribute__(self, name):
  390. if name in type(self)._FORWARDED_ATTRS:
  391. self._warn_deprecated()
  392. return getattr(self.refs, name)
  393. return super().__getattribute__(name)
  394. def __repr__(self) -> str:
  395. return f"{self.__class__.__name__}({self.refs!r}, {self.agent!r})"
  396. def _read_shallow_updates(pkt_seq):
  397. new_shallow = set()
  398. new_unshallow = set()
  399. for pkt in pkt_seq:
  400. if pkt == b"shallow-info\n": # Git-protocol v2
  401. continue
  402. try:
  403. cmd, sha = pkt.split(b" ", 1)
  404. except ValueError:
  405. raise GitProtocolError(f"unknown command {pkt}")
  406. if cmd == COMMAND_SHALLOW:
  407. new_shallow.add(sha.strip())
  408. elif cmd == COMMAND_UNSHALLOW:
  409. new_unshallow.add(sha.strip())
  410. else:
  411. raise GitProtocolError(f"unknown command {pkt}")
  412. return (new_shallow, new_unshallow)
  413. class _v1ReceivePackHeader:
  414. def __init__(self, capabilities, old_refs, new_refs) -> None:
  415. self.want: list[bytes] = []
  416. self.have: list[bytes] = []
  417. self._it = self._handle_receive_pack_head(capabilities, old_refs, new_refs)
  418. self.sent_capabilities = False
  419. def __iter__(self):
  420. return self._it
  421. def _handle_receive_pack_head(self, capabilities, old_refs, new_refs):
  422. """Handle the head of a 'git-receive-pack' request.
  423. Args:
  424. capabilities: List of negotiated capabilities
  425. old_refs: Old refs, as received from the server
  426. new_refs: Refs to change
  427. Returns:
  428. (have, want) tuple
  429. """
  430. self.have = [x for x in old_refs.values() if not x == ZERO_SHA]
  431. for refname in new_refs:
  432. if not isinstance(refname, bytes):
  433. raise TypeError(f"refname is not a bytestring: {refname!r}")
  434. old_sha1 = old_refs.get(refname, ZERO_SHA)
  435. if not isinstance(old_sha1, bytes):
  436. raise TypeError(
  437. f"old sha1 for {refname!r} is not a bytestring: {old_sha1!r}"
  438. )
  439. new_sha1 = new_refs.get(refname, ZERO_SHA)
  440. if not isinstance(new_sha1, bytes):
  441. raise TypeError(
  442. f"old sha1 for {refname!r} is not a bytestring {new_sha1!r}"
  443. )
  444. if old_sha1 != new_sha1:
  445. logger.debug(
  446. "Sending updated ref %r: %r -> %r", refname, old_sha1, new_sha1
  447. )
  448. if self.sent_capabilities:
  449. yield old_sha1 + b" " + new_sha1 + b" " + refname
  450. else:
  451. yield (
  452. old_sha1
  453. + b" "
  454. + new_sha1
  455. + b" "
  456. + refname
  457. + b"\0"
  458. + b" ".join(sorted(capabilities))
  459. )
  460. self.sent_capabilities = True
  461. if new_sha1 not in self.have and new_sha1 != ZERO_SHA:
  462. self.want.append(new_sha1)
  463. yield None
  464. def _read_side_band64k_data(pkt_seq: Iterable[bytes]) -> Iterator[tuple[int, bytes]]:
  465. """Read per-channel data.
  466. This requires the side-band-64k capability.
  467. Args:
  468. pkt_seq: Sequence of packets to read
  469. """
  470. for pkt in pkt_seq:
  471. channel = ord(pkt[:1])
  472. yield channel, pkt[1:]
  473. def find_capability(capabilities, key, value):
  474. for capability in capabilities:
  475. k, v = parse_capability(capability)
  476. if k != key:
  477. continue
  478. if value and value not in v.split(b" "):
  479. continue
  480. return capability
  481. def _handle_upload_pack_head(
  482. proto,
  483. capabilities,
  484. graph_walker,
  485. wants,
  486. can_read,
  487. depth,
  488. protocol_version,
  489. ):
  490. """Handle the head of a 'git-upload-pack' request.
  491. Args:
  492. proto: Protocol object to read from
  493. capabilities: List of negotiated capabilities
  494. graph_walker: GraphWalker instance to call .ack() on
  495. wants: List of commits to fetch
  496. can_read: function that returns a boolean that indicates
  497. whether there is extra graph data to read on proto
  498. depth: Depth for request
  499. protocol_version: Neogiated Git protocol version.
  500. """
  501. assert isinstance(wants, list) and isinstance(wants[0], bytes)
  502. wantcmd = COMMAND_WANT + b" " + wants[0]
  503. if protocol_version is None:
  504. protocol_version = DEFAULT_GIT_PROTOCOL_VERSION_SEND
  505. if protocol_version != 2:
  506. wantcmd += b" " + b" ".join(sorted(capabilities))
  507. wantcmd += b"\n"
  508. proto.write_pkt_line(wantcmd)
  509. for want in wants[1:]:
  510. proto.write_pkt_line(COMMAND_WANT + b" " + want + b"\n")
  511. if depth not in (0, None) or getattr(graph_walker, "shallow", None):
  512. if protocol_version == 2:
  513. if not find_capability(capabilities, CAPABILITY_FETCH, CAPABILITY_SHALLOW):
  514. raise GitProtocolError(
  515. "server does not support shallow capability required for " "depth"
  516. )
  517. elif CAPABILITY_SHALLOW not in capabilities:
  518. raise GitProtocolError(
  519. "server does not support shallow capability required for " "depth"
  520. )
  521. for sha in graph_walker.shallow:
  522. proto.write_pkt_line(COMMAND_SHALLOW + b" " + sha + b"\n")
  523. if depth is not None:
  524. proto.write_pkt_line(
  525. COMMAND_DEEPEN + b" " + str(depth).encode("ascii") + b"\n"
  526. )
  527. if protocol_version == 2:
  528. proto.write_pkt_line(None)
  529. if protocol_version != 2:
  530. proto.write_pkt_line(None)
  531. if depth not in (0, None):
  532. if can_read is not None:
  533. (new_shallow, new_unshallow) = _read_shallow_updates(proto.read_pkt_seq())
  534. else:
  535. new_shallow = new_unshallow = None
  536. else:
  537. new_shallow = new_unshallow = set()
  538. have = next(graph_walker)
  539. while have:
  540. proto.write_pkt_line(COMMAND_HAVE + b" " + have + b"\n")
  541. if can_read is not None and can_read():
  542. pkt = proto.read_pkt_line()
  543. parts = pkt.rstrip(b"\n").split(b" ")
  544. if parts[0] == b"ACK":
  545. graph_walker.ack(parts[1])
  546. if parts[2] in (b"continue", b"common"):
  547. pass
  548. elif parts[2] == b"ready":
  549. break
  550. else:
  551. raise AssertionError(
  552. f"{parts[2]} not in ('continue', 'ready', 'common)"
  553. )
  554. have = next(graph_walker)
  555. proto.write_pkt_line(COMMAND_DONE + b"\n")
  556. if protocol_version == 2:
  557. proto.write_pkt_line(None)
  558. return (new_shallow, new_unshallow)
  559. def _handle_upload_pack_tail(
  560. proto,
  561. capabilities: set[bytes],
  562. graph_walker,
  563. pack_data: Callable[[bytes], None],
  564. progress: Optional[Callable[[bytes], None]] = None,
  565. rbufsize=_RBUFSIZE,
  566. protocol_version=0,
  567. ):
  568. """Handle the tail of a 'git-upload-pack' request.
  569. Args:
  570. proto: Protocol object to read from
  571. capabilities: List of negotiated capabilities
  572. graph_walker: GraphWalker instance to call .ack() on
  573. pack_data: Function to call with pack data
  574. progress: Optional progress reporting function
  575. rbufsize: Read buffer size
  576. protocol_version: Neogiated Git protocol version.
  577. """
  578. pkt = proto.read_pkt_line()
  579. while pkt:
  580. parts = pkt.rstrip(b"\n").split(b" ")
  581. if protocol_version == 2 and parts[0] != "packfile":
  582. break
  583. else:
  584. if parts[0] == b"ACK":
  585. graph_walker.ack(parts[1])
  586. if parts[0] == b"NAK":
  587. graph_walker.nak()
  588. if len(parts) < 3 or parts[2] not in (
  589. b"ready",
  590. b"continue",
  591. b"common",
  592. ):
  593. break
  594. pkt = proto.read_pkt_line()
  595. if CAPABILITY_SIDE_BAND_64K in capabilities or protocol_version == 2:
  596. if progress is None:
  597. # Just ignore progress data
  598. def progress(x):
  599. pass
  600. for chan, data in _read_side_band64k_data(proto.read_pkt_seq()):
  601. if chan == SIDE_BAND_CHANNEL_DATA:
  602. pack_data(data)
  603. elif chan == SIDE_BAND_CHANNEL_PROGRESS:
  604. progress(data)
  605. else:
  606. raise AssertionError("Invalid sideband channel %d" % chan)
  607. else:
  608. while True:
  609. data = proto.read(rbufsize)
  610. if data == b"":
  611. break
  612. pack_data(data)
  613. def _extract_symrefs_and_agent(capabilities):
  614. """Extract symrefs and agent from capabilities.
  615. Args:
  616. capabilities: List of capabilities
  617. Returns:
  618. (symrefs, agent) tuple
  619. """
  620. symrefs = {}
  621. agent = None
  622. for capability in capabilities:
  623. k, v = parse_capability(capability)
  624. if k == CAPABILITY_SYMREF:
  625. (src, dst) = v.split(b":", 1)
  626. symrefs[src] = dst
  627. if k == CAPABILITY_AGENT:
  628. agent = v
  629. return (symrefs, agent)
  630. # TODO(durin42): this doesn't correctly degrade if the server doesn't
  631. # support some capabilities. This should work properly with servers
  632. # that don't support multi_ack.
  633. class GitClient:
  634. """Git smart server client."""
  635. def __init__(
  636. self,
  637. thin_packs=True,
  638. report_activity=None,
  639. quiet=False,
  640. include_tags=False,
  641. **kwargs,
  642. ) -> None:
  643. """Create a new GitClient instance.
  644. Args:
  645. thin_packs: Whether or not thin packs should be retrieved
  646. report_activity: Optional callback for reporting transport
  647. activity.
  648. include_tags: send annotated tags when sending the objects they point
  649. to
  650. """
  651. self._report_activity = report_activity
  652. self._report_status_parser: Optional[ReportStatusParser] = None
  653. self._fetch_capabilities = set(UPLOAD_CAPABILITIES)
  654. self._fetch_capabilities.add(capability_agent())
  655. self._send_capabilities = set(RECEIVE_CAPABILITIES)
  656. self._send_capabilities.add(capability_agent())
  657. if quiet:
  658. self._send_capabilities.add(CAPABILITY_QUIET)
  659. if not thin_packs:
  660. self._fetch_capabilities.remove(CAPABILITY_THIN_PACK)
  661. if include_tags:
  662. self._fetch_capabilities.add(CAPABILITY_INCLUDE_TAG)
  663. self.protocol_version = 0 # will be overridden later
  664. def get_url(self, path):
  665. """Retrieves full url to given path.
  666. Args:
  667. path: Repository path (as string)
  668. Returns:
  669. Url to path (as string)
  670. """
  671. raise NotImplementedError(self.get_url)
  672. @classmethod
  673. def from_parsedurl(cls, parsedurl, **kwargs):
  674. """Create an instance of this client from a urlparse.parsed object.
  675. Args:
  676. parsedurl: Result of urlparse()
  677. Returns:
  678. A `GitClient` object
  679. """
  680. raise NotImplementedError(cls.from_parsedurl)
  681. def send_pack(
  682. self,
  683. path: str,
  684. update_refs,
  685. generate_pack_data: Callable[
  686. [set[bytes], set[bytes], bool], tuple[int, Iterator[UnpackedObject]]
  687. ],
  688. progress=None,
  689. ):
  690. """Upload a pack to a remote repository.
  691. Args:
  692. path: Repository path (as bytestring)
  693. update_refs: Function to determine changes to remote refs. Receive
  694. dict with existing remote refs, returns dict with
  695. changed refs (name -> sha, where sha=ZERO_SHA for deletions)
  696. generate_pack_data: Function that can return a tuple
  697. with number of objects and list of pack data to include
  698. progress: Optional progress function
  699. Returns:
  700. SendPackResult object
  701. Raises:
  702. SendPackError: if server rejects the pack data
  703. """
  704. raise NotImplementedError(self.send_pack)
  705. def clone(
  706. self,
  707. path,
  708. target_path,
  709. mkdir: bool = True,
  710. bare: bool = False,
  711. origin: Optional[str] = "origin",
  712. checkout=None,
  713. branch=None,
  714. progress=None,
  715. depth=None,
  716. ref_prefix: Optional[list[Ref]] = None,
  717. filter_spec=None,
  718. protocol_version: Optional[int] = None,
  719. ) -> Repo:
  720. """Clone a repository."""
  721. if mkdir:
  722. os.mkdir(target_path)
  723. try:
  724. target = None
  725. if not bare:
  726. target = Repo.init(target_path)
  727. if checkout is None:
  728. checkout = True
  729. else:
  730. if checkout:
  731. raise ValueError("checkout and bare are incompatible")
  732. target = Repo.init_bare(target_path)
  733. # TODO(jelmer): abstract method for get_location?
  734. if isinstance(self, (LocalGitClient, SubprocessGitClient)):
  735. encoded_path = path.encode("utf-8")
  736. else:
  737. encoded_path = self.get_url(path).encode("utf-8")
  738. assert target is not None
  739. if origin is not None:
  740. target_config = target.get_config()
  741. target_config.set(
  742. (b"remote", origin.encode("utf-8")), b"url", encoded_path
  743. )
  744. target_config.set(
  745. (b"remote", origin.encode("utf-8")),
  746. b"fetch",
  747. b"+refs/heads/*:refs/remotes/" + origin.encode("utf-8") + b"/*",
  748. )
  749. target_config.write_to_path()
  750. ref_message = b"clone: from " + encoded_path
  751. result = self.fetch(
  752. path,
  753. target,
  754. progress=progress,
  755. depth=depth,
  756. ref_prefix=ref_prefix,
  757. filter_spec=filter_spec,
  758. protocol_version=protocol_version,
  759. )
  760. if origin is not None:
  761. _import_remote_refs(
  762. target.refs, origin, result.refs, message=ref_message
  763. )
  764. origin_head = result.symrefs.get(b"HEAD")
  765. origin_sha = result.refs.get(b"HEAD")
  766. if origin is None or (origin_sha and not origin_head):
  767. # set detached HEAD
  768. target.refs[b"HEAD"] = origin_sha
  769. head = origin_sha
  770. else:
  771. _set_origin_head(target.refs, origin.encode("utf-8"), origin_head)
  772. head_ref = _set_default_branch(
  773. target.refs,
  774. origin.encode("utf-8"),
  775. origin_head,
  776. branch,
  777. ref_message,
  778. )
  779. # Update target head
  780. if head_ref:
  781. head = _set_head(target.refs, head_ref, ref_message)
  782. else:
  783. head = None
  784. if checkout and head is not None:
  785. target.reset_index()
  786. except BaseException:
  787. if target is not None:
  788. target.close()
  789. if mkdir:
  790. import shutil
  791. shutil.rmtree(target_path)
  792. raise
  793. return target
  794. def fetch(
  795. self,
  796. path: str,
  797. target: Repo,
  798. determine_wants: Optional[
  799. Callable[[dict[bytes, bytes], Optional[int]], list[bytes]]
  800. ] = None,
  801. progress: Optional[Callable[[bytes], None]] = None,
  802. depth: Optional[int] = None,
  803. ref_prefix: Optional[list[Ref]] = None,
  804. filter_spec: Optional[bytes] = None,
  805. protocol_version: Optional[int] = None,
  806. ) -> FetchPackResult:
  807. """Fetch into a target repository.
  808. Args:
  809. path: Path to fetch from (as bytestring)
  810. target: Target repository to fetch into
  811. determine_wants: Optional function to determine what refs to fetch.
  812. Receives dictionary of name->sha, should return
  813. list of shas to fetch. Defaults to all shas.
  814. progress: Optional progress function
  815. depth: Depth to fetch at
  816. ref_prefix: List of prefixes of desired references, as a list of
  817. bytestrings. Filtering is done by the server if supported, and
  818. client side otherwise.
  819. filter_spec: A git-rev-list-style object filter spec, as bytestring.
  820. Only used if the server supports the Git protocol-v2 'filter'
  821. feature, and ignored otherwise.
  822. protocol_version: Desired Git protocol version. By default the highest
  823. mutually supported protocol version will be used.
  824. Returns:
  825. Dictionary with all remote refs (not just those fetched)
  826. """
  827. if determine_wants is None:
  828. determine_wants = target.object_store.determine_wants_all
  829. if CAPABILITY_THIN_PACK in self._fetch_capabilities:
  830. from tempfile import SpooledTemporaryFile
  831. f: IO[bytes] = SpooledTemporaryFile(
  832. max_size=PACK_SPOOL_FILE_MAX_SIZE,
  833. prefix="incoming-",
  834. dir=getattr(target.object_store, "path", None),
  835. )
  836. def commit():
  837. if f.tell():
  838. f.seek(0)
  839. target.object_store.add_thin_pack(f.read, None, progress=progress)
  840. f.close()
  841. def abort():
  842. f.close()
  843. else:
  844. f, commit, abort = target.object_store.add_pack()
  845. try:
  846. result = self.fetch_pack(
  847. path,
  848. determine_wants,
  849. target.get_graph_walker(),
  850. f.write,
  851. progress=progress,
  852. depth=depth,
  853. ref_prefix=ref_prefix,
  854. filter_spec=filter_spec,
  855. protocol_version=protocol_version,
  856. )
  857. except BaseException:
  858. abort()
  859. raise
  860. else:
  861. commit()
  862. target.update_shallow(result.new_shallow, result.new_unshallow)
  863. return result
  864. def fetch_pack(
  865. self,
  866. path: str,
  867. determine_wants,
  868. graph_walker,
  869. pack_data,
  870. *,
  871. progress: Optional[Callable[[bytes], None]] = None,
  872. depth: Optional[int] = None,
  873. ref_prefix: Optional[list[Ref]] = None,
  874. filter_spec=None,
  875. protocol_version: Optional[int] = None,
  876. ):
  877. """Retrieve a pack from a git smart server.
  878. Args:
  879. path: Remote path to fetch from
  880. determine_wants: Function determine what refs
  881. to fetch. Receives dictionary of name->sha, should return
  882. list of shas to fetch.
  883. graph_walker: Object with next() and ack().
  884. pack_data: Callback called for each bit of data in the pack
  885. progress: Callback for progress reports (strings)
  886. depth: Shallow fetch depth
  887. ref_prefix: List of prefixes of desired references, as a list of
  888. bytestrings. Filtering is done by the server if supported, and
  889. client side otherwise.
  890. filter_spec: A git-rev-list-style object filter spec, as bytestring.
  891. Only used if the server supports the Git protocol-v2 'filter'
  892. feature, and ignored otherwise.
  893. protocol_version: Desired Git protocol version. By default the highest
  894. mutually supported protocol version will be used.
  895. Returns:
  896. FetchPackResult object
  897. """
  898. raise NotImplementedError(self.fetch_pack)
  899. def get_refs(
  900. self,
  901. path,
  902. protocol_version: Optional[int] = None,
  903. ref_prefix: Optional[list[Ref]] = None,
  904. ):
  905. """Retrieve the current refs from a git smart server.
  906. Args:
  907. path: Path to the repo to fetch from. (as bytestring)
  908. """
  909. raise NotImplementedError(self.get_refs)
  910. @staticmethod
  911. def _should_send_pack(new_refs):
  912. # The packfile MUST NOT be sent if the only command used is delete.
  913. return any(sha != ZERO_SHA for sha in new_refs.values())
  914. def _negotiate_receive_pack_capabilities(self, server_capabilities):
  915. negotiated_capabilities = self._send_capabilities & server_capabilities
  916. (agent, _symrefs) = _extract_symrefs_and_agent(server_capabilities)
  917. (extract_capability_names(server_capabilities) - KNOWN_RECEIVE_CAPABILITIES)
  918. # TODO(jelmer): warn about unknown capabilities
  919. return negotiated_capabilities, agent
  920. def _handle_receive_pack_tail(
  921. self,
  922. proto: Protocol,
  923. capabilities: set[bytes],
  924. progress: Optional[Callable[[bytes], None]] = None,
  925. ) -> Optional[dict[bytes, Optional[str]]]:
  926. """Handle the tail of a 'git-receive-pack' request.
  927. Args:
  928. proto: Protocol object to read from
  929. capabilities: List of negotiated capabilities
  930. progress: Optional progress reporting function
  931. Returns:
  932. dict mapping ref name to:
  933. error message if the ref failed to update
  934. None if it was updated successfully
  935. """
  936. if CAPABILITY_SIDE_BAND_64K in capabilities or self.protocol_version == 2:
  937. if progress is None:
  938. def progress(x):
  939. pass
  940. if CAPABILITY_REPORT_STATUS in capabilities:
  941. assert self._report_status_parser is not None
  942. pktline_parser = PktLineParser(self._report_status_parser.handle_packet)
  943. for chan, data in _read_side_band64k_data(proto.read_pkt_seq()):
  944. if chan == SIDE_BAND_CHANNEL_DATA:
  945. if CAPABILITY_REPORT_STATUS in capabilities:
  946. pktline_parser.parse(data)
  947. elif chan == SIDE_BAND_CHANNEL_PROGRESS:
  948. progress(data)
  949. else:
  950. raise AssertionError("Invalid sideband channel %d" % chan)
  951. else:
  952. if CAPABILITY_REPORT_STATUS in capabilities:
  953. assert self._report_status_parser
  954. for pkt in proto.read_pkt_seq():
  955. self._report_status_parser.handle_packet(pkt)
  956. if self._report_status_parser is not None:
  957. return dict(self._report_status_parser.check())
  958. return None
  959. def _negotiate_upload_pack_capabilities(self, server_capabilities):
  960. (extract_capability_names(server_capabilities) - KNOWN_UPLOAD_CAPABILITIES)
  961. # TODO(jelmer): warn about unknown capabilities
  962. fetch_capa = None
  963. for capability in server_capabilities:
  964. k, v = parse_capability(capability)
  965. if self.protocol_version == 2 and k == CAPABILITY_FETCH:
  966. fetch_capa = CAPABILITY_FETCH
  967. fetch_features = []
  968. v = v.strip().split(b" ")
  969. if b"shallow" in v:
  970. fetch_features.append(CAPABILITY_SHALLOW)
  971. if b"filter" in v:
  972. fetch_features.append(CAPABILITY_FILTER)
  973. for i in range(len(fetch_features)):
  974. if i == 0:
  975. fetch_capa += b"="
  976. else:
  977. fetch_capa += b" "
  978. fetch_capa += fetch_features[i]
  979. (symrefs, agent) = _extract_symrefs_and_agent(server_capabilities)
  980. negotiated_capabilities = self._fetch_capabilities & server_capabilities
  981. if fetch_capa:
  982. negotiated_capabilities.add(fetch_capa)
  983. return (negotiated_capabilities, symrefs, agent)
  984. def archive(
  985. self,
  986. path,
  987. committish,
  988. write_data,
  989. progress=None,
  990. write_error=None,
  991. format=None,
  992. subdirs=None,
  993. prefix=None,
  994. ):
  995. """Retrieve an archive of the specified tree."""
  996. raise NotImplementedError(self.archive)
  997. @staticmethod
  998. def _warn_filter_objects():
  999. import warnings
  1000. warnings.warn(
  1001. "object filtering not recognized by server, ignoring",
  1002. UserWarning,
  1003. )
  1004. def check_wants(wants, refs):
  1005. """Check that a set of wants is valid.
  1006. Args:
  1007. wants: Set of object SHAs to fetch
  1008. refs: Refs dictionary to check against
  1009. """
  1010. missing = set(wants) - {
  1011. v for (k, v) in refs.items() if not k.endswith(PEELED_TAG_SUFFIX)
  1012. }
  1013. if missing:
  1014. raise InvalidWants(missing)
  1015. def _remote_error_from_stderr(stderr):
  1016. if stderr is None:
  1017. return HangupException()
  1018. lines = [line.rstrip(b"\n") for line in stderr.readlines()]
  1019. for line in lines:
  1020. if line.startswith(b"ERROR: "):
  1021. return GitProtocolError(line[len(b"ERROR: ") :].decode("utf-8", "replace"))
  1022. return HangupException(lines)
  1023. class TraditionalGitClient(GitClient):
  1024. """Traditional Git client."""
  1025. DEFAULT_ENCODING = "utf-8"
  1026. def __init__(self, path_encoding=DEFAULT_ENCODING, **kwargs) -> None:
  1027. self._remote_path_encoding = path_encoding
  1028. super().__init__(**kwargs)
  1029. def _connect(
  1030. self,
  1031. cmd: bytes,
  1032. path: Union[str, bytes],
  1033. protocol_version: Optional[int] = None,
  1034. ) -> tuple[Protocol, Callable[[], bool], Optional[IO[bytes]]]:
  1035. """Create a connection to the server.
  1036. This method is abstract - concrete implementations should
  1037. implement their own variant which connects to the server and
  1038. returns an initialized Protocol object with the service ready
  1039. for use and a can_read function which may be used to see if
  1040. reads would block.
  1041. Args:
  1042. cmd: The git service name to which we should connect.
  1043. path: The path we should pass to the service. (as bytestirng)
  1044. protocol_version: Desired Git protocol version. By default the highest
  1045. mutually supported protocol version will be used.
  1046. """
  1047. raise NotImplementedError
  1048. def send_pack(self, path, update_refs, generate_pack_data, progress=None):
  1049. """Upload a pack to a remote repository.
  1050. Args:
  1051. path: Repository path (as bytestring)
  1052. update_refs: Function to determine changes to remote refs.
  1053. Receive dict with existing remote refs, returns dict with
  1054. changed refs (name -> sha, where sha=ZERO_SHA for deletions)
  1055. generate_pack_data: Function that can return a tuple with
  1056. number of objects and pack data to upload.
  1057. progress: Optional callback called with progress updates
  1058. Returns:
  1059. SendPackResult
  1060. Raises:
  1061. SendPackError: if server rejects the pack data
  1062. """
  1063. self.protocol_version = DEFAULT_GIT_PROTOCOL_VERSION_SEND
  1064. proto, unused_can_read, stderr = self._connect(b"receive-pack", path)
  1065. with proto:
  1066. try:
  1067. old_refs, server_capabilities = read_pkt_refs_v1(proto.read_pkt_seq())
  1068. except HangupException as exc:
  1069. raise _remote_error_from_stderr(stderr) from exc
  1070. (
  1071. negotiated_capabilities,
  1072. agent,
  1073. ) = self._negotiate_receive_pack_capabilities(server_capabilities)
  1074. if CAPABILITY_REPORT_STATUS in negotiated_capabilities:
  1075. self._report_status_parser = ReportStatusParser()
  1076. report_status_parser = self._report_status_parser
  1077. try:
  1078. new_refs = orig_new_refs = update_refs(dict(old_refs))
  1079. except BaseException:
  1080. proto.write_pkt_line(None)
  1081. raise
  1082. if set(new_refs.items()).issubset(set(old_refs.items())):
  1083. proto.write_pkt_line(None)
  1084. return SendPackResult(new_refs, agent=agent, ref_status={})
  1085. if CAPABILITY_DELETE_REFS not in server_capabilities:
  1086. # Server does not support deletions. Fail later.
  1087. new_refs = dict(orig_new_refs)
  1088. for ref, sha in orig_new_refs.items():
  1089. if sha == ZERO_SHA:
  1090. if CAPABILITY_REPORT_STATUS in negotiated_capabilities:
  1091. report_status_parser._ref_statuses.append(
  1092. b"ng " + ref + b" remote does not support deleting refs"
  1093. )
  1094. report_status_parser._ref_status_ok = False
  1095. del new_refs[ref]
  1096. if new_refs is None:
  1097. proto.write_pkt_line(None)
  1098. return SendPackResult(old_refs, agent=agent, ref_status={})
  1099. if len(new_refs) == 0 and orig_new_refs:
  1100. # NOOP - Original new refs filtered out by policy
  1101. proto.write_pkt_line(None)
  1102. if report_status_parser is not None:
  1103. ref_status = dict(report_status_parser.check())
  1104. else:
  1105. ref_status = None
  1106. return SendPackResult(old_refs, agent=agent, ref_status=ref_status)
  1107. header_handler = _v1ReceivePackHeader(
  1108. negotiated_capabilities, old_refs, new_refs
  1109. )
  1110. for pkt in header_handler:
  1111. proto.write_pkt_line(pkt)
  1112. pack_data_count, pack_data = generate_pack_data(
  1113. header_handler.have,
  1114. header_handler.want,
  1115. ofs_delta=(CAPABILITY_OFS_DELTA in negotiated_capabilities),
  1116. progress=progress,
  1117. )
  1118. if self._should_send_pack(new_refs):
  1119. for chunk in PackChunkGenerator(
  1120. pack_data_count, pack_data, progress=progress
  1121. ):
  1122. proto.write(chunk)
  1123. ref_status = self._handle_receive_pack_tail(
  1124. proto, negotiated_capabilities, progress
  1125. )
  1126. return SendPackResult(new_refs, agent=agent, ref_status=ref_status)
  1127. def fetch_pack(
  1128. self,
  1129. path,
  1130. determine_wants,
  1131. graph_walker,
  1132. pack_data,
  1133. progress=None,
  1134. depth=None,
  1135. ref_prefix: Optional[list[Ref]] = None,
  1136. filter_spec=None,
  1137. protocol_version: Optional[int] = None,
  1138. ):
  1139. """Retrieve a pack from a git smart server.
  1140. Args:
  1141. path: Remote path to fetch from
  1142. determine_wants: Function determine what refs
  1143. to fetch. Receives dictionary of name->sha, should return
  1144. list of shas to fetch.
  1145. graph_walker: Object with next() and ack().
  1146. pack_data: Callback called for each bit of data in the pack
  1147. progress: Callback for progress reports (strings)
  1148. depth: Shallow fetch depth
  1149. ref_prefix: List of prefixes of desired references, as a list of
  1150. bytestrings. Filtering is done by the server if supported, and
  1151. client side otherwise.
  1152. filter_spec: A git-rev-list-style object filter spec, as bytestring.
  1153. Only used if the server supports the Git protocol-v2 'filter'
  1154. feature, and ignored otherwise.
  1155. protocol_version: Desired Git protocol version. By default the highest
  1156. mutually supported protocol version will be used.
  1157. Returns:
  1158. FetchPackResult object
  1159. """
  1160. if (
  1161. protocol_version is not None
  1162. and protocol_version not in GIT_PROTOCOL_VERSIONS
  1163. ):
  1164. raise ValueError("unknown Git protocol version %d" % protocol_version)
  1165. proto, can_read, stderr = self._connect(b"upload-pack", path, protocol_version)
  1166. server_protocol_version = negotiate_protocol_version(proto)
  1167. if server_protocol_version not in GIT_PROTOCOL_VERSIONS:
  1168. raise ValueError(
  1169. "unknown Git protocol version %d used by server"
  1170. % server_protocol_version
  1171. )
  1172. if protocol_version and server_protocol_version > protocol_version:
  1173. raise ValueError(
  1174. "bad Git protocol version %d used by server" % server_protocol_version
  1175. )
  1176. self.protocol_version = server_protocol_version
  1177. with proto:
  1178. if self.protocol_version == 2:
  1179. try:
  1180. server_capabilities = read_server_capabilities(proto.read_pkt_seq())
  1181. except HangupException as exc:
  1182. raise _remote_error_from_stderr(stderr) from exc
  1183. (
  1184. negotiated_capabilities,
  1185. symrefs,
  1186. agent,
  1187. ) = self._negotiate_upload_pack_capabilities(server_capabilities)
  1188. proto.write_pkt_line(b"command=ls-refs\n")
  1189. proto.write(b"0001") # delim-pkt
  1190. proto.write_pkt_line(b"symrefs")
  1191. proto.write_pkt_line(b"peel")
  1192. if ref_prefix is None:
  1193. ref_prefix = DEFAULT_REF_PREFIX
  1194. for prefix in ref_prefix:
  1195. proto.write_pkt_line(b"ref-prefix " + prefix)
  1196. proto.write_pkt_line(None)
  1197. refs, symrefs, _peeled = read_pkt_refs_v2(proto.read_pkt_seq())
  1198. else:
  1199. try:
  1200. refs, server_capabilities = read_pkt_refs_v1(proto.read_pkt_seq())
  1201. except HangupException as exc:
  1202. raise _remote_error_from_stderr(stderr) from exc
  1203. (
  1204. negotiated_capabilities,
  1205. symrefs,
  1206. agent,
  1207. ) = self._negotiate_upload_pack_capabilities(server_capabilities)
  1208. if ref_prefix is not None:
  1209. refs = filter_ref_prefix(refs, ref_prefix)
  1210. if refs is None:
  1211. proto.write_pkt_line(None)
  1212. return FetchPackResult(refs, symrefs, agent)
  1213. try:
  1214. if depth is not None:
  1215. wants = determine_wants(refs, depth=depth)
  1216. else:
  1217. wants = determine_wants(refs)
  1218. except BaseException:
  1219. proto.write_pkt_line(None)
  1220. raise
  1221. if wants is not None:
  1222. wants = [cid for cid in wants if cid != ZERO_SHA]
  1223. if not wants:
  1224. proto.write_pkt_line(None)
  1225. return FetchPackResult(refs, symrefs, agent)
  1226. if self.protocol_version == 2:
  1227. proto.write_pkt_line(b"command=fetch\n")
  1228. proto.write(b"0001") # delim-pkt
  1229. if (
  1230. find_capability(
  1231. negotiated_capabilities, CAPABILITY_FETCH, CAPABILITY_FILTER
  1232. )
  1233. and filter_spec
  1234. ):
  1235. proto.write(pkt_line(b"filter %s\n" % filter_spec))
  1236. elif filter_spec:
  1237. self._warn_filter_objects()
  1238. elif filter_spec:
  1239. self._warn_filter_objects()
  1240. (new_shallow, new_unshallow) = _handle_upload_pack_head(
  1241. proto,
  1242. negotiated_capabilities,
  1243. graph_walker,
  1244. wants,
  1245. can_read,
  1246. depth=depth,
  1247. protocol_version=self.protocol_version,
  1248. )
  1249. _handle_upload_pack_tail(
  1250. proto,
  1251. negotiated_capabilities,
  1252. graph_walker,
  1253. pack_data,
  1254. progress,
  1255. protocol_version=self.protocol_version,
  1256. )
  1257. return FetchPackResult(refs, symrefs, agent, new_shallow, new_unshallow)
  1258. def get_refs(
  1259. self,
  1260. path,
  1261. protocol_version: Optional[int] = None,
  1262. ref_prefix: Optional[list[Ref]] = None,
  1263. ):
  1264. """Retrieve the current refs from a git smart server."""
  1265. # stock `git ls-remote` uses upload-pack
  1266. if (
  1267. protocol_version is not None
  1268. and protocol_version not in GIT_PROTOCOL_VERSIONS
  1269. ):
  1270. raise ValueError("unknown Git protocol version %d" % protocol_version)
  1271. proto, _, stderr = self._connect(b"upload-pack", path, protocol_version)
  1272. server_protocol_version = negotiate_protocol_version(proto)
  1273. if server_protocol_version not in GIT_PROTOCOL_VERSIONS:
  1274. raise ValueError(
  1275. "unknown Git protocol version %d used by server"
  1276. % server_protocol_version
  1277. )
  1278. if protocol_version and server_protocol_version > protocol_version:
  1279. raise ValueError(
  1280. "bad Git protocol version %d used by server" % server_protocol_version
  1281. )
  1282. self.protocol_version = server_protocol_version
  1283. if self.protocol_version == 2:
  1284. server_capabilities = read_server_capabilities(proto.read_pkt_seq())
  1285. proto.write_pkt_line(b"command=ls-refs\n")
  1286. proto.write(b"0001") # delim-pkt
  1287. proto.write_pkt_line(b"symrefs")
  1288. proto.write_pkt_line(b"peel")
  1289. if ref_prefix is None:
  1290. ref_prefix = DEFAULT_REF_PREFIX
  1291. for prefix in ref_prefix:
  1292. proto.write_pkt_line(b"ref-prefix " + prefix)
  1293. proto.write_pkt_line(None)
  1294. with proto:
  1295. try:
  1296. refs, _symrefs, peeled = read_pkt_refs_v2(proto.read_pkt_seq())
  1297. except HangupException as exc:
  1298. raise _remote_error_from_stderr(stderr) from exc
  1299. proto.write_pkt_line(None)
  1300. for refname, refvalue in peeled.items():
  1301. refs[refname + PEELED_TAG_SUFFIX] = refvalue
  1302. return refs
  1303. else:
  1304. with proto:
  1305. try:
  1306. refs, server_capabilities = read_pkt_refs_v1(proto.read_pkt_seq())
  1307. except HangupException as exc:
  1308. raise _remote_error_from_stderr(stderr) from exc
  1309. proto.write_pkt_line(None)
  1310. (_symrefs, _agent) = _extract_symrefs_and_agent(server_capabilities)
  1311. if ref_prefix is not None:
  1312. refs = filter_ref_prefix(refs, ref_prefix)
  1313. return refs
  1314. def archive(
  1315. self,
  1316. path,
  1317. committish,
  1318. write_data,
  1319. progress=None,
  1320. write_error=None,
  1321. format=None,
  1322. subdirs=None,
  1323. prefix=None,
  1324. ):
  1325. proto, can_read, stderr = self._connect(b"upload-archive", path)
  1326. with proto:
  1327. if format is not None:
  1328. proto.write_pkt_line(b"argument --format=" + format)
  1329. proto.write_pkt_line(b"argument " + committish)
  1330. if subdirs is not None:
  1331. for subdir in subdirs:
  1332. proto.write_pkt_line(b"argument " + subdir)
  1333. if prefix is not None:
  1334. proto.write_pkt_line(b"argument --prefix=" + prefix)
  1335. proto.write_pkt_line(None)
  1336. try:
  1337. pkt = proto.read_pkt_line()
  1338. except HangupException as exc:
  1339. raise _remote_error_from_stderr(stderr) from exc
  1340. if pkt == b"NACK\n" or pkt == b"NACK":
  1341. return
  1342. elif pkt == b"ACK\n" or pkt == b"ACK":
  1343. pass
  1344. elif pkt.startswith(b"ERR "):
  1345. raise GitProtocolError(pkt[4:].rstrip(b"\n").decode("utf-8", "replace"))
  1346. else:
  1347. raise AssertionError(f"invalid response {pkt!r}")
  1348. ret = proto.read_pkt_line()
  1349. if ret is not None:
  1350. raise AssertionError("expected pkt tail")
  1351. for chan, data in _read_side_band64k_data(proto.read_pkt_seq()):
  1352. if chan == SIDE_BAND_CHANNEL_DATA:
  1353. write_data(data)
  1354. elif chan == SIDE_BAND_CHANNEL_PROGRESS:
  1355. progress(data)
  1356. elif chan == SIDE_BAND_CHANNEL_FATAL:
  1357. write_error(data)
  1358. else:
  1359. raise AssertionError("Invalid sideband channel %d" % chan)
  1360. class TCPGitClient(TraditionalGitClient):
  1361. """A Git Client that works over TCP directly (i.e. git://)."""
  1362. def __init__(self, host, port=None, **kwargs) -> None:
  1363. if port is None:
  1364. port = TCP_GIT_PORT
  1365. self._host = host
  1366. self._port = port
  1367. super().__init__(**kwargs)
  1368. @classmethod
  1369. def from_parsedurl(cls, parsedurl, **kwargs):
  1370. return cls(parsedurl.hostname, port=parsedurl.port, **kwargs)
  1371. def get_url(self, path):
  1372. netloc = self._host
  1373. if self._port is not None and self._port != TCP_GIT_PORT:
  1374. netloc += ":%d" % self._port
  1375. return urlunsplit(("git", netloc, path, "", ""))
  1376. def _connect(
  1377. self,
  1378. cmd: bytes,
  1379. path: Union[str, bytes],
  1380. protocol_version: Optional[int] = None,
  1381. ) -> tuple[Protocol, Callable[[], bool], Optional[IO[bytes]]]:
  1382. if not isinstance(cmd, bytes):
  1383. raise TypeError(cmd)
  1384. if not isinstance(path, bytes):
  1385. path = path.encode(self._remote_path_encoding)
  1386. sockaddrs = socket.getaddrinfo(
  1387. self._host, self._port, socket.AF_UNSPEC, socket.SOCK_STREAM
  1388. )
  1389. s = None
  1390. err = OSError(f"no address found for {self._host}")
  1391. for family, socktype, protof, canonname, sockaddr in sockaddrs:
  1392. s = socket.socket(family, socktype, protof)
  1393. s.setsockopt(socket.IPPROTO_TCP, socket.TCP_NODELAY, 1)
  1394. try:
  1395. s.connect(sockaddr)
  1396. break
  1397. except OSError as e:
  1398. err = e
  1399. if s is not None:
  1400. s.close()
  1401. s = None
  1402. if s is None:
  1403. raise err
  1404. # -1 means system default buffering
  1405. rfile = s.makefile("rb", -1)
  1406. # 0 means unbuffered
  1407. wfile = s.makefile("wb", 0)
  1408. def close():
  1409. rfile.close()
  1410. wfile.close()
  1411. s.close()
  1412. proto = Protocol(
  1413. rfile.read,
  1414. wfile.write,
  1415. close,
  1416. report_activity=self._report_activity,
  1417. )
  1418. if path.startswith(b"/~"):
  1419. path = path[1:]
  1420. if cmd == b"upload-pack":
  1421. if protocol_version is None:
  1422. self.protocol_version = DEFAULT_GIT_PROTOCOL_VERSION_FETCH
  1423. else:
  1424. self.protocol_version = protocol_version
  1425. else:
  1426. self.protocol_version = DEFAULT_GIT_PROTOCOL_VERSION_SEND
  1427. if cmd == b"upload-pack" and self.protocol_version == 2:
  1428. # Git protocol version advertisement is hidden behind two NUL bytes
  1429. # for compatibility with older Git server implementations, which
  1430. # would crash if something other than a "host=" header was found
  1431. # after the first NUL byte.
  1432. version_str = b"\0\0version=%d\0" % self.protocol_version
  1433. else:
  1434. version_str = b""
  1435. # TODO(jelmer): Alternative to ascii?
  1436. proto.send_cmd(
  1437. b"git-" + cmd, path, b"host=" + self._host.encode("ascii") + version_str
  1438. )
  1439. return proto, lambda: _fileno_can_read(s), None
  1440. class SubprocessWrapper:
  1441. """A socket-like object that talks to a subprocess via pipes."""
  1442. def __init__(self, proc) -> None:
  1443. self.proc = proc
  1444. self.read = BufferedReader(proc.stdout).read
  1445. self.write = proc.stdin.write
  1446. @property
  1447. def stderr(self):
  1448. return self.proc.stderr
  1449. def can_read(self):
  1450. if sys.platform == "win32":
  1451. from msvcrt import get_osfhandle
  1452. handle = get_osfhandle(self.proc.stdout.fileno())
  1453. return _win32_peek_avail(handle) != 0
  1454. else:
  1455. return _fileno_can_read(self.proc.stdout.fileno())
  1456. def close(self):
  1457. self.proc.stdin.close()
  1458. self.proc.stdout.close()
  1459. if self.proc.stderr:
  1460. self.proc.stderr.close()
  1461. self.proc.wait()
  1462. def find_git_command() -> list[str]:
  1463. """Find command to run for system Git (usually C Git)."""
  1464. if sys.platform == "win32": # support .exe, .bat and .cmd
  1465. try: # to avoid overhead
  1466. import pywintypes
  1467. import win32api
  1468. except ImportError: # run through cmd.exe with some overhead
  1469. return ["cmd", "/c", "git"]
  1470. else:
  1471. try:
  1472. status, git = win32api.FindExecutable("git")
  1473. return [git]
  1474. except pywintypes.error:
  1475. return ["cmd", "/c", "git"]
  1476. else:
  1477. return ["git"]
  1478. class SubprocessGitClient(TraditionalGitClient):
  1479. """Git client that talks to a server using a subprocess."""
  1480. @classmethod
  1481. def from_parsedurl(cls, parsedurl, **kwargs):
  1482. return cls(**kwargs)
  1483. git_command = None
  1484. def _connect(
  1485. self,
  1486. service: bytes,
  1487. path: Union[bytes, str],
  1488. protocol_version: Optional[int] = None,
  1489. ) -> tuple[Protocol, Callable[[], bool], Optional[IO[bytes]]]:
  1490. if not isinstance(service, bytes):
  1491. raise TypeError(service)
  1492. if isinstance(path, bytes):
  1493. path = path.decode(self._remote_path_encoding)
  1494. if self.git_command is None:
  1495. git_command = find_git_command()
  1496. argv = [*git_command, service.decode("ascii"), path]
  1497. p = subprocess.Popen(
  1498. argv,
  1499. bufsize=0,
  1500. stdin=subprocess.PIPE,
  1501. stdout=subprocess.PIPE,
  1502. stderr=subprocess.PIPE,
  1503. )
  1504. pw = SubprocessWrapper(p)
  1505. return (
  1506. Protocol(
  1507. pw.read,
  1508. pw.write,
  1509. pw.close,
  1510. report_activity=self._report_activity,
  1511. ),
  1512. pw.can_read,
  1513. p.stderr,
  1514. )
  1515. class LocalGitClient(GitClient):
  1516. """Git Client that just uses a local on-disk repository."""
  1517. def __init__(
  1518. self,
  1519. thin_packs: bool = True,
  1520. report_activity=None,
  1521. config: Optional[Config] = None,
  1522. ) -> None:
  1523. """Create a new LocalGitClient instance.
  1524. Args:
  1525. thin_packs: Whether or not thin packs should be retrieved
  1526. report_activity: Optional callback for reporting transport
  1527. activity.
  1528. """
  1529. self._report_activity = report_activity
  1530. # Ignore the thin_packs argument
  1531. def get_url(self, path):
  1532. return urlunsplit(("file", "", path, "", ""))
  1533. @classmethod
  1534. def from_parsedurl(cls, parsedurl, **kwargs):
  1535. return cls(**kwargs)
  1536. @classmethod
  1537. def _open_repo(cls, path):
  1538. if not isinstance(path, str):
  1539. path = os.fsdecode(path)
  1540. return closing(Repo(path))
  1541. def send_pack(self, path, update_refs, generate_pack_data, progress=None):
  1542. """Upload a pack to a local on-disk repository.
  1543. Args:
  1544. path: Repository path (as bytestring)
  1545. update_refs: Function to determine changes to remote refs.
  1546. Receive dict with existing remote refs, returns dict with
  1547. changed refs (name -> sha, where sha=ZERO_SHA for deletions)
  1548. with number of items and pack data to upload.
  1549. progress: Optional progress function
  1550. Returns:
  1551. SendPackResult
  1552. Raises:
  1553. SendPackError: if server rejects the pack data
  1554. """
  1555. if not progress:
  1556. def progress(x):
  1557. pass
  1558. with self._open_repo(path) as target:
  1559. old_refs = target.get_refs()
  1560. new_refs = update_refs(dict(old_refs))
  1561. have = [sha1 for sha1 in old_refs.values() if sha1 != ZERO_SHA]
  1562. want = []
  1563. for refname, new_sha1 in new_refs.items():
  1564. if (
  1565. new_sha1 not in have
  1566. and new_sha1 not in want
  1567. and new_sha1 != ZERO_SHA
  1568. ):
  1569. want.append(new_sha1)
  1570. if not want and set(new_refs.items()).issubset(set(old_refs.items())):
  1571. return SendPackResult(new_refs, ref_status={})
  1572. target.object_store.add_pack_data(
  1573. *generate_pack_data(have, want, ofs_delta=True)
  1574. )
  1575. ref_status = {}
  1576. for refname, new_sha1 in new_refs.items():
  1577. old_sha1 = old_refs.get(refname, ZERO_SHA)
  1578. if new_sha1 != ZERO_SHA:
  1579. if not target.refs.set_if_equals(refname, old_sha1, new_sha1):
  1580. msg = f"unable to set {refname} to {new_sha1}"
  1581. progress(msg)
  1582. ref_status[refname] = msg
  1583. else:
  1584. if not target.refs.remove_if_equals(refname, old_sha1):
  1585. progress(f"unable to remove {refname}")
  1586. ref_status[refname] = "unable to remove"
  1587. return SendPackResult(new_refs, ref_status=ref_status)
  1588. def fetch(
  1589. self,
  1590. path: str,
  1591. target: Repo,
  1592. determine_wants: Optional[
  1593. Callable[[dict[bytes, bytes], Optional[int]], list[bytes]]
  1594. ] = None,
  1595. progress: Optional[Callable[[bytes], None]] = None,
  1596. depth: Optional[int] = None,
  1597. ref_prefix: Optional[list[Ref]] = None,
  1598. filter_spec: Optional[bytes] = None,
  1599. protocol_version: Optional[int] = None,
  1600. **kwargs,
  1601. ):
  1602. """Fetch into a target repository.
  1603. Args:
  1604. path: Path to fetch from (as bytestring)
  1605. target: Target repository to fetch into
  1606. determine_wants: Optional function determine what refs
  1607. to fetch. Receives dictionary of name->sha, should return
  1608. list of shas to fetch. Defaults to all shas.
  1609. progress: Optional progress function
  1610. depth: Shallow fetch depth
  1611. ref_prefix: List of prefixes of desired references, as a list of
  1612. bytestrings. Filtering is done by the server if supported, and
  1613. client side otherwise.
  1614. filter_spec: A git-rev-list-style object filter spec, as bytestring.
  1615. Only used if the server supports the Git protocol-v2 'filter'
  1616. feature, and ignored otherwise.
  1617. Returns:
  1618. FetchPackResult object
  1619. """
  1620. with self._open_repo(path) as r:
  1621. refs = r.fetch(
  1622. target,
  1623. determine_wants=determine_wants,
  1624. progress=progress,
  1625. depth=depth,
  1626. )
  1627. return FetchPackResult(refs, r.refs.get_symrefs(), agent_string())
  1628. def fetch_pack(
  1629. self,
  1630. path,
  1631. determine_wants,
  1632. graph_walker,
  1633. pack_data,
  1634. progress=None,
  1635. depth=None,
  1636. ref_prefix: Optional[list[Ref]] = None,
  1637. filter_spec: Optional[bytes] = None,
  1638. protocol_version: Optional[int] = None,
  1639. ) -> FetchPackResult:
  1640. """Retrieve a pack from a local on-disk repository.
  1641. Args:
  1642. path: Remote path to fetch from
  1643. determine_wants: Function determine what refs
  1644. to fetch. Receives dictionary of name->sha, should return
  1645. list of shas to fetch.
  1646. graph_walker: Object with next() and ack().
  1647. pack_data: Callback called for each bit of data in the pack
  1648. progress: Callback for progress reports (strings)
  1649. depth: Shallow fetch depth
  1650. ref_prefix: List of prefixes of desired references, as a list of
  1651. bytestrings. Filtering is done by the server if supported, and
  1652. client side otherwise.
  1653. filter_spec: A git-rev-list-style object filter spec, as bytestring.
  1654. Only used if the server supports the Git protocol-v2 'filter'
  1655. feature, and ignored otherwise.
  1656. Returns:
  1657. FetchPackResult object
  1658. """
  1659. with self._open_repo(path) as r:
  1660. missing_objects = r.find_missing_objects(
  1661. determine_wants, graph_walker, progress=progress, depth=depth
  1662. )
  1663. other_haves = missing_objects.get_remote_has()
  1664. object_ids = list(missing_objects)
  1665. symrefs = r.refs.get_symrefs()
  1666. agent = agent_string()
  1667. # Did the process short-circuit (e.g. in a stateless RPC call)?
  1668. # Note that the client still expects a 0-object pack in most cases.
  1669. if object_ids is None:
  1670. return FetchPackResult(None, symrefs, agent)
  1671. write_pack_from_container(
  1672. pack_data, r.object_store, object_ids, other_haves=other_haves
  1673. )
  1674. return FetchPackResult(r.get_refs(), symrefs, agent)
  1675. def get_refs(
  1676. self,
  1677. path,
  1678. protocol_version: Optional[int] = None,
  1679. ref_prefix: Optional[list[Ref]] = None,
  1680. ):
  1681. """Retrieve the current refs from a local on-disk repository."""
  1682. with self._open_repo(path) as target:
  1683. return target.get_refs()
  1684. # What Git client to use for local access
  1685. default_local_git_client_cls = LocalGitClient
  1686. class SSHVendor:
  1687. """A client side SSH implementation."""
  1688. def run_command(
  1689. self,
  1690. host,
  1691. command,
  1692. username=None,
  1693. port=None,
  1694. password=None,
  1695. key_filename=None,
  1696. ssh_command=None,
  1697. protocol_version: Optional[int] = None,
  1698. ):
  1699. """Connect to an SSH server.
  1700. Run a command remotely and return a file-like object for interaction
  1701. with the remote command.
  1702. Args:
  1703. host: Host name
  1704. command: Command to run (as argv array)
  1705. username: Optional ame of user to log in as
  1706. port: Optional SSH port to use
  1707. password: Optional ssh password for login or private key
  1708. key_filename: Optional path to private keyfile
  1709. ssh_command: Optional SSH command
  1710. protocol_version: Desired Git protocol version. By default the highest
  1711. mutually supported protocol version will be used.
  1712. """
  1713. raise NotImplementedError(self.run_command)
  1714. class StrangeHostname(Exception):
  1715. """Refusing to connect to strange SSH hostname."""
  1716. def __init__(self, hostname) -> None:
  1717. super().__init__(hostname)
  1718. class SubprocessSSHVendor(SSHVendor):
  1719. """SSH vendor that shells out to the local 'ssh' command."""
  1720. def run_command(
  1721. self,
  1722. host,
  1723. command,
  1724. username=None,
  1725. port=None,
  1726. password=None,
  1727. key_filename=None,
  1728. ssh_command=None,
  1729. protocol_version: Optional[int] = None,
  1730. ):
  1731. if password is not None:
  1732. raise NotImplementedError(
  1733. "Setting password not supported by SubprocessSSHVendor."
  1734. )
  1735. if ssh_command:
  1736. import shlex
  1737. args = [*shlex.split(ssh_command, posix=sys.platform != "win32"), "-x"]
  1738. else:
  1739. args = ["ssh", "-x"]
  1740. if port:
  1741. args.extend(["-p", str(port)])
  1742. if key_filename:
  1743. args.extend(["-i", str(key_filename)])
  1744. if protocol_version is None:
  1745. protocol_version = DEFAULT_GIT_PROTOCOL_VERSION_FETCH
  1746. if protocol_version > 0:
  1747. args.extend(["-o", f"SetEnv GIT_PROTOCOL=version={protocol_version}"])
  1748. if username:
  1749. host = f"{username}@{host}"
  1750. if host.startswith("-"):
  1751. raise StrangeHostname(hostname=host)
  1752. args.append(host)
  1753. proc = subprocess.Popen(
  1754. [*args, command],
  1755. bufsize=0,
  1756. stdin=subprocess.PIPE,
  1757. stdout=subprocess.PIPE,
  1758. stderr=subprocess.PIPE,
  1759. )
  1760. return SubprocessWrapper(proc)
  1761. class PLinkSSHVendor(SSHVendor):
  1762. """SSH vendor that shells out to the local 'plink' command."""
  1763. def run_command(
  1764. self,
  1765. host,
  1766. command,
  1767. username=None,
  1768. port=None,
  1769. password=None,
  1770. key_filename=None,
  1771. ssh_command=None,
  1772. protocol_version: Optional[int] = None,
  1773. ):
  1774. if ssh_command:
  1775. import shlex
  1776. args = [*shlex.split(ssh_command, posix=sys.platform != "win32"), "-ssh"]
  1777. elif sys.platform == "win32":
  1778. args = ["plink.exe", "-ssh"]
  1779. else:
  1780. args = ["plink", "-ssh"]
  1781. if password is not None:
  1782. import warnings
  1783. warnings.warn(
  1784. "Invoking PLink with a password exposes the password in the "
  1785. "process list."
  1786. )
  1787. args.extend(["-pw", str(password)])
  1788. if port:
  1789. args.extend(["-P", str(port)])
  1790. if key_filename:
  1791. args.extend(["-i", str(key_filename)])
  1792. if username:
  1793. host = f"{username}@{host}"
  1794. if host.startswith("-"):
  1795. raise StrangeHostname(hostname=host)
  1796. args.append(host)
  1797. # plink.exe does not provide a way to pass environment variables
  1798. # via the command line. The best we can do is set an environment
  1799. # variable and hope that plink will pass it to the server. If this
  1800. # does not work then the server should behave as if we had requested
  1801. # protocol version 0.
  1802. env = copy.deepcopy(os.environ)
  1803. if protocol_version is None:
  1804. protocol_version = DEFAULT_GIT_PROTOCOL_VERSION_FETCH
  1805. if protocol_version > 0:
  1806. env["GIT_PROTOCOL"] = f"version={protocol_version}"
  1807. proc = subprocess.Popen(
  1808. [*args, command],
  1809. bufsize=0,
  1810. stdin=subprocess.PIPE,
  1811. stdout=subprocess.PIPE,
  1812. stderr=subprocess.PIPE,
  1813. env=env,
  1814. )
  1815. return SubprocessWrapper(proc)
  1816. def ParamikoSSHVendor(**kwargs):
  1817. import warnings
  1818. warnings.warn(
  1819. "ParamikoSSHVendor has been moved to dulwich.contrib.paramiko_vendor.",
  1820. DeprecationWarning,
  1821. )
  1822. from .contrib.paramiko_vendor import ParamikoSSHVendor
  1823. return ParamikoSSHVendor(**kwargs)
  1824. # Can be overridden by users
  1825. get_ssh_vendor = SubprocessSSHVendor
  1826. class SSHGitClient(TraditionalGitClient):
  1827. def __init__(
  1828. self,
  1829. host,
  1830. port=None,
  1831. username=None,
  1832. vendor=None,
  1833. config=None,
  1834. password=None,
  1835. key_filename=None,
  1836. ssh_command=None,
  1837. **kwargs,
  1838. ) -> None:
  1839. self.host = host
  1840. self.port = port
  1841. self.username = username
  1842. self.password = password
  1843. self.key_filename = key_filename
  1844. self.ssh_command = ssh_command or os.environ.get(
  1845. "GIT_SSH_COMMAND", os.environ.get("GIT_SSH")
  1846. )
  1847. super().__init__(**kwargs)
  1848. self.alternative_paths: dict[bytes, bytes] = {}
  1849. if vendor is not None:
  1850. self.ssh_vendor = vendor
  1851. else:
  1852. self.ssh_vendor = get_ssh_vendor()
  1853. def get_url(self, path):
  1854. netloc = self.host
  1855. if self.port is not None:
  1856. netloc += ":%d" % self.port
  1857. if self.username is not None:
  1858. netloc = urlquote(self.username, "@/:") + "@" + netloc
  1859. return urlunsplit(("ssh", netloc, path, "", ""))
  1860. @classmethod
  1861. def from_parsedurl(cls, parsedurl, **kwargs):
  1862. return cls(
  1863. host=parsedurl.hostname,
  1864. port=parsedurl.port,
  1865. username=parsedurl.username,
  1866. **kwargs,
  1867. )
  1868. def _get_cmd_path(self, cmd):
  1869. cmd = self.alternative_paths.get(cmd, b"git-" + cmd)
  1870. assert isinstance(cmd, bytes)
  1871. return cmd
  1872. def _connect(
  1873. self,
  1874. cmd: bytes,
  1875. path: Union[str, bytes],
  1876. protocol_version: Optional[int] = None,
  1877. ) -> tuple[Protocol, Callable[[], bool], Optional[IO[bytes]]]:
  1878. if not isinstance(cmd, bytes):
  1879. raise TypeError(cmd)
  1880. if isinstance(path, bytes):
  1881. path = path.decode(self._remote_path_encoding)
  1882. if path.startswith("/~"):
  1883. path = path[1:]
  1884. argv = (
  1885. self._get_cmd_path(cmd).decode(self._remote_path_encoding)
  1886. + " '"
  1887. + path
  1888. + "'"
  1889. )
  1890. kwargs = {}
  1891. if self.password is not None:
  1892. kwargs["password"] = self.password
  1893. if self.key_filename is not None:
  1894. kwargs["key_filename"] = self.key_filename
  1895. # GIT_SSH_COMMAND takes precedence over GIT_SSH
  1896. if self.ssh_command is not None:
  1897. kwargs["ssh_command"] = self.ssh_command
  1898. con = self.ssh_vendor.run_command(
  1899. self.host,
  1900. argv,
  1901. port=self.port,
  1902. username=self.username,
  1903. protocol_version=protocol_version,
  1904. **kwargs,
  1905. )
  1906. return (
  1907. Protocol(
  1908. con.read,
  1909. con.write,
  1910. con.close,
  1911. report_activity=self._report_activity,
  1912. ),
  1913. con.can_read,
  1914. getattr(con, "stderr", None),
  1915. )
  1916. def default_user_agent_string():
  1917. # Start user agent with "git/", because GitHub requires this. :-( See
  1918. # https://github.com/jelmer/dulwich/issues/562 for details.
  1919. return "git/dulwich/{}".format(".".join([str(x) for x in dulwich.__version__]))
  1920. def default_urllib3_manager(
  1921. config,
  1922. pool_manager_cls=None,
  1923. proxy_manager_cls=None,
  1924. base_url=None,
  1925. **override_kwargs,
  1926. ) -> Union["urllib3.ProxyManager", "urllib3.PoolManager"]:
  1927. """Return urllib3 connection pool manager.
  1928. Honour detected proxy configurations.
  1929. Args:
  1930. config: `dulwich.config.ConfigDict` instance with Git configuration.
  1931. override_kwargs: Additional arguments for `urllib3.ProxyManager`
  1932. Returns:
  1933. Either pool_manager_cls (defaults to `urllib3.ProxyManager`) instance for
  1934. proxy configurations, proxy_manager_cls
  1935. (defaults to `urllib3.PoolManager`) instance otherwise
  1936. """
  1937. proxy_server = user_agent = None
  1938. ca_certs = ssl_verify = None
  1939. if proxy_server is None:
  1940. for proxyname in ("https_proxy", "http_proxy", "all_proxy"):
  1941. proxy_server = os.environ.get(proxyname)
  1942. if proxy_server:
  1943. break
  1944. if proxy_server:
  1945. if check_for_proxy_bypass(base_url):
  1946. proxy_server = None
  1947. if config is not None:
  1948. if proxy_server is None:
  1949. try:
  1950. proxy_server = config.get(b"http", b"proxy")
  1951. except KeyError:
  1952. pass
  1953. try:
  1954. user_agent = config.get(b"http", b"useragent")
  1955. except KeyError:
  1956. pass
  1957. # TODO(jelmer): Support per-host settings
  1958. try:
  1959. ssl_verify = config.get_boolean(b"http", b"sslVerify")
  1960. except KeyError:
  1961. ssl_verify = True
  1962. try:
  1963. ca_certs = config.get(b"http", b"sslCAInfo")
  1964. except KeyError:
  1965. ca_certs = None
  1966. if user_agent is None:
  1967. user_agent = default_user_agent_string()
  1968. headers = {"User-agent": user_agent}
  1969. kwargs = {
  1970. "ca_certs": ca_certs,
  1971. }
  1972. if ssl_verify is True:
  1973. kwargs["cert_reqs"] = "CERT_REQUIRED"
  1974. elif ssl_verify is False:
  1975. kwargs["cert_reqs"] = "CERT_NONE"
  1976. else:
  1977. # Default to SSL verification
  1978. kwargs["cert_reqs"] = "CERT_REQUIRED"
  1979. kwargs.update(override_kwargs)
  1980. import urllib3
  1981. if proxy_server is not None:
  1982. if proxy_manager_cls is None:
  1983. proxy_manager_cls = urllib3.ProxyManager
  1984. if not isinstance(proxy_server, str):
  1985. proxy_server = proxy_server.decode()
  1986. proxy_server_url = urlparse(proxy_server)
  1987. if proxy_server_url.username is not None:
  1988. proxy_headers = urllib3.make_headers(
  1989. proxy_basic_auth=f"{proxy_server_url.username}:{proxy_server_url.password or ''}" # type: ignore
  1990. )
  1991. else:
  1992. proxy_headers = {}
  1993. manager = proxy_manager_cls(
  1994. proxy_server, proxy_headers=proxy_headers, headers=headers, **kwargs
  1995. )
  1996. else:
  1997. if pool_manager_cls is None:
  1998. pool_manager_cls = urllib3.PoolManager
  1999. manager = pool_manager_cls(headers=headers, **kwargs)
  2000. return manager
  2001. def check_for_proxy_bypass(base_url):
  2002. # Check if a proxy bypass is defined with the no_proxy environment variable
  2003. if base_url: # only check if base_url is provided
  2004. no_proxy_str = os.environ.get("no_proxy")
  2005. if no_proxy_str:
  2006. # implementation based on curl behavior: https://curl.se/libcurl/c/CURLOPT_NOPROXY.html
  2007. # get hostname of provided parsed url
  2008. parsed_url = urlparse(base_url)
  2009. hostname = parsed_url.hostname
  2010. if hostname:
  2011. import ipaddress
  2012. # check if hostname is an ip address
  2013. try:
  2014. hostname_ip = ipaddress.ip_address(hostname)
  2015. except ValueError:
  2016. hostname_ip = None
  2017. no_proxy_values = no_proxy_str.split(",")
  2018. for no_proxy_value in no_proxy_values:
  2019. no_proxy_value = no_proxy_value.strip()
  2020. if no_proxy_value:
  2021. no_proxy_value = no_proxy_value.lower()
  2022. no_proxy_value = no_proxy_value.lstrip(
  2023. "."
  2024. ) # ignore leading dots
  2025. if hostname_ip:
  2026. # check if no_proxy_value is a ip network
  2027. try:
  2028. no_proxy_value_network = ipaddress.ip_network(
  2029. no_proxy_value, strict=False
  2030. )
  2031. except ValueError:
  2032. no_proxy_value_network = None
  2033. if no_proxy_value_network:
  2034. # if hostname is a ip address and no_proxy_value is a ip network -> check if ip address is part of network
  2035. if hostname_ip in no_proxy_value_network:
  2036. return True
  2037. if no_proxy_value == "*":
  2038. # '*' is special case for always bypass proxy
  2039. return True
  2040. if hostname == no_proxy_value:
  2041. return True
  2042. no_proxy_value = (
  2043. "." + no_proxy_value
  2044. ) # add a dot to only match complete domains
  2045. if hostname.endswith(no_proxy_value):
  2046. return True
  2047. return False
  2048. class AbstractHttpGitClient(GitClient):
  2049. """Abstract base class for HTTP Git Clients.
  2050. This is agonistic of the actual HTTP implementation.
  2051. Subclasses should provide an implementation of the
  2052. _http_request method.
  2053. """
  2054. def __init__(self, base_url, dumb=False, **kwargs) -> None:
  2055. self._base_url = base_url.rstrip("/") + "/"
  2056. self.dumb = dumb
  2057. GitClient.__init__(self, **kwargs)
  2058. def _http_request(self, url, headers=None, data=None):
  2059. """Perform HTTP request.
  2060. Args:
  2061. url: Request URL.
  2062. headers: Optional custom headers to override defaults.
  2063. data: Request data.
  2064. Returns:
  2065. Tuple (response, read), where response is an urllib3
  2066. response object with additional content_type and
  2067. redirect_location properties, and read is a consumable read
  2068. method for the response data.
  2069. Raises:
  2070. GitProtocolError
  2071. """
  2072. raise NotImplementedError(self._http_request)
  2073. def _discover_references(
  2074. self,
  2075. service,
  2076. base_url,
  2077. protocol_version: Optional[int] = None,
  2078. ref_prefix: Optional[list[Ref]] = None,
  2079. ) -> tuple[
  2080. dict[Ref, ObjectID], set[bytes], str, dict[Ref, Ref], dict[Ref, ObjectID]
  2081. ]:
  2082. if (
  2083. protocol_version is not None
  2084. and protocol_version not in GIT_PROTOCOL_VERSIONS
  2085. ):
  2086. raise ValueError("unknown Git protocol version %d" % protocol_version)
  2087. assert base_url[-1] == "/"
  2088. tail = "info/refs"
  2089. headers = {"Accept": "*/*"}
  2090. if self.dumb is not True:
  2091. tail += "?service={}".format(service.decode("ascii"))
  2092. # Enable protocol v2 only when fetching, not when pushing.
  2093. # Git does not yet implement push over protocol v2, and as of
  2094. # git version 2.37.3 git-http-backend's behaviour is erratic if
  2095. # we try: It responds with a Git-protocol-v1-style ref listing
  2096. # which lacks the "001f# service=git-receive-pack" marker.
  2097. if service == b"git-upload-pack":
  2098. if protocol_version is None:
  2099. self.protocol_version = DEFAULT_GIT_PROTOCOL_VERSION_FETCH
  2100. else:
  2101. self.protocol_version = protocol_version
  2102. if self.protocol_version == 2:
  2103. headers["Git-Protocol"] = "version=2"
  2104. else:
  2105. self.protocol_version = DEFAULT_GIT_PROTOCOL_VERSION_SEND
  2106. url = urljoin(base_url, tail)
  2107. resp, read = self._http_request(url, headers)
  2108. if resp.redirect_location:
  2109. # Something changed (redirect!), so let's update the base URL
  2110. if not resp.redirect_location.endswith(tail):
  2111. raise GitProtocolError(
  2112. f"Redirected from URL {url} to URL {resp.redirect_location} without {tail}"
  2113. )
  2114. base_url = urljoin(url, resp.redirect_location[: -len(tail)])
  2115. try:
  2116. self.dumb = resp.content_type is None or not resp.content_type.startswith(
  2117. "application/x-git-"
  2118. )
  2119. if not self.dumb:
  2120. def begin_protocol_v2(proto):
  2121. nonlocal ref_prefix
  2122. server_capabilities = read_server_capabilities(proto.read_pkt_seq())
  2123. if ref_prefix is None:
  2124. ref_prefix = DEFAULT_REF_PREFIX
  2125. pkts = [
  2126. b"symrefs",
  2127. b"peel",
  2128. ]
  2129. for prefix in ref_prefix:
  2130. pkts.append(b"ref-prefix " + prefix)
  2131. body = b"".join(
  2132. [pkt_line(b"command=ls-refs\n"), b"0001", pkt_seq(*pkts)]
  2133. )
  2134. resp, read = self._smart_request(
  2135. service.decode("ascii"), base_url, body
  2136. )
  2137. proto = Protocol(read, None)
  2138. return server_capabilities, resp, read, proto
  2139. proto = Protocol(read, None)
  2140. server_protocol_version = negotiate_protocol_version(proto)
  2141. if server_protocol_version not in GIT_PROTOCOL_VERSIONS:
  2142. raise ValueError(
  2143. "unknown Git protocol version %d used by server"
  2144. % server_protocol_version
  2145. )
  2146. if protocol_version and server_protocol_version > protocol_version:
  2147. raise ValueError(
  2148. "bad Git protocol version %d used by server"
  2149. % server_protocol_version
  2150. )
  2151. self.protocol_version = server_protocol_version
  2152. if self.protocol_version == 2:
  2153. server_capabilities, resp, read, proto = begin_protocol_v2(proto)
  2154. (refs, symrefs, peeled) = read_pkt_refs_v2(proto.read_pkt_seq())
  2155. return refs, server_capabilities, base_url, symrefs, peeled
  2156. else:
  2157. try:
  2158. [pkt] = list(proto.read_pkt_seq())
  2159. except ValueError as exc:
  2160. raise GitProtocolError(
  2161. "unexpected number of packets received"
  2162. ) from exc
  2163. if pkt.rstrip(b"\n") != (b"# service=" + service):
  2164. raise GitProtocolError(
  2165. f"unexpected first line {pkt!r} from smart server"
  2166. )
  2167. # Github sends "version 2" after sending the service name.
  2168. # Try to negotiate protocol version 2 again.
  2169. server_protocol_version = negotiate_protocol_version(proto)
  2170. if server_protocol_version not in GIT_PROTOCOL_VERSIONS:
  2171. raise ValueError(
  2172. "unknown Git protocol version %d used by server"
  2173. % server_protocol_version
  2174. )
  2175. if protocol_version and server_protocol_version > protocol_version:
  2176. raise ValueError(
  2177. "bad Git protocol version %d used by server"
  2178. % server_protocol_version
  2179. )
  2180. self.protocol_version = server_protocol_version
  2181. if self.protocol_version == 2:
  2182. server_capabilities, resp, read, proto = begin_protocol_v2(
  2183. proto
  2184. )
  2185. (refs, symrefs, peeled) = read_pkt_refs_v2(proto.read_pkt_seq())
  2186. else:
  2187. (
  2188. refs,
  2189. server_capabilities,
  2190. ) = read_pkt_refs_v1(proto.read_pkt_seq())
  2191. (refs, peeled) = split_peeled_refs(refs)
  2192. (symrefs, agent) = _extract_symrefs_and_agent(
  2193. server_capabilities
  2194. )
  2195. if ref_prefix is not None:
  2196. refs = filter_ref_prefix(refs, ref_prefix)
  2197. return refs, server_capabilities, base_url, symrefs, peeled
  2198. else:
  2199. self.protocol_version = 0 # dumb servers only support protocol v0
  2200. (refs, peeled) = split_peeled_refs(read_info_refs(resp))
  2201. if ref_prefix is not None:
  2202. refs = filter_ref_prefix(refs, ref_prefix)
  2203. return refs, set(), base_url, {}, peeled
  2204. finally:
  2205. resp.close()
  2206. def _smart_request(self, service, url, data):
  2207. """Send a 'smart' HTTP request.
  2208. This is a simple wrapper around _http_request that sets
  2209. a couple of extra headers.
  2210. """
  2211. assert url[-1] == "/"
  2212. url = urljoin(url, service)
  2213. result_content_type = f"application/x-{service}-result"
  2214. headers = {
  2215. "Content-Type": f"application/x-{service}-request",
  2216. "Accept": result_content_type,
  2217. }
  2218. if self.protocol_version == 2:
  2219. headers["Git-Protocol"] = "version=2"
  2220. if isinstance(data, bytes):
  2221. headers["Content-Length"] = str(len(data))
  2222. resp, read = self._http_request(url, headers, data)
  2223. if resp.content_type.split(";")[0] != result_content_type:
  2224. raise GitProtocolError(
  2225. f"Invalid content-type from server: {resp.content_type}"
  2226. )
  2227. return resp, read
  2228. def send_pack(self, path, update_refs, generate_pack_data, progress=None):
  2229. """Upload a pack to a remote repository.
  2230. Args:
  2231. path: Repository path (as bytestring)
  2232. update_refs: Function to determine changes to remote refs.
  2233. Receives dict with existing remote refs, returns dict with
  2234. changed refs (name -> sha, where sha=ZERO_SHA for deletions)
  2235. generate_pack_data: Function that can return a tuple
  2236. with number of elements and pack data to upload.
  2237. progress: Optional progress function
  2238. Returns:
  2239. SendPackResult
  2240. Raises:
  2241. SendPackError: if server rejects the pack data
  2242. """
  2243. url = self._get_url(path)
  2244. old_refs, server_capabilities, url, symrefs, peeled = self._discover_references(
  2245. b"git-receive-pack", url
  2246. )
  2247. (
  2248. negotiated_capabilities,
  2249. agent,
  2250. ) = self._negotiate_receive_pack_capabilities(server_capabilities)
  2251. negotiated_capabilities.add(capability_agent())
  2252. if CAPABILITY_REPORT_STATUS in negotiated_capabilities:
  2253. self._report_status_parser = ReportStatusParser()
  2254. new_refs = update_refs(dict(old_refs))
  2255. if new_refs is None:
  2256. # Determine wants function is aborting the push.
  2257. return SendPackResult(old_refs, agent=agent, ref_status={})
  2258. if set(new_refs.items()).issubset(set(old_refs.items())):
  2259. return SendPackResult(new_refs, agent=agent, ref_status={})
  2260. if self.dumb:
  2261. raise NotImplementedError(self.fetch_pack)
  2262. def body_generator():
  2263. header_handler = _v1ReceivePackHeader(
  2264. negotiated_capabilities, old_refs, new_refs
  2265. )
  2266. for pkt in header_handler:
  2267. yield pkt_line(pkt)
  2268. pack_data_count, pack_data = generate_pack_data(
  2269. header_handler.have,
  2270. header_handler.want,
  2271. ofs_delta=(CAPABILITY_OFS_DELTA in negotiated_capabilities),
  2272. )
  2273. if self._should_send_pack(new_refs):
  2274. yield from PackChunkGenerator(pack_data_count, pack_data)
  2275. resp, read = self._smart_request("git-receive-pack", url, data=body_generator())
  2276. try:
  2277. resp_proto = Protocol(read, None)
  2278. ref_status = self._handle_receive_pack_tail(
  2279. resp_proto, negotiated_capabilities, progress
  2280. )
  2281. return SendPackResult(new_refs, agent=agent, ref_status=ref_status)
  2282. finally:
  2283. resp.close()
  2284. def fetch_pack(
  2285. self,
  2286. path,
  2287. determine_wants,
  2288. graph_walker,
  2289. pack_data,
  2290. progress=None,
  2291. depth=None,
  2292. ref_prefix: Optional[list[Ref]] = None,
  2293. filter_spec=None,
  2294. protocol_version: Optional[int] = None,
  2295. ):
  2296. """Retrieve a pack from a git smart server.
  2297. Args:
  2298. path: Path to fetch from
  2299. determine_wants: Callback that returns list of commits to fetch
  2300. graph_walker: Object with next() and ack().
  2301. pack_data: Callback called for each bit of data in the pack
  2302. progress: Callback for progress reports (strings)
  2303. depth: Depth for request
  2304. ref_prefix: List of prefixes of desired references, as a list of
  2305. bytestrings. Filtering is done by the server if supported, and
  2306. client side otherwise.
  2307. filter_spec: A git-rev-list-style object filter spec, as bytestring.
  2308. Only used if the server supports the Git protocol-v2 'filter'
  2309. feature, and ignored otherwise.
  2310. protocol_version: Desired Git protocol version. By default the highest
  2311. mutually supported protocol version will be used.
  2312. Returns:
  2313. FetchPackResult object
  2314. """
  2315. url = self._get_url(path)
  2316. refs, server_capabilities, url, symrefs, peeled = self._discover_references(
  2317. b"git-upload-pack",
  2318. url,
  2319. protocol_version=protocol_version,
  2320. ref_prefix=ref_prefix,
  2321. )
  2322. (
  2323. negotiated_capabilities,
  2324. capa_symrefs,
  2325. agent,
  2326. ) = self._negotiate_upload_pack_capabilities(server_capabilities)
  2327. if not symrefs and capa_symrefs:
  2328. symrefs = capa_symrefs
  2329. if depth is not None:
  2330. wants = determine_wants(refs, depth=depth)
  2331. else:
  2332. wants = determine_wants(refs)
  2333. if wants is not None:
  2334. wants = [cid for cid in wants if cid != ZERO_SHA]
  2335. if not wants:
  2336. return FetchPackResult(refs, symrefs, agent)
  2337. if self.dumb:
  2338. raise NotImplementedError(self.fetch_pack)
  2339. req_data = BytesIO()
  2340. req_proto = Protocol(None, req_data.write)
  2341. (new_shallow, new_unshallow) = _handle_upload_pack_head(
  2342. req_proto,
  2343. negotiated_capabilities,
  2344. graph_walker,
  2345. wants,
  2346. can_read=None,
  2347. depth=depth,
  2348. protocol_version=self.protocol_version,
  2349. )
  2350. if self.protocol_version == 2:
  2351. data = pkt_line(b"command=fetch\n") + b"0001"
  2352. if (
  2353. find_capability(
  2354. negotiated_capabilities, CAPABILITY_FETCH, CAPABILITY_FILTER
  2355. )
  2356. and filter_spec
  2357. ):
  2358. data += pkt_line(b"filter %s\n" % filter_spec)
  2359. elif filter_spec:
  2360. self._warn_filter_objects()
  2361. data += req_data.getvalue()
  2362. else:
  2363. if filter_spec:
  2364. self._warn_filter_objects()
  2365. data = req_data.getvalue()
  2366. resp, read = self._smart_request("git-upload-pack", url, data)
  2367. try:
  2368. resp_proto = Protocol(read, None)
  2369. if new_shallow is None and new_unshallow is None:
  2370. (new_shallow, new_unshallow) = _read_shallow_updates(
  2371. resp_proto.read_pkt_seq()
  2372. )
  2373. _handle_upload_pack_tail(
  2374. resp_proto,
  2375. negotiated_capabilities,
  2376. graph_walker,
  2377. pack_data,
  2378. progress,
  2379. protocol_version=self.protocol_version,
  2380. )
  2381. return FetchPackResult(refs, symrefs, agent, new_shallow, new_unshallow)
  2382. finally:
  2383. resp.close()
  2384. def get_refs(
  2385. self,
  2386. path,
  2387. protocol_version: Optional[int] = None,
  2388. ref_prefix: Optional[list[Ref]] = None,
  2389. ):
  2390. """Retrieve the current refs from a git smart server."""
  2391. url = self._get_url(path)
  2392. refs, _, _, _, peeled = self._discover_references(
  2393. b"git-upload-pack",
  2394. url,
  2395. protocol_version=protocol_version,
  2396. ref_prefix=ref_prefix,
  2397. )
  2398. for refname, refvalue in peeled.items():
  2399. refs[refname + PEELED_TAG_SUFFIX] = refvalue
  2400. return refs
  2401. def get_url(self, path):
  2402. return self._get_url(path).rstrip("/")
  2403. def _get_url(self, path):
  2404. return urljoin(self._base_url, path).rstrip("/") + "/"
  2405. @classmethod
  2406. def from_parsedurl(cls, parsedurl, **kwargs):
  2407. password = parsedurl.password
  2408. if password is not None:
  2409. kwargs["password"] = urlunquote(password)
  2410. username = parsedurl.username
  2411. if username is not None:
  2412. kwargs["username"] = urlunquote(username)
  2413. return cls(urlunparse(parsedurl), **kwargs)
  2414. def __repr__(self) -> str:
  2415. return f"{type(self).__name__}({self._base_url!r}, dumb={self.dumb!r})"
  2416. def _wrap_urllib3_exceptions(func):
  2417. from urllib3.exceptions import ProtocolError
  2418. def wrapper(*args, **kwargs):
  2419. try:
  2420. return func(*args, **kwargs)
  2421. except ProtocolError as error:
  2422. raise GitProtocolError(str(error)) from error
  2423. return wrapper
  2424. class Urllib3HttpGitClient(AbstractHttpGitClient):
  2425. def __init__(
  2426. self,
  2427. base_url,
  2428. dumb=None,
  2429. pool_manager=None,
  2430. config=None,
  2431. username=None,
  2432. password=None,
  2433. **kwargs,
  2434. ) -> None:
  2435. self._username = username
  2436. self._password = password
  2437. if pool_manager is None:
  2438. self.pool_manager = default_urllib3_manager(config, base_url=base_url)
  2439. else:
  2440. self.pool_manager = pool_manager
  2441. if username is not None:
  2442. # No escaping needed: ":" is not allowed in username:
  2443. # https://tools.ietf.org/html/rfc2617#section-2
  2444. credentials = f"{username}:{password or ''}"
  2445. import urllib3.util
  2446. basic_auth = urllib3.util.make_headers(basic_auth=credentials)
  2447. self.pool_manager.headers.update(basic_auth) # type: ignore
  2448. self.config = config
  2449. super().__init__(base_url=base_url, dumb=dumb, **kwargs)
  2450. def _get_url(self, path):
  2451. if not isinstance(path, str):
  2452. # urllib3.util.url._encode_invalid_chars() converts the path back
  2453. # to bytes using the utf-8 codec.
  2454. path = path.decode("utf-8")
  2455. return urljoin(self._base_url, path).rstrip("/") + "/"
  2456. def _http_request(self, url, headers=None, data=None):
  2457. import urllib3.exceptions
  2458. req_headers = self.pool_manager.headers.copy()
  2459. if headers is not None:
  2460. req_headers.update(headers)
  2461. req_headers["Pragma"] = "no-cache"
  2462. try:
  2463. if data is None:
  2464. resp = self.pool_manager.request(
  2465. "GET", url, headers=req_headers, preload_content=False
  2466. )
  2467. else:
  2468. resp = self.pool_manager.request(
  2469. "POST", url, headers=req_headers, body=data, preload_content=False
  2470. )
  2471. except urllib3.exceptions.HTTPError as e:
  2472. raise GitProtocolError(str(e)) from e
  2473. if resp.status == 404:
  2474. raise NotGitRepository
  2475. if resp.status == 401:
  2476. raise HTTPUnauthorized(resp.headers.get("WWW-Authenticate"), url)
  2477. if resp.status == 407:
  2478. raise HTTPProxyUnauthorized(resp.headers.get("Proxy-Authenticate"), url)
  2479. if resp.status != 200:
  2480. raise GitProtocolError(
  2481. "unexpected http resp %d for %s" % (resp.status, url)
  2482. )
  2483. resp.content_type = resp.headers.get("Content-Type")
  2484. # Check if geturl() is available (urllib3 version >= 1.23)
  2485. try:
  2486. resp_url = resp.geturl()
  2487. except AttributeError:
  2488. # get_redirect_location() is available for urllib3 >= 1.1
  2489. resp.redirect_location = resp.get_redirect_location()
  2490. else:
  2491. resp.redirect_location = resp_url if resp_url != url else ""
  2492. return resp, _wrap_urllib3_exceptions(resp.read)
  2493. HttpGitClient = Urllib3HttpGitClient
  2494. def _win32_url_to_path(parsed) -> str:
  2495. """Convert a file: URL to a path.
  2496. https://datatracker.ietf.org/doc/html/rfc8089
  2497. """
  2498. assert sys.platform == "win32" or os.name == "nt"
  2499. assert parsed.scheme == "file"
  2500. _, netloc, path, _, _, _ = parsed
  2501. if netloc == "localhost" or not netloc:
  2502. netloc = ""
  2503. elif (
  2504. netloc
  2505. and len(netloc) >= 2
  2506. and netloc[0].isalpha()
  2507. and netloc[1:2] in (":", ":/")
  2508. ):
  2509. # file://C:/foo.bar/baz or file://C://foo.bar//baz
  2510. netloc = netloc[:2]
  2511. else:
  2512. raise NotImplementedError("Non-local file URLs are not supported")
  2513. global url2pathname
  2514. if url2pathname is None:
  2515. from urllib.request import url2pathname # type: ignore
  2516. return url2pathname(netloc + path) # type: ignore
  2517. def get_transport_and_path_from_url(
  2518. url: str, config: Optional[Config] = None, operation: Optional[str] = None, **kwargs
  2519. ) -> tuple[GitClient, str]:
  2520. """Obtain a git client from a URL.
  2521. Args:
  2522. url: URL to open (a unicode string)
  2523. config: Optional config object
  2524. operation: Kind of operation that'll be performed; "pull" or "push"
  2525. thin_packs: Whether or not thin packs should be retrieved
  2526. report_activity: Optional callback for reporting transport
  2527. activity.
  2528. Returns:
  2529. Tuple with client instance and relative path.
  2530. """
  2531. if config is not None:
  2532. url = apply_instead_of(config, url, push=(operation == "push"))
  2533. return _get_transport_and_path_from_url(
  2534. url, config=config, operation=operation, **kwargs
  2535. )
  2536. def _get_transport_and_path_from_url(url, config, operation, **kwargs):
  2537. parsed = urlparse(url)
  2538. if parsed.scheme == "git":
  2539. return (TCPGitClient.from_parsedurl(parsed, **kwargs), parsed.path)
  2540. elif parsed.scheme in ("git+ssh", "ssh"):
  2541. return SSHGitClient.from_parsedurl(parsed, **kwargs), parsed.path
  2542. elif parsed.scheme in ("http", "https"):
  2543. return (
  2544. HttpGitClient.from_parsedurl(parsed, config=config, **kwargs),
  2545. parsed.path,
  2546. )
  2547. elif parsed.scheme == "file":
  2548. if sys.platform == "win32" or os.name == "nt":
  2549. return default_local_git_client_cls(**kwargs), _win32_url_to_path(parsed)
  2550. return (
  2551. default_local_git_client_cls.from_parsedurl(parsed, **kwargs),
  2552. parsed.path,
  2553. )
  2554. raise ValueError(f"unknown scheme '{parsed.scheme}'")
  2555. def parse_rsync_url(location: str) -> tuple[Optional[str], str, str]:
  2556. """Parse a rsync-style URL."""
  2557. if ":" in location and "@" not in location:
  2558. # SSH with no user@, zero or one leading slash.
  2559. (host, path) = location.split(":", 1)
  2560. user = None
  2561. elif ":" in location:
  2562. # SSH with user@host:foo.
  2563. user_host, path = location.split(":", 1)
  2564. if "@" in user_host:
  2565. user, host = user_host.rsplit("@", 1)
  2566. else:
  2567. user = None
  2568. host = user_host
  2569. else:
  2570. raise ValueError("not a valid rsync-style URL")
  2571. return (user, host, path)
  2572. def get_transport_and_path(
  2573. location: str,
  2574. config: Optional[Config] = None,
  2575. operation: Optional[str] = None,
  2576. **kwargs,
  2577. ) -> tuple[GitClient, str]:
  2578. """Obtain a git client from a URL.
  2579. Args:
  2580. location: URL or path (a string)
  2581. config: Optional config object
  2582. operation: Kind of operation that'll be performed; "pull" or "push"
  2583. thin_packs: Whether or not thin packs should be retrieved
  2584. report_activity: Optional callback for reporting transport
  2585. activity.
  2586. Returns:
  2587. Tuple with client instance and relative path.
  2588. """
  2589. if config is not None:
  2590. location = apply_instead_of(config, location, push=(operation == "push"))
  2591. # First, try to parse it as a URL
  2592. try:
  2593. return _get_transport_and_path_from_url(
  2594. location, config=config, operation=operation, **kwargs
  2595. )
  2596. except ValueError:
  2597. pass
  2598. if sys.platform == "win32" and location[0].isalpha() and location[1:3] == ":\\":
  2599. # Windows local path
  2600. return default_local_git_client_cls(**kwargs), location
  2601. try:
  2602. (username, hostname, path) = parse_rsync_url(location)
  2603. except ValueError:
  2604. # Otherwise, assume it's a local path.
  2605. return default_local_git_client_cls(**kwargs), location
  2606. else:
  2607. return SSHGitClient(hostname, username=username, **kwargs), path
  2608. DEFAULT_GIT_CREDENTIALS_PATHS = [
  2609. os.path.expanduser("~/.git-credentials"),
  2610. get_xdg_config_home_path("git", "credentials"),
  2611. ]
  2612. def get_credentials_from_store(
  2613. scheme, hostname, username=None, fnames=DEFAULT_GIT_CREDENTIALS_PATHS
  2614. ):
  2615. for fname in fnames:
  2616. try:
  2617. with open(fname, "rb") as f:
  2618. for line in f:
  2619. parsed_line = urlparse(line.strip())
  2620. if (
  2621. parsed_line.scheme == scheme
  2622. and parsed_line.hostname == hostname
  2623. and (username is None or parsed_line.username == username)
  2624. ):
  2625. return parsed_line.username, parsed_line.password
  2626. except FileNotFoundError:
  2627. # If the file doesn't exist, try the next one.
  2628. continue