client.py 74 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365
  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. from contextlib import closing
  36. from io import BytesIO, BufferedReader
  37. import logging
  38. import os
  39. import select
  40. import socket
  41. import subprocess
  42. import sys
  43. from typing import Any, Callable, Dict, List, Optional, Set, Tuple, IO
  44. from urllib.parse import (
  45. quote as urlquote,
  46. unquote as urlunquote,
  47. urlparse,
  48. urljoin,
  49. urlunsplit,
  50. urlunparse,
  51. )
  52. import dulwich
  53. from dulwich.config import get_xdg_config_home_path, Config, apply_instead_of
  54. from dulwich.errors import (
  55. GitProtocolError,
  56. NotGitRepository,
  57. SendPackError,
  58. )
  59. from dulwich.protocol import (
  60. HangupException,
  61. _RBUFSIZE,
  62. agent_string,
  63. capability_agent,
  64. extract_capability_names,
  65. CAPABILITY_AGENT,
  66. CAPABILITY_DELETE_REFS,
  67. CAPABILITY_INCLUDE_TAG,
  68. CAPABILITY_MULTI_ACK,
  69. CAPABILITY_MULTI_ACK_DETAILED,
  70. CAPABILITY_OFS_DELTA,
  71. CAPABILITY_QUIET,
  72. CAPABILITY_REPORT_STATUS,
  73. CAPABILITY_SHALLOW,
  74. CAPABILITY_SYMREF,
  75. CAPABILITY_SIDE_BAND_64K,
  76. CAPABILITY_THIN_PACK,
  77. CAPABILITIES_REF,
  78. KNOWN_RECEIVE_CAPABILITIES,
  79. KNOWN_UPLOAD_CAPABILITIES,
  80. COMMAND_DEEPEN,
  81. COMMAND_SHALLOW,
  82. COMMAND_UNSHALLOW,
  83. COMMAND_DONE,
  84. COMMAND_HAVE,
  85. COMMAND_WANT,
  86. SIDE_BAND_CHANNEL_DATA,
  87. SIDE_BAND_CHANNEL_PROGRESS,
  88. SIDE_BAND_CHANNEL_FATAL,
  89. PktLineParser,
  90. Protocol,
  91. ProtocolFile,
  92. TCP_GIT_PORT,
  93. ZERO_SHA,
  94. extract_capabilities,
  95. parse_capability,
  96. pkt_line,
  97. )
  98. from dulwich.pack import (
  99. write_pack_objects,
  100. PackChunkGenerator,
  101. )
  102. from dulwich.refs import (
  103. read_info_refs,
  104. ANNOTATED_TAG_SUFFIX,
  105. _import_remote_refs,
  106. )
  107. from dulwich.repo import Repo
  108. # url2pathname is lazily imported
  109. url2pathname = None
  110. logger = logging.getLogger(__name__)
  111. class InvalidWants(Exception):
  112. """Invalid wants."""
  113. def __init__(self, wants):
  114. Exception.__init__(
  115. self, "requested wants not in server provided refs: %r" % wants
  116. )
  117. class HTTPUnauthorized(Exception):
  118. """Raised when authentication fails."""
  119. def __init__(self, www_authenticate, url):
  120. Exception.__init__(self, "No valid credentials provided")
  121. self.www_authenticate = www_authenticate
  122. self.url = url
  123. class HTTPProxyUnauthorized(Exception):
  124. """Raised when proxy authentication fails."""
  125. def __init__(self, proxy_authenticate, url):
  126. Exception.__init__(self, "No valid proxy credentials provided")
  127. self.proxy_authenticate = proxy_authenticate
  128. self.url = url
  129. def _fileno_can_read(fileno):
  130. """Check if a file descriptor is readable."""
  131. return len(select.select([fileno], [], [], 0)[0]) > 0
  132. def _win32_peek_avail(handle):
  133. """Wrapper around PeekNamedPipe to check how many bytes are available."""
  134. from ctypes import byref, wintypes, windll
  135. c_avail = wintypes.DWORD()
  136. c_message = wintypes.DWORD()
  137. success = windll.kernel32.PeekNamedPipe(
  138. handle, None, 0, None, byref(c_avail), byref(c_message)
  139. )
  140. if not success:
  141. raise OSError(wintypes.GetLastError())
  142. return c_avail.value
  143. COMMON_CAPABILITIES = [CAPABILITY_OFS_DELTA, CAPABILITY_SIDE_BAND_64K]
  144. UPLOAD_CAPABILITIES = [
  145. CAPABILITY_THIN_PACK,
  146. CAPABILITY_MULTI_ACK,
  147. CAPABILITY_MULTI_ACK_DETAILED,
  148. CAPABILITY_SHALLOW,
  149. ] + COMMON_CAPABILITIES
  150. RECEIVE_CAPABILITIES = [
  151. CAPABILITY_REPORT_STATUS,
  152. CAPABILITY_DELETE_REFS,
  153. ] + COMMON_CAPABILITIES
  154. class ReportStatusParser(object):
  155. """Handle status as reported by servers with 'report-status' capability."""
  156. def __init__(self):
  157. self._done = False
  158. self._pack_status = None
  159. self._ref_statuses = []
  160. def check(self):
  161. """Check if there were any errors and, if so, raise exceptions.
  162. Raises:
  163. SendPackError: Raised when the server could not unpack
  164. Returns:
  165. iterator over refs
  166. """
  167. if self._pack_status not in (b"unpack ok", None):
  168. raise SendPackError(self._pack_status)
  169. for status in self._ref_statuses:
  170. try:
  171. status, rest = status.split(b" ", 1)
  172. except ValueError:
  173. # malformed response, move on to the next one
  174. continue
  175. if status == b"ng":
  176. ref, error = rest.split(b" ", 1)
  177. yield ref, error.decode("utf-8")
  178. elif status == b"ok":
  179. yield rest, None
  180. else:
  181. raise GitProtocolError("invalid ref status %r" % status)
  182. def handle_packet(self, pkt):
  183. """Handle a packet.
  184. Raises:
  185. GitProtocolError: Raised when packets are received after a flush
  186. packet.
  187. """
  188. if self._done:
  189. raise GitProtocolError("received more data after status report")
  190. if pkt is None:
  191. self._done = True
  192. return
  193. if self._pack_status is None:
  194. self._pack_status = pkt.strip()
  195. else:
  196. ref_status = pkt.strip()
  197. self._ref_statuses.append(ref_status)
  198. def read_pkt_refs(pkt_seq):
  199. server_capabilities = None
  200. refs = {}
  201. # Receive refs from server
  202. for pkt in pkt_seq:
  203. (sha, ref) = pkt.rstrip(b"\n").split(None, 1)
  204. if sha == b"ERR":
  205. raise GitProtocolError(ref.decode("utf-8", "replace"))
  206. if server_capabilities is None:
  207. (ref, server_capabilities) = extract_capabilities(ref)
  208. refs[ref] = sha
  209. if len(refs) == 0:
  210. return {}, set([])
  211. if refs == {CAPABILITIES_REF: ZERO_SHA}:
  212. refs = {}
  213. return refs, set(server_capabilities)
  214. class FetchPackResult(object):
  215. """Result of a fetch-pack operation.
  216. Attributes:
  217. refs: Dictionary with all remote refs
  218. symrefs: Dictionary with remote symrefs
  219. agent: User agent string
  220. """
  221. _FORWARDED_ATTRS = [
  222. "clear",
  223. "copy",
  224. "fromkeys",
  225. "get",
  226. "items",
  227. "keys",
  228. "pop",
  229. "popitem",
  230. "setdefault",
  231. "update",
  232. "values",
  233. "viewitems",
  234. "viewkeys",
  235. "viewvalues",
  236. ]
  237. def __init__(self, refs, symrefs, agent, new_shallow=None, new_unshallow=None):
  238. self.refs = refs
  239. self.symrefs = symrefs
  240. self.agent = agent
  241. self.new_shallow = new_shallow
  242. self.new_unshallow = new_unshallow
  243. def _warn_deprecated(self):
  244. import warnings
  245. warnings.warn(
  246. "Use FetchPackResult.refs instead.",
  247. DeprecationWarning,
  248. stacklevel=3,
  249. )
  250. def __eq__(self, other):
  251. if isinstance(other, dict):
  252. self._warn_deprecated()
  253. return self.refs == other
  254. return (
  255. self.refs == other.refs
  256. and self.symrefs == other.symrefs
  257. and self.agent == other.agent
  258. )
  259. def __contains__(self, name):
  260. self._warn_deprecated()
  261. return name in self.refs
  262. def __getitem__(self, name):
  263. self._warn_deprecated()
  264. return self.refs[name]
  265. def __len__(self):
  266. self._warn_deprecated()
  267. return len(self.refs)
  268. def __iter__(self):
  269. self._warn_deprecated()
  270. return iter(self.refs)
  271. def __getattribute__(self, name):
  272. if name in type(self)._FORWARDED_ATTRS:
  273. self._warn_deprecated()
  274. return getattr(self.refs, name)
  275. return super(FetchPackResult, self).__getattribute__(name)
  276. def __repr__(self):
  277. return "%s(%r, %r, %r)" % (
  278. self.__class__.__name__,
  279. self.refs,
  280. self.symrefs,
  281. self.agent,
  282. )
  283. class SendPackResult(object):
  284. """Result of a upload-pack operation.
  285. Attributes:
  286. refs: Dictionary with all remote refs
  287. agent: User agent string
  288. ref_status: Optional dictionary mapping ref name to error message (if it
  289. failed to update), or None if it was updated successfully
  290. """
  291. _FORWARDED_ATTRS = [
  292. "clear",
  293. "copy",
  294. "fromkeys",
  295. "get",
  296. "items",
  297. "keys",
  298. "pop",
  299. "popitem",
  300. "setdefault",
  301. "update",
  302. "values",
  303. "viewitems",
  304. "viewkeys",
  305. "viewvalues",
  306. ]
  307. def __init__(self, refs, agent=None, ref_status=None):
  308. self.refs = refs
  309. self.agent = agent
  310. self.ref_status = ref_status
  311. def _warn_deprecated(self):
  312. import warnings
  313. warnings.warn(
  314. "Use SendPackResult.refs instead.",
  315. DeprecationWarning,
  316. stacklevel=3,
  317. )
  318. def __eq__(self, other):
  319. if isinstance(other, dict):
  320. self._warn_deprecated()
  321. return self.refs == other
  322. return self.refs == other.refs and self.agent == other.agent
  323. def __contains__(self, name):
  324. self._warn_deprecated()
  325. return name in self.refs
  326. def __getitem__(self, name):
  327. self._warn_deprecated()
  328. return self.refs[name]
  329. def __len__(self):
  330. self._warn_deprecated()
  331. return len(self.refs)
  332. def __iter__(self):
  333. self._warn_deprecated()
  334. return iter(self.refs)
  335. def __getattribute__(self, name):
  336. if name in type(self)._FORWARDED_ATTRS:
  337. self._warn_deprecated()
  338. return getattr(self.refs, name)
  339. return super(SendPackResult, self).__getattribute__(name)
  340. def __repr__(self):
  341. return "%s(%r, %r)" % (self.__class__.__name__, self.refs, self.agent)
  342. def _read_shallow_updates(pkt_seq):
  343. new_shallow = set()
  344. new_unshallow = set()
  345. for pkt in pkt_seq:
  346. cmd, sha = pkt.split(b" ", 1)
  347. if cmd == COMMAND_SHALLOW:
  348. new_shallow.add(sha.strip())
  349. elif cmd == COMMAND_UNSHALLOW:
  350. new_unshallow.add(sha.strip())
  351. else:
  352. raise GitProtocolError("unknown command %s" % pkt)
  353. return (new_shallow, new_unshallow)
  354. class _v1ReceivePackHeader(object):
  355. def __init__(self, capabilities, old_refs, new_refs):
  356. self.want = []
  357. self.have = []
  358. self._it = self._handle_receive_pack_head(capabilities, old_refs, new_refs)
  359. self.sent_capabilities = False
  360. def __iter__(self):
  361. return self._it
  362. def _handle_receive_pack_head(self, capabilities, old_refs, new_refs):
  363. """Handle the head of a 'git-receive-pack' request.
  364. Args:
  365. proto: Protocol object to read from
  366. capabilities: List of negotiated capabilities
  367. old_refs: Old refs, as received from the server
  368. new_refs: Refs to change
  369. Returns:
  370. (have, want) tuple
  371. """
  372. self.have = [x for x in old_refs.values() if not x == ZERO_SHA]
  373. for refname in new_refs:
  374. if not isinstance(refname, bytes):
  375. raise TypeError("refname is not a bytestring: %r" % refname)
  376. old_sha1 = old_refs.get(refname, ZERO_SHA)
  377. if not isinstance(old_sha1, bytes):
  378. raise TypeError(
  379. "old sha1 for %s is not a bytestring: %r" % (refname, old_sha1)
  380. )
  381. new_sha1 = new_refs.get(refname, ZERO_SHA)
  382. if not isinstance(new_sha1, bytes):
  383. raise TypeError(
  384. "old sha1 for %s is not a bytestring %r" % (refname, new_sha1)
  385. )
  386. if old_sha1 != new_sha1:
  387. logger.debug(
  388. 'Sending updated ref %r: %r -> %r',
  389. refname, old_sha1, new_sha1)
  390. if self.sent_capabilities:
  391. yield old_sha1 + b" " + new_sha1 + b" " + refname
  392. else:
  393. yield (
  394. old_sha1
  395. + b" "
  396. + new_sha1
  397. + b" "
  398. + refname
  399. + b"\0"
  400. + b" ".join(sorted(capabilities))
  401. )
  402. self.sent_capabilities = True
  403. if new_sha1 not in self.have and new_sha1 != ZERO_SHA:
  404. self.want.append(new_sha1)
  405. yield None
  406. def _read_side_band64k_data(pkt_seq, channel_callbacks):
  407. """Read per-channel data.
  408. This requires the side-band-64k capability.
  409. Args:
  410. pkt_seq: Sequence of packets to read
  411. channel_callbacks: Dictionary mapping channels to packet
  412. handlers to use. None for a callback discards channel data.
  413. """
  414. for pkt in pkt_seq:
  415. channel = ord(pkt[:1])
  416. pkt = pkt[1:]
  417. try:
  418. cb = channel_callbacks[channel]
  419. except KeyError:
  420. raise AssertionError("Invalid sideband channel %d" % channel)
  421. else:
  422. if cb is not None:
  423. cb(pkt)
  424. def _handle_upload_pack_head(
  425. proto, capabilities, graph_walker, wants, can_read, depth
  426. ):
  427. """Handle the head of a 'git-upload-pack' request.
  428. Args:
  429. proto: Protocol object to read from
  430. capabilities: List of negotiated capabilities
  431. graph_walker: GraphWalker instance to call .ack() on
  432. wants: List of commits to fetch
  433. can_read: function that returns a boolean that indicates
  434. whether there is extra graph data to read on proto
  435. depth: Depth for request
  436. Returns:
  437. """
  438. assert isinstance(wants, list) and isinstance(wants[0], bytes)
  439. proto.write_pkt_line(
  440. COMMAND_WANT
  441. + b" "
  442. + wants[0]
  443. + b" "
  444. + b" ".join(sorted(capabilities))
  445. + b"\n"
  446. )
  447. for want in wants[1:]:
  448. proto.write_pkt_line(COMMAND_WANT + b" " + want + b"\n")
  449. if depth not in (0, None) or getattr(graph_walker, "shallow", None):
  450. if CAPABILITY_SHALLOW not in capabilities:
  451. raise GitProtocolError(
  452. "server does not support shallow capability required for " "depth"
  453. )
  454. for sha in graph_walker.shallow:
  455. proto.write_pkt_line(COMMAND_SHALLOW + b" " + sha + b"\n")
  456. if depth is not None:
  457. proto.write_pkt_line(
  458. COMMAND_DEEPEN + b" " + str(depth).encode("ascii") + b"\n"
  459. )
  460. proto.write_pkt_line(None)
  461. if can_read is not None:
  462. (new_shallow, new_unshallow) = _read_shallow_updates(proto.read_pkt_seq())
  463. else:
  464. new_shallow = new_unshallow = None
  465. else:
  466. new_shallow = new_unshallow = set()
  467. proto.write_pkt_line(None)
  468. have = next(graph_walker)
  469. while have:
  470. proto.write_pkt_line(COMMAND_HAVE + b" " + have + b"\n")
  471. if can_read is not None and can_read():
  472. pkt = proto.read_pkt_line()
  473. parts = pkt.rstrip(b"\n").split(b" ")
  474. if parts[0] == b"ACK":
  475. graph_walker.ack(parts[1])
  476. if parts[2] in (b"continue", b"common"):
  477. pass
  478. elif parts[2] == b"ready":
  479. break
  480. else:
  481. raise AssertionError(
  482. "%s not in ('continue', 'ready', 'common)" % parts[2]
  483. )
  484. have = next(graph_walker)
  485. proto.write_pkt_line(COMMAND_DONE + b"\n")
  486. return (new_shallow, new_unshallow)
  487. def _handle_upload_pack_tail(
  488. proto,
  489. capabilities,
  490. graph_walker,
  491. pack_data,
  492. progress=None,
  493. rbufsize=_RBUFSIZE,
  494. ):
  495. """Handle the tail of a 'git-upload-pack' request.
  496. Args:
  497. proto: Protocol object to read from
  498. capabilities: List of negotiated capabilities
  499. graph_walker: GraphWalker instance to call .ack() on
  500. pack_data: Function to call with pack data
  501. progress: Optional progress reporting function
  502. rbufsize: Read buffer size
  503. Returns:
  504. """
  505. pkt = proto.read_pkt_line()
  506. while pkt:
  507. parts = pkt.rstrip(b"\n").split(b" ")
  508. if parts[0] == b"ACK":
  509. graph_walker.ack(parts[1])
  510. if len(parts) < 3 or parts[2] not in (
  511. b"ready",
  512. b"continue",
  513. b"common",
  514. ):
  515. break
  516. pkt = proto.read_pkt_line()
  517. if CAPABILITY_SIDE_BAND_64K in capabilities:
  518. if progress is None:
  519. # Just ignore progress data
  520. def progress(x):
  521. pass
  522. _read_side_band64k_data(
  523. proto.read_pkt_seq(),
  524. {
  525. SIDE_BAND_CHANNEL_DATA: pack_data,
  526. SIDE_BAND_CHANNEL_PROGRESS: progress,
  527. },
  528. )
  529. else:
  530. while True:
  531. data = proto.read(rbufsize)
  532. if data == b"":
  533. break
  534. pack_data(data)
  535. # TODO(durin42): this doesn't correctly degrade if the server doesn't
  536. # support some capabilities. This should work properly with servers
  537. # that don't support multi_ack.
  538. class GitClient(object):
  539. """Git smart server client."""
  540. def __init__(
  541. self,
  542. thin_packs=True,
  543. report_activity=None,
  544. quiet=False,
  545. include_tags=False,
  546. ):
  547. """Create a new GitClient instance.
  548. Args:
  549. thin_packs: Whether or not thin packs should be retrieved
  550. report_activity: Optional callback for reporting transport
  551. activity.
  552. include_tags: send annotated tags when sending the objects they point
  553. to
  554. """
  555. self._report_activity = report_activity
  556. self._report_status_parser = None
  557. self._fetch_capabilities = set(UPLOAD_CAPABILITIES)
  558. self._fetch_capabilities.add(capability_agent())
  559. self._send_capabilities = set(RECEIVE_CAPABILITIES)
  560. self._send_capabilities.add(capability_agent())
  561. if quiet:
  562. self._send_capabilities.add(CAPABILITY_QUIET)
  563. if not thin_packs:
  564. self._fetch_capabilities.remove(CAPABILITY_THIN_PACK)
  565. if include_tags:
  566. self._fetch_capabilities.add(CAPABILITY_INCLUDE_TAG)
  567. def get_url(self, path):
  568. """Retrieves full url to given path.
  569. Args:
  570. path: Repository path (as string)
  571. Returns:
  572. Url to path (as string)
  573. """
  574. raise NotImplementedError(self.get_url)
  575. @classmethod
  576. def from_parsedurl(cls, parsedurl, **kwargs):
  577. """Create an instance of this client from a urlparse.parsed object.
  578. Args:
  579. parsedurl: Result of urlparse()
  580. Returns:
  581. A `GitClient` object
  582. """
  583. raise NotImplementedError(cls.from_parsedurl)
  584. def send_pack(self, path, update_refs, generate_pack_data, progress=None):
  585. """Upload a pack to a remote repository.
  586. Args:
  587. path: Repository path (as bytestring)
  588. update_refs: Function to determine changes to remote refs. Receive
  589. dict with existing remote refs, returns dict with
  590. changed refs (name -> sha, where sha=ZERO_SHA for deletions)
  591. generate_pack_data: Function that can return a tuple
  592. with number of objects and list of pack data to include
  593. progress: Optional progress function
  594. Returns:
  595. SendPackResult object
  596. Raises:
  597. SendPackError: if server rejects the pack data
  598. """
  599. raise NotImplementedError(self.send_pack)
  600. def clone(self, path, target_path, mkdir: bool = True, bare=False, origin="origin",
  601. checkout=None, branch=None, progress=None, depth=None):
  602. """Clone a repository."""
  603. from .refs import _set_origin_head, _set_default_branch, _set_head
  604. if mkdir:
  605. os.mkdir(target_path)
  606. try:
  607. target = None
  608. if not bare:
  609. target = Repo.init(target_path)
  610. if checkout is None:
  611. checkout = True
  612. else:
  613. if checkout:
  614. raise ValueError("checkout and bare are incompatible")
  615. target = Repo.init_bare(target_path)
  616. # TODO(jelmer): abstract method for get_location?
  617. if isinstance(self, (LocalGitClient, SubprocessGitClient)):
  618. encoded_path = path.encode('utf-8')
  619. else:
  620. encoded_path = self.get_url(path).encode('utf-8')
  621. assert target is not None
  622. target_config = target.get_config()
  623. target_config.set((b"remote", origin.encode('utf-8')), b"url", encoded_path)
  624. target_config.set(
  625. (b"remote", origin.encode('utf-8')),
  626. b"fetch",
  627. b"+refs/heads/*:refs/remotes/" + origin.encode('utf-8') + b"/*",
  628. )
  629. target_config.write_to_path()
  630. ref_message = b"clone: from " + encoded_path
  631. result = self.fetch(path, target, progress=progress, depth=depth)
  632. _import_remote_refs(
  633. target.refs, origin, result.refs, message=ref_message)
  634. origin_head = result.symrefs.get(b"HEAD")
  635. origin_sha = result.refs.get(b'HEAD')
  636. if origin_sha and not origin_head:
  637. # set detached HEAD
  638. target.refs[b"HEAD"] = origin_sha
  639. _set_origin_head(target.refs, origin.encode('utf-8'), origin_head)
  640. head_ref = _set_default_branch(
  641. target.refs, origin.encode('utf-8'), origin_head, branch, ref_message
  642. )
  643. # Update target head
  644. if head_ref:
  645. head = _set_head(target.refs, head_ref, ref_message)
  646. else:
  647. head = None
  648. if checkout and head is not None:
  649. target.reset_index()
  650. except BaseException:
  651. if target is not None:
  652. target.close()
  653. if mkdir:
  654. import shutil
  655. shutil.rmtree(target_path)
  656. raise
  657. return target
  658. def fetch(
  659. self,
  660. path: str,
  661. target: Repo,
  662. determine_wants: Optional[
  663. Callable[[Dict[bytes, bytes], Optional[int]], List[bytes]]
  664. ] = None,
  665. progress: Optional[Callable[[bytes], None]] = None,
  666. depth: Optional[int] = None
  667. ) -> FetchPackResult:
  668. """Fetch into a target repository.
  669. Args:
  670. path: Path to fetch from (as bytestring)
  671. target: Target repository to fetch into
  672. determine_wants: Optional function to determine what refs to fetch.
  673. Receives dictionary of name->sha, should return
  674. list of shas to fetch. Defaults to all shas.
  675. progress: Optional progress function
  676. depth: Depth to fetch at
  677. Returns:
  678. Dictionary with all remote refs (not just those fetched)
  679. """
  680. if determine_wants is None:
  681. determine_wants = target.object_store.determine_wants_all
  682. if CAPABILITY_THIN_PACK in self._fetch_capabilities:
  683. # TODO(jelmer): Avoid reading entire file into memory and
  684. # only processing it after the whole file has been fetched.
  685. from tempfile import SpooledTemporaryFile
  686. f = SpooledTemporaryFile() # type: IO[bytes]
  687. def commit():
  688. if f.tell():
  689. f.seek(0)
  690. target.object_store.add_thin_pack(f.read, None)
  691. f.close()
  692. def abort():
  693. f.close()
  694. else:
  695. f, commit, abort = target.object_store.add_pack()
  696. try:
  697. result = self.fetch_pack(
  698. path,
  699. determine_wants,
  700. target.get_graph_walker(),
  701. f.write,
  702. progress=progress,
  703. depth=depth,
  704. )
  705. except BaseException:
  706. abort()
  707. raise
  708. else:
  709. commit()
  710. target.update_shallow(result.new_shallow, result.new_unshallow)
  711. return result
  712. def fetch_pack(
  713. self,
  714. path,
  715. determine_wants,
  716. graph_walker,
  717. pack_data,
  718. progress=None,
  719. depth=None,
  720. ):
  721. """Retrieve a pack from a git smart server.
  722. Args:
  723. path: Remote path to fetch from
  724. determine_wants: Function determine what refs
  725. to fetch. Receives dictionary of name->sha, should return
  726. list of shas to fetch.
  727. graph_walker: Object with next() and ack().
  728. pack_data: Callback called for each bit of data in the pack
  729. progress: Callback for progress reports (strings)
  730. depth: Shallow fetch depth
  731. Returns:
  732. FetchPackResult object
  733. """
  734. raise NotImplementedError(self.fetch_pack)
  735. def get_refs(self, path):
  736. """Retrieve the current refs from a git smart server.
  737. Args:
  738. path: Path to the repo to fetch from. (as bytestring)
  739. Returns:
  740. """
  741. raise NotImplementedError(self.get_refs)
  742. @staticmethod
  743. def _should_send_pack(new_refs):
  744. # The packfile MUST NOT be sent if the only command used is delete.
  745. return any(sha != ZERO_SHA for sha in new_refs.values())
  746. def _negotiate_receive_pack_capabilities(self, server_capabilities):
  747. negotiated_capabilities = self._send_capabilities & server_capabilities
  748. agent = None
  749. for capability in server_capabilities:
  750. k, v = parse_capability(capability)
  751. if k == CAPABILITY_AGENT:
  752. agent = v
  753. unknown_capabilities = ( # noqa: F841
  754. extract_capability_names(server_capabilities) - KNOWN_RECEIVE_CAPABILITIES
  755. )
  756. # TODO(jelmer): warn about unknown capabilities
  757. return negotiated_capabilities, agent
  758. def _handle_receive_pack_tail(
  759. self,
  760. proto: Protocol,
  761. capabilities: Set[bytes],
  762. progress: Callable[[bytes], None] = None,
  763. ) -> Optional[Dict[bytes, Optional[str]]]:
  764. """Handle the tail of a 'git-receive-pack' request.
  765. Args:
  766. proto: Protocol object to read from
  767. capabilities: List of negotiated capabilities
  768. progress: Optional progress reporting function
  769. Returns:
  770. dict mapping ref name to:
  771. error message if the ref failed to update
  772. None if it was updated successfully
  773. """
  774. if CAPABILITY_SIDE_BAND_64K in capabilities:
  775. if progress is None:
  776. def progress(x):
  777. pass
  778. channel_callbacks = {2: progress}
  779. if CAPABILITY_REPORT_STATUS in capabilities:
  780. channel_callbacks[1] = PktLineParser(
  781. self._report_status_parser.handle_packet
  782. ).parse
  783. _read_side_band64k_data(proto.read_pkt_seq(), channel_callbacks)
  784. else:
  785. if CAPABILITY_REPORT_STATUS in capabilities:
  786. for pkt in proto.read_pkt_seq():
  787. self._report_status_parser.handle_packet(pkt)
  788. if self._report_status_parser is not None:
  789. return dict(self._report_status_parser.check())
  790. return None
  791. def _negotiate_upload_pack_capabilities(self, server_capabilities):
  792. unknown_capabilities = ( # noqa: F841
  793. extract_capability_names(server_capabilities) - KNOWN_UPLOAD_CAPABILITIES
  794. )
  795. # TODO(jelmer): warn about unknown capabilities
  796. symrefs = {}
  797. agent = None
  798. for capability in server_capabilities:
  799. k, v = parse_capability(capability)
  800. if k == CAPABILITY_SYMREF:
  801. (src, dst) = v.split(b":", 1)
  802. symrefs[src] = dst
  803. if k == CAPABILITY_AGENT:
  804. agent = v
  805. negotiated_capabilities = self._fetch_capabilities & server_capabilities
  806. return (negotiated_capabilities, symrefs, agent)
  807. def check_wants(wants, refs):
  808. """Check that a set of wants is valid.
  809. Args:
  810. wants: Set of object SHAs to fetch
  811. refs: Refs dictionary to check against
  812. Returns:
  813. """
  814. missing = set(wants) - {
  815. v for (k, v) in refs.items() if not k.endswith(ANNOTATED_TAG_SUFFIX)
  816. }
  817. if missing:
  818. raise InvalidWants(missing)
  819. def _remote_error_from_stderr(stderr):
  820. if stderr is None:
  821. return HangupException()
  822. lines = [line.rstrip(b"\n") for line in stderr.readlines()]
  823. for line in lines:
  824. if line.startswith(b"ERROR: "):
  825. return GitProtocolError(line[len(b"ERROR: ") :].decode("utf-8", "replace"))
  826. return HangupException(lines)
  827. class TraditionalGitClient(GitClient):
  828. """Traditional Git client."""
  829. DEFAULT_ENCODING = "utf-8"
  830. def __init__(self, path_encoding=DEFAULT_ENCODING, **kwargs):
  831. self._remote_path_encoding = path_encoding
  832. super(TraditionalGitClient, self).__init__(**kwargs)
  833. async def _connect(self, cmd, path):
  834. """Create a connection to the server.
  835. This method is abstract - concrete implementations should
  836. implement their own variant which connects to the server and
  837. returns an initialized Protocol object with the service ready
  838. for use and a can_read function which may be used to see if
  839. reads would block.
  840. Args:
  841. cmd: The git service name to which we should connect.
  842. path: The path we should pass to the service. (as bytestirng)
  843. """
  844. raise NotImplementedError()
  845. def send_pack(self, path, update_refs, generate_pack_data, progress=None):
  846. """Upload a pack to a remote repository.
  847. Args:
  848. path: Repository path (as bytestring)
  849. update_refs: Function to determine changes to remote refs.
  850. Receive dict with existing remote refs, returns dict with
  851. changed refs (name -> sha, where sha=ZERO_SHA for deletions)
  852. generate_pack_data: Function that can return a tuple with
  853. number of objects and pack data to upload.
  854. progress: Optional callback called with progress updates
  855. Returns:
  856. SendPackResult
  857. Raises:
  858. SendPackError: if server rejects the pack data
  859. """
  860. proto, unused_can_read, stderr = self._connect(b"receive-pack", path)
  861. with proto:
  862. try:
  863. old_refs, server_capabilities = read_pkt_refs(proto.read_pkt_seq())
  864. except HangupException:
  865. raise _remote_error_from_stderr(stderr)
  866. (
  867. negotiated_capabilities,
  868. agent,
  869. ) = self._negotiate_receive_pack_capabilities(server_capabilities)
  870. if CAPABILITY_REPORT_STATUS in negotiated_capabilities:
  871. self._report_status_parser = ReportStatusParser()
  872. report_status_parser = self._report_status_parser
  873. try:
  874. new_refs = orig_new_refs = update_refs(dict(old_refs))
  875. except BaseException:
  876. proto.write_pkt_line(None)
  877. raise
  878. if set(new_refs.items()).issubset(set(old_refs.items())):
  879. proto.write_pkt_line(None)
  880. return SendPackResult(new_refs, agent=agent, ref_status={})
  881. if CAPABILITY_DELETE_REFS not in server_capabilities:
  882. # Server does not support deletions. Fail later.
  883. new_refs = dict(orig_new_refs)
  884. for ref, sha in orig_new_refs.items():
  885. if sha == ZERO_SHA:
  886. if CAPABILITY_REPORT_STATUS in negotiated_capabilities:
  887. report_status_parser._ref_statuses.append(
  888. b"ng " + ref + b" remote does not support deleting refs"
  889. )
  890. report_status_parser._ref_status_ok = False
  891. del new_refs[ref]
  892. if new_refs is None:
  893. proto.write_pkt_line(None)
  894. return SendPackResult(old_refs, agent=agent, ref_status={})
  895. if len(new_refs) == 0 and orig_new_refs:
  896. # NOOP - Original new refs filtered out by policy
  897. proto.write_pkt_line(None)
  898. if report_status_parser is not None:
  899. ref_status = dict(report_status_parser.check())
  900. else:
  901. ref_status = None
  902. return SendPackResult(old_refs, agent=agent, ref_status=ref_status)
  903. header_handler = _v1ReceivePackHeader(negotiated_capabilities, old_refs, new_refs)
  904. for pkt in header_handler:
  905. proto.write_pkt_line(pkt)
  906. pack_data_count, pack_data = generate_pack_data(
  907. header_handler.have,
  908. header_handler.want,
  909. ofs_delta=(CAPABILITY_OFS_DELTA in negotiated_capabilities),
  910. )
  911. if self._should_send_pack(new_refs):
  912. for chunk in PackChunkGenerator(pack_data_count, pack_data):
  913. proto.write(chunk)
  914. ref_status = self._handle_receive_pack_tail(
  915. proto, negotiated_capabilities, progress
  916. )
  917. return SendPackResult(new_refs, agent=agent, ref_status=ref_status)
  918. def fetch_pack(
  919. self,
  920. path,
  921. determine_wants,
  922. graph_walker,
  923. pack_data,
  924. progress=None,
  925. depth=None,
  926. ):
  927. """Retrieve a pack from a git smart server.
  928. Args:
  929. path: Remote path to fetch from
  930. determine_wants: Function determine what refs
  931. to fetch. Receives dictionary of name->sha, should return
  932. list of shas to fetch.
  933. graph_walker: Object with next() and ack().
  934. pack_data: Callback called for each bit of data in the pack
  935. progress: Callback for progress reports (strings)
  936. depth: Shallow fetch depth
  937. Returns:
  938. FetchPackResult object
  939. """
  940. proto, can_read, stderr = self._connect(b"upload-pack", path)
  941. with proto:
  942. try:
  943. refs, server_capabilities = read_pkt_refs(proto.read_pkt_seq())
  944. except HangupException:
  945. raise _remote_error_from_stderr(stderr)
  946. (
  947. negotiated_capabilities,
  948. symrefs,
  949. agent,
  950. ) = self._negotiate_upload_pack_capabilities(server_capabilities)
  951. if refs is None:
  952. proto.write_pkt_line(None)
  953. return FetchPackResult(refs, symrefs, agent)
  954. try:
  955. if depth is not None:
  956. wants = determine_wants(refs, depth=depth)
  957. else:
  958. wants = determine_wants(refs)
  959. except BaseException:
  960. proto.write_pkt_line(None)
  961. raise
  962. if wants is not None:
  963. wants = [cid for cid in wants if cid != ZERO_SHA]
  964. if not wants:
  965. proto.write_pkt_line(None)
  966. return FetchPackResult(refs, symrefs, agent)
  967. (new_shallow, new_unshallow) = _handle_upload_pack_head(
  968. proto,
  969. negotiated_capabilities,
  970. graph_walker,
  971. wants,
  972. can_read,
  973. depth=depth,
  974. )
  975. _handle_upload_pack_tail(
  976. proto,
  977. negotiated_capabilities,
  978. graph_walker,
  979. pack_data,
  980. progress,
  981. )
  982. return FetchPackResult(refs, symrefs, agent, new_shallow, new_unshallow)
  983. def get_refs(self, path):
  984. """Retrieve the current refs from a git smart server."""
  985. # stock `git ls-remote` uses upload-pack
  986. proto, _, stderr = self._connect(b"upload-pack", path)
  987. with proto:
  988. try:
  989. refs, _ = read_pkt_refs(proto.read_pkt_seq())
  990. except HangupException:
  991. raise _remote_error_from_stderr(stderr)
  992. proto.write_pkt_line(None)
  993. return refs
  994. def archive(
  995. self,
  996. path,
  997. committish,
  998. write_data,
  999. progress=None,
  1000. write_error=None,
  1001. format=None,
  1002. subdirs=None,
  1003. prefix=None,
  1004. ):
  1005. proto, can_read, stderr = self._connect(b"upload-archive", path)
  1006. with proto:
  1007. if format is not None:
  1008. proto.write_pkt_line(b"argument --format=" + format)
  1009. proto.write_pkt_line(b"argument " + committish)
  1010. if subdirs is not None:
  1011. for subdir in subdirs:
  1012. proto.write_pkt_line(b"argument " + subdir)
  1013. if prefix is not None:
  1014. proto.write_pkt_line(b"argument --prefix=" + prefix)
  1015. proto.write_pkt_line(None)
  1016. try:
  1017. pkt = proto.read_pkt_line()
  1018. except HangupException:
  1019. raise _remote_error_from_stderr(stderr)
  1020. if pkt == b"NACK\n" or pkt == b"NACK":
  1021. return
  1022. elif pkt == b"ACK\n" or pkt == b"ACK":
  1023. pass
  1024. elif pkt.startswith(b"ERR "):
  1025. raise GitProtocolError(pkt[4:].rstrip(b"\n").decode("utf-8", "replace"))
  1026. else:
  1027. raise AssertionError("invalid response %r" % pkt)
  1028. ret = proto.read_pkt_line()
  1029. if ret is not None:
  1030. raise AssertionError("expected pkt tail")
  1031. _read_side_band64k_data(
  1032. proto.read_pkt_seq(),
  1033. {
  1034. SIDE_BAND_CHANNEL_DATA: write_data,
  1035. SIDE_BAND_CHANNEL_PROGRESS: progress,
  1036. SIDE_BAND_CHANNEL_FATAL: write_error,
  1037. },
  1038. )
  1039. class TCPGitClient(TraditionalGitClient):
  1040. """A Git Client that works over TCP directly (i.e. git://)."""
  1041. def __init__(self, host, port=None, **kwargs):
  1042. if port is None:
  1043. port = TCP_GIT_PORT
  1044. self._host = host
  1045. self._port = port
  1046. super(TCPGitClient, self).__init__(**kwargs)
  1047. @classmethod
  1048. def from_parsedurl(cls, parsedurl, **kwargs):
  1049. return cls(parsedurl.hostname, port=parsedurl.port, **kwargs)
  1050. def get_url(self, path):
  1051. netloc = self._host
  1052. if self._port is not None and self._port != TCP_GIT_PORT:
  1053. netloc += ":%d" % self._port
  1054. return urlunsplit(("git", netloc, path, "", ""))
  1055. def _connect(self, cmd, path):
  1056. if not isinstance(cmd, bytes):
  1057. raise TypeError(cmd)
  1058. if not isinstance(path, bytes):
  1059. path = path.encode(self._remote_path_encoding)
  1060. sockaddrs = socket.getaddrinfo(
  1061. self._host, self._port, socket.AF_UNSPEC, socket.SOCK_STREAM
  1062. )
  1063. s = None
  1064. err = socket.error("no address found for %s" % self._host)
  1065. for (family, socktype, proto, canonname, sockaddr) in sockaddrs:
  1066. s = socket.socket(family, socktype, proto)
  1067. s.setsockopt(socket.IPPROTO_TCP, socket.TCP_NODELAY, 1)
  1068. try:
  1069. s.connect(sockaddr)
  1070. break
  1071. except socket.error as e:
  1072. err = e
  1073. if s is not None:
  1074. s.close()
  1075. s = None
  1076. if s is None:
  1077. raise err
  1078. # -1 means system default buffering
  1079. rfile = s.makefile("rb", -1)
  1080. # 0 means unbuffered
  1081. wfile = s.makefile("wb", 0)
  1082. def close():
  1083. rfile.close()
  1084. wfile.close()
  1085. s.close()
  1086. proto = Protocol(
  1087. rfile.read,
  1088. wfile.write,
  1089. close,
  1090. report_activity=self._report_activity,
  1091. )
  1092. if path.startswith(b"/~"):
  1093. path = path[1:]
  1094. # TODO(jelmer): Alternative to ascii?
  1095. proto.send_cmd(b"git-" + cmd, path, b"host=" + self._host.encode("ascii"))
  1096. return proto, lambda: _fileno_can_read(s), None
  1097. class SubprocessWrapper(object):
  1098. """A socket-like object that talks to a subprocess via pipes."""
  1099. def __init__(self, proc):
  1100. self.proc = proc
  1101. self.read = BufferedReader(proc.stdout).read
  1102. self.write = proc.stdin.write
  1103. @property
  1104. def stderr(self):
  1105. return self.proc.stderr
  1106. def can_read(self):
  1107. if sys.platform == "win32":
  1108. from msvcrt import get_osfhandle
  1109. handle = get_osfhandle(self.proc.stdout.fileno())
  1110. return _win32_peek_avail(handle) != 0
  1111. else:
  1112. return _fileno_can_read(self.proc.stdout.fileno())
  1113. def close(self):
  1114. self.proc.stdin.close()
  1115. self.proc.stdout.close()
  1116. if self.proc.stderr:
  1117. self.proc.stderr.close()
  1118. self.proc.wait()
  1119. def find_git_command() -> List[str]:
  1120. """Find command to run for system Git (usually C Git)."""
  1121. if sys.platform == "win32": # support .exe, .bat and .cmd
  1122. try: # to avoid overhead
  1123. import win32api
  1124. except ImportError: # run through cmd.exe with some overhead
  1125. return ["cmd", "/c", "git"]
  1126. else:
  1127. status, git = win32api.FindExecutable("git")
  1128. return [git]
  1129. else:
  1130. return ["git"]
  1131. class SubprocessGitClient(TraditionalGitClient):
  1132. """Git client that talks to a server using a subprocess."""
  1133. @classmethod
  1134. def from_parsedurl(cls, parsedurl, **kwargs):
  1135. return cls(**kwargs)
  1136. git_command = None
  1137. def _connect(self, service, path):
  1138. if not isinstance(service, bytes):
  1139. raise TypeError(service)
  1140. if isinstance(path, bytes):
  1141. path = path.decode(self._remote_path_encoding)
  1142. if self.git_command is None:
  1143. git_command = find_git_command()
  1144. argv = git_command + [service.decode("ascii"), path]
  1145. p = subprocess.Popen(
  1146. argv,
  1147. bufsize=0,
  1148. stdin=subprocess.PIPE,
  1149. stdout=subprocess.PIPE,
  1150. stderr=subprocess.PIPE,
  1151. )
  1152. pw = SubprocessWrapper(p)
  1153. return (
  1154. Protocol(
  1155. pw.read,
  1156. pw.write,
  1157. pw.close,
  1158. report_activity=self._report_activity,
  1159. ),
  1160. pw.can_read,
  1161. p.stderr,
  1162. )
  1163. class LocalGitClient(GitClient):
  1164. """Git Client that just uses a local Repo."""
  1165. def __init__(self, thin_packs=True, report_activity=None, config=None):
  1166. """Create a new LocalGitClient instance.
  1167. Args:
  1168. thin_packs: Whether or not thin packs should be retrieved
  1169. report_activity: Optional callback for reporting transport
  1170. activity.
  1171. """
  1172. self._report_activity = report_activity
  1173. # Ignore the thin_packs argument
  1174. def get_url(self, path):
  1175. return urlunsplit(("file", "", path, "", ""))
  1176. @classmethod
  1177. def from_parsedurl(cls, parsedurl, **kwargs):
  1178. return cls(**kwargs)
  1179. @classmethod
  1180. def _open_repo(cls, path):
  1181. if not isinstance(path, str):
  1182. path = os.fsdecode(path)
  1183. return closing(Repo(path))
  1184. def send_pack(self, path, update_refs, generate_pack_data, progress=None):
  1185. """Upload a pack to a remote repository.
  1186. Args:
  1187. path: Repository path (as bytestring)
  1188. update_refs: Function to determine changes to remote refs.
  1189. Receive dict with existing remote refs, returns dict with
  1190. changed refs (name -> sha, where sha=ZERO_SHA for deletions)
  1191. with number of items and pack data to upload.
  1192. progress: Optional progress function
  1193. Returns:
  1194. SendPackResult
  1195. Raises:
  1196. SendPackError: if server rejects the pack data
  1197. """
  1198. if not progress:
  1199. def progress(x):
  1200. pass
  1201. with self._open_repo(path) as target:
  1202. old_refs = target.get_refs()
  1203. new_refs = update_refs(dict(old_refs))
  1204. have = [sha1 for sha1 in old_refs.values() if sha1 != ZERO_SHA]
  1205. want = []
  1206. for refname, new_sha1 in new_refs.items():
  1207. if (
  1208. new_sha1 not in have
  1209. and new_sha1 not in want
  1210. and new_sha1 != ZERO_SHA
  1211. ):
  1212. want.append(new_sha1)
  1213. if not want and set(new_refs.items()).issubset(set(old_refs.items())):
  1214. return SendPackResult(new_refs, ref_status={})
  1215. target.object_store.add_pack_data(
  1216. *generate_pack_data(have, want, ofs_delta=True)
  1217. )
  1218. ref_status = {}
  1219. for refname, new_sha1 in new_refs.items():
  1220. old_sha1 = old_refs.get(refname, ZERO_SHA)
  1221. if new_sha1 != ZERO_SHA:
  1222. if not target.refs.set_if_equals(refname, old_sha1, new_sha1):
  1223. msg = "unable to set %s to %s" % (refname, new_sha1)
  1224. progress(msg)
  1225. ref_status[refname] = msg
  1226. else:
  1227. if not target.refs.remove_if_equals(refname, old_sha1):
  1228. progress("unable to remove %s" % refname)
  1229. ref_status[refname] = "unable to remove"
  1230. return SendPackResult(new_refs, ref_status=ref_status)
  1231. def fetch(self, path, target, determine_wants=None, progress=None, depth=None):
  1232. """Fetch into a target repository.
  1233. Args:
  1234. path: Path to fetch from (as bytestring)
  1235. target: Target repository to fetch into
  1236. determine_wants: Optional function determine what refs
  1237. to fetch. Receives dictionary of name->sha, should return
  1238. list of shas to fetch. Defaults to all shas.
  1239. progress: Optional progress function
  1240. depth: Shallow fetch depth
  1241. Returns:
  1242. FetchPackResult object
  1243. """
  1244. with self._open_repo(path) as r:
  1245. refs = r.fetch(
  1246. target,
  1247. determine_wants=determine_wants,
  1248. progress=progress,
  1249. depth=depth,
  1250. )
  1251. return FetchPackResult(refs, r.refs.get_symrefs(), agent_string())
  1252. def fetch_pack(
  1253. self,
  1254. path,
  1255. determine_wants,
  1256. graph_walker,
  1257. pack_data,
  1258. progress=None,
  1259. depth=None,
  1260. ):
  1261. """Retrieve a pack from a git smart server.
  1262. Args:
  1263. path: Remote path to fetch from
  1264. determine_wants: Function determine what refs
  1265. to fetch. Receives dictionary of name->sha, should return
  1266. list of shas to fetch.
  1267. graph_walker: Object with next() and ack().
  1268. pack_data: Callback called for each bit of data in the pack
  1269. progress: Callback for progress reports (strings)
  1270. depth: Shallow fetch depth
  1271. Returns:
  1272. FetchPackResult object
  1273. """
  1274. with self._open_repo(path) as r:
  1275. objects_iter = r.fetch_objects(
  1276. determine_wants, graph_walker, progress=progress, depth=depth
  1277. )
  1278. symrefs = r.refs.get_symrefs()
  1279. agent = agent_string()
  1280. # Did the process short-circuit (e.g. in a stateless RPC call)?
  1281. # Note that the client still expects a 0-object pack in most cases.
  1282. if objects_iter is None:
  1283. return FetchPackResult(None, symrefs, agent)
  1284. protocol = ProtocolFile(None, pack_data)
  1285. write_pack_objects(protocol, objects_iter)
  1286. return FetchPackResult(r.get_refs(), symrefs, agent)
  1287. def get_refs(self, path):
  1288. """Retrieve the current refs from a git smart server."""
  1289. with self._open_repo(path) as target:
  1290. return target.get_refs()
  1291. # What Git client to use for local access
  1292. default_local_git_client_cls = LocalGitClient
  1293. class SSHVendor(object):
  1294. """A client side SSH implementation."""
  1295. def run_command(
  1296. self,
  1297. host,
  1298. command,
  1299. username=None,
  1300. port=None,
  1301. password=None,
  1302. key_filename=None,
  1303. ssh_command=None,
  1304. ):
  1305. """Connect to an SSH server.
  1306. Run a command remotely and return a file-like object for interaction
  1307. with the remote command.
  1308. Args:
  1309. host: Host name
  1310. command: Command to run (as argv array)
  1311. username: Optional ame of user to log in as
  1312. port: Optional SSH port to use
  1313. password: Optional ssh password for login or private key
  1314. key_filename: Optional path to private keyfile
  1315. ssh_command: Optional SSH command
  1316. Returns:
  1317. """
  1318. raise NotImplementedError(self.run_command)
  1319. class StrangeHostname(Exception):
  1320. """Refusing to connect to strange SSH hostname."""
  1321. def __init__(self, hostname):
  1322. super(StrangeHostname, self).__init__(hostname)
  1323. class SubprocessSSHVendor(SSHVendor):
  1324. """SSH vendor that shells out to the local 'ssh' command."""
  1325. def run_command(
  1326. self,
  1327. host,
  1328. command,
  1329. username=None,
  1330. port=None,
  1331. password=None,
  1332. key_filename=None,
  1333. ssh_command=None,
  1334. ):
  1335. if password is not None:
  1336. raise NotImplementedError(
  1337. "Setting password not supported by SubprocessSSHVendor."
  1338. )
  1339. if ssh_command:
  1340. import shlex
  1341. args = shlex.split(ssh_command) + ["-x"]
  1342. else:
  1343. args = ["ssh", "-x"]
  1344. if port:
  1345. args.extend(["-p", str(port)])
  1346. if key_filename:
  1347. args.extend(["-i", str(key_filename)])
  1348. if username:
  1349. host = "%s@%s" % (username, host)
  1350. if host.startswith("-"):
  1351. raise StrangeHostname(hostname=host)
  1352. args.append(host)
  1353. proc = subprocess.Popen(
  1354. args + [command],
  1355. bufsize=0,
  1356. stdin=subprocess.PIPE,
  1357. stdout=subprocess.PIPE,
  1358. stderr=subprocess.PIPE,
  1359. )
  1360. return SubprocessWrapper(proc)
  1361. class PLinkSSHVendor(SSHVendor):
  1362. """SSH vendor that shells out to the local 'plink' command."""
  1363. def run_command(
  1364. self,
  1365. host,
  1366. command,
  1367. username=None,
  1368. port=None,
  1369. password=None,
  1370. key_filename=None,
  1371. ssh_command=None,
  1372. ):
  1373. if ssh_command:
  1374. import shlex
  1375. args = shlex.split(ssh_command) + ["-ssh"]
  1376. elif sys.platform == "win32":
  1377. args = ["plink.exe", "-ssh"]
  1378. else:
  1379. args = ["plink", "-ssh"]
  1380. if password is not None:
  1381. import warnings
  1382. warnings.warn(
  1383. "Invoking PLink with a password exposes the password in the "
  1384. "process list."
  1385. )
  1386. args.extend(["-pw", str(password)])
  1387. if port:
  1388. args.extend(["-P", str(port)])
  1389. if key_filename:
  1390. args.extend(["-i", str(key_filename)])
  1391. if username:
  1392. host = "%s@%s" % (username, host)
  1393. if host.startswith("-"):
  1394. raise StrangeHostname(hostname=host)
  1395. args.append(host)
  1396. proc = subprocess.Popen(
  1397. args + [command],
  1398. bufsize=0,
  1399. stdin=subprocess.PIPE,
  1400. stdout=subprocess.PIPE,
  1401. stderr=subprocess.PIPE,
  1402. )
  1403. return SubprocessWrapper(proc)
  1404. def ParamikoSSHVendor(**kwargs):
  1405. import warnings
  1406. warnings.warn(
  1407. "ParamikoSSHVendor has been moved to dulwich.contrib.paramiko_vendor.",
  1408. DeprecationWarning,
  1409. )
  1410. from dulwich.contrib.paramiko_vendor import ParamikoSSHVendor
  1411. return ParamikoSSHVendor(**kwargs)
  1412. # Can be overridden by users
  1413. get_ssh_vendor = SubprocessSSHVendor
  1414. class SSHGitClient(TraditionalGitClient):
  1415. def __init__(
  1416. self,
  1417. host,
  1418. port=None,
  1419. username=None,
  1420. vendor=None,
  1421. config=None,
  1422. password=None,
  1423. key_filename=None,
  1424. ssh_command=None,
  1425. **kwargs
  1426. ):
  1427. self.host = host
  1428. self.port = port
  1429. self.username = username
  1430. self.password = password
  1431. self.key_filename = key_filename
  1432. self.ssh_command = ssh_command or os.environ.get(
  1433. "GIT_SSH_COMMAND", os.environ.get("GIT_SSH")
  1434. )
  1435. super(SSHGitClient, self).__init__(**kwargs)
  1436. self.alternative_paths = {}
  1437. if vendor is not None:
  1438. self.ssh_vendor = vendor
  1439. else:
  1440. self.ssh_vendor = get_ssh_vendor()
  1441. def get_url(self, path):
  1442. netloc = self.host
  1443. if self.port is not None:
  1444. netloc += ":%d" % self.port
  1445. if self.username is not None:
  1446. netloc = urlquote(self.username, "@/:") + "@" + netloc
  1447. return urlunsplit(("ssh", netloc, path, "", ""))
  1448. @classmethod
  1449. def from_parsedurl(cls, parsedurl, **kwargs):
  1450. return cls(
  1451. host=parsedurl.hostname,
  1452. port=parsedurl.port,
  1453. username=parsedurl.username,
  1454. **kwargs
  1455. )
  1456. def _get_cmd_path(self, cmd):
  1457. cmd = self.alternative_paths.get(cmd, b"git-" + cmd)
  1458. assert isinstance(cmd, bytes)
  1459. return cmd
  1460. def _connect(self, cmd, path):
  1461. if not isinstance(cmd, bytes):
  1462. raise TypeError(cmd)
  1463. if isinstance(path, bytes):
  1464. path = path.decode(self._remote_path_encoding)
  1465. if path.startswith("/~"):
  1466. path = path[1:]
  1467. argv = (
  1468. self._get_cmd_path(cmd).decode(self._remote_path_encoding)
  1469. + " '"
  1470. + path
  1471. + "'"
  1472. )
  1473. kwargs = {}
  1474. if self.password is not None:
  1475. kwargs["password"] = self.password
  1476. if self.key_filename is not None:
  1477. kwargs["key_filename"] = self.key_filename
  1478. # GIT_SSH_COMMAND takes precendence over GIT_SSH
  1479. if self.ssh_command is not None:
  1480. kwargs["ssh_command"] = self.ssh_command
  1481. con = self.ssh_vendor.run_command(
  1482. self.host, argv, port=self.port, username=self.username, **kwargs
  1483. )
  1484. return (
  1485. Protocol(
  1486. con.read,
  1487. con.write,
  1488. con.close,
  1489. report_activity=self._report_activity,
  1490. ),
  1491. con.can_read,
  1492. getattr(con, "stderr", None),
  1493. )
  1494. def default_user_agent_string():
  1495. # Start user agent with "git/", because GitHub requires this. :-( See
  1496. # https://github.com/jelmer/dulwich/issues/562 for details.
  1497. return "git/dulwich/%s" % ".".join([str(x) for x in dulwich.__version__])
  1498. def default_urllib3_manager( # noqa: C901
  1499. config, pool_manager_cls=None, proxy_manager_cls=None, **override_kwargs
  1500. ):
  1501. """Return `urllib3` connection pool manager.
  1502. Honour detected proxy configurations.
  1503. Args:
  1504. config: `dulwich.config.ConfigDict` instance with Git configuration.
  1505. override_kwargs: Additional arguments for `urllib3.ProxyManager`
  1506. Returns:
  1507. `pool_manager_cls` (defaults to `urllib3.ProxyManager`) instance for
  1508. proxy configurations, `proxy_manager_cls` (defaults to
  1509. `urllib3.PoolManager`) instance otherwise.
  1510. """
  1511. proxy_server = user_agent = None
  1512. ca_certs = ssl_verify = None
  1513. if proxy_server is None:
  1514. for proxyname in ("https_proxy", "http_proxy", "all_proxy"):
  1515. proxy_server = os.environ.get(proxyname)
  1516. if proxy_server is not None:
  1517. break
  1518. if config is not None:
  1519. if proxy_server is None:
  1520. try:
  1521. proxy_server = config.get(b"http", b"proxy")
  1522. except KeyError:
  1523. pass
  1524. try:
  1525. user_agent = config.get(b"http", b"useragent")
  1526. except KeyError:
  1527. pass
  1528. # TODO(jelmer): Support per-host settings
  1529. try:
  1530. ssl_verify = config.get_boolean(b"http", b"sslVerify")
  1531. except KeyError:
  1532. ssl_verify = True
  1533. try:
  1534. ca_certs = config.get(b"http", b"sslCAInfo")
  1535. except KeyError:
  1536. ca_certs = None
  1537. if user_agent is None:
  1538. user_agent = default_user_agent_string()
  1539. headers = {"User-agent": user_agent}
  1540. kwargs = {}
  1541. if ssl_verify is True:
  1542. kwargs["cert_reqs"] = "CERT_REQUIRED"
  1543. elif ssl_verify is False:
  1544. kwargs["cert_reqs"] = "CERT_NONE"
  1545. else:
  1546. # Default to SSL verification
  1547. kwargs["cert_reqs"] = "CERT_REQUIRED"
  1548. if ca_certs is not None:
  1549. kwargs["ca_certs"] = ca_certs
  1550. kwargs.update(override_kwargs)
  1551. # Try really hard to find a SSL certificate path
  1552. if "ca_certs" not in kwargs and kwargs.get("cert_reqs") != "CERT_NONE":
  1553. try:
  1554. import certifi
  1555. except ImportError:
  1556. pass
  1557. else:
  1558. kwargs["ca_certs"] = certifi.where()
  1559. import urllib3
  1560. if proxy_server is not None:
  1561. if proxy_manager_cls is None:
  1562. proxy_manager_cls = urllib3.ProxyManager
  1563. if not isinstance(proxy_server, str):
  1564. proxy_server = proxy_server.decode()
  1565. manager = proxy_manager_cls(proxy_server, headers=headers, **kwargs)
  1566. else:
  1567. if pool_manager_cls is None:
  1568. pool_manager_cls = urllib3.PoolManager
  1569. manager = pool_manager_cls(headers=headers, **kwargs)
  1570. return manager
  1571. class AbstractHttpGitClient(GitClient):
  1572. """Abstract base class for HTTP Git Clients.
  1573. This is agonistic of the actual HTTP implementation.
  1574. Subclasses should provide an implementation of the
  1575. _http_request method.
  1576. """
  1577. def __init__(self, base_url, dumb=False, **kwargs):
  1578. self._base_url = base_url.rstrip("/") + "/"
  1579. self.dumb = dumb
  1580. GitClient.__init__(self, **kwargs)
  1581. def _http_request(self, url, headers=None, data=None):
  1582. """Perform HTTP request.
  1583. Args:
  1584. url: Request URL.
  1585. headers: Optional custom headers to override defaults.
  1586. data: Request data.
  1587. Returns:
  1588. Tuple (`response`, `read`), where response is an `urllib3`
  1589. response object with additional `content_type` and
  1590. `redirect_location` properties, and `read` is a consumable read
  1591. method for the response data.
  1592. """
  1593. raise NotImplementedError(self._http_request)
  1594. def _discover_references(self, service, base_url):
  1595. assert base_url[-1] == "/"
  1596. tail = "info/refs"
  1597. headers = {"Accept": "*/*"}
  1598. if self.dumb is not True:
  1599. tail += "?service=%s" % service.decode("ascii")
  1600. url = urljoin(base_url, tail)
  1601. resp, read = self._http_request(url, headers)
  1602. if resp.redirect_location:
  1603. # Something changed (redirect!), so let's update the base URL
  1604. if not resp.redirect_location.endswith(tail):
  1605. raise GitProtocolError(
  1606. "Redirected from URL %s to URL %s without %s"
  1607. % (url, resp.redirect_location, tail)
  1608. )
  1609. base_url = resp.redirect_location[: -len(tail)]
  1610. try:
  1611. self.dumb = not resp.content_type.startswith("application/x-git-")
  1612. if not self.dumb:
  1613. proto = Protocol(read, None)
  1614. # The first line should mention the service
  1615. try:
  1616. [pkt] = list(proto.read_pkt_seq())
  1617. except ValueError:
  1618. raise GitProtocolError("unexpected number of packets received")
  1619. if pkt.rstrip(b"\n") != (b"# service=" + service):
  1620. raise GitProtocolError(
  1621. "unexpected first line %r from smart server" % pkt
  1622. )
  1623. return read_pkt_refs(proto.read_pkt_seq()) + (base_url,)
  1624. else:
  1625. return read_info_refs(resp), set(), base_url
  1626. finally:
  1627. resp.close()
  1628. def _smart_request(self, service, url, data):
  1629. """Send a 'smart' HTTP request.
  1630. This is a simple wrapper around _http_request that sets
  1631. a couple of extra headers.
  1632. """
  1633. assert url[-1] == "/"
  1634. url = urljoin(url, service)
  1635. result_content_type = "application/x-%s-result" % service
  1636. headers = {
  1637. "Content-Type": "application/x-%s-request" % service,
  1638. "Accept": result_content_type,
  1639. }
  1640. if isinstance(data, bytes):
  1641. headers["Content-Length"] = str(len(data))
  1642. resp, read = self._http_request(url, headers, data)
  1643. if resp.content_type != result_content_type:
  1644. raise GitProtocolError(
  1645. "Invalid content-type from server: %s" % resp.content_type
  1646. )
  1647. return resp, read
  1648. def send_pack(self, path, update_refs, generate_pack_data, progress=None):
  1649. """Upload a pack to a remote repository.
  1650. Args:
  1651. path: Repository path (as bytestring)
  1652. update_refs: Function to determine changes to remote refs.
  1653. Receives dict with existing remote refs, returns dict with
  1654. changed refs (name -> sha, where sha=ZERO_SHA for deletions)
  1655. generate_pack_data: Function that can return a tuple
  1656. with number of elements and pack data to upload.
  1657. progress: Optional progress function
  1658. Returns:
  1659. SendPackResult
  1660. Raises:
  1661. SendPackError: if server rejects the pack data
  1662. """
  1663. url = self._get_url(path)
  1664. old_refs, server_capabilities, url = self._discover_references(
  1665. b"git-receive-pack", url
  1666. )
  1667. (
  1668. negotiated_capabilities,
  1669. agent,
  1670. ) = self._negotiate_receive_pack_capabilities(server_capabilities)
  1671. negotiated_capabilities.add(capability_agent())
  1672. if CAPABILITY_REPORT_STATUS in negotiated_capabilities:
  1673. self._report_status_parser = ReportStatusParser()
  1674. new_refs = update_refs(dict(old_refs))
  1675. if new_refs is None:
  1676. # Determine wants function is aborting the push.
  1677. return SendPackResult(old_refs, agent=agent, ref_status={})
  1678. if set(new_refs.items()).issubset(set(old_refs.items())):
  1679. return SendPackResult(new_refs, agent=agent, ref_status={})
  1680. if self.dumb:
  1681. raise NotImplementedError(self.fetch_pack)
  1682. def body_generator():
  1683. header_handler = _v1ReceivePackHeader(negotiated_capabilities, old_refs, new_refs)
  1684. for pkt in header_handler:
  1685. yield pkt_line(pkt)
  1686. pack_data_count, pack_data = generate_pack_data(
  1687. header_handler.have,
  1688. header_handler.want,
  1689. ofs_delta=(CAPABILITY_OFS_DELTA in negotiated_capabilities),
  1690. )
  1691. if self._should_send_pack(new_refs):
  1692. yield from PackChunkGenerator(pack_data_count, pack_data)
  1693. resp, read = self._smart_request(
  1694. "git-receive-pack", url, data=body_generator()
  1695. )
  1696. try:
  1697. resp_proto = Protocol(read, None)
  1698. ref_status = self._handle_receive_pack_tail(
  1699. resp_proto, negotiated_capabilities, progress
  1700. )
  1701. return SendPackResult(new_refs, agent=agent, ref_status=ref_status)
  1702. finally:
  1703. resp.close()
  1704. def fetch_pack(
  1705. self,
  1706. path,
  1707. determine_wants,
  1708. graph_walker,
  1709. pack_data,
  1710. progress=None,
  1711. depth=None,
  1712. ):
  1713. """Retrieve a pack from a git smart server.
  1714. Args:
  1715. path: Path to fetch from
  1716. determine_wants: Callback that returns list of commits to fetch
  1717. graph_walker: Object with next() and ack().
  1718. pack_data: Callback called for each bit of data in the pack
  1719. progress: Callback for progress reports (strings)
  1720. depth: Depth for request
  1721. Returns:
  1722. FetchPackResult object
  1723. """
  1724. url = self._get_url(path)
  1725. refs, server_capabilities, url = self._discover_references(
  1726. b"git-upload-pack", url
  1727. )
  1728. (
  1729. negotiated_capabilities,
  1730. symrefs,
  1731. agent,
  1732. ) = self._negotiate_upload_pack_capabilities(server_capabilities)
  1733. if depth is not None:
  1734. wants = determine_wants(refs, depth=depth)
  1735. else:
  1736. wants = determine_wants(refs)
  1737. if wants is not None:
  1738. wants = [cid for cid in wants if cid != ZERO_SHA]
  1739. if not wants:
  1740. return FetchPackResult(refs, symrefs, agent)
  1741. if self.dumb:
  1742. raise NotImplementedError(self.fetch_pack)
  1743. req_data = BytesIO()
  1744. req_proto = Protocol(None, req_data.write)
  1745. (new_shallow, new_unshallow) = _handle_upload_pack_head(
  1746. req_proto,
  1747. negotiated_capabilities,
  1748. graph_walker,
  1749. wants,
  1750. can_read=None,
  1751. depth=depth,
  1752. )
  1753. resp, read = self._smart_request(
  1754. "git-upload-pack", url, data=req_data.getvalue()
  1755. )
  1756. try:
  1757. resp_proto = Protocol(read, None)
  1758. if new_shallow is None and new_unshallow is None:
  1759. (new_shallow, new_unshallow) = _read_shallow_updates(
  1760. resp_proto.read_pkt_seq())
  1761. _handle_upload_pack_tail(
  1762. resp_proto,
  1763. negotiated_capabilities,
  1764. graph_walker,
  1765. pack_data,
  1766. progress,
  1767. )
  1768. return FetchPackResult(refs, symrefs, agent, new_shallow, new_unshallow)
  1769. finally:
  1770. resp.close()
  1771. def get_refs(self, path):
  1772. """Retrieve the current refs from a git smart server."""
  1773. url = self._get_url(path)
  1774. refs, _, _ = self._discover_references(b"git-upload-pack", url)
  1775. return refs
  1776. def get_url(self, path):
  1777. return self._get_url(path).rstrip("/")
  1778. def _get_url(self, path):
  1779. return urljoin(self._base_url, path).rstrip("/") + "/"
  1780. @classmethod
  1781. def from_parsedurl(cls, parsedurl, **kwargs):
  1782. password = parsedurl.password
  1783. if password is not None:
  1784. kwargs["password"] = urlunquote(password)
  1785. username = parsedurl.username
  1786. if username is not None:
  1787. kwargs["username"] = urlunquote(username)
  1788. netloc = parsedurl.hostname
  1789. if parsedurl.port:
  1790. netloc = "%s:%s" % (netloc, parsedurl.port)
  1791. if parsedurl.username:
  1792. netloc = "%s@%s" % (parsedurl.username, netloc)
  1793. parsedurl = parsedurl._replace(netloc=netloc)
  1794. return cls(urlunparse(parsedurl), **kwargs)
  1795. def __repr__(self):
  1796. return "%s(%r, dumb=%r)" % (
  1797. type(self).__name__,
  1798. self._base_url,
  1799. self.dumb,
  1800. )
  1801. class Urllib3HttpGitClient(AbstractHttpGitClient):
  1802. def __init__(
  1803. self,
  1804. base_url,
  1805. dumb=None,
  1806. pool_manager=None,
  1807. config=None,
  1808. username=None,
  1809. password=None,
  1810. **kwargs
  1811. ):
  1812. self._username = username
  1813. self._password = password
  1814. if pool_manager is None:
  1815. self.pool_manager = default_urllib3_manager(config)
  1816. else:
  1817. self.pool_manager = pool_manager
  1818. if username is not None:
  1819. # No escaping needed: ":" is not allowed in username:
  1820. # https://tools.ietf.org/html/rfc2617#section-2
  1821. credentials = f"{username}:{password or ''}"
  1822. import urllib3.util
  1823. basic_auth = urllib3.util.make_headers(basic_auth=credentials)
  1824. self.pool_manager.headers.update(basic_auth)
  1825. self.config = config
  1826. super(Urllib3HttpGitClient, self).__init__(
  1827. base_url=base_url, dumb=dumb, **kwargs)
  1828. def _get_url(self, path):
  1829. if not isinstance(path, str):
  1830. # urllib3.util.url._encode_invalid_chars() converts the path back
  1831. # to bytes using the utf-8 codec.
  1832. path = path.decode("utf-8")
  1833. return urljoin(self._base_url, path).rstrip("/") + "/"
  1834. def _http_request(self, url, headers=None, data=None):
  1835. req_headers = self.pool_manager.headers.copy()
  1836. if headers is not None:
  1837. req_headers.update(headers)
  1838. req_headers["Pragma"] = "no-cache"
  1839. if data is None:
  1840. resp = self.pool_manager.request(
  1841. "GET", url, headers=req_headers, preload_content=False)
  1842. else:
  1843. resp = self.pool_manager.request(
  1844. "POST", url, headers=req_headers, body=data, preload_content=False
  1845. )
  1846. if resp.status == 404:
  1847. raise NotGitRepository()
  1848. if resp.status == 401:
  1849. raise HTTPUnauthorized(resp.getheader("WWW-Authenticate"), url)
  1850. if resp.status == 407:
  1851. raise HTTPProxyUnauthorized(resp.getheader("Proxy-Authenticate"), url)
  1852. if resp.status != 200:
  1853. raise GitProtocolError(
  1854. "unexpected http resp %d for %s" % (resp.status, url)
  1855. )
  1856. resp.content_type = resp.getheader("Content-Type")
  1857. # Check if geturl() is available (urllib3 version >= 1.23)
  1858. try:
  1859. resp_url = resp.geturl()
  1860. except AttributeError:
  1861. # get_redirect_location() is available for urllib3 >= 1.1
  1862. resp.redirect_location = resp.get_redirect_location()
  1863. else:
  1864. resp.redirect_location = resp_url if resp_url != url else ""
  1865. return resp, resp.read
  1866. HttpGitClient = Urllib3HttpGitClient
  1867. def _win32_url_to_path(parsed) -> str:
  1868. """Convert a file: URL to a path.
  1869. https://datatracker.ietf.org/doc/html/rfc8089
  1870. """
  1871. assert sys.platform == "win32" or os.name == "nt"
  1872. assert parsed.scheme == "file"
  1873. _, netloc, path, _, _, _ = parsed
  1874. if netloc == "localhost" or not netloc:
  1875. netloc = ""
  1876. elif (
  1877. netloc
  1878. and len(netloc) >= 2
  1879. and netloc[0].isalpha()
  1880. and netloc[1:2] in (":", ":/")
  1881. ):
  1882. # file://C:/foo.bar/baz or file://C://foo.bar//baz
  1883. netloc = netloc[:2]
  1884. else:
  1885. raise NotImplementedError("Non-local file URLs are not supported")
  1886. global url2pathname
  1887. if url2pathname is None:
  1888. from urllib.request import url2pathname # type: ignore
  1889. return url2pathname(netloc + path) # type: ignore
  1890. def get_transport_and_path_from_url(
  1891. url: str, config: Optional[Config] = None,
  1892. operation: Optional[str] = None, **kwargs) -> Tuple[GitClient, str]:
  1893. """Obtain a git client from a URL.
  1894. Args:
  1895. url: URL to open (a unicode string)
  1896. config: Optional config object
  1897. operation: Kind of operation that'll be performed; "pull" or "push"
  1898. thin_packs: Whether or not thin packs should be retrieved
  1899. report_activity: Optional callback for reporting transport
  1900. activity.
  1901. Returns:
  1902. Tuple with client instance and relative path.
  1903. """
  1904. if config is not None:
  1905. url = apply_instead_of(config, url, push=(operation == "push"))
  1906. parsed = urlparse(url)
  1907. if parsed.scheme == "git":
  1908. return (TCPGitClient.from_parsedurl(parsed, **kwargs), parsed.path)
  1909. elif parsed.scheme in ("git+ssh", "ssh"):
  1910. return SSHGitClient.from_parsedurl(parsed, **kwargs), parsed.path
  1911. elif parsed.scheme in ("http", "https"):
  1912. return (
  1913. HttpGitClient.from_parsedurl(parsed, config=config, **kwargs),
  1914. parsed.path,
  1915. )
  1916. elif parsed.scheme == "file":
  1917. if sys.platform == "win32" or os.name == "nt":
  1918. return default_local_git_client_cls(**kwargs), _win32_url_to_path(parsed)
  1919. return (
  1920. default_local_git_client_cls.from_parsedurl(parsed, **kwargs),
  1921. parsed.path,
  1922. )
  1923. raise ValueError("unknown scheme '%s'" % parsed.scheme)
  1924. def parse_rsync_url(location: str) -> Tuple[Optional[str], str, str]:
  1925. """Parse a rsync-style URL."""
  1926. if ":" in location and "@" not in location:
  1927. # SSH with no user@, zero or one leading slash.
  1928. (host, path) = location.split(":", 1)
  1929. user = None
  1930. elif ":" in location:
  1931. # SSH with user@host:foo.
  1932. user_host, path = location.split(":", 1)
  1933. if "@" in user_host:
  1934. user, host = user_host.rsplit("@", 1)
  1935. else:
  1936. user = None
  1937. host = user_host
  1938. else:
  1939. raise ValueError("not a valid rsync-style URL")
  1940. return (user, host, path)
  1941. def get_transport_and_path(
  1942. location: str,
  1943. operation: Optional[str] = None,
  1944. **kwargs: Any
  1945. ) -> Tuple[GitClient, str]:
  1946. """Obtain a git client from a URL.
  1947. Args:
  1948. location: URL or path (a string)
  1949. config: Optional config object
  1950. operation: Kind of operation that'll be performed; "pull" or "push"
  1951. thin_packs: Whether or not thin packs should be retrieved
  1952. report_activity: Optional callback for reporting transport
  1953. activity.
  1954. Returns:
  1955. Tuple with client instance and relative path.
  1956. """
  1957. # First, try to parse it as a URL
  1958. try:
  1959. return get_transport_and_path_from_url(location, operation=operation, **kwargs)
  1960. except ValueError:
  1961. pass
  1962. if sys.platform == "win32" and location[0].isalpha() and location[1:3] == ":\\":
  1963. # Windows local path
  1964. return default_local_git_client_cls(**kwargs), location
  1965. try:
  1966. (username, hostname, path) = parse_rsync_url(location)
  1967. except ValueError:
  1968. # Otherwise, assume it's a local path.
  1969. return default_local_git_client_cls(**kwargs), location
  1970. else:
  1971. return SSHGitClient(hostname, username=username, **kwargs), path
  1972. DEFAULT_GIT_CREDENTIALS_PATHS = [
  1973. os.path.expanduser("~/.git-credentials"),
  1974. get_xdg_config_home_path("git", "credentials"),
  1975. ]
  1976. def get_credentials_from_store(
  1977. scheme, hostname, username=None, fnames=DEFAULT_GIT_CREDENTIALS_PATHS
  1978. ):
  1979. for fname in fnames:
  1980. try:
  1981. with open(fname, "rb") as f:
  1982. for line in f:
  1983. parsed_line = urlparse(line.strip())
  1984. if (
  1985. parsed_line.scheme == scheme
  1986. and parsed_line.hostname == hostname
  1987. and (username is None or parsed_line.username == username)
  1988. ):
  1989. return parsed_line.username, parsed_line.password
  1990. except FileNotFoundError:
  1991. # If the file doesn't exist, try the next one.
  1992. continue