From 6f34b77a2a51972086ca718b2c4d9f4dd026f874 Mon Sep 17 00:00:00 2001 From: Kamyar Ghasemlou Date: Thu, 22 Apr 2021 23:56:07 +0200 Subject: [PATCH 1/4] add pyupgrade to precommit file Co-authored-by: Kamyar Ghasemlou Co-authored-by: Harry Peach --- .pre-commit-config.yaml | 6 ++++++ 1 file changed, 6 insertions(+) diff --git a/.pre-commit-config.yaml b/.pre-commit-config.yaml index 9377e9a6992..45f28baecce 100644 --- a/.pre-commit-config.yaml +++ b/.pre-commit-config.yaml @@ -28,3 +28,9 @@ repos: - id: end-of-file-fixer exclude: ^tests/.*/fixtures/.* - id: debug-statements + - repo: https://github.com/asottile/pyupgrade + rev: v2.13.0 + hooks: + - id: pyupgrade + args: + - --py36-plus From 9bb76f52d7f8b77a5a35445c0a5e8b76f12f5246 Mon Sep 17 00:00:00 2001 From: Kamyar Ghasemlou Date: Sun, 9 May 2021 00:27:34 +0200 Subject: [PATCH 2/4] pyupgrade changes Co-authored-by: Kamyar Ghasemlou Co-authored-by: Harry Peach --- get-poetry.py | 43 ++++--- install-poetry.py | 18 +-- poetry/console/commands/add.py | 3 +- poetry/console/commands/cache/clear.py | 14 +-- poetry/console/commands/cache/list.py | 2 +- poetry/console/commands/check.py | 4 +- poetry/console/commands/config.py | 26 ++--- poetry/console/commands/debug/info.py | 2 +- poetry/console/commands/debug/resolve.py | 4 +- poetry/console/commands/env/info.py | 8 +- poetry/console/commands/env/list.py | 2 +- poetry/console/commands/env/remove.py | 2 +- poetry/console/commands/env/use.py | 2 +- poetry/console/commands/env_command.py | 2 +- poetry/console/commands/export.py | 2 +- poetry/console/commands/init.py | 20 ++-- poetry/console/commands/installer_command.py | 4 +- poetry/console/commands/new.py | 2 +- poetry/console/commands/plugin/add.py | 2 +- poetry/console/commands/remove.py | 2 +- poetry/console/commands/search.py | 6 +- poetry/console/commands/self/update.py | 22 ++-- poetry/console/commands/shell.py | 2 +- poetry/console/commands/show.py | 16 +-- poetry/console/commands/source/show.py | 8 +- poetry/console/commands/version.py | 4 +- .../console/logging/formatters/formatter.py | 2 +- poetry/console/logging/io_formatter.py | 4 +- poetry/console/logging/io_handler.py | 2 +- poetry/factory.py | 7 +- poetry/inspection/info.py | 2 +- poetry/installation/operations/install.py | 2 +- poetry/installation/operations/operation.py | 2 +- poetry/installation/operations/uninstall.py | 2 +- poetry/installation/operations/update.py | 2 +- poetry/layouts/layout.py | 4 +- poetry/masonry/builders/editable.py | 8 +- poetry/mixology/failure.py | 2 +- poetry/mixology/incompatibility.py | 12 +- poetry/mixology/term.py | 2 +- poetry/packages/locker.py | 2 +- poetry/poetry.py | 2 +- poetry/puzzle/provider.py | 8 +- poetry/repositories/legacy_repository.py | 2 +- poetry/repositories/pypi_repository.py | 2 +- poetry/utils/env.py | 13 +-- poetry/utils/helpers.py | 2 +- poetry/utils/password_manager.py | 2 +- poetry/utils/shell.py | 2 +- sonnet | 20 ++-- tests/conftest.py | 8 +- tests/console/commands/env/conftest.py | 2 +- tests/console/commands/env/helpers.py | 2 +- tests/console/commands/env/test_remove.py | 6 +- tests/console/commands/env/test_use.py | 6 +- tests/console/commands/self/test_update.py | 6 +- tests/console/commands/test_add.py | 18 +-- tests/console/commands/test_cache.py | 4 +- tests/console/commands/test_export.py | 3 - tests/console/commands/test_init.py | 6 +- tests/console/commands/test_new.py | 2 +- .../setup.py | 1 - .../git/github.com/demo/demo/setup.py | 1 - .../github.com/demo/no-dependencies/setup.py | 1 - .../git/github.com/demo/no-version/setup.py | 1 - .../demo/non-canonical-name/setup.py | 1 - tests/fixtures/project_with_setup/setup.py | 2 - tests/helpers.py | 14 +-- tests/installation/test_authenticator.py | 6 +- tests/installation/test_executor.py | 3 - tests/installation/test_installer.py | 12 +- tests/installation/test_installer_old.py | 6 +- tests/installation/test_pip_installer.py | 2 +- .../masonry/builders/test_editable_builder.py | 3 - tests/packages/test_locker.py | 2 +- tests/repositories/test_legacy_repository.py | 4 +- tests/repositories/test_pypi_repository.py | 2 +- tests/test_factory.py | 4 - tests/utils/fixtures/setups/ansible/setup.py | 8 +- tests/utils/fixtures/setups/flask/setup.py | 5 +- tests/utils/fixtures/setups/pendulum/setup.py | 1 - tests/utils/fixtures/setups/pyyaml/setup.py | 4 +- tests/utils/test_env.py | 106 +++++++++--------- 83 files changed, 272 insertions(+), 310 deletions(-) diff --git a/get-poetry.py b/get-poetry.py index 16e4bdcddfd..62be13c1c7a 100644 --- a/get-poetry.py +++ b/get-poetry.py @@ -34,7 +34,6 @@ from functools import cmp_to_key from gzip import GzipFile from io import UnsupportedOperation -from io import open try: @@ -152,7 +151,7 @@ def colorize(style, text): if not is_decorated(): return text - return "{}{}\033[0m".format(STYLES[style], text) + return f"{STYLES[style]}{text}\033[0m" @contextmanager @@ -363,7 +362,7 @@ def run(self): version, upgrade=current_version is not None, file=self._offline_file ) except subprocess.CalledProcessError as e: - print(colorize("error", "An error has occured: {}".format(str(e)))) + print(colorize("error", f"An error has occured: {str(e)}")) print(e.output.decode()) return e.returncode @@ -434,7 +433,7 @@ def _compare_versions(x, y): ) if self._version and self._version not in releases: - print(colorize("error", "Version {} does not exist.".format(self._version))) + print(colorize("error", f"Version {self._version} does not exist.")) return None, None @@ -572,25 +571,25 @@ def _make_lib(self, version): if platform == "linux2": platform = "linux" - url = self._base_url + "{}/".format(version) - name = "poetry-{}-{}.tar.gz".format(version, platform) - checksum = "poetry-{}-{}.sha256sum".format(version, platform) + url = self._base_url + f"{version}/" + name = f"poetry-{version}-{platform}.tar.gz" + checksum = f"poetry-{version}-{platform}.sha256sum" try: - r = urlopen(url + "{}".format(checksum)) + r = urlopen(url + f"{checksum}") except HTTPError as e: if e.code == 404: - raise RuntimeError("Could not find {} file".format(checksum)) + raise RuntimeError(f"Could not find {checksum} file") raise checksum = r.read().decode() try: - r = urlopen(url + "{}".format(name)) + r = urlopen(url + f"{name}") except HTTPError as e: if e.code == 404: - raise RuntimeError("Could not find {} file".format(name)) + raise RuntimeError(f"Could not find {name} file") raise @@ -692,7 +691,7 @@ def make_bin(self): if WINDOWS: python_executable = "python" - f.write(u("#!/usr/bin/env {}\n".format(python_executable))) + f.write(u(f"#!/usr/bin/env {python_executable}\n")) f.write(u(BIN)) if not WINDOWS: @@ -723,14 +722,14 @@ def update_path(self): # Updating any profile we can on UNIX systems export_string = self.get_export_string() - addition = "\n{}\n".format(export_string) + addition = f"\n{export_string}\n" profiles = self.get_unix_profiles() for profile in profiles: if not os.path.exists(profile): continue - with open(profile, "r") as f: + with open(profile) as f: content = f.read() if addition not in content: @@ -758,8 +757,8 @@ def add_to_fish_path(self): ["fish", "-c", "echo $fish_user_paths"] ).decode("utf-8") if POETRY_BIN not in fish_user_paths: - cmd = "set -U fish_user_paths {} $fish_user_paths".format(POETRY_BIN) - set_fish_user_path = ["fish", "-c", "{}".format(cmd)] + cmd = f"set -U fish_user_paths {POETRY_BIN} $fish_user_paths" + set_fish_user_path = ["fish", "-c", f"{cmd}"] subprocess.check_output(set_fish_user_path) else: print( @@ -774,7 +773,7 @@ def add_to_fish_path(self): def add_to_windows_path(self): try: old_path = self.get_windows_path_var() - except WindowsError: + except OSError: old_path = None if old_path is None: @@ -824,7 +823,7 @@ def set_windows_path_var(self, value): HWND_BROADCAST, WM_SETTINGCHANGE, 0, - u"Environment", + "Environment", SMTO_ABORTIFHUNG, 5000, ctypes.byref(result), @@ -847,7 +846,7 @@ def remove_from_fish_path(self): cmd = "set -U fish_user_paths (string match -v {} $fish_user_paths)".format( POETRY_BIN ) - set_fish_user_path = ["fish", "-c", "{}".format(cmd)] + set_fish_user_path = ["fish", "-c", f"{cmd}"] subprocess.check_output(set_fish_user_path) def remove_from_windows_path(self): @@ -866,14 +865,14 @@ def remove_from_unix_path(self): # Updating any profile we can on UNIX systems export_string = self.get_export_string() - addition = "{}\n".format(export_string) + addition = f"{export_string}\n" profiles = self.get_unix_profiles() for profile in profiles: if not os.path.exists(profile): continue - with open(profile, "r") as f: + with open(profile) as f: content = f.readlines() if addition not in content: @@ -894,7 +893,7 @@ def remove_from_unix_path(self): def get_export_string(self): path = POETRY_BIN.replace(os.getenv("HOME", ""), "$HOME") - export_string = 'export PATH="{}:$PATH"'.format(path) + export_string = f'export PATH="{path}:$PATH"' return export_string diff --git a/install-poetry.py b/install-poetry.py index ba67d3df8c8..c29898bc300 100644 --- a/install-poetry.py +++ b/install-poetry.py @@ -122,7 +122,7 @@ def colorize(style, text): if not is_decorated(): return text - return "{}{}\033[0m".format(STYLES[style], text) + return f"{STYLES[style]}{text}\033[0m" def string_to_bool(value): @@ -282,32 +282,32 @@ def __init__(self) -> None: self._output = sys.stdout def move_up(self, lines: int = 1) -> "Cursor": - self._output.write("\x1b[{}A".format(lines)) + self._output.write(f"\x1b[{lines}A") return self def move_down(self, lines: int = 1) -> "Cursor": - self._output.write("\x1b[{}B".format(lines)) + self._output.write(f"\x1b[{lines}B") return self def move_right(self, columns: int = 1) -> "Cursor": - self._output.write("\x1b[{}C".format(columns)) + self._output.write(f"\x1b[{columns}C") return self def move_left(self, columns: int = 1) -> "Cursor": - self._output.write("\x1b[{}D".format(columns)) + self._output.write(f"\x1b[{columns}D") return self def move_to_column(self, column: int) -> "Cursor": - self._output.write("\x1b[{}G".format(column)) + self._output.write(f"\x1b[{column}G") return self def move_to_position(self, column: int, row: int) -> "Cursor": - self._output.write("\x1b[{};{}H".format(row + 1, column)) + self._output.write(f"\x1b[{row + 1};{column}H") return self @@ -416,7 +416,7 @@ def run(self) -> int: try: self.install(version) except subprocess.CalledProcessError as e: - print(colorize("error", "An error has occured: {}".format(str(e)))) + print(colorize("error", f"An error has occured: {str(e)}")) print(e.output.decode()) return e.returncode @@ -685,7 +685,7 @@ def _compare_versions(x, y): if self._version and self._version not in releases: self._write( - colorize("error", "Version {} does not exist.".format(self._version)) + colorize("error", f"Version {self._version} does not exist.") ) return None, None diff --git a/poetry/console/commands/add.py b/poetry/console/commands/add.py index 777f3744787..e8640a2c100 100644 --- a/poetry/console/commands/add.py +++ b/poetry/console/commands/add.py @@ -1,4 +1,3 @@ -# -*- coding: utf-8 -*- from typing import Dict from typing import List @@ -222,7 +221,7 @@ def notify_about_existing_packages(self, existing_packages: List[str]) -> None: "The following packages are already present in the pyproject.toml and will be skipped:\n" ) for name in existing_packages: - self.line(" • {name}".format(name=name)) + self.line(f" • {name}") self.line( "\nIf you want to update it to the latest compatible version, you can use `poetry update package`.\n" "If you prefer to upgrade it to the latest available version, you can use `poetry add package@latest`.\n" diff --git a/poetry/console/commands/cache/clear.py b/poetry/console/commands/cache/clear.py index 7bacdb891cb..07b027ac144 100644 --- a/poetry/console/commands/cache/clear.py +++ b/poetry/console/commands/cache/clear.py @@ -29,7 +29,7 @@ def handle(self) -> int: try: cache_dir.relative_to(REPOSITORY_CACHE_DIR) except ValueError: - raise ValueError("{} is not a valid repository cache".format(root)) + raise ValueError(f"{root} is not a valid repository cache") cache = CacheManager( { @@ -47,7 +47,7 @@ def handle(self) -> int: ) if not os.path.exists(str(cache_dir)): - self.line("No cache entries for {}".format(parts[0])) + self.line(f"No cache entries for {parts[0]}") return 0 # Calculate number of entries @@ -56,7 +56,7 @@ def handle(self) -> int: entries_count += len(files) delete = self.confirm( - "Delete {} entries?".format(entries_count) + f"Delete {entries_count} entries?" ) if not delete: return 0 @@ -71,14 +71,14 @@ def handle(self) -> int: package = parts[1] version = parts[2] - if not cache.has("{}:{}".format(package, version)): - self.line("No cache entries for {}:{}".format(package, version)) + if not cache.has(f"{package}:{version}"): + self.line(f"No cache entries for {package}:{version}") return 0 - delete = self.confirm("Delete cache entry {}:{}".format(package, version)) + delete = self.confirm(f"Delete cache entry {package}:{version}") if not delete: return 0 - cache.forget("{}:{}".format(package, version)) + cache.forget(f"{package}:{version}") else: raise ValueError("Invalid cache key") diff --git a/poetry/console/commands/cache/list.py b/poetry/console/commands/cache/list.py index b22dc9c312c..3cf8b7115d2 100644 --- a/poetry/console/commands/cache/list.py +++ b/poetry/console/commands/cache/list.py @@ -17,7 +17,7 @@ def handle(self) -> Optional[int]: caches = list(sorted(REPOSITORY_CACHE_DIR.iterdir())) if caches: for cache in caches: - self.line("{}".format(cache.name)) + self.line(f"{cache.name}") return 0 self.line("No caches found") diff --git a/poetry/console/commands/check.py b/poetry/console/commands/check.py index f6531dab992..16b722c6a70 100644 --- a/poetry/console/commands/check.py +++ b/poetry/console/commands/check.py @@ -22,9 +22,9 @@ def handle(self) -> int: return 0 for error in check_result["errors"]: - self.line("Error: {}".format(error)) + self.line(f"Error: {error}") for error in check_result["warnings"]: - self.line("Warning: {}".format(error)) + self.line(f"Warning: {error}") return 1 diff --git a/poetry/console/commands/config.py b/poetry/console/commands/config.py index 300245955d0..0f1a365019d 100644 --- a/poetry/console/commands/config.py +++ b/poetry/console/commands/config.py @@ -138,10 +138,10 @@ def handle(self) -> Optional[int]: if config.get("repositories") is not None: value = config.get("repositories") else: - repo = config.get("repositories.{}".format(m.group(1))) + repo = config.get(f"repositories.{m.group(1)}") if repo is None: raise ValueError( - "There is no {} repository defined".format(m.group(1)) + f"There is no {m.group(1)} repository defined" ) value = repo @@ -150,7 +150,7 @@ def handle(self) -> Optional[int]: else: values = self.unique_config_values if setting_key not in values: - raise ValueError("There is no {} setting.".format(setting_key)) + raise ValueError(f"There is no {setting_key} setting.") value = config.get(setting_key) @@ -182,14 +182,14 @@ def handle(self) -> Optional[int]: raise ValueError("You cannot remove the [repositories] section") if self.option("unset"): - repo = config.get("repositories.{}".format(m.group(1))) + repo = config.get(f"repositories.{m.group(1)}") if repo is None: raise ValueError( - "There is no {} repository defined".format(m.group(1)) + f"There is no {m.group(1)} repository defined" ) config.config_source.remove_property( - "repositories.{}".format(m.group(1)) + f"repositories.{m.group(1)}" ) return 0 @@ -198,7 +198,7 @@ def handle(self) -> Optional[int]: url = values[0] config.config_source.add_property( - "repositories.{}.url".format(m.group(1)), url + f"repositories.{m.group(1)}.url", url ) return 0 @@ -240,7 +240,7 @@ def handle(self) -> Optional[int]: elif m.group(1) == "pypi-token": if len(values) != 1: raise ValueError( - "Expected only one argument (token), got {}".format(len(values)) + f"Expected only one argument (token), got {len(values)}" ) token = values[0] @@ -256,14 +256,14 @@ def handle(self) -> Optional[int]: if m: if self.option("unset"): config.auth_config_source.remove_property( - "certificates.{}.{}".format(m.group(1), m.group(2)) + f"certificates.{m.group(1)}.{m.group(2)}" ) return 0 if len(values) == 1: config.auth_config_source.add_property( - "certificates.{}.{}".format(m.group(1), m.group(2)), values[0] + f"certificates.{m.group(1)}.{m.group(2)}", values[0] ) else: raise ValueError("You must pass exactly 1 value") @@ -286,7 +286,7 @@ def _handle_single_value( value = values[0] if not validator(value): - raise RuntimeError('"{}" is an invalid value for {}'.format(value, key)) + raise RuntimeError(f'"{value}" is an invalid value for {key}') source.add_property(key, normalizer(value)) @@ -301,7 +301,7 @@ def _list_configuration(self, config: Dict, raw: Dict, k: str = "") -> None: raw_val = raw.get(key) if isinstance(value, dict): - k += "{}.".format(key) + k += f"{key}." self._list_configuration(value, raw_val, k=k) k = orig_k @@ -322,7 +322,7 @@ def _list_configuration(self, config: Dict, raw: Dict, k: str = "") -> None: k + key, json.dumps(raw_val), value ) else: - message = "{} = {}".format(k + key, json.dumps(value)) + message = f"{k + key} = {json.dumps(value)}" self.line(message) diff --git a/poetry/console/commands/debug/info.py b/poetry/console/commands/debug/info.py index b007d93d4c8..ac458b2bb89 100644 --- a/poetry/console/commands/debug/info.py +++ b/poetry/console/commands/debug/info.py @@ -16,7 +16,7 @@ def handle(self) -> int: self.line( "\n".join( [ - "Version: {}".format(self.poetry.VERSION), + f"Version: {self.poetry.VERSION}", "Python: {}".format( poetry_python_version ), diff --git a/poetry/console/commands/debug/resolve.py b/poetry/console/commands/debug/resolve.py index 06b0fa9d21f..c55fc1efdb0 100644 --- a/poetry/console/commands/debug/resolve.py +++ b/poetry/console/commands/debug/resolve.py @@ -131,8 +131,8 @@ def handle(self) -> Optional[int]: pkg = op.package row = [ - "{}".format(pkg.complete_name), - "{}".format(pkg.version), + f"{pkg.complete_name}", + f"{pkg.version}", "", ] diff --git a/poetry/console/commands/env/info.py b/poetry/console/commands/env/info.py index aecce3628ac..a8c8a921a62 100644 --- a/poetry/console/commands/env/info.py +++ b/poetry/console/commands/env/info.py @@ -37,7 +37,7 @@ def _display_complete_info(self, env: "Env") -> None: self.line("") self.line("Virtualenv") listing = [ - "Python: {}".format(env_python_version), + f"Python: {env_python_version}", "Implementation: {}".format( env.python_implementation ), @@ -59,9 +59,9 @@ def _display_complete_info(self, env: "Env") -> None: self.line( "\n".join( [ - "Platform: {}".format(env.platform), - "OS: {}".format(env.os), - "Python: {}".format(env.base), + f"Platform: {env.platform}", + f"OS: {env.os}", + f"Python: {env.base}", ] ) ) diff --git a/poetry/console/commands/env/list.py b/poetry/console/commands/env/list.py index e7b1eac6cd5..3eaa0111af1 100644 --- a/poetry/console/commands/env/list.py +++ b/poetry/console/commands/env/list.py @@ -22,7 +22,7 @@ def handle(self) -> None: name = str(venv.path) if venv == current_env: - self.line("{} (Activated)".format(name)) + self.line(f"{name} (Activated)") continue diff --git a/poetry/console/commands/env/remove.py b/poetry/console/commands/env/remove.py index 9d5153c420b..494400e918d 100644 --- a/poetry/console/commands/env/remove.py +++ b/poetry/console/commands/env/remove.py @@ -18,4 +18,4 @@ def handle(self) -> None: manager = EnvManager(self.poetry) venv = manager.remove(self.argument("python")) - self.line("Deleted virtualenv: {}".format(venv.path)) + self.line(f"Deleted virtualenv: {venv.path}") diff --git a/poetry/console/commands/env/use.py b/poetry/console/commands/env/use.py index fa8a455bcf7..faccc8c2198 100644 --- a/poetry/console/commands/env/use.py +++ b/poetry/console/commands/env/use.py @@ -22,4 +22,4 @@ def handle(self) -> None: env = manager.activate(self.argument("python"), self._io) - self.line("Using virtualenv: {}".format(env.path)) + self.line(f"Using virtualenv: {env.path}") diff --git a/poetry/console/commands/env_command.py b/poetry/console/commands/env_command.py index fd44b415c00..fd7c7b9adad 100644 --- a/poetry/console/commands/env_command.py +++ b/poetry/console/commands/env_command.py @@ -11,7 +11,7 @@ class EnvCommand(Command): def __init__(self) -> None: self._env = None - super(EnvCommand, self).__init__() + super().__init__() @property def env(self) -> "Env": diff --git a/poetry/console/commands/export.py b/poetry/console/commands/export.py index a58d96f50fe..5f8f4b7035f 100644 --- a/poetry/console/commands/export.py +++ b/poetry/console/commands/export.py @@ -35,7 +35,7 @@ def handle(self) -> None: fmt = self.option("format") if fmt not in Exporter.ACCEPTED_FORMATS: - raise ValueError("Invalid export format: {}".format(fmt)) + raise ValueError(f"Invalid export format: {fmt}") output = self.option("output") diff --git a/poetry/console/commands/init.py b/poetry/console/commands/init.py index b2e4fd0a315..979c5948566 100644 --- a/poetry/console/commands/init.py +++ b/poetry/console/commands/init.py @@ -57,7 +57,7 @@ class InitCommand(Command): """ def __init__(self) -> None: - super(InitCommand, self).__init__() + super().__init__() self._pool = None @@ -97,19 +97,19 @@ def handle(self) -> int: name = Path.cwd().name.lower() question = self.create_question( - "Package name [{}]: ".format(name), default=name + f"Package name [{name}]: ", default=name ) name = self.ask(question) version = "0.1.0" question = self.create_question( - "Version [{}]: ".format(version), default=version + f"Version [{version}]: ", default=version ) version = self.ask(question) description = self.option("description") or "" question = self.create_question( - "Description [{}]: ".format(description), + f"Description [{description}]: ", default=description, ) description = self.ask(question) @@ -119,10 +119,10 @@ def handle(self) -> int: author = vcs_config["user.name"] author_email = vcs_config.get("user.email") if author_email: - author += " <{}>".format(author_email) + author += f" <{author_email}>" question = self.create_question( - "Author [{}, n to skip]: ".format(author), default=author + f"Author [{author}, n to skip]: ", default=author ) question.set_validator(lambda v: self._validate_author(v, author)) author = self.ask(question) @@ -135,7 +135,7 @@ def handle(self) -> int: license = self.option("license") or "" question = self.create_question( - "License [{}]: ".format(license), default=license + f"License [{license}]: ", default=license ) question.set_validator(self._validate_license) license = self.ask(question) @@ -246,7 +246,7 @@ def _determine_requirements( or "path" in constraint or "version" in constraint ): - self.line("Adding {}".format(package)) + self.line(f"Adding {package}") requires.append(constraint) package = self.ask("\nAdd a package:") continue @@ -338,7 +338,7 @@ def _determine_requirements( requirement["name"] = name self.line( - "Using version {} for {}".format(version, name) + f"Using version {version} for {name}" ) else: # check that the specified version/constraint exists @@ -373,7 +373,7 @@ def _find_best_version_for_package( if not package: # TODO: find similar raise ValueError( - "Could not find a matching version of package {}".format(name) + f"Could not find a matching version of package {name}" ) return package.pretty_name, selector.find_recommended_require_version(package) diff --git a/poetry/console/commands/installer_command.py b/poetry/console/commands/installer_command.py index 409e2fc456c..a0da62c666f 100644 --- a/poetry/console/commands/installer_command.py +++ b/poetry/console/commands/installer_command.py @@ -12,10 +12,10 @@ class InstallerCommand(EnvCommand): def __init__(self) -> None: self._installer: Optional["Installer"] = None - super(InstallerCommand, self).__init__() + super().__init__() def reset_poetry(self) -> None: - super(InstallerCommand, self).reset_poetry() + super().reset_poetry() self._installer.set_package(self.poetry.package) self._installer.set_locker(self.poetry.locker) diff --git a/poetry/console/commands/new.py b/poetry/console/commands/new.py index 8158442f741..b47df231be5 100644 --- a/poetry/console/commands/new.py +++ b/poetry/console/commands/new.py @@ -60,7 +60,7 @@ def handle(self) -> None: author = config["user.name"] author_email = config.get("user.email") if author_email: - author += " <{}>".format(author_email) + author += f" <{author_email}>" current_env = SystemEnv(Path(sys.executable)) default_python = "^{}".format( diff --git a/poetry/console/commands/plugin/add.py b/poetry/console/commands/plugin/add.py index 8418aa25c89..32d12d878ef 100644 --- a/poetry/console/commands/plugin/add.py +++ b/poetry/console/commands/plugin/add.py @@ -193,7 +193,7 @@ def notify_about_existing_packages(self, existing_packages: List[str]) -> None: "pyproject.toml file and will be skipped:\n" ) for name in existing_packages: - self.line(" • {name}".format(name=name)) + self.line(f" • {name}") self.line( "\nIf you want to update it to the latest compatible version, " diff --git a/poetry/console/commands/remove.py b/poetry/console/commands/remove.py index 58af353ccc6..0ebf17ab35f 100644 --- a/poetry/console/commands/remove.py +++ b/poetry/console/commands/remove.py @@ -49,7 +49,7 @@ def handle(self) -> int: break if not found: - raise ValueError("Package {} not found".format(name)) + raise ValueError(f"Package {name} not found") for key in requirements: del poetry_content[section][key] diff --git a/poetry/console/commands/search.py b/poetry/console/commands/search.py index 85384125bca..5cb99e70ca5 100644 --- a/poetry/console/commands/search.py +++ b/poetry/console/commands/search.py @@ -17,11 +17,11 @@ def handle(self) -> None: for result in results: self.line("") - name = "{}".format(result.name) + name = f"{result.name}" - name += " ({})".format(result.version) + name += f" ({result.version})" self.line(name) if result.description: - self.line(" {}".format(result.description)) + self.line(f" {result.description}") diff --git a/poetry/console/commands/self/update.py b/poetry/console/commands/self/update.py index 95e8f5dce6a..5f625ff47b9 100644 --- a/poetry/console/commands/self/update.py +++ b/poetry/console/commands/self/update.py @@ -1,5 +1,3 @@ -from __future__ import unicode_literals - import hashlib import os import re @@ -132,7 +130,7 @@ def handle(self) -> None: def update(self, release: "Package") -> None: version = release.version - self.line("Updating to {}".format(version)) + self.line(f"Updating to {version}") if self.lib_backup.exists(): shutil.rmtree(str(self.lib_backup)) @@ -171,27 +169,27 @@ def _update(self, version: "Version") -> None: release_name = self._get_release_name(version) - checksum = "{}.sha256sum".format(release_name) + checksum = f"{release_name}.sha256sum" base_url = self.BASE_URL try: - r = urlopen(base_url + "/{}/{}".format(version, checksum)) + r = urlopen(base_url + f"/{version}/{checksum}") except HTTPError as e: if e.code == 404: - raise RuntimeError("Could not find {} file".format(checksum)) + raise RuntimeError(f"Could not find {checksum} file") raise checksum = r.read().decode().strip() # We get the payload from the remote host - name = "{}.tar.gz".format(release_name) + name = f"{release_name}.tar.gz" try: - r = urlopen(base_url + "/{}/{}".format(version, name)) + r = urlopen(base_url + f"/{version}/{name}") except HTTPError as e: if e.code == 404: - raise RuntimeError("Could not find {} file".format(name)) + raise RuntimeError(f"Could not find {name} file") raise @@ -201,7 +199,7 @@ def _update(self, version: "Version") -> None: block_size = 8192 bar = self.progress_bar(max=size) - bar.set_format(" - Downloading {} %percent%%".format(name)) + bar.set_format(f" - Downloading {name} %percent%%") bar.start() sha = hashlib.sha256() @@ -258,7 +256,7 @@ def _get_release_name(self, version: "Version") -> str: if platform == "linux2": platform = "linux" - return "poetry-{}-{}".format(version, platform) + return f"poetry-{version}-{platform}" def make_bin(self) -> None: from poetry.utils._compat import WINDOWS @@ -280,7 +278,7 @@ def make_bin(self) -> None: bin_content = BIN if not WINDOWS: - bin_content = "#!/usr/bin/env {}\n".format(python_executable) + bin_content + bin_content = f"#!/usr/bin/env {python_executable}\n" + bin_content self.bin.joinpath("poetry").write_text(bin_content, encoding="utf-8") diff --git a/poetry/console/commands/shell.py b/poetry/console/commands/shell.py index f0f7f851fba..a1f44df32f1 100644 --- a/poetry/console/commands/shell.py +++ b/poetry/console/commands/shell.py @@ -31,7 +31,7 @@ def handle(self) -> None: return - self.line("Spawning shell within {}".format(self.env.path)) + self.line(f"Spawning shell within {self.env.path}") # Setting this to avoid spawning unnecessary nested shells environ["POETRY_ACTIVE"] = "1" diff --git a/poetry/console/commands/show.py b/poetry/console/commands/show.py index 799fa4d78db..7b840e4bfa1 100644 --- a/poetry/console/commands/show.py +++ b/poetry/console/commands/show.py @@ -95,7 +95,7 @@ def handle(self) -> Optional[int]: with solver.use_environment(self.env): ops = solver.solve() - required_locked_packages = set([op.package for op in ops if not op.skipped]) + required_locked_packages = {op.package for op in ops if not op.skipped} if self.option("no-dev"): required_locked_packages = [ @@ -110,7 +110,7 @@ def handle(self) -> Optional[int]: break if not pkg: - raise ValueError("Package {} not found".format(package)) + raise ValueError(f"Package {package} not found") if self.option("tree"): self.display_package_tree(self.io, pkg, locked_repo) @@ -118,9 +118,9 @@ def handle(self) -> Optional[int]: return 0 rows = [ - ["name", " : {}".format(pkg.pretty_name)], - ["version", " : {}".format(pkg.pretty_version)], - ["description", " : {}".format(pkg.description)], + ["name", f" : {pkg.pretty_name}"], + ["version", f" : {pkg.pretty_version}"], + ["description", f" : {pkg.description}"], ] table.add_rows(rows) @@ -272,12 +272,12 @@ def handle(self) -> Optional[int]: def display_package_tree( self, io: "IO", package: "Package", installed_repo: "Repository" ) -> None: - io.write("{}".format(package.pretty_name)) + io.write(f"{package.pretty_name}") description = "" if package.description: description = " " + package.description - io.write_line(" {}{}".format(package.pretty_version, description)) + io.write_line(f" {package.pretty_version}{description}") dependencies = package.requires dependencies = sorted(dependencies, key=lambda x: x.name) @@ -404,7 +404,7 @@ def find_latest_package( name = package.name selector = VersionSelector(self.poetry.pool) - return selector.find_best_candidate(name, ">={}".format(package.pretty_version)) + return selector.find_best_candidate(name, f">={package.pretty_version}") def get_update_status(self, latest: "Package", package: "Package") -> str: from poetry.core.semver.helpers import parse_constraint diff --git a/poetry/console/commands/source/show.py b/poetry/console/commands/source/show.py index 67e843fcf61..23cfedfbccc 100644 --- a/poetry/console/commands/source/show.py +++ b/poetry/console/commands/source/show.py @@ -41,15 +41,15 @@ def handle(self) -> Optional[int]: table = self.table(style="compact") rows = [ - ["name", " : {}".format(source.name)], - ["url", " : {}".format(source.url)], + ["name", f" : {source.name}"], + ["url", f" : {source.url}"], [ "default", - " : {}".format(bool_string.get(source.default, False)), + f" : {bool_string.get(source.default, False)}", ], [ "secondary", - " : {}".format(bool_string.get(source.secondary, False)), + f" : {bool_string.get(source.secondary, False)}", ], ] table.add_rows(rows) diff --git a/poetry/console/commands/version.py b/poetry/console/commands/version.py index 71c18a0260c..c79355f5d7a 100644 --- a/poetry/console/commands/version.py +++ b/poetry/console/commands/version.py @@ -55,7 +55,7 @@ def handle(self) -> None: ) if self.option("short"): - self.line("{}".format(version)) + self.line(f"{version}") else: self.line( "Bumping version from {} to {}".format( @@ -70,7 +70,7 @@ def handle(self) -> None: self.poetry.file.write(content) else: if self.option("short"): - self.line("{}".format(self.poetry.package.pretty_version)) + self.line(f"{self.poetry.package.pretty_version}") else: self.line( "{} {}".format( diff --git a/poetry/console/logging/formatters/formatter.py b/poetry/console/logging/formatters/formatter.py index f2ab7b18624..922b4d85f83 100644 --- a/poetry/console/logging/formatters/formatter.py +++ b/poetry/console/logging/formatters/formatter.py @@ -1,6 +1,6 @@ import logging -class Formatter(object): +class Formatter: def format(self, record: logging.LogRecord) -> str: raise NotImplementedError() diff --git a/poetry/console/logging/io_formatter.py b/poetry/console/logging/io_formatter.py index c7ca46fef97..64b0b3c5af4 100644 --- a/poetry/console/logging/io_formatter.py +++ b/poetry/console/logging/io_formatter.py @@ -26,8 +26,8 @@ def format(self, record: "LogRecord") -> str: if record.name in FORMATTERS: msg = FORMATTERS[record.name].format(msg) elif level in self._colors: - msg = "<{}>{}".format(self._colors[level], msg) + msg = f"<{self._colors[level]}>{msg}" return msg - return super(IOFormatter, self).format(record) + return super().format(record) diff --git a/poetry/console/logging/io_handler.py b/poetry/console/logging/io_handler.py index 9a13e68b0e9..7b5c4d06d0e 100644 --- a/poetry/console/logging/io_handler.py +++ b/poetry/console/logging/io_handler.py @@ -13,7 +13,7 @@ class IOHandler(logging.Handler): def __init__(self, io: "IO") -> None: self._io = io - super(IOHandler, self).__init__() + super().__init__() def emit(self, record: "LogRecord") -> None: try: diff --git a/poetry/factory.py b/poetry/factory.py index 144bfe35871..0b1f228675a 100644 --- a/poetry/factory.py +++ b/poetry/factory.py @@ -1,6 +1,3 @@ -from __future__ import absolute_import -from __future__ import unicode_literals - from pathlib import Path from typing import TYPE_CHECKING from typing import Dict @@ -41,7 +38,7 @@ def create_poetry( if io is None: io = NullIO() - base_poetry = super(Factory, self).create_poetry(cwd) + base_poetry = super().create_poetry(cwd) locker = Locker( base_poetry.file.parent / "poetry.lock", base_poetry.local_config @@ -55,7 +52,7 @@ def create_poetry( if local_config_file.exists(): if io.is_debug(): io.write_line( - "Loading configuration file {}".format(local_config_file.path) + f"Loading configuration file {local_config_file.path}" ) config.merge(local_config_file.read()) diff --git a/poetry/inspection/info.py b/poetry/inspection/info.py index ae5f59bd63f..30e965fa40c 100644 --- a/poetry/inspection/info.py +++ b/poetry/inspection/info.py @@ -45,7 +45,7 @@ def __init__( self, path: Union[Path, str], *reasons: Union[BaseException, str] ) -> None: reasons = ( - "Unable to determine package info for path: {}".format(str(path)), + f"Unable to determine package info for path: {str(path)}", ) + reasons super().__init__("\n\n".join(str(msg).strip() for msg in reasons if msg)) diff --git a/poetry/installation/operations/install.py b/poetry/installation/operations/install.py index 621ff4a37dc..6b583b5aa84 100644 --- a/poetry/installation/operations/install.py +++ b/poetry/installation/operations/install.py @@ -12,7 +12,7 @@ class Install(Operation): def __init__( self, package: "Package", reason: Optional[str] = None, priority: int = 0 ) -> None: - super(Install, self).__init__(reason, priority=priority) + super().__init__(reason, priority=priority) self._package = package diff --git a/poetry/installation/operations/operation.py b/poetry/installation/operations/operation.py index 581b62959cd..aacfb9f0f2e 100644 --- a/poetry/installation/operations/operation.py +++ b/poetry/installation/operations/operation.py @@ -6,7 +6,7 @@ from poetry.core.packages.package import Package -class Operation(object): +class Operation: def __init__(self, reason: Optional[str] = None, priority: int = 0) -> None: self._reason = reason diff --git a/poetry/installation/operations/uninstall.py b/poetry/installation/operations/uninstall.py index d9f41055d1a..5ee2b32547d 100644 --- a/poetry/installation/operations/uninstall.py +++ b/poetry/installation/operations/uninstall.py @@ -15,7 +15,7 @@ def __init__( reason: Optional[str] = None, priority: int = float("inf"), ) -> None: - super(Uninstall, self).__init__(reason, priority=priority) + super().__init__(reason, priority=priority) self._package = package diff --git a/poetry/installation/operations/update.py b/poetry/installation/operations/update.py index 26ca853df05..3010d156370 100644 --- a/poetry/installation/operations/update.py +++ b/poetry/installation/operations/update.py @@ -19,7 +19,7 @@ def __init__( self._initial_package = initial self._target_package = target - super(Update, self).__init__(reason, priority=priority) + super().__init__(reason, priority=priority) @property def initial_package(self) -> "Package": diff --git a/poetry/layouts/layout.py b/poetry/layouts/layout.py index f4610564582..ac25bb3bf1b 100644 --- a/poetry/layouts/layout.py +++ b/poetry/layouts/layout.py @@ -131,7 +131,7 @@ def generate_poetry_content( else: poetry_content.remove("license") - poetry_content["readme"] = "README.{}".format(self._readme_format) + poetry_content["readme"] = f"README.{self._readme_format}" packages = self.get_package_include() if packages: poetry_content["packages"].append(packages) @@ -177,7 +177,7 @@ def _create_default(self, path: "Path", src: bool = True) -> None: package_init.touch() def _create_readme(self, path: "Path") -> "Path": - readme_file = path.joinpath("README.{}".format(self._readme_format)) + readme_file = path.joinpath(f"README.{self._readme_format}") readme_file.touch() return readme_file diff --git a/poetry/masonry/builders/editable.py b/poetry/masonry/builders/editable.py index 2483a5ec704..86898b75525 100644 --- a/poetry/masonry/builders/editable.py +++ b/poetry/masonry/builders/editable.py @@ -1,5 +1,3 @@ -from __future__ import unicode_literals - import hashlib import os import shutil @@ -40,7 +38,7 @@ class EditableBuilder(Builder): def __init__(self, poetry: "Poetry", env: "Env", io: "IO") -> None: - super(EditableBuilder, self).__init__(poetry) + super().__init__(poetry) self._env = env self._io = io @@ -76,7 +74,7 @@ def build(self) -> None: self._add_dist_info(added_files) def _run_build_script(self, build_script: Path) -> None: - self._debug(" - Executing build script: {}".format(build_script)) + self._debug(f" - Executing build script: {build_script}") self._env.run("python", str(self._path.joinpath(build_script)), call=True) def _setup_build(self) -> None: @@ -250,7 +248,7 @@ def _add_dist_info(self, added_files: List[Path]) -> None: for path in added_files: hash = self._get_file_hash(path) size = path.stat().st_size - f.write("{},sha256={},{}\n".format(str(path), hash, size)) + f.write(f"{str(path)},sha256={hash},{size}\n") # RECORD itself is recorded with no hash or size f.write("{},,\n".format(dist_info.joinpath("RECORD"))) diff --git a/poetry/mixology/failure.py b/poetry/mixology/failure.py index bf84348ced1..38e6d276841 100644 --- a/poetry/mixology/failure.py +++ b/poetry/mixology/failure.py @@ -70,7 +70,7 @@ def write(self) -> str: padding = ( 0 if not self._line_numbers - else len("({}) ".format(list(self._line_numbers.values())[-1])) + else len(f"({list(self._line_numbers.values())[-1]}) ") ) last_was_empty = False diff --git a/poetry/mixology/incompatibility.py b/poetry/mixology/incompatibility.py index e195e08b7ab..90ca7c08cd8 100644 --- a/poetry/mixology/incompatibility.py +++ b/poetry/mixology/incompatibility.py @@ -133,7 +133,7 @@ def __str__(self) -> str: assert self._terms[0].is_positive() cause: PythonCause = self._cause - text = "{} requires ".format(self._terse(self._terms[0], allow_every=True)) + text = f"{self._terse(self._terms[0], allow_every=True)} requires " text += f"Python {cause.python_version}" return text @@ -142,7 +142,7 @@ def __str__(self) -> str: assert self._terms[0].is_positive() cause: PlatformCause = self._cause - text = "{} requires ".format(self._terse(self._terms[0], allow_every=True)) + text = f"{self._terse(self._terms[0], allow_every=True)} requires " text += f"platform {cause.platform}" return text @@ -157,7 +157,7 @@ def __str__(self) -> str: assert len(self._terms) == 1 assert self._terms[0].is_positive() - return "{} doesn't exist".format(self._terms[0].dependency.name) + return f"{self._terms[0].dependency.name} doesn't exist" elif isinstance(self._cause, RootCause): assert len(self._terms) == 1 assert not self._terms[0].is_positive() @@ -257,7 +257,7 @@ def and_to_string( if this_line is not None: buffer.append(" " + str(this_line)) - buffer.append(" and {}".format(str(other))) + buffer.append(f" and {str(other)}") if other_line is not None: buffer.append(" " + str(other_line)) @@ -367,7 +367,7 @@ def _try_requires_through( verb = "requires" buffer.append( - "{} {} ".format(self._terse(prior_positives[0], allow_every=True), verb) + f"{self._terse(prior_positives[0], allow_every=True)} {verb} " ) buffer.append(self._terse(prior_negative)) @@ -473,4 +473,4 @@ def _single_term_where(self, callable: callable) -> Optional[Term]: return found def __repr__(self) -> str: - return "".format(str(self)) + return f"" diff --git a/poetry/mixology/term.py b/poetry/mixology/term.py index 9542689e033..a59e3f52270 100644 --- a/poetry/mixology/term.py +++ b/poetry/mixology/term.py @@ -166,4 +166,4 @@ def __str__(self) -> str: return "{}{}".format("not " if not self.is_positive() else "", self._dependency) def __repr__(self) -> str: - return "".format(str(self)) + return f"" diff --git a/poetry/packages/locker.py b/poetry/packages/locker.py index 03f6e677eb9..7360f9db066 100644 --- a/poetry/packages/locker.py +++ b/poetry/packages/locker.py @@ -478,7 +478,7 @@ def _get_lock_data(self) -> "TOMLDocument": # We expect the locker to be able to read lock files # from the same semantic versioning range accepted_versions = parse_constraint( - "^{}".format(Version.from_parts(current_version.major, 0)) + f"^{Version.from_parts(current_version.major, 0)}" ) lock_version_allowed = accepted_versions.allows(lock_version) if lock_version_allowed and current_version < lock_version: diff --git a/poetry/poetry.py b/poetry/poetry.py index 95814330e4a..73034b422d1 100644 --- a/poetry/poetry.py +++ b/poetry/poetry.py @@ -30,7 +30,7 @@ def __init__( ): from .repositories.pool import Pool # noqa - super(Poetry, self).__init__(file, local_config, package) + super().__init__(file, local_config, package) self._locker = locker self._config = config diff --git a/poetry/puzzle/provider.py b/poetry/puzzle/provider.py index c7427161c2c..3bcaafd323f 100644 --- a/poetry/puzzle/provider.py +++ b/poetry/puzzle/provider.py @@ -578,7 +578,7 @@ def complete_package(self, package: DependencyPackage) -> DependencyPackage: if len(by_constraint) == 1: self.debug( - "Merging requirements for {}".format(str(deps[0])) + f"Merging requirements for {str(deps[0])}" ) dependencies.append(list(by_constraint.values())[0][0]) continue @@ -713,7 +713,7 @@ def debug(self, message: str, depth: int = 0) -> None: m2 = re.match(r"(.+?) \((.+?)\)", m.group(1)) if m2: name = m2.group(1) - version = " ({})".format(m2.group(2)) + version = f" ({m2.group(2)})" else: name = m.group(1) version = "" @@ -757,7 +757,7 @@ def debug(self, message: str, depth: int = 0) -> None: m2 = re.match(r"(.+?) \((.+?)\)", m.group(1)) if m2: name = m2.group(1) - version = " ({})".format(m2.group(2)) + version = f" ({m2.group(2)})" else: name = m.group(1) version = "" @@ -780,7 +780,7 @@ def debug(self, message: str, depth: int = 0) -> None: debug_info = ( "\n".join( [ - "{}: {}".format(str(depth).rjust(4), s) + f"{str(depth).rjust(4)}: {s}" for s in debug_info.split("\n") ] ) diff --git a/poetry/repositories/legacy_repository.py b/poetry/repositories/legacy_repository.py index 60fd8c8b6fa..d92ad16bcc0 100644 --- a/poetry/repositories/legacy_repository.py +++ b/poetry/repositories/legacy_repository.py @@ -262,7 +262,7 @@ def find_packages(self, dependency: "Dependency") -> List[Package]: key = dependency.name if not constraint.is_any(): - key = "{}:{}".format(key, str(constraint)) + key = f"{key}:{str(constraint)}" ignored_pre_release_versions = [] diff --git a/poetry/repositories/pypi_repository.py b/poetry/repositories/pypi_repository.py index 1c7b7be316a..e9f8879a2f8 100644 --- a/poetry/repositories/pypi_repository.py +++ b/poetry/repositories/pypi_repository.py @@ -108,7 +108,7 @@ def find_packages(self, dependency: Dependency) -> List[Package]: info = self.get_package_info(dependency.name) except PackageNotFound: self._log( - "No packages found for {} {}".format(dependency.name, str(constraint)), + f"No packages found for {dependency.name} {str(constraint)}", level="debug", ) return [] diff --git a/poetry/utils/env.py b/poetry/utils/env.py index 195d08162de..20cea57a836 100644 --- a/poetry/utils/env.py +++ b/poetry/utils/env.py @@ -243,10 +243,9 @@ def distributions( str, self._candidates if not writable_only else self.writable_candidates ) ) - for distribution in metadata.PathDistribution.discover( + yield from metadata.PathDistribution.discover( name=name, path=path - ): # type: metadata.PathDistribution - yield distribution + ) def find_distribution( self, name: str, writable_only: bool = False @@ -344,7 +343,7 @@ def _path_method_wrapper( if results: return results - raise OSError("Unable to access any of {}".format(paths_csv(candidates))) + raise OSError(f"Unable to access any of {paths_csv(candidates)}") def write_text(self, path: Union[str, Path], *args: Any, **kwargs: Any) -> Path: return self._path_method_wrapper(path, "write_text", *args, **kwargs)[0] @@ -875,7 +874,7 @@ def create_venv( return SystemEnv(Path(sys.prefix)) io.write_line( - "Creating virtualenv {} in {}".format(name, str(venv_path)) + f"Creating virtualenv {name} in {str(venv_path)}" ) else: create_venv = False @@ -887,7 +886,7 @@ def create_venv( ) ) io.write_line( - "Recreating virtualenv {} in {}".format(name, str(venv)) + f"Recreating virtualenv {name} in {str(venv)}" ) self.remove_venv(venv) create_venv = True @@ -1080,7 +1079,7 @@ def marker_env(self) -> Dict[str, Any]: def get_embedded_wheel(self, distribution): return get_embed_wheel( - distribution, "{}.{}".format(self.version_info[0], self.version_info[1]) + distribution, f"{self.version_info[0]}.{self.version_info[1]}" ).path @property diff --git a/poetry/utils/helpers.py b/poetry/utils/helpers.py index d81d0f15b3d..1ade9447b05 100644 --- a/poetry/utils/helpers.py +++ b/poetry/utils/helpers.py @@ -119,7 +119,7 @@ def get_package_version_display_string( def paths_csv(paths: List[Path]) -> str: - return ", ".join('"{}"'.format(str(c)) for c in paths) + return ", ".join(f'"{str(c)}"' for c in paths) def is_dir_writable(path: Path, create: bool = False) -> bool: diff --git a/poetry/utils/password_manager.py b/poetry/utils/password_manager.py index e5eb05eab51..d359c616169 100644 --- a/poetry/utils/password_manager.py +++ b/poetry/utils/password_manager.py @@ -88,7 +88,7 @@ def _check(self) -> None: try: import keyring except Exception as e: - logger.debug("An error occurred while importing keyring: {}".format(str(e))) + logger.debug(f"An error occurred while importing keyring: {str(e)}") self._is_available = False return diff --git a/poetry/utils/shell.py b/poetry/utils/shell.py index ce91bfba029..176f39524e9 100644 --- a/poetry/utils/shell.py +++ b/poetry/utils/shell.py @@ -80,7 +80,7 @@ def activate(self, env: VirtualEnv) -> None: bin_dir = "Scripts" if WINDOWS else "bin" activate_path = env.path / bin_dir / activate_script c.sendline( - "{} {}".format(self._get_source_command(), shlex.quote(str(activate_path))) + f"{self._get_source_command()} {shlex.quote(str(activate_path))}" ) def resize(sig: Any, data: Any) -> None: diff --git a/sonnet b/sonnet index 090e31ecda2..9bc9725f10f 100755 --- a/sonnet +++ b/sonnet @@ -26,7 +26,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) io.output.formatter.set_style("debug", Style("default", options=["dark"])) io.error_output.formatter.set_style("debug", Style("default", options=["dark"])) @@ -100,7 +100,7 @@ class MakeReleaseCommand(Command): os.path.join(os.path.dirname(__file__), "poetry"), poetry_dir, ignore=lambda dir_, names: set(vcs_excluded).intersection( - set([os.path.join(dir_, name) for name in names]) + {os.path.join(dir_, name) for name in names} ), ) created_files += [ @@ -149,8 +149,8 @@ class MakeReleaseCommand(Command): self.line("Packaging files") with temporary_directory() as tmp_dir2: - base_name = "poetry-{}-{}".format(__version__, sys.platform) - name = "{}.tar.gz".format(base_name) + base_name = f"poetry-{__version__}-{sys.platform}" + name = f"{base_name}.tar.gz" gz = GzipFile(os.path.join(tmp_dir2, name), mode="wb") try: with tarfile.TarFile( @@ -195,7 +195,7 @@ class MakeReleaseCommand(Command): if missing_files: self.line("Some files are missing:") for missing_file in missing_files: - self.line(" - {}".format(missing_file)) + self.line(f" - {missing_file}") return 1 @@ -218,11 +218,11 @@ class MakeReleaseCommand(Command): sha.update(buffer) with open( - os.path.join(releases_dir, "{}.sha256sum".format(base_name)), "w" + os.path.join(releases_dir, f"{base_name}.sha256sum"), "w" ) as f: f.write(sha.hexdigest()) - self.line("Built {}".format(name)) + self.line(f"Built {name}") def check_system(self, pythons): for version, python in sorted(pythons.items()): @@ -235,10 +235,10 @@ class MakeReleaseCommand(Command): subprocess.check_output([python, "-m", "pip", "install", "pip", "-U"]) except subprocess.CalledProcessError: - raise RuntimeError("Python {} is not available".format(version)) + raise RuntimeError(f"Python {version} is not available") def vendorize_for_python(self, env, packages, dest, python_version): - vendor_dir = os.path.join(dest, "_vendor", "py{}".format(python_version)) + vendor_dir = os.path.join(dest, "_vendor", f"py{python_version}") bar = self.progress_bar(max=len(packages)) bar.set_format("%message% %current%/%max%") @@ -251,7 +251,7 @@ class MakeReleaseCommand(Command): for package in packages: env.run_pip( "install", - "{}=={}".format(package.name, package.version), + f"{package.name}=={package.version}", "--no-deps", "--target", vendor_dir, diff --git a/tests/conftest.py b/tests/conftest.py index d66ed9ba659..3957535bfa9 100644 --- a/tests/conftest.py +++ b/tests/conftest.py @@ -38,19 +38,19 @@ def get(self, setting_name: str, default: Any = None) -> Any: self.merge(self._config_source.config) self.merge(self._auth_config_source.config) - return super(Config, self).get(setting_name, default=default) + return super().get(setting_name, default=default) def raw(self) -> Dict[str, Any]: self.merge(self._config_source.config) self.merge(self._auth_config_source.config) - return super(Config, self).raw() + return super().raw() def all(self) -> Dict[str, Any]: self.merge(self._config_source.config) self.merge(self._auth_config_source.config) - return super(Config, self).all() + return super().all() @pytest.fixture @@ -252,7 +252,7 @@ def _factory( poetry_lock_content=None, install_deps=True, ): - project_dir = workspace / "poetry-fixture-{}".format(name) + project_dir = workspace / f"poetry-fixture-{name}" dependencies = dependencies or {} dev_dependencies = dev_dependencies or {} diff --git a/tests/console/commands/env/conftest.py b/tests/console/commands/env/conftest.py index 22b12f0d44b..e8bda54c8ce 100644 --- a/tests/console/commands/env/conftest.py +++ b/tests/console/commands/env/conftest.py @@ -33,7 +33,7 @@ def venvs_in_cache_dirs( ): directories = [] for version in python_versions: - directory = venv_cache.joinpath("{}-py{}".format(venv_name, version)) + directory = venv_cache.joinpath(f"{venv_name}-py{version}") directory.mkdir(parents=True, exist_ok=True) directories.append(directory.name) return directories diff --git a/tests/console/commands/env/helpers.py b/tests/console/commands/env/helpers.py index b15a68d07a2..cfb01797f37 100644 --- a/tests/console/commands/env/helpers.py +++ b/tests/console/commands/env/helpers.py @@ -14,7 +14,7 @@ def check_output(cmd, *_, **__): if "sys.version_info[:3]" in cmd: return version.text elif "sys.version_info[:2]" in cmd: - return "{}.{}".format(version.major, version.minor) + return f"{version.major}.{version.minor}" else: return str(Path("/prefix")) diff --git a/tests/console/commands/env/test_remove.py b/tests/console/commands/env/test_remove.py index b95419bb6fb..e8503c699cf 100644 --- a/tests/console/commands/env/test_remove.py +++ b/tests/console/commands/env/test_remove.py @@ -20,10 +20,10 @@ def test_remove_by_python_version( tester.execute("3.6") assert check_output.called - assert not (venv_cache / "{}-py3.6".format(venv_name)).exists() + assert not (venv_cache / f"{venv_name}-py3.6").exists() expected = "Deleted virtualenv: {}\n".format( - (venv_cache / "{}-py3.6".format(venv_name)) + venv_cache / f"{venv_name}-py3.6" ) assert expected == tester.io.fetch_output() @@ -36,6 +36,6 @@ def test_remove_by_name(tester, venvs_in_cache_dirs, venv_name, venv_cache): assert not (venv_cache / name).exists() - expected += "Deleted virtualenv: {}\n".format((venv_cache / name)) + expected += f"Deleted virtualenv: {venv_cache / name}\n" assert expected == tester.io.fetch_output() diff --git a/tests/console/commands/env/test_use.py b/tests/console/commands/env/test_use.py index 8b37c8e726e..4895f20e569 100644 --- a/tests/console/commands/env/test_use.py +++ b/tests/console/commands/env/test_use.py @@ -50,7 +50,7 @@ def test_activate_activates_non_existing_virtualenv_no_envs_file( tester.execute("3.7") - venv_py37 = venv_cache / "{}-py3.7".format(venv_name) + venv_py37 = venv_cache / f"{venv_name}-py3.7" mock_build_env.assert_called_with( venv_py37, executable="python3.7", @@ -85,7 +85,7 @@ def test_get_prefers_explicitly_activated_virtualenvs_over_env_var( python_minor = ".".join(str(v) for v in current_python[:2]) python_patch = ".".join(str(v) for v in current_python[:3]) - venv_dir = venv_cache / "{}-py{}".format(venv_name, python_minor) + venv_dir = venv_cache / f"{venv_name}-py{python_minor}" venv_dir.mkdir(parents=True, exist_ok=True) envs_file = TOMLFile(venv_cache / "envs.toml") @@ -110,7 +110,7 @@ def test_get_prefers_explicitly_activated_non_existing_virtualenvs_over_env_var( os.environ["VIRTUAL_ENV"] = "/environment/prefix" python_minor = ".".join(str(v) for v in current_python[:2]) - venv_dir = venv_cache / "{}-py{}".format(venv_name, python_minor) + venv_dir = venv_cache / f"{venv_name}-py{python_minor}" mocker.patch( "poetry.utils.env.EnvManager._env", diff --git a/tests/console/commands/self/test_update.py b/tests/console/commands/self/test_update.py index 5b70b4daefe..f938d124c03 100644 --- a/tests/console/commands/self/test_update.py +++ b/tests/console/commands/self/test_update.py @@ -32,18 +32,18 @@ def test_self_update_should_install_all_necessary_elements( ) mocker.patch.object(command, "_check_recommended_installation", return_value=None) mocker.patch.object( - command, "_get_release_name", return_value="poetry-{}-darwin".format(version) + command, "_get_release_name", return_value=f"poetry-{version}-darwin" ) mocker.patch("subprocess.check_output", return_value=b"Python 3.8.2") http.register_uri( "GET", - command.BASE_URL + "/{}/poetry-{}-darwin.sha256sum".format(version, version), + command.BASE_URL + f"/{version}/poetry-{version}-darwin.sha256sum", body=FIXTURES.joinpath("poetry-1.0.5-darwin.sha256sum").read_bytes(), ) http.register_uri( "GET", - command.BASE_URL + "/{}/poetry-{}-darwin.tar.gz".format(version, version), + command.BASE_URL + f"/{version}/poetry-{version}-darwin.tar.gz", body=FIXTURES.joinpath("poetry-1.0.5-darwin.tar.gz").read_bytes(), ) diff --git a/tests/console/commands/test_add.py b/tests/console/commands/test_add.py index 26955345457..ce7579e89c7 100644 --- a/tests/console/commands/test_add.py +++ b/tests/console/commands/test_add.py @@ -348,7 +348,7 @@ def test_add_directory_with_poetry(app, repo, tester, mocker): repo.add_package(get_package("pendulum", "1.4.4")) path = "../git/github.com/demo/pyproject-demo" - tester.execute("{}".format(path)) + tester.execute(f"{path}") expected = """\ @@ -376,7 +376,7 @@ def test_add_file_constraint_wheel(app, repo, tester, mocker, poetry): repo.add_package(get_package("pendulum", "1.4.4")) path = "../distributions/demo-0.1.0-py2.py3-none-any.whl" - tester.execute("{}".format(path)) + tester.execute(f"{path}") expected = """\ @@ -411,7 +411,7 @@ def test_add_file_constraint_sdist(app, repo, tester, mocker): repo.add_package(get_package("pendulum", "1.4.4")) path = "../distributions/demo-0.1.0.tar.gz" - tester.execute("{}".format(path)) + tester.execute(f"{path}") expected = """\ @@ -586,7 +586,7 @@ def test_add_constraint_with_platform(app, repo, tester, env): repo.add_package(get_package("cachy", "0.1.0")) repo.add_package(cachy2) - tester.execute("cachy=0.2.0 --platform {} -vvv".format(platform)) + tester.execute(f"cachy=0.2.0 --platform {platform} -vvv") expected = """\ @@ -1105,7 +1105,7 @@ def test_add_directory_constraint_old_installer( repo.add_package(get_package("cleo", "0.6.5")) path = "../git/github.com/demo/demo" - old_tester.execute("{}".format(path)) + old_tester.execute(f"{path}") expected = """\ @@ -1141,7 +1141,7 @@ def test_add_directory_with_poetry_old_installer( repo.add_package(get_package("pendulum", "1.4.4")) path = "../git/github.com/demo/pyproject-demo" - old_tester.execute("{}".format(path)) + old_tester.execute(f"{path}") expected = """\ @@ -1172,7 +1172,7 @@ def test_add_file_constraint_wheel_old_installer( repo.add_package(get_package("pendulum", "1.4.4")) path = "../distributions/demo-0.1.0-py2.py3-none-any.whl" - old_tester.execute("{}".format(path)) + old_tester.execute(f"{path}") expected = """\ @@ -1210,7 +1210,7 @@ def test_add_file_constraint_sdist_old_installer( repo.add_package(get_package("pendulum", "1.4.4")) path = "../distributions/demo-0.1.0.tar.gz" - old_tester.execute("{}".format(path)) + old_tester.execute(f"{path}") expected = """\ @@ -1396,7 +1396,7 @@ def test_add_constraint_with_platform_old_installer( repo.add_package(get_package("cachy", "0.1.0")) repo.add_package(cachy2) - old_tester.execute("cachy=0.2.0 --platform {} -vvv".format(platform)) + old_tester.execute(f"cachy=0.2.0 --platform {platform} -vvv") expected = """\ diff --git a/tests/console/commands/test_cache.py b/tests/console/commands/test_cache.py index f33fa9ad31a..fba3ffd7d6f 100644 --- a/tests/console/commands/test_cache.py +++ b/tests/console/commands/test_cache.py @@ -16,12 +16,12 @@ def repository_cache_dir(monkeypatch, tmpdir): @pytest.fixture def repository_one(): - return "01_{}".format(uuid.uuid4()) + return f"01_{uuid.uuid4()}" @pytest.fixture def repository_two(): - return "02_{}".format(uuid.uuid4()) + return f"02_{uuid.uuid4()}" @pytest.fixture diff --git a/tests/console/commands/test_export.py b/tests/console/commands/test_export.py index f5b9fba4a7d..dfc648028b8 100644 --- a/tests/console/commands/test_export.py +++ b/tests/console/commands/test_export.py @@ -1,6 +1,3 @@ -# -*- coding: utf-8 -*- -from __future__ import unicode_literals - import pytest from tests.helpers import get_package diff --git a/tests/console/commands/test_init.py b/tests/console/commands/test_init.py index 4ae13465399..fcad0e41082 100644 --- a/tests/console/commands/test_init.py +++ b/tests/console/commands/test_init.py @@ -647,7 +647,7 @@ def test_init_existing_pyproject_simple( pyproject_file.write_text(decode(existing_section)) tester.execute(inputs=init_basic_inputs) assert ( - "{}\n{}".format(existing_section, init_basic_toml) in pyproject_file.read_text() + f"{existing_section}\n{init_basic_toml}" in pyproject_file.read_text() ) @@ -686,7 +686,7 @@ def test_init_non_interactive_existing_pyproject_add_dependency( [tool.poetry.dev-dependencies] """ - assert "{}\n{}".format(existing_section, expected) in pyproject_file.read_text() + assert f"{existing_section}\n{expected}" in pyproject_file.read_text() def test_init_existing_pyproject_with_build_system_fails( @@ -704,4 +704,4 @@ def test_init_existing_pyproject_with_build_system_fails( tester.io.fetch_output().strip() == "A pyproject.toml file with a defined build-system already exists." ) - assert "{}".format(existing_section) in pyproject_file.read_text() + assert f"{existing_section}" in pyproject_file.read_text() diff --git a/tests/console/commands/test_new.py b/tests/console/commands/test_new.py index 0df5149ae0c..9196ac44076 100644 --- a/tests/console/commands/test_new.py +++ b/tests/console/commands/test_new.py @@ -148,7 +148,7 @@ def test_command_new_with_readme(fmt, tester, tmp_dir): fmt = "md" package = "package" path = Path(tmp_dir) / package - options = ["--readme {}".format(fmt) if fmt else "md", path.as_posix()] + options = [f"--readme {fmt}" if fmt else "md", path.as_posix()] tester.execute(" ".join(options)) poetry = verify_project_directory(path, package, package, None) diff --git a/tests/fixtures/directory/project_with_transitive_directory_dependencies/setup.py b/tests/fixtures/directory/project_with_transitive_directory_dependencies/setup.py index 24a8f05be9f..cfce0806c30 100644 --- a/tests/fixtures/directory/project_with_transitive_directory_dependencies/setup.py +++ b/tests/fixtures/directory/project_with_transitive_directory_dependencies/setup.py @@ -1,4 +1,3 @@ -# -*- coding: utf-8 -*- from distutils.core import setup packages = ["project_with_extras"] diff --git a/tests/fixtures/git/github.com/demo/demo/setup.py b/tests/fixtures/git/github.com/demo/demo/setup.py index faebbc83748..b6f6d0c1f8c 100644 --- a/tests/fixtures/git/github.com/demo/demo/setup.py +++ b/tests/fixtures/git/github.com/demo/demo/setup.py @@ -1,4 +1,3 @@ -# -*- coding: utf-8 -*- from setuptools import setup diff --git a/tests/fixtures/git/github.com/demo/no-dependencies/setup.py b/tests/fixtures/git/github.com/demo/no-dependencies/setup.py index da86b53b2bb..099c69cf976 100644 --- a/tests/fixtures/git/github.com/demo/no-dependencies/setup.py +++ b/tests/fixtures/git/github.com/demo/no-dependencies/setup.py @@ -1,4 +1,3 @@ -# -*- coding: utf-8 -*- from setuptools import setup diff --git a/tests/fixtures/git/github.com/demo/no-version/setup.py b/tests/fixtures/git/github.com/demo/no-version/setup.py index 4e1aea3034c..d14b308cb23 100644 --- a/tests/fixtures/git/github.com/demo/no-version/setup.py +++ b/tests/fixtures/git/github.com/demo/no-version/setup.py @@ -1,4 +1,3 @@ -# -*- coding: utf-8 -*- import ast import os diff --git a/tests/fixtures/git/github.com/demo/non-canonical-name/setup.py b/tests/fixtures/git/github.com/demo/non-canonical-name/setup.py index 3e6da62e986..8004332d6d9 100644 --- a/tests/fixtures/git/github.com/demo/non-canonical-name/setup.py +++ b/tests/fixtures/git/github.com/demo/non-canonical-name/setup.py @@ -1,4 +1,3 @@ -# -*- coding: utf-8 -*- from setuptools import setup diff --git a/tests/fixtures/project_with_setup/setup.py b/tests/fixtures/project_with_setup/setup.py index 0f9e0d095a0..c329347f9bb 100644 --- a/tests/fixtures/project_with_setup/setup.py +++ b/tests/fixtures/project_with_setup/setup.py @@ -1,5 +1,3 @@ -# -*- coding: utf-8 -*- - from setuptools import setup diff --git a/tests/helpers.py b/tests/helpers.py index f1bafd42700..8b48fd9799e 100644 --- a/tests/helpers.py +++ b/tests/helpers.py @@ -96,7 +96,7 @@ def mock_download(url, dest, **__): class TestExecutor(Executor): def __init__(self, *args, **kwargs): - super(TestExecutor, self).__init__(*args, **kwargs) + super().__init__(*args, **kwargs) self._installs = [] self._updates = [] @@ -115,10 +115,10 @@ def removals(self): return self._uninstalls def _do_execute_operation(self, operation): - super(TestExecutor, self)._do_execute_operation(operation) + super()._do_execute_operation(operation) if not operation.skipped: - getattr(self, "_{}s".format(operation.job_type)).append(operation.package) + getattr(self, f"_{operation.job_type}s").append(operation.package) def _execute_install(self, operation): return 0 @@ -132,7 +132,7 @@ def _execute_remove(self, operation): class TestApplication(Application): def __init__(self, poetry): - super(TestApplication, self).__init__() + super().__init__() self._poetry = poetry def reset_poetry(self): @@ -176,7 +176,7 @@ def is_fresh(self): def _write_lock_data(self, data): if self._write: - super(TestLocker, self)._write_lock_data(data) + super()._write_lock_data(data) self._locked = True return @@ -185,9 +185,9 @@ def _write_lock_data(self, data): class TestRepository(Repository): def find_packages(self, dependency): - packages = super(TestRepository, self).find_packages(dependency) + packages = super().find_packages(dependency) if len(packages) == 0: - raise PackageNotFound("Package [{}] not found.".format(dependency.name)) + raise PackageNotFound(f"Package [{dependency.name}] not found.") return packages diff --git a/tests/installation/test_authenticator.py b/tests/installation/test_authenticator.py index 5f756c34f91..f842125c4d6 100644 --- a/tests/installation/test_authenticator.py +++ b/tests/installation/test_authenticator.py @@ -122,7 +122,7 @@ def test_authenticator_uses_empty_strings_as_default_username( def test_authenticator_request_retries_on_exception(mocker, config, http): sleep = mocker.patch("time.sleep") - sdist_uri = "https://foo.bar/files/{}/foo-0.1.0.tar.gz".format(str(uuid.uuid4())) + sdist_uri = f"https://foo.bar/files/{str(uuid.uuid4())}/foo-0.1.0.tar.gz" content = str(uuid.uuid4()) seen = list() @@ -144,7 +144,7 @@ def test_authenticator_request_raises_exception_when_attempts_exhausted( mocker, config, http ): sleep = mocker.patch("time.sleep") - sdist_uri = "https://foo.bar/files/{}/foo-0.1.0.tar.gz".format(str(uuid.uuid4())) + sdist_uri = f"https://foo.bar/files/{str(uuid.uuid4())}/foo-0.1.0.tar.gz" def callback(*_, **__): raise requests.exceptions.ConnectionError(str(uuid.uuid4())) @@ -166,7 +166,7 @@ def test_authenticator_request_retries_on_status_code( mocker, config, http, status, attempts ): sleep = mocker.patch("time.sleep") - sdist_uri = "https://foo.bar/files/{}/foo-0.1.0.tar.gz".format(str(uuid.uuid4())) + sdist_uri = f"https://foo.bar/files/{str(uuid.uuid4())}/foo-0.1.0.tar.gz" content = str(uuid.uuid4()) def callback(request, uri, response_headers): diff --git a/tests/installation/test_executor.py b/tests/installation/test_executor.py index 9b7b413b92b..de3945661fd 100644 --- a/tests/installation/test_executor.py +++ b/tests/installation/test_executor.py @@ -1,6 +1,3 @@ -# -*- coding: utf-8 -*- -from __future__ import unicode_literals - import json import re import shutil diff --git a/tests/installation/test_installer.py b/tests/installation/test_installer.py index 00986905984..7a4e86ecdec 100644 --- a/tests/installation/test_installer.py +++ b/tests/installation/test_installer.py @@ -1,5 +1,3 @@ -from __future__ import unicode_literals - import itertools import json import sys @@ -46,7 +44,7 @@ def _get_installer(self): class Executor(BaseExecutor): def __init__(self, *args, **kwargs): - super(Executor, self).__init__(*args, **kwargs) + super().__init__(*args, **kwargs) self._installs = [] self._updates = [] @@ -65,10 +63,10 @@ def removals(self): return self._uninstalls def _do_execute_operation(self, operation): - super(Executor, self)._do_execute_operation(operation) + super()._do_execute_operation(operation) if not operation.skipped: - getattr(self, "_{}s".format(operation.job_type)).append(operation.package) + getattr(self, f"_{operation.job_type}s").append(operation.package) def _execute_install(self, operation): return 0 @@ -182,7 +180,7 @@ def installer(package, pool, locker, env, installed, config): def fixture(name): - file = TOMLFile(Path(__file__).parent / "fixtures" / "{}.test".format(name)) + file = TOMLFile(Path(__file__).parent / "fixtures" / f"{name}.test") return json.loads(json.dumps(file.read())) @@ -452,7 +450,7 @@ def test_run_install_remove_untracked( *managed_reserved_package_names, } - assert expected_removals == set(r.name for r in installer.executor.removals) + assert expected_removals == {r.name for r in installer.executor.removals} def test_run_whitelist_add(installer, locker, repo, package): diff --git a/tests/installation/test_installer_old.py b/tests/installation/test_installer_old.py index 20936fe5f09..aad0a523815 100644 --- a/tests/installation/test_installer_old.py +++ b/tests/installation/test_installer_old.py @@ -1,5 +1,3 @@ -from __future__ import unicode_literals - import itertools import sys @@ -127,7 +125,7 @@ def installer(package, pool, locker, env, installed, config): def fixture(name): - file = TOMLFile(Path(__file__).parent / "fixtures" / "{}.test".format(name)) + file = TOMLFile(Path(__file__).parent / "fixtures" / f"{name}.test") return file.read() @@ -379,7 +377,7 @@ def test_run_install_remove_untracked( package_c.name, *managed_reserved_package_names, } - assert set(r.name for r in removals) == expected_removals + assert {r.name for r in removals} == expected_removals def test_run_whitelist_add(installer, locker, repo, package): diff --git a/tests/installation/test_pip_installer.py b/tests/installation/test_pip_installer.py index 20fc9d0a9d3..1a274e1effa 100644 --- a/tests/installation/test_pip_installer.py +++ b/tests/installation/test_pip_installer.py @@ -69,7 +69,7 @@ def test_requirement_source_type_url(): ) result = installer.requirement(foo, formatted=True) - expected = "{}#egg={}".format(foo.source_url, foo.name) + expected = f"{foo.source_url}#egg={foo.name}" assert expected == result diff --git a/tests/masonry/builders/test_editable_builder.py b/tests/masonry/builders/test_editable_builder.py index 6fb0a07a445..66e630fa6cb 100644 --- a/tests/masonry/builders/test_editable_builder.py +++ b/tests/masonry/builders/test_editable_builder.py @@ -1,6 +1,3 @@ -# -*- coding: utf-8 -*- -from __future__ import unicode_literals - import os import shutil diff --git a/tests/packages/test_locker.py b/tests/packages/test_locker.py index 285b91a8788..8fac1fd670c 100644 --- a/tests/packages/test_locker.py +++ b/tests/packages/test_locker.py @@ -346,7 +346,7 @@ def test_lock_file_should_not_have_mixed_types(locker, root): def test_reading_lock_file_should_raise_an_error_on_invalid_data(locker): - content = u"""[[package]] + content = """[[package]] name = "A" version = "1.0.0" description = "" diff --git a/tests/repositories/test_legacy_repository.py b/tests/repositories/test_legacy_repository.py index a1db15952e1..cd844068293 100644 --- a/tests/repositories/test_legacy_repository.py +++ b/tests/repositories/test_legacy_repository.py @@ -24,7 +24,7 @@ class MockRepository(LegacyRepository): FIXTURES = Path(__file__).parent / "fixtures" / "legacy" def __init__(self): - super(MockRepository, self).__init__( + super().__init__( "legacy", url="http://legacy.foo.bar", disable_cache=True ) @@ -323,7 +323,7 @@ def test_get_package_retrieves_packages_with_no_hashes(): class MockHttpRepository(LegacyRepository): def __init__(self, endpoint_responses, http): base_url = "http://legacy.foo.bar" - super(MockHttpRepository, self).__init__( + super().__init__( "legacy", url=base_url, disable_cache=True ) diff --git a/tests/repositories/test_pypi_repository.py b/tests/repositories/test_pypi_repository.py index f567314a34c..34e389dbd3a 100644 --- a/tests/repositories/test_pypi_repository.py +++ b/tests/repositories/test_pypi_repository.py @@ -21,7 +21,7 @@ class MockRepository(PyPiRepository): DIST_FIXTURES = Path(__file__).parent / "fixtures" / "pypi.org" / "dists" def __init__(self, fallback=False): - super(MockRepository, self).__init__( + super().__init__( url="http://foo.bar", disable_cache=True, fallback=fallback ) diff --git a/tests/test_factory.py b/tests/test_factory.py index e9a9a9a5994..feb505ae20e 100644 --- a/tests/test_factory.py +++ b/tests/test_factory.py @@ -1,7 +1,3 @@ -# -*- coding: utf-8 -*- -from __future__ import absolute_import -from __future__ import unicode_literals - from pathlib import Path import pytest diff --git a/tests/utils/fixtures/setups/ansible/setup.py b/tests/utils/fixtures/setups/ansible/setup.py index 5d7d1f4ec60..8216f154257 100644 --- a/tests/utils/fixtures/setups/ansible/setup.py +++ b/tests/utils/fixtures/setups/ansible/setup.py @@ -1,5 +1,3 @@ -from __future__ import print_function - import json import os import os.path @@ -63,9 +61,9 @@ def _maintain_symlinks(symlink_type, base_path): try: # Try the cache first because going from git checkout to sdist is the # only time we know that we're going to cache correctly - with open(SYMLINK_CACHE, "r") as f: + with open(SYMLINK_CACHE) as f: symlink_data = json.load(f) - except (IOError, OSError) as e: + except OSError as e: # IOError on py2, OSError on py3. Both have errno if e.errno == 2: # SYMLINKS_CACHE doesn't exist. Fallback to trying to create the @@ -139,7 +137,7 @@ def run(self): def read_file(file_name): """Read file and return its contents.""" - with open(file_name, "r") as f: + with open(file_name) as f: return f.read() diff --git a/tests/utils/fixtures/setups/flask/setup.py b/tests/utils/fixtures/setups/flask/setup.py index 2117d7ccc0a..9eef0653edc 100644 --- a/tests/utils/fixtures/setups/flask/setup.py +++ b/tests/utils/fixtures/setups/flask/setup.py @@ -1,15 +1,14 @@ #!/usr/bin/env python -# -*- coding: utf-8 -*- import io import re from collections import OrderedDict from setuptools import setup -with io.open("README.rst", "rt", encoding="utf8") as f: +with open("README.rst", "rt", encoding="utf8") as f: readme = f.read() -with io.open("flask/__init__.py", "rt", encoding="utf8") as f: +with open("flask/__init__.py", "rt", encoding="utf8") as f: version = re.search(r"__version__ = \'(.*?)\'", f.read()).group(1) setup( diff --git a/tests/utils/fixtures/setups/pendulum/setup.py b/tests/utils/fixtures/setups/pendulum/setup.py index 3a6323fbbdf..4dcbe961465 100644 --- a/tests/utils/fixtures/setups/pendulum/setup.py +++ b/tests/utils/fixtures/setups/pendulum/setup.py @@ -1,4 +1,3 @@ -# -*- coding: utf-8 -*- from distutils.core import setup from build import * diff --git a/tests/utils/fixtures/setups/pyyaml/setup.py b/tests/utils/fixtures/setups/pyyaml/setup.py index 5285386ba55..b443b6c3ad0 100644 --- a/tests/utils/fixtures/setups/pyyaml/setup.py +++ b/tests/utils/fixtures/setups/pyyaml/setup.py @@ -18,7 +18,7 @@ LICENSE = "MIT" PLATFORMS = "Any" URL = "http://pyyaml.org/wiki/PyYAML" -DOWNLOAD_URL = "http://pyyaml.org/download/pyyaml/%s-%s.tar.gz" % (NAME, VERSION) +DOWNLOAD_URL = f"http://pyyaml.org/download/pyyaml/{NAME}-{VERSION}.tar.gz" CLASSIFIERS = [ "Development Status :: 5 - Production/Stable", "Intended Audience :: Developers", @@ -185,7 +185,7 @@ def get_source_files(self): filenames.append(filename) base = os.path.splitext(filename)[0] for ext in ["c", "h", "pyx", "pxd"]: - filename = "%s.%s" % (base, ext) + filename = f"{base}.{ext}" if filename not in filenames and os.path.isfile(filename): filenames.append(filename) return filenames diff --git a/tests/utils/test_env.py b/tests/utils/test_env.py index d09012c821f..da26cbe2172 100644 --- a/tests/utils/test_env.py +++ b/tests/utils/test_env.py @@ -38,7 +38,7 @@ class MockVirtualEnv(VirtualEnv): def __init__(self, path, base=None, sys_path=None): - super(MockVirtualEnv, self).__init__(path, base=base) + super().__init__(path, base=base) self._sys_path = sys_path @@ -47,7 +47,7 @@ def sys_path(self): if self._sys_path is not None: return self._sys_path - return super(MockVirtualEnv, self).sys_path + return super().sys_path @pytest.fixture() @@ -80,7 +80,7 @@ def test_env_commands_with_spaces_in_their_arg_work_as_expected(tmp_dir, manager manager.build_venv(str(venv_path)) venv = VirtualEnv(venv_path) assert venv.run("python", venv.pip, "--version", shell=True).startswith( - "pip {} from ".format(venv.pip_version) + f"pip {venv.pip_version} from " ) @@ -127,7 +127,7 @@ def check_output(cmd, *args, **kwargs): if "sys.version_info[:3]" in cmd: return version.text elif "sys.version_info[:2]" in cmd: - return "{}.{}".format(version.major, version.minor) + return f"{version.major}.{version.minor}" else: return str(Path("/prefix")) @@ -156,7 +156,7 @@ def test_activate_activates_non_existing_virtualenv_no_envs_file( venv_name = EnvManager.generate_env_name("simple-project", str(poetry.file.parent)) m.assert_called_with( - Path(tmp_dir) / "{}-py3.7".format(venv_name), + Path(tmp_dir) / f"{venv_name}-py3.7", executable="python3.7", flags={"always-copy": False, "system-site-packages": False}, with_pip=True, @@ -170,7 +170,7 @@ def test_activate_activates_non_existing_virtualenv_no_envs_file( assert envs[venv_name]["minor"] == "3.7" assert envs[venv_name]["patch"] == "3.7.1" - assert env.path == Path(tmp_dir) / "{}-py3.7".format(venv_name) + assert env.path == Path(tmp_dir) / f"{venv_name}-py3.7" assert env.base == Path("/prefix") @@ -182,7 +182,7 @@ def test_activate_activates_existing_virtualenv_no_envs_file( venv_name = manager.generate_env_name("simple-project", str(poetry.file.parent)) - os.mkdir(os.path.join(tmp_dir, "{}-py3.7".format(venv_name))) + os.mkdir(os.path.join(tmp_dir, f"{venv_name}-py3.7")) config.merge({"virtualenvs": {"path": str(tmp_dir)}}) @@ -206,7 +206,7 @@ def test_activate_activates_existing_virtualenv_no_envs_file( assert envs[venv_name]["minor"] == "3.7" assert envs[venv_name]["patch"] == "3.7.1" - assert env.path == Path(tmp_dir) / "{}-py3.7".format(venv_name) + assert env.path == Path(tmp_dir) / f"{venv_name}-py3.7" assert env.base == Path("/prefix") @@ -223,7 +223,7 @@ def test_activate_activates_same_virtualenv_with_envs_file( doc[venv_name] = {"minor": "3.7", "patch": "3.7.1"} envs_file.write(doc) - os.mkdir(os.path.join(tmp_dir, "{}-py3.7".format(venv_name))) + os.mkdir(os.path.join(tmp_dir, f"{venv_name}-py3.7")) config.merge({"virtualenvs": {"path": str(tmp_dir)}}) @@ -246,7 +246,7 @@ def test_activate_activates_same_virtualenv_with_envs_file( assert envs[venv_name]["minor"] == "3.7" assert envs[venv_name]["patch"] == "3.7.1" - assert env.path == Path(tmp_dir) / "{}-py3.7".format(venv_name) + assert env.path == Path(tmp_dir) / f"{venv_name}-py3.7" assert env.base == Path("/prefix") @@ -262,7 +262,7 @@ def test_activate_activates_different_virtualenv_with_envs_file( doc[venv_name] = {"minor": "3.7", "patch": "3.7.1"} envs_file.write(doc) - os.mkdir(os.path.join(tmp_dir, "{}-py3.7".format(venv_name))) + os.mkdir(os.path.join(tmp_dir, f"{venv_name}-py3.7")) config.merge({"virtualenvs": {"path": str(tmp_dir)}}) @@ -279,7 +279,7 @@ def test_activate_activates_different_virtualenv_with_envs_file( env = manager.activate("python3.6", NullIO()) m.assert_called_with( - Path(tmp_dir) / "{}-py3.6".format(venv_name), + Path(tmp_dir) / f"{venv_name}-py3.6", executable="python3.6", flags={"always-copy": False, "system-site-packages": False}, with_pip=True, @@ -292,7 +292,7 @@ def test_activate_activates_different_virtualenv_with_envs_file( assert envs[venv_name]["minor"] == "3.6" assert envs[venv_name]["patch"] == "3.6.6" - assert env.path == Path(tmp_dir) / "{}-py3.6".format(venv_name) + assert env.path == Path(tmp_dir) / f"{venv_name}-py3.6" assert env.base == Path("/prefix") @@ -308,7 +308,7 @@ def test_activate_activates_recreates_for_different_patch( doc[venv_name] = {"minor": "3.7", "patch": "3.7.0"} envs_file.write(doc) - os.mkdir(os.path.join(tmp_dir, "{}-py3.7".format(venv_name))) + os.mkdir(os.path.join(tmp_dir, f"{venv_name}-py3.7")) config.merge({"virtualenvs": {"path": str(tmp_dir)}}) @@ -336,23 +336,23 @@ def test_activate_activates_recreates_for_different_patch( env = manager.activate("python3.7", NullIO()) build_venv_m.assert_called_with( - Path(tmp_dir) / "{}-py3.7".format(venv_name), + Path(tmp_dir) / f"{venv_name}-py3.7", executable="python3.7", flags={"always-copy": False, "system-site-packages": False}, with_pip=True, with_setuptools=True, with_wheel=True, ) - remove_venv_m.assert_called_with(Path(tmp_dir) / "{}-py3.7".format(venv_name)) + remove_venv_m.assert_called_with(Path(tmp_dir) / f"{venv_name}-py3.7") assert envs_file.exists() envs = envs_file.read() assert envs[venv_name]["minor"] == "3.7" assert envs[venv_name]["patch"] == "3.7.1" - assert env.path == Path(tmp_dir) / "{}-py3.7".format(venv_name) + assert env.path == Path(tmp_dir) / f"{venv_name}-py3.7" assert env.base == Path("/prefix") - assert (Path(tmp_dir) / "{}-py3.7".format(venv_name)).exists() + assert (Path(tmp_dir) / f"{venv_name}-py3.7").exists() def test_activate_does_not_recreate_when_switching_minor( @@ -367,8 +367,8 @@ def test_activate_does_not_recreate_when_switching_minor( doc[venv_name] = {"minor": "3.7", "patch": "3.7.0"} envs_file.write(doc) - os.mkdir(os.path.join(tmp_dir, "{}-py3.7".format(venv_name))) - os.mkdir(os.path.join(tmp_dir, "{}-py3.6".format(venv_name))) + os.mkdir(os.path.join(tmp_dir, f"{venv_name}-py3.7")) + os.mkdir(os.path.join(tmp_dir, f"{venv_name}-py3.6")) config.merge({"virtualenvs": {"path": str(tmp_dir)}}) @@ -397,9 +397,9 @@ def test_activate_does_not_recreate_when_switching_minor( assert envs[venv_name]["minor"] == "3.6" assert envs[venv_name]["patch"] == "3.6.6" - assert env.path == Path(tmp_dir) / "{}-py3.6".format(venv_name) + assert env.path == Path(tmp_dir) / f"{venv_name}-py3.6" assert env.base == Path("/prefix") - assert (Path(tmp_dir) / "{}-py3.6".format(venv_name)).exists() + assert (Path(tmp_dir) / f"{venv_name}-py3.6").exists() def test_deactivate_non_activated_but_existing( @@ -439,17 +439,17 @@ def test_deactivate_activated(tmp_dir, manager, poetry, config, mocker): version = Version.parse(".".join(str(c) for c in sys.version_info[:3])) other_version = Version.parse("3.4") if version.major == 2 else version.next_minor() ( - Path(tmp_dir) / "{}-py{}.{}".format(venv_name, version.major, version.minor) + Path(tmp_dir) / f"{venv_name}-py{version.major}.{version.minor}" ).mkdir() ( Path(tmp_dir) - / "{}-py{}.{}".format(venv_name, other_version.major, other_version.minor) + / f"{venv_name}-py{other_version.major}.{other_version.minor}" ).mkdir() envs_file = TOMLFile(Path(tmp_dir) / "envs.toml") doc = tomlkit.document() doc[venv_name] = { - "minor": "{}.{}".format(other_version.major, other_version.minor), + "minor": f"{other_version.major}.{other_version.minor}", "patch": other_version.text, } envs_file.write(doc) @@ -481,7 +481,7 @@ def test_get_prefers_explicitly_activated_virtualenvs_over_env_var( venv_name = manager.generate_env_name("simple-project", str(poetry.file.parent)) config.merge({"virtualenvs": {"path": str(tmp_dir)}}) - (Path(tmp_dir) / "{}-py3.7".format(venv_name)).mkdir() + (Path(tmp_dir) / f"{venv_name}-py3.7").mkdir() envs_file = TOMLFile(Path(tmp_dir) / "envs.toml") doc = tomlkit.document() @@ -499,7 +499,7 @@ def test_get_prefers_explicitly_activated_virtualenvs_over_env_var( env = manager.get() - assert env.path == Path(tmp_dir) / "{}-py3.7".format(venv_name) + assert env.path == Path(tmp_dir) / f"{venv_name}-py3.7" assert env.base == Path("/prefix") @@ -507,22 +507,22 @@ def test_list(tmp_dir, manager, poetry, config): config.merge({"virtualenvs": {"path": str(tmp_dir)}}) venv_name = manager.generate_env_name("simple-project", str(poetry.file.parent)) - (Path(tmp_dir) / "{}-py3.7".format(venv_name)).mkdir() - (Path(tmp_dir) / "{}-py3.6".format(venv_name)).mkdir() + (Path(tmp_dir) / f"{venv_name}-py3.7").mkdir() + (Path(tmp_dir) / f"{venv_name}-py3.6").mkdir() venvs = manager.list() assert 2 == len(venvs) - assert (Path(tmp_dir) / "{}-py3.6".format(venv_name)) == venvs[0].path - assert (Path(tmp_dir) / "{}-py3.7".format(venv_name)) == venvs[1].path + assert (Path(tmp_dir) / f"{venv_name}-py3.6") == venvs[0].path + assert (Path(tmp_dir) / f"{venv_name}-py3.7") == venvs[1].path def test_remove_by_python_version(tmp_dir, manager, poetry, config, mocker): config.merge({"virtualenvs": {"path": str(tmp_dir)}}) venv_name = manager.generate_env_name("simple-project", str(poetry.file.parent)) - (Path(tmp_dir) / "{}-py3.7".format(venv_name)).mkdir() - (Path(tmp_dir) / "{}-py3.6".format(venv_name)).mkdir() + (Path(tmp_dir) / f"{venv_name}-py3.7").mkdir() + (Path(tmp_dir) / f"{venv_name}-py3.6").mkdir() mocker.patch( "subprocess.check_output", @@ -531,34 +531,34 @@ def test_remove_by_python_version(tmp_dir, manager, poetry, config, mocker): venv = manager.remove("3.6") - assert (Path(tmp_dir) / "{}-py3.6".format(venv_name)) == venv.path - assert not (Path(tmp_dir) / "{}-py3.6".format(venv_name)).exists() + assert (Path(tmp_dir) / f"{venv_name}-py3.6") == venv.path + assert not (Path(tmp_dir) / f"{venv_name}-py3.6").exists() def test_remove_by_name(tmp_dir, manager, poetry, config, mocker): config.merge({"virtualenvs": {"path": str(tmp_dir)}}) venv_name = manager.generate_env_name("simple-project", str(poetry.file.parent)) - (Path(tmp_dir) / "{}-py3.7".format(venv_name)).mkdir() - (Path(tmp_dir) / "{}-py3.6".format(venv_name)).mkdir() + (Path(tmp_dir) / f"{venv_name}-py3.7").mkdir() + (Path(tmp_dir) / f"{venv_name}-py3.6").mkdir() mocker.patch( "subprocess.check_output", side_effect=check_output_wrapper(Version.parse("3.6.6")), ) - venv = manager.remove("{}-py3.6".format(venv_name)) + venv = manager.remove(f"{venv_name}-py3.6") - assert (Path(tmp_dir) / "{}-py3.6".format(venv_name)) == venv.path - assert not (Path(tmp_dir) / "{}-py3.6".format(venv_name)).exists() + assert (Path(tmp_dir) / f"{venv_name}-py3.6") == venv.path + assert not (Path(tmp_dir) / f"{venv_name}-py3.6").exists() def test_remove_also_deactivates(tmp_dir, manager, poetry, config, mocker): config.merge({"virtualenvs": {"path": str(tmp_dir)}}) venv_name = manager.generate_env_name("simple-project", str(poetry.file.parent)) - (Path(tmp_dir) / "{}-py3.7".format(venv_name)).mkdir() - (Path(tmp_dir) / "{}-py3.6".format(venv_name)).mkdir() + (Path(tmp_dir) / f"{venv_name}-py3.7").mkdir() + (Path(tmp_dir) / f"{venv_name}-py3.6").mkdir() mocker.patch( "subprocess.check_output", @@ -572,8 +572,8 @@ def test_remove_also_deactivates(tmp_dir, manager, poetry, config, mocker): venv = manager.remove("python3.6") - assert (Path(tmp_dir) / "{}-py3.6".format(venv_name)) == venv.path - assert not (Path(tmp_dir) / "{}-py3.6".format(venv_name)).exists() + assert (Path(tmp_dir) / f"{venv_name}-py3.6") == venv.path + assert not (Path(tmp_dir) / f"{venv_name}-py3.6").exists() envs = envs_file.read() assert venv_name not in envs @@ -585,7 +585,7 @@ def test_remove_keeps_dir_if_not_deleteable(tmp_dir, manager, poetry, config, mo config.merge({"virtualenvs": {"path": str(tmp_dir)}}) venv_name = manager.generate_env_name("simple-project", str(poetry.file.parent)) - venv_path = Path(tmp_dir) / "{}-py3.6".format(venv_name) + venv_path = Path(tmp_dir) / f"{venv_name}-py3.6" venv_path.mkdir() folder1_path = venv_path / "folder1" @@ -612,7 +612,7 @@ def err_on_rm_venv_only(path, *args, **kwargs): m = mocker.patch("shutil.rmtree", side_effect=err_on_rm_venv_only) - venv = manager.remove("{}-py3.6".format(venv_name)) + venv = manager.remove(f"{venv_name}-py3.6") m.assert_any_call(str(venv_path)) @@ -719,7 +719,7 @@ def test_create_venv_tries_to_find_a_compatible_python_executable_using_generic_ manager.create_venv(NullIO()) m.assert_called_with( - config_virtualenvs_path / "{}-py3.7".format(venv_name), + config_virtualenvs_path / f"{venv_name}-py3.7", executable="python3", flags={"always-copy": False, "system-site-packages": False}, with_pip=True, @@ -746,7 +746,7 @@ def test_create_venv_tries_to_find_a_compatible_python_executable_using_specific manager.create_venv(NullIO()) m.assert_called_with( - config_virtualenvs_path / "{}-py3.9".format(venv_name), + config_virtualenvs_path / f"{venv_name}-py3.9", executable="python3.9", flags={"always-copy": False, "system-site-packages": False}, with_pip=True, @@ -833,7 +833,7 @@ def test_create_venv_uses_patch_version_to_detect_compatibility( assert not check_output.called m.assert_called_with( config_virtualenvs_path - / "{}-py{}.{}".format(venv_name, version.major, version.minor), + / f"{venv_name}-py{version.major}.{version.minor}", executable=None, flags={"always-copy": False, "system-site-packages": False}, with_pip=True, @@ -857,7 +857,7 @@ def test_create_venv_uses_patch_version_to_detect_compatibility_with_executable( check_output = mocker.patch( "subprocess.check_output", side_effect=check_output_wrapper( - Version.parse("{}.{}.0".format(version.major, version.minor - 1)) + Version.parse(f"{version.major}.{version.minor - 1}.0") ), ) m = mocker.patch( @@ -865,14 +865,14 @@ def test_create_venv_uses_patch_version_to_detect_compatibility_with_executable( ) manager.create_venv( - NullIO(), executable="python{}.{}".format(version.major, version.minor - 1) + NullIO(), executable=f"python{version.major}.{version.minor - 1}" ) assert check_output.called m.assert_called_with( config_virtualenvs_path - / "{}-py{}.{}".format(venv_name, version.major, version.minor - 1), - executable="python{}.{}".format(version.major, version.minor - 1), + / f"{venv_name}-py{version.major}.{version.minor - 1}", + executable=f"python{version.major}.{version.minor - 1}", flags={"always-copy": False, "system-site-packages": False}, with_pip=True, with_setuptools=True, From 318c6543fb60b5b260a075dec86e2f7619e84e02 Mon Sep 17 00:00:00 2001 From: Kamyar Ghasemlou Date: Sun, 9 May 2021 00:45:24 +0200 Subject: [PATCH 3/4] black fixes Co-authored-by: Kamyar Ghasemlou Co-authored-by: Harry Peach --- install-poetry.py | 4 +--- poetry/console/commands/cache/clear.py | 4 +--- poetry/console/commands/config.py | 16 ++++------------ poetry/console/commands/init.py | 8 ++------ poetry/factory.py | 4 +--- poetry/inspection/info.py | 4 +--- poetry/puzzle/provider.py | 4 +--- poetry/utils/env.py | 12 +++--------- poetry/utils/shell.py | 4 +--- tests/console/commands/env/test_remove.py | 4 +--- tests/console/commands/test_init.py | 4 +--- tests/repositories/test_legacy_repository.py | 8 ++------ tests/repositories/test_pypi_repository.py | 4 +--- tests/utils/fixtures/setups/flask/setup.py | 4 ++-- tests/utils/test_env.py | 13 ++++--------- 15 files changed, 26 insertions(+), 71 deletions(-) diff --git a/install-poetry.py b/install-poetry.py index c29898bc300..7ab17790315 100644 --- a/install-poetry.py +++ b/install-poetry.py @@ -684,9 +684,7 @@ def _compare_versions(x, y): ) if self._version and self._version not in releases: - self._write( - colorize("error", f"Version {self._version} does not exist.") - ) + self._write(colorize("error", f"Version {self._version} does not exist.")) return None, None diff --git a/poetry/console/commands/cache/clear.py b/poetry/console/commands/cache/clear.py index 07b027ac144..f1be61e0298 100644 --- a/poetry/console/commands/cache/clear.py +++ b/poetry/console/commands/cache/clear.py @@ -55,9 +55,7 @@ def handle(self) -> int: for path, dirs, files in os.walk(str(cache_dir)): entries_count += len(files) - delete = self.confirm( - f"Delete {entries_count} entries?" - ) + delete = self.confirm(f"Delete {entries_count} entries?") if not delete: return 0 diff --git a/poetry/console/commands/config.py b/poetry/console/commands/config.py index 0f1a365019d..0d5b09f9d8a 100644 --- a/poetry/console/commands/config.py +++ b/poetry/console/commands/config.py @@ -140,9 +140,7 @@ def handle(self) -> Optional[int]: else: repo = config.get(f"repositories.{m.group(1)}") if repo is None: - raise ValueError( - f"There is no {m.group(1)} repository defined" - ) + raise ValueError(f"There is no {m.group(1)} repository defined") value = repo @@ -184,22 +182,16 @@ def handle(self) -> Optional[int]: if self.option("unset"): repo = config.get(f"repositories.{m.group(1)}") if repo is None: - raise ValueError( - f"There is no {m.group(1)} repository defined" - ) + raise ValueError(f"There is no {m.group(1)} repository defined") - config.config_source.remove_property( - f"repositories.{m.group(1)}" - ) + config.config_source.remove_property(f"repositories.{m.group(1)}") return 0 if len(values) == 1: url = values[0] - config.config_source.add_property( - f"repositories.{m.group(1)}.url", url - ) + config.config_source.add_property(f"repositories.{m.group(1)}.url", url) return 0 diff --git a/poetry/console/commands/init.py b/poetry/console/commands/init.py index 979c5948566..19e2e011a34 100644 --- a/poetry/console/commands/init.py +++ b/poetry/console/commands/init.py @@ -337,9 +337,7 @@ def _determine_requirements( requirement["version"] = version requirement["name"] = name - self.line( - f"Using version {version} for {name}" - ) + self.line(f"Using version {version} for {name}") else: # check that the specified version/constraint exists # before we proceed @@ -372,9 +370,7 @@ def _find_best_version_for_package( if not package: # TODO: find similar - raise ValueError( - f"Could not find a matching version of package {name}" - ) + raise ValueError(f"Could not find a matching version of package {name}") return package.pretty_name, selector.find_recommended_require_version(package) diff --git a/poetry/factory.py b/poetry/factory.py index 0b1f228675a..ad328002b45 100644 --- a/poetry/factory.py +++ b/poetry/factory.py @@ -51,9 +51,7 @@ def create_poetry( local_config_file = TOMLFile(base_poetry.file.parent / "poetry.toml") if local_config_file.exists(): if io.is_debug(): - io.write_line( - f"Loading configuration file {local_config_file.path}" - ) + io.write_line(f"Loading configuration file {local_config_file.path}") config.merge(local_config_file.read()) diff --git a/poetry/inspection/info.py b/poetry/inspection/info.py index 30e965fa40c..15468416f92 100644 --- a/poetry/inspection/info.py +++ b/poetry/inspection/info.py @@ -44,9 +44,7 @@ class PackageInfoError(ValueError): def __init__( self, path: Union[Path, str], *reasons: Union[BaseException, str] ) -> None: - reasons = ( - f"Unable to determine package info for path: {str(path)}", - ) + reasons + reasons = (f"Unable to determine package info for path: {str(path)}",) + reasons super().__init__("\n\n".join(str(msg).strip() for msg in reasons if msg)) diff --git a/poetry/puzzle/provider.py b/poetry/puzzle/provider.py index 3bcaafd323f..06282a5bb1f 100644 --- a/poetry/puzzle/provider.py +++ b/poetry/puzzle/provider.py @@ -577,9 +577,7 @@ def complete_package(self, package: DependencyPackage) -> DependencyPackage: continue if len(by_constraint) == 1: - self.debug( - f"Merging requirements for {str(deps[0])}" - ) + self.debug(f"Merging requirements for {str(deps[0])}") dependencies.append(list(by_constraint.values())[0][0]) continue diff --git a/poetry/utils/env.py b/poetry/utils/env.py index 20cea57a836..d18f93bc3cf 100644 --- a/poetry/utils/env.py +++ b/poetry/utils/env.py @@ -243,9 +243,7 @@ def distributions( str, self._candidates if not writable_only else self.writable_candidates ) ) - yield from metadata.PathDistribution.discover( - name=name, path=path - ) + yield from metadata.PathDistribution.discover(name=name, path=path) def find_distribution( self, name: str, writable_only: bool = False @@ -873,9 +871,7 @@ def create_venv( return SystemEnv(Path(sys.prefix)) - io.write_line( - f"Creating virtualenv {name} in {str(venv_path)}" - ) + io.write_line(f"Creating virtualenv {name} in {str(venv_path)}") else: create_venv = False if force: @@ -885,9 +881,7 @@ def create_venv( env.path ) ) - io.write_line( - f"Recreating virtualenv {name} in {str(venv)}" - ) + io.write_line(f"Recreating virtualenv {name} in {str(venv)}") self.remove_venv(venv) create_venv = True elif io.is_very_verbose(): diff --git a/poetry/utils/shell.py b/poetry/utils/shell.py index 176f39524e9..3e3c4ec0449 100644 --- a/poetry/utils/shell.py +++ b/poetry/utils/shell.py @@ -79,9 +79,7 @@ def activate(self, env: VirtualEnv) -> None: activate_script = self._get_activate_script() bin_dir = "Scripts" if WINDOWS else "bin" activate_path = env.path / bin_dir / activate_script - c.sendline( - f"{self._get_source_command()} {shlex.quote(str(activate_path))}" - ) + c.sendline(f"{self._get_source_command()} {shlex.quote(str(activate_path))}") def resize(sig: Any, data: Any) -> None: terminal = Terminal() diff --git a/tests/console/commands/env/test_remove.py b/tests/console/commands/env/test_remove.py index e8503c699cf..74123233cb6 100644 --- a/tests/console/commands/env/test_remove.py +++ b/tests/console/commands/env/test_remove.py @@ -22,9 +22,7 @@ def test_remove_by_python_version( assert check_output.called assert not (venv_cache / f"{venv_name}-py3.6").exists() - expected = "Deleted virtualenv: {}\n".format( - venv_cache / f"{venv_name}-py3.6" - ) + expected = "Deleted virtualenv: {}\n".format(venv_cache / f"{venv_name}-py3.6") assert expected == tester.io.fetch_output() diff --git a/tests/console/commands/test_init.py b/tests/console/commands/test_init.py index fcad0e41082..08a46f0f714 100644 --- a/tests/console/commands/test_init.py +++ b/tests/console/commands/test_init.py @@ -646,9 +646,7 @@ def test_init_existing_pyproject_simple( """ pyproject_file.write_text(decode(existing_section)) tester.execute(inputs=init_basic_inputs) - assert ( - f"{existing_section}\n{init_basic_toml}" in pyproject_file.read_text() - ) + assert f"{existing_section}\n{init_basic_toml}" in pyproject_file.read_text() def test_init_non_interactive_existing_pyproject_add_dependency( diff --git a/tests/repositories/test_legacy_repository.py b/tests/repositories/test_legacy_repository.py index cd844068293..b991ff2d10d 100644 --- a/tests/repositories/test_legacy_repository.py +++ b/tests/repositories/test_legacy_repository.py @@ -24,9 +24,7 @@ class MockRepository(LegacyRepository): FIXTURES = Path(__file__).parent / "fixtures" / "legacy" def __init__(self): - super().__init__( - "legacy", url="http://legacy.foo.bar", disable_cache=True - ) + super().__init__("legacy", url="http://legacy.foo.bar", disable_cache=True) def _get(self, endpoint): parts = endpoint.split("/") @@ -323,9 +321,7 @@ def test_get_package_retrieves_packages_with_no_hashes(): class MockHttpRepository(LegacyRepository): def __init__(self, endpoint_responses, http): base_url = "http://legacy.foo.bar" - super().__init__( - "legacy", url=base_url, disable_cache=True - ) + super().__init__("legacy", url=base_url, disable_cache=True) for endpoint, response in endpoint_responses.items(): url = base_url + endpoint diff --git a/tests/repositories/test_pypi_repository.py b/tests/repositories/test_pypi_repository.py index 34e389dbd3a..537272fb49f 100644 --- a/tests/repositories/test_pypi_repository.py +++ b/tests/repositories/test_pypi_repository.py @@ -21,9 +21,7 @@ class MockRepository(PyPiRepository): DIST_FIXTURES = Path(__file__).parent / "fixtures" / "pypi.org" / "dists" def __init__(self, fallback=False): - super().__init__( - url="http://foo.bar", disable_cache=True, fallback=fallback - ) + super().__init__(url="http://foo.bar", disable_cache=True, fallback=fallback) def _get(self, url): parts = url.split("/")[1:] diff --git a/tests/utils/fixtures/setups/flask/setup.py b/tests/utils/fixtures/setups/flask/setup.py index 9eef0653edc..82bd906f8f6 100644 --- a/tests/utils/fixtures/setups/flask/setup.py +++ b/tests/utils/fixtures/setups/flask/setup.py @@ -5,10 +5,10 @@ from setuptools import setup -with open("README.rst", "rt", encoding="utf8") as f: +with open("README.rst", encoding="utf8") as f: readme = f.read() -with open("flask/__init__.py", "rt", encoding="utf8") as f: +with open("flask/__init__.py", encoding="utf8") as f: version = re.search(r"__version__ = \'(.*?)\'", f.read()).group(1) setup( diff --git a/tests/utils/test_env.py b/tests/utils/test_env.py index da26cbe2172..f7b53428b08 100644 --- a/tests/utils/test_env.py +++ b/tests/utils/test_env.py @@ -438,12 +438,9 @@ def test_deactivate_activated(tmp_dir, manager, poetry, config, mocker): venv_name = manager.generate_env_name("simple-project", str(poetry.file.parent)) version = Version.parse(".".join(str(c) for c in sys.version_info[:3])) other_version = Version.parse("3.4") if version.major == 2 else version.next_minor() + (Path(tmp_dir) / f"{venv_name}-py{version.major}.{version.minor}").mkdir() ( - Path(tmp_dir) / f"{venv_name}-py{version.major}.{version.minor}" - ).mkdir() - ( - Path(tmp_dir) - / f"{venv_name}-py{other_version.major}.{other_version.minor}" + Path(tmp_dir) / f"{venv_name}-py{other_version.major}.{other_version.minor}" ).mkdir() envs_file = TOMLFile(Path(tmp_dir) / "envs.toml") @@ -832,8 +829,7 @@ def test_create_venv_uses_patch_version_to_detect_compatibility( assert not check_output.called m.assert_called_with( - config_virtualenvs_path - / f"{venv_name}-py{version.major}.{version.minor}", + config_virtualenvs_path / f"{venv_name}-py{version.major}.{version.minor}", executable=None, flags={"always-copy": False, "system-site-packages": False}, with_pip=True, @@ -870,8 +866,7 @@ def test_create_venv_uses_patch_version_to_detect_compatibility_with_executable( assert check_output.called m.assert_called_with( - config_virtualenvs_path - / f"{venv_name}-py{version.major}.{version.minor - 1}", + config_virtualenvs_path / f"{venv_name}-py{version.major}.{version.minor - 1}", executable=f"python{version.major}.{version.minor - 1}", flags={"always-copy": False, "system-site-packages": False}, with_pip=True, From 62004aa25f77169945a9fdcfbeeac2ee29a5f23b Mon Sep 17 00:00:00 2001 From: Kamyar Ghasemlou Date: Tue, 11 May 2021 22:26:17 +0200 Subject: [PATCH 4/4] remove python 3.5 windows related code Co-authored-by: Kamyar Ghasemlou Co-authored-by: Harry Peach --- poetry/repositories/installed_repository.py | 6 +----- 1 file changed, 1 insertion(+), 5 deletions(-) diff --git a/poetry/repositories/installed_repository.py b/poetry/repositories/installed_repository.py index 841c0a5e610..cf7b5662ca1 100644 --- a/poetry/repositories/installed_repository.py +++ b/poetry/repositories/installed_repository.py @@ -63,11 +63,7 @@ def get_package_paths(cls, env: Env, name: str) -> Set[Path]: if line and not line.startswith(("#", "import ", "import\t")): path = Path(line) if not path.is_absolute(): - try: - path = lib.joinpath(path).resolve() - except FileNotFoundError: - # this is required to handle pathlib oddity on win32 python==3.5 - path = lib.joinpath(path) + path = lib.joinpath(path).resolve() paths.add(path) return paths