Skip to content

Commit

Permalink
Merge branch 'main' into update-python-3.2-to-3.6-code
Browse files Browse the repository at this point in the history
  • Loading branch information
Avasam authored Jan 8, 2024
2 parents b05644e + 85fd45b commit de16d24
Show file tree
Hide file tree
Showing 34 changed files with 167 additions and 144 deletions.
3 changes: 2 additions & 1 deletion .github/workflows/main.yml
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,8 @@ on:
merge_group:
push:
branches-ignore:
- gh-readonly-queue/** # Temporary merge queue-related GH-made branches
# disabled for jaraco/skeleton#103
# - gh-readonly-queue/** # Temporary merge queue-related GH-made branches
pull_request:
workflow_dispatch:

Expand Down
7 changes: 3 additions & 4 deletions README.rst
Original file line number Diff line number Diff line change
Expand Up @@ -27,10 +27,9 @@
:target: https://discord.com/channels/803025117553754132/815945031150993468
:alt: Discord

See the `Installation Instructions
<https://packaging.python.org/installing/>`_ in the Python Packaging
User's Guide for instructions on installing, upgrading, and uninstalling
Setuptools.
See the `Quickstart <https://setuptools.pypa.io/en/latest/userguide/quickstart.html>`_
and the `User's Guide <https://setuptools.pypa.io/en/latest/userguide/>`_ for
instructions on how to use Setuptools.

Questions and comments should be directed to `GitHub Discussions
<https://github.com/pypa/setuptools/discussions>`_.
Expand Down
43 changes: 19 additions & 24 deletions pkg_resources/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -399,20 +399,18 @@ def get_provider(moduleOrReq):
return _find_adapter(_provider_factories, loader)(module)


def _macos_vers(_cache=[]):
if not _cache:
version = platform.mac_ver()[0]
# fallback for MacPorts
if version == '':
plist = '/System/Library/CoreServices/SystemVersion.plist'
if os.path.exists(plist):
if hasattr(plistlib, 'readPlist'):
plist_content = plistlib.readPlist(plist)
if 'ProductVersion' in plist_content:
version = plist_content['ProductVersion']

_cache.append(version.split('.'))
return _cache[0]
@functools.lru_cache(maxsize=None)
def _macos_vers():
version = platform.mac_ver()[0]
# fallback for MacPorts
if version == '':
plist = '/System/Library/CoreServices/SystemVersion.plist'
if os.path.exists(plist):
with open(plist, 'rb') as fh:
plist_content = plistlib.load(fh)
if 'ProductVersion' in plist_content:
version = plist_content['ProductVersion']
return version.split('.')


def _macos_arch(machine):
Expand Down Expand Up @@ -1887,7 +1885,7 @@ def _extract_resource(self, manager, zip_path): # noqa: C901
try:
rename(tmpnam, real_path)

except os.error:
except OSError:
if os.path.isfile(real_path):
if self._is_current(real_path, zip_path):
# the file became current since it was checked above,
Expand All @@ -1900,7 +1898,7 @@ def _extract_resource(self, manager, zip_path): # noqa: C901
return real_path
raise

except os.error:
except OSError:
# report a user-friendly error
manager.extraction_error()

Expand Down Expand Up @@ -2414,12 +2412,9 @@ def _cygwin_patch(filename): # pragma: nocover
return os.path.abspath(filename) if sys.platform == 'cygwin' else filename


def _normalize_cached(filename, _cache={}):
try:
return _cache[filename]
except KeyError:
_cache[filename] = result = normalize_path(filename)
return result
@functools.lru_cache(maxsize=None)
def _normalize_cached(filename):
return normalize_path(filename)


def _is_egg_path(path):
Expand Down Expand Up @@ -2893,7 +2888,7 @@ def __getattr__(self, attr):

def __dir__(self):
return list(
set(super(Distribution, self).__dir__())
set(super().__dir__())
| set(attr for attr in self._provider.__dir__() if not attr.startswith('_'))
)

Expand Down Expand Up @@ -3160,7 +3155,7 @@ class RequirementParseError(packaging.requirements.InvalidRequirement):
class Requirement(packaging.requirements.Requirement):
def __init__(self, requirement_string):
"""DO NOT CALL THIS UNDOCUMENTED METHOD; use Requirement.parse()!"""
super(Requirement, self).__init__(requirement_string)
super().__init__(requirement_string)
self.unsafe_name = self.name
project_name = safe_name(self.name)
self.project_name, self.key = project_name, project_name.lower()
Expand Down
27 changes: 27 additions & 0 deletions pkg_resources/tests/test_pkg_resources.py
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
import builtins
import sys
import tempfile
import os
Expand Down Expand Up @@ -308,6 +309,32 @@ def test_dist_info_is_not_dir(tmp_path, only):
assert not pkg_resources.dist_factory(str(tmp_path), str(dist_info), only)


def test_macos_vers_fallback(monkeypatch, tmp_path):
"""Regression test for pkg_resources._macos_vers"""
orig_open = builtins.open

# Pretend we need to use the plist file
monkeypatch.setattr('platform.mac_ver', mock.Mock(return_value=('', (), '')))

# Create fake content for the fake plist file
with open(tmp_path / 'fake.plist', 'wb') as fake_file:
plistlib.dump({"ProductVersion": "11.4"}, fake_file)

# Pretend the fake file exists
monkeypatch.setattr('os.path.exists', mock.Mock(return_value=True))

def fake_open(file, *args, **kwargs):
return orig_open(tmp_path / 'fake.plist', *args, **kwargs)

# Ensure that the _macos_vers works correctly
with mock.patch('builtins.open', mock.Mock(side_effect=fake_open)) as m:
pkg_resources._macos_vers.cache_clear()
assert pkg_resources._macos_vers() == ["11", "4"]
pkg_resources._macos_vers.cache_clear()

m.assert_called()


class TestDeepVersionLookupDistutils:
@pytest.fixture
def env(self, tmpdir):
Expand Down
4 changes: 2 additions & 2 deletions pkg_resources/tests/test_working_set.py
Original file line number Diff line number Diff line change
Expand Up @@ -76,10 +76,10 @@ def parametrize_test_working_set_resolve(*test_list):
requirements,
expected1,
expected2,
) = [
) = (
strip_comments(s.lstrip())
for s in textwrap.dedent(test).lstrip().split('\n\n', 5)
]
)
installed_dists = list(parse_distributions(installed_dists))
installable_dists = list(parse_distributions(installable_dists))
requirements = list(pkg_resources.parse_requirements(requirements))
Expand Down
22 changes: 21 additions & 1 deletion ruff.toml
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
[lint]
extend-ignore = [
ignore = [
# https://docs.astral.sh/ruff/formatter/#conflicting-lint-rules
"W191",
"E111",
Expand All @@ -16,7 +16,27 @@ extend-ignore = [
"ISC001",
"ISC002",
]
extend-select = [
"UP", # pyupgrade
]
extend-ignore = [
"UP015", # redundant-open-modes, explicit is prefered
"UP030", # temporarily disabled
"UP031", # temporarily disabled
"UP032", # temporarily disabled
"UP036", # temporarily disabled
]
exclude = [
"**/_vendor",
"setuptools/_distutils",
"setuptools/config/_validate_pyproject",
]

[format]
exclude = [
"**/_vendor",
"setuptools/_distutils",
"setuptools/config/_validate_pyproject",
]
# https://docs.astral.sh/ruff/settings/#format-quote-style
quote-style = "preserve"
4 changes: 2 additions & 2 deletions setuptools/build_meta.py
Original file line number Diff line number Diff line change
Expand Up @@ -121,7 +121,7 @@ def _file_with_extension(directory, extension):
raise ValueError(
'No distribution was found. Ensure that `setup.py` '
'is not empty and that it calls `setup()`.'
)
) from None
return file


Expand Down Expand Up @@ -477,7 +477,7 @@ def run_setup(self, setup_script='setup.py'):
sys.argv[0] = setup_script

try:
super(_BuildMetaLegacyBackend, self).run_setup(setup_script=setup_script)
super().run_setup(setup_script=setup_script)
finally:
# While PEP 517 frontends should be calling each hook in a fresh
# subprocess according to the standard (and thus it should not be
Expand Down
9 changes: 3 additions & 6 deletions setuptools/command/bdist_egg.py
Original file line number Diff line number Diff line change
Expand Up @@ -321,8 +321,7 @@ def walk_egg(egg_dir):
if 'EGG-INFO' in dirs:
dirs.remove('EGG-INFO')
yield base, dirs, files
for bdf in walker:
yield bdf
yield from walker


def analyze_egg(egg_dir, stubs):
Expand Down Expand Up @@ -403,14 +402,12 @@ def scan_module(egg_dir, base, name, stubs):

def iter_symbols(code):
"""Yield names and strings used by `code` and its nested code objects"""
for name in code.co_names:
yield name
yield from code.co_names
for const in code.co_consts:
if isinstance(const, str):
yield const
elif isinstance(const, CodeType):
for name in iter_symbols(const):
yield name
yield from iter_symbols(const)


def can_scan():
Expand Down
2 changes: 1 addition & 1 deletion setuptools/command/build_ext.py
Original file line number Diff line number Diff line change
Expand Up @@ -157,7 +157,7 @@ def get_ext_filename(self, fullname):

if fullname in self.ext_map:
ext = self.ext_map[fullname]
use_abi3 = getattr(ext, 'py_limited_api') and get_abi3_suffix()
use_abi3 = ext.py_limited_api and get_abi3_suffix()
if use_abi3:
filename = filename[: -len(so_ext)]
so_ext = get_abi3_suffix()
Expand Down
2 changes: 1 addition & 1 deletion setuptools/command/build_py.py
Original file line number Diff line number Diff line change
Expand Up @@ -288,7 +288,7 @@ def exclude_data_files(self, package, src_dir, files):
return list(unique_everseen(keepers))

@staticmethod
def _get_platform_patterns(spec, package, src_dir, extra_patterns=[]):
def _get_platform_patterns(spec, package, src_dir, extra_patterns=()):
"""
yield platform-specific path patterns (suitable for glob
or fn_match) from a glob-based spec (such as
Expand Down
8 changes: 3 additions & 5 deletions setuptools/command/easy_install.py
Original file line number Diff line number Diff line change
Expand Up @@ -1744,8 +1744,7 @@ class RewritePthDistributions(PthDistributions):
@classmethod
def _wrap_lines(cls, lines):
yield cls.prelude
for line in lines:
yield line
yield from lines
yield cls.postlude

prelude = _one_liner(
Expand Down Expand Up @@ -2025,7 +2024,7 @@ def chmod(path, mode):
log.debug("changing mode of %s to %o", path, mode)
try:
_chmod(path, mode)
except os.error as e:
except OSError as e:
log.debug("chmod failed: %s", e)


Expand Down Expand Up @@ -2181,8 +2180,7 @@ def get_args(cls, dist, header=None):
cls._ensure_safe_name(name)
script_text = cls.template % locals()
args = cls._get_script_args(type_, name, header, script_text)
for res in args:
yield res
yield from args

@staticmethod
def _ensure_safe_name(name):
Expand Down
6 changes: 3 additions & 3 deletions setuptools/command/editable_wheel.py
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,7 @@
from contextlib import suppress
from enum import Enum
from inspect import cleandoc
from itertools import chain
from itertools import chain, starmap
from pathlib import Path
from tempfile import TemporaryDirectory
from typing import (
Expand Down Expand Up @@ -394,7 +394,7 @@ def __init__(self, dist: Distribution, name: str, path_entries: List[Path]):
self.path_entries = path_entries

def __call__(self, wheel: "WheelFile", files: List[str], mapping: Dict[str, str]):
entries = "\n".join((str(p.resolve()) for p in self.path_entries))
entries = "\n".join(str(p.resolve()) for p in self.path_entries)
contents = _encode_pth(f"{entries}\n")
wheel.writestr(f"__editable__.{self.name}.pth", contents)

Expand Down Expand Up @@ -600,7 +600,7 @@ def _simple_layout(
layout = {pkg: find_package_path(pkg, package_dir, project_dir) for pkg in packages}
if not layout:
return set(package_dir) in ({}, {""})
parent = os.path.commonpath([_parent_path(k, v) for k, v in layout.items()])
parent = os.path.commonpath(starmap(_parent_path, layout.items()))
return all(
_path.same_path(Path(parent, *key.split('.')), value)
for key, value in layout.items()
Expand Down
5 changes: 2 additions & 3 deletions setuptools/command/egg_info.py
Original file line number Diff line number Diff line change
Expand Up @@ -385,9 +385,8 @@ def process_template_line(self, line):
try:
process_action = action_map[action]
except KeyError:
raise DistutilsInternalError(
"this cannot happen: invalid action '{action!s}'".format(action=action),
)
msg = f"Invalid MANIFEST.in: unknown action {action!r} in {line!r}"
raise DistutilsInternalError(msg) from None

# OK, now we know that the action is valid and we have the
# right number of words on the line for that action -- so we
Expand Down
7 changes: 3 additions & 4 deletions setuptools/command/sdist.py
Original file line number Diff line number Diff line change
Expand Up @@ -13,8 +13,7 @@
def walk_revctrl(dirname=''):
"""Find all files under revision control"""
for ep in metadata.entry_points(group='setuptools.file_finders'):
for item in ep.load()(dirname):
yield item
yield from ep.load()(dirname)


class sdist(orig.sdist):
Expand Down Expand Up @@ -97,7 +96,7 @@ class NoValue:
yield
finally:
if orig_val is not NoValue:
setattr(os, 'link', orig_val)
os.link = orig_val

def add_defaults(self):
super().add_defaults()
Expand Down Expand Up @@ -181,7 +180,7 @@ def _manifest_is_not_generated(self):

with open(self.manifest, 'rb') as fp:
first_line = fp.readline()
return first_line != '# file GENERATED by distutils, do NOT edit\n'.encode()
return first_line != b'# file GENERATED by distutils, do NOT edit\n'

def read_manifest(self):
"""Read the manifest file (named by 'self.manifest') and use it to
Expand Down
2 changes: 1 addition & 1 deletion setuptools/command/test.py
Original file line number Diff line number Diff line change
Expand Up @@ -132,7 +132,7 @@ def with_project_on_sys_path(self, func):
func()

@contextlib.contextmanager
def project_on_sys_path(self, include_dists=[]):
def project_on_sys_path(self, include_dists=()):
self.run_command('egg_info')

# Build extensions in-place
Expand Down
2 changes: 1 addition & 1 deletion setuptools/config/_validate_pyproject/error_reporting.py
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,7 @@
"must not be there",
)

_NEED_DETAILS = {"anyOf", "oneOf", "anyOf", "contains", "propertyNames", "not", "items"}
_NEED_DETAILS = {"anyOf", "oneOf", "allOf", "contains", "propertyNames", "not", "items"}

_CAMEL_CASE_SPLITTER = re.compile(r"\W+|([A-Z][^A-Z\W]*)")
_IDENTIFIER = re.compile(r"^[\w_]+$", re.I)
Expand Down
8 changes: 4 additions & 4 deletions setuptools/config/setupcfg.py
Original file line number Diff line number Diff line change
Expand Up @@ -283,8 +283,8 @@ def __setitem__(self, option_name, value):

try:
current_value = getattr(target_obj, option_name)
except AttributeError:
raise KeyError(option_name)
except AttributeError as e:
raise KeyError(option_name) from e

if current_value:
# Already inhabited. Skipping.
Expand Down Expand Up @@ -582,11 +582,11 @@ def _parse_version(self, value):
# accidentally include newlines and other unintended content
try:
Version(version)
except InvalidVersion:
except InvalidVersion as e:
raise OptionError(
f'Version loaded from {value} does not '
f'comply with PEP 440: {version}'
)
) from e

return version

Expand Down
Loading

0 comments on commit de16d24

Please sign in to comment.