client.py 69 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194
  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 len(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. wants = determine_wants(refs)
  871. except BaseException:
  872. proto.write_pkt_line(None)
  873. raise
  874. if wants is not None:
  875. wants = [cid for cid in wants if cid != ZERO_SHA]
  876. if not wants:
  877. proto.write_pkt_line(None)
  878. return FetchPackResult(refs, symrefs, agent)
  879. (new_shallow, new_unshallow) = self._handle_upload_pack_head(
  880. proto,
  881. negotiated_capabilities,
  882. graph_walker,
  883. wants,
  884. can_read,
  885. depth=depth,
  886. )
  887. self._handle_upload_pack_tail(
  888. proto,
  889. negotiated_capabilities,
  890. graph_walker,
  891. pack_data,
  892. progress,
  893. )
  894. return FetchPackResult(refs, symrefs, agent, new_shallow, new_unshallow)
  895. def get_refs(self, path):
  896. """Retrieve the current refs from a git smart server."""
  897. # stock `git ls-remote` uses upload-pack
  898. proto, _, stderr = self._connect(b"upload-pack", path)
  899. with proto:
  900. try:
  901. refs, _ = read_pkt_refs(proto)
  902. except HangupException:
  903. raise _remote_error_from_stderr(stderr)
  904. proto.write_pkt_line(None)
  905. return refs
  906. def archive(
  907. self,
  908. path,
  909. committish,
  910. write_data,
  911. progress=None,
  912. write_error=None,
  913. format=None,
  914. subdirs=None,
  915. prefix=None,
  916. ):
  917. proto, can_read, stderr = self._connect(b"upload-archive", path)
  918. with proto:
  919. if format is not None:
  920. proto.write_pkt_line(b"argument --format=" + format)
  921. proto.write_pkt_line(b"argument " + committish)
  922. if subdirs is not None:
  923. for subdir in subdirs:
  924. proto.write_pkt_line(b"argument " + subdir)
  925. if prefix is not None:
  926. proto.write_pkt_line(b"argument --prefix=" + prefix)
  927. proto.write_pkt_line(None)
  928. try:
  929. pkt = proto.read_pkt_line()
  930. except HangupException:
  931. raise _remote_error_from_stderr(stderr)
  932. if pkt == b"NACK\n" or pkt == b"NACK":
  933. return
  934. elif pkt == b"ACK\n" or pkt == b"ACK":
  935. pass
  936. elif pkt.startswith(b"ERR "):
  937. raise GitProtocolError(pkt[4:].rstrip(b"\n").decode("utf-8", "replace"))
  938. else:
  939. raise AssertionError("invalid response %r" % pkt)
  940. ret = proto.read_pkt_line()
  941. if ret is not None:
  942. raise AssertionError("expected pkt tail")
  943. self._read_side_band64k_data(
  944. proto,
  945. {
  946. SIDE_BAND_CHANNEL_DATA: write_data,
  947. SIDE_BAND_CHANNEL_PROGRESS: progress,
  948. SIDE_BAND_CHANNEL_FATAL: write_error,
  949. },
  950. )
  951. class TCPGitClient(TraditionalGitClient):
  952. """A Git Client that works over TCP directly (i.e. git://)."""
  953. def __init__(self, host, port=None, **kwargs):
  954. if port is None:
  955. port = TCP_GIT_PORT
  956. self._host = host
  957. self._port = port
  958. super(TCPGitClient, self).__init__(**kwargs)
  959. @classmethod
  960. def from_parsedurl(cls, parsedurl, **kwargs):
  961. return cls(parsedurl.hostname, port=parsedurl.port, **kwargs)
  962. def get_url(self, path):
  963. netloc = self._host
  964. if self._port is not None and self._port != TCP_GIT_PORT:
  965. netloc += ":%d" % self._port
  966. return urlunsplit(("git", netloc, path, "", ""))
  967. def _connect(self, cmd, path):
  968. if not isinstance(cmd, bytes):
  969. raise TypeError(cmd)
  970. if not isinstance(path, bytes):
  971. path = path.encode(self._remote_path_encoding)
  972. sockaddrs = socket.getaddrinfo(
  973. self._host, self._port, socket.AF_UNSPEC, socket.SOCK_STREAM
  974. )
  975. s = None
  976. err = socket.error("no address found for %s" % self._host)
  977. for (family, socktype, proto, canonname, sockaddr) in sockaddrs:
  978. s = socket.socket(family, socktype, proto)
  979. s.setsockopt(socket.IPPROTO_TCP, socket.TCP_NODELAY, 1)
  980. try:
  981. s.connect(sockaddr)
  982. break
  983. except socket.error as e:
  984. err = e
  985. if s is not None:
  986. s.close()
  987. s = None
  988. if s is None:
  989. raise err
  990. # -1 means system default buffering
  991. rfile = s.makefile("rb", -1)
  992. # 0 means unbuffered
  993. wfile = s.makefile("wb", 0)
  994. def close():
  995. rfile.close()
  996. wfile.close()
  997. s.close()
  998. proto = Protocol(
  999. rfile.read,
  1000. wfile.write,
  1001. close,
  1002. report_activity=self._report_activity,
  1003. )
  1004. if path.startswith(b"/~"):
  1005. path = path[1:]
  1006. # TODO(jelmer): Alternative to ascii?
  1007. proto.send_cmd(b"git-" + cmd, path, b"host=" + self._host.encode("ascii"))
  1008. return proto, lambda: _fileno_can_read(s), None
  1009. class SubprocessWrapper(object):
  1010. """A socket-like object that talks to a subprocess via pipes."""
  1011. def __init__(self, proc):
  1012. self.proc = proc
  1013. self.read = BufferedReader(proc.stdout).read
  1014. self.write = proc.stdin.write
  1015. @property
  1016. def stderr(self):
  1017. return self.proc.stderr
  1018. def can_read(self):
  1019. if sys.platform == "win32":
  1020. from msvcrt import get_osfhandle
  1021. handle = get_osfhandle(self.proc.stdout.fileno())
  1022. return _win32_peek_avail(handle) != 0
  1023. else:
  1024. return _fileno_can_read(self.proc.stdout.fileno())
  1025. def close(self):
  1026. self.proc.stdin.close()
  1027. self.proc.stdout.close()
  1028. if self.proc.stderr:
  1029. self.proc.stderr.close()
  1030. self.proc.wait()
  1031. def find_git_command():
  1032. """Find command to run for system Git (usually C Git)."""
  1033. if sys.platform == "win32": # support .exe, .bat and .cmd
  1034. try: # to avoid overhead
  1035. import win32api
  1036. except ImportError: # run through cmd.exe with some overhead
  1037. return ["cmd", "/c", "git"]
  1038. else:
  1039. status, git = win32api.FindExecutable("git")
  1040. return [git]
  1041. else:
  1042. return ["git"]
  1043. class SubprocessGitClient(TraditionalGitClient):
  1044. """Git client that talks to a server using a subprocess."""
  1045. @classmethod
  1046. def from_parsedurl(cls, parsedurl, **kwargs):
  1047. return cls(**kwargs)
  1048. git_command = None
  1049. def _connect(self, service, path):
  1050. if not isinstance(service, bytes):
  1051. raise TypeError(service)
  1052. if isinstance(path, bytes):
  1053. path = path.decode(self._remote_path_encoding)
  1054. if self.git_command is None:
  1055. git_command = find_git_command()
  1056. argv = git_command + [service.decode("ascii"), path]
  1057. p = subprocess.Popen(
  1058. argv,
  1059. bufsize=0,
  1060. stdin=subprocess.PIPE,
  1061. stdout=subprocess.PIPE,
  1062. stderr=subprocess.PIPE,
  1063. )
  1064. pw = SubprocessWrapper(p)
  1065. return (
  1066. Protocol(
  1067. pw.read,
  1068. pw.write,
  1069. pw.close,
  1070. report_activity=self._report_activity,
  1071. ),
  1072. pw.can_read,
  1073. p.stderr,
  1074. )
  1075. class LocalGitClient(GitClient):
  1076. """Git Client that just uses a local Repo."""
  1077. def __init__(self, thin_packs=True, report_activity=None, config=None):
  1078. """Create a new LocalGitClient instance.
  1079. Args:
  1080. thin_packs: Whether or not thin packs should be retrieved
  1081. report_activity: Optional callback for reporting transport
  1082. activity.
  1083. """
  1084. self._report_activity = report_activity
  1085. # Ignore the thin_packs argument
  1086. def get_url(self, path):
  1087. return urlunsplit(("file", "", path, "", ""))
  1088. @classmethod
  1089. def from_parsedurl(cls, parsedurl, **kwargs):
  1090. return cls(**kwargs)
  1091. @classmethod
  1092. def _open_repo(cls, path):
  1093. from dulwich.repo import Repo
  1094. if not isinstance(path, str):
  1095. path = os.fsdecode(path)
  1096. return closing(Repo(path))
  1097. def send_pack(self, path, update_refs, generate_pack_data, progress=None):
  1098. """Upload a pack to a remote repository.
  1099. Args:
  1100. path: Repository path (as bytestring)
  1101. update_refs: Function to determine changes to remote refs.
  1102. Receive dict with existing remote refs, returns dict with
  1103. changed refs (name -> sha, where sha=ZERO_SHA for deletions)
  1104. with number of items and pack data to upload.
  1105. progress: Optional progress function
  1106. Returns:
  1107. SendPackResult
  1108. Raises:
  1109. SendPackError: if server rejects the pack data
  1110. """
  1111. if not progress:
  1112. def progress(x):
  1113. pass
  1114. with self._open_repo(path) as target:
  1115. old_refs = target.get_refs()
  1116. new_refs = update_refs(dict(old_refs))
  1117. have = [sha1 for sha1 in old_refs.values() if sha1 != ZERO_SHA]
  1118. want = []
  1119. for refname, new_sha1 in new_refs.items():
  1120. if (
  1121. new_sha1 not in have
  1122. and new_sha1 not in want
  1123. and new_sha1 != ZERO_SHA
  1124. ):
  1125. want.append(new_sha1)
  1126. if not want and set(new_refs.items()).issubset(set(old_refs.items())):
  1127. return SendPackResult(new_refs, ref_status={})
  1128. target.object_store.add_pack_data(
  1129. *generate_pack_data(have, want, ofs_delta=True)
  1130. )
  1131. ref_status = {}
  1132. for refname, new_sha1 in new_refs.items():
  1133. old_sha1 = old_refs.get(refname, ZERO_SHA)
  1134. if new_sha1 != ZERO_SHA:
  1135. if not target.refs.set_if_equals(refname, old_sha1, new_sha1):
  1136. msg = "unable to set %s to %s" % (refname, new_sha1)
  1137. progress(msg)
  1138. ref_status[refname] = msg
  1139. else:
  1140. if not target.refs.remove_if_equals(refname, old_sha1):
  1141. progress("unable to remove %s" % refname)
  1142. ref_status[refname] = "unable to remove"
  1143. return SendPackResult(new_refs, ref_status=ref_status)
  1144. def fetch(self, path, target, determine_wants=None, progress=None, depth=None):
  1145. """Fetch into a target repository.
  1146. Args:
  1147. path: Path to fetch from (as bytestring)
  1148. target: Target repository to fetch into
  1149. determine_wants: Optional function determine what refs
  1150. to fetch. Receives dictionary of name->sha, should return
  1151. list of shas to fetch. Defaults to all shas.
  1152. progress: Optional progress function
  1153. depth: Shallow fetch depth
  1154. Returns:
  1155. FetchPackResult object
  1156. """
  1157. with self._open_repo(path) as r:
  1158. refs = r.fetch(
  1159. target,
  1160. determine_wants=determine_wants,
  1161. progress=progress,
  1162. depth=depth,
  1163. )
  1164. return FetchPackResult(refs, r.refs.get_symrefs(), agent_string())
  1165. def fetch_pack(
  1166. self,
  1167. path,
  1168. determine_wants,
  1169. graph_walker,
  1170. pack_data,
  1171. progress=None,
  1172. depth=None,
  1173. ):
  1174. """Retrieve a pack from a git smart server.
  1175. Args:
  1176. path: Remote path to fetch from
  1177. determine_wants: Function determine what refs
  1178. to fetch. Receives dictionary of name->sha, should return
  1179. list of shas to fetch.
  1180. graph_walker: Object with next() and ack().
  1181. pack_data: Callback called for each bit of data in the pack
  1182. progress: Callback for progress reports (strings)
  1183. depth: Shallow fetch depth
  1184. Returns:
  1185. FetchPackResult object
  1186. """
  1187. with self._open_repo(path) as r:
  1188. objects_iter = r.fetch_objects(
  1189. determine_wants, graph_walker, progress=progress, depth=depth
  1190. )
  1191. symrefs = r.refs.get_symrefs()
  1192. agent = agent_string()
  1193. # Did the process short-circuit (e.g. in a stateless RPC call)?
  1194. # Note that the client still expects a 0-object pack in most cases.
  1195. if objects_iter is None:
  1196. return FetchPackResult(None, symrefs, agent)
  1197. protocol = ProtocolFile(None, pack_data)
  1198. write_pack_objects(protocol, objects_iter)
  1199. return FetchPackResult(r.get_refs(), symrefs, agent)
  1200. def get_refs(self, path):
  1201. """Retrieve the current refs from a git smart server."""
  1202. with self._open_repo(path) as target:
  1203. return target.get_refs()
  1204. # What Git client to use for local access
  1205. default_local_git_client_cls = LocalGitClient
  1206. class SSHVendor(object):
  1207. """A client side SSH implementation."""
  1208. def connect_ssh(
  1209. self,
  1210. host,
  1211. command,
  1212. username=None,
  1213. port=None,
  1214. password=None,
  1215. key_filename=None,
  1216. ):
  1217. # This function was deprecated in 0.9.1
  1218. import warnings
  1219. warnings.warn(
  1220. "SSHVendor.connect_ssh has been renamed to SSHVendor.run_command",
  1221. DeprecationWarning,
  1222. )
  1223. return self.run_command(
  1224. host,
  1225. command,
  1226. username=username,
  1227. port=port,
  1228. password=password,
  1229. key_filename=key_filename,
  1230. )
  1231. def run_command(
  1232. self,
  1233. host,
  1234. command,
  1235. username=None,
  1236. port=None,
  1237. password=None,
  1238. key_filename=None,
  1239. ):
  1240. """Connect to an SSH server.
  1241. Run a command remotely and return a file-like object for interaction
  1242. with the remote command.
  1243. Args:
  1244. host: Host name
  1245. command: Command to run (as argv array)
  1246. username: Optional ame of user to log in as
  1247. port: Optional SSH port to use
  1248. password: Optional ssh password for login or private key
  1249. key_filename: Optional path to private keyfile
  1250. Returns:
  1251. """
  1252. raise NotImplementedError(self.run_command)
  1253. class StrangeHostname(Exception):
  1254. """Refusing to connect to strange SSH hostname."""
  1255. def __init__(self, hostname):
  1256. super(StrangeHostname, self).__init__(hostname)
  1257. class SubprocessSSHVendor(SSHVendor):
  1258. """SSH vendor that shells out to the local 'ssh' command."""
  1259. def run_command(
  1260. self,
  1261. host,
  1262. command,
  1263. username=None,
  1264. port=None,
  1265. password=None,
  1266. key_filename=None,
  1267. ):
  1268. if password is not None:
  1269. raise NotImplementedError(
  1270. "Setting password not supported by SubprocessSSHVendor."
  1271. )
  1272. args = ["ssh", "-x"]
  1273. if port:
  1274. args.extend(["-p", str(port)])
  1275. if key_filename:
  1276. args.extend(["-i", str(key_filename)])
  1277. if username:
  1278. host = "%s@%s" % (username, host)
  1279. if host.startswith("-"):
  1280. raise StrangeHostname(hostname=host)
  1281. args.append(host)
  1282. proc = subprocess.Popen(
  1283. args + [command],
  1284. bufsize=0,
  1285. stdin=subprocess.PIPE,
  1286. stdout=subprocess.PIPE,
  1287. stderr=subprocess.PIPE,
  1288. )
  1289. return SubprocessWrapper(proc)
  1290. class PLinkSSHVendor(SSHVendor):
  1291. """SSH vendor that shells out to the local 'plink' command."""
  1292. def run_command(
  1293. self,
  1294. host,
  1295. command,
  1296. username=None,
  1297. port=None,
  1298. password=None,
  1299. key_filename=None,
  1300. ):
  1301. if sys.platform == "win32":
  1302. args = ["plink.exe", "-ssh"]
  1303. else:
  1304. args = ["plink", "-ssh"]
  1305. if password is not None:
  1306. import warnings
  1307. warnings.warn(
  1308. "Invoking PLink with a password exposes the password in the "
  1309. "process list."
  1310. )
  1311. args.extend(["-pw", str(password)])
  1312. if port:
  1313. args.extend(["-P", str(port)])
  1314. if key_filename:
  1315. args.extend(["-i", str(key_filename)])
  1316. if username:
  1317. host = "%s@%s" % (username, host)
  1318. if host.startswith("-"):
  1319. raise StrangeHostname(hostname=host)
  1320. args.append(host)
  1321. proc = subprocess.Popen(
  1322. args + [command],
  1323. bufsize=0,
  1324. stdin=subprocess.PIPE,
  1325. stdout=subprocess.PIPE,
  1326. stderr=subprocess.PIPE,
  1327. )
  1328. return SubprocessWrapper(proc)
  1329. def ParamikoSSHVendor(**kwargs):
  1330. import warnings
  1331. warnings.warn(
  1332. "ParamikoSSHVendor has been moved to dulwich.contrib.paramiko_vendor.",
  1333. DeprecationWarning,
  1334. )
  1335. from dulwich.contrib.paramiko_vendor import ParamikoSSHVendor
  1336. return ParamikoSSHVendor(**kwargs)
  1337. # Can be overridden by users
  1338. get_ssh_vendor = SubprocessSSHVendor
  1339. class SSHGitClient(TraditionalGitClient):
  1340. def __init__(
  1341. self,
  1342. host,
  1343. port=None,
  1344. username=None,
  1345. vendor=None,
  1346. config=None,
  1347. password=None,
  1348. key_filename=None,
  1349. **kwargs
  1350. ):
  1351. self.host = host
  1352. self.port = port
  1353. self.username = username
  1354. self.password = password
  1355. self.key_filename = key_filename
  1356. super(SSHGitClient, self).__init__(**kwargs)
  1357. self.alternative_paths = {}
  1358. if vendor is not None:
  1359. self.ssh_vendor = vendor
  1360. else:
  1361. self.ssh_vendor = get_ssh_vendor()
  1362. def get_url(self, path):
  1363. netloc = self.host
  1364. if self.port is not None:
  1365. netloc += ":%d" % self.port
  1366. if self.username is not None:
  1367. netloc = urlquote(self.username, "@/:") + "@" + netloc
  1368. return urlunsplit(("ssh", netloc, path, "", ""))
  1369. @classmethod
  1370. def from_parsedurl(cls, parsedurl, **kwargs):
  1371. return cls(
  1372. host=parsedurl.hostname,
  1373. port=parsedurl.port,
  1374. username=parsedurl.username,
  1375. **kwargs
  1376. )
  1377. def _get_cmd_path(self, cmd):
  1378. cmd = self.alternative_paths.get(cmd, b"git-" + cmd)
  1379. assert isinstance(cmd, bytes)
  1380. return cmd
  1381. def _connect(self, cmd, path):
  1382. if not isinstance(cmd, bytes):
  1383. raise TypeError(cmd)
  1384. if isinstance(path, bytes):
  1385. path = path.decode(self._remote_path_encoding)
  1386. if path.startswith("/~"):
  1387. path = path[1:]
  1388. argv = (
  1389. self._get_cmd_path(cmd).decode(self._remote_path_encoding)
  1390. + " '"
  1391. + path
  1392. + "'"
  1393. )
  1394. kwargs = {}
  1395. if self.password is not None:
  1396. kwargs["password"] = self.password
  1397. if self.key_filename is not None:
  1398. kwargs["key_filename"] = self.key_filename
  1399. con = self.ssh_vendor.run_command(
  1400. self.host, argv, port=self.port, username=self.username, **kwargs
  1401. )
  1402. return (
  1403. Protocol(
  1404. con.read,
  1405. con.write,
  1406. con.close,
  1407. report_activity=self._report_activity,
  1408. ),
  1409. con.can_read,
  1410. getattr(con, "stderr", None),
  1411. )
  1412. def default_user_agent_string():
  1413. # Start user agent with "git/", because GitHub requires this. :-( See
  1414. # https://github.com/jelmer/dulwich/issues/562 for details.
  1415. return "git/dulwich/%s" % ".".join([str(x) for x in dulwich.__version__])
  1416. def default_urllib3_manager( # noqa: C901
  1417. config, pool_manager_cls=None, proxy_manager_cls=None, **override_kwargs
  1418. ):
  1419. """Return `urllib3` connection pool manager.
  1420. Honour detected proxy configurations.
  1421. Args:
  1422. config: dulwich.config.ConfigDict` instance with Git configuration.
  1423. kwargs: Additional arguments for urllib3.ProxyManager
  1424. Returns:
  1425. `pool_manager_cls` (defaults to `urllib3.ProxyManager`) instance for
  1426. proxy configurations, `proxy_manager_cls` (defaults to
  1427. `urllib3.PoolManager`) instance otherwise.
  1428. """
  1429. proxy_server = user_agent = None
  1430. ca_certs = ssl_verify = None
  1431. if proxy_server is None:
  1432. for proxyname in ("https_proxy", "http_proxy", "all_proxy"):
  1433. proxy_server = os.environ.get(proxyname)
  1434. if proxy_server is not None:
  1435. break
  1436. if config is not None:
  1437. if proxy_server is None:
  1438. try:
  1439. proxy_server = config.get(b"http", b"proxy")
  1440. except KeyError:
  1441. pass
  1442. try:
  1443. user_agent = config.get(b"http", b"useragent")
  1444. except KeyError:
  1445. pass
  1446. # TODO(jelmer): Support per-host settings
  1447. try:
  1448. ssl_verify = config.get_boolean(b"http", b"sslVerify")
  1449. except KeyError:
  1450. ssl_verify = True
  1451. try:
  1452. ca_certs = config.get(b"http", b"sslCAInfo")
  1453. except KeyError:
  1454. ca_certs = None
  1455. if user_agent is None:
  1456. user_agent = default_user_agent_string()
  1457. headers = {"User-agent": user_agent}
  1458. kwargs = {}
  1459. if ssl_verify is True:
  1460. kwargs["cert_reqs"] = "CERT_REQUIRED"
  1461. elif ssl_verify is False:
  1462. kwargs["cert_reqs"] = "CERT_NONE"
  1463. else:
  1464. # Default to SSL verification
  1465. kwargs["cert_reqs"] = "CERT_REQUIRED"
  1466. if ca_certs is not None:
  1467. kwargs["ca_certs"] = ca_certs
  1468. kwargs.update(override_kwargs)
  1469. # Try really hard to find a SSL certificate path
  1470. if "ca_certs" not in kwargs and kwargs.get("cert_reqs") != "CERT_NONE":
  1471. try:
  1472. import certifi
  1473. except ImportError:
  1474. pass
  1475. else:
  1476. kwargs["ca_certs"] = certifi.where()
  1477. import urllib3
  1478. if proxy_server is not None:
  1479. if proxy_manager_cls is None:
  1480. proxy_manager_cls = urllib3.ProxyManager
  1481. # `urllib3` requires a `str` object in both Python 2 and 3, while
  1482. # `ConfigDict` coerces entries to `bytes` on Python 3. Compensate.
  1483. if not isinstance(proxy_server, str):
  1484. proxy_server = proxy_server.decode()
  1485. manager = proxy_manager_cls(proxy_server, headers=headers, **kwargs)
  1486. else:
  1487. if pool_manager_cls is None:
  1488. pool_manager_cls = urllib3.PoolManager
  1489. manager = pool_manager_cls(headers=headers, **kwargs)
  1490. return manager
  1491. class HttpGitClient(GitClient):
  1492. def __init__(
  1493. self,
  1494. base_url,
  1495. dumb=None,
  1496. pool_manager=None,
  1497. config=None,
  1498. username=None,
  1499. password=None,
  1500. **kwargs
  1501. ):
  1502. self._base_url = base_url.rstrip("/") + "/"
  1503. self._username = username
  1504. self._password = password
  1505. self.dumb = dumb
  1506. if pool_manager is None:
  1507. self.pool_manager = default_urllib3_manager(config)
  1508. else:
  1509. self.pool_manager = pool_manager
  1510. if username is not None:
  1511. # No escaping needed: ":" is not allowed in username:
  1512. # https://tools.ietf.org/html/rfc2617#section-2
  1513. credentials = "%s:%s" % (username, password)
  1514. import urllib3.util
  1515. basic_auth = urllib3.util.make_headers(basic_auth=credentials)
  1516. self.pool_manager.headers.update(basic_auth)
  1517. GitClient.__init__(self, **kwargs)
  1518. def get_url(self, path):
  1519. return self._get_url(path).rstrip("/")
  1520. @classmethod
  1521. def from_parsedurl(cls, parsedurl, **kwargs):
  1522. password = parsedurl.password
  1523. if password is not None:
  1524. kwargs["password"] = urlunquote(password)
  1525. username = parsedurl.username
  1526. if username is not None:
  1527. kwargs["username"] = urlunquote(username)
  1528. netloc = parsedurl.hostname
  1529. if parsedurl.port:
  1530. netloc = "%s:%s" % (netloc, parsedurl.port)
  1531. if parsedurl.username:
  1532. netloc = "%s@%s" % (parsedurl.username, netloc)
  1533. parsedurl = parsedurl._replace(netloc=netloc)
  1534. return cls(urlunparse(parsedurl), **kwargs)
  1535. def __repr__(self):
  1536. return "%s(%r, dumb=%r)" % (
  1537. type(self).__name__,
  1538. self._base_url,
  1539. self.dumb,
  1540. )
  1541. def _get_url(self, path):
  1542. if not isinstance(path, str):
  1543. # urllib3.util.url._encode_invalid_chars() converts the path back
  1544. # to bytes using the utf-8 codec.
  1545. path = path.decode("utf-8")
  1546. return urljoin(self._base_url, path).rstrip("/") + "/"
  1547. def _http_request(self, url, headers=None, data=None, allow_compression=False):
  1548. """Perform HTTP request.
  1549. Args:
  1550. url: Request URL.
  1551. headers: Optional custom headers to override defaults.
  1552. data: Request data.
  1553. allow_compression: Allow GZipped communication.
  1554. Returns:
  1555. Tuple (`response`, `read`), where response is an `urllib3`
  1556. response object with additional `content_type` and
  1557. `redirect_location` properties, and `read` is a consumable read
  1558. method for the response data.
  1559. """
  1560. req_headers = self.pool_manager.headers.copy()
  1561. if headers is not None:
  1562. req_headers.update(headers)
  1563. req_headers["Pragma"] = "no-cache"
  1564. if allow_compression:
  1565. req_headers["Accept-Encoding"] = "gzip"
  1566. else:
  1567. req_headers["Accept-Encoding"] = "identity"
  1568. if data is None:
  1569. resp = self.pool_manager.request("GET", url, headers=req_headers)
  1570. else:
  1571. resp = self.pool_manager.request(
  1572. "POST", url, headers=req_headers, body=data
  1573. )
  1574. if resp.status == 404:
  1575. raise NotGitRepository()
  1576. if resp.status == 401:
  1577. raise HTTPUnauthorized(resp.getheader("WWW-Authenticate"), url)
  1578. if resp.status != 200:
  1579. raise GitProtocolError(
  1580. "unexpected http resp %d for %s" % (resp.status, url)
  1581. )
  1582. # TODO: Optimization available by adding `preload_content=False` to the
  1583. # request and just passing the `read` method on instead of going via
  1584. # `BytesIO`, if we can guarantee that the entire response is consumed
  1585. # before issuing the next to still allow for connection reuse from the
  1586. # pool.
  1587. read = BytesIO(resp.data).read
  1588. resp.content_type = resp.getheader("Content-Type")
  1589. # Check if geturl() is available (urllib3 version >= 1.23)
  1590. try:
  1591. resp_url = resp.geturl()
  1592. except AttributeError:
  1593. # get_redirect_location() is available for urllib3 >= 1.1
  1594. resp.redirect_location = resp.get_redirect_location()
  1595. else:
  1596. resp.redirect_location = resp_url if resp_url != url else ""
  1597. return resp, read
  1598. def _discover_references(self, service, base_url):
  1599. assert base_url[-1] == "/"
  1600. tail = "info/refs"
  1601. headers = {"Accept": "*/*"}
  1602. if self.dumb is not True:
  1603. tail += "?service=%s" % service.decode("ascii")
  1604. url = urljoin(base_url, tail)
  1605. resp, read = self._http_request(url, headers, allow_compression=True)
  1606. if resp.redirect_location:
  1607. # Something changed (redirect!), so let's update the base URL
  1608. if not resp.redirect_location.endswith(tail):
  1609. raise GitProtocolError(
  1610. "Redirected from URL %s to URL %s without %s"
  1611. % (url, resp.redirect_location, tail)
  1612. )
  1613. base_url = resp.redirect_location[: -len(tail)]
  1614. try:
  1615. self.dumb = not resp.content_type.startswith("application/x-git-")
  1616. if not self.dumb:
  1617. proto = Protocol(read, None)
  1618. # The first line should mention the service
  1619. try:
  1620. [pkt] = list(proto.read_pkt_seq())
  1621. except ValueError:
  1622. raise GitProtocolError("unexpected number of packets received")
  1623. if pkt.rstrip(b"\n") != (b"# service=" + service):
  1624. raise GitProtocolError(
  1625. "unexpected first line %r from smart server" % pkt
  1626. )
  1627. return read_pkt_refs(proto) + (base_url,)
  1628. else:
  1629. return read_info_refs(resp), set(), base_url
  1630. finally:
  1631. resp.close()
  1632. def _smart_request(self, service, url, data):
  1633. assert url[-1] == "/"
  1634. url = urljoin(url, service)
  1635. result_content_type = "application/x-%s-result" % service
  1636. headers = {
  1637. "Content-Type": "application/x-%s-request" % service,
  1638. "Accept": result_content_type,
  1639. "Content-Length": str(len(data)),
  1640. }
  1641. resp, read = self._http_request(url, headers, data)
  1642. if resp.content_type != result_content_type:
  1643. raise GitProtocolError(
  1644. "Invalid content-type from server: %s" % resp.content_type
  1645. )
  1646. return resp, read
  1647. def send_pack(self, path, update_refs, generate_pack_data, progress=None):
  1648. """Upload a pack to a remote repository.
  1649. Args:
  1650. path: Repository path (as bytestring)
  1651. update_refs: Function to determine changes to remote refs.
  1652. Receives dict with existing remote refs, returns dict with
  1653. changed refs (name -> sha, where sha=ZERO_SHA for deletions)
  1654. generate_pack_data: Function that can return a tuple
  1655. with number of elements and pack data to upload.
  1656. progress: Optional progress function
  1657. Returns:
  1658. SendPackResult
  1659. Raises:
  1660. SendPackError: if server rejects the pack data
  1661. """
  1662. url = self._get_url(path)
  1663. old_refs, server_capabilities, url = self._discover_references(
  1664. b"git-receive-pack", url
  1665. )
  1666. (
  1667. negotiated_capabilities,
  1668. agent,
  1669. ) = self._negotiate_receive_pack_capabilities(server_capabilities)
  1670. negotiated_capabilities.add(capability_agent())
  1671. if CAPABILITY_REPORT_STATUS in negotiated_capabilities:
  1672. self._report_status_parser = ReportStatusParser()
  1673. new_refs = update_refs(dict(old_refs))
  1674. if new_refs is None:
  1675. # Determine wants function is aborting the push.
  1676. return SendPackResult(old_refs, agent=agent, ref_status={})
  1677. if set(new_refs.items()).issubset(set(old_refs.items())):
  1678. return SendPackResult(new_refs, agent=agent, ref_status={})
  1679. if self.dumb:
  1680. raise NotImplementedError(self.fetch_pack)
  1681. req_data = BytesIO()
  1682. req_proto = Protocol(None, req_data.write)
  1683. (have, want) = self._handle_receive_pack_head(
  1684. req_proto, negotiated_capabilities, old_refs, new_refs
  1685. )
  1686. pack_data_count, pack_data = generate_pack_data(
  1687. have,
  1688. want,
  1689. ofs_delta=(CAPABILITY_OFS_DELTA in negotiated_capabilities),
  1690. )
  1691. if self._should_send_pack(new_refs):
  1692. write_pack_data(req_proto.write_file(), pack_data_count, pack_data)
  1693. resp, read = self._smart_request(
  1694. "git-receive-pack", url, data=req_data.getvalue()
  1695. )
  1696. try:
  1697. resp_proto = Protocol(read, None)
  1698. ref_status = self._handle_receive_pack_tail(
  1699. resp_proto, negotiated_capabilities, progress
  1700. )
  1701. return SendPackResult(new_refs, agent=agent, ref_status=ref_status)
  1702. finally:
  1703. resp.close()
  1704. def fetch_pack(
  1705. self,
  1706. path,
  1707. determine_wants,
  1708. graph_walker,
  1709. pack_data,
  1710. progress=None,
  1711. depth=None,
  1712. ):
  1713. """Retrieve a pack from a git smart server.
  1714. Args:
  1715. path: Path to fetch from
  1716. determine_wants: Callback that returns list of commits to fetch
  1717. graph_walker: Object with next() and ack().
  1718. pack_data: Callback called for each bit of data in the pack
  1719. progress: Callback for progress reports (strings)
  1720. depth: Depth for request
  1721. Returns:
  1722. FetchPackResult object
  1723. """
  1724. url = self._get_url(path)
  1725. refs, server_capabilities, url = self._discover_references(
  1726. b"git-upload-pack", url
  1727. )
  1728. (
  1729. negotiated_capabilities,
  1730. symrefs,
  1731. agent,
  1732. ) = self._negotiate_upload_pack_capabilities(server_capabilities)
  1733. wants = determine_wants(refs)
  1734. if wants is not None:
  1735. wants = [cid for cid in wants if cid != ZERO_SHA]
  1736. if not wants:
  1737. return FetchPackResult(refs, symrefs, agent)
  1738. if self.dumb:
  1739. raise NotImplementedError(self.fetch_pack)
  1740. req_data = BytesIO()
  1741. req_proto = Protocol(None, req_data.write)
  1742. (new_shallow, new_unshallow) = self._handle_upload_pack_head(
  1743. req_proto,
  1744. negotiated_capabilities,
  1745. graph_walker,
  1746. wants,
  1747. can_read=None,
  1748. depth=depth,
  1749. )
  1750. resp, read = self._smart_request(
  1751. "git-upload-pack", url, data=req_data.getvalue()
  1752. )
  1753. try:
  1754. resp_proto = Protocol(read, None)
  1755. if new_shallow is None and new_unshallow is None:
  1756. (new_shallow, new_unshallow) = _read_shallow_updates(resp_proto)
  1757. self._handle_upload_pack_tail(
  1758. resp_proto,
  1759. negotiated_capabilities,
  1760. graph_walker,
  1761. pack_data,
  1762. progress,
  1763. )
  1764. return FetchPackResult(refs, symrefs, agent, new_shallow, new_unshallow)
  1765. finally:
  1766. resp.close()
  1767. def get_refs(self, path):
  1768. """Retrieve the current refs from a git smart server."""
  1769. url = self._get_url(path)
  1770. refs, _, _ = self._discover_references(b"git-upload-pack", url)
  1771. return refs
  1772. def get_transport_and_path_from_url(url, config=None, **kwargs):
  1773. """Obtain a git client from a URL.
  1774. Args:
  1775. url: URL to open (a unicode string)
  1776. config: Optional config object
  1777. thin_packs: Whether or not thin packs should be retrieved
  1778. report_activity: Optional callback for reporting transport
  1779. activity.
  1780. Returns:
  1781. Tuple with client instance and relative path.
  1782. """
  1783. parsed = urlparse(url)
  1784. if parsed.scheme == "git":
  1785. return (TCPGitClient.from_parsedurl(parsed, **kwargs), parsed.path)
  1786. elif parsed.scheme in ("git+ssh", "ssh"):
  1787. return SSHGitClient.from_parsedurl(parsed, **kwargs), parsed.path
  1788. elif parsed.scheme in ("http", "https"):
  1789. return (
  1790. HttpGitClient.from_parsedurl(parsed, config=config, **kwargs),
  1791. parsed.path,
  1792. )
  1793. elif parsed.scheme == "file":
  1794. return (
  1795. default_local_git_client_cls.from_parsedurl(parsed, **kwargs),
  1796. parsed.path,
  1797. )
  1798. raise ValueError("unknown scheme '%s'" % parsed.scheme)
  1799. def parse_rsync_url(location):
  1800. """Parse a rsync-style URL."""
  1801. if ":" in location and "@" not in location:
  1802. # SSH with no user@, zero or one leading slash.
  1803. (host, path) = location.split(":", 1)
  1804. user = None
  1805. elif ":" in location:
  1806. # SSH with user@host:foo.
  1807. user_host, path = location.split(":", 1)
  1808. if "@" in user_host:
  1809. user, host = user_host.rsplit("@", 1)
  1810. else:
  1811. user = None
  1812. host = user_host
  1813. else:
  1814. raise ValueError("not a valid rsync-style URL")
  1815. return (user, host, path)
  1816. def get_transport_and_path(location, **kwargs):
  1817. """Obtain a git client from a URL.
  1818. Args:
  1819. location: URL or path (a string)
  1820. config: Optional config object
  1821. thin_packs: Whether or not thin packs should be retrieved
  1822. report_activity: Optional callback for reporting transport
  1823. activity.
  1824. Returns:
  1825. Tuple with client instance and relative path.
  1826. """
  1827. # First, try to parse it as a URL
  1828. try:
  1829. return get_transport_and_path_from_url(location, **kwargs)
  1830. except ValueError:
  1831. pass
  1832. if sys.platform == "win32" and location[0].isalpha() and location[1:3] == ":\\":
  1833. # Windows local path
  1834. return default_local_git_client_cls(**kwargs), location
  1835. try:
  1836. (username, hostname, path) = parse_rsync_url(location)
  1837. except ValueError:
  1838. # Otherwise, assume it's a local path.
  1839. return default_local_git_client_cls(**kwargs), location
  1840. else:
  1841. return SSHGitClient(hostname, username=username, **kwargs), path
  1842. DEFAULT_GIT_CREDENTIALS_PATHS = [
  1843. os.path.expanduser("~/.git-credentials"),
  1844. get_xdg_config_home_path("git", "credentials"),
  1845. ]
  1846. def get_credentials_from_store(
  1847. scheme, hostname, username=None, fnames=DEFAULT_GIT_CREDENTIALS_PATHS
  1848. ):
  1849. for fname in fnames:
  1850. try:
  1851. with open(fname, "rb") as f:
  1852. for line in f:
  1853. parsed_line = urlparse(line.strip())
  1854. if (
  1855. parsed_line.scheme == scheme
  1856. and parsed_line.hostname == hostname
  1857. and (username is None or parsed_line.username == username)
  1858. ):
  1859. return parsed_line.username, parsed_line.password
  1860. except FileNotFoundError:
  1861. # If the file doesn't exist, try the next one.
  1862. continue