Commit 7fa563f0 by David Hotham Committed by GitHub

Misc typing fixes (#6021)

* remove unnecessary annotations

* os.path.relpath accepts a Path

* simpler handling and typechecking of cachecontrol

* remove unneeded type assertion

* os.path.exists accepts a Path

* tighten the handling of env on commands

* tighten handling of installer on commands

* tighten handling of environment in poetry shell

* tighten typechecking in authenticator
parent 13f18079
...@@ -285,7 +285,7 @@ class Application(BaseApplication): # type: ignore[misc] ...@@ -285,7 +285,7 @@ class Application(BaseApplication): # type: ignore[misc]
if not isinstance(command, EnvCommand): if not isinstance(command, EnvCommand):
return return
if command.env is not None: if command._env is not None:
return return
from poetry.utils.env import EnvManager from poetry.utils.env import EnvManager
...@@ -313,7 +313,7 @@ class Application(BaseApplication): # type: ignore[misc] ...@@ -313,7 +313,7 @@ class Application(BaseApplication): # type: ignore[misc]
# If the command already has an installer # If the command already has an installer
# we skip this step # we skip this step
if command.installer is not None: if command._installer is not None:
return return
cls.configure_installer_for_command(command, event.io) cls.configure_installer_for_command(command, event.io)
......
...@@ -234,21 +234,21 @@ The add command adds required packages to your <comment>pyproject.toml</> and in ...@@ -234,21 +234,21 @@ The add command adds required packages to your <comment>pyproject.toml</> and in
self.poetry.set_locker( self.poetry.set_locker(
self.poetry.locker.__class__(self.poetry.locker.lock.path, poetry_content) self.poetry.locker.__class__(self.poetry.locker.lock.path, poetry_content)
) )
self._installer.set_locker(self.poetry.locker) self.installer.set_locker(self.poetry.locker)
# Cosmetic new line # Cosmetic new line
self.line("") self.line("")
self._installer.set_package(self.poetry.package) self.installer.set_package(self.poetry.package)
self._installer.dry_run(self.option("dry-run")) self.installer.dry_run(self.option("dry-run"))
self._installer.verbose(self.io.is_verbose()) self.installer.verbose(self.io.is_verbose())
self._installer.update(True) self.installer.update(True)
if self.option("lock"): if self.option("lock"):
self._installer.lock() self.installer.lock()
self._installer.whitelist([r["name"] for r in requirements]) self.installer.whitelist([r["name"] for r in requirements])
status = self._installer.run() status = self.installer.run()
if status == 0 and not self.option("dry-run"): if status == 0 and not self.option("dry-run"):
assert isinstance(content, TOMLDocument) assert isinstance(content, TOMLDocument)
......
...@@ -46,7 +46,7 @@ class CacheClearCommand(Command): ...@@ -46,7 +46,7 @@ class CacheClearCommand(Command):
f"Add the --all option if you want to clear all {parts[0]} caches" f"Add the --all option if you want to clear all {parts[0]} caches"
) )
if not os.path.exists(str(cache_dir)): if not os.path.exists(cache_dir):
self.line(f"No cache entries for {parts[0]}") self.line(f"No cache entries for {parts[0]}")
return 0 return 0
......
...@@ -11,13 +11,14 @@ if TYPE_CHECKING: ...@@ -11,13 +11,14 @@ if TYPE_CHECKING:
class EnvCommand(Command): class EnvCommand(Command):
def __init__(self) -> None: def __init__(self) -> None:
# Set in poetry.console.application.Application.configure_installer # Set in poetry.console.application.Application.configure_env
self._env: Env = None # type: ignore[assignment] self._env: Env | None = None
super().__init__() super().__init__()
@property @property
def env(self) -> Env: def env(self) -> Env:
assert self._env is not None
return self._env return self._env
def set_env(self, env: Env) -> None: def set_env(self, env: Env) -> None:
......
...@@ -84,7 +84,7 @@ dependencies and not including the current project, run the command with the ...@@ -84,7 +84,7 @@ dependencies and not including the current project, run the command with the
from poetry.masonry.builders.editable import EditableBuilder from poetry.masonry.builders.editable import EditableBuilder
self._installer.use_executor( self.installer.use_executor(
self.poetry.config.get("experimental.new-installer", False) self.poetry.config.get("experimental.new-installer", False)
) )
...@@ -125,7 +125,7 @@ dependencies and not including the current project, run the command with the ...@@ -125,7 +125,7 @@ dependencies and not including the current project, run the command with the
else: else:
extras.append(extra) extras.append(extra)
self._installer.extras(extras) self.installer.extras(extras)
with_synchronization = self.option("sync") with_synchronization = self.option("sync")
if self.option("remove-untracked"): if self.option("remove-untracked"):
...@@ -137,12 +137,12 @@ dependencies and not including the current project, run the command with the ...@@ -137,12 +137,12 @@ dependencies and not including the current project, run the command with the
with_synchronization = True with_synchronization = True
self._installer.only_groups(self.activated_groups) self.installer.only_groups(self.activated_groups)
self._installer.dry_run(self.option("dry-run")) self.installer.dry_run(self.option("dry-run"))
self._installer.requires_synchronization(with_synchronization) self.installer.requires_synchronization(with_synchronization)
self._installer.verbose(self.io.is_verbose()) self.installer.verbose(self.io.is_verbose())
return_code = self._installer.run() return_code = self.installer.run()
if return_code != 0: if return_code != 0:
return return_code return return_code
...@@ -151,7 +151,7 @@ dependencies and not including the current project, run the command with the ...@@ -151,7 +151,7 @@ dependencies and not including the current project, run the command with the
return 0 return 0
try: try:
builder = EditableBuilder(self.poetry, self._env, self.io) builder = EditableBuilder(self.poetry, self.env, self.io)
except ModuleOrPackageNotFound: except ModuleOrPackageNotFound:
# This is likely due to the fact that the project is an application # This is likely due to the fact that the project is an application
# not following the structure expected by Poetry # not following the structure expected by Poetry
......
...@@ -12,18 +12,19 @@ if TYPE_CHECKING: ...@@ -12,18 +12,19 @@ if TYPE_CHECKING:
class InstallerCommand(GroupCommand): class InstallerCommand(GroupCommand):
def __init__(self) -> None: def __init__(self) -> None:
# Set in poetry.console.application.Application.configure_installer # Set in poetry.console.application.Application.configure_installer
self._installer: Installer = None # type: ignore[assignment] self._installer: Installer | None = None
super().__init__() super().__init__()
def reset_poetry(self) -> None: def reset_poetry(self) -> None:
super().reset_poetry() super().reset_poetry()
self._installer.set_package(self.poetry.package) self.installer.set_package(self.poetry.package)
self._installer.set_locker(self.poetry.locker) self.installer.set_locker(self.poetry.locker)
@property @property
def installer(self) -> Installer: def installer(self) -> Installer:
assert self._installer is not None
return self._installer return self._installer
def set_installer(self, installer: Installer) -> None: def set_installer(self, installer: Installer) -> None:
......
...@@ -33,7 +33,7 @@ file. ...@@ -33,7 +33,7 @@ file.
loggers = ["poetry.repositories.pypi_repository"] loggers = ["poetry.repositories.pypi_repository"]
def handle(self) -> int: def handle(self) -> int:
self._installer.use_executor( self.installer.use_executor(
self.poetry.config.get("experimental.new-installer", False) self.poetry.config.get("experimental.new-installer", False)
) )
...@@ -49,6 +49,6 @@ file. ...@@ -49,6 +49,6 @@ file.
) )
return 1 return 1
self._installer.lock(update=not self.option("no-update")) self.installer.lock(update=not self.option("no-update"))
return self._installer.run() return self.installer.run()
...@@ -100,15 +100,15 @@ list of installed packages ...@@ -100,15 +100,15 @@ list of installed packages
self.poetry.set_locker( self.poetry.set_locker(
self.poetry.locker.__class__(self.poetry.locker.lock.path, poetry_content) self.poetry.locker.__class__(self.poetry.locker.lock.path, poetry_content)
) )
self._installer.set_locker(self.poetry.locker) self.installer.set_locker(self.poetry.locker)
self._installer.set_package(self.poetry.package) self.installer.set_package(self.poetry.package)
self._installer.dry_run(self.option("dry-run", False)) self.installer.dry_run(self.option("dry-run", False))
self._installer.verbose(self.io.is_verbose()) self.installer.verbose(self.io.is_verbose())
self._installer.update(True) self.installer.update(True)
self._installer.whitelist(removed_set) self.installer.whitelist(removed_set)
status = self._installer.run() status = self.installer.run()
if not self.option("dry-run") and status == 0: if not self.option("dry-run") and status == 0:
assert isinstance(content, TOMLDocument) assert isinstance(content, TOMLDocument)
......
...@@ -46,6 +46,7 @@ class SelfCommand(InstallerCommand): ...@@ -46,6 +46,7 @@ class SelfCommand(InstallerCommand):
def env(self) -> Env: def env(self) -> Env:
if not isinstance(self._env, SystemEnv): if not isinstance(self._env, SystemEnv):
self.reset_env() self.reset_env()
assert self._env is not None
return self._env return self._env
@property @property
......
...@@ -4,10 +4,16 @@ import sys ...@@ -4,10 +4,16 @@ import sys
from distutils.util import strtobool from distutils.util import strtobool
from os import environ from os import environ
from typing import TYPE_CHECKING
from typing import cast
from poetry.console.commands.env_command import EnvCommand from poetry.console.commands.env_command import EnvCommand
if TYPE_CHECKING:
from poetry.utils.env import VirtualEnv
class ShellCommand(EnvCommand): class ShellCommand(EnvCommand):
name = "shell" name = "shell"
description = "Spawns a shell within the virtual environment." description = "Spawns a shell within the virtual environment."
...@@ -33,10 +39,15 @@ If one doesn't exist yet, it will be created. ...@@ -33,10 +39,15 @@ If one doesn't exist yet, it will be created.
self.line(f"Spawning shell within <info>{self.env.path}</>") self.line(f"Spawning shell within <info>{self.env.path}</>")
# Be sure that we have the right type of environment.
env = self.env
assert env.is_venv()
env = cast("VirtualEnv", env)
# Setting this to avoid spawning unnecessary nested shells # Setting this to avoid spawning unnecessary nested shells
environ["POETRY_ACTIVE"] = "1" environ["POETRY_ACTIVE"] = "1"
shell = Shell.get() shell = Shell.get()
shell.activate(self.env) # type: ignore[arg-type] shell.activate(env)
environ.pop("POETRY_ACTIVE") environ.pop("POETRY_ACTIVE")
return 0 return 0
...@@ -37,18 +37,18 @@ class UpdateCommand(InstallerCommand): ...@@ -37,18 +37,18 @@ class UpdateCommand(InstallerCommand):
def handle(self) -> int: def handle(self) -> int:
packages = self.argument("packages") packages = self.argument("packages")
self._installer.use_executor( self.installer.use_executor(
self.poetry.config.get("experimental.new-installer", False) self.poetry.config.get("experimental.new-installer", False)
) )
if packages: if packages:
self._installer.whitelist({name: "*" for name in packages}) self.installer.whitelist({name: "*" for name in packages})
self._installer.only_groups(self.activated_groups) self.installer.only_groups(self.activated_groups)
self._installer.dry_run(self.option("dry-run")) self.installer.dry_run(self.option("dry-run"))
self._installer.execute_operations(not self.option("lock")) self.installer.execute_operations(not self.option("lock"))
# Force update # Force update
self._installer.update(True) self.installer.update(True)
return self._installer.run() return self.installer.run()
...@@ -463,7 +463,6 @@ class Executor: ...@@ -463,7 +463,6 @@ class Executor:
if package.source_type == "git": if package.source_type == "git":
return self._install_git(operation) return self._install_git(operation)
archive: Path
if package.source_type == "file": if package.source_type == "file":
archive = self._prepare_file(operation) archive = self._prepare_file(operation)
elif package.source_type == "url": elif package.source_type == "url":
...@@ -617,7 +616,6 @@ class Executor: ...@@ -617,7 +616,6 @@ class Executor:
def _download_link(self, operation: Install | Update, link: Link) -> Path: def _download_link(self, operation: Install | Update, link: Link) -> Path:
package = operation.package package = operation.package
archive: Path | None
archive = self._chef.get_cached_archive_for_link(link) archive = self._chef.get_cached_archive_for_link(link)
if archive is None: if archive is None:
# No cached distributions was found, so we download and prepare it # No cached distributions was found, so we download and prepare it
...@@ -681,7 +679,7 @@ class Executor: ...@@ -681,7 +679,7 @@ class Executor:
progress.start() progress.start()
done = 0 done = 0
archive: Path = self._chef.get_cache_directory_for_link(link) / link.filename archive = self._chef.get_cache_directory_for_link(link) / link.filename
archive.parent.mkdir(parents=True, exist_ok=True) archive.parent.mkdir(parents=True, exist_ok=True)
with archive.open("wb") as f: with archive.open("wb") as f:
for chunk in response.iter_content(chunk_size=4096): for chunk in response.iter_content(chunk_size=4096):
......
...@@ -425,8 +425,8 @@ class Locker: ...@@ -425,8 +425,8 @@ class Locker:
# The lock file should only store paths relative to the root project # The lock file should only store paths relative to the root project
url = Path( url = Path(
os.path.relpath( os.path.relpath(
Path(url).resolve().as_posix(), Path(url).resolve(),
Path(self._lock.path.parent).resolve().as_posix(), Path(self._lock.path.parent).resolve(),
) )
).as_posix() ).as_posix()
......
...@@ -131,18 +131,10 @@ class Authenticator: ...@@ -131,18 +131,10 @@ class Authenticator:
self._get_repository_config_for_url self._get_repository_config_for_url
) )
@property
def cache(self) -> FileCache | None:
return self._cache_control
@property
def is_cached(self) -> bool:
return self._cache_control is not None
def create_session(self) -> requests.Session: def create_session(self) -> requests.Session:
session = requests.Session() session = requests.Session()
if not self.is_cached: if self._cache_control is None:
return session return session
session = CacheControl(sess=session, cache=self._cache_control) session = CacheControl(sess=session, cache=self._cache_control)
...@@ -171,7 +163,7 @@ class Authenticator: ...@@ -171,7 +163,7 @@ class Authenticator:
self.close() self.close()
def delete_cache(self, url: str) -> None: def delete_cache(self, url: str) -> None:
if self.is_cached: if self._cache_control is not None:
self._cache_control.delete(key=url) self._cache_control.delete(key=url)
def authenticated_url(self, url: str) -> str: def authenticated_url(self, url: str) -> str:
...@@ -202,12 +194,12 @@ class Authenticator: ...@@ -202,12 +194,12 @@ class Authenticator:
session = self.get_session(url=url) session = self.get_session(url=url)
prepared_request = session.prepare_request(request) prepared_request = session.prepare_request(request)
proxies = kwargs.get("proxies", {}) proxies: dict[str, str] = kwargs.get("proxies", {})
stream = kwargs.get("stream") stream: bool | None = kwargs.get("stream")
certs = self.get_certs_for_url(url) certs = self.get_certs_for_url(url)
verify = kwargs.get("verify") or certs.cert or certs.verify verify: bool | str | Path = kwargs.get("verify") or certs.cert or certs.verify
cert = kwargs.get("cert") or certs.client_cert cert: str | Path | None = kwargs.get("cert") or certs.client_cert
if cert is not None: if cert is not None:
cert = str(cert) cert = str(cert)
......
...@@ -120,7 +120,7 @@ def get_package_version_display_string( ...@@ -120,7 +120,7 @@ def get_package_version_display_string(
) -> str: ) -> str:
if package.source_type in ["file", "directory"] and root: if package.source_type in ["file", "directory"] and root:
assert package.source_url is not None assert package.source_url is not None
path = Path(os.path.relpath(package.source_url, root.as_posix())).as_posix() path = Path(os.path.relpath(package.source_url, root)).as_posix()
return f"{package.version} {path}" return f"{package.version} {path}"
pretty_version: str = package.full_pretty_version pretty_version: str = package.full_pretty_version
......
...@@ -160,7 +160,6 @@ class Git: ...@@ -160,7 +160,6 @@ class Git:
url = "" url = ""
if config.has_section(section): if config.has_section(section):
value = config.get(section, b"url") value = config.get(section, b"url")
assert isinstance(value, bytes)
url = value.decode("utf-8") url = value.decode("utf-8")
return url return url
......
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment