Commit a49372a5 by danieleades Committed by GitHub

fix: misc type errors (#4024)

parent 8786f1de
...@@ -21,3 +21,4 @@ class CacheListCommand(Command): ...@@ -21,3 +21,4 @@ class CacheListCommand(Command):
return 0 return 0
self.line("<warning>No caches found</>") self.line("<warning>No caches found</>")
return None
...@@ -166,7 +166,8 @@ To remove a repository (repo is a short alias for repositories): ...@@ -166,7 +166,8 @@ To remove a repository (repo is a short alias for repositories):
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:
if self.option("unset"): if self.option("unset"):
return config.config_source.remove_property(setting_key) config.config_source.remove_property(setting_key)
return None
return self._handle_single_value( return self._handle_single_value(
config.config_source, config.config_source,
......
...@@ -143,3 +143,5 @@ class DebugResolveCommand(InitCommand): ...@@ -143,3 +143,5 @@ class DebugResolveCommand(InitCommand):
table.set_rows(rows) table.set_rows(rows)
table.render() table.render()
return None
...@@ -28,9 +28,10 @@ class EnvInfoCommand(Command): ...@@ -28,9 +28,10 @@ class EnvInfoCommand(Command):
self.line(str(env.path)) self.line(str(env.path))
return return None
self._display_complete_info(env) self._display_complete_info(env)
return None
def _display_complete_info(self, env: "Env") -> None: def _display_complete_info(self, env: "Env") -> None:
env_python_version = ".".join(str(s) for s in env.version_info[:3]) env_python_version = ".".join(str(s) for s in env.version_info[:3])
......
from typing import TYPE_CHECKING from typing import Optional
from .command import Command
from poetry.utils.env import Env
if TYPE_CHECKING: from .command import Command
from poetry.utils.env import Env
class EnvCommand(Command): class EnvCommand(Command):
...@@ -14,8 +12,8 @@ class EnvCommand(Command): ...@@ -14,8 +12,8 @@ class EnvCommand(Command):
super(EnvCommand, self).__init__() super(EnvCommand, self).__init__()
@property @property
def env(self) -> "Env": def env(self) -> Optional[Env]:
return self._env return self._env
def set_env(self, env: "Env") -> None: def set_env(self, env: Env) -> None:
self._env = env self._env = env
...@@ -7,6 +7,7 @@ from pathlib import Path ...@@ -7,6 +7,7 @@ from pathlib import Path
from typing import TYPE_CHECKING from typing import TYPE_CHECKING
from typing import Dict from typing import Dict
from typing import List from typing import List
from typing import Mapping
from typing import Optional from typing import Optional
from typing import Tuple from typing import Tuple
from typing import Union from typing import Union
...@@ -515,7 +516,7 @@ The <c1>init</c1> command creates a basic <comment>pyproject.toml</> file in the ...@@ -515,7 +516,7 @@ The <c1>init</c1> command creates a basic <comment>pyproject.toml</> file in the
def _format_requirements( def _format_requirements(
self, requirements: List[Dict[str, str]] self, requirements: List[Dict[str, str]]
) -> Dict[str, Union[str, Dict[str, str]]]: ) -> Mapping[str, Union[str, Mapping[str, str]]]:
requires = {} requires = {}
for requirement in requirements: for requirement in requirements:
name = requirement.pop("name") name = requirement.pop("name")
...@@ -536,7 +537,7 @@ The <c1>init</c1> command creates a basic <comment>pyproject.toml</> file in the ...@@ -536,7 +537,7 @@ The <c1>init</c1> command creates a basic <comment>pyproject.toml</> file in the
author = author or default author = author or default
if author in ["n", "no"]: if author in ["n", "no"]:
return return None
m = AUTHOR_REGEX.match(author) m = AUTHOR_REGEX.match(author)
if not m: if not m:
......
...@@ -83,3 +83,5 @@ the config command. ...@@ -83,3 +83,5 @@ the config command.
client_cert, client_cert,
self.option("dry-run"), self.option("dry-run"),
) )
return None
...@@ -346,6 +346,7 @@ lists all packages available.""" ...@@ -346,6 +346,7 @@ lists all packages available."""
line += " " + description line += " " + description
self.line(line) self.line(line)
return None
def display_package_tree( def display_package_tree(
self, io: "IO", package: "Package", installed_repo: "Repository" self, io: "IO", package: "Package", installed_repo: "Repository"
......
...@@ -397,11 +397,12 @@ class PackageInfo: ...@@ -397,11 +397,12 @@ class PackageInfo:
# handle PKG-INFO in unpacked sdist root # handle PKG-INFO in unpacked sdist root
dist = pkginfo.UnpackedSDist(path.as_posix()) dist = pkginfo.UnpackedSDist(path.as_posix())
except ValueError: except ValueError:
return return None
info = cls._from_distribution(dist=dist) info = cls._from_distribution(dist=dist)
if info: if info:
return info return info
return None
@classmethod @classmethod
def from_package(cls, package: Package) -> "PackageInfo": def from_package(cls, package: Package) -> "PackageInfo":
...@@ -432,6 +433,7 @@ class PackageInfo: ...@@ -432,6 +433,7 @@ class PackageInfo:
# TODO: add support for handling non-poetry PEP-517 builds # TODO: add support for handling non-poetry PEP-517 builds
if PyProjectTOML(path.joinpath("pyproject.toml")).is_poetry_project(): if PyProjectTOML(path.joinpath("pyproject.toml")).is_poetry_project():
return Factory().create_poetry(path).package return Factory().create_poetry(path).package
return None
@classmethod @classmethod
def _pep517_metadata(cls, path: Path) -> "PackageInfo": def _pep517_metadata(cls, path: Path) -> "PackageInfo":
......
...@@ -2,6 +2,7 @@ from typing import TYPE_CHECKING ...@@ -2,6 +2,7 @@ from typing import TYPE_CHECKING
from typing import Iterable from typing import Iterable
from typing import List from typing import List
from typing import Optional from typing import Optional
from typing import Sequence
from typing import Union from typing import Union
from cleo.io.io import IO from cleo.io.io import IO
...@@ -499,7 +500,7 @@ class Installer: ...@@ -499,7 +500,7 @@ class Installer:
self._installer.remove(operation.package) self._installer.remove(operation.package)
def _populate_local_repo( def _populate_local_repo(
self, local_repo: Repository, ops: List[Operation] self, local_repo: Repository, ops: Sequence[Operation]
) -> None: ) -> None:
for op in ops: for op in ops:
if isinstance(op, Uninstall): if isinstance(op, Uninstall):
...@@ -514,7 +515,7 @@ class Installer: ...@@ -514,7 +515,7 @@ class Installer:
def _get_operations_from_lock( def _get_operations_from_lock(
self, locked_repository: Repository self, locked_repository: Repository
) -> List[Operation]: ) -> Sequence[Operation]:
installed_repo = self._installed_repository installed_repo = self._installed_repository
ops = [] ops = []
...@@ -543,7 +544,7 @@ class Installer: ...@@ -543,7 +544,7 @@ class Installer:
return ops return ops
def _filter_operations(self, ops: List[Operation], repo: Repository) -> None: def _filter_operations(self, ops: Sequence[Operation], repo: Repository) -> None:
extra_packages = self._get_extra_packages(repo) extra_packages = self._get_extra_packages(repo)
for op in ops: for op in ops:
if isinstance(op, Update): if isinstance(op, Update):
......
from typing import Callable
from typing import Dict from typing import Dict
from typing import Iterator from typing import Iterator
from typing import List from typing import List
...@@ -272,18 +273,18 @@ class Incompatibility: ...@@ -272,18 +273,18 @@ class Incompatibility:
other_line: Optional[int], other_line: Optional[int],
) -> Optional[str]: ) -> Optional[str]:
if len(self._terms) == 1 or len(other.terms) == 1: if len(self._terms) == 1 or len(other.terms) == 1:
return return None
this_positive = self._single_term_where(lambda term: term.is_positive()) this_positive = self._single_term_where(lambda term: term.is_positive())
if this_positive is None: if this_positive is None:
return return None
other_positive = other._single_term_where(lambda term: term.is_positive()) other_positive = other._single_term_where(lambda term: term.is_positive())
if other_positive is None: if other_positive is None:
return return None
if this_positive.dependency != other_positive.dependency: if this_positive.dependency != other_positive.dependency:
return return None
this_negatives = " or ".join( this_negatives = " or ".join(
[self._terse(term) for term in self._terms if not term.is_positive()] [self._terse(term) for term in self._terms if not term.is_positive()]
...@@ -318,13 +319,13 @@ class Incompatibility: ...@@ -318,13 +319,13 @@ class Incompatibility:
self, other: "Incompatibility", details: dict, this_line: int, other_line: int self, other: "Incompatibility", details: dict, this_line: int, other_line: int
) -> Optional[str]: ) -> Optional[str]:
if len(self._terms) == 1 or len(other.terms) == 1: if len(self._terms) == 1 or len(other.terms) == 1:
return return None
this_negative = self._single_term_where(lambda term: not term.is_positive()) this_negative = self._single_term_where(lambda term: not term.is_positive())
other_negative = other._single_term_where(lambda term: not term.is_positive()) other_negative = other._single_term_where(lambda term: not term.is_positive())
if this_negative is None and other_negative is None: if this_negative is None and other_negative is None:
return return None
this_positive = self._single_term_where(lambda term: term.is_positive()) this_positive = self._single_term_where(lambda term: term.is_positive())
other_positive = self._single_term_where(lambda term: term.is_positive()) other_positive = self._single_term_where(lambda term: term.is_positive())
...@@ -352,7 +353,7 @@ class Incompatibility: ...@@ -352,7 +353,7 @@ class Incompatibility:
latter = self latter = self
latter_line = this_line latter_line = this_line
else: else:
return return None
prior_positives = [term for term in prior.terms if term.is_positive()] prior_positives = [term for term in prior.terms if term.is_positive()]
...@@ -411,10 +412,10 @@ class Incompatibility: ...@@ -411,10 +412,10 @@ class Incompatibility:
negative = prior._single_term_where(lambda term: not term.is_positive()) negative = prior._single_term_where(lambda term: not term.is_positive())
if negative is None: if negative is None:
return return None
if not negative.inverse.satisfies(latter.terms[0]): if not negative.inverse.satisfies(latter.terms[0]):
return return None
positives = [t for t in prior.terms if t.is_positive()] positives = [t for t in prior.terms if t.is_positive()]
...@@ -459,14 +460,14 @@ class Incompatibility: ...@@ -459,14 +460,14 @@ class Incompatibility:
term.dependency.pretty_name, term.dependency.pretty_constraint term.dependency.pretty_name, term.dependency.pretty_constraint
) )
def _single_term_where(self, callable: callable) -> Optional[Term]: def _single_term_where(self, callable: Callable[[Term], bool]) -> Optional[Term]:
found = None found = None
for term in self._terms: for term in self._terms:
if not callable(term): if not callable(term):
continue continue
if found is not None: if found is not None:
return return None
found = term found = term
......
...@@ -138,7 +138,7 @@ class Term: ...@@ -138,7 +138,7 @@ class Term:
elif self.is_positive() != other.is_positive(): elif self.is_positive() != other.is_positive():
return self if self.is_positive() else other return self if self.is_positive() else other
else: else:
return return None
def difference(self, other: "Term") -> "Term": def difference(self, other: "Term") -> "Term":
""" """
...@@ -158,7 +158,7 @@ class Term: ...@@ -158,7 +158,7 @@ class Term:
self, constraint: "VersionTypes", is_positive: bool self, constraint: "VersionTypes", is_positive: bool
) -> Optional["Term"]: ) -> Optional["Term"]:
if constraint.is_empty(): if constraint.is_empty():
return return None
return Term(self.dependency.with_constraint(constraint), is_positive) return Term(self.dependency.with_constraint(constraint), is_positive)
......
...@@ -131,7 +131,7 @@ class VersionSolver: ...@@ -131,7 +131,7 @@ class VersionSolver:
def _propagate_incompatibility( def _propagate_incompatibility(
self, incompatibility: Incompatibility self, incompatibility: Incompatibility
) -> Optional[Union[str, object]]: ) -> Union[str, object, None]:
""" """
If incompatibility is almost satisfied by _solution, adds the If incompatibility is almost satisfied by _solution, adds the
negation of the unsatisfied term to _solution. negation of the unsatisfied term to _solution.
...@@ -154,12 +154,12 @@ class VersionSolver: ...@@ -154,12 +154,12 @@ class VersionSolver:
# If term is already contradicted by _solution, then # If term is already contradicted by _solution, then
# incompatibility is contradicted as well and there's nothing new we # incompatibility is contradicted as well and there's nothing new we
# can deduce from it. # can deduce from it.
return return None
elif relation == SetRelation.OVERLAPPING: elif relation == SetRelation.OVERLAPPING:
# If more than one term is inconclusive, we can't deduce anything about # If more than one term is inconclusive, we can't deduce anything about
# incompatibility. # incompatibility.
if unsatisfied is not None: if unsatisfied is not None:
return return None
# If exactly one term in incompatibility is inconclusive, then it's # If exactly one term in incompatibility is inconclusive, then it's
# almost satisfied and [term] is the unsatisfied term. We can add the # almost satisfied and [term] is the unsatisfied term. We can add the
...@@ -324,7 +324,7 @@ class VersionSolver: ...@@ -324,7 +324,7 @@ class VersionSolver:
""" """
unsatisfied = self._solution.unsatisfied unsatisfied = self._solution.unsatisfied
if not unsatisfied: if not unsatisfied:
return return None
# Prefer packages with as few remaining versions as possible, # Prefer packages with as few remaining versions as possible,
# so that if a conflict is necessary it's forced quickly. # so that if a conflict is necessary it's forced quickly.
...@@ -449,14 +449,14 @@ class VersionSolver: ...@@ -449,14 +449,14 @@ class VersionSolver:
def _get_locked(self, dependency: Dependency) -> Optional[Package]: def _get_locked(self, dependency: Dependency) -> Optional[Package]:
if dependency.name in self._use_latest: if dependency.name in self._use_latest:
return return None
locked = self._locked.get(dependency.name) locked = self._locked.get(dependency.name)
if not locked: if not locked:
return return None
if not dependency.is_same_package_as(locked): if not dependency.is_same_package_as(locked):
return return None
return locked return locked
......
...@@ -12,7 +12,7 @@ if TYPE_CHECKING: ...@@ -12,7 +12,7 @@ if TYPE_CHECKING:
class ProjectPackage(_ProjectPackage): class ProjectPackage(_ProjectPackage):
def set_version( def set_version(
self, version: Union[str, "Version"], pretty_version: Optional[str] = None self, version: Union[str, "Version"], pretty_version: Optional[str] = None
) -> "ProjectPackage": ) -> None:
from poetry.core.semver.version import Version # noqa from poetry.core.semver.version import Version # noqa
if not isinstance(version, Version): if not isinstance(version, Version):
......
...@@ -85,7 +85,7 @@ class Provider: ...@@ -85,7 +85,7 @@ class Provider:
self._load_deferred = load_deferred self._load_deferred = load_deferred
@contextmanager @contextmanager
def use_environment(self, env: Env) -> "Provider": def use_environment(self, env: Env) -> Iterator["Provider"]:
original_env = self._env original_env = self._env
original_python_constraint = self._python_constraint original_python_constraint = self._python_constraint
......
...@@ -7,6 +7,7 @@ from typing import TYPE_CHECKING ...@@ -7,6 +7,7 @@ from typing import TYPE_CHECKING
from typing import Callable from typing import Callable
from typing import Dict from typing import Dict
from typing import FrozenSet from typing import FrozenSet
from typing import Iterator
from typing import List from typing import List
from typing import Optional from typing import Optional
from typing import Tuple from typing import Tuple
...@@ -65,7 +66,7 @@ class Solver: ...@@ -65,7 +66,7 @@ class Solver:
return self._provider return self._provider
@contextmanager @contextmanager
def use_environment(self, env: Env) -> None: def use_environment(self, env: Env) -> Iterator[None]:
with self.provider.use_environment(env): with self.provider.use_environment(env):
yield yield
......
...@@ -144,14 +144,14 @@ class Page: ...@@ -144,14 +144,14 @@ class Page:
info, ext = link.splitext() info, ext = link.splitext()
match = self.VERSION_REGEX.match(info) match = self.VERSION_REGEX.match(info)
if not match: if not match:
return return None
version = match.group(2) version = match.group(2)
try: try:
version = Version.parse(version) version = Version.parse(version)
except ValueError: except ValueError:
return return None
return version return version
...@@ -428,9 +428,9 @@ class LegacyRepository(PyPiRepository): ...@@ -428,9 +428,9 @@ class LegacyRepository(PyPiRepository):
f"Authorization error accessing {url}", f"Authorization error accessing {url}",
level="warning", level="warning",
) )
return return None
if response.status_code == 404: if response.status_code == 404:
return return None
response.raise_for_status() response.raise_for_status()
except requests.HTTPError as e: except requests.HTTPError as e:
raise RepositoryError(e) raise RepositoryError(e)
......
...@@ -111,7 +111,7 @@ class Repository(BaseRepository): ...@@ -111,7 +111,7 @@ class Repository(BaseRepository):
return [] return []
def search(self, query: str) -> List["Package"]: def search(self, query: str) -> List["Package"]:
results = [] results: List["Package"] = []
for package in self.packages: for package in self.packages:
if query in package.name: if query in package.name:
......
...@@ -148,7 +148,7 @@ class Authenticator: ...@@ -148,7 +148,7 @@ class Authenticator:
else: else:
url = self._config.get(f"repositories.{name}.url") url = self._config.get(f"repositories.{name}.url")
if not url: if not url:
return return None
parsed_url = urllib.parse.urlsplit(url) parsed_url = urllib.parse.urlsplit(url)
......
...@@ -1229,11 +1229,13 @@ class Env: ...@@ -1229,11 +1229,13 @@ class Env:
def usersite(self) -> Optional[Path]: def usersite(self) -> Optional[Path]:
if "usersite" in self.paths: if "usersite" in self.paths:
return Path(self.paths["usersite"]) return Path(self.paths["usersite"])
return None
@property @property
def userbase(self) -> Optional[Path]: def userbase(self) -> Optional[Path]:
if "userbase" in self.paths: if "userbase" in self.paths:
return Path(self.paths["userbase"]) return Path(self.paths["userbase"])
return None
@property @property
def purelib(self) -> Path: def purelib(self) -> Path:
...@@ -1337,7 +1339,7 @@ class Env: ...@@ -1337,7 +1339,7 @@ class Env:
cmd = pip + list(args) cmd = pip + list(args)
return self._run(cmd, **kwargs) return self._run(cmd, **kwargs)
def run_python_script(self, content: str, **kwargs: Any) -> str: def run_python_script(self, content: str, **kwargs: Any) -> Union[int, str]:
return self.run(self._executable, "-W", "ignore", "-", input_=content, **kwargs) return self.run(self._executable, "-W", "ignore", "-", input_=content, **kwargs)
def _run(self, cmd: List[str], **kwargs: Any) -> Union[int, str]: def _run(self, cmd: List[str], **kwargs: Any) -> Union[int, str]:
...@@ -1428,7 +1430,7 @@ class Env: ...@@ -1428,7 +1430,7 @@ class Env:
return str(bin_path) return str(bin_path)
def __eq__(self, other: "Env") -> bool: def __eq__(self, other: object) -> bool:
return other.__class__ == self.__class__ and other.path == self.path return other.__class__ == self.__class__ and other.path == self.path
def __repr__(self) -> str: def __repr__(self) -> str:
...@@ -1774,17 +1776,19 @@ class NullEnv(SystemEnv): ...@@ -1774,17 +1776,19 @@ class NullEnv(SystemEnv):
self.pip_embedded if embedded else self.pip, self.pip_embedded if embedded else self.pip,
] ]
def _run(self, cmd: List[str], **kwargs: Any) -> int: def _run(self, cmd: List[str], **kwargs: Any) -> Optional[int]:
self.executed.append(cmd) self.executed.append(cmd)
if self._execute: if self._execute:
return super()._run(cmd, **kwargs) return super()._run(cmd, **kwargs)
return None
def execute(self, bin: str, *args: str, **kwargs: Any) -> Optional[int]: def execute(self, bin: str, *args: str, **kwargs: Any) -> Optional[int]:
self.executed.append([bin] + list(args)) self.executed.append([bin] + list(args))
if self._execute: if self._execute:
return super().execute(bin, *args, **kwargs) return super().execute(bin, *args, **kwargs)
return None
def _bin(self, bin: str) -> str: def _bin(self, bin: str) -> str:
return bin return bin
......
...@@ -14,7 +14,7 @@ def get_extra_package_names( ...@@ -14,7 +14,7 @@ def get_extra_package_names(
packages: Sequence["Package"], packages: Sequence["Package"],
extras: Mapping[str, List[str]], extras: Mapping[str, List[str]],
extra_names: Sequence[str], extra_names: Sequence[str],
) -> Iterator[str]: ) -> Iterable[str]:
""" """
Returns all package names required by the given extras. Returns all package names required by the given extras.
......
...@@ -33,7 +33,7 @@ class KeyRing: ...@@ -33,7 +33,7 @@ class KeyRing:
def get_password(self, name: str, username: str) -> Optional[str]: def get_password(self, name: str, username: str) -> Optional[str]:
if not self.is_available(): if not self.is_available():
return return None
import keyring import keyring
import keyring.errors import keyring.errors
...@@ -125,7 +125,7 @@ class PasswordManager: ...@@ -125,7 +125,7 @@ class PasswordManager:
self._keyring = None self._keyring = None
@property @property
def keyring(self) -> KeyRing: def keyring(self) -> Optional[KeyRing]:
if self._keyring is None: if self._keyring is None:
self._keyring = KeyRing("poetry-repository") self._keyring = KeyRing("poetry-repository")
if not self._keyring.is_available(): if not self._keyring.is_available():
......
...@@ -293,25 +293,25 @@ class SetupReader: ...@@ -293,25 +293,25 @@ class SetupReader:
kwargs = self._find_call_kwargs(call) kwargs = self._find_call_kwargs(call)
if kwargs is None or not isinstance(kwargs, ast.Name): if kwargs is None or not isinstance(kwargs, ast.Name):
return return None
variable = self._find_variable_in_body(body, kwargs.id) variable = self._find_variable_in_body(body, kwargs.id)
if not isinstance(variable, (ast.Dict, ast.Call)): if not isinstance(variable, (ast.Dict, ast.Call)):
return return None
if isinstance(variable, ast.Call): if isinstance(variable, ast.Call):
if not isinstance(variable.func, ast.Name): if not isinstance(variable.func, ast.Name):
return return None
if variable.func.id != "dict": if variable.func.id != "dict":
return return None
value = self._find_in_call(variable, name) value = self._find_in_call(variable, name)
else: else:
value = self._find_in_dict(variable, name) value = self._find_in_dict(variable, name)
if value is None: if value is None:
return return None
if isinstance(value, ast.Str): if isinstance(value, ast.Str):
return value.s return value.s
...@@ -325,6 +325,7 @@ class SetupReader: ...@@ -325,6 +325,7 @@ class SetupReader:
for keyword in call.keywords: for keyword in call.keywords:
if keyword.arg == name: if keyword.arg == name:
return keyword.value return keyword.value
return None
def _find_call_kwargs(self, call: ast.Call) -> Optional[Any]: def _find_call_kwargs(self, call: ast.Call) -> Optional[Any]:
kwargs = None kwargs = None
...@@ -356,3 +357,4 @@ class SetupReader: ...@@ -356,3 +357,4 @@ class SetupReader:
for key, val in zip(dict_.keys, dict_.values): for key, val in zip(dict_.keys, dict_.values):
if isinstance(key, ast.Str) and key.s == name: if isinstance(key, ast.Str) and key.s == name:
return val return val
return None
...@@ -4,6 +4,7 @@ import sys ...@@ -4,6 +4,7 @@ import sys
from pathlib import Path from pathlib import Path
from typing import Any from typing import Any
from typing import Optional
import pexpect import pexpect
...@@ -61,7 +62,7 @@ class Shell: ...@@ -61,7 +62,7 @@ class Shell:
return cls._shell return cls._shell
def activate(self, env: VirtualEnv) -> None: def activate(self, env: VirtualEnv) -> Optional[int]:
if WINDOWS: if WINDOWS:
return env.execute(self.path) return env.execute(self.path)
......
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