Skip to content
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
1 change: 1 addition & 0 deletions news/10159.trivial.rst
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
Complete the type annotations from ``pip/_internal/utils``.
9 changes: 3 additions & 6 deletions src/pip/_internal/utils/appdirs.py
Original file line number Diff line number Diff line change
Expand Up @@ -12,13 +12,11 @@
from pip._vendor import appdirs as _appdirs


def user_cache_dir(appname):
# type: (str) -> str
def user_cache_dir(appname: str) -> str:
return _appdirs.user_cache_dir(appname, appauthor=False)


def user_config_dir(appname, roaming=True):
# type: (str, bool) -> str
def user_config_dir(appname: str, roaming: bool = True) -> str:
path = _appdirs.user_config_dir(appname, appauthor=False, roaming=roaming)
if _appdirs.system == "darwin" and not os.path.isdir(path):
path = os.path.expanduser("~/.config/")
Expand All @@ -29,8 +27,7 @@ def user_config_dir(appname, roaming=True):

# for the discussion regarding site_config_dir locations
# see <https://github.com/pypa/pip/issues/1733>
def site_config_dirs(appname):
# type: (str) -> List[str]
def site_config_dirs(appname: str) -> List[str]:
dirval = _appdirs.site_config_dir(appname, appauthor=False, multipath=True)
if _appdirs.system not in ["win32", "darwin"]:
# always look in /etc directly as well
Expand Down
6 changes: 2 additions & 4 deletions src/pip/_internal/utils/compat.py
Original file line number Diff line number Diff line change
Expand Up @@ -11,8 +11,7 @@
logger = logging.getLogger(__name__)


def has_tls():
# type: () -> bool
def has_tls() -> bool:
try:
import _ssl # noqa: F401 # ignore unused

Expand All @@ -25,8 +24,7 @@ def has_tls():
return IS_PYOPENSSL


def get_path_uid(path):
# type: (str) -> int
def get_path_uid(path: str) -> int:
"""
Return path's uid.

Expand Down
38 changes: 16 additions & 22 deletions src/pip/_internal/utils/compatibility_tags.py
Original file line number Diff line number Diff line change
Expand Up @@ -21,14 +21,12 @@
_osx_arch_pat = re.compile(r"(.+)_(\d+)_(\d+)_(.+)")


def version_info_to_nodot(version_info):
# type: (Tuple[int, ...]) -> str
def version_info_to_nodot(version_info: Tuple[int, ...]) -> str:
# Only use up to the first two numbers.
return "".join(map(str, version_info[:2]))


def _mac_platforms(arch):
# type: (str) -> List[str]
def _mac_platforms(arch: str) -> List[str]:
match = _osx_arch_pat.match(arch)
if match:
name, major, minor, actual_arch = match.groups()
Expand All @@ -48,8 +46,7 @@ def _mac_platforms(arch):
return arches


def _custom_manylinux_platforms(arch):
# type: (str) -> List[str]
def _custom_manylinux_platforms(arch: str) -> List[str]:
arches = [arch]
arch_prefix, arch_sep, arch_suffix = arch.partition("_")
if arch_prefix == "manylinux2014":
Expand All @@ -70,8 +67,7 @@ def _custom_manylinux_platforms(arch):
return arches


def _get_custom_platforms(arch):
# type: (str) -> List[str]
def _get_custom_platforms(arch: str) -> List[str]:
arch_prefix, arch_sep, arch_suffix = arch.partition("_")
if arch.startswith("macosx"):
arches = _mac_platforms(arch)
Expand All @@ -82,8 +78,7 @@ def _get_custom_platforms(arch):
return arches


def _expand_allowed_platforms(platforms):
# type: (Optional[List[str]]) -> Optional[List[str]]
def _expand_allowed_platforms(platforms: Optional[List[str]]) -> Optional[List[str]]:
if not platforms:
return None

Expand All @@ -100,16 +95,16 @@ def _expand_allowed_platforms(platforms):
return result


def _get_python_version(version):
# type: (str) -> PythonVersion
def _get_python_version(version: str) -> "PythonVersion":
if len(version) > 1:
return int(version[0]), int(version[1:])
else:
return (int(version[0]),)


def _get_custom_interpreter(implementation=None, version=None):
# type: (Optional[str], Optional[str]) -> str
def _get_custom_interpreter(
implementation: Optional[str] = None, version: Optional[str] = None
) -> str:
if implementation is None:
implementation = interpreter_name()
if version is None:
Expand All @@ -118,12 +113,11 @@ def _get_custom_interpreter(implementation=None, version=None):


def get_supported(
version=None, # type: Optional[str]
platforms=None, # type: Optional[List[str]]
impl=None, # type: Optional[str]
abis=None, # type: Optional[List[str]]
):
# type: (...) -> List[Tag]
version: Optional[str] = None,
platforms: Optional[List[str]] = None,
impl: Optional[str] = None,
abis: Optional[List[str]] = None,
) -> List[Tag]:
"""Return a list of supported tags for each version specified in
`versions`.

Expand All @@ -136,9 +130,9 @@ def get_supported(
:param abis: specify a list of abis you want valid
tags for, or None. If None, use the local interpreter abi.
"""
supported = [] # type: List[Tag]
supported: List[Tag] = []

python_version = None # type: Optional[PythonVersion]
python_version: Optional["PythonVersion"] = None
if version is not None:
python_version = _get_python_version(version)

Expand Down
3 changes: 1 addition & 2 deletions src/pip/_internal/utils/datetime.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,8 +4,7 @@
import datetime


def today_is_later_than(year, month, day):
# type: (int, int, int) -> bool
def today_is_later_than(year: int, month: int, day: int) -> bool:
today = datetime.date.today()
given = datetime.date(year, month, day)

Expand Down
28 changes: 15 additions & 13 deletions src/pip/_internal/utils/deprecation.py
Original file line number Diff line number Diff line change
Expand Up @@ -17,19 +17,18 @@ class PipDeprecationWarning(Warning):
pass


_original_showwarning = None # type: Any
_original_showwarning: Any = None


# Warnings <-> Logging Integration
def _showwarning(
message, # type: Union[Warning, str]
category, # type: Type[Warning]
filename, # type: str
lineno, # type: int
file=None, # type: Optional[TextIO]
line=None, # type: Optional[str]
):
# type: (...) -> None
message: Union[Warning, str],
category: Type[Warning],
filename: str,
lineno: int,
file: Optional[TextIO] = None,
line: Optional[str] = None,
) -> None:
if file is not None:
if _original_showwarning is not None:
_original_showwarning(message, category, filename, lineno, file, line)
Expand All @@ -42,8 +41,7 @@ def _showwarning(
_original_showwarning(message, category, filename, lineno, file, line)


def install_warning_logger():
# type: () -> None
def install_warning_logger() -> None:
# Enable our Deprecation Warnings
warnings.simplefilter("default", PipDeprecationWarning, append=True)

Expand All @@ -54,8 +52,12 @@ def install_warning_logger():
warnings.showwarning = _showwarning


def deprecated(reason, replacement, gone_in, issue=None):
# type: (str, Optional[str], Optional[str], Optional[int]) -> None
def deprecated(
reason: str,
replacement: Optional[str],
gone_in: Optional[str],
issue: Optional[int] = None,
) -> None:
"""Helper to deprecate existing functionality.

reason:
Expand Down
8 changes: 4 additions & 4 deletions src/pip/_internal/utils/direct_url_helpers.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,8 +5,7 @@
from pip._internal.vcs import vcs


def direct_url_as_pep440_direct_reference(direct_url, name):
# type: (DirectUrl, str) -> str
def direct_url_as_pep440_direct_reference(direct_url: DirectUrl, name: str) -> str:
"""Convert a DirectUrl to a pip requirement string."""
direct_url.validate() # if invalid, this is a pip bug
requirement = name + " @ "
Expand All @@ -29,8 +28,9 @@ def direct_url_as_pep440_direct_reference(direct_url, name):
return requirement


def direct_url_from_link(link, source_dir=None, link_is_in_wheel_cache=False):
# type: (Link, Optional[str], bool) -> DirectUrl
def direct_url_from_link(
link: Link, source_dir: Optional[str] = None, link_is_in_wheel_cache: bool = False
) -> DirectUrl:
if link.is_vcs:
vcs_backend = vcs.get_backend_for_scheme(link.scheme)
assert vcs_backend
Expand Down
3 changes: 1 addition & 2 deletions src/pip/_internal/utils/distutils_args.py
Original file line number Diff line number Diff line change
Expand Up @@ -22,8 +22,7 @@
_distutils_getopt = FancyGetopt(_options) # type: ignore


def parse_distutils_args(args):
# type: (List[str]) -> Dict[str, str]
def parse_distutils_args(args: List[str]) -> Dict[str, str]:
"""Parse provided arguments, returning an object that has the
matched arguments.

Expand Down
7 changes: 3 additions & 4 deletions src/pip/_internal/utils/encoding.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,21 +4,20 @@
import sys
from typing import List, Tuple

BOMS = [
BOMS: List[Tuple[bytes, str]] = [
(codecs.BOM_UTF8, "utf-8"),
(codecs.BOM_UTF16, "utf-16"),
(codecs.BOM_UTF16_BE, "utf-16-be"),
(codecs.BOM_UTF16_LE, "utf-16-le"),
(codecs.BOM_UTF32, "utf-32"),
(codecs.BOM_UTF32_BE, "utf-32-be"),
(codecs.BOM_UTF32_LE, "utf-32-le"),
] # type: List[Tuple[bytes, str]]
]

ENCODING_RE = re.compile(br"coding[:=]\s*([-\w.]+)")


def auto_decode(data):
# type: (bytes) -> str
def auto_decode(data: bytes) -> str:
"""Check a bytes string for a BOM to correctly detect the encoding

Fallback to locale.getpreferredencoding(False) like open() on Python3"""
Expand Down
3 changes: 1 addition & 2 deletions src/pip/_internal/utils/entrypoints.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,8 +4,7 @@
from pip._internal.cli.main import main


def _wrapper(args=None):
# type: (Optional[List[str]]) -> int
def _wrapper(args: Optional[List[str]] = None) -> int:
"""Central wrapper for all old entrypoints.

Historically pip has had several entrypoints defined. Because of issues
Expand Down
35 changes: 12 additions & 23 deletions src/pip/_internal/utils/filesystem.py
Original file line number Diff line number Diff line change
Expand Up @@ -15,8 +15,7 @@
from pip._internal.utils.misc import format_size


def check_path_owner(path):
# type: (str) -> bool
def check_path_owner(path: str) -> bool:
# If we don't have a way to check the effective uid of this process, then
# we'll just assume that we own the directory.
if sys.platform == "win32" or not hasattr(os, "geteuid"):
Expand All @@ -43,8 +42,7 @@ def check_path_owner(path):
return False # assume we don't own the path


def copy2_fixed(src, dest):
# type: (str, str) -> None
def copy2_fixed(src: str, dest: str) -> None:
"""Wrap shutil.copy2() but map errors copying socket files to
SpecialFileError as expected.

Expand All @@ -67,14 +65,12 @@ def copy2_fixed(src, dest):
raise


def is_socket(path):
# type: (str) -> bool
def is_socket(path: str) -> bool:
return stat.S_ISSOCK(os.lstat(path).st_mode)


@contextmanager
def adjacent_tmp_file(path, **kwargs):
# type: (str, **Any) -> Iterator[BinaryIO]
def adjacent_tmp_file(path: str, **kwargs: Any) -> Iterator[BinaryIO]:
"""Return a file-like object pointing to a tmp file next to path.

The file is created securely and is ensured to be written to disk
Expand Down Expand Up @@ -106,8 +102,7 @@ def adjacent_tmp_file(path, **kwargs):

# test_writable_dir and _test_writable_dir_win are copied from Flit,
# with the author's agreement to also place them under pip's license.
def test_writable_dir(path):
# type: (str) -> bool
def test_writable_dir(path: str) -> bool:
"""Check if a directory is writable.

Uses os.access() on POSIX, tries creating files on Windows.
Expand All @@ -125,8 +120,7 @@ def test_writable_dir(path):
return _test_writable_dir_win(path)


def _test_writable_dir_win(path):
# type: (str) -> bool
def _test_writable_dir_win(path: str) -> bool:
# os.access doesn't work on Windows: http://bugs.python.org/issue2528
# and we can't use tempfile: http://bugs.python.org/issue22107
basename = "accesstest_deleteme_fishfingers_custard_"
Expand Down Expand Up @@ -154,32 +148,28 @@ def _test_writable_dir_win(path):
raise OSError("Unexpected condition testing for writable directory")


def find_files(path, pattern):
# type: (str, str) -> List[str]
def find_files(path: str, pattern: str) -> List[str]:
"""Returns a list of absolute paths of files beneath path, recursively,
with filenames which match the UNIX-style shell glob pattern."""
result = [] # type: List[str]
result: List[str] = []
for root, _, files in os.walk(path):
matches = fnmatch.filter(files, pattern)
result.extend(os.path.join(root, f) for f in matches)
return result


def file_size(path):
# type: (str) -> Union[int, float]
def file_size(path: str) -> Union[int, float]:
# If it's a symlink, return 0.
if os.path.islink(path):
return 0
return os.path.getsize(path)


def format_file_size(path):
# type: (str) -> str
def format_file_size(path: str) -> str:
return format_size(file_size(path))


def directory_size(path):
# type: (str) -> Union[int, float]
def directory_size(path: str) -> Union[int, float]:
size = 0.0
for root, _dirs, files in os.walk(path):
for filename in files:
Expand All @@ -188,6 +178,5 @@ def directory_size(path):
return size


def format_directory_size(path):
# type: (str) -> str
def format_directory_size(path: str) -> str:
return format_size(directory_size(path))