Commit 6b2299c3 by Bjorn Neergaard

feat: pyupgrade via pre-commit

parent 7c53db96
......@@ -40,6 +40,13 @@ repos:
- flake8-typing-imports==1.11.0
- pep8-naming==0.12.1
- repo: https://github.com/asottile/pyupgrade
rev: v2.29.0
hooks:
- id: pyupgrade
args: [--py36-plus]
exclude: '^(install|get)-poetry.py$'
- repo: https://github.com/pycqa/isort
rev: 5.10.1
hooks:
......
......@@ -247,7 +247,7 @@ class AddCommand(InstallerCommand, InitCommand):
"The following packages are already present in the pyproject.toml and will be skipped:\n"
)
for name in existing_packages:
self.line(" • <c1>{name}</c1>".format(name=name))
self.line(f" • <c1>{name}</c1>")
self.line(
"\nIf you want to update it to the latest compatible version, you can use `poetry update package`.\n"
"If you prefer to upgrade it to the latest available version, you can use `poetry add package@latest`.\n"
......
......@@ -29,7 +29,7 @@ class CacheClearCommand(Command):
try:
cache_dir.relative_to(REPOSITORY_CACHE_DIR)
except ValueError:
raise ValueError("{} is not a valid repository cache".format(root))
raise ValueError(f"{root} is not a valid repository cache")
cache = CacheManager(
{
......@@ -47,7 +47,7 @@ class CacheClearCommand(Command):
)
if not os.path.exists(str(cache_dir)):
self.line("No cache entries for {}".format(parts[0]))
self.line(f"No cache entries for {parts[0]}")
return 0
# Calculate number of entries
......@@ -55,9 +55,7 @@ class CacheClearCommand(Command):
for _path, _dirs, files in os.walk(str(cache_dir)):
entries_count += len(files)
delete = self.confirm(
"<question>Delete {} entries?</>".format(entries_count)
)
delete = self.confirm(f"<question>Delete {entries_count} entries?</>")
if not delete:
return 0
......@@ -71,14 +69,14 @@ class CacheClearCommand(Command):
package = parts[1]
version = parts[2]
if not cache.has("{}:{}".format(package, version)):
self.line("No cache entries for {}:{}".format(package, version))
if not cache.has(f"{package}:{version}"):
self.line(f"No cache entries for {package}:{version}")
return 0
delete = self.confirm("Delete cache entry {}:{}".format(package, version))
delete = self.confirm(f"Delete cache entry {package}:{version}")
if not delete:
return 0
cache.forget("{}:{}".format(package, version))
cache.forget(f"{package}:{version}")
else:
raise ValueError("Invalid cache key")
......@@ -17,7 +17,7 @@ class CacheListCommand(Command):
caches = sorted(REPOSITORY_CACHE_DIR.iterdir())
if caches:
for cache in caches:
self.line("<info>{}</>".format(cache.name))
self.line(f"<info>{cache.name}</>")
return 0
self.line("<warning>No caches found</>")
......
......@@ -22,9 +22,9 @@ class CheckCommand(Command):
return 0
for error in check_result["errors"]:
self.line("<error>Error: {}</error>".format(error))
self.line(f"<error>Error: {error}</error>")
for error in check_result["warnings"]:
self.line("<warning>Warning: {}</warning>".format(error))
self.line(f"<warning>Warning: {error}</warning>")
return 1
......@@ -138,11 +138,9 @@ To remove a repository (repo is a short alias for repositories):
if config.get("repositories") is not None:
value = config.get("repositories")
else:
repo = config.get("repositories.{}".format(m.group(1)))
repo = config.get(f"repositories.{m.group(1)}")
if repo is None:
raise ValueError(
"There is no {} repository defined".format(m.group(1))
)
raise ValueError(f"There is no {m.group(1)} repository defined")
value = repo
......@@ -150,7 +148,7 @@ To remove a repository (repo is a short alias for repositories):
else:
values = self.unique_config_values
if setting_key not in values:
raise ValueError("There is no {} setting.".format(setting_key))
raise ValueError(f"There is no {setting_key} setting.")
value = config.get(setting_key)
......@@ -183,24 +181,18 @@ To remove a repository (repo is a short alias for repositories):
raise ValueError("You cannot remove the [repositories] section")
if self.option("unset"):
repo = config.get("repositories.{}".format(m.group(1)))
repo = config.get(f"repositories.{m.group(1)}")
if repo is None:
raise ValueError(
"There is no {} repository defined".format(m.group(1))
)
raise ValueError(f"There is no {m.group(1)} repository defined")
config.config_source.remove_property(
"repositories.{}".format(m.group(1))
)
config.config_source.remove_property(f"repositories.{m.group(1)}")
return 0
if len(values) == 1:
url = values[0]
config.config_source.add_property(
"repositories.{}.url".format(m.group(1)), url
)
config.config_source.add_property(f"repositories.{m.group(1)}.url", url)
return 0
......@@ -241,7 +233,7 @@ To remove a repository (repo is a short alias for repositories):
elif m.group(1) == "pypi-token":
if len(values) != 1:
raise ValueError(
"Expected only one argument (token), got {}".format(len(values))
f"Expected only one argument (token), got {len(values)}"
)
token = values[0]
......@@ -257,14 +249,14 @@ To remove a repository (repo is a short alias for repositories):
if m:
if self.option("unset"):
config.auth_config_source.remove_property(
"certificates.{}.{}".format(m.group(1), m.group(2))
f"certificates.{m.group(1)}.{m.group(2)}"
)
return 0
if len(values) == 1:
config.auth_config_source.add_property(
"certificates.{}.{}".format(m.group(1), m.group(2)), values[0]
f"certificates.{m.group(1)}.{m.group(2)}", values[0]
)
else:
raise ValueError("You must pass exactly 1 value")
......@@ -287,7 +279,7 @@ To remove a repository (repo is a short alias for repositories):
value = values[0]
if not validator(value):
raise RuntimeError('"{}" is an invalid value for {}'.format(value, key))
raise RuntimeError(f'"{value}" is an invalid value for {key}')
source.add_property(key, normalizer(value))
......@@ -302,7 +294,7 @@ To remove a repository (repo is a short alias for repositories):
raw_val = raw.get(key)
if isinstance(value, dict):
k += "{}.".format(key)
k += f"{key}."
self._list_configuration(value, raw_val, k=k)
k = orig_k
......@@ -323,7 +315,7 @@ To remove a repository (repo is a short alias for repositories):
k + key, json.dumps(raw_val), value
)
else:
message = "<c1>{}</c1> = <c2>{}</c2>".format(k + key, json.dumps(value))
message = f"<c1>{k + key}</c1> = <c2>{json.dumps(value)}</c2>"
self.line(message)
......
......@@ -16,7 +16,7 @@ class DebugInfoCommand(Command):
self.line(
"\n".join(
[
"<info>Version</info>: <comment>{}</>".format(self.poetry.VERSION),
f"<info>Version</info>: <comment>{self.poetry.VERSION}</>",
"<info>Python</info>: <comment>{}</>".format(
poetry_python_version
),
......
......@@ -131,8 +131,8 @@ class DebugResolveCommand(InitCommand):
pkg = op.package
row = [
"<c1>{}</c1>".format(pkg.complete_name),
"<b>{}</b>".format(pkg.version),
f"<c1>{pkg.complete_name}</c1>",
f"<b>{pkg.version}</b>",
]
if not pkg.marker.is_any():
......
......@@ -38,7 +38,7 @@ class EnvInfoCommand(Command):
self.line("")
self.line("<b>Virtualenv</b>")
listing = [
"<info>Python</info>: <comment>{}</>".format(env_python_version),
f"<info>Python</info>: <comment>{env_python_version}</>",
"<info>Implementation</info>: <comment>{}</>".format(
env.python_implementation
),
......@@ -64,13 +64,13 @@ class EnvInfoCommand(Command):
self.line(
"\n".join(
[
"<info>Platform</info>: <comment>{}</>".format(env.platform),
"<info>OS</info>: <comment>{}</>".format(env.os),
f"<info>Platform</info>: <comment>{env.platform}</>",
f"<info>OS</info>: <comment>{env.os}</>",
"<info>Python</info>: <comment>{}</>".format(
".".join(str(v) for v in system_env.version_info[:3])
),
"<info>Path</info>: <comment>{}</>".format(system_env.path),
"<info>Executable</info>: <comment>{}</>".format(system_env.python),
f"<info>Path</info>: <comment>{system_env.path}</>",
f"<info>Executable</info>: <comment>{system_env.python}</>",
]
)
)
......@@ -22,7 +22,7 @@ class EnvListCommand(Command):
name = str(venv.path)
if venv == current_env:
self.line("<info>{} (Activated)</info>".format(name))
self.line(f"<info>{name} (Activated)</info>")
continue
......
......@@ -38,8 +38,8 @@ class EnvRemoveCommand(Command):
# TODO: refactor env.py to allow removal with one loop
for python in pythons:
venv = manager.remove(python)
self.line("Deleted virtualenv: <comment>{}</comment>".format(venv.path))
self.line(f"Deleted virtualenv: <comment>{venv.path}</comment>")
if all:
for venv in manager.list():
manager.remove_venv(venv.path)
self.line("Deleted virtualenv: <comment>{}</comment>".format(venv.path))
self.line(f"Deleted virtualenv: <comment>{venv.path}</comment>")
......@@ -22,4 +22,4 @@ class EnvUseCommand(Command):
env = manager.activate(self.argument("python"), self._io)
self.line("Using virtualenv: <comment>{}</>".format(env.path))
self.line(f"Using virtualenv: <comment>{env.path}</>")
......@@ -8,7 +8,7 @@ class EnvCommand(Command):
def __init__(self) -> None:
self._env = None
super(EnvCommand, self).__init__()
super().__init__()
@property
def env(self) -> Optional[Env]:
......
......@@ -39,7 +39,7 @@ class ExportCommand(Command):
fmt = self.option("format")
if fmt not in Exporter.ACCEPTED_FORMATS:
raise ValueError("Invalid export format: {}".format(fmt))
raise ValueError(f"Invalid export format: {fmt}")
output = self.option("output")
......
......@@ -58,7 +58,7 @@ The <c1>init</c1> command creates a basic <comment>pyproject.toml</> file in the
"""
def __init__(self) -> None:
super(InitCommand, self).__init__()
super().__init__()
self._pool = None
......@@ -99,19 +99,19 @@ The <c1>init</c1> command creates a basic <comment>pyproject.toml</> file in the
name = Path.cwd().name.lower()
question = self.create_question(
"Package name [<comment>{}</comment>]: ".format(name), default=name
f"Package name [<comment>{name}</comment>]: ", default=name
)
name = self.ask(question)
version = "0.1.0"
question = self.create_question(
"Version [<comment>{}</comment>]: ".format(version), default=version
f"Version [<comment>{version}</comment>]: ", default=version
)
version = self.ask(question)
description = self.option("description") or ""
question = self.create_question(
"Description [<comment>{}</comment>]: ".format(description),
f"Description [<comment>{description}</comment>]: ",
default=description,
)
description = self.ask(question)
......@@ -121,10 +121,10 @@ The <c1>init</c1> command creates a basic <comment>pyproject.toml</> file in the
author = vcs_config["user.name"]
author_email = vcs_config.get("user.email")
if author_email:
author += " <{}>".format(author_email)
author += f" <{author_email}>"
question = self.create_question(
"Author [<comment>{}</comment>, n to skip]: ".format(author), default=author
f"Author [<comment>{author}</comment>, n to skip]: ", default=author
)
question.set_validator(lambda v: self._validate_author(v, author))
author = self.ask(question)
......@@ -137,7 +137,7 @@ The <c1>init</c1> command creates a basic <comment>pyproject.toml</> file in the
license = self.option("license") or ""
question = self.create_question(
"License [<comment>{}</comment>]: ".format(license), default=license
f"License [<comment>{license}</comment>]: ", default=license
)
question.set_validator(self._validate_license)
license = self.ask(question)
......@@ -252,7 +252,7 @@ The <c1>init</c1> command creates a basic <comment>pyproject.toml</> file in the
or "path" in constraint
or "version" in constraint
):
self.line("Adding <info>{}</info>".format(package))
self.line(f"Adding <info>{package}</info>")
requires.append(constraint)
package = self.ask("\nAdd a package:")
continue
......@@ -344,9 +344,7 @@ The <c1>init</c1> command creates a basic <comment>pyproject.toml</> file in the
requirement["version"] = version
requirement["name"] = name
self.line(
"Using version <b>{}</b> for <c1>{}</c1>".format(version, name)
)
self.line(f"Using version <b>{version}</b> for <c1>{name}</c1>")
else:
# check that the specified version/constraint exists
# before we proceed
......@@ -379,9 +377,7 @@ The <c1>init</c1> command creates a basic <comment>pyproject.toml</> file in the
if not package:
# TODO: find similar
raise ValueError(
"Could not find a matching version of package {}".format(name)
)
raise ValueError(f"Could not find a matching version of package {name}")
return package.pretty_name, selector.find_recommended_require_version(package)
......
......@@ -12,10 +12,10 @@ class InstallerCommand(EnvCommand):
def __init__(self) -> None:
self._installer: Optional["Installer"] = None
super(InstallerCommand, self).__init__()
super().__init__()
def reset_poetry(self) -> None:
super(InstallerCommand, self).reset_poetry()
super().reset_poetry()
self._installer.set_package(self.poetry.package)
self._installer.set_locker(self.poetry.locker)
......
......@@ -60,7 +60,7 @@ class NewCommand(Command):
author = config["user.name"]
author_email = config.get("user.email")
if author_email:
author += " <{}>".format(author_email)
author += f" <{author_email}>"
current_env = SystemEnv(Path(sys.executable))
default_python = "^{}".format(
......
......@@ -193,7 +193,7 @@ You can specify a package in the following forms:
"<c2>pyproject.toml</c2> file and will be skipped:\n"
)
for name in existing_packages:
self.line(" • <c1>{name}</c1>".format(name=name))
self.line(f" • <c1>{name}</c1>")
self.line(
"\nIf you want to update it to the latest compatible version, "
......
......@@ -17,11 +17,11 @@ class SearchCommand(Command):
for result in results:
self.line("")
name = "<info>{}</>".format(result.name)
name = f"<info>{result.name}</>"
name += " (<comment>{}</>)".format(result.version)
name += f" (<comment>{result.version}</>)"
self.line(name)
if result.description:
self.line(" {}".format(result.description))
self.line(f" {result.description}")
......@@ -130,7 +130,7 @@ class SelfUpdateCommand(Command):
self.line("You are using the latest version")
return 0
self.line("Updating <c1>Poetry</c1> to <c2>{}</c2>".format(release.version))
self.line(f"Updating <c1>Poetry</c1> to <c2>{release.version}</c2>")
self.line("")
self.update(release)
......
......@@ -31,7 +31,7 @@ If one doesn't exist yet, it will be created.
return
self.line("Spawning shell within <info>{}</>".format(self.env.path))
self.line(f"Spawning shell within <info>{self.env.path}</>")
# Setting this to avoid spawning unnecessary nested shells
environ["POETRY_ACTIVE"] = "1"
......
......@@ -173,7 +173,7 @@ lists all packages available."""
break
if not pkg:
raise ValueError("Package {} not found".format(package))
raise ValueError(f"Package {package} not found")
if self.option("tree"):
self.display_package_tree(self.io, pkg, locked_repo)
......@@ -188,9 +188,9 @@ lists all packages available."""
required_by[locked.pretty_name] = dependencies[pkg.name]
rows = [
["<info>name</>", " : <c1>{}</>".format(pkg.pretty_name)],
["<info>version</>", " : <b>{}</b>".format(pkg.pretty_version)],
["<info>description</>", " : {}".format(pkg.description)],
["<info>name</>", f" : <c1>{pkg.pretty_name}</>"],
["<info>version</>", f" : <b>{pkg.pretty_version}</b>"],
["<info>description</>", f" : {pkg.description}"],
]
table.add_rows(rows)
......@@ -210,9 +210,7 @@ lists all packages available."""
self.line("")
self.line("<info>required by</info>")
for parent, requires_version in required_by.items():
self.line(
" - <c1>{}</c1> <b>{}</b>".format(parent, requires_version)
)
self.line(f" - <c1>{parent}</c1> <b>{requires_version}</b>")
return 0
......@@ -351,12 +349,12 @@ lists all packages available."""
def display_package_tree(
self, io: "IO", package: "Package", installed_repo: "Repository"
) -> None:
io.write("<c1>{}</c1>".format(package.pretty_name))
io.write(f"<c1>{package.pretty_name}</c1>")
description = ""
if package.description:
description = " " + package.description
io.write_line(" <b>{}</b>{}".format(package.pretty_version, description))
io.write_line(f" <b>{package.pretty_version}</b>{description}")
dependencies = package.requires
dependencies = sorted(dependencies, key=lambda x: x.name)
......@@ -481,7 +479,7 @@ lists all packages available."""
name = package.name
selector = VersionSelector(self.poetry.pool)
return selector.find_best_candidate(name, ">={}".format(package.pretty_version))
return selector.find_best_candidate(name, f">={package.pretty_version}")
def get_update_status(self, latest: "Package", package: "Package") -> str:
from poetry.core.semver.helpers import parse_constraint
......
......@@ -41,15 +41,15 @@ class SourceShowCommand(Command):
table = self.table(style="compact")
rows = [
["<info>name</>", " : <c1>{}</>".format(source.name)],
["<info>url</>", " : {}".format(source.url)],
["<info>name</>", f" : <c1>{source.name}</>"],
["<info>url</>", f" : {source.url}"],
[
"<info>default</>",
" : {}".format(bool_string.get(source.default, False)),
f" : {bool_string.get(source.default, False)}",
],
[
"<info>secondary</>",
" : {}".format(bool_string.get(source.secondary, False)),
f" : {bool_string.get(source.secondary, False)}",
],
]
table.add_rows(rows)
......
......@@ -55,7 +55,7 @@ patch, minor, major, prepatch, preminor, premajor, prerelease.
)
if self.option("short"):
self.line("{}".format(version))
self.line(f"{version}")
else:
self.line(
"Bumping version from <b>{}</> to <fg=green>{}</>".format(
......@@ -70,7 +70,7 @@ patch, minor, major, prepatch, preminor, premajor, prerelease.
self.poetry.file.write(content)
else:
if self.option("short"):
self.line("{}".format(self.poetry.package.pretty_version))
self.line(f"{self.poetry.package.pretty_version}")
else:
self.line(
"<comment>{}</> <info>{}</>".format(
......
import logging
class Formatter(object):
class Formatter:
def format(self, record: logging.LogRecord) -> str:
raise NotImplementedError()
......@@ -26,8 +26,8 @@ class IOFormatter(logging.Formatter):
if record.name in FORMATTERS:
msg = FORMATTERS[record.name].format(msg)
elif level in self._colors:
msg = "<{}>{}</>".format(self._colors[level], msg)
msg = f"<{self._colors[level]}>{msg}</>"
return msg
return super(IOFormatter, self).format(record)
return super().format(record)
......@@ -13,7 +13,7 @@ class IOHandler(logging.Handler):
def __init__(self, io: "IO") -> None:
self._io = io
super(IOHandler, self).__init__()
super().__init__()
def emit(self, record: "LogRecord") -> None:
try:
......
......@@ -36,7 +36,7 @@ class Factory(BaseFactory):
if io is None:
io = NullIO()
base_poetry = super(Factory, self).create_poetry(cwd)
base_poetry = super().create_poetry(cwd)
locker = Locker(
base_poetry.file.parent / "poetry.lock", base_poetry.local_config
......@@ -49,9 +49,7 @@ class Factory(BaseFactory):
local_config_file = TOMLFile(base_poetry.file.parent / "poetry.toml")
if local_config_file.exists():
if io.is_debug():
io.write_line(
"Loading configuration file {}".format(local_config_file.path)
)
io.write_line(f"Loading configuration file {local_config_file.path}")
config.merge(local_config_file.read())
......
......@@ -44,9 +44,7 @@ class PackageInfoError(ValueError):
def __init__(
self, path: Union[Path, str], *reasons: Union[BaseException, str]
) -> None:
reasons = (
"Unable to determine package info for path: {}".format(str(path)),
) + reasons
reasons = (f"Unable to determine package info for path: {str(path)}",) + reasons
super().__init__("\n\n".join(str(msg).strip() for msg in reasons if msg))
......
......@@ -12,7 +12,7 @@ class Install(Operation):
def __init__(
self, package: "Package", reason: Optional[str] = None, priority: int = 0
) -> None:
super(Install, self).__init__(reason, priority=priority)
super().__init__(reason, priority=priority)
self._package = package
......
......@@ -6,7 +6,7 @@ if TYPE_CHECKING:
from poetry.core.packages.package import Package
class Operation(object):
class Operation:
def __init__(self, reason: Optional[str] = None, priority: int = 0) -> None:
self._reason = reason
......
......@@ -15,7 +15,7 @@ class Uninstall(Operation):
reason: Optional[str] = None,
priority: int = float("inf"),
) -> None:
super(Uninstall, self).__init__(reason, priority=priority)
super().__init__(reason, priority=priority)
self._package = package
......
......@@ -19,7 +19,7 @@ class Update(Operation):
self._initial_package = initial
self._target_package = target
super(Update, self).__init__(reason, priority=priority)
super().__init__(reason, priority=priority)
@property
def initial_package(self) -> "Package":
......
......@@ -131,7 +131,7 @@ class Layout:
else:
poetry_content.remove("license")
poetry_content["readme"] = "README.{}".format(self._readme_format)
poetry_content["readme"] = f"README.{self._readme_format}"
packages = self.get_package_include()
if packages:
poetry_content["packages"].append(packages)
......@@ -182,7 +182,7 @@ class Layout:
package_init.touch()
def _create_readme(self, path: "Path") -> "Path":
readme_file = path.joinpath("README.{}".format(self._readme_format))
readme_file = path.joinpath(f"README.{self._readme_format}")
readme_file.touch()
return readme_file
......
......@@ -39,7 +39,7 @@ WINDOWS_CMD_TEMPLATE = """\
class EditableBuilder(Builder):
def __init__(self, poetry: "Poetry", env: "Env", io: "IO") -> None:
super(EditableBuilder, self).__init__(poetry)
super().__init__(poetry)
self._env = env
self._io = io
......@@ -75,7 +75,7 @@ class EditableBuilder(Builder):
self._add_dist_info(added_files)
def _run_build_script(self, build_script: Path) -> None:
self._debug(" - Executing build script: <b>{}</b>".format(build_script))
self._debug(f" - Executing build script: <b>{build_script}</b>")
self._env.run("python", str(self._path.joinpath(build_script)), call=True)
def _setup_build(self) -> None:
......@@ -249,7 +249,7 @@ class EditableBuilder(Builder):
for path in added_files:
hash = self._get_file_hash(path)
size = path.stat().st_size
f.write("{},sha256={},{}\n".format(str(path), hash, size))
f.write(f"{str(path)},sha256={hash},{size}\n")
# RECORD itself is recorded with no hash or size
f.write("{},,\n".format(dist_info.joinpath("RECORD")))
......
......@@ -69,7 +69,7 @@ class _Writer:
padding = (
0
if not self._line_numbers
else len("({}) ".format(list(self._line_numbers.values())[-1]))
else len(f"({list(self._line_numbers.values())[-1]}) ")
)
last_was_empty = False
......
......@@ -134,7 +134,7 @@ class Incompatibility:
assert self._terms[0].is_positive()
cause: PythonCause = self._cause
text = "{} requires ".format(self._terse(self._terms[0], allow_every=True))
text = f"{self._terse(self._terms[0], allow_every=True)} requires "
text += f"Python {cause.python_version}"
return text
......@@ -143,7 +143,7 @@ class Incompatibility:
assert self._terms[0].is_positive()
cause: PlatformCause = self._cause
text = "{} requires ".format(self._terse(self._terms[0], allow_every=True))
text = f"{self._terse(self._terms[0], allow_every=True)} requires "
text += f"platform {cause.platform}"
return text
......@@ -158,7 +158,7 @@ class Incompatibility:
assert len(self._terms) == 1
assert self._terms[0].is_positive()
return "{} doesn't exist".format(self._terms[0].dependency.name)
return f"{self._terms[0].dependency.name} doesn't exist"
elif isinstance(self._cause, RootCause):
assert len(self._terms) == 1
assert not self._terms[0].is_positive()
......@@ -258,7 +258,7 @@ class Incompatibility:
if this_line is not None:
buffer.append(" " + str(this_line))
buffer.append(" and {}".format(str(other)))
buffer.append(f" and {str(other)}")
if other_line is not None:
buffer.append(" " + str(other_line))
......@@ -368,7 +368,7 @@ class Incompatibility:
verb = "requires"
buffer.append(
"{} {} ".format(self._terse(prior_positives[0], allow_every=True), verb)
f"{self._terse(prior_positives[0], allow_every=True)} {verb} "
)
buffer.append(self._terse(prior_negative))
......@@ -474,4 +474,4 @@ class Incompatibility:
return found
def __repr__(self) -> str:
return "<Incompatibility {}>".format(str(self))
return f"<Incompatibility {str(self)}>"
......@@ -165,4 +165,4 @@ class Term:
return "{}{}".format("not " if not self.is_positive() else "", self._dependency)
def __repr__(self) -> str:
return "<Term {}>".format(str(self))
return f"<Term {str(self)}>"
......@@ -477,7 +477,7 @@ class Locker:
# We expect the locker to be able to read lock files
# from the same semantic versioning range
accepted_versions = parse_constraint(
"^{}".format(Version.from_parts(current_version.major, 0))
f"^{Version.from_parts(current_version.major, 0)}"
)
lock_version_allowed = accepted_versions.allows(lock_version)
if lock_version_allowed and current_version < lock_version:
......
......@@ -30,7 +30,7 @@ class Poetry(BasePoetry):
):
from poetry.repositories.pool import Pool
super(Poetry, self).__init__(file, local_config, package)
super().__init__(file, local_config, package)
self._locker = locker
self._config = config
......
......@@ -587,9 +587,7 @@ class Provider:
continue
if len(by_constraint) == 1:
self.debug(
"<debug>Merging requirements for {}</debug>".format(str(deps[0]))
)
self.debug(f"<debug>Merging requirements for {str(deps[0])}</debug>")
dependencies.append(list(by_constraint.values())[0][0])
continue
......@@ -728,7 +726,7 @@ class Provider:
m2 = re.match(r"(.+?) \((.+?)\)", m.group(1))
if m2:
name = m2.group(1)
version = " (<c2>{}</c2>)".format(m2.group(2))
version = f" (<c2>{m2.group(2)}</c2>)"
else:
name = m.group(1)
version = ""
......@@ -772,7 +770,7 @@ class Provider:
m2 = re.match(r"(.+?) \((.+?)\)", m.group(1))
if m2:
name = m2.group(1)
version = " (<c2>{}</c2>)".format(m2.group(2))
version = f" (<c2>{m2.group(2)}</c2>)"
else:
name = m.group(1)
version = ""
......@@ -795,7 +793,7 @@ class Provider:
debug_info = (
"\n".join(
[
"<debug>{}:</debug> {}".format(str(depth).rjust(4), s)
f"<debug>{str(depth).rjust(4)}:</debug> {s}"
for s in debug_info.split("\n")
]
)
......
......@@ -248,7 +248,7 @@ class LegacyRepository(PyPiRepository):
key = dependency.name
if not constraint.is_any():
key = "{}:{}".format(key, str(constraint))
key = f"{key}:{str(constraint)}"
ignored_pre_release_versions = []
......
......@@ -110,7 +110,7 @@ class PyPiRepository(RemoteRepository):
info = self.get_package_info(dependency.name)
except PackageNotFound:
self._log(
"No packages found for {} {}".format(dependency.name, str(constraint)),
f"No packages found for {dependency.name} {str(constraint)}",
level="debug",
)
return []
......
......@@ -274,8 +274,8 @@ class SitePackages:
str, self._candidates if not writable_only else self.writable_candidates
)
)
for distribution in metadata.PathDistribution.discover(name=name, path=path):
yield distribution
yield from metadata.PathDistribution.discover(name=name, path=path)
def find_distribution(
self, name: str, writable_only: bool = False
......@@ -373,7 +373,7 @@ class SitePackages:
if results:
return results
raise OSError("Unable to access any of {}".format(paths_csv(candidates)))
raise OSError(f"Unable to access any of {paths_csv(candidates)}")
def write_text(self, path: Union[str, Path], *args: Any, **kwargs: Any) -> Path:
return self._path_method_wrapper(path, "write_text", *args, **kwargs)[0]
......@@ -902,9 +902,7 @@ class EnvManager:
return self.get_system_env()
io.write_line(
"Creating virtualenv <c1>{}</> in {}".format(name, str(venv_path))
)
io.write_line(f"Creating virtualenv <c1>{name}</> in {str(venv_path)}")
else:
create_venv = False
if force:
......@@ -914,9 +912,7 @@ class EnvManager:
env.path
)
)
io.write_line(
"Recreating virtualenv <c1>{}</> in {}".format(name, str(venv))
)
io.write_line(f"Recreating virtualenv <c1>{name}</> in {str(venv)}")
self.remove_venv(venv)
create_venv = True
elif io.is_very_verbose():
......@@ -1144,11 +1140,9 @@ class Env:
def find_executables(self) -> None:
python_executables = sorted(
[
p.name
for p in self._bin_dir.glob("python*")
if re.match(r"python(?:\d+(?:\.\d+)?)?(?:\.exe)?$", p.name)
]
p.name
for p in self._bin_dir.glob("python*")
if re.match(r"python(?:\d+(?:\.\d+)?)?(?:\.exe)?$", p.name)
)
if python_executables:
executable = python_executables[0]
......@@ -1158,11 +1152,9 @@ class Env:
self._executable = executable
pip_executables = sorted(
[
p.name
for p in self._bin_dir.glob("pip*")
if re.match(r"pip(?:\d+(?:\.\d+)?)?(?:\.exe)?$", p.name)
]
p.name
for p in self._bin_dir.glob("pip*")
if re.match(r"pip(?:\d+(?:\.\d+)?)?(?:\.exe)?$", p.name)
)
if pip_executables:
pip_executable = pip_executables[0]
......@@ -1173,7 +1165,7 @@ class Env:
def get_embedded_wheel(self, distribution):
return get_embed_wheel(
distribution, "{}.{}".format(self.version_info[0], self.version_info[1])
distribution, f"{self.version_info[0]}.{self.version_info[1]}"
).path
@property
......@@ -1554,7 +1546,7 @@ class VirtualEnv(Env):
def get_version_info(self) -> Tuple[int]:
output = self.run_python_script(GET_PYTHON_VERSION)
return tuple([int(s) for s in output.strip().split(".")])
return tuple(int(s) for s in output.strip().split("."))
def get_python_implementation(self) -> str:
return self.marker_env["platform_python_implementation"]
......@@ -1680,10 +1672,10 @@ class GenericEnv(VirtualEnv):
minor_version = "{}.{}".format(
self._child_env.version_info[0], self._child_env.version_info[1]
)
major_version = "{}".format(self._child_env.version_info[0])
major_version = f"{self._child_env.version_info[0]}"
patterns = [
("python{}".format(minor_version), "pip{}".format(minor_version)),
("python{}".format(major_version), "pip{}".format(major_version)),
(f"python{minor_version}", f"pip{minor_version}"),
(f"python{major_version}", f"pip{major_version}"),
]
python_executable = None
......@@ -1695,11 +1687,9 @@ class GenericEnv(VirtualEnv):
if not python_executable:
python_executables = sorted(
[
p.name
for p in self._bin_dir.glob(python_pattern)
if re.match(r"python(?:\d+(?:\.\d+)?)?(?:\.exe)?$", p.name)
]
p.name
for p in self._bin_dir.glob(python_pattern)
if re.match(r"python(?:\d+(?:\.\d+)?)?(?:\.exe)?$", p.name)
)
if python_executables:
......@@ -1711,11 +1701,9 @@ class GenericEnv(VirtualEnv):
if not pip_executable:
pip_executables = sorted(
[
p.name
for p in self._bin_dir.glob(pip_pattern)
if re.match(r"pip(?:\d+(?:\.\d+)?)?(?:\.exe)?$", p.name)
]
p.name
for p in self._bin_dir.glob(pip_pattern)
if re.match(r"pip(?:\d+(?:\.\d+)?)?(?:\.exe)?$", p.name)
)
if pip_executables:
pip_executable = pip_executables[0]
......
......@@ -120,7 +120,7 @@ def get_package_version_display_string(
def paths_csv(paths: List[Path]) -> str:
return ", ".join('"{}"'.format(str(c)) for c in paths)
return ", ".join(f'"{str(c)}"' for c in paths)
def is_dir_writable(path: Path, create: bool = False) -> bool:
......
......@@ -88,7 +88,7 @@ class KeyRing:
try:
import keyring
except Exception as e:
logger.debug("An error occurred while importing keyring: {}".format(str(e)))
logger.debug(f"An error occurred while importing keyring: {str(e)}")
self._is_available = False
return
......
......@@ -80,9 +80,7 @@ class Shell:
activate_script = self._get_activate_script()
bin_dir = "Scripts" if WINDOWS else "bin"
activate_path = env.path / bin_dir / activate_script
c.sendline(
"{} {}".format(self._get_source_command(), shlex.quote(str(activate_path)))
)
c.sendline(f"{self._get_source_command()} {shlex.quote(str(activate_path))}")
def resize(sig: Any, data: Any) -> None:
terminal = Terminal()
......
......@@ -15,7 +15,7 @@ def get_boolean_options(config=None):
yield k
if isinstance(v, dict):
for suboption in get_boolean_options(v):
yield "{}.{}".format(k, suboption)
yield f"{k}.{suboption}"
@pytest.mark.parametrize(
......
......@@ -39,19 +39,19 @@ class Config(BaseConfig):
self.merge(self._config_source.config)
self.merge(self._auth_config_source.config)
return super(Config, self).get(setting_name, default=default)
return super().get(setting_name, default=default)
def raw(self) -> Dict[str, Any]:
self.merge(self._config_source.config)
self.merge(self._auth_config_source.config)
return super(Config, self).raw()
return super().raw()
def all(self) -> Dict[str, Any]:
self.merge(self._config_source.config)
self.merge(self._auth_config_source.config)
return super(Config, self).all()
return super().all()
class DummyBackend(KeyringBackend):
......@@ -308,7 +308,7 @@ def project_factory(tmp_dir, config, repo, installed, default_python):
poetry_lock_content=None,
install_deps=True,
):
project_dir = workspace / "poetry-fixture-{}".format(name)
project_dir = workspace / f"poetry-fixture-{name}"
dependencies = dependencies or {}
dev_dependencies = dev_dependencies or {}
......
......@@ -33,7 +33,7 @@ def venvs_in_cache_dirs(
):
directories = []
for version in python_versions:
directory = venv_cache.joinpath("{}-py{}".format(venv_name, version))
directory = venv_cache.joinpath(f"{venv_name}-py{version}")
directory.mkdir(parents=True, exist_ok=True)
directories.append(directory.name)
return directories
......
......@@ -17,7 +17,7 @@ def check_output_wrapper(version=VERSION_3_7_1):
if "sys.version_info[:3]" in cmd:
return version.text
elif "sys.version_info[:2]" in cmd:
return "{}.{}".format(version.major, version.minor)
return f"{version.major}.{version.minor}"
else:
return str(Path("/prefix"))
......
......@@ -20,11 +20,9 @@ def test_remove_by_python_version(
tester.execute("3.6")
assert check_output.called
assert not (venv_cache / "{}-py3.6".format(venv_name)).exists()
assert not (venv_cache / f"{venv_name}-py3.6").exists()
expected = "Deleted virtualenv: {}\n".format(
(venv_cache / "{}-py3.6".format(venv_name))
)
expected = "Deleted virtualenv: {}\n".format(venv_cache / f"{venv_name}-py3.6")
assert expected == tester.io.fetch_output()
......@@ -36,7 +34,7 @@ def test_remove_by_name(tester, venvs_in_cache_dirs, venv_name, venv_cache):
assert not (venv_cache / name).exists()
expected += "Deleted virtualenv: {}\n".format((venv_cache / name))
expected += f"Deleted virtualenv: {venv_cache / name}\n"
assert expected == tester.io.fetch_output()
......@@ -46,16 +44,16 @@ def test_remove_all(tester, venvs_in_cache_dirs, venv_name, venv_cache):
tester.execute("--all")
for name in venvs_in_cache_dirs:
assert not (venv_cache / name).exists()
expected.add("Deleted virtualenv: {}".format((venv_cache / name)))
expected.add(f"Deleted virtualenv: {venv_cache / name}")
assert expected == set(tester.io.fetch_output().split("\n"))
def test_remove_all_and_version(tester, venvs_in_cache_dirs, venv_name, venv_cache):
expected = {""}
tester.execute("--all {}".format(venvs_in_cache_dirs[0]))
tester.execute(f"--all {venvs_in_cache_dirs[0]}")
for name in venvs_in_cache_dirs:
assert not (venv_cache / name).exists()
expected.add("Deleted virtualenv: {}".format((venv_cache / name)))
expected.add(f"Deleted virtualenv: {venv_cache / name}")
assert expected == set(tester.io.fetch_output().split("\n"))
......@@ -66,7 +64,7 @@ def test_remove_multiple(tester, venvs_in_cache_dirs, venv_name, venv_cache):
tester.execute(" ".join(removed_envs))
for name in removed_envs:
assert not (venv_cache / name).exists()
expected.add("Deleted virtualenv: {}".format((venv_cache / name)))
expected.add(f"Deleted virtualenv: {venv_cache / name}")
for name in remaining_envs:
assert (venv_cache / name).exists()
assert expected == set(tester.io.fetch_output().split("\n"))
......@@ -50,7 +50,7 @@ def test_activate_activates_non_existing_virtualenv_no_envs_file(
tester.execute("3.7")
venv_py37 = venv_cache / "{}-py3.7".format(venv_name)
venv_py37 = venv_cache / f"{venv_name}-py3.7"
mock_build_env.assert_called_with(
venv_py37,
executable="python3.7",
......@@ -85,7 +85,7 @@ def test_get_prefers_explicitly_activated_virtualenvs_over_env_var(
python_minor = ".".join(str(v) for v in current_python[:2])
python_patch = ".".join(str(v) for v in current_python[:3])
venv_dir = venv_cache / "{}-py{}".format(venv_name, python_minor)
venv_dir = venv_cache / f"{venv_name}-py{python_minor}"
venv_dir.mkdir(parents=True, exist_ok=True)
envs_file = TOMLFile(venv_cache / "envs.toml")
......@@ -110,7 +110,7 @@ def test_get_prefers_explicitly_activated_non_existing_virtualenvs_over_env_var(
os.environ["VIRTUAL_ENV"] = "/environment/prefix"
python_minor = ".".join(str(v) for v in current_python[:2])
venv_dir = venv_cache / "{}-py{}".format(venv_name, python_minor)
venv_dir = venv_cache / f"{venv_name}-py{python_minor}"
mocker.patch(
"poetry.utils.env.EnvManager._env",
......
......@@ -348,7 +348,7 @@ def test_add_directory_with_poetry(app, repo, tester, mocker):
repo.add_package(get_package("pendulum", "1.4.4"))
path = "../git/github.com/demo/pyproject-demo"
tester.execute("{}".format(path))
tester.execute(f"{path}")
expected = """\
......@@ -376,7 +376,7 @@ def test_add_file_constraint_wheel(app, repo, tester, mocker, poetry):
repo.add_package(get_package("pendulum", "1.4.4"))
path = "../distributions/demo-0.1.0-py2.py3-none-any.whl"
tester.execute("{}".format(path))
tester.execute(f"{path}")
expected = """\
......@@ -411,7 +411,7 @@ def test_add_file_constraint_sdist(app, repo, tester, mocker):
repo.add_package(get_package("pendulum", "1.4.4"))
path = "../distributions/demo-0.1.0.tar.gz"
tester.execute("{}".format(path))
tester.execute(f"{path}")
expected = """\
......@@ -586,7 +586,7 @@ def test_add_constraint_with_platform(app, repo, tester, env):
repo.add_package(get_package("cachy", "0.1.0"))
repo.add_package(cachy2)
tester.execute("cachy=0.2.0 --platform {} -vvv".format(platform))
tester.execute(f"cachy=0.2.0 --platform {platform} -vvv")
expected = """\
......@@ -1144,7 +1144,7 @@ def test_add_directory_constraint_old_installer(
repo.add_package(get_package("cleo", "0.6.5"))
path = "../git/github.com/demo/demo"
old_tester.execute("{}".format(path))
old_tester.execute(f"{path}")
expected = """\
......@@ -1180,7 +1180,7 @@ def test_add_directory_with_poetry_old_installer(
repo.add_package(get_package("pendulum", "1.4.4"))
path = "../git/github.com/demo/pyproject-demo"
old_tester.execute("{}".format(path))
old_tester.execute(f"{path}")
expected = """\
......@@ -1211,7 +1211,7 @@ def test_add_file_constraint_wheel_old_installer(
repo.add_package(get_package("pendulum", "1.4.4"))
path = "../distributions/demo-0.1.0-py2.py3-none-any.whl"
old_tester.execute("{}".format(path))
old_tester.execute(f"{path}")
expected = """\
......@@ -1249,7 +1249,7 @@ def test_add_file_constraint_sdist_old_installer(
repo.add_package(get_package("pendulum", "1.4.4"))
path = "../distributions/demo-0.1.0.tar.gz"
old_tester.execute("{}".format(path))
old_tester.execute(f"{path}")
expected = """\
......@@ -1435,7 +1435,7 @@ def test_add_constraint_with_platform_old_installer(
repo.add_package(get_package("cachy", "0.1.0"))
repo.add_package(cachy2)
old_tester.execute("cachy=0.2.0 --platform {} -vvv".format(platform))
old_tester.execute(f"cachy=0.2.0 --platform {platform} -vvv")
expected = """\
......
......@@ -16,12 +16,12 @@ def repository_cache_dir(monkeypatch, tmpdir):
@pytest.fixture
def repository_one():
return "01_{}".format(uuid.uuid4())
return f"01_{uuid.uuid4()}"
@pytest.fixture
def repository_two():
return "02_{}".format(uuid.uuid4())
return f"02_{uuid.uuid4()}"
@pytest.fixture
......
......@@ -660,9 +660,7 @@ line-length = 88
"""
pyproject_file.write_text(decode(existing_section))
tester.execute(inputs=init_basic_inputs)
assert (
"{}\n{}".format(existing_section, init_basic_toml) in pyproject_file.read_text()
)
assert f"{existing_section}\n{init_basic_toml}" in pyproject_file.read_text()
def test_init_non_interactive_existing_pyproject_add_dependency(
......@@ -698,7 +696,7 @@ packages = [{include = "my_package"}]
python = "^3.6"
foo = "^1.19.2"
"""
assert "{}\n{}".format(existing_section, expected) in pyproject_file.read_text()
assert f"{existing_section}\n{expected}" in pyproject_file.read_text()
def test_init_existing_pyproject_with_build_system_fails(
......@@ -716,4 +714,4 @@ build-backend = "setuptools.build_meta"
tester.io.fetch_output().strip()
== "A pyproject.toml file with a defined build-system already exists."
)
assert "{}".format(existing_section) in pyproject_file.read_text()
assert f"{existing_section}" in pyproject_file.read_text()
......@@ -148,7 +148,7 @@ def test_command_new_with_readme(fmt, tester, tmp_dir):
fmt = "md"
package = "package"
path = Path(tmp_dir) / package
options = ["--readme {}".format(fmt) if fmt else "md", path.as_posix()]
options = [f"--readme {fmt}" if fmt else "md", path.as_posix()]
tester.execute(" ".join(options))
poetry = verify_project_directory(path, package, package, None)
......
......@@ -98,7 +98,7 @@ def mock_download(url, dest, **__):
class TestExecutor(Executor):
def __init__(self, *args, **kwargs):
super(TestExecutor, self).__init__(*args, **kwargs)
super().__init__(*args, **kwargs)
self._installs = []
self._updates = []
......@@ -117,10 +117,10 @@ class TestExecutor(Executor):
return self._uninstalls
def _do_execute_operation(self, operation):
super(TestExecutor, self)._do_execute_operation(operation)
super()._do_execute_operation(operation)
if not operation.skipped:
getattr(self, "_{}s".format(operation.job_type)).append(operation.package)
getattr(self, f"_{operation.job_type}s").append(operation.package)
def _execute_install(self, operation):
return 0
......@@ -134,7 +134,7 @@ class TestExecutor(Executor):
class PoetryTestApplication(Application):
def __init__(self, poetry):
super(PoetryTestApplication, self).__init__()
super().__init__()
self._poetry = poetry
def reset_poetry(self):
......@@ -178,7 +178,7 @@ class TestLocker(Locker):
def _write_lock_data(self, data):
if self._write:
super(TestLocker, self)._write_lock_data(data)
super()._write_lock_data(data)
self._locked = True
return
......@@ -187,9 +187,9 @@ class TestLocker(Locker):
class TestRepository(Repository):
def find_packages(self, dependency):
packages = super(TestRepository, self).find_packages(dependency)
packages = super().find_packages(dependency)
if len(packages) == 0:
raise PackageNotFound("Package [{}] not found.".format(dependency.name))
raise PackageNotFound(f"Package [{dependency.name}] not found.")
return packages
......
......@@ -44,7 +44,7 @@ class Installer(BaseInstaller):
class Executor(BaseExecutor):
def __init__(self, *args, **kwargs):
super(Executor, self).__init__(*args, **kwargs)
super().__init__(*args, **kwargs)
self._installs = []
self._updates = []
......@@ -63,10 +63,10 @@ class Executor(BaseExecutor):
return self._uninstalls
def _do_execute_operation(self, operation):
super(Executor, self)._do_execute_operation(operation)
super()._do_execute_operation(operation)
if not operation.skipped:
getattr(self, "_{}s".format(operation.job_type)).append(operation.package)
getattr(self, f"_{operation.job_type}s").append(operation.package)
def _execute_install(self, operation):
return 0
......@@ -180,7 +180,7 @@ def installer(package, pool, locker, env, installed, config):
def fixture(name):
file = TOMLFile(Path(__file__).parent / "fixtures" / "{}.test".format(name))
file = TOMLFile(Path(__file__).parent / "fixtures" / f"{name}.test")
return json.loads(json.dumps(file.read()))
......
......@@ -124,7 +124,7 @@ def installer(package, pool, locker, env, installed, config):
def fixture(name):
file = TOMLFile(Path(__file__).parent / "fixtures" / "{}.test".format(name))
file = TOMLFile(Path(__file__).parent / "fixtures" / f"{name}.test")
return file.read()
......
......@@ -69,7 +69,7 @@ def test_requirement_source_type_url():
)
result = installer.requirement(foo, formatted=True)
expected = "{}#egg={}".format(foo.source_url, foo.name)
expected = f"{foo.source_url}#egg={foo.name}"
assert expected == result
......
......@@ -24,9 +24,7 @@ class MockRepository(LegacyRepository):
FIXTURES = Path(__file__).parent / "fixtures" / "legacy"
def __init__(self):
super(MockRepository, self).__init__(
"legacy", url="http://legacy.foo.bar", disable_cache=True
)
super().__init__("legacy", url="http://legacy.foo.bar", disable_cache=True)
def _get_page(self, endpoint):
parts = endpoint.split("/")
......@@ -110,7 +108,7 @@ def test_get_package_information_skips_dependencies_with_invalid_constraints():
assert 25 == len(package.requires)
assert sorted(
[r for r in package.requires if not r.is_optional()], key=lambda r: r.name
(r for r in package.requires if not r.is_optional()), key=lambda r: r.name
) == [
Dependency("configparser", "*"),
Dependency("future", ">=0.14.0"),
......@@ -323,9 +321,7 @@ def test_get_package_retrieves_packages_with_no_hashes():
class MockHttpRepository(LegacyRepository):
def __init__(self, endpoint_responses, http):
base_url = "http://legacy.foo.bar"
super(MockHttpRepository, self).__init__(
"legacy", url=base_url, disable_cache=True
)
super().__init__("legacy", url=base_url, disable_cache=True)
for endpoint, response in endpoint_responses.items():
url = base_url + endpoint
......
......@@ -21,9 +21,7 @@ class MockRepository(PyPiRepository):
DIST_FIXTURES = Path(__file__).parent / "fixtures" / "pypi.org" / "dists"
def __init__(self, fallback=False):
super(MockRepository, self).__init__(
url="http://foo.bar", disable_cache=True, fallback=fallback
)
super().__init__(url="http://foo.bar", disable_cache=True, fallback=fallback)
def _get(self, url):
parts = url.split("/")[1:]
......@@ -111,7 +109,7 @@ def test_fallback_on_downloading_packages():
assert package.name == "jupyter"
assert len(package.requires) == 6
dependency_names = sorted([dep.name for dep in package.requires])
dependency_names = sorted(dep.name for dep in package.requires)
assert dependency_names == [
"ipykernel",
"ipywidgets",
......@@ -165,7 +163,7 @@ def test_pypi_repository_supports_reading_bz2_files():
assert package.name == "twisted"
assert 71 == len(package.requires)
assert sorted(
[r for r in package.requires if not r.is_optional()], key=lambda r: r.name
(r for r in package.requires if not r.is_optional()), key=lambda r: r.name
) == [
Dependency("attrs", ">=17.4.0"),
Dependency("Automat", ">=0.3.0"),
......
......@@ -61,9 +61,9 @@ def _maintain_symlinks(symlink_type, base_path):
try:
# Try the cache first because going from git checkout to sdist is the
# only time we know that we're going to cache correctly
with open(SYMLINK_CACHE, "r") as f:
with open(SYMLINK_CACHE) as f:
symlink_data = json.load(f)
except (IOError, OSError) as e:
except OSError as e:
# IOError on py2, OSError on py3. Both have errno
if e.errno == 2:
# SYMLINKS_CACHE doesn't exist. Fallback to trying to create the
......@@ -137,7 +137,7 @@ class SDistCommand(SDist):
def read_file(file_name):
"""Read file and return its contents."""
with open(file_name, "r") as f:
with open(file_name) as f:
return f.read()
......
......@@ -5,10 +5,10 @@ from collections import OrderedDict
from setuptools import setup
with io.open("README.rst", "rt", encoding="utf8") as f:
with open("README.rst", encoding="utf8") as f:
readme = f.read()
with io.open("flask/__init__.py", "rt", encoding="utf8") as f:
with open("flask/__init__.py", encoding="utf8") as f:
version = re.search(r"__version__ = \'(.*?)\'", f.read()).group(1)
setup(
......
......@@ -18,7 +18,7 @@ AUTHOR_EMAIL = "xi@resolvent.net"
LICENSE = "MIT"
PLATFORMS = "Any"
URL = "http://pyyaml.org/wiki/PyYAML"
DOWNLOAD_URL = "http://pyyaml.org/download/pyyaml/%s-%s.tar.gz" % (NAME, VERSION)
DOWNLOAD_URL = f"http://pyyaml.org/download/pyyaml/{NAME}-{VERSION}.tar.gz"
CLASSIFIERS = [
"Development Status :: 5 - Production/Stable",
"Intended Audience :: Developers",
......@@ -185,7 +185,7 @@ class build_ext(_build_ext):
filenames.append(filename)
base = os.path.splitext(filename)[0]
for ext in ["c", "h", "pyx", "pxd"]:
filename = "%s.%s" % (base, ext)
filename = f"{base}.{ext}"
if filename not in filenames and os.path.isfile(filename):
filenames.append(filename)
return filenames
......
......@@ -171,7 +171,7 @@ def test_authenticator_falls_back_to_keyring_netloc(
@pytest.mark.filterwarnings("ignore::pytest.PytestUnhandledThreadExceptionWarning")
def test_authenticator_request_retries_on_exception(mocker, config, http):
sleep = mocker.patch("time.sleep")
sdist_uri = "https://foo.bar/files/{}/foo-0.1.0.tar.gz".format(str(uuid.uuid4()))
sdist_uri = f"https://foo.bar/files/{str(uuid.uuid4())}/foo-0.1.0.tar.gz"
content = str(uuid.uuid4())
seen = []
......@@ -194,7 +194,7 @@ def test_authenticator_request_raises_exception_when_attempts_exhausted(
mocker, config, http
):
sleep = mocker.patch("time.sleep")
sdist_uri = "https://foo.bar/files/{}/foo-0.1.0.tar.gz".format(str(uuid.uuid4()))
sdist_uri = f"https://foo.bar/files/{str(uuid.uuid4())}/foo-0.1.0.tar.gz"
def callback(*_, **__):
raise requests.exceptions.ConnectionError(str(uuid.uuid4()))
......@@ -216,7 +216,7 @@ def test_authenticator_request_retries_on_status_code(
mocker, config, http, status, attempts
):
sleep = mocker.patch("time.sleep")
sdist_uri = "https://foo.bar/files/{}/foo-0.1.0.tar.gz".format(str(uuid.uuid4()))
sdist_uri = f"https://foo.bar/files/{str(uuid.uuid4())}/foo-0.1.0.tar.gz"
content = str(uuid.uuid4())
def callback(request, uri, response_headers):
......
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment