client.py 69 KB

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