versioncontrol.py 25 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811
  1. """Handles all VCS (version control) support"""
  2. from __future__ import absolute_import
  3. import errno
  4. import logging
  5. import os
  6. import shutil
  7. import subprocess
  8. import sys
  9. from pip._vendor import pkg_resources
  10. from pip._vendor.six.moves.urllib import parse as urllib_parse
  11. from pip._internal.exceptions import (
  12. BadCommand,
  13. InstallationError,
  14. SubProcessError,
  15. )
  16. from pip._internal.utils.compat import console_to_str, samefile
  17. from pip._internal.utils.logging import subprocess_logger
  18. from pip._internal.utils.misc import (
  19. ask_path_exists,
  20. backup_dir,
  21. display_path,
  22. hide_url,
  23. hide_value,
  24. rmtree,
  25. )
  26. from pip._internal.utils.subprocess import (
  27. format_command_args,
  28. make_command,
  29. make_subprocess_output_error,
  30. reveal_command_args,
  31. )
  32. from pip._internal.utils.typing import MYPY_CHECK_RUNNING
  33. from pip._internal.utils.urls import get_url_scheme
  34. if MYPY_CHECK_RUNNING:
  35. from typing import (
  36. Dict, Iterable, Iterator, List, Optional, Text, Tuple,
  37. Type, Union, Mapping, Any
  38. )
  39. from pip._internal.utils.misc import HiddenText
  40. from pip._internal.utils.subprocess import CommandArgs
  41. AuthInfo = Tuple[Optional[str], Optional[str]]
  42. __all__ = ['vcs']
  43. logger = logging.getLogger(__name__)
  44. def is_url(name):
  45. # type: (Union[str, Text]) -> bool
  46. """
  47. Return true if the name looks like a URL.
  48. """
  49. scheme = get_url_scheme(name)
  50. if scheme is None:
  51. return False
  52. return scheme in ['http', 'https', 'file', 'ftp'] + vcs.all_schemes
  53. def make_vcs_requirement_url(repo_url, rev, project_name, subdir=None):
  54. # type: (str, str, str, Optional[str]) -> str
  55. """
  56. Return the URL for a VCS requirement.
  57. Args:
  58. repo_url: the remote VCS url, with any needed VCS prefix (e.g. "git+").
  59. project_name: the (unescaped) project name.
  60. """
  61. egg_project_name = pkg_resources.to_filename(project_name)
  62. req = '{}@{}#egg={}'.format(repo_url, rev, egg_project_name)
  63. if subdir:
  64. req += '&subdirectory={}'.format(subdir)
  65. return req
  66. def call_subprocess(
  67. cmd, # type: Union[List[str], CommandArgs]
  68. cwd=None, # type: Optional[str]
  69. extra_environ=None, # type: Optional[Mapping[str, Any]]
  70. extra_ok_returncodes=None, # type: Optional[Iterable[int]]
  71. log_failed_cmd=True # type: Optional[bool]
  72. ):
  73. # type: (...) -> Text
  74. """
  75. Args:
  76. extra_ok_returncodes: an iterable of integer return codes that are
  77. acceptable, in addition to 0. Defaults to None, which means [].
  78. log_failed_cmd: if false, failed commands are not logged,
  79. only raised.
  80. """
  81. if extra_ok_returncodes is None:
  82. extra_ok_returncodes = []
  83. # log the subprocess output at DEBUG level.
  84. log_subprocess = subprocess_logger.debug
  85. env = os.environ.copy()
  86. if extra_environ:
  87. env.update(extra_environ)
  88. # Whether the subprocess will be visible in the console.
  89. showing_subprocess = True
  90. command_desc = format_command_args(cmd)
  91. try:
  92. proc = subprocess.Popen(
  93. # Convert HiddenText objects to the underlying str.
  94. reveal_command_args(cmd),
  95. stdout=subprocess.PIPE,
  96. stderr=subprocess.PIPE,
  97. cwd=cwd
  98. )
  99. if proc.stdin:
  100. proc.stdin.close()
  101. except Exception as exc:
  102. if log_failed_cmd:
  103. subprocess_logger.critical(
  104. "Error %s while executing command %s", exc, command_desc,
  105. )
  106. raise
  107. all_output = []
  108. while True:
  109. # The "line" value is a unicode string in Python 2.
  110. line = None
  111. if proc.stdout:
  112. line = console_to_str(proc.stdout.readline())
  113. if not line:
  114. break
  115. line = line.rstrip()
  116. all_output.append(line + '\n')
  117. # Show the line immediately.
  118. log_subprocess(line)
  119. try:
  120. proc.wait()
  121. finally:
  122. if proc.stdout:
  123. proc.stdout.close()
  124. proc_had_error = (
  125. proc.returncode and proc.returncode not in extra_ok_returncodes
  126. )
  127. if proc_had_error:
  128. if not showing_subprocess and log_failed_cmd:
  129. # Then the subprocess streams haven't been logged to the
  130. # console yet.
  131. msg = make_subprocess_output_error(
  132. cmd_args=cmd,
  133. cwd=cwd,
  134. lines=all_output,
  135. exit_status=proc.returncode,
  136. )
  137. subprocess_logger.error(msg)
  138. exc_msg = (
  139. 'Command errored out with exit status {}: {} '
  140. 'Check the logs for full command output.'
  141. ).format(proc.returncode, command_desc)
  142. raise SubProcessError(exc_msg)
  143. return ''.join(all_output)
  144. def find_path_to_setup_from_repo_root(location, repo_root):
  145. # type: (str, str) -> Optional[str]
  146. """
  147. Find the path to `setup.py` by searching up the filesystem from `location`.
  148. Return the path to `setup.py` relative to `repo_root`.
  149. Return None if `setup.py` is in `repo_root` or cannot be found.
  150. """
  151. # find setup.py
  152. orig_location = location
  153. while not os.path.exists(os.path.join(location, 'setup.py')):
  154. last_location = location
  155. location = os.path.dirname(location)
  156. if location == last_location:
  157. # We've traversed up to the root of the filesystem without
  158. # finding setup.py
  159. logger.warning(
  160. "Could not find setup.py for directory %s (tried all "
  161. "parent directories)",
  162. orig_location,
  163. )
  164. return None
  165. if samefile(repo_root, location):
  166. return None
  167. return os.path.relpath(location, repo_root)
  168. class RemoteNotFoundError(Exception):
  169. pass
  170. class RevOptions(object):
  171. """
  172. Encapsulates a VCS-specific revision to install, along with any VCS
  173. install options.
  174. Instances of this class should be treated as if immutable.
  175. """
  176. def __init__(
  177. self,
  178. vc_class, # type: Type[VersionControl]
  179. rev=None, # type: Optional[str]
  180. extra_args=None, # type: Optional[CommandArgs]
  181. ):
  182. # type: (...) -> None
  183. """
  184. Args:
  185. vc_class: a VersionControl subclass.
  186. rev: the name of the revision to install.
  187. extra_args: a list of extra options.
  188. """
  189. if extra_args is None:
  190. extra_args = []
  191. self.extra_args = extra_args
  192. self.rev = rev
  193. self.vc_class = vc_class
  194. self.branch_name = None # type: Optional[str]
  195. def __repr__(self):
  196. # type: () -> str
  197. return '<RevOptions {}: rev={!r}>'.format(self.vc_class.name, self.rev)
  198. @property
  199. def arg_rev(self):
  200. # type: () -> Optional[str]
  201. if self.rev is None:
  202. return self.vc_class.default_arg_rev
  203. return self.rev
  204. def to_args(self):
  205. # type: () -> CommandArgs
  206. """
  207. Return the VCS-specific command arguments.
  208. """
  209. args = [] # type: CommandArgs
  210. rev = self.arg_rev
  211. if rev is not None:
  212. args += self.vc_class.get_base_rev_args(rev)
  213. args += self.extra_args
  214. return args
  215. def to_display(self):
  216. # type: () -> str
  217. if not self.rev:
  218. return ''
  219. return ' (to revision {})'.format(self.rev)
  220. def make_new(self, rev):
  221. # type: (str) -> RevOptions
  222. """
  223. Make a copy of the current instance, but with a new rev.
  224. Args:
  225. rev: the name of the revision for the new object.
  226. """
  227. return self.vc_class.make_rev_options(rev, extra_args=self.extra_args)
  228. class VcsSupport(object):
  229. _registry = {} # type: Dict[str, VersionControl]
  230. schemes = ['ssh', 'git', 'hg', 'bzr', 'sftp', 'svn']
  231. def __init__(self):
  232. # type: () -> None
  233. # Register more schemes with urlparse for various version control
  234. # systems
  235. urllib_parse.uses_netloc.extend(self.schemes)
  236. # Python >= 2.7.4, 3.3 doesn't have uses_fragment
  237. if getattr(urllib_parse, 'uses_fragment', None):
  238. urllib_parse.uses_fragment.extend(self.schemes)
  239. super(VcsSupport, self).__init__()
  240. def __iter__(self):
  241. # type: () -> Iterator[str]
  242. return self._registry.__iter__()
  243. @property
  244. def backends(self):
  245. # type: () -> List[VersionControl]
  246. return list(self._registry.values())
  247. @property
  248. def dirnames(self):
  249. # type: () -> List[str]
  250. return [backend.dirname for backend in self.backends]
  251. @property
  252. def all_schemes(self):
  253. # type: () -> List[str]
  254. schemes = [] # type: List[str]
  255. for backend in self.backends:
  256. schemes.extend(backend.schemes)
  257. return schemes
  258. def register(self, cls):
  259. # type: (Type[VersionControl]) -> None
  260. if not hasattr(cls, 'name'):
  261. logger.warning('Cannot register VCS %s', cls.__name__)
  262. return
  263. if cls.name not in self._registry:
  264. self._registry[cls.name] = cls()
  265. logger.debug('Registered VCS backend: %s', cls.name)
  266. def unregister(self, name):
  267. # type: (str) -> None
  268. if name in self._registry:
  269. del self._registry[name]
  270. def get_backend_for_dir(self, location):
  271. # type: (str) -> Optional[VersionControl]
  272. """
  273. Return a VersionControl object if a repository of that type is found
  274. at the given directory.
  275. """
  276. vcs_backends = {}
  277. for vcs_backend in self._registry.values():
  278. repo_path = vcs_backend.get_repository_root(location)
  279. if not repo_path:
  280. continue
  281. logger.debug('Determine that %s uses VCS: %s',
  282. location, vcs_backend.name)
  283. vcs_backends[repo_path] = vcs_backend
  284. if not vcs_backends:
  285. return None
  286. # Choose the VCS in the inner-most directory. Since all repository
  287. # roots found here would be either `location` or one of its
  288. # parents, the longest path should have the most path components,
  289. # i.e. the backend representing the inner-most repository.
  290. inner_most_repo_path = max(vcs_backends, key=len)
  291. return vcs_backends[inner_most_repo_path]
  292. def get_backend_for_scheme(self, scheme):
  293. # type: (str) -> Optional[VersionControl]
  294. """
  295. Return a VersionControl object or None.
  296. """
  297. for vcs_backend in self._registry.values():
  298. if scheme in vcs_backend.schemes:
  299. return vcs_backend
  300. return None
  301. def get_backend(self, name):
  302. # type: (str) -> Optional[VersionControl]
  303. """
  304. Return a VersionControl object or None.
  305. """
  306. name = name.lower()
  307. return self._registry.get(name)
  308. vcs = VcsSupport()
  309. class VersionControl(object):
  310. name = ''
  311. dirname = ''
  312. repo_name = ''
  313. # List of supported schemes for this Version Control
  314. schemes = () # type: Tuple[str, ...]
  315. # Iterable of environment variable names to pass to call_subprocess().
  316. unset_environ = () # type: Tuple[str, ...]
  317. default_arg_rev = None # type: Optional[str]
  318. @classmethod
  319. def should_add_vcs_url_prefix(cls, remote_url):
  320. # type: (str) -> bool
  321. """
  322. Return whether the vcs prefix (e.g. "git+") should be added to a
  323. repository's remote url when used in a requirement.
  324. """
  325. return not remote_url.lower().startswith('{}:'.format(cls.name))
  326. @classmethod
  327. def get_subdirectory(cls, location):
  328. # type: (str) -> Optional[str]
  329. """
  330. Return the path to setup.py, relative to the repo root.
  331. Return None if setup.py is in the repo root.
  332. """
  333. return None
  334. @classmethod
  335. def get_requirement_revision(cls, repo_dir):
  336. # type: (str) -> str
  337. """
  338. Return the revision string that should be used in a requirement.
  339. """
  340. return cls.get_revision(repo_dir)
  341. @classmethod
  342. def get_src_requirement(cls, repo_dir, project_name):
  343. # type: (str, str) -> Optional[str]
  344. """
  345. Return the requirement string to use to redownload the files
  346. currently at the given repository directory.
  347. Args:
  348. project_name: the (unescaped) project name.
  349. The return value has a form similar to the following:
  350. {repository_url}@{revision}#egg={project_name}
  351. """
  352. repo_url = cls.get_remote_url(repo_dir)
  353. if repo_url is None:
  354. return None
  355. if cls.should_add_vcs_url_prefix(repo_url):
  356. repo_url = '{}+{}'.format(cls.name, repo_url)
  357. revision = cls.get_requirement_revision(repo_dir)
  358. subdir = cls.get_subdirectory(repo_dir)
  359. req = make_vcs_requirement_url(repo_url, revision, project_name,
  360. subdir=subdir)
  361. return req
  362. @staticmethod
  363. def get_base_rev_args(rev):
  364. # type: (str) -> List[str]
  365. """
  366. Return the base revision arguments for a vcs command.
  367. Args:
  368. rev: the name of a revision to install. Cannot be None.
  369. """
  370. raise NotImplementedError
  371. def is_immutable_rev_checkout(self, url, dest):
  372. # type: (str, str) -> bool
  373. """
  374. Return true if the commit hash checked out at dest matches
  375. the revision in url.
  376. Always return False, if the VCS does not support immutable commit
  377. hashes.
  378. This method does not check if there are local uncommitted changes
  379. in dest after checkout, as pip currently has no use case for that.
  380. """
  381. return False
  382. @classmethod
  383. def make_rev_options(cls, rev=None, extra_args=None):
  384. # type: (Optional[str], Optional[CommandArgs]) -> RevOptions
  385. """
  386. Return a RevOptions object.
  387. Args:
  388. rev: the name of a revision to install.
  389. extra_args: a list of extra options.
  390. """
  391. return RevOptions(cls, rev, extra_args=extra_args)
  392. @classmethod
  393. def _is_local_repository(cls, repo):
  394. # type: (str) -> bool
  395. """
  396. posix absolute paths start with os.path.sep,
  397. win32 ones start with drive (like c:\\folder)
  398. """
  399. drive, tail = os.path.splitdrive(repo)
  400. return repo.startswith(os.path.sep) or bool(drive)
  401. def export(self, location, url):
  402. # type: (str, HiddenText) -> None
  403. """
  404. Export the repository at the url to the destination location
  405. i.e. only download the files, without vcs informations
  406. :param url: the repository URL starting with a vcs prefix.
  407. """
  408. raise NotImplementedError
  409. @classmethod
  410. def get_netloc_and_auth(cls, netloc, scheme):
  411. # type: (str, str) -> Tuple[str, Tuple[Optional[str], Optional[str]]]
  412. """
  413. Parse the repository URL's netloc, and return the new netloc to use
  414. along with auth information.
  415. Args:
  416. netloc: the original repository URL netloc.
  417. scheme: the repository URL's scheme without the vcs prefix.
  418. This is mainly for the Subversion class to override, so that auth
  419. information can be provided via the --username and --password options
  420. instead of through the URL. For other subclasses like Git without
  421. such an option, auth information must stay in the URL.
  422. Returns: (netloc, (username, password)).
  423. """
  424. return netloc, (None, None)
  425. @classmethod
  426. def get_url_rev_and_auth(cls, url):
  427. # type: (str) -> Tuple[str, Optional[str], AuthInfo]
  428. """
  429. Parse the repository URL to use, and return the URL, revision,
  430. and auth info to use.
  431. Returns: (url, rev, (username, password)).
  432. """
  433. scheme, netloc, path, query, frag = urllib_parse.urlsplit(url)
  434. if '+' not in scheme:
  435. raise ValueError(
  436. "Sorry, {!r} is a malformed VCS url. "
  437. "The format is <vcs>+<protocol>://<url>, "
  438. "e.g. svn+http://myrepo/svn/MyApp#egg=MyApp".format(url)
  439. )
  440. # Remove the vcs prefix.
  441. scheme = scheme.split('+', 1)[1]
  442. netloc, user_pass = cls.get_netloc_and_auth(netloc, scheme)
  443. rev = None
  444. if '@' in path:
  445. path, rev = path.rsplit('@', 1)
  446. if not rev:
  447. raise InstallationError(
  448. "The URL {!r} has an empty revision (after @) "
  449. "which is not supported. Include a revision after @ "
  450. "or remove @ from the URL.".format(url)
  451. )
  452. url = urllib_parse.urlunsplit((scheme, netloc, path, query, ''))
  453. return url, rev, user_pass
  454. @staticmethod
  455. def make_rev_args(username, password):
  456. # type: (Optional[str], Optional[HiddenText]) -> CommandArgs
  457. """
  458. Return the RevOptions "extra arguments" to use in obtain().
  459. """
  460. return []
  461. def get_url_rev_options(self, url):
  462. # type: (HiddenText) -> Tuple[HiddenText, RevOptions]
  463. """
  464. Return the URL and RevOptions object to use in obtain() and in
  465. some cases export(), as a tuple (url, rev_options).
  466. """
  467. secret_url, rev, user_pass = self.get_url_rev_and_auth(url.secret)
  468. username, secret_password = user_pass
  469. password = None # type: Optional[HiddenText]
  470. if secret_password is not None:
  471. password = hide_value(secret_password)
  472. extra_args = self.make_rev_args(username, password)
  473. rev_options = self.make_rev_options(rev, extra_args=extra_args)
  474. return hide_url(secret_url), rev_options
  475. @staticmethod
  476. def normalize_url(url):
  477. # type: (str) -> str
  478. """
  479. Normalize a URL for comparison by unquoting it and removing any
  480. trailing slash.
  481. """
  482. return urllib_parse.unquote(url).rstrip('/')
  483. @classmethod
  484. def compare_urls(cls, url1, url2):
  485. # type: (str, str) -> bool
  486. """
  487. Compare two repo URLs for identity, ignoring incidental differences.
  488. """
  489. return (cls.normalize_url(url1) == cls.normalize_url(url2))
  490. def fetch_new(self, dest, url, rev_options):
  491. # type: (str, HiddenText, RevOptions) -> None
  492. """
  493. Fetch a revision from a repository, in the case that this is the
  494. first fetch from the repository.
  495. Args:
  496. dest: the directory to fetch the repository to.
  497. rev_options: a RevOptions object.
  498. """
  499. raise NotImplementedError
  500. def switch(self, dest, url, rev_options):
  501. # type: (str, HiddenText, RevOptions) -> None
  502. """
  503. Switch the repo at ``dest`` to point to ``URL``.
  504. Args:
  505. rev_options: a RevOptions object.
  506. """
  507. raise NotImplementedError
  508. def update(self, dest, url, rev_options):
  509. # type: (str, HiddenText, RevOptions) -> None
  510. """
  511. Update an already-existing repo to the given ``rev_options``.
  512. Args:
  513. rev_options: a RevOptions object.
  514. """
  515. raise NotImplementedError
  516. @classmethod
  517. def is_commit_id_equal(cls, dest, name):
  518. # type: (str, Optional[str]) -> bool
  519. """
  520. Return whether the id of the current commit equals the given name.
  521. Args:
  522. dest: the repository directory.
  523. name: a string name.
  524. """
  525. raise NotImplementedError
  526. def obtain(self, dest, url):
  527. # type: (str, HiddenText) -> None
  528. """
  529. Install or update in editable mode the package represented by this
  530. VersionControl object.
  531. :param dest: the repository directory in which to install or update.
  532. :param url: the repository URL starting with a vcs prefix.
  533. """
  534. url, rev_options = self.get_url_rev_options(url)
  535. if not os.path.exists(dest):
  536. self.fetch_new(dest, url, rev_options)
  537. return
  538. rev_display = rev_options.to_display()
  539. if self.is_repository_directory(dest):
  540. existing_url = self.get_remote_url(dest)
  541. if self.compare_urls(existing_url, url.secret):
  542. logger.debug(
  543. '%s in %s exists, and has correct URL (%s)',
  544. self.repo_name.title(),
  545. display_path(dest),
  546. url,
  547. )
  548. if not self.is_commit_id_equal(dest, rev_options.rev):
  549. logger.info(
  550. 'Updating %s %s%s',
  551. display_path(dest),
  552. self.repo_name,
  553. rev_display,
  554. )
  555. self.update(dest, url, rev_options)
  556. else:
  557. logger.info('Skipping because already up-to-date.')
  558. return
  559. logger.warning(
  560. '%s %s in %s exists with URL %s',
  561. self.name,
  562. self.repo_name,
  563. display_path(dest),
  564. existing_url,
  565. )
  566. prompt = ('(s)witch, (i)gnore, (w)ipe, (b)ackup ',
  567. ('s', 'i', 'w', 'b'))
  568. else:
  569. logger.warning(
  570. 'Directory %s already exists, and is not a %s %s.',
  571. dest,
  572. self.name,
  573. self.repo_name,
  574. )
  575. # https://github.com/python/mypy/issues/1174
  576. prompt = ('(i)gnore, (w)ipe, (b)ackup ', # type: ignore
  577. ('i', 'w', 'b'))
  578. logger.warning(
  579. 'The plan is to install the %s repository %s',
  580. self.name,
  581. url,
  582. )
  583. response = ask_path_exists('What to do? {}'.format(
  584. prompt[0]), prompt[1])
  585. if response == 'a':
  586. sys.exit(-1)
  587. if response == 'w':
  588. logger.warning('Deleting %s', display_path(dest))
  589. rmtree(dest)
  590. self.fetch_new(dest, url, rev_options)
  591. return
  592. if response == 'b':
  593. dest_dir = backup_dir(dest)
  594. logger.warning(
  595. 'Backing up %s to %s', display_path(dest), dest_dir,
  596. )
  597. shutil.move(dest, dest_dir)
  598. self.fetch_new(dest, url, rev_options)
  599. return
  600. # Do nothing if the response is "i".
  601. if response == 's':
  602. logger.info(
  603. 'Switching %s %s to %s%s',
  604. self.repo_name,
  605. display_path(dest),
  606. url,
  607. rev_display,
  608. )
  609. self.switch(dest, url, rev_options)
  610. def unpack(self, location, url):
  611. # type: (str, HiddenText) -> None
  612. """
  613. Clean up current location and download the url repository
  614. (and vcs infos) into location
  615. :param url: the repository URL starting with a vcs prefix.
  616. """
  617. if os.path.exists(location):
  618. rmtree(location)
  619. self.obtain(location, url=url)
  620. @classmethod
  621. def get_remote_url(cls, location):
  622. # type: (str) -> str
  623. """
  624. Return the url used at location
  625. Raises RemoteNotFoundError if the repository does not have a remote
  626. url configured.
  627. """
  628. raise NotImplementedError
  629. @classmethod
  630. def get_revision(cls, location):
  631. # type: (str) -> str
  632. """
  633. Return the current commit id of the files at the given location.
  634. """
  635. raise NotImplementedError
  636. @classmethod
  637. def run_command(
  638. cls,
  639. cmd, # type: Union[List[str], CommandArgs]
  640. cwd=None, # type: Optional[str]
  641. extra_environ=None, # type: Optional[Mapping[str, Any]]
  642. extra_ok_returncodes=None, # type: Optional[Iterable[int]]
  643. log_failed_cmd=True # type: bool
  644. ):
  645. # type: (...) -> Text
  646. """
  647. Run a VCS subcommand
  648. This is simply a wrapper around call_subprocess that adds the VCS
  649. command name, and checks that the VCS is available
  650. """
  651. cmd = make_command(cls.name, *cmd)
  652. try:
  653. return call_subprocess(cmd, cwd,
  654. extra_environ=extra_environ,
  655. extra_ok_returncodes=extra_ok_returncodes,
  656. log_failed_cmd=log_failed_cmd)
  657. except OSError as e:
  658. # errno.ENOENT = no such file or directory
  659. # In other words, the VCS executable isn't available
  660. if e.errno == errno.ENOENT:
  661. raise BadCommand(
  662. 'Cannot find command {cls.name!r} - do you have '
  663. '{cls.name!r} installed and in your '
  664. 'PATH?'.format(**locals()))
  665. else:
  666. raise # re-raise exception if a different error occurred
  667. @classmethod
  668. def is_repository_directory(cls, path):
  669. # type: (str) -> bool
  670. """
  671. Return whether a directory path is a repository directory.
  672. """
  673. logger.debug('Checking in %s for %s (%s)...',
  674. path, cls.dirname, cls.name)
  675. return os.path.exists(os.path.join(path, cls.dirname))
  676. @classmethod
  677. def get_repository_root(cls, location):
  678. # type: (str) -> Optional[str]
  679. """
  680. Return the "root" (top-level) directory controlled by the vcs,
  681. or `None` if the directory is not in any.
  682. It is meant to be overridden to implement smarter detection
  683. mechanisms for specific vcs.
  684. This can do more than is_repository_directory() alone. For
  685. example, the Git override checks that Git is actually available.
  686. """
  687. if cls.is_repository_directory(location):
  688. return location
  689. return None