Commit c1c74b98 by Branch Vincent Committed by GitHub

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

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