Commit a49372a5 by danieleades Committed by GitHub

fix: misc type errors (#4024)

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