Change venv

This commit is contained in:
Ambulance Clerc
2023-05-31 08:31:22 +02:00
parent fb6f579089
commit fdbb52c96f
466 changed files with 25899 additions and 64721 deletions

View File

@@ -16,61 +16,76 @@ logger = logging.getLogger(__name__)
class Bazaar(VersionControl):
name = 'bzr'
dirname = '.bzr'
repo_name = 'branch'
name = "bzr"
dirname = ".bzr"
repo_name = "branch"
schemes = (
'bzr+http', 'bzr+https', 'bzr+ssh', 'bzr+sftp', 'bzr+ftp',
'bzr+lp', 'bzr+file'
"bzr+http",
"bzr+https",
"bzr+ssh",
"bzr+sftp",
"bzr+ftp",
"bzr+lp",
"bzr+file",
)
@staticmethod
def get_base_rev_args(rev):
# type: (str) -> List[str]
return ['-r', rev]
def get_base_rev_args(rev: str) -> List[str]:
return ["-r", rev]
def fetch_new(self, dest, url, rev_options):
# type: (str, HiddenText, RevOptions) -> None
def fetch_new(
self, dest: str, url: HiddenText, rev_options: RevOptions, verbosity: int
) -> None:
rev_display = rev_options.to_display()
logger.info(
'Checking out %s%s to %s',
"Checking out %s%s to %s",
url,
rev_display,
display_path(dest),
)
cmd_args = (
make_command('branch', '-q', rev_options.to_args(), url, dest)
if verbosity <= 0:
flag = "--quiet"
elif verbosity == 1:
flag = ""
else:
flag = f"-{'v'*verbosity}"
cmd_args = make_command(
"checkout", "--lightweight", flag, rev_options.to_args(), url, dest
)
self.run_command(cmd_args)
def switch(self, dest, url, rev_options):
# type: (str, HiddenText, RevOptions) -> None
self.run_command(make_command('switch', url), cwd=dest)
def switch(self, dest: str, url: HiddenText, rev_options: RevOptions) -> None:
self.run_command(make_command("switch", url), cwd=dest)
def update(self, dest, url, rev_options):
# type: (str, HiddenText, RevOptions) -> None
cmd_args = make_command('pull', '-q', rev_options.to_args())
def update(self, dest: str, url: HiddenText, rev_options: RevOptions) -> None:
output = self.run_command(
make_command("info"), show_stdout=False, stdout_only=True, cwd=dest
)
if output.startswith("Standalone "):
# Older versions of pip used to create standalone branches.
# Convert the standalone branch to a checkout by calling "bzr bind".
cmd_args = make_command("bind", "-q", url)
self.run_command(cmd_args, cwd=dest)
cmd_args = make_command("update", "-q", rev_options.to_args())
self.run_command(cmd_args, cwd=dest)
@classmethod
def get_url_rev_and_auth(cls, url):
# type: (str) -> Tuple[str, Optional[str], AuthInfo]
# hotfix the URL scheme after removing bzr+ from bzr+ssh:// readd it
def get_url_rev_and_auth(cls, url: str) -> Tuple[str, Optional[str], AuthInfo]:
# hotfix the URL scheme after removing bzr+ from bzr+ssh:// re-add it
url, rev, user_pass = super().get_url_rev_and_auth(url)
if url.startswith('ssh://'):
url = 'bzr+' + url
if url.startswith("ssh://"):
url = "bzr+" + url
return url, rev, user_pass
@classmethod
def get_remote_url(cls, location):
# type: (str) -> str
def get_remote_url(cls, location: str) -> str:
urls = cls.run_command(
['info'], show_stdout=False, stdout_only=True, cwd=location
["info"], show_stdout=False, stdout_only=True, cwd=location
)
for line in urls.splitlines():
line = line.strip()
for x in ('checkout of branch: ',
'parent branch: '):
for x in ("checkout of branch: ", "parent branch: "):
if line.startswith(x):
repo = line.split(x)[1]
if cls._is_local_repository(repo):
@@ -79,16 +94,17 @@ class Bazaar(VersionControl):
raise RemoteNotFoundError
@classmethod
def get_revision(cls, location):
# type: (str) -> str
def get_revision(cls, location: str) -> str:
revision = cls.run_command(
['revno'], show_stdout=False, stdout_only=True, cwd=location,
["revno"],
show_stdout=False,
stdout_only=True,
cwd=location,
)
return revision.splitlines()[-1]
@classmethod
def is_commit_id_equal(cls, dest, name):
# type: (str, Optional[str]) -> bool
def is_commit_id_equal(cls, dest: str, name: Optional[str]) -> bool:
"""Always assume the versions don't match"""
return False

View File

@@ -34,10 +34,11 @@ GIT_VERSION_REGEX = re.compile(
r".*$" # Suffix, including any pre- and post-release segments we don't care about.
)
HASH_REGEX = re.compile('^[a-fA-F0-9]{40}$')
HASH_REGEX = re.compile("^[a-fA-F0-9]{40}$")
# SCP (Secure copy protocol) shorthand. e.g. 'git@example.com:foo/bar.git'
SCP_REGEX = re.compile(r"""^
SCP_REGEX = re.compile(
r"""^
# Optional user, e.g. 'git@'
(\w+@)?
# Server, e.g. 'github.com'.
@@ -46,33 +47,36 @@ SCP_REGEX = re.compile(r"""^
# alphanumeric character so as not to be confusable with a Windows paths
# like 'C:/foo/bar' or 'C:\foo\bar'.
(\w[^:]*)
$""", re.VERBOSE)
$""",
re.VERBOSE,
)
def looks_like_hash(sha):
# type: (str) -> bool
def looks_like_hash(sha: str) -> bool:
return bool(HASH_REGEX.match(sha))
class Git(VersionControl):
name = 'git'
dirname = '.git'
repo_name = 'clone'
name = "git"
dirname = ".git"
repo_name = "clone"
schemes = (
'git+http', 'git+https', 'git+ssh', 'git+git', 'git+file',
"git+http",
"git+https",
"git+ssh",
"git+git",
"git+file",
)
# Prevent the user's environment variables from interfering with pip:
# https://github.com/pypa/pip/issues/1130
unset_environ = ('GIT_DIR', 'GIT_WORK_TREE')
default_arg_rev = 'HEAD'
unset_environ = ("GIT_DIR", "GIT_WORK_TREE")
default_arg_rev = "HEAD"
@staticmethod
def get_base_rev_args(rev):
# type: (str) -> List[str]
def get_base_rev_args(rev: str) -> List[str]:
return [rev]
def is_immutable_rev_checkout(self, url, dest):
# type: (str, str) -> bool
def is_immutable_rev_checkout(self, url: str, dest: str) -> bool:
_, rev_options = self.get_url_rev_options(hide_url(url))
if not rev_options.rev:
return False
@@ -83,23 +87,24 @@ class Git(VersionControl):
# return False in the rare case rev is both a commit hash
# and a tag or a branch; we don't want to cache in that case
# because that branch/tag could point to something else in the future
is_tag_or_branch = bool(
self.get_revision_sha(dest, rev_options.rev)[0]
)
is_tag_or_branch = bool(self.get_revision_sha(dest, rev_options.rev)[0])
return not is_tag_or_branch
def get_git_version(self) -> Tuple[int, ...]:
version = self.run_command(
['version'], show_stdout=False, stdout_only=True
["version"],
command_desc="git version",
show_stdout=False,
stdout_only=True,
)
match = GIT_VERSION_REGEX.match(version)
if not match:
logger.warning("Can't parse git version: %s", version)
return ()
return tuple(int(c) for c in match.groups())
@classmethod
def get_current_branch(cls, location):
# type: (str) -> Optional[str]
def get_current_branch(cls, location: str) -> Optional[str]:
"""
Return the current branch, or None if HEAD isn't at a branch
(e.g. detached HEAD).
@@ -108,24 +113,23 @@ class Git(VersionControl):
# HEAD rather than a symbolic ref. In addition, the -q causes the
# command to exit with status code 1 instead of 128 in this case
# and to suppress the message to stderr.
args = ['symbolic-ref', '-q', 'HEAD']
args = ["symbolic-ref", "-q", "HEAD"]
output = cls.run_command(
args,
extra_ok_returncodes=(1, ),
extra_ok_returncodes=(1,),
show_stdout=False,
stdout_only=True,
cwd=location,
)
ref = output.strip()
if ref.startswith('refs/heads/'):
return ref[len('refs/heads/'):]
if ref.startswith("refs/heads/"):
return ref[len("refs/heads/") :]
return None
@classmethod
def get_revision_sha(cls, dest, rev):
# type: (str, str) -> Tuple[Optional[str], bool]
def get_revision_sha(cls, dest: str, rev: str) -> Tuple[Optional[str], bool]:
"""
Return (sha_or_none, is_branch), where sha_or_none is a commit hash
if the revision names a remote branch or tag, otherwise None.
@@ -136,11 +140,11 @@ class Git(VersionControl):
"""
# Pass rev to pre-filter the list.
output = cls.run_command(
['show-ref', rev],
["show-ref", rev],
cwd=dest,
show_stdout=False,
stdout_only=True,
on_returncode='ignore',
on_returncode="ignore",
)
refs = {}
# NOTE: We do not use splitlines here since that would split on other
@@ -155,12 +159,12 @@ class Git(VersionControl):
except ValueError:
# Include the offending line to simplify troubleshooting if
# this error ever occurs.
raise ValueError(f'unexpected show-ref line: {line!r}')
raise ValueError(f"unexpected show-ref line: {line!r}")
refs[ref_name] = ref_sha
branch_ref = f'refs/remotes/origin/{rev}'
tag_ref = f'refs/tags/{rev}'
branch_ref = f"refs/remotes/origin/{rev}"
tag_ref = f"refs/tags/{rev}"
sha = refs.get(branch_ref)
if sha is not None:
@@ -171,8 +175,7 @@ class Git(VersionControl):
return (sha, False)
@classmethod
def _should_fetch(cls, dest, rev):
# type: (str, str) -> bool
def _should_fetch(cls, dest: str, rev: str) -> bool:
"""
Return true if rev is a ref or is a commit that we don't have locally.
@@ -195,8 +198,9 @@ class Git(VersionControl):
return True
@classmethod
def resolve_revision(cls, dest, url, rev_options):
# type: (str, HiddenText, RevOptions) -> RevOptions
def resolve_revision(
cls, dest: str, url: HiddenText, rev_options: RevOptions
) -> RevOptions:
"""
Resolve a revision to a new RevOptions object with the SHA1 of the
branch, tag, or ref if found.
@@ -230,18 +234,17 @@ class Git(VersionControl):
# fetch the requested revision
cls.run_command(
make_command('fetch', '-q', url, rev_options.to_args()),
make_command("fetch", "-q", url, rev_options.to_args()),
cwd=dest,
)
# Change the revision to the SHA of the ref we fetched
sha = cls.get_revision(dest, rev='FETCH_HEAD')
sha = cls.get_revision(dest, rev="FETCH_HEAD")
rev_options = rev_options.make_new(sha)
return rev_options
@classmethod
def is_commit_id_equal(cls, dest, name):
# type: (str, Optional[str]) -> bool
def is_commit_id_equal(cls, dest: str, name: Optional[str]) -> bool:
"""
Return whether the current commit hash equals the given name.
@@ -255,30 +258,58 @@ class Git(VersionControl):
return cls.get_revision(dest) == name
def fetch_new(self, dest, url, rev_options):
# type: (str, HiddenText, RevOptions) -> None
def fetch_new(
self, dest: str, url: HiddenText, rev_options: RevOptions, verbosity: int
) -> None:
rev_display = rev_options.to_display()
logger.info('Cloning %s%s to %s', url, rev_display, display_path(dest))
self.run_command(make_command('clone', '-q', url, dest))
logger.info("Cloning %s%s to %s", url, rev_display, display_path(dest))
if verbosity <= 0:
flags: Tuple[str, ...] = ("--quiet",)
elif verbosity == 1:
flags = ()
else:
flags = ("--verbose", "--progress")
if self.get_git_version() >= (2, 17):
# Git added support for partial clone in 2.17
# https://git-scm.com/docs/partial-clone
# Speeds up cloning by functioning without a complete copy of repository
self.run_command(
make_command(
"clone",
"--filter=blob:none",
*flags,
url,
dest,
)
)
else:
self.run_command(make_command("clone", *flags, url, dest))
if rev_options.rev:
# Then a specific revision was requested.
rev_options = self.resolve_revision(dest, url, rev_options)
branch_name = getattr(rev_options, 'branch_name', None)
branch_name = getattr(rev_options, "branch_name", None)
logger.debug("Rev options %s, branch_name %s", rev_options, branch_name)
if branch_name is None:
# Only do a checkout if the current commit id doesn't match
# the requested revision.
if not self.is_commit_id_equal(dest, rev_options.rev):
cmd_args = make_command(
'checkout', '-q', rev_options.to_args(),
"checkout",
"-q",
rev_options.to_args(),
)
self.run_command(cmd_args, cwd=dest)
elif self.get_current_branch(dest) != branch_name:
# Then a specific branch was requested, and that branch
# is not yet checked out.
track_branch = f'origin/{branch_name}'
track_branch = f"origin/{branch_name}"
cmd_args = [
'checkout', '-b', branch_name, '--track', track_branch,
"checkout",
"-b",
branch_name,
"--track",
track_branch,
]
self.run_command(cmd_args, cwd=dest)
else:
@@ -290,35 +321,32 @@ class Git(VersionControl):
#: repo may contain submodules
self.update_submodules(dest)
def switch(self, dest, url, rev_options):
# type: (str, HiddenText, RevOptions) -> None
def switch(self, dest: str, url: HiddenText, rev_options: RevOptions) -> None:
self.run_command(
make_command('config', 'remote.origin.url', url),
make_command("config", "remote.origin.url", url),
cwd=dest,
)
cmd_args = make_command('checkout', '-q', rev_options.to_args())
cmd_args = make_command("checkout", "-q", rev_options.to_args())
self.run_command(cmd_args, cwd=dest)
self.update_submodules(dest)
def update(self, dest, url, rev_options):
# type: (str, HiddenText, RevOptions) -> None
def update(self, dest: str, url: HiddenText, rev_options: RevOptions) -> None:
# First fetch changes from the default remote
if self.get_git_version() >= (1, 9):
# fetch tags in addition to everything else
self.run_command(['fetch', '-q', '--tags'], cwd=dest)
self.run_command(["fetch", "-q", "--tags"], cwd=dest)
else:
self.run_command(['fetch', '-q'], cwd=dest)
self.run_command(["fetch", "-q"], cwd=dest)
# Then reset to wanted revision (maybe even origin/master)
rev_options = self.resolve_revision(dest, url, rev_options)
cmd_args = make_command('reset', '--hard', '-q', rev_options.to_args())
cmd_args = make_command("reset", "--hard", "-q", rev_options.to_args())
self.run_command(cmd_args, cwd=dest)
#: update submodules
self.update_submodules(dest)
@classmethod
def get_remote_url(cls, location):
# type: (str) -> str
def get_remote_url(cls, location: str) -> str:
"""
Return URL of the first remote encountered.
@@ -328,8 +356,8 @@ class Git(VersionControl):
# We need to pass 1 for extra_ok_returncodes since the command
# exits with return code 1 if there are no matching lines.
stdout = cls.run_command(
['config', '--get-regexp', r'remote\..*\.url'],
extra_ok_returncodes=(1, ),
["config", "--get-regexp", r"remote\..*\.url"],
extra_ok_returncodes=(1,),
show_stdout=False,
stdout_only=True,
cwd=location,
@@ -341,15 +369,14 @@ class Git(VersionControl):
raise RemoteNotFoundError
for remote in remotes:
if remote.startswith('remote.origin.url '):
if remote.startswith("remote.origin.url "):
found_remote = remote
break
url = found_remote.split(' ')[1]
url = found_remote.split(" ")[1]
return cls._git_remote_to_pip_url(url.strip())
@staticmethod
def _git_remote_to_pip_url(url):
# type: (str) -> str
def _git_remote_to_pip_url(url: str) -> str:
"""
Convert a remote url from what git uses to what pip accepts.
@@ -380,14 +407,13 @@ class Git(VersionControl):
raise RemoteNotValidError(url)
@classmethod
def has_commit(cls, location, rev):
# type: (str, str) -> bool
def has_commit(cls, location: str, rev: str) -> bool:
"""
Check if rev is a commit that is available in the local repository.
"""
try:
cls.run_command(
['rev-parse', '-q', '--verify', "sha^" + rev],
["rev-parse", "-q", "--verify", "sha^" + rev],
cwd=location,
log_failed_cmd=False,
)
@@ -397,12 +423,11 @@ class Git(VersionControl):
return True
@classmethod
def get_revision(cls, location, rev=None):
# type: (str, Optional[str]) -> str
def get_revision(cls, location: str, rev: Optional[str] = None) -> str:
if rev is None:
rev = 'HEAD'
rev = "HEAD"
current_rev = cls.run_command(
['rev-parse', rev],
["rev-parse", rev],
show_stdout=False,
stdout_only=True,
cwd=location,
@@ -410,27 +435,25 @@ class Git(VersionControl):
return current_rev.strip()
@classmethod
def get_subdirectory(cls, location):
# type: (str) -> Optional[str]
def get_subdirectory(cls, location: str) -> Optional[str]:
"""
Return the path to Python project root, relative to the repo root.
Return None if the project root is in the repo root.
"""
# find the repo root
git_dir = cls.run_command(
['rev-parse', '--git-dir'],
["rev-parse", "--git-dir"],
show_stdout=False,
stdout_only=True,
cwd=location,
).strip()
if not os.path.isabs(git_dir):
git_dir = os.path.join(location, git_dir)
repo_root = os.path.abspath(os.path.join(git_dir, '..'))
repo_root = os.path.abspath(os.path.join(git_dir, ".."))
return find_path_to_project_root_from_repo_root(location, repo_root)
@classmethod
def get_url_rev_and_auth(cls, url):
# type: (str) -> Tuple[str, Optional[str], AuthInfo]
def get_url_rev_and_auth(cls, url: str) -> Tuple[str, Optional[str], AuthInfo]:
"""
Prefixes stub URLs like 'user@hostname:user/repo.git' with 'ssh://'.
That's required because although they use SSH they sometimes don't
@@ -440,66 +463,63 @@ class Git(VersionControl):
# Works around an apparent Git bug
# (see https://article.gmane.org/gmane.comp.version-control.git/146500)
scheme, netloc, path, query, fragment = urlsplit(url)
if scheme.endswith('file'):
initial_slashes = path[:-len(path.lstrip('/'))]
newpath = (
initial_slashes +
urllib.request.url2pathname(path)
.replace('\\', '/').lstrip('/')
)
after_plus = scheme.find('+') + 1
if scheme.endswith("file"):
initial_slashes = path[: -len(path.lstrip("/"))]
newpath = initial_slashes + urllib.request.url2pathname(path).replace(
"\\", "/"
).lstrip("/")
after_plus = scheme.find("+") + 1
url = scheme[:after_plus] + urlunsplit(
(scheme[after_plus:], netloc, newpath, query, fragment),
)
if '://' not in url:
assert 'file:' not in url
url = url.replace('git+', 'git+ssh://')
if "://" not in url:
assert "file:" not in url
url = url.replace("git+", "git+ssh://")
url, rev, user_pass = super().get_url_rev_and_auth(url)
url = url.replace('ssh://', '')
url = url.replace("ssh://", "")
else:
url, rev, user_pass = super().get_url_rev_and_auth(url)
return url, rev, user_pass
@classmethod
def update_submodules(cls, location):
# type: (str) -> None
if not os.path.exists(os.path.join(location, '.gitmodules')):
def update_submodules(cls, location: str) -> None:
if not os.path.exists(os.path.join(location, ".gitmodules")):
return
cls.run_command(
['submodule', 'update', '--init', '--recursive', '-q'],
["submodule", "update", "--init", "--recursive", "-q"],
cwd=location,
)
@classmethod
def get_repository_root(cls, location):
# type: (str) -> Optional[str]
def get_repository_root(cls, location: str) -> Optional[str]:
loc = super().get_repository_root(location)
if loc:
return loc
try:
r = cls.run_command(
['rev-parse', '--show-toplevel'],
["rev-parse", "--show-toplevel"],
cwd=location,
show_stdout=False,
stdout_only=True,
on_returncode='raise',
on_returncode="raise",
log_failed_cmd=False,
)
except BadCommand:
logger.debug("could not determine if %s is under git control "
"because git is not available", location)
logger.debug(
"could not determine if %s is under git control "
"because git is not available",
location,
)
return None
except InstallationError:
return None
return os.path.normpath(r.rstrip('\r\n'))
return os.path.normpath(r.rstrip("\r\n"))
@staticmethod
def should_add_vcs_url_prefix(repo_url):
# type: (str) -> bool
"""In either https or ssh form, requirements must be prefixed with git+.
"""
def should_add_vcs_url_prefix(repo_url: str) -> bool:
"""In either https or ssh form, requirements must be prefixed with git+."""
return True

View File

@@ -1,7 +1,7 @@
import configparser
import logging
import os
from typing import List, Optional
from typing import List, Optional, Tuple
from pip._internal.exceptions import BadCommand, InstallationError
from pip._internal.utils.misc import HiddenText, display_path
@@ -18,61 +18,68 @@ logger = logging.getLogger(__name__)
class Mercurial(VersionControl):
name = 'hg'
dirname = '.hg'
repo_name = 'clone'
name = "hg"
dirname = ".hg"
repo_name = "clone"
schemes = (
'hg+file', 'hg+http', 'hg+https', 'hg+ssh', 'hg+static-http',
"hg+file",
"hg+http",
"hg+https",
"hg+ssh",
"hg+static-http",
)
@staticmethod
def get_base_rev_args(rev):
# type: (str) -> List[str]
def get_base_rev_args(rev: str) -> List[str]:
return [rev]
def fetch_new(self, dest, url, rev_options):
# type: (str, HiddenText, RevOptions) -> None
def fetch_new(
self, dest: str, url: HiddenText, rev_options: RevOptions, verbosity: int
) -> None:
rev_display = rev_options.to_display()
logger.info(
'Cloning hg %s%s to %s',
"Cloning hg %s%s to %s",
url,
rev_display,
display_path(dest),
)
self.run_command(make_command('clone', '--noupdate', '-q', url, dest))
if verbosity <= 0:
flags: Tuple[str, ...] = ("--quiet",)
elif verbosity == 1:
flags = ()
elif verbosity == 2:
flags = ("--verbose",)
else:
flags = ("--verbose", "--debug")
self.run_command(make_command("clone", "--noupdate", *flags, url, dest))
self.run_command(
make_command('update', '-q', rev_options.to_args()),
make_command("update", *flags, rev_options.to_args()),
cwd=dest,
)
def switch(self, dest, url, rev_options):
# type: (str, HiddenText, RevOptions) -> None
repo_config = os.path.join(dest, self.dirname, 'hgrc')
def switch(self, dest: str, url: HiddenText, rev_options: RevOptions) -> None:
repo_config = os.path.join(dest, self.dirname, "hgrc")
config = configparser.RawConfigParser()
try:
config.read(repo_config)
config.set('paths', 'default', url.secret)
with open(repo_config, 'w') as config_file:
config.set("paths", "default", url.secret)
with open(repo_config, "w") as config_file:
config.write(config_file)
except (OSError, configparser.NoSectionError) as exc:
logger.warning(
'Could not switch Mercurial repository to %s: %s', url, exc,
)
logger.warning("Could not switch Mercurial repository to %s: %s", url, exc)
else:
cmd_args = make_command('update', '-q', rev_options.to_args())
cmd_args = make_command("update", "-q", rev_options.to_args())
self.run_command(cmd_args, cwd=dest)
def update(self, dest, url, rev_options):
# type: (str, HiddenText, RevOptions) -> None
self.run_command(['pull', '-q'], cwd=dest)
cmd_args = make_command('update', '-q', rev_options.to_args())
def update(self, dest: str, url: HiddenText, rev_options: RevOptions) -> None:
self.run_command(["pull", "-q"], cwd=dest)
cmd_args = make_command("update", "-q", rev_options.to_args())
self.run_command(cmd_args, cwd=dest)
@classmethod
def get_remote_url(cls, location):
# type: (str) -> str
def get_remote_url(cls, location: str) -> str:
url = cls.run_command(
['showconfig', 'paths.default'],
["showconfig", "paths.default"],
show_stdout=False,
stdout_only=True,
cwd=location,
@@ -82,13 +89,12 @@ class Mercurial(VersionControl):
return url.strip()
@classmethod
def get_revision(cls, location):
# type: (str) -> str
def get_revision(cls, location: str) -> str:
"""
Return the repository-local changeset revision number, as an integer.
"""
current_revision = cls.run_command(
['parents', '--template={rev}'],
["parents", "--template={rev}"],
show_stdout=False,
stdout_only=True,
cwd=location,
@@ -96,14 +102,13 @@ class Mercurial(VersionControl):
return current_revision
@classmethod
def get_requirement_revision(cls, location):
# type: (str) -> str
def get_requirement_revision(cls, location: str) -> str:
"""
Return the changeset identification hash, as a 40-character
hexadecimal string
"""
current_rev_hash = cls.run_command(
['parents', '--template={node}'],
["parents", "--template={node}"],
show_stdout=False,
stdout_only=True,
cwd=location,
@@ -111,48 +116,48 @@ class Mercurial(VersionControl):
return current_rev_hash
@classmethod
def is_commit_id_equal(cls, dest, name):
# type: (str, Optional[str]) -> bool
def is_commit_id_equal(cls, dest: str, name: Optional[str]) -> bool:
"""Always assume the versions don't match"""
return False
@classmethod
def get_subdirectory(cls, location):
# type: (str) -> Optional[str]
def get_subdirectory(cls, location: str) -> Optional[str]:
"""
Return the path to Python project root, relative to the repo root.
Return None if the project root is in the repo root.
"""
# find the repo root
repo_root = cls.run_command(
['root'], show_stdout=False, stdout_only=True, cwd=location
["root"], show_stdout=False, stdout_only=True, cwd=location
).strip()
if not os.path.isabs(repo_root):
repo_root = os.path.abspath(os.path.join(location, repo_root))
return find_path_to_project_root_from_repo_root(location, repo_root)
@classmethod
def get_repository_root(cls, location):
# type: (str) -> Optional[str]
def get_repository_root(cls, location: str) -> Optional[str]:
loc = super().get_repository_root(location)
if loc:
return loc
try:
r = cls.run_command(
['root'],
["root"],
cwd=location,
show_stdout=False,
stdout_only=True,
on_returncode='raise',
on_returncode="raise",
log_failed_cmd=False,
)
except BadCommand:
logger.debug("could not determine if %s is under hg control "
"because hg is not available", location)
logger.debug(
"could not determine if %s is under hg control "
"because hg is not available",
location,
)
return None
except InstallationError:
return None
return os.path.normpath(r.rstrip('\r\n'))
return os.path.normpath(r.rstrip("\r\n"))
vcs.register(Mercurial)

View File

@@ -24,30 +24,25 @@ logger = logging.getLogger(__name__)
_svn_xml_url_re = re.compile('url="([^"]+)"')
_svn_rev_re = re.compile(r'committed-rev="(\d+)"')
_svn_info_xml_rev_re = re.compile(r'\s*revision="(\d+)"')
_svn_info_xml_url_re = re.compile(r'<url>(.*)</url>')
_svn_info_xml_url_re = re.compile(r"<url>(.*)</url>")
class Subversion(VersionControl):
name = 'svn'
dirname = '.svn'
repo_name = 'checkout'
schemes = (
'svn+ssh', 'svn+http', 'svn+https', 'svn+svn', 'svn+file'
)
name = "svn"
dirname = ".svn"
repo_name = "checkout"
schemes = ("svn+ssh", "svn+http", "svn+https", "svn+svn", "svn+file")
@classmethod
def should_add_vcs_url_prefix(cls, remote_url):
# type: (str) -> bool
def should_add_vcs_url_prefix(cls, remote_url: str) -> bool:
return True
@staticmethod
def get_base_rev_args(rev):
# type: (str) -> List[str]
return ['-r', rev]
def get_base_rev_args(rev: str) -> List[str]:
return ["-r", rev]
@classmethod
def get_revision(cls, location):
# type: (str) -> str
def get_revision(cls, location: str) -> str:
"""
Return the maximum revision for all files under a given location
"""
@@ -57,9 +52,9 @@ class Subversion(VersionControl):
for base, dirs, _ in os.walk(location):
if cls.dirname not in dirs:
dirs[:] = []
continue # no sense walking uncontrolled subdirs
continue # no sense walking uncontrolled subdirs
dirs.remove(cls.dirname)
entries_fn = os.path.join(base, cls.dirname, 'entries')
entries_fn = os.path.join(base, cls.dirname, "entries")
if not os.path.exists(entries_fn):
# FIXME: should we warn?
continue
@@ -68,21 +63,22 @@ class Subversion(VersionControl):
if base == location:
assert dirurl is not None
base = dirurl + '/' # save the root url
base = dirurl + "/" # save the root url
elif not dirurl or not dirurl.startswith(base):
dirs[:] = []
continue # not part of the same svn tree, skip it
continue # not part of the same svn tree, skip it
revision = max(revision, localrev)
return str(revision)
@classmethod
def get_netloc_and_auth(cls, netloc, scheme):
# type: (str, str) -> Tuple[str, Tuple[Optional[str], Optional[str]]]
def get_netloc_and_auth(
cls, netloc: str, scheme: str
) -> Tuple[str, Tuple[Optional[str], Optional[str]]]:
"""
This override allows the auth information to be passed to svn via the
--username and --password options instead of via the URL.
"""
if scheme == 'ssh':
if scheme == "ssh":
# The --username and --password options can't be used for
# svn+ssh URLs, so keep the auth information in the URL.
return super().get_netloc_and_auth(netloc, scheme)
@@ -90,28 +86,27 @@ class Subversion(VersionControl):
return split_auth_from_netloc(netloc)
@classmethod
def get_url_rev_and_auth(cls, url):
# type: (str) -> Tuple[str, Optional[str], AuthInfo]
# hotfix the URL scheme after removing svn+ from svn+ssh:// readd it
def get_url_rev_and_auth(cls, url: str) -> Tuple[str, Optional[str], AuthInfo]:
# hotfix the URL scheme after removing svn+ from svn+ssh:// re-add it
url, rev, user_pass = super().get_url_rev_and_auth(url)
if url.startswith('ssh://'):
url = 'svn+' + url
if url.startswith("ssh://"):
url = "svn+" + url
return url, rev, user_pass
@staticmethod
def make_rev_args(username, password):
# type: (Optional[str], Optional[HiddenText]) -> CommandArgs
extra_args = [] # type: CommandArgs
def make_rev_args(
username: Optional[str], password: Optional[HiddenText]
) -> CommandArgs:
extra_args: CommandArgs = []
if username:
extra_args += ['--username', username]
extra_args += ["--username", username]
if password:
extra_args += ['--password', password]
extra_args += ["--password", password]
return extra_args
@classmethod
def get_remote_url(cls, location):
# type: (str) -> str
def get_remote_url(cls, location: str) -> str:
# In cases where the source is in a subdirectory, we have to look up in
# the location until we find a valid project root.
orig_location = location
@@ -135,30 +130,27 @@ class Subversion(VersionControl):
return url
@classmethod
def _get_svn_url_rev(cls, location):
# type: (str) -> Tuple[Optional[str], int]
def _get_svn_url_rev(cls, location: str) -> Tuple[Optional[str], int]:
from pip._internal.exceptions import InstallationError
entries_path = os.path.join(location, cls.dirname, 'entries')
entries_path = os.path.join(location, cls.dirname, "entries")
if os.path.exists(entries_path):
with open(entries_path) as f:
data = f.read()
else: # subversion >= 1.7 does not have the 'entries' file
data = ''
data = ""
url = None
if (data.startswith('8') or
data.startswith('9') or
data.startswith('10')):
entries = list(map(str.splitlines, data.split('\n\x0c\n')))
if data.startswith("8") or data.startswith("9") or data.startswith("10"):
entries = list(map(str.splitlines, data.split("\n\x0c\n")))
del entries[0][0] # get rid of the '8'
url = entries[0][3]
revs = [int(d[9]) for d in entries if len(d) > 9 and d[9]] + [0]
elif data.startswith('<?xml'):
elif data.startswith("<?xml"):
match = _svn_xml_url_re.search(data)
if not match:
raise ValueError(f'Badly formatted data: {data!r}')
url = match.group(1) # get repository URL
raise ValueError(f"Badly formatted data: {data!r}")
url = match.group(1) # get repository URL
revs = [int(m.group(1)) for m in _svn_rev_re.finditer(data)] + [0]
else:
try:
@@ -169,16 +161,14 @@ class Subversion(VersionControl):
# is being used to prompt for passwords, because passwords
# are only potentially needed for remote server requests.
xml = cls.run_command(
['info', '--xml', location],
["info", "--xml", location],
show_stdout=False,
stdout_only=True,
)
match = _svn_info_xml_url_re.search(xml)
assert match is not None
url = match.group(1)
revs = [
int(m.group(1)) for m in _svn_info_xml_rev_re.finditer(xml)
]
revs = [int(m.group(1)) for m in _svn_info_xml_rev_re.finditer(xml)]
except InstallationError:
url, revs = None, []
@@ -190,13 +180,11 @@ class Subversion(VersionControl):
return url, rev
@classmethod
def is_commit_id_equal(cls, dest, name):
# type: (str, Optional[str]) -> bool
def is_commit_id_equal(cls, dest: str, name: Optional[str]) -> bool:
"""Always assume the versions don't match"""
return False
def __init__(self, use_interactive=None):
# type: (bool) -> None
def __init__(self, use_interactive: Optional[bool] = None) -> None:
if use_interactive is None:
use_interactive = is_console_interactive()
self.use_interactive = use_interactive
@@ -206,12 +194,11 @@ class Subversion(VersionControl):
# Special value definitions:
# None: Not evaluated yet.
# Empty tuple: Could not parse version.
self._vcs_version = None # type: Optional[Tuple[int, ...]]
self._vcs_version: Optional[Tuple[int, ...]] = None
super().__init__()
def call_vcs_version(self):
# type: () -> Tuple[int, ...]
def call_vcs_version(self) -> Tuple[int, ...]:
"""Query the version of the currently installed Subversion client.
:return: A tuple containing the parts of the version information or
@@ -225,15 +212,13 @@ class Subversion(VersionControl):
# compiled Mar 28 2018, 08:49:13 on x86_64-pc-linux-gnu
# svn, version 1.12.0-SlikSvn (SlikSvn/1.12.0)
# compiled May 28 2019, 13:44:56 on x86_64-microsoft-windows6.2
version_prefix = 'svn, version '
version = self.run_command(
['--version'], show_stdout=False, stdout_only=True
)
version_prefix = "svn, version "
version = self.run_command(["--version"], show_stdout=False, stdout_only=True)
if not version.startswith(version_prefix):
return ()
version = version[len(version_prefix):].split()[0]
version_list = version.partition('-')[0].split('.')
version = version[len(version_prefix) :].split()[0]
version_list = version.partition("-")[0].split(".")
try:
parsed_version = tuple(map(int, version_list))
except ValueError:
@@ -241,8 +226,7 @@ class Subversion(VersionControl):
return parsed_version
def get_vcs_version(self):
# type: () -> Tuple[int, ...]
def get_vcs_version(self) -> Tuple[int, ...]:
"""Return the version of the currently installed Subversion client.
If the version of the Subversion client has already been queried,
@@ -262,8 +246,7 @@ class Subversion(VersionControl):
self._vcs_version = vcs_version
return vcs_version
def get_remote_call_options(self):
# type: () -> CommandArgs
def get_remote_call_options(self) -> CommandArgs:
"""Return options to be used on calls to Subversion that contact the server.
These options are applicable for the following ``svn`` subcommands used
@@ -278,7 +261,7 @@ class Subversion(VersionControl):
if not self.use_interactive:
# --non-interactive switch is available since Subversion 0.14.4.
# Subversion < 1.8 runs in interactive mode by default.
return ['--non-interactive']
return ["--non-interactive"]
svn_version = self.get_vcs_version()
# By default, Subversion >= 1.8 runs in non-interactive mode if
@@ -290,37 +273,49 @@ class Subversion(VersionControl):
# SVN 1.7, pip should continue to support SVN 1.7. Therefore, pip
# can't safely add the option if the SVN version is < 1.8 (or unknown).
if svn_version >= (1, 8):
return ['--force-interactive']
return ["--force-interactive"]
return []
def fetch_new(self, dest, url, rev_options):
# type: (str, HiddenText, RevOptions) -> None
def fetch_new(
self, dest: str, url: HiddenText, rev_options: RevOptions, verbosity: int
) -> None:
rev_display = rev_options.to_display()
logger.info(
'Checking out %s%s to %s',
"Checking out %s%s to %s",
url,
rev_display,
display_path(dest),
)
if verbosity <= 0:
flag = "--quiet"
else:
flag = ""
cmd_args = make_command(
'checkout', '-q', self.get_remote_call_options(),
rev_options.to_args(), url, dest,
"checkout",
flag,
self.get_remote_call_options(),
rev_options.to_args(),
url,
dest,
)
self.run_command(cmd_args)
def switch(self, dest, url, rev_options):
# type: (str, HiddenText, RevOptions) -> None
def switch(self, dest: str, url: HiddenText, rev_options: RevOptions) -> None:
cmd_args = make_command(
'switch', self.get_remote_call_options(), rev_options.to_args(),
url, dest,
"switch",
self.get_remote_call_options(),
rev_options.to_args(),
url,
dest,
)
self.run_command(cmd_args)
def update(self, dest, url, rev_options):
# type: (str, HiddenText, RevOptions) -> None
def update(self, dest: str, url: HiddenText, rev_options: RevOptions) -> None:
cmd_args = make_command(
'update', self.get_remote_call_options(), rev_options.to_args(),
"update",
self.get_remote_call_options(),
rev_options.to_args(),
dest,
)
self.run_command(cmd_args)

View File

@@ -6,6 +6,7 @@ import shutil
import sys
import urllib.parse
from typing import (
TYPE_CHECKING,
Any,
Dict,
Iterable,
@@ -30,10 +31,22 @@ from pip._internal.utils.misc import (
is_installable_dir,
rmtree,
)
from pip._internal.utils.subprocess import CommandArgs, call_subprocess, make_command
from pip._internal.utils.subprocess import (
CommandArgs,
call_subprocess,
format_command_args,
make_command,
)
from pip._internal.utils.urls import get_url_scheme
__all__ = ['vcs']
if TYPE_CHECKING:
# Literal was introduced in Python 3.8.
#
# TODO: Remove `if TYPE_CHECKING` when dropping support for Python 3.7.
from typing import Literal
__all__ = ["vcs"]
logger = logging.getLogger(__name__)
@@ -41,19 +54,19 @@ logger = logging.getLogger(__name__)
AuthInfo = Tuple[Optional[str], Optional[str]]
def is_url(name):
# type: (str) -> bool
def is_url(name: str) -> bool:
"""
Return true if the name looks like a URL.
"""
scheme = get_url_scheme(name)
if scheme is None:
return False
return scheme in ['http', 'https', 'file', 'ftp'] + vcs.all_schemes
return scheme in ["http", "https", "file", "ftp"] + vcs.all_schemes
def make_vcs_requirement_url(repo_url, rev, project_name, subdir=None):
# type: (str, str, str, Optional[str]) -> str
def make_vcs_requirement_url(
repo_url: str, rev: str, project_name: str, subdir: Optional[str] = None
) -> str:
"""
Return the URL for a VCS requirement.
@@ -62,15 +75,16 @@ def make_vcs_requirement_url(repo_url, rev, project_name, subdir=None):
project_name: the (unescaped) project name.
"""
egg_project_name = project_name.replace("-", "_")
req = f'{repo_url}@{rev}#egg={egg_project_name}'
req = f"{repo_url}@{rev}#egg={egg_project_name}"
if subdir:
req += f'&subdirectory={subdir}'
req += f"&subdirectory={subdir}"
return req
def find_path_to_project_root_from_repo_root(location, repo_root):
# type: (str, str) -> Optional[str]
def find_path_to_project_root_from_repo_root(
location: str, repo_root: str
) -> Optional[str]:
"""
Find the the Python project's root by searching up the filesystem from
`location`. Return the path to project root relative to `repo_root`.
@@ -118,11 +132,10 @@ class RevOptions:
def __init__(
self,
vc_class, # type: Type[VersionControl]
rev=None, # type: Optional[str]
extra_args=None, # type: Optional[CommandArgs]
):
# type: (...) -> None
vc_class: Type["VersionControl"],
rev: Optional[str] = None,
extra_args: Optional[CommandArgs] = None,
) -> None:
"""
Args:
vc_class: a VersionControl subclass.
@@ -135,26 +148,23 @@ class RevOptions:
self.extra_args = extra_args
self.rev = rev
self.vc_class = vc_class
self.branch_name = None # type: Optional[str]
self.branch_name: Optional[str] = None
def __repr__(self):
# type: () -> str
return f'<RevOptions {self.vc_class.name}: rev={self.rev!r}>'
def __repr__(self) -> str:
return f"<RevOptions {self.vc_class.name}: rev={self.rev!r}>"
@property
def arg_rev(self):
# type: () -> Optional[str]
def arg_rev(self) -> Optional[str]:
if self.rev is None:
return self.vc_class.default_arg_rev
return self.rev
def to_args(self):
# type: () -> CommandArgs
def to_args(self) -> CommandArgs:
"""
Return the VCS-specific command arguments.
"""
args = [] # type: CommandArgs
args: CommandArgs = []
rev = self.arg_rev
if rev is not None:
args += self.vc_class.get_base_rev_args(rev)
@@ -162,15 +172,13 @@ class RevOptions:
return args
def to_display(self):
# type: () -> str
def to_display(self) -> str:
if not self.rev:
return ''
return ""
return f' (to revision {self.rev})'
return f" (to revision {self.rev})"
def make_new(self, rev):
# type: (str) -> RevOptions
def make_new(self, rev: str) -> "RevOptions":
"""
Make a copy of the current instance, but with a new rev.
@@ -181,54 +189,46 @@ class RevOptions:
class VcsSupport:
_registry = {} # type: Dict[str, VersionControl]
schemes = ['ssh', 'git', 'hg', 'bzr', 'sftp', 'svn']
_registry: Dict[str, "VersionControl"] = {}
schemes = ["ssh", "git", "hg", "bzr", "sftp", "svn"]
def __init__(self):
# type: () -> None
def __init__(self) -> None:
# Register more schemes with urlparse for various version control
# systems
urllib.parse.uses_netloc.extend(self.schemes)
super().__init__()
def __iter__(self):
# type: () -> Iterator[str]
def __iter__(self) -> Iterator[str]:
return self._registry.__iter__()
@property
def backends(self):
# type: () -> List[VersionControl]
def backends(self) -> List["VersionControl"]:
return list(self._registry.values())
@property
def dirnames(self):
# type: () -> List[str]
def dirnames(self) -> List[str]:
return [backend.dirname for backend in self.backends]
@property
def all_schemes(self):
# type: () -> List[str]
schemes = [] # type: List[str]
def all_schemes(self) -> List[str]:
schemes: List[str] = []
for backend in self.backends:
schemes.extend(backend.schemes)
return schemes
def register(self, cls):
# type: (Type[VersionControl]) -> None
if not hasattr(cls, 'name'):
logger.warning('Cannot register VCS %s', cls.__name__)
def register(self, cls: Type["VersionControl"]) -> None:
if not hasattr(cls, "name"):
logger.warning("Cannot register VCS %s", cls.__name__)
return
if cls.name not in self._registry:
self._registry[cls.name] = cls()
logger.debug('Registered VCS backend: %s', cls.name)
logger.debug("Registered VCS backend: %s", cls.name)
def unregister(self, name):
# type: (str) -> None
def unregister(self, name: str) -> None:
if name in self._registry:
del self._registry[name]
def get_backend_for_dir(self, location):
# type: (str) -> Optional[VersionControl]
def get_backend_for_dir(self, location: str) -> Optional["VersionControl"]:
"""
Return a VersionControl object if a repository of that type is found
at the given directory.
@@ -238,8 +238,7 @@ class VcsSupport:
repo_path = vcs_backend.get_repository_root(location)
if not repo_path:
continue
logger.debug('Determine that %s uses VCS: %s',
location, vcs_backend.name)
logger.debug("Determine that %s uses VCS: %s", location, vcs_backend.name)
vcs_backends[repo_path] = vcs_backend
if not vcs_backends:
@@ -252,8 +251,7 @@ class VcsSupport:
inner_most_repo_path = max(vcs_backends, key=len)
return vcs_backends[inner_most_repo_path]
def get_backend_for_scheme(self, scheme):
# type: (str) -> Optional[VersionControl]
def get_backend_for_scheme(self, scheme: str) -> Optional["VersionControl"]:
"""
Return a VersionControl object or None.
"""
@@ -262,8 +260,7 @@ class VcsSupport:
return vcs_backend
return None
def get_backend(self, name):
# type: (str) -> Optional[VersionControl]
def get_backend(self, name: str) -> Optional["VersionControl"]:
"""
Return a VersionControl object or None.
"""
@@ -275,27 +272,25 @@ vcs = VcsSupport()
class VersionControl:
name = ''
dirname = ''
repo_name = ''
name = ""
dirname = ""
repo_name = ""
# List of supported schemes for this Version Control
schemes = () # type: Tuple[str, ...]
schemes: Tuple[str, ...] = ()
# Iterable of environment variable names to pass to call_subprocess().
unset_environ = () # type: Tuple[str, ...]
default_arg_rev = None # type: Optional[str]
unset_environ: Tuple[str, ...] = ()
default_arg_rev: Optional[str] = None
@classmethod
def should_add_vcs_url_prefix(cls, remote_url):
# type: (str) -> bool
def should_add_vcs_url_prefix(cls, remote_url: str) -> bool:
"""
Return whether the vcs prefix (e.g. "git+") should be added to a
repository's remote url when used in a requirement.
"""
return not remote_url.lower().startswith(f'{cls.name}:')
return not remote_url.lower().startswith(f"{cls.name}:")
@classmethod
def get_subdirectory(cls, location):
# type: (str) -> Optional[str]
def get_subdirectory(cls, location: str) -> Optional[str]:
"""
Return the path to Python project root, relative to the repo root.
Return None if the project root is in the repo root.
@@ -303,16 +298,14 @@ class VersionControl:
return None
@classmethod
def get_requirement_revision(cls, repo_dir):
# type: (str) -> str
def get_requirement_revision(cls, repo_dir: str) -> str:
"""
Return the revision string that should be used in a requirement.
"""
return cls.get_revision(repo_dir)
@classmethod
def get_src_requirement(cls, repo_dir, project_name):
# type: (str, str) -> str
def get_src_requirement(cls, repo_dir: str, project_name: str) -> str:
"""
Return the requirement string to use to redownload the files
currently at the given repository directory.
@@ -327,18 +320,16 @@ class VersionControl:
repo_url = cls.get_remote_url(repo_dir)
if cls.should_add_vcs_url_prefix(repo_url):
repo_url = f'{cls.name}+{repo_url}'
repo_url = f"{cls.name}+{repo_url}"
revision = cls.get_requirement_revision(repo_dir)
subdir = cls.get_subdirectory(repo_dir)
req = make_vcs_requirement_url(repo_url, revision, project_name,
subdir=subdir)
req = make_vcs_requirement_url(repo_url, revision, project_name, subdir=subdir)
return req
@staticmethod
def get_base_rev_args(rev):
# type: (str) -> List[str]
def get_base_rev_args(rev: str) -> List[str]:
"""
Return the base revision arguments for a vcs command.
@@ -347,8 +338,7 @@ class VersionControl:
"""
raise NotImplementedError
def is_immutable_rev_checkout(self, url, dest):
# type: (str, str) -> bool
def is_immutable_rev_checkout(self, url: str, dest: str) -> bool:
"""
Return true if the commit hash checked out at dest matches
the revision in url.
@@ -362,8 +352,9 @@ class VersionControl:
return False
@classmethod
def make_rev_options(cls, rev=None, extra_args=None):
# type: (Optional[str], Optional[CommandArgs]) -> RevOptions
def make_rev_options(
cls, rev: Optional[str] = None, extra_args: Optional[CommandArgs] = None
) -> RevOptions:
"""
Return a RevOptions object.
@@ -374,18 +365,18 @@ class VersionControl:
return RevOptions(cls, rev, extra_args=extra_args)
@classmethod
def _is_local_repository(cls, repo):
# type: (str) -> bool
def _is_local_repository(cls, repo: str) -> bool:
"""
posix absolute paths start with os.path.sep,
win32 ones start with drive (like c:\\folder)
posix absolute paths start with os.path.sep,
win32 ones start with drive (like c:\\folder)
"""
drive, tail = os.path.splitdrive(repo)
return repo.startswith(os.path.sep) or bool(drive)
@classmethod
def get_netloc_and_auth(cls, netloc, scheme):
# type: (str, str) -> Tuple[str, Tuple[Optional[str], Optional[str]]]
def get_netloc_and_auth(
cls, netloc: str, scheme: str
) -> Tuple[str, Tuple[Optional[str], Optional[str]]]:
"""
Parse the repository URL's netloc, and return the new netloc to use
along with auth information.
@@ -404,8 +395,7 @@ class VersionControl:
return netloc, (None, None)
@classmethod
def get_url_rev_and_auth(cls, url):
# type: (str) -> Tuple[str, Optional[str], AuthInfo]
def get_url_rev_and_auth(cls, url: str) -> Tuple[str, Optional[str], AuthInfo]:
"""
Parse the repository URL to use, and return the URL, revision,
and auth info to use.
@@ -413,44 +403,44 @@ class VersionControl:
Returns: (url, rev, (username, password)).
"""
scheme, netloc, path, query, frag = urllib.parse.urlsplit(url)
if '+' not in scheme:
if "+" not in scheme:
raise ValueError(
"Sorry, {!r} is a malformed VCS url. "
"The format is <vcs>+<protocol>://<url>, "
"e.g. svn+http://myrepo/svn/MyApp#egg=MyApp".format(url)
)
# Remove the vcs prefix.
scheme = scheme.split('+', 1)[1]
scheme = scheme.split("+", 1)[1]
netloc, user_pass = cls.get_netloc_and_auth(netloc, scheme)
rev = None
if '@' in path:
path, rev = path.rsplit('@', 1)
if "@" in path:
path, rev = path.rsplit("@", 1)
if not rev:
raise InstallationError(
"The URL {!r} has an empty revision (after @) "
"which is not supported. Include a revision after @ "
"or remove @ from the URL.".format(url)
)
url = urllib.parse.urlunsplit((scheme, netloc, path, query, ''))
url = urllib.parse.urlunsplit((scheme, netloc, path, query, ""))
return url, rev, user_pass
@staticmethod
def make_rev_args(username, password):
# type: (Optional[str], Optional[HiddenText]) -> CommandArgs
def make_rev_args(
username: Optional[str], password: Optional[HiddenText]
) -> CommandArgs:
"""
Return the RevOptions "extra arguments" to use in obtain().
"""
return []
def get_url_rev_options(self, url):
# type: (HiddenText) -> Tuple[HiddenText, RevOptions]
def get_url_rev_options(self, url: HiddenText) -> Tuple[HiddenText, RevOptions]:
"""
Return the URL and RevOptions object to use in obtain(),
as a tuple (url, rev_options).
"""
secret_url, rev, user_pass = self.get_url_rev_and_auth(url.secret)
username, secret_password = user_pass
password = None # type: Optional[HiddenText]
password: Optional[HiddenText] = None
if secret_password is not None:
password = hide_value(secret_password)
extra_args = self.make_rev_args(username, password)
@@ -459,24 +449,23 @@ class VersionControl:
return hide_url(secret_url), rev_options
@staticmethod
def normalize_url(url):
# type: (str) -> str
def normalize_url(url: str) -> str:
"""
Normalize a URL for comparison by unquoting it and removing any
trailing slash.
"""
return urllib.parse.unquote(url).rstrip('/')
return urllib.parse.unquote(url).rstrip("/")
@classmethod
def compare_urls(cls, url1, url2):
# type: (str, str) -> bool
def compare_urls(cls, url1: str, url2: str) -> bool:
"""
Compare two repo URLs for identity, ignoring incidental differences.
"""
return (cls.normalize_url(url1) == cls.normalize_url(url2))
return cls.normalize_url(url1) == cls.normalize_url(url2)
def fetch_new(self, dest, url, rev_options):
# type: (str, HiddenText, RevOptions) -> None
def fetch_new(
self, dest: str, url: HiddenText, rev_options: RevOptions, verbosity: int
) -> None:
"""
Fetch a revision from a repository, in the case that this is the
first fetch from the repository.
@@ -484,11 +473,11 @@ class VersionControl:
Args:
dest: the directory to fetch the repository to.
rev_options: a RevOptions object.
verbosity: verbosity level.
"""
raise NotImplementedError
def switch(self, dest, url, rev_options):
# type: (str, HiddenText, RevOptions) -> None
def switch(self, dest: str, url: HiddenText, rev_options: RevOptions) -> None:
"""
Switch the repo at ``dest`` to point to ``URL``.
@@ -497,8 +486,7 @@ class VersionControl:
"""
raise NotImplementedError
def update(self, dest, url, rev_options):
# type: (str, HiddenText, RevOptions) -> None
def update(self, dest: str, url: HiddenText, rev_options: RevOptions) -> None:
"""
Update an already-existing repo to the given ``rev_options``.
@@ -508,8 +496,7 @@ class VersionControl:
raise NotImplementedError
@classmethod
def is_commit_id_equal(cls, dest, name):
# type: (str, Optional[str]) -> bool
def is_commit_id_equal(cls, dest: str, name: Optional[str]) -> bool:
"""
Return whether the id of the current commit equals the given name.
@@ -519,19 +506,19 @@ class VersionControl:
"""
raise NotImplementedError
def obtain(self, dest, url):
# type: (str, HiddenText) -> None
def obtain(self, dest: str, url: HiddenText, verbosity: int) -> None:
"""
Install or update in editable mode the package represented by this
VersionControl object.
:param dest: the repository directory in which to install or update.
:param url: the repository URL starting with a vcs prefix.
:param verbosity: verbosity level.
"""
url, rev_options = self.get_url_rev_options(url)
if not os.path.exists(dest):
self.fetch_new(dest, url, rev_options)
self.fetch_new(dest, url, rev_options, verbosity=verbosity)
return
rev_display = rev_options.to_display()
@@ -539,73 +526,68 @@ class VersionControl:
existing_url = self.get_remote_url(dest)
if self.compare_urls(existing_url, url.secret):
logger.debug(
'%s in %s exists, and has correct URL (%s)',
"%s in %s exists, and has correct URL (%s)",
self.repo_name.title(),
display_path(dest),
url,
)
if not self.is_commit_id_equal(dest, rev_options.rev):
logger.info(
'Updating %s %s%s',
"Updating %s %s%s",
display_path(dest),
self.repo_name,
rev_display,
)
self.update(dest, url, rev_options)
else:
logger.info('Skipping because already up-to-date.')
logger.info("Skipping because already up-to-date.")
return
logger.warning(
'%s %s in %s exists with URL %s',
"%s %s in %s exists with URL %s",
self.name,
self.repo_name,
display_path(dest),
existing_url,
)
prompt = ('(s)witch, (i)gnore, (w)ipe, (b)ackup ',
('s', 'i', 'w', 'b'))
prompt = ("(s)witch, (i)gnore, (w)ipe, (b)ackup ", ("s", "i", "w", "b"))
else:
logger.warning(
'Directory %s already exists, and is not a %s %s.',
"Directory %s already exists, and is not a %s %s.",
dest,
self.name,
self.repo_name,
)
# https://github.com/python/mypy/issues/1174
prompt = ('(i)gnore, (w)ipe, (b)ackup ', # type: ignore
('i', 'w', 'b'))
prompt = ("(i)gnore, (w)ipe, (b)ackup ", ("i", "w", "b")) # type: ignore
logger.warning(
'The plan is to install the %s repository %s',
"The plan is to install the %s repository %s",
self.name,
url,
)
response = ask_path_exists('What to do? {}'.format(
prompt[0]), prompt[1])
response = ask_path_exists("What to do? {}".format(prompt[0]), prompt[1])
if response == 'a':
if response == "a":
sys.exit(-1)
if response == 'w':
logger.warning('Deleting %s', display_path(dest))
if response == "w":
logger.warning("Deleting %s", display_path(dest))
rmtree(dest)
self.fetch_new(dest, url, rev_options)
self.fetch_new(dest, url, rev_options, verbosity=verbosity)
return
if response == 'b':
if response == "b":
dest_dir = backup_dir(dest)
logger.warning(
'Backing up %s to %s', display_path(dest), dest_dir,
)
logger.warning("Backing up %s to %s", display_path(dest), dest_dir)
shutil.move(dest, dest_dir)
self.fetch_new(dest, url, rev_options)
self.fetch_new(dest, url, rev_options, verbosity=verbosity)
return
# Do nothing if the response is "i".
if response == 's':
if response == "s":
logger.info(
'Switching %s %s to %s%s',
"Switching %s %s to %s%s",
self.repo_name,
display_path(dest),
url,
@@ -613,21 +595,20 @@ class VersionControl:
)
self.switch(dest, url, rev_options)
def unpack(self, location, url):
# type: (str, HiddenText) -> None
def unpack(self, location: str, url: HiddenText, verbosity: int) -> None:
"""
Clean up current location and download the url repository
(and vcs infos) into location
:param url: the repository URL starting with a vcs prefix.
:param verbosity: verbosity level.
"""
if os.path.exists(location):
rmtree(location)
self.obtain(location, url=url)
self.obtain(location, url=url, verbosity=verbosity)
@classmethod
def get_remote_url(cls, location):
# type: (str) -> str
def get_remote_url(cls, location: str) -> str:
"""
Return the url used at location
@@ -637,8 +618,7 @@ class VersionControl:
raise NotImplementedError
@classmethod
def get_revision(cls, location):
# type: (str) -> str
def get_revision(cls, location: str) -> str:
"""
Return the current commit id of the files at the given location.
"""
@@ -647,40 +627,46 @@ class VersionControl:
@classmethod
def run_command(
cls,
cmd, # type: Union[List[str], CommandArgs]
show_stdout=True, # type: bool
cwd=None, # type: Optional[str]
on_returncode='raise', # type: str
extra_ok_returncodes=None, # type: Optional[Iterable[int]]
command_desc=None, # type: Optional[str]
extra_environ=None, # type: Optional[Mapping[str, Any]]
spinner=None, # type: Optional[SpinnerInterface]
log_failed_cmd=True, # type: bool
stdout_only=False, # type: bool
):
# type: (...) -> str
cmd: Union[List[str], CommandArgs],
show_stdout: bool = True,
cwd: Optional[str] = None,
on_returncode: 'Literal["raise", "warn", "ignore"]' = "raise",
extra_ok_returncodes: Optional[Iterable[int]] = None,
command_desc: Optional[str] = None,
extra_environ: Optional[Mapping[str, Any]] = None,
spinner: Optional[SpinnerInterface] = None,
log_failed_cmd: bool = True,
stdout_only: bool = False,
) -> str:
"""
Run a VCS subcommand
This is simply a wrapper around call_subprocess that adds the VCS
command name, and checks that the VCS is available
"""
cmd = make_command(cls.name, *cmd)
if command_desc is None:
command_desc = format_command_args(cmd)
try:
return call_subprocess(cmd, show_stdout, cwd,
on_returncode=on_returncode,
extra_ok_returncodes=extra_ok_returncodes,
command_desc=command_desc,
extra_environ=extra_environ,
unset_environ=cls.unset_environ,
spinner=spinner,
log_failed_cmd=log_failed_cmd,
stdout_only=stdout_only)
return call_subprocess(
cmd,
show_stdout,
cwd,
on_returncode=on_returncode,
extra_ok_returncodes=extra_ok_returncodes,
command_desc=command_desc,
extra_environ=extra_environ,
unset_environ=cls.unset_environ,
spinner=spinner,
log_failed_cmd=log_failed_cmd,
stdout_only=stdout_only,
)
except FileNotFoundError:
# errno.ENOENT = no such file or directory
# In other words, the VCS executable isn't available
raise BadCommand(
f'Cannot find command {cls.name!r} - do you have '
f'{cls.name!r} installed and in your PATH?')
f"Cannot find command {cls.name!r} - do you have "
f"{cls.name!r} installed and in your PATH?"
)
except PermissionError:
# errno.EACCES = Permission denied
# This error occurs, for instance, when the command is installed
@@ -695,18 +681,15 @@ class VersionControl:
)
@classmethod
def is_repository_directory(cls, path):
# type: (str) -> bool
def is_repository_directory(cls, path: str) -> bool:
"""
Return whether a directory path is a repository directory.
"""
logger.debug('Checking in %s for %s (%s)...',
path, cls.dirname, cls.name)
logger.debug("Checking in %s for %s (%s)...", path, cls.dirname, cls.name)
return os.path.exists(os.path.join(path, cls.dirname))
@classmethod
def get_repository_root(cls, location):
# type: (str) -> Optional[str]
def get_repository_root(cls, location: str) -> Optional[str]:
"""
Return the "root" (top-level) directory controlled by the vcs,
or `None` if the directory is not in any.