Commit b753aaf4 by ThatXliner Committed by GitHub

Used pyupgrade to remove compatibility code (#3861)

* Used pyupgrade to remove compatibility code

May fix #3860
parent 45a9b8f2
from __future__ import absolute_import
import os
import re
......@@ -27,7 +25,7 @@ def boolean_normalizer(val: str) -> bool:
return val in ["true", "1"]
class Config(object):
class Config:
default_config = {
"cache-dir": str(CACHE_DIR),
......
from typing import Any
class ConfigSource(object):
class ConfigSource:
def add_property(self, key: str, value: Any) -> None:
raise NotImplementedError()
......
......@@ -88,7 +88,7 @@ if TYPE_CHECKING:
class Application(BaseApplication):
def __init__(self) -> None:
super(Application, self).__init__("poetry", __version__)
super().__init__("poetry", __version__)
self._poetry = None
self._io: Optional[IO] = None
......@@ -132,7 +132,7 @@ class Application(BaseApplication):
output: Optional[Output] = None,
error_output: Optional[Output] = None,
) -> IO:
io = super(Application, self).create_io(input, output, error_output)
io = super().create_io(input, output, error_output)
# Set our own CLI styles
formatter = io.output.formatter
......@@ -265,7 +265,7 @@ class Application(BaseApplication):
env = env_manager.create_venv(io)
if env.is_venv() and io.is_verbose():
io.write_line("Using virtualenv: <comment>{}</>".format(env.path))
io.write_line(f"Using virtualenv: <comment>{env.path}</>")
command.set_env(env)
......
......@@ -47,9 +47,7 @@ class PackageInfoError(ValueError):
reasons = (
"Unable to determine package info for path: {}".format(str(path)),
) + reasons
super(PackageInfoError, self).__init__(
"\n\n".join(str(msg).strip() for msg in reasons if msg)
)
super().__init__("\n\n".join(str(msg).strip() for msg in reasons if msg))
class PackageInfo:
......@@ -119,7 +117,7 @@ class PackageInfo:
@classmethod
def _log(cls, msg: str, level: str = "info") -> None:
"""Internal helper method to log information."""
getattr(logger, level)("<debug>{}:</debug> {}".format(cls.__name__, msg))
getattr(logger, level)(f"<debug>{cls.__name__}:</debug> {msg}")
def to_package(
self,
......@@ -139,9 +137,7 @@ class PackageInfo:
if not self.version:
# The version could not be determined, so we raise an error since it is mandatory.
raise RuntimeError(
"Unable to retrieve the package version for {}".format(name)
)
raise RuntimeError(f"Unable to retrieve the package version for {name}")
package = Package(
name=name,
......@@ -329,7 +325,7 @@ class PackageInfo:
requires += "\n"
for extra_name, deps in result["extras_require"].items():
requires += "[{}]\n".format(extra_name)
requires += f"[{extra_name}]\n"
for dep in deps:
requires += dep + "\n"
......@@ -462,7 +458,7 @@ class PackageInfo:
"install",
"--disable-pip-version-check",
"--ignore-installed",
*PEP517_META_BUILD_DEPS
*PEP517_META_BUILD_DEPS,
)
venv.run(
"python",
......@@ -475,7 +471,7 @@ class PackageInfo:
except EnvCommandError as e:
# something went wrong while attempting pep517 metadata build
# fallback to egg_info if setup.py available
cls._log("PEP517 build failed: {}".format(e), level="debug")
cls._log(f"PEP517 build failed: {e}", level="debug")
setup_py = path / "setup.py"
if not setup_py.exists():
raise PackageInfoError(
......@@ -497,9 +493,7 @@ class PackageInfo:
os.chdir(cwd.as_posix())
if info:
cls._log(
"Falling back to parsed setup.py file for {}".format(path), "debug"
)
cls._log(f"Falling back to parsed setup.py file for {path}", "debug")
return info
# if we reach here, everything has failed and all hope is lost
......
......@@ -24,7 +24,7 @@ if TYPE_CHECKING:
logger = logging.getLogger()
class Authenticator(object):
class Authenticator:
def __init__(self, config: "Config", io: Optional["IO"] = None) -> None:
self._config = config
self._io = io
......@@ -92,9 +92,7 @@ class Authenticator(object):
if not is_last_attempt:
attempt += 1
delay = 0.5 * attempt
self._log(
"Retrying HTTP request in {} seconds.".format(delay), level="debug"
)
self._log(f"Retrying HTTP request in {delay} seconds.", level="debug")
time.sleep(delay)
continue
......@@ -141,9 +139,7 @@ class Authenticator(object):
credentials = (None, None)
for repository_name in self._config.get("repositories", []):
repository_config = self._config.get(
"repositories.{}".format(repository_name)
)
repository_config = self._config.get(f"repositories.{repository_name}")
if not repository_config:
continue
......
......@@ -80,7 +80,7 @@ class Chef:
archive_types = ["whl", "tar.gz", "tar.bz2", "bz2", "zip"]
links = []
for archive_type in archive_types:
for archive in cache_dir.glob("*.{}".format(archive_type)):
for archive in cache_dir.glob(f"*.{archive_type}"):
links.append(Link(archive.as_uri()))
return links
......
......@@ -17,11 +17,11 @@ class InvalidWheelName(Exception):
pass
class Wheel(object):
class Wheel:
def __init__(self, filename: str) -> None:
wheel_info = wheel_file_re.match(filename)
if not wheel_info:
raise InvalidWheelName("{} is not a valid wheel filename.".format(filename))
raise InvalidWheelName(f"{filename} is not a valid wheel filename.")
self.filename = filename
self.name = wheel_info.group("name").replace("_", "-")
......@@ -70,16 +70,12 @@ class Chooser:
links.append(link)
if not links:
raise RuntimeError(
"Unable to find installation candidates for {}".format(package)
)
raise RuntimeError(f"Unable to find installation candidates for {package}")
# Get the best link
chosen = max(links, key=lambda link: self._sort_key(package, link))
if not chosen:
raise RuntimeError(
"Unable to find installation candidates for {}".format(package)
)
raise RuntimeError(f"Unable to find installation candidates for {package}")
return chosen
......
# -*- coding: utf-8 -*-
from __future__ import division
import itertools
import os
import threading
......@@ -44,7 +41,7 @@ if TYPE_CHECKING:
from .operations import OperationTypes
class Executor(object):
class Executor:
def __init__(
self,
env: "Env",
......@@ -296,7 +293,7 @@ class Executor(object):
return 0
result = getattr(self, "_execute_{}".format(method))(operation)
result = getattr(self, f"_execute_{method}")(operation)
if result != 0:
return result
......@@ -431,9 +428,7 @@ class Executor(object):
"" if updates == 1 else "s",
uninstalls,
"" if uninstalls == 1 else "s",
", <info>{}</> skipped".format(skipped)
if skipped and self._verbose
else "",
f", <info>{skipped}</> skipped" if skipped and self._verbose else "",
)
)
self._io.write_line("")
......@@ -638,7 +633,7 @@ class Executor(object):
archive_hash = "sha256:" + FileDependency(package.name, archive).hash()
if archive_hash not in {f["hash"] for f in package.files}:
raise RuntimeError(
"Invalid hash for {} using archive {}".format(package, archive.name)
f"Invalid hash for {package} using archive {archive.name}"
)
return archive
......
......@@ -200,7 +200,7 @@ class Installer:
# Checking extras
for extra in self._extras:
if extra not in self._package.extras:
raise ValueError("Extra [{}] is not specified.".format(extra))
raise ValueError(f"Extra [{extra}] is not specified.")
locked_repository = self._locker.locked_repository(True)
solver = Solver(
......@@ -237,7 +237,7 @@ class Installer:
# Checking extras
for extra in self._extras:
if extra not in self._package.extras:
raise ValueError("Extra [{}] is not specified.".format(extra))
raise ValueError(f"Extra [{extra}] is not specified.")
self._io.write_line("<info>Updating dependencies</>")
solver = Solver(
......@@ -267,7 +267,7 @@ class Installer:
for extra in self._extras:
if extra not in self._locker.lock_data.get("extras", {}):
raise ValueError("Extra [{}] is not specified.".format(extra))
raise ValueError(f"Extra [{extra}] is not specified.")
# If we are installing from lock
# Filter the operations by comparing it with what is
......@@ -378,7 +378,7 @@ class Installer:
"" if updates == 1 else "s",
uninstalls,
"" if uninstalls == 1 else "s",
", <info>{}</> skipped".format(skipped)
f", <info>{skipped}</> skipped"
if skipped and self.is_verbose()
else "",
)
......@@ -397,7 +397,7 @@ class Installer:
"""
method = operation.job_type
getattr(self, "_execute_{}".format(method))(operation)
getattr(self, f"_execute_{method}")(operation)
def _execute_install(self, operation: Install) -> None:
if operation.skipped:
......
......@@ -134,14 +134,14 @@ class PipInstaller(BaseInstaller):
def requirement(self, package: "Package", formatted: bool = False) -> str:
if formatted and not package.source_type:
req = "{}=={}".format(package.name, package.version)
req = f"{package.name}=={package.version}"
for f in package.files:
hash_type = "sha256"
h = f["hash"]
if ":" in h:
hash_type, h = h.split(":")
req += " --hash {}:{}".format(hash_type, h)
req += f" --hash {hash_type}:{h}"
req += "\n"
......@@ -169,14 +169,12 @@ class PipInstaller(BaseInstaller):
return req
if package.source_type == "url":
return "{}#egg={}".format(package.source_url, package.name)
return f"{package.source_url}#egg={package.name}"
return "{}=={}".format(package.name, package.version)
return f"{package.name}=={package.version}"
def create_temporary_requirement(self, package: "Package") -> str:
fd, name = tempfile.mkstemp(
"reqs.txt", "{}-{}".format(package.name, package.version)
)
fd, name = tempfile.mkstemp("reqs.txt", f"{package.name}-{package.version}")
try:
os.write(fd, encode(self.requirement(package, formatted=True)))
......
import json
import os
from io import open
from typing import List
import jsonschema
......@@ -16,10 +15,10 @@ class ValidationError(ValueError):
def validate_object(obj: dict, schema_name: str) -> List[str]:
schema = os.path.join(SCHEMA_DIR, "{}.json".format(schema_name))
schema = os.path.join(SCHEMA_DIR, f"{schema_name}.json")
if not os.path.exists(schema):
raise ValueError("Schema {} does not exist.".format(schema_name))
raise ValueError(f"Schema {schema_name} does not exist.")
with open(schema, encoding="utf-8") as f:
schema = json.loads(f.read())
......
......@@ -14,7 +14,7 @@ if TYPE_CHECKING:
from poetry.core.pyproject.toml import PyProjectTOML
TESTS_DEFAULT = u"""from {package_name} import __version__
TESTS_DEFAULT = """from {package_name} import __version__
def test_version():
......@@ -51,7 +51,7 @@ BUILD_SYSTEM_MIN_VERSION = "1.0.0"
BUILD_SYSTEM_MAX_VERSION: Optional[str] = None
class Layout(object):
class Layout:
def __init__(
self,
project: str,
......@@ -146,7 +146,7 @@ class Layout(object):
def _create_tests(self, path: "Path") -> None:
tests = path / "tests"
tests_init = tests / "__init__.py"
tests_default = tests / "test_{}.py".format(self._package_name)
tests_default = tests / f"test_{self._package_name}.py"
tests.mkdir()
tests_init.touch(exist_ok=False)
......
# -*- coding: utf-8 -*-
from typing import TYPE_CHECKING
from .layout import Layout
......@@ -8,7 +6,7 @@ from .layout import Layout
if TYPE_CHECKING:
from pathlib import Path
DEFAULT = u"""__version__ = '{version}'
DEFAULT = """__version__ = '{version}'
"""
......
# -*- coding: utf-8 -*-
from typing import TYPE_CHECKING
from .layout import Layout
......@@ -7,7 +5,7 @@ from .layout import Layout
if TYPE_CHECKING:
from pathlib import Path
DEFAULT = u"""__version__ = '{version}'
DEFAULT = """__version__ = '{version}'
"""
......
......@@ -25,7 +25,7 @@ class Assignment(Term):
index: int,
cause: Optional["Incompatibility"] = None,
) -> None:
super(Assignment, self).__init__(dependency, is_positive)
super().__init__(dependency, is_positive)
self._decision_level = decision_level
self._index = index
......
......@@ -65,9 +65,7 @@ class _Writer:
if isinstance(self._root.cause, ConflictCause):
self._visit(self._root, {})
else:
self._write(
self._root, "Because {}, version solving failed.".format(self._root)
)
self._write(self._root, f"Because {self._root}, version solving failed.")
padding = (
0
......@@ -89,7 +87,7 @@ class _Writer:
number = line[-1]
if number is not None:
message = "({})".format(number).ljust(padding) + message
message = f"({number})".ljust(padding) + message
else:
message = " " * padding + message
......@@ -165,7 +163,7 @@ class _Writer:
self._visit(second, details_for_cause)
self._write(
incompatibility,
"Thus, {}.".format(incompatibility_string),
f"Thus, {incompatibility_string}.",
numbered=numbered,
)
else:
......
......@@ -105,11 +105,9 @@ class Incompatibility:
"""
if isinstance(self._cause, ConflictCause):
cause: ConflictCause = self._cause
for incompatibility in cause.conflict.external_incompatibilities:
yield incompatibility
yield from cause.conflict.external_incompatibilities
for incompatibility in cause.other.external_incompatibilities:
yield incompatibility
yield from cause.other.external_incompatibilities
else:
yield self
......@@ -136,7 +134,7 @@ class Incompatibility:
cause: PythonCause = self._cause
text = "{} requires ".format(self._terse(self._terms[0], allow_every=True))
text += "Python {}".format(cause.python_version)
text += f"Python {cause.python_version}"
return text
elif isinstance(self._cause, PlatformCause):
......@@ -145,7 +143,7 @@ class Incompatibility:
cause: PlatformCause = self._cause
text = "{} requires ".format(self._terse(self._terms[0], allow_every=True))
text += "platform {}".format(cause.platform)
text += f"platform {cause.platform}"
return text
elif isinstance(self._cause, NoVersionsCause):
......@@ -201,7 +199,7 @@ class Incompatibility:
else self._terse(term2)
)
return "{} is incompatible with {}".format(package1, package2)
return f"{package1} is incompatible with {package2}"
else:
return "either {} or {}".format(
self._terse(term1), self._terse(term2)
......@@ -305,14 +303,14 @@ class Incompatibility:
else:
buffer.append("requires")
buffer.append(" both {}".format(this_negatives))
buffer.append(f" both {this_negatives}")
if this_line is not None:
buffer.append(" ({})".format(this_line))
buffer.append(f" ({this_line})")
buffer.append(" and {}".format(other_negatives))
buffer.append(f" and {other_negatives}")
if other_line is not None:
buffer.append(" ({})".format(other_line))
buffer.append(f" ({other_line})")
return "".join(buffer)
......@@ -361,7 +359,7 @@ class Incompatibility:
buffer = []
if len(prior_positives) > 1:
prior_string = " or ".join([self._terse(term) for term in prior_positives])
buffer.append("if {} then ".format(prior_string))
buffer.append(f"if {prior_string} then ")
else:
if isinstance(prior.cause, DependencyCause):
verb = "depends on"
......@@ -374,7 +372,7 @@ class Incompatibility:
buffer.append(self._terse(prior_negative))
if prior_line is not None:
buffer.append(" ({})".format(prior_line))
buffer.append(f" ({prior_line})")
buffer.append(" which ")
......@@ -390,7 +388,7 @@ class Incompatibility:
)
if latter_line is not None:
buffer.append(" ({})".format(latter_line))
buffer.append(f" ({latter_line})")
return "".join(buffer)
......@@ -423,7 +421,7 @@ class Incompatibility:
buffer = []
if len(positives) > 1:
prior_string = " or ".join([self._terse(term) for term in positives])
buffer.append("if {} then ".format(prior_string))
buffer.append(f"if {prior_string} then ")
else:
buffer.append(self._terse(positives[0], allow_every=True))
if isinstance(prior.cause, DependencyCause):
......@@ -433,11 +431,11 @@ class Incompatibility:
buffer.append(self._terse(latter.terms[0]) + " ")
if prior_line is not None:
buffer.append("({}) ".format(prior_line))
buffer.append(f"({prior_line}) ")
if isinstance(latter.cause, PythonCause):
cause: PythonCause = latter.cause
buffer.append("which requires Python {}".format(cause.python_version))
buffer.append(f"which requires Python {cause.python_version}")
elif isinstance(latter.cause, NoVersionsCause):
buffer.append("which doesn't match any versions")
elif isinstance(latter.cause, PackageNotFoundCause):
......@@ -446,13 +444,13 @@ class Incompatibility:
buffer.append("which is forbidden")
if latter_line is not None:
buffer.append(" ({})".format(latter_line))
buffer.append(f" ({latter_line})")
return "".join(buffer)
def _terse(self, term: Term, allow_every: bool = False) -> str:
if allow_every and term.constraint.is_any():
return "every version of {}".format(term.dependency.complete_name)
return f"every version of {term.dependency.complete_name}"
if term.dependency.is_root:
return term.dependency.pretty_name
......
......@@ -199,7 +199,7 @@ class PartialSolution:
if assigned_term.satisfies(term):
return assignment
raise RuntimeError("[BUG] {} is not satisfied.".format(term))
raise RuntimeError(f"[BUG] {term} is not satisfied.")
def satisfies(self, term: Term) -> bool:
return self.relation(term) == SetRelation.SUBSET
......
......@@ -10,7 +10,7 @@ if TYPE_CHECKING:
from poetry.core.semver.helpers import VersionTypes
class Term(object):
class Term:
"""
A statement about a package which is true or false for a given selection of
package versions.
......@@ -52,9 +52,7 @@ class Term(object):
allowed by this term and another.
"""
if self.dependency.complete_name != other.dependency.complete_name:
raise ValueError(
"{} should refer to {}".format(other, self.dependency.complete_name)
)
raise ValueError(f"{other} should refer to {self.dependency.complete_name}")
other_constraint = other.constraint
......@@ -116,9 +114,7 @@ class Term(object):
allowed by both this term and another
"""
if self.dependency.complete_name != other.dependency.complete_name:
raise ValueError(
"{} should refer to {}".format(other, self.dependency.complete_name)
)
raise ValueError(f"{other} should refer to {self.dependency.complete_name}")
if self._compatible_dependency(other.dependency):
if self.is_positive() != other.is_positive():
......
......@@ -193,7 +193,7 @@ class VersionSolver:
.. _conflict resolution: https://github.com/dart-lang/pub/tree/master/doc/solver.md#conflict-resolution
"""
self._log("conflict: {}".format(incompatibility))
self._log(f"conflict: {incompatibility}")
new_incompatibility = False
while not incompatibility.is_failure():
......@@ -308,10 +308,8 @@ class VersionSolver:
bang, most_recent_term, partially, most_recent_satisfier
)
)
self._log(
'{} which is caused by "{}"'.format(bang, most_recent_satisfier.cause)
)
self._log("{} thus: {}".format(bang, incompatibility))
self._log(f'{bang} which is caused by "{most_recent_satisfier.cause}"')
self._log(f"{bang} thus: {incompatibility}")
raise SolveFailure(incompatibility)
......@@ -429,7 +427,7 @@ class VersionSolver:
)
def _add_incompatibility(self, incompatibility: Incompatibility) -> None:
self._log("fact: {}".format(incompatibility))
self._log(f"fact: {incompatibility}")
for term in incompatibility.terms:
if term.dependency.complete_name not in self._incompatibilities:
......
......@@ -6,7 +6,7 @@ from poetry.core.packages.dependency import Dependency
from poetry.core.packages.package import Package
class DependencyPackage(object):
class DependencyPackage:
def __init__(self, dependency: Dependency, package: Package) -> None:
self._dependency = dependency
self._package = package
......@@ -33,7 +33,7 @@ class DependencyPackage(object):
def __setattr__(self, key: str, value: Any) -> None:
if key in {"_dependency", "_package"}:
return super(DependencyPackage, self).__setattr__(key, value)
return super().__setattr__(key, value)
setattr(self._package, key, value)
......
......@@ -43,7 +43,7 @@ if TYPE_CHECKING:
logger = logging.getLogger(__name__)
class Locker(object):
class Locker:
_VERSION = "1.1"
......@@ -471,7 +471,7 @@ class Locker(object):
try:
lock_data = self._lock.read()
except TOMLKitError as e:
raise RuntimeError("Unable to read the lock file ({}).".format(e))
raise RuntimeError(f"Unable to read the lock file ({e}).")
lock_version = Version.parse(lock_data["metadata"].get("lock-version", "1.0"))
current_version = Version.parse(self._VERSION)
......
......@@ -21,7 +21,7 @@ class PackageCollection(list):
if packages is None:
packages = []
super(PackageCollection, self).__init__()
super().__init__()
for package in packages:
self.append(package)
......@@ -32,4 +32,4 @@ class PackageCollection(list):
package = DependencyPackage(self._dependency, package)
return super(PackageCollection, self).append(package)
return super().append(package)
class BasePlugin(object):
class BasePlugin:
"""
Base class for all plugin types
"""
......
......@@ -11,7 +11,7 @@ from .plugin import Plugin
logger = logging.getLogger(__name__)
class PluginManager(object):
class PluginManager:
"""
This class registers and activates plugins.
"""
......@@ -31,7 +31,7 @@ class PluginManager(object):
self._load_plugin_entrypoint(entrypoint)
def get_plugin_entry_points(self) -> List[entrypoints.EntryPoint]:
return entrypoints.get_group_all("poetry.{}".format(self._type))
return entrypoints.get_group_all(f"poetry.{self._type}")
def add_plugin(self, plugin): # type: (Plugin) -> None
if not isinstance(plugin, (Plugin, ApplicationPlugin)):
......@@ -48,7 +48,7 @@ class PluginManager(object):
def _load_plugin_entrypoint(
self, entrypoint
): # type: (entrypoints.EntryPoint) -> None
logger.debug("Loading the {} plugin".format(entrypoint.name))
logger.debug(f"Loading the {entrypoint.name} plugin")
plugin = entrypoint.load()
......
......@@ -52,17 +52,15 @@ class Publisher:
repository_name = "pypi"
else:
# Retrieving config information
url = self._poetry.config.get("repositories.{}.url".format(repository_name))
url = self._poetry.config.get(f"repositories.{repository_name}.url")
if url is None:
raise RuntimeError(
"Repository {} is not defined".format(repository_name)
)
raise RuntimeError(f"Repository {repository_name} is not defined")
if not (username and password):
# Check if we have a token first
token = self._password_manager.get_pypi_token(repository_name)
if token:
logger.debug("Found an API token for {}.".format(repository_name))
logger.debug(f"Found an API token for {repository_name}.")
username = "__token__"
password = token
else:
......
......@@ -39,8 +39,8 @@ _has_blake2 = hasattr(hashlib, "blake2b")
class UploadError(Exception):
def __init__(self, error: Union[ConnectionError, HTTPError, str]) -> None:
if isinstance(error, HTTPError):
message = "HTTP Error {}: {}".format(
error.response.status_code, error.response.reason
message = (
f"HTTP Error {error.response.status_code}: {error.response.reason}"
)
elif isinstance(error, ConnectionError):
message = (
......@@ -49,7 +49,7 @@ class UploadError(Exception):
)
else:
message = str(error)
super(UploadError, self).__init__(message)
super().__init__(message)
class Uploader:
......@@ -82,14 +82,10 @@ class Uploader:
wheels = list(
dist.glob(
"{}-{}-*.whl".format(
escape_name(self._package.pretty_name), escape_version(version)
)
f"{escape_name(self._package.pretty_name)}-{escape_version(version)}-*.whl"
)
)
tars = list(
dist.glob("{}-{}.tar.gz".format(self._package.pretty_name, version))
)
tars = list(dist.glob(f"{self._package.pretty_name}-{version}.tar.gz"))
return sorted(wheels + tars)
......@@ -263,9 +259,7 @@ class Uploader:
)
encoder = MultipartEncoder(data_to_send)
bar = ProgressBar(self._io, max=encoder.len)
bar.set_format(
" - Uploading <c1>{0}</c1> <b>%percent%%</b>".format(file.name)
)
bar.set_format(f" - Uploading <c1>{file.name}</c1> <b>%percent%%</b>")
monitor = MultipartEncoderMonitor(
encoder, lambda monitor: bar.set_progress(monitor.bytes_read)
)
......@@ -284,17 +278,13 @@ class Uploader:
)
if dry_run or 200 <= resp.status_code < 300:
bar.set_format(
" - Uploading <c1>{0}</c1> <fg=green>%percent%%</>".format(
file.name
)
f" - Uploading <c1>{file.name}</c1> <fg=green>%percent%%</>"
)
bar.finish()
elif resp.status_code == 301:
if self._io.output.is_decorated():
self._io.overwrite(
" - Uploading <c1>{0}</c1> <error>{1}</>".format(
file.name, "FAILED"
)
f" - Uploading <c1>{file.name}</c1> <error>FAILED</>"
)
raise UploadError(
"Redirects are not supported. "
......@@ -303,9 +293,7 @@ class Uploader:
except (requests.ConnectionError, requests.HTTPError) as e:
if self._io.output.is_decorated():
self._io.overwrite(
" - Uploading <c1>{0}</c1> <error>{1}</>".format(
file.name, "FAILED"
)
f" - Uploading <c1>{file.name}</c1> <error>FAILED</>"
)
raise UploadError(e)
finally:
......@@ -318,12 +306,13 @@ class Uploader:
Register a package to a repository.
"""
dist = self._poetry.file.parent / "dist"
file = dist / "{}-{}.tar.gz".format(
self._package.name, normalize_version(self._package.version.text)
file = (
dist
/ f"{self._package.name}-{normalize_version(self._package.version.text)}.tar.gz"
)
if not file.exists():
raise RuntimeError('"{0}" does not exist.'.format(file.name))
raise RuntimeError(f'"{file.name}" does not exist.')
data = self.post_data(file)
data.update({":action": "submit", "protocol_version": "1"})
......
......@@ -6,7 +6,7 @@ class SolverProblemError(Exception):
def __init__(self, error: Exception) -> None:
self._error = error
super(SolverProblemError, self).__init__(str(error))
super().__init__(str(error))
@property
def error(self) -> Exception:
......
......@@ -49,7 +49,7 @@ class Indicator(ProgressIndicator):
def _formatter_elapsed(self) -> str:
elapsed = time.time() - self._start_time
return "{:.1f}s".format(elapsed)
return f"{elapsed:.1f}s"
class Provider:
......@@ -199,7 +199,7 @@ class Provider:
name: Optional[str] = None,
) -> Package:
if vcs != "git":
raise ValueError("Unsupported VCS dependency {}".format(vcs))
raise ValueError(f"Unsupported VCS dependency {vcs}")
tmp_dir = Path(
mkdtemp(prefix="pypoetry-git-{}".format(url.split("/")[-1].rstrip(".git")))
......@@ -266,7 +266,7 @@ class Provider:
)
except PackageInfoError:
raise RuntimeError(
"Unable to determine package info from path: {}".format(file_path)
f"Unable to determine package info from path: {file_path}"
)
return package
......@@ -546,7 +546,7 @@ class Provider:
dependencies.append(deps[0])
continue
self.debug("<debug>Duplicate dependencies for {}</debug>".format(dep_name))
self.debug(f"<debug>Duplicate dependencies for {dep_name}</debug>")
# Regrouping by constraint
by_constraint = dict()
......
......@@ -85,9 +85,7 @@ class Solver:
)
)
self._provider.debug(
"Resolved with overrides: {}".format(
", ".join("({})".format(b) for b in self._overrides)
)
f"Resolved with overrides: {', '.join(f'({b})' for b in self._overrides)}"
)
operations = []
......@@ -221,7 +219,7 @@ class Solver:
for override in overrides:
self._provider.debug(
"<comment>Retrying dependency resolution "
"with the following overrides ({}).</comment>".format(override)
f"with the following overrides ({override}).</comment>"
)
self._provider.set_overrides(override)
_packages, _depths = self._solve(use_latest=use_latest)
......@@ -293,7 +291,7 @@ class Solver:
return final_packages, depths
class DFSNode(object):
class DFSNode:
def __init__(self, id: Tuple[str, str, bool], name: str, base_name: str) -> None:
self.id = id
self.name = name
......@@ -408,7 +406,7 @@ class PackageNode(DFSNode):
self.category = dep.category
self.optional = dep.is_optional()
super(PackageNode, self).__init__(
super().__init__(
(package.complete_name, self.category, self.optional),
package.complete_name,
package.name,
......
......@@ -8,7 +8,7 @@ if TYPE_CHECKING:
from poetry.core.packages.package import Package
class BaseRepository(object):
class BaseRepository:
def __init__(self) -> None:
self._packages = []
......
......@@ -330,7 +330,7 @@ class LegacyRepository(PyPiRepository):
return self._packages[index]
except ValueError:
package = super(LegacyRepository, self).package(name, version, extras)
package = super().package(name, version, extras)
package._source_type = "legacy"
package._source_url = self._url
package._source_reference = self.name
......@@ -347,7 +347,7 @@ class LegacyRepository(PyPiRepository):
def _get_release_info(self, name: str, version: str) -> dict:
page = self._get("/{}/".format(canonicalize_name(name).replace(".", "-")))
if page is None:
raise PackageNotFound('No package named "{}"'.format(name))
raise PackageNotFound(f'No package named "{name}"')
data = PackageInfo(
name=name,
......@@ -377,7 +377,7 @@ class LegacyRepository(PyPiRepository):
):
urls["sdist"].append(link.url)
file_hash = "{}:{}".format(link.hash_name, link.hash) if link.hash else None
file_hash = f"{link.hash_name}:{link.hash}" if link.hash else None
if not link.hash or (
link.hash_name not in ("sha256", "sha384", "sha512")
......@@ -425,7 +425,7 @@ class LegacyRepository(PyPiRepository):
response = self.session.get(url)
if response.status_code in (401, 403):
self._log(
"Authorization error accessing {url}".format(url=url),
f"Authorization error accessing {url}",
level="warning",
)
return
......
......@@ -32,7 +32,7 @@ class Pool(BaseRepository):
self._ignore_repository_names = ignore_repository_names
super(Pool, self).__init__()
super().__init__()
@property
def repositories(self) -> List[Repository]:
......@@ -53,7 +53,7 @@ class Pool(BaseRepository):
if name in self._lookup:
return self._repositories[self._lookup[name]]
raise ValueError('Repository "{}" does not exist.'.format(name))
raise ValueError(f'Repository "{name}" does not exist.')
def add_repository(
self, repository: Repository, default: bool = False, secondary: bool = False
......@@ -125,7 +125,7 @@ class Pool(BaseRepository):
and repository not in self._lookup
and not self._ignore_repository_names
):
raise ValueError('Repository "{}" does not exist.'.format(repository))
raise ValueError(f'Repository "{repository}" does not exist.')
if repository is not None and not self._ignore_repository_names:
try:
......@@ -144,7 +144,7 @@ class Pool(BaseRepository):
return package
raise PackageNotFound("Package {} ({}) not found.".format(name, version))
raise PackageNotFound(f"Package {name} ({version}) not found.")
def find_packages(self, dependency: "Dependency") -> List["Package"]:
repository = dependency.source_name
......@@ -156,7 +156,7 @@ class Pool(BaseRepository):
and repository not in self._lookup
and not self._ignore_repository_names
):
raise ValueError('Repository "{}" does not exist.'.format(repository))
raise ValueError(f'Repository "{repository}" does not exist.')
if repository is not None and not self._ignore_repository_names:
return self.repository(repository).find_packages(dependency)
......
......@@ -54,7 +54,7 @@ class PyPiRepository(RemoteRepository):
disable_cache: bool = False,
fallback: bool = True,
) -> None:
super(PyPiRepository, self).__init__(url.rstrip("/") + "/simple/")
super().__init__(url.rstrip("/") + "/simple/")
self._base_url = url
self._disable_cache = disable_cache
......@@ -211,9 +211,9 @@ class PyPiRepository(RemoteRepository):
)
def _get_package_info(self, name: str) -> dict:
data = self._get("pypi/{}/json".format(name))
data = self._get(f"pypi/{name}/json")
if data is None:
raise PackageNotFound("Package [{}] not found.".format(name))
raise PackageNotFound(f"Package [{name}] not found.")
return data
......@@ -230,24 +230,24 @@ class PyPiRepository(RemoteRepository):
return PackageInfo.load(self._get_release_info(name, version))
cached = self._cache.remember_forever(
"{}:{}".format(name, version), lambda: self._get_release_info(name, version)
f"{name}:{version}", lambda: self._get_release_info(name, version)
)
cache_version = cached.get("_cache_version", "0.0.0")
if parse_constraint(cache_version) != self.CACHE_VERSION:
# The cache must be updated
self._log(
"The cache for {} {} is outdated. Refreshing.".format(name, version),
f"The cache for {name} {version} is outdated. Refreshing.",
level="debug",
)
cached = self._get_release_info(name, version)
self._cache.forever("{}:{}".format(name, version), cached)
self._cache.forever(f"{name}:{version}", cached)
return PackageInfo.load(cached)
def find_links_for_package(self, package: Package) -> List[Link]:
json_data = self._get("pypi/{}/{}/json".format(package.name, package.version))
json_data = self._get(f"pypi/{package.name}/{package.version}/json")
if json_data is None:
return []
......@@ -261,11 +261,11 @@ class PyPiRepository(RemoteRepository):
def _get_release_info(self, name: str, version: str) -> dict:
from poetry.inspection.info import PackageInfo
self._log("Getting info for {} ({}) from PyPI".format(name, version), "debug")
self._log(f"Getting info for {name} ({version}) from PyPI", "debug")
json_data = self._get("pypi/{}/{}/json".format(name, version))
json_data = self._get(f"pypi/{name}/{version}/json")
if json_data is None:
raise PackageNotFound("Package [{}] not found.".format(name))
raise PackageNotFound(f"Package [{name}] not found.")
info = json_data["info"]
......@@ -383,14 +383,14 @@ class PyPiRepository(RemoteRepository):
return info
py2_requires_dist = set(
py2_requires_dist = {
Dependency.create_from_pep_508(r).to_pep_508()
for r in info.requires_dist
)
py3_requires_dist = set(
}
py3_requires_dist = {
Dependency.create_from_pep_508(r).to_pep_508()
for r in py3_info.requires_dist
)
}
base_requires_dist = py2_requires_dist & py3_requires_dist
py2_only_requires_dist = py2_requires_dist - py3_requires_dist
py3_only_requires_dist = py3_requires_dist - py2_requires_dist
......@@ -469,4 +469,4 @@ class PyPiRepository(RemoteRepository):
return download_file(url, dest, session=self.session)
def _log(self, msg: str, level: str = "info") -> None:
getattr(logger, level)("<debug>{}:</debug> {}".format(self._name, msg))
getattr(logger, level)(f"<debug>{self._name}:</debug> {msg}")
......@@ -5,7 +5,7 @@ class RemoteRepository(Repository):
def __init__(self, url: str) -> None:
self._url = url
super(RemoteRepository, self).__init__()
super().__init__()
@property
def url(self) -> str:
......
......@@ -13,7 +13,7 @@ if TYPE_CHECKING:
class Repository(BaseRepository):
def __init__(self, packages: List["Package"] = None, name: str = None) -> None:
super(Repository, self).__init__()
super().__init__()
self._name = name
......
......@@ -46,6 +46,6 @@ def to_str(string):
def list_to_shell_command(cmd):
return " ".join(
'"{}"'.format(token) if " " in token and token[0] not in {"'", '"'} else token
f'"{token}"' if " " in token and token[0] not in {"'", '"'} else token
for token in cmd
)
......@@ -225,7 +225,7 @@ class SitePackages:
return result
else:
results.append(result)
except (IOError, OSError):
except OSError:
# TODO: Replace with PermissionError
pass
......@@ -257,7 +257,7 @@ class SitePackages:
def __getattr__(self, item: str) -> Any:
try:
return super(SitePackages, self).__getattribute__(item)
return super().__getattribute__(item)
except AttributeError:
return getattr(self.path, item)
......@@ -275,8 +275,8 @@ class EnvCommandError(EnvError):
e.cmd, e.returncode, decode(e.output)
)
if input:
message += "input was : {}".format(input)
super(EnvCommandError, self).__init__(message)
message += f"input was : {input}"
super().__init__(message)
class NoCompatiblePythonVersionFound(EnvError):
......@@ -296,10 +296,10 @@ class NoCompatiblePythonVersionFound(EnvError):
'via the "env use" command.'
)
super(NoCompatiblePythonVersionFound, self).__init__(message)
super().__init__(message)
class EnvManager(object):
class EnvManager:
"""
Environments manager
"""
......@@ -324,9 +324,9 @@ class EnvManager(object):
try:
python_version = Version.parse(python)
python = "python{}".format(python_version.major)
python = f"python{python_version.major}"
if python_version.precision > 1:
python += ".{}".format(python_version.minor)
python += f".{python_version.minor}"
except ValueError:
# Executable in PATH or full executable path
pass
......@@ -348,7 +348,7 @@ class EnvManager(object):
raise EnvCommandError(e)
python_version = Version.parse(python_version.strip())
minor = "{}.{}".format(python_version.major, python_version.minor)
minor = f"{python_version.major}.{python_version.minor}"
patch = python_version.text
create = False
......@@ -383,7 +383,7 @@ class EnvManager(object):
# We need to recreate
create = True
name = "{}-py{}".format(base_env_name, minor)
name = f"{base_env_name}-py{minor}"
venv = venv_path / name
# Create if needed
......@@ -482,7 +482,7 @@ class EnvManager(object):
else:
venv_path = Path(venv_path)
name = "{}-py{}".format(base_env_name, python_minor.strip())
name = f"{base_env_name}-py{python_minor.strip()}"
venv = venv_path / name
......@@ -513,8 +513,7 @@ class EnvManager(object):
venv_path = Path(venv_path)
env_list = [
VirtualEnv(Path(p))
for p in sorted(venv_path.glob("{}-py*".format(venv_name)))
VirtualEnv(Path(p)) for p in sorted(venv_path.glob(f"{venv_name}-py*"))
]
venv = self._poetry.file.parent / ".venv"
......@@ -566,14 +565,14 @@ class EnvManager(object):
return venv
raise ValueError(
'<warning>Environment "{}" does not exist.</warning>'.format(python)
f'<warning>Environment "{python}" does not exist.</warning>'
)
try:
python_version = Version.parse(python)
python = "python{}".format(python_version.major)
python = f"python{python_version.major}"
if python_version.precision > 1:
python += ".{}".format(python_version.minor)
python += f".{python_version.minor}"
except ValueError:
# Executable in PATH or full executable path
pass
......@@ -595,15 +594,13 @@ class EnvManager(object):
raise EnvCommandError(e)
python_version = Version.parse(python_version.strip())
minor = "{}.{}".format(python_version.major, python_version.minor)
minor = f"{python_version.major}.{python_version.minor}"
name = "{}-py{}".format(base_env_name, minor)
name = f"{base_env_name}-py{minor}"
venv = venv_path / name
if not venv.exists():
raise ValueError(
'<warning>Environment "{}" does not exist.</warning>'.format(name)
)
raise ValueError(f'<warning>Environment "{name}" does not exist.</warning>')
if envs_file.exists():
envs = envs_file.read()
......@@ -698,7 +695,7 @@ class EnvManager(object):
)
):
if len(python_to_try) == 1:
if not parse_constraint("^{}.0".format(python_to_try)).allows_any(
if not parse_constraint(f"^{python_to_try}.0").allows_any(
supported_python
):
continue
......@@ -710,7 +707,7 @@ class EnvManager(object):
python = "python" + python_to_try
if io.is_debug():
io.write_line("<debug>Trying {}</debug>".format(python))
io.write_line(f"<debug>Trying {python}</debug>")
try:
python_patch = decode(
......@@ -733,7 +730,7 @@ class EnvManager(object):
continue
if supported_python.allows(Version.parse(python_patch)):
io.write_line("Using <c1>{}</c1> ({})".format(python, python_patch))
io.write_line(f"Using <c1>{python}</c1> ({python_patch})")
executable = python
python_minor = ".".join(python_patch.split(".")[:2])
break
......@@ -747,7 +744,7 @@ class EnvManager(object):
venv = venv_path
else:
name = self.generate_env_name(name, str(cwd))
name = "{}-py{}".format(name, python_minor.strip())
name = f"{name}-py{python_minor.strip()}"
venv = venv_path / name
if not venv.exists():
......@@ -788,7 +785,7 @@ class EnvManager(object):
flags=self._poetry.config.get("virtualenvs.options"),
)
elif io.is_very_verbose():
io.write_line("Virtualenv <c1>{}</> already exists.".format(name))
io.write_line(f"Virtualenv <c1>{name}</> already exists.")
# venv detection:
# stdlib venv may symlink sys.executable, so we can't use realpath.
......@@ -846,7 +843,7 @@ class EnvManager(object):
for flag, value in flags.items():
if value is True:
args.append("--{}".format(flag))
args.append(f"--{flag}")
args.append(str(path))
......@@ -896,10 +893,10 @@ class EnvManager(object):
h = hashlib.sha256(encode(cwd)).digest()
h = base64.urlsafe_b64encode(h).decode()[:8]
return "{}-{}".format(sanitized_name, h)
return f"{sanitized_name}-{h}"
class Env(object):
class Env:
"""
An abstract Python environment.
"""
......@@ -1196,7 +1193,7 @@ class Env(object):
return other.__class__ == self.__class__ and other.path == self.path
def __repr__(self) -> str:
return '{}("{}")'.format(self.__class__.__name__, self._path)
return f'{self.__class__.__name__}("{self._path}")'
class SystemEnv(Env):
......@@ -1244,7 +1241,7 @@ class SystemEnv(Env):
# headers is not a path returned by sysconfig.get_paths()
continue
paths[key] = getattr(obj, "install_{}".format(key))
paths[key] = getattr(obj, f"install_{key}")
if site.check_enableusersite() and hasattr(obj, "install_usersite"):
paths["usersite"] = getattr(obj, "install_usersite")
......@@ -1303,7 +1300,7 @@ class VirtualEnv(Env):
"""
def __init__(self, path: Path, base: Optional[Path] = None) -> None:
super(VirtualEnv, self).__init__(path, base)
super().__init__(path, base)
# If base is None, it probably means this is
# a virtualenv created from VIRTUAL_ENV.
......@@ -1388,7 +1385,7 @@ class VirtualEnv(Env):
def _run(self, cmd: List[str], **kwargs: Any) -> Optional[int]:
kwargs["env"] = self.get_temp_environ(environ=kwargs.get("env"))
return super(VirtualEnv, self)._run(cmd, **kwargs)
return super()._run(cmd, **kwargs)
def get_temp_environ(
self,
......@@ -1415,7 +1412,7 @@ class VirtualEnv(Env):
def execute(self, bin: str, *args: str, **kwargs: Any) -> Optional[int]:
kwargs["env"] = self.get_temp_environ(environ=kwargs.get("env"))
return super(VirtualEnv, self).execute(bin, *args, **kwargs)
return super().execute(bin, *args, **kwargs)
@contextmanager
def temp_environ(self) -> Iterator[None]:
......@@ -1437,7 +1434,7 @@ class NullEnv(SystemEnv):
if path is None:
path = Path(sys.prefix)
super(NullEnv, self).__init__(path, base=base)
super().__init__(path, base=base)
self._execute = execute
self.executed = []
......@@ -1449,13 +1446,13 @@ class NullEnv(SystemEnv):
self.executed.append(cmd)
if self._execute:
return super(NullEnv, self)._run(cmd, **kwargs)
return super()._run(cmd, **kwargs)
def execute(self, bin: str, *args: str, **kwargs: Any) -> Optional[int]:
self.executed.append([bin] + list(args))
if self._execute:
return super(NullEnv, self).execute(bin, *args, **kwargs)
return super().execute(bin, *args, **kwargs)
def _bin(self, bin: str) -> str:
return bin
......@@ -1497,7 +1494,7 @@ class MockEnv(NullEnv):
supported_tags: List[Tag] = None,
**kwargs: Any,
):
super(MockEnv, self).__init__(**kwargs)
super().__init__(**kwargs)
self._version_info = version_info
self._python_implementation = python_implementation
......@@ -1524,7 +1521,7 @@ class MockEnv(NullEnv):
@property
def sys_path(self) -> List[str]:
if self._sys_path is None:
return super(MockEnv, self).sys_path
return super().sys_path
return self._sys_path
......@@ -1532,7 +1529,7 @@ class MockEnv(NullEnv):
if self._mock_marker_env is not None:
return self._mock_marker_env
marker_env = super(MockEnv, self).get_marker_env()
marker_env = super().get_marker_env()
marker_env["python_implementation"] = self._python_implementation
marker_env["version_info"] = self._version_info
marker_env["python_version"] = ".".join(str(v) for v in self._version_info[:2])
......
......@@ -12,7 +12,7 @@ from poetry.poetry import Poetry
from poetry.utils._compat import decode
class Exporter(object):
class Exporter:
"""
Exporter class to export a lock file to alternative formats.
"""
......@@ -36,7 +36,7 @@ class Exporter(object):
with_credentials: bool = False,
) -> None:
if fmt not in self.ACCEPTED_FORMATS:
raise ValueError("Invalid export format: {}".format(fmt))
raise ValueError(f"Invalid export format: {fmt}")
getattr(self, "_export_{}".format(fmt.replace(".", "_")))(
cwd,
......@@ -81,15 +81,15 @@ class Exporter(object):
line = requirement
elif is_direct_local_reference:
dependency_uri = path_to_url(dependency.source_url)
line = "{} @ {}".format(dependency.name, dependency_uri)
line = f"{dependency.name} @ {dependency_uri}"
else:
line = "{}=={}".format(package.name, package.version)
line = f"{package.name}=={package.version}"
if not is_direct_remote_reference:
if ";" in requirement:
markers = requirement.split(";", 1)[1].strip()
if markers:
line += "; {}".format(markers)
line += f"; {markers}"
if (
not is_direct_remote_reference
......@@ -109,7 +109,7 @@ class Exporter(object):
if algorithm not in self.ALLOWED_HASH_ALGORITHMS:
continue
hashes.append("{}:{}".format(algorithm, h))
hashes.append(f"{algorithm}:{h}")
if hashes:
line += " \\\n"
......@@ -143,7 +143,7 @@ class Exporter(object):
if with_credentials
else repository.url
)
indexes_header = "--index-url {}\n".format(url)
indexes_header = f"--index-url {url}\n"
continue
url = (
......@@ -151,8 +151,8 @@ class Exporter(object):
)
parsed_url = urllib.parse.urlsplit(url)
if parsed_url.scheme == "http":
indexes_header += "--trusted-host {}\n".format(parsed_url.netloc)
indexes_header += "--extra-index-url {}\n".format(url)
indexes_header += f"--trusted-host {parsed_url.netloc}\n"
indexes_header += f"--extra-index-url {url}\n"
content = indexes_header + "\n" + content
......
......@@ -51,7 +51,7 @@ def temporary_directory(*args: Any, **kwargs: Any) -> Iterator[str]:
def get_cert(config: Config, repository_name: str) -> Optional[Path]:
cert = config.get("certificates.{}.cert".format(repository_name))
cert = config.get(f"certificates.{repository_name}.cert")
if cert:
return Path(cert)
else:
......@@ -59,7 +59,7 @@ def get_cert(config: Config, repository_name: str) -> Optional[Path]:
def get_client_cert(config: Config, repository_name: str) -> Optional[Path]:
client_cert = config.get("certificates.{}.client-cert".format(repository_name))
client_cert = config.get(f"certificates.{repository_name}.client-cert")
if client_cert:
return Path(client_cert)
else:
......@@ -131,7 +131,7 @@ def is_dir_writable(path: Path, create: bool = False) -> bool:
with tempfile.TemporaryFile(dir=str(path)):
pass
except (IOError, OSError):
except OSError:
return False
else:
return True
......@@ -44,7 +44,7 @@ class KeyRing:
return keyring.get_password(name, username)
except (RuntimeError, keyring.errors.KeyringError):
raise KeyRingError(
"Unable to retrieve the password for {} from the key ring".format(name)
f"Unable to retrieve the password for {name} from the key ring"
)
def set_password(self, name: str, username: str, password: str) -> None:
......@@ -78,11 +78,11 @@ class KeyRing:
keyring.delete_password(name, username)
except (RuntimeError, keyring.errors.KeyringError):
raise KeyRingError(
"Unable to delete the password for {} from the key ring".format(name)
f"Unable to delete the password for {name} from the key ring"
)
def get_entry_name(self, name: str) -> str:
return "{}-{}".format(self._namespace, name)
return f"{self._namespace}-{name}"
def _check(self) -> None:
try:
......@@ -137,31 +137,27 @@ class PasswordManager:
def set_pypi_token(self, name: str, token: str) -> None:
if not self.keyring.is_available():
self._config.auth_config_source.add_property(
"pypi-token.{}".format(name), token
)
self._config.auth_config_source.add_property(f"pypi-token.{name}", token)
else:
self.keyring.set_password(name, "__token__", token)
def get_pypi_token(self, name: str) -> str:
if not self.keyring.is_available():
return self._config.get("pypi-token.{}".format(name))
return self._config.get(f"pypi-token.{name}")
return self.keyring.get_password(name, "__token__")
def delete_pypi_token(self, name: str) -> None:
if not self.keyring.is_available():
return self._config.auth_config_source.remove_property(
"pypi-token.{}".format(name)
)
return self._config.auth_config_source.remove_property(f"pypi-token.{name}")
self.keyring.delete_password(name, "__token__")
def get_http_auth(self, name: str) -> Optional[Dict[str, str]]:
auth = self._config.get("http-basic.{}".format(name))
auth = self._config.get(f"http-basic.{name}")
if not auth:
username = self._config.get("http-basic.{}.username".format(name))
password = self._config.get("http-basic.{}.password".format(name))
username = self._config.get(f"http-basic.{name}.username")
password = self._config.get(f"http-basic.{name}.password")
if not username and not password:
return None
else:
......@@ -182,7 +178,7 @@ class PasswordManager:
else:
self.keyring.set_password(name, username, password)
self._config.auth_config_source.add_property("http-basic.{}".format(name), auth)
self._config.auth_config_source.add_property(f"http-basic.{name}", auth)
def delete_http_password(self, name: str) -> None:
auth = self.get_http_auth(name)
......@@ -194,4 +190,4 @@ class PasswordManager:
except KeyRingError:
pass
self._config.auth_config_source.remove_property("http-basic.{}".format(name))
self._config.auth_config_source.remove_property(f"http-basic.{name}")
......@@ -13,7 +13,7 @@ from typing import Union
from poetry.core.semver.version import Version
class SetupReader(object):
class SetupReader:
"""
Class that reads a setup.py file without executing it.
"""
......
......@@ -118,4 +118,4 @@ class Shell:
return "."
def __repr__(self) -> str:
return '{}("{}", "{}")'.format(self.__class__.__name__, self._name, self._path)
return f'{self.__class__.__name__}("{self._name}", "{self._path}")'
......@@ -10,7 +10,7 @@ if TYPE_CHECKING:
from poetry.repositories import Pool
class VersionSelector(object):
class VersionSelector:
def __init__(self, pool: "Pool") -> None:
self._pool = pool
......@@ -78,6 +78,6 @@ class VersionSelector(object):
else:
version = ".".join(str(p) for p in parts)
if parsed.is_unstable():
version += "-{}".format(parsed.pre.to_string())
version += f"-{parsed.pre.to_string()}"
return "^{}".format(version)
return f"^{version}"
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