client.py 74 KB

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