Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

chore(commands): remove most type errors #5113

Merged
merged 2 commits into from
Jan 27, 2022
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
23 changes: 1 addition & 22 deletions pyproject.toml
Original file line number Diff line number Diff line change
Expand Up @@ -97,6 +97,7 @@ force-exclude = '''
[tool.mypy]
check_untyped_defs = true
ignore_missing_imports = true
show_error_codes = true
Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

this shows error codes, which was useful for our flake8 lint that requires type: ignore[error-code]

warn_redundant_casts = true
warn_unused_configs = true
warn_unused_ignores = true
Expand All @@ -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',
Expand Down
3 changes: 2 additions & 1 deletion src/poetry/console/commands/add.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@

from typing import Dict
from typing import List
from typing import cast

from cleo.helpers import argument
from cleo.helpers import option
Expand Down Expand Up @@ -236,7 +237,7 @@ def handle(self) -> int:
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])
Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

reached for a cast here as requirements is too loosely typed as Dict[str, Union[str, List[str]]]. planning to tighten that up after removing all ignored files

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

That's kind of what I expected, sounds good.


status = self._installer.run()

Expand Down
2 changes: 2 additions & 0 deletions src/poetry/console/commands/cache/clear.py
Original file line number Diff line number Diff line change
Expand Up @@ -79,3 +79,5 @@ def handle(self) -> int:
cache.forget(f"{package}:{version}")
else:
raise ValueError("Invalid cache key")

return 0
3 changes: 2 additions & 1 deletion src/poetry/console/commands/command.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
from typing import TYPE_CHECKING
from typing import List
from typing import Optional

from cleo.commands.command import Command as BaseCommand
Expand All @@ -10,7 +11,7 @@


class Command(BaseCommand):
loggers = []
loggers: List[str] = []

_poetry: Optional["Poetry"] = None

Expand Down
16 changes: 10 additions & 6 deletions src/poetry/console/commands/config.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,8 @@
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
Expand Down Expand Up @@ -144,6 +146,7 @@ def handle(self) -> Optional[int]:
# 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 = {}
Expand All @@ -158,8 +161,7 @@ def handle(self) -> Optional[int]:

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)
Expand All @@ -171,7 +173,7 @@ def handle(self) -> Optional[int]:

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:
Expand Down Expand Up @@ -297,7 +299,9 @@ def _handle_single_value(

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:
Expand All @@ -307,7 +311,7 @@ def _list_configuration(self, config: Dict, raw: Dict, k: str = "") -> None:

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
Expand Down Expand Up @@ -356,7 +360,7 @@ def _get_setting(
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

Expand Down
5 changes: 2 additions & 3 deletions src/poetry/console/commands/debug/resolve.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,4 @@
from typing import TYPE_CHECKING
from typing import Optional

from cleo.helpers import argument
from cleo.helpers import option
Expand Down Expand Up @@ -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

Expand Down Expand Up @@ -143,4 +142,4 @@ def handle(self) -> Optional[int]:
table.set_rows(rows)
table.render()

return None
return 0
6 changes: 3 additions & 3 deletions src/poetry/console/commands/env_command.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,4 @@
from typing import TYPE_CHECKING
from typing import Optional

from poetry.console.commands.command import Command

Expand All @@ -10,12 +9,13 @@

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:
Expand Down
6 changes: 3 additions & 3 deletions src/poetry/console/commands/export.py
Original file line number Diff line number Diff line change
Expand Up @@ -48,11 +48,11 @@ def handle(self) -> None:
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")
Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Found a bug here 😄

$ rm poetry.lock && poetry export -vv
...
  TypeError

  sequence item 0: expected str instance, tuple found
  at src/poetry/console/commands/export.py:57 in handle
       53│                 options.append(("-vv", None))
       54│             elif self.io.is_verbose():
       55│                 options.append(("-v", None))
       56│ 
    →  57│             self.call("lock", " ".join(options))
       58│ 
       59│         if not locker.is_fresh():
       60│             self.line_error(
       61│                 ""

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))

Expand Down
14 changes: 10 additions & 4 deletions src/poetry/console/commands/init.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@

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
Expand All @@ -20,6 +21,8 @@


if TYPE_CHECKING:
from tomlkit.items import InlineTable

from poetry.repositories import Pool


Expand Down Expand Up @@ -61,7 +64,7 @@ class InitCommand(Command):
def __init__(self) -> None:
super().__init__()

self._pool = None
self._pool: Optional["Pool"] = None

def handle(self) -> int:
from pathlib import Path
Expand Down Expand Up @@ -192,7 +195,7 @@ def handle(self) -> int:
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"))
Expand Down Expand Up @@ -237,6 +240,8 @@ def handle(self) -> int:
with (Path.cwd() / "pyproject.toml").open("w", encoding="utf-8") as f:
f.write(content)

return 0

def _determine_requirements(
self,
requires: List[str],
Expand Down Expand Up @@ -385,7 +390,7 @@ def _find_best_version_for_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.puzzle.provider import Provider
Expand Down Expand Up @@ -476,7 +481,7 @@ def _parse_requirements(self, requirements: List[str]) -> List[Dict[str, str]]:
)
pair = pair.strip()

require = {}
require: Dict[str, str] = {}
if " " in pair:
name, version = pair.split(" ", 2)
extras_m = re.search(r"\[([\w\d,-_]+)\]$", name)
Expand Down Expand Up @@ -521,6 +526,7 @@ def _format_requirements(
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:
Expand Down
4 changes: 2 additions & 2 deletions src/poetry/console/commands/installer_command.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,4 @@
from typing import TYPE_CHECKING
from typing import Optional

from poetry.console.commands.env_command import EnvCommand

Expand All @@ -10,7 +9,8 @@

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__()

Expand Down
6 changes: 3 additions & 3 deletions src/poetry/console/commands/new.py
Original file line number Diff line number Diff line change
Expand Up @@ -34,9 +34,9 @@ def handle(self) -> None:
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():
Expand Down Expand Up @@ -67,7 +67,7 @@ def handle(self) -> None:
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,
Expand Down
7 changes: 5 additions & 2 deletions src/poetry/console/commands/plugin/add.py
Original file line number Diff line number Diff line change
Expand Up @@ -115,13 +115,16 @@ def handle(self) -> int:

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
Expand Down
6 changes: 3 additions & 3 deletions src/poetry/console/commands/remove.py
Original file line number Diff line number Diff line change
Expand Up @@ -83,8 +83,8 @@ def handle(self) -> int:
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))
Expand All @@ -104,7 +104,7 @@ def handle(self) -> int:
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()

Expand Down
3 changes: 2 additions & 1 deletion src/poetry/console/commands/run.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
from typing import TYPE_CHECKING
from typing import Any
from typing import Dict
from typing import Union

from cleo.helpers import argument
Expand Down Expand Up @@ -41,7 +42,7 @@ def _module(self) -> "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):
script = script["callable"]

Expand Down
18 changes: 9 additions & 9 deletions src/poetry/console/commands/self/update.py
Original file line number Diff line number Diff line change
Expand Up @@ -57,8 +57,9 @@ def bin_dir(self) -> Path:

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()

Expand Down Expand Up @@ -102,13 +103,12 @@ def handle(self) -> int:
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:
Expand Down
2 changes: 1 addition & 1 deletion src/poetry/console/commands/shell.py
Original file line number Diff line number Diff line change
Expand Up @@ -35,5 +35,5 @@ def handle(self) -> None:
# 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")
Loading