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