Skip to content

Commit e6c3f1f

Browse files
authored
Merge "Relax path related params" from typeshed (#4388)
2 parents 5ed52c1 + 9d0f075 commit e6c3f1f

File tree

5 files changed

+60
-32
lines changed

5 files changed

+60
-32
lines changed

pkg_resources/__init__.py

Lines changed: 28 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -36,7 +36,6 @@
3636
MutableSequence,
3737
NamedTuple,
3838
NoReturn,
39-
Sequence,
4039
Set,
4140
Tuple,
4241
Type,
@@ -49,6 +48,7 @@
4948
Iterable,
5049
Optional,
5150
TypeVar,
51+
overload,
5252
)
5353
import zipfile
5454
import zipimport
@@ -99,7 +99,7 @@
9999
from pkg_resources.extern.platformdirs import user_cache_dir as _user_cache_dir
100100

101101
if TYPE_CHECKING:
102-
from _typeshed import StrPath
102+
from _typeshed import StrPath, StrOrBytesPath, BytesPath
103103

104104
warnings.warn(
105105
"pkg_resources is deprecated as an API. "
@@ -1046,7 +1046,7 @@ class Environment:
10461046

10471047
def __init__(
10481048
self,
1049-
search_path: Optional[Sequence[str]] = None,
1049+
search_path: Optional[Iterable[str]] = None,
10501050
platform: Optional[str] = get_supported_platform(),
10511051
python: Optional[str] = PY_MAJOR,
10521052
):
@@ -1089,7 +1089,7 @@ def remove(self, dist: "Distribution"):
10891089
"""Remove `dist` from the environment"""
10901090
self._distmap[dist.key].remove(dist)
10911091

1092-
def scan(self, search_path: Optional[Sequence[str]] = None):
1092+
def scan(self, search_path: Optional[Iterable[str]] = None):
10931093
"""Scan `search_path` for distributions usable in this environment
10941094
10951095
Any distributions found are added to the environment.
@@ -1293,7 +1293,7 @@ def extraction_error(self) -> NoReturn:
12931293
err.original_error = old_exc
12941294
raise err
12951295

1296-
def get_cache_path(self, archive_name: str, names: Iterable[str] = ()):
1296+
def get_cache_path(self, archive_name: str, names: Iterable["StrPath"] = ()):
12971297
"""Return absolute location in cache for `archive_name` and `names`
12981298
12991299
The parent directory of the resulting path will be created if it does
@@ -1345,7 +1345,7 @@ def _warn_unsafe_extraction_path(path):
13451345
).format(**locals())
13461346
warnings.warn(msg, UserWarning)
13471347

1348-
def postprocess(self, tempname: str, filename: str):
1348+
def postprocess(self, tempname: "StrOrBytesPath", filename: "StrOrBytesPath"):
13491349
"""Perform any platform-specific postprocessing of `tempname`
13501350
13511351
This is where Mac header rewrites should be done; other platforms don't
@@ -2472,12 +2472,16 @@ def null_ns_handler(
24722472
register_namespace_handler(object, null_ns_handler)
24732473

24742474

2475-
def normalize_path(filename: "StrPath"):
2475+
@overload
2476+
def normalize_path(filename: "StrPath") -> str: ...
2477+
@overload
2478+
def normalize_path(filename: "BytesPath") -> bytes: ...
2479+
def normalize_path(filename: "StrOrBytesPath"):
24762480
"""Normalize a file/dir name for comparison purposes"""
24772481
return os.path.normcase(os.path.realpath(os.path.normpath(_cygwin_patch(filename))))
24782482

24792483

2480-
def _cygwin_patch(filename: "StrPath"): # pragma: nocover
2484+
def _cygwin_patch(filename: "StrOrBytesPath"): # pragma: nocover
24812485
"""
24822486
Contrary to POSIX 2008, on Cygwin, getcwd (3) contains
24832487
symlink components. Using
@@ -2488,9 +2492,19 @@ def _cygwin_patch(filename: "StrPath"): # pragma: nocover
24882492
return os.path.abspath(filename) if sys.platform == 'cygwin' else filename
24892493

24902494

2491-
@functools.lru_cache(maxsize=None)
2492-
def _normalize_cached(filename):
2493-
return normalize_path(filename)
2495+
if TYPE_CHECKING:
2496+
# https://github.com/python/mypy/issues/16261
2497+
# https://github.com/python/typeshed/issues/6347
2498+
@overload
2499+
def _normalize_cached(filename: "StrPath") -> str: ...
2500+
@overload
2501+
def _normalize_cached(filename: "BytesPath") -> bytes: ...
2502+
def _normalize_cached(filename: "StrOrBytesPath") -> Union[str, bytes]: ...
2503+
else:
2504+
2505+
@functools.lru_cache(maxsize=None)
2506+
def _normalize_cached(filename):
2507+
return normalize_path(filename)
24942508

24952509

24962510
def _is_egg_path(path):
@@ -2743,7 +2757,7 @@ def __init__(
27432757
def from_location(
27442758
cls,
27452759
location: str,
2746-
basename: str,
2760+
basename: "StrPath",
27472761
metadata: _MetadataType = None,
27482762
**kw: int, # We could set `precedence` explicitly, but keeping this as `**kw` for full backwards and subclassing compatibility
27492763
):
@@ -3003,7 +3017,7 @@ def __dir__(self):
30033017
@classmethod
30043018
def from_filename(
30053019
cls,
3006-
filename: str,
3020+
filename: "StrPath",
30073021
metadata: _MetadataType = None,
30083022
**kw: int, # We could set `precedence` explicitly, but keeping this as `**kw` for full backwards and subclassing compatibility
30093023
):
@@ -3339,7 +3353,7 @@ def _find_adapter(registry: Mapping[type, _AdapterT], ob: object) -> _AdapterT:
33393353
raise TypeError(f"Could not find adapter for {registry} and {ob}")
33403354

33413355

3342-
def ensure_directory(path: str):
3356+
def ensure_directory(path: "StrOrBytesPath"):
33433357
"""Ensure that the parent directory of `path` exists"""
33443358
dirname = os.path.dirname(path)
33453359
os.makedirs(dirname, exist_ok=True)

setuptools/build_meta.py

Lines changed: 22 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -36,12 +36,12 @@
3636
import tempfile
3737
import warnings
3838
from pathlib import Path
39-
from typing import Dict, Iterator, List, Optional, Union
39+
from typing import Dict, Iterator, List, Optional, Tuple, Union, Iterable
4040

4141
import setuptools
4242
import distutils
4343
from . import errors
44-
from ._path import same_path
44+
from ._path import same_path, StrPath
4545
from ._reqs import parse_strings
4646
from .warnings import SetuptoolsDeprecationWarning
4747
from distutils.util import strtobool
@@ -113,7 +113,7 @@ def _get_immediate_subdirectories(a_dir):
113113
]
114114

115115

116-
def _file_with_extension(directory, extension):
116+
def _file_with_extension(directory: StrPath, extension: Union[str, Tuple[str, ...]]):
117117
matching = (f for f in os.listdir(directory) if f.endswith(extension))
118118
try:
119119
(file,) = matching
@@ -370,11 +370,11 @@ def prepare_metadata_for_build_wheel(
370370

371371
def _build_with_temp_dir(
372372
self,
373-
setup_command,
374-
result_extension,
375-
result_directory,
376-
config_settings,
377-
arbitrary_args=(),
373+
setup_command: Iterable[str],
374+
result_extension: Union[str, Tuple[str, ...]],
375+
result_directory: StrPath,
376+
config_settings: _ConfigSettings,
377+
arbitrary_args: Iterable[str] = (),
378378
):
379379
result_directory = os.path.abspath(result_directory)
380380

@@ -404,7 +404,10 @@ def _build_with_temp_dir(
404404
return result_basename
405405

406406
def build_wheel(
407-
self, wheel_directory, config_settings=None, metadata_directory=None
407+
self,
408+
wheel_directory: StrPath,
409+
config_settings: _ConfigSettings = None,
410+
metadata_directory: Optional[StrPath] = None,
408411
):
409412
with suppress_known_deprecation():
410413
return self._build_with_temp_dir(
@@ -415,12 +418,16 @@ def build_wheel(
415418
self._arbitrary_args(config_settings),
416419
)
417420

418-
def build_sdist(self, sdist_directory, config_settings=None):
421+
def build_sdist(
422+
self, sdist_directory: StrPath, config_settings: _ConfigSettings = None
423+
):
419424
return self._build_with_temp_dir(
420425
['sdist', '--formats', 'gztar'], '.tar.gz', sdist_directory, config_settings
421426
)
422427

423-
def _get_dist_info_dir(self, metadata_directory: Optional[str]) -> Optional[str]:
428+
def _get_dist_info_dir(
429+
self, metadata_directory: Optional[StrPath]
430+
) -> Optional[str]:
424431
if not metadata_directory:
425432
return None
426433
dist_info_candidates = list(Path(metadata_directory).glob("*.dist-info"))
@@ -433,7 +440,10 @@ def _get_dist_info_dir(self, metadata_directory: Optional[str]) -> Optional[str]
433440
# get_requires_for_build_editable
434441
# prepare_metadata_for_build_editable
435442
def build_editable(
436-
self, wheel_directory, config_settings=None, metadata_directory=None
443+
self,
444+
wheel_directory: StrPath,
445+
config_settings: _ConfigSettings = None,
446+
metadata_directory: Optional[str] = None,
437447
):
438448
# XXX can or should we hide our editable_wheel command normally?
439449
info_dir = self._get_dist_info_dir(metadata_directory)

setuptools/command/install_lib.py

Lines changed: 4 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,7 @@
22
import sys
33
from itertools import product, starmap
44
import distutils.command.install_lib as orig
5+
from .._path import StrPath
56

67

78
class install_lib(orig.install_lib):
@@ -85,8 +86,8 @@ def _gen_exclusion_paths():
8586

8687
def copy_tree(
8788
self,
88-
infile,
89-
outfile,
89+
infile: StrPath,
90+
outfile: str,
9091
preserve_mode=1,
9192
preserve_times=1,
9293
preserve_symlinks=0,
@@ -96,7 +97,7 @@ def copy_tree(
9697
exclude = self.get_exclusions()
9798

9899
if not exclude:
99-
return orig.install_lib.copy_tree(self, infile, outfile)
100+
return orig.install_lib.copy_tree(self, infile, outfile) # type: ignore[arg-type] # Fixed upstream
100101

101102
# Exclude namespace package __init__.py* files from the output
102103

setuptools/command/install_scripts.py

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,7 @@
22
import distutils.command.install_scripts as orig
33
import os
44
import sys
5+
from typing import List
56

67
from .._path import ensure_directory
78

@@ -13,12 +14,12 @@ def initialize_options(self):
1314
orig.install_scripts.initialize_options(self)
1415
self.no_ep = False
1516

16-
def run(self):
17+
def run(self) -> None:
1718
self.run_command("egg_info")
1819
if self.distribution.scripts:
1920
orig.install_scripts.run(self) # run first to set up self.outfiles
2021
else:
21-
self.outfiles = []
22+
self.outfiles: List[str] = []
2223
if self.no_ep:
2324
# don't install entry point scripts into .egg file!
2425
return

setuptools/config/expand.py

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -119,7 +119,9 @@ def glob_relative(
119119
return expanded_values
120120

121121

122-
def read_files(filepaths: Union[str, bytes, Iterable[StrPath]], root_dir=None) -> str:
122+
def read_files(
123+
filepaths: Union[StrPath, Iterable[StrPath]], root_dir: Optional[StrPath] = None
124+
) -> str:
123125
"""Return the content of the files concatenated using ``\n`` as str
124126
125127
This function is sandboxed and won't reach anything outside ``root_dir``

0 commit comments

Comments
 (0)