Commit c1c74b98 by Branch Vincent Committed by GitHub

chore(commands): remove most type errors (#5113)

parent 8d9fdade
...@@ -97,6 +97,7 @@ force-exclude = ''' ...@@ -97,6 +97,7 @@ force-exclude = '''
[tool.mypy] [tool.mypy]
check_untyped_defs = true check_untyped_defs = true
ignore_missing_imports = true ignore_missing_imports = true
show_error_codes = true
warn_redundant_casts = true warn_redundant_casts = true
warn_unused_configs = true warn_unused_configs = true
warn_unused_ignores = true warn_unused_ignores = true
...@@ -113,29 +114,7 @@ module = [ ...@@ -113,29 +114,7 @@ module = [
'poetry.config.file_config_source', 'poetry.config.file_config_source',
'poetry.console.application', 'poetry.console.application',
'poetry.console.logging.formatters.builder_formatter', 'poetry.console.logging.formatters.builder_formatter',
'poetry.console.commands.add',
'poetry.console.commands.build',
'poetry.console.commands.cache.clear',
'poetry.console.commands.command',
'poetry.console.commands.config',
'poetry.console.commands.debug.resolve',
'poetry.console.commands.end',
'poetry.console.commands.env_command',
'poetry.console.commands.export',
'poetry.console.commands.init', 'poetry.console.commands.init',
'poetry.console.commands.installer_command',
'poetry.console.commands.install',
'poetry.console.commands.lock',
'poetry.console.commands.new',
'poetry.console.commands.plugin.add',
'poetry.console.commands.remove',
'poetry.console.commands.run',
'poetry.console.commands.self.update',
'poetry.console.commands.shell',
'poetry.console.commands.show',
'poetry.console.commands.source.add',
'poetry.console.commands.update',
'poetry.console.commands.version',
'poetry.inspection.info', 'poetry.inspection.info',
'poetry.installation.chef', 'poetry.installation.chef',
'poetry.installation.chooser', 'poetry.installation.chooser',
......
...@@ -2,6 +2,7 @@ import contextlib ...@@ -2,6 +2,7 @@ import contextlib
from typing import Dict from typing import Dict
from typing import List from typing import List
from typing import cast
from cleo.helpers import argument from cleo.helpers import argument
from cleo.helpers import option from cleo.helpers import option
...@@ -236,7 +237,7 @@ You can specify a package in the following forms: ...@@ -236,7 +237,7 @@ You can specify a package in the following forms:
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([cast(str, r["name"]) for r in requirements])
status = self._installer.run() status = self._installer.run()
......
...@@ -79,3 +79,5 @@ class CacheClearCommand(Command): ...@@ -79,3 +79,5 @@ class CacheClearCommand(Command):
cache.forget(f"{package}:{version}") cache.forget(f"{package}:{version}")
else: else:
raise ValueError("Invalid cache key") raise ValueError("Invalid cache key")
return 0
from typing import TYPE_CHECKING from typing import TYPE_CHECKING
from typing import List
from typing import Optional from typing import Optional
from cleo.commands.command import Command as BaseCommand from cleo.commands.command import Command as BaseCommand
...@@ -10,7 +11,7 @@ if TYPE_CHECKING: ...@@ -10,7 +11,7 @@ if TYPE_CHECKING:
class Command(BaseCommand): class Command(BaseCommand):
loggers = [] loggers: List[str] = []
_poetry: Optional["Poetry"] = None _poetry: Optional["Poetry"] = None
......
...@@ -7,6 +7,8 @@ from typing import Dict ...@@ -7,6 +7,8 @@ from typing import Dict
from typing import List from typing import List
from typing import Optional from typing import Optional
from typing import Tuple from typing import Tuple
from typing import Union
from typing import cast
from cleo.helpers import argument from cleo.helpers import argument
from cleo.helpers import option from cleo.helpers import option
...@@ -144,6 +146,7 @@ To remove a repository (repo is a short alias for repositories): ...@@ -144,6 +146,7 @@ To remove a repository (repo is a short alias for repositories):
# show the value if no value is provided # show the value if no value is provided
if not self.argument("value") and not self.option("unset"): if not self.argument("value") and not self.option("unset"):
m = re.match(r"^repos?(?:itories)?(?:\.(.+))?", self.argument("key")) m = re.match(r"^repos?(?:itories)?(?:\.(.+))?", self.argument("key"))
value: Union[str, Dict[str, Any]]
if m: if m:
if not m.group(1): if not m.group(1):
value = {} value = {}
...@@ -158,8 +161,7 @@ To remove a repository (repo is a short alias for repositories): ...@@ -158,8 +161,7 @@ To remove a repository (repo is a short alias for repositories):
self.line(str(value)) self.line(str(value))
else: else:
values = self.unique_config_values if setting_key not in self.unique_config_values:
if setting_key not in values:
raise ValueError(f"There is no {setting_key} setting.") raise ValueError(f"There is no {setting_key} setting.")
value = config.get(setting_key) value = config.get(setting_key)
...@@ -171,7 +173,7 @@ To remove a repository (repo is a short alias for repositories): ...@@ -171,7 +173,7 @@ To remove a repository (repo is a short alias for repositories):
return 0 return 0
values = self.argument("value") values: List[str] = self.argument("value")
unique_config_values = self.unique_config_values unique_config_values = self.unique_config_values
if setting_key in unique_config_values: if setting_key in unique_config_values:
...@@ -297,7 +299,9 @@ To remove a repository (repo is a short alias for repositories): ...@@ -297,7 +299,9 @@ To remove a repository (repo is a short alias for repositories):
return 0 return 0
def _list_configuration(self, config: Dict, raw: Dict, k: str = "") -> None: def _list_configuration(
self, config: Dict[str, Any], raw: Dict[str, Any], k: str = ""
) -> None:
orig_k = k orig_k = k
for key, value in sorted(config.items()): for key, value in sorted(config.items()):
if k + key in self.LIST_PROHIBITED_SETTINGS: if k + key in self.LIST_PROHIBITED_SETTINGS:
...@@ -307,7 +311,7 @@ To remove a repository (repo is a short alias for repositories): ...@@ -307,7 +311,7 @@ To remove a repository (repo is a short alias for repositories):
if isinstance(value, dict): if isinstance(value, dict):
k += f"{key}." k += f"{key}."
self._list_configuration(value, raw_val, k=k) self._list_configuration(value, cast(dict, raw_val), k=k)
k = orig_k k = orig_k
continue continue
...@@ -356,7 +360,7 @@ To remove a repository (repo is a short alias for repositories): ...@@ -356,7 +360,7 @@ To remove a repository (repo is a short alias for repositories):
setting = ".".join(setting.split(".")[1:]) setting = ".".join(setting.split(".")[1:])
values += self._get_setting( values += self._get_setting(
value, k=k, setting=setting, default=default cast(dict, value), k=k, setting=setting, default=default
) )
k = orig_k k = orig_k
......
from typing import TYPE_CHECKING from typing import TYPE_CHECKING
from typing import Optional
from cleo.helpers import argument from cleo.helpers import argument
from cleo.helpers import option from cleo.helpers import option
...@@ -35,7 +34,7 @@ class DebugResolveCommand(InitCommand): ...@@ -35,7 +34,7 @@ class DebugResolveCommand(InitCommand):
loggers = ["poetry.repositories.pypi_repository", "poetry.inspection.info"] loggers = ["poetry.repositories.pypi_repository", "poetry.inspection.info"]
def handle(self) -> Optional[int]: def handle(self) -> int:
from cleo.io.null_io import NullIO from cleo.io.null_io import NullIO
from poetry.core.packages.project_package import ProjectPackage from poetry.core.packages.project_package import ProjectPackage
...@@ -143,4 +142,4 @@ class DebugResolveCommand(InitCommand): ...@@ -143,4 +142,4 @@ class DebugResolveCommand(InitCommand):
table.set_rows(rows) table.set_rows(rows)
table.render() table.render()
return None return 0
from typing import TYPE_CHECKING from typing import TYPE_CHECKING
from typing import Optional
from poetry.console.commands.command import Command from poetry.console.commands.command import Command
...@@ -10,12 +9,13 @@ if TYPE_CHECKING: ...@@ -10,12 +9,13 @@ if TYPE_CHECKING:
class EnvCommand(Command): class EnvCommand(Command):
def __init__(self) -> None: def __init__(self) -> None:
self._env = None # Set in poetry.console.application.Application.configure_installer
self._env: "Env" = None # type: ignore[assignment]
super().__init__() super().__init__()
@property @property
def env(self) -> Optional["Env"]: def env(self) -> "Env":
return self._env return self._env
def set_env(self, env: "Env") -> None: def set_env(self, env: "Env") -> None:
......
...@@ -48,11 +48,11 @@ class ExportCommand(Command): ...@@ -48,11 +48,11 @@ class ExportCommand(Command):
self.line_error("<comment>The lock file does not exist. Locking.</comment>") self.line_error("<comment>The lock file does not exist. Locking.</comment>")
options = [] options = []
if self.io.is_debug(): if self.io.is_debug():
options.append(("-vvv", None)) options.append("-vvv")
elif self.io.is_very_verbose(): elif self.io.is_very_verbose():
options.append(("-vv", None)) options.append("-vv")
elif self.io.is_verbose(): elif self.io.is_verbose():
options.append(("-v", None)) options.append("-v")
self.call("lock", " ".join(options)) self.call("lock", " ".join(options))
......
...@@ -5,6 +5,7 @@ import urllib.parse ...@@ -5,6 +5,7 @@ import urllib.parse
from pathlib import Path from pathlib import Path
from typing import TYPE_CHECKING from typing import TYPE_CHECKING
from typing import Any
from typing import Dict from typing import Dict
from typing import List from typing import List
from typing import Mapping from typing import Mapping
...@@ -20,6 +21,8 @@ from poetry.console.commands.env_command import EnvCommand ...@@ -20,6 +21,8 @@ from poetry.console.commands.env_command import EnvCommand
if TYPE_CHECKING: if TYPE_CHECKING:
from tomlkit.items import InlineTable
from poetry.repositories import Pool from poetry.repositories import Pool
...@@ -61,7 +64,7 @@ The <c1>init</c1> command creates a basic <comment>pyproject.toml</> file in the ...@@ -61,7 +64,7 @@ The <c1>init</c1> command creates a basic <comment>pyproject.toml</> file in the
def __init__(self) -> None: def __init__(self) -> None:
super().__init__() super().__init__()
self._pool = None self._pool: Optional["Pool"] = None
def handle(self) -> int: def handle(self) -> int:
from pathlib import Path from pathlib import Path
...@@ -192,7 +195,7 @@ You can specify a package in the following forms: ...@@ -192,7 +195,7 @@ You can specify a package in the following forms:
if self.io.is_interactive(): if self.io.is_interactive():
self.line("") self.line("")
dev_requirements = {} dev_requirements: Dict[str, str] = {}
if self.option("dev-dependency"): if self.option("dev-dependency"):
dev_requirements = self._format_requirements( dev_requirements = self._format_requirements(
self._determine_requirements(self.option("dev-dependency")) self._determine_requirements(self.option("dev-dependency"))
...@@ -237,6 +240,8 @@ You can specify a package in the following forms: ...@@ -237,6 +240,8 @@ You can specify a package in the following forms:
with (Path.cwd() / "pyproject.toml").open("w", encoding="utf-8") as f: with (Path.cwd() / "pyproject.toml").open("w", encoding="utf-8") as f:
f.write(content) f.write(content)
return 0
def _determine_requirements( def _determine_requirements(
self, self,
requires: List[str], requires: List[str],
...@@ -385,7 +390,7 @@ You can specify a package in the following forms: ...@@ -385,7 +390,7 @@ You can specify a package in the following forms:
return package.pretty_name, selector.find_recommended_require_version(package) return package.pretty_name, selector.find_recommended_require_version(package)
def _parse_requirements(self, requirements: List[str]) -> List[Dict[str, str]]: def _parse_requirements(self, requirements: List[str]) -> List[Dict[str, Any]]:
from poetry.core.pyproject.exceptions import PyProjectException from poetry.core.pyproject.exceptions import PyProjectException
from poetry.puzzle.provider import Provider from poetry.puzzle.provider import Provider
...@@ -476,7 +481,7 @@ You can specify a package in the following forms: ...@@ -476,7 +481,7 @@ You can specify a package in the following forms:
) )
pair = pair.strip() pair = pair.strip()
require = {} require: Dict[str, str] = {}
if " " in pair: if " " in pair:
name, version = pair.split(" ", 2) name, version = pair.split(" ", 2)
extras_m = re.search(r"\[([\w\d,-_]+)\]$", name) extras_m = re.search(r"\[([\w\d,-_]+)\]$", name)
...@@ -521,6 +526,7 @@ You can specify a package in the following forms: ...@@ -521,6 +526,7 @@ You can specify a package in the following forms:
requires = {} requires = {}
for requirement in requirements: for requirement in requirements:
name = requirement.pop("name") name = requirement.pop("name")
constraint: Union[str, "InlineTable"]
if "version" in requirement and len(requirement) == 1: if "version" in requirement and len(requirement) == 1:
constraint = requirement["version"] constraint = requirement["version"]
else: else:
......
from typing import TYPE_CHECKING from typing import TYPE_CHECKING
from typing import Optional
from poetry.console.commands.env_command import EnvCommand from poetry.console.commands.env_command import EnvCommand
...@@ -10,7 +9,8 @@ if TYPE_CHECKING: ...@@ -10,7 +9,8 @@ if TYPE_CHECKING:
class InstallerCommand(EnvCommand): class InstallerCommand(EnvCommand):
def __init__(self) -> None: def __init__(self) -> None:
self._installer: Optional["Installer"] = None # Set in poetry.console.application.Application.configure_installer
self._installer: "Installer" = None # type: ignore[assignment]
super().__init__() super().__init__()
......
...@@ -34,9 +34,9 @@ class NewCommand(Command): ...@@ -34,9 +34,9 @@ class NewCommand(Command):
from poetry.utils.env import SystemEnv from poetry.utils.env import SystemEnv
if self.option("src"): if self.option("src"):
layout_ = layout("src") layout_cls = layout("src")
else: else:
layout_ = layout("standard") layout_cls = layout("standard")
path = Path(self.argument("path")) path = Path(self.argument("path"))
if not path.is_absolute(): if not path.is_absolute():
...@@ -67,7 +67,7 @@ class NewCommand(Command): ...@@ -67,7 +67,7 @@ class NewCommand(Command):
current_env = SystemEnv(Path(sys.executable)) current_env = SystemEnv(Path(sys.executable))
default_python = "^" + ".".join(str(v) for v in current_env.version_info[:2]) default_python = "^" + ".".join(str(v) for v in current_env.version_info[:2])
layout_ = layout_( layout_ = layout_cls(
name, name,
"0.1.0", "0.1.0",
author=author, author=author,
......
...@@ -115,13 +115,16 @@ You can specify a package in the following forms: ...@@ -115,13 +115,16 @@ You can specify a package in the following forms:
break break
root_package.python_versions = ".".join( root_package.python_versions = ".".join( # type: ignore[union-attr]
str(v) for v in system_env.version_info[:3] str(v) for v in system_env.version_info[:3]
) )
# We create a `pyproject.toml` file based on all the information # We create a `pyproject.toml` file based on all the information
# we have about the current environment. # we have about the current environment.
if not env_dir.joinpath("pyproject.toml").exists(): if not env_dir.joinpath("pyproject.toml").exists():
Factory.create_pyproject_from_package(root_package, env_dir) Factory.create_pyproject_from_package(
root_package, # type: ignore[arg-type]
env_dir,
)
# We add the plugins to the dependencies section of the previously # We add the plugins to the dependencies section of the previously
# created `pyproject.toml` file # created `pyproject.toml` file
......
...@@ -83,8 +83,8 @@ list of installed packages ...@@ -83,8 +83,8 @@ list of installed packages
if "group" in poetry_content and not poetry_content["group"]: if "group" in poetry_content and not poetry_content["group"]:
del poetry_content["group"] del poetry_content["group"]
removed = set(removed) removed_set = set(removed)
not_found = set(packages).difference(removed) not_found = set(packages).difference(removed_set)
if not_found: if not_found:
raise ValueError( raise ValueError(
"The following packages were not found: " + ", ".join(sorted(not_found)) "The following packages were not found: " + ", ".join(sorted(not_found))
...@@ -104,7 +104,7 @@ list of installed packages ...@@ -104,7 +104,7 @@ list of installed packages
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)
self._installer.whitelist(removed) self._installer.whitelist(removed_set)
status = self._installer.run() status = self._installer.run()
......
from typing import TYPE_CHECKING from typing import TYPE_CHECKING
from typing import Any from typing import Any
from typing import Dict
from typing import Union from typing import Union
from cleo.helpers import argument from cleo.helpers import argument
...@@ -41,7 +42,7 @@ class RunCommand(EnvCommand): ...@@ -41,7 +42,7 @@ class RunCommand(EnvCommand):
return module return module
def run_script(self, script: Union[str, dict], args: str) -> Any: def run_script(self, script: Union[str, Dict[str, str]], args: str) -> Any:
if isinstance(script, dict): if isinstance(script, dict):
script = script["callable"] script = script["callable"]
......
...@@ -57,8 +57,9 @@ class SelfUpdateCommand(Command): ...@@ -57,8 +57,9 @@ class SelfUpdateCommand(Command):
from poetry.utils._compat import WINDOWS from poetry.utils._compat import WINDOWS
if os.getenv("POETRY_HOME"): home = os.getenv("POETRY_HOME")
return Path(os.getenv("POETRY_HOME"), "bin").expanduser() if home:
return Path(home, "bin").expanduser()
user_base = site.getuserbase() user_base = site.getuserbase()
...@@ -102,13 +103,12 @@ class SelfUpdateCommand(Command): ...@@ -102,13 +103,12 @@ class SelfUpdateCommand(Command):
self.line("No release found for the specified version") self.line("No release found for the specified version")
return 1 return 1
packages.sort( def cmp(x: "Package", y: "Package") -> int:
key=cmp_to_key( if x.version == y.version:
lambda x, y: 0 return 0
if x.version == y.version return int(x.version < y.version or -1)
else int(x.version < y.version or -1)
) packages.sort(key=cmp_to_key(cmp))
)
release = None release = None
for package in packages: for package in packages:
......
...@@ -35,5 +35,5 @@ If one doesn't exist yet, it will be created. ...@@ -35,5 +35,5 @@ If one doesn't exist yet, it will be created.
# 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) shell.activate(self.env) # type: ignore[arg-type]
environ.pop("POETRY_ACTIVE") environ.pop("POETRY_ACTIVE")
...@@ -64,7 +64,7 @@ class SourceAddCommand(Command): ...@@ -64,7 +64,7 @@ class SourceAddCommand(Command):
) )
return 1 return 1
new_source = Source( new_source: Optional[Source] = Source(
name=name, url=url, default=is_default, secondary=is_secondary name=name, url=url, default=is_default, secondary=is_secondary
) )
existing_sources = self.poetry.get_sources() existing_sources = self.poetry.get_sources()
...@@ -86,7 +86,7 @@ class SourceAddCommand(Command): ...@@ -86,7 +86,7 @@ class SourceAddCommand(Command):
) )
return 1 return 1
if source.name == name: if new_source and source.name == name:
self.line(f"Source with name <c1>{name}</c1> already exists. Updating.") self.line(f"Source with name <c1>{name}</c1> already exists. Updating.")
source = new_source source = new_source
new_source = None new_source = None
......
...@@ -80,27 +80,27 @@ patch, minor, major, prepatch, preminor, premajor, prerelease. ...@@ -80,27 +80,27 @@ patch, minor, major, prepatch, preminor, premajor, prerelease.
from poetry.core.semver.version import Version from poetry.core.semver.version import Version
try: try:
version = Version.parse(version) parsed = Version.parse(version)
except ValueError: except ValueError:
raise ValueError("The project's version doesn't seem to follow semver") raise ValueError("The project's version doesn't seem to follow semver")
if rule in {"major", "premajor"}: if rule in {"major", "premajor"}:
new = version.next_major() new = parsed.next_major()
if rule == "premajor": if rule == "premajor":
new = new.first_prerelease() new = new.first_prerelease()
elif rule in {"minor", "preminor"}: elif rule in {"minor", "preminor"}:
new = version.next_minor() new = parsed.next_minor()
if rule == "preminor": if rule == "preminor":
new = new.first_prerelease() new = new.first_prerelease()
elif rule in {"patch", "prepatch"}: elif rule in {"patch", "prepatch"}:
new = version.next_patch() new = parsed.next_patch()
if rule == "prepatch": if rule == "prepatch":
new = new.first_prerelease() new = new.first_prerelease()
elif rule == "prerelease": elif rule == "prerelease":
if version.is_unstable(): if parsed.is_unstable():
new = Version(version.epoch, version.release, version.pre.next()) new = Version(parsed.epoch, parsed.release, parsed.pre.next())
else: else:
new = version.next_patch().first_prerelease() new = parsed.next_patch().first_prerelease()
else: else:
new = Version.parse(rule) new = Version.parse(rule)
......
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