Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Enforce ruff/pyupgrade rules (UP) #4379

Open
wants to merge 12 commits into
base: main
Choose a base branch
from
Open
54 changes: 24 additions & 30 deletions pkg_resources/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -214,7 +214,7 @@ def get_supported_platform():
m = macosVersionString.match(plat)
if m is not None and sys.platform == "darwin":
try:
plat = 'macosx-%s-%s' % ('.'.join(_macos_vers()[:2]), m.group(3))
plat = 'macosx-{}-{}'.format('.'.join(_macos_vers()[:2]), m.group(3))
except ValueError:
# not macOS
pass
Expand Down Expand Up @@ -504,7 +504,7 @@ def compatible_platforms(provided: str | None, required: str | None):
provDarwin = darwinVersionString.match(provided)
if provDarwin:
dversion = int(provDarwin.group(1))
macosversion = "%s.%s" % (reqMac.group(1), reqMac.group(2))
macosversion = f"{reqMac.group(1)}.{reqMac.group(2)}"
if (
dversion == 7
and macosversion >= "10.3"
Expand Down Expand Up @@ -1306,7 +1306,7 @@ def __iadd__(self, other: Distribution | Environment):
for dist in other[project]:
self.add(dist)
else:
raise TypeError("Can't add %r to environment" % (other,))
raise TypeError(f"Can't add {other!r} to environment")
return self

def __add__(self, other: Distribution | Environment):
Expand Down Expand Up @@ -1676,7 +1676,7 @@ def get_metadata(self, name: str):
except UnicodeDecodeError as exc:
# Include the path in the error message to simplify
# troubleshooting, and without changing the exception type.
exc.reason += ' in {} file at path: {}'.format(name, path)
exc.reason += f' in {name} file at path: {path}'
raise

def get_metadata_lines(self, name: str) -> Iterator[str]:
Expand Down Expand Up @@ -1993,15 +1993,15 @@ def _zipinfo_name(self, fspath):
return ''
if fspath.startswith(self.zip_pre):
return fspath[len(self.zip_pre) :]
raise AssertionError("%s is not a subpath of %s" % (fspath, self.zip_pre))
raise AssertionError(f"{fspath} is not a subpath of {self.zip_pre}")

def _parts(self, zip_path):
# Convert a zipfile subpath into an egg-relative path part list.
# pseudo-fs path
fspath = self.zip_pre + zip_path
if fspath.startswith(self.egg_root + os.sep):
return fspath[len(self.egg_root) + 1 :].split(os.sep)
raise AssertionError("%s is not a subpath of %s" % (fspath, self.egg_root))
raise AssertionError(f"{fspath} is not a subpath of {self.egg_root}")

@property
def zipinfo(self):
Expand Down Expand Up @@ -2699,15 +2699,15 @@ def __init__(
self.dist = dist

def __str__(self):
s = "%s = %s" % (self.name, self.module_name)
s = f"{self.name} = {self.module_name}"
if self.attrs:
s += ':' + '.'.join(self.attrs)
if self.extras:
s += ' [%s]' % ','.join(self.extras)
s += ' [{}]'.format(','.join(self.extras))
return s

def __repr__(self):
return "EntryPoint.parse(%r)" % str(self)
return f"EntryPoint.parse({str(self)!r})"
DimitriPapadopoulos marked this conversation as resolved.
Show resolved Hide resolved

@overload
def load(
Expand Down Expand Up @@ -2981,7 +2981,7 @@ def parsed_version(self):
if hasattr(ex, "add_note"):
ex.add_note(info) # PEP 678
raise
raise _packaging_version.InvalidVersion(f"{str(ex)} {info}") from None
raise _packaging_version.InvalidVersion(f"{ex} {info}") from None

return self._parsed_version

Expand All @@ -2995,7 +2995,7 @@ def _forgiving_parsed_version(self):
notes = "\n".join(getattr(ex, "__notes__", [])) # PEP 678
msg = f"""!!\n\n
*************************************************************************
{str(ex)}\n{notes}
{ex}\n{notes}

This is a long overdue deprecation.
For the time being, `pkg_resources` will use `{self._parsed_version}`
Expand All @@ -3019,9 +3019,7 @@ def version(self):
version = self._get_version()
if version is None:
path = self._get_metadata_path_for_display(self.PKG_INFO)
msg = ("Missing 'Version:' header and/or {} file at path: {}").format(
self.PKG_INFO, path
)
msg = f"Missing 'Version:' header and/or {self.PKG_INFO} file at path: {path}"
raise ValueError(msg, self) from e

return version
Expand Down Expand Up @@ -3075,9 +3073,7 @@ def requires(self, extras: Iterable[str] = ()):
try:
deps.extend(dm[safe_extra(ext)])
except KeyError as e:
raise UnknownExtra(
"%s has no such extra feature %r" % (self, ext)
) from e
raise UnknownExtra(f"{self} has no such extra feature {ext!r}") from e
return deps

def _get_metadata_path_for_display(self, name):
Expand Down Expand Up @@ -3118,19 +3114,18 @@ def activate(self, path: list[str] | None = None, replace: bool = False):

def egg_name(self):
"""Return what this distribution's standard .egg filename should be"""
filename = "%s-%s-py%s" % (
to_filename(self.project_name),
to_filename(self.version),
self.py_version or PY_MAJOR,
)
name = to_filename(self.project_name)
version = to_filename(self.version)
py_version = self.py_version or PY_MAJOR
filename = f"{name}-{version}-py{py_version}"

if self.platform:
filename += '-' + self.platform
return filename

def __repr__(self):
if self.location:
return "%s (%s)" % (self, self.location)
return f"{self} ({self.location})"
else:
return str(self)

Expand All @@ -3140,7 +3135,7 @@ def __str__(self):
except ValueError:
version = None
version = version or "[unknown version]"
return "%s %s" % (self.project_name, version)
return f"{self.project_name} {version}"

def __getattr__(self, attr):
"""Delegate all unrecognized public attributes to .metadata provider"""
Expand Down Expand Up @@ -3168,17 +3163,17 @@ def from_filename(
def as_requirement(self):
"""Return a ``Requirement`` that matches this distribution exactly"""
if isinstance(self.parsed_version, _packaging_version.Version):
spec = "%s==%s" % (self.project_name, self.parsed_version)
spec = f"{self.project_name}=={self.parsed_version}"
else:
spec = "%s===%s" % (self.project_name, self.parsed_version)
spec = f"{self.project_name}==={self.parsed_version}"

return Requirement.parse(spec)

def load_entry_point(self, group: str, name: str) -> _ResolvedEntryPoint:
"""Return the `name` entry point of `group` or raise ImportError"""
ep = self.get_entry_info(group, name)
if ep is None:
raise ImportError("Entry point %r not found" % ((group, name),))
raise ImportError(f"Entry point {(group, name)!r} not found")
return ep.load()

@overload
Expand Down Expand Up @@ -3295,8 +3290,7 @@ def check_version_conflict(self):
):
continue
issue_warning(
"Module %s was already imported from %s, but %s is being added"
" to sys.path" % (modname, fn, self.location),
f"Module {modname} was already imported from {fn}, but {self.location} is being added to sys.path",
)

def has_version(self):
Expand Down Expand Up @@ -3470,7 +3464,7 @@ def __hash__(self):
return self.__hash

def __repr__(self):
return "Requirement.parse(%r)" % str(self)
return f"Requirement.parse({str(self)!r})"
DimitriPapadopoulos marked this conversation as resolved.
Show resolved Hide resolved

@staticmethod
def parse(s: str | Iterable[str]):
Expand Down
10 changes: 5 additions & 5 deletions pkg_resources/tests/test_pkg_resources.py
Original file line number Diff line number Diff line change
Expand Up @@ -219,8 +219,8 @@ def test_get_metadata__bad_utf8(tmpdir):
"codec can't decode byte 0xe9 in position 1: "
'invalid continuation byte in METADATA file at path: '
)
assert expected in actual, 'actual: {}'.format(actual)
assert actual.endswith(metadata_path), 'actual: {}'.format(actual)
assert expected in actual, f'{actual=}'
assert actual.endswith(metadata_path), f'{actual=}'


def make_distribution_no_version(tmpdir, basename):
Expand Down Expand Up @@ -257,11 +257,11 @@ def test_distribution_version_missing(
"""
Test Distribution.version when the "Version" header is missing.
"""
basename = 'foo.{}'.format(suffix)
basename = f'foo.{suffix}'
dist, dist_dir = make_distribution_no_version(tmpdir, basename)

expected_text = ("Missing 'Version:' header and/or {} file at path: ").format(
expected_filename
expected_text = (
f"Missing 'Version:' header and/or {expected_filename} file at path: "
)
metadata_path = os.path.join(dist_dir, expected_filename)

Expand Down
3 changes: 0 additions & 3 deletions ruff.toml
Original file line number Diff line number Diff line change
Expand Up @@ -20,9 +20,6 @@ extend-select = [
ignore = [
"TRY301", # raise-within-try, it's handy
"UP015", # redundant-open-modes, explicit is preferred
"UP030", # temporarily disabled
"UP031", # temporarily disabled
"UP032", # temporarily disabled
"UP038", # Using `X | Y` in `isinstance` call is slower and more verbose https://github.com/astral-sh/ruff/issues/7871

# https://docs.astral.sh/ruff/formatter/#conflicting-lint-rules
Expand Down
6 changes: 2 additions & 4 deletions setuptools/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -184,9 +184,7 @@ def _ensure_stringlike(self, option, what, default=None):
setattr(self, option, default)
return default
elif not isinstance(val, str):
raise DistutilsOptionError(
"'%s' must be a %s (got `%s`)" % (option, what, val)
)
raise DistutilsOptionError(f"'{option}' must be a {what} (got `{val}`)")
return val

def ensure_string_list(self, option):
Expand All @@ -213,7 +211,7 @@ def ensure_string_list(self, option):
ok = False
if not ok:
raise DistutilsOptionError(
"'%s' must be a list of strings (got %r)" % (option, val)
f"'{option}' must be a list of strings (got {val!r})"
)

def reinitialize_command(self, command, reinit_subcommands=False, **kw):
Expand Down
6 changes: 3 additions & 3 deletions setuptools/_core_metadata.py
Original file line number Diff line number Diff line change
Expand Up @@ -149,7 +149,7 @@ def write_pkg_file(self, file): # noqa: C901 # is too complex (14) # FIXME
version = self.get_metadata_version()

def write_field(key, value):
file.write("%s: %s\n" % (key, value))
file.write(f"{key}: {value}\n")

write_field('Metadata-Version', str(version))
write_field('Name', self.get_name())
Expand Down Expand Up @@ -178,7 +178,7 @@ def write_field(key, value):
write_field('License', rfc822_escape(license))

for project_url in self.project_urls.items():
write_field('Project-URL', '%s, %s' % project_url)
write_field('Project-URL', '{}, {}'.format(*project_url))

keywords = ','.join(self.get_keywords())
if keywords:
Expand Down Expand Up @@ -208,7 +208,7 @@ def write_field(key, value):

long_description = self.get_long_description()
if long_description:
file.write("\n%s" % long_description)
file.write(f"\n{long_description}")
if not long_description.endswith("\n"):
file.write("\n")

Expand Down
6 changes: 3 additions & 3 deletions setuptools/_imp.py
Original file line number Diff line number Diff line change
Expand Up @@ -31,7 +31,7 @@ def find_module(module, paths=None):
"""Just like 'imp.find_module()', but with package support"""
spec = find_spec(module, paths)
if spec is None:
raise ImportError("Can't find %s" % module)
raise ImportError(f"Can't find {module}")
if not spec.has_location and hasattr(spec, 'submodule_search_locations'):
spec = importlib.util.spec_from_loader('__init__.py', spec.loader)

Expand Down Expand Up @@ -78,12 +78,12 @@ def find_module(module, paths=None):
def get_frozen_object(module, paths=None):
spec = find_spec(module, paths)
if not spec:
raise ImportError("Can't find %s" % module)
raise ImportError(f"Can't find {module}")
return spec.loader.get_code(module)


def get_module(module, paths, info):
spec = find_spec(module, paths)
if not spec:
raise ImportError("Can't find %s" % module)
raise ImportError(f"Can't find {module}")
return module_from_spec(spec)
8 changes: 4 additions & 4 deletions setuptools/archive_util.py
Original file line number Diff line number Diff line change
Expand Up @@ -59,7 +59,7 @@ def unpack_archive(filename, extract_dir, progress_filter=default_filter, driver
else:
return
else:
raise UnrecognizedFormat("Not a recognized archive type: %s" % filename)
raise UnrecognizedFormat(f"Not a recognized archive type: {filename}")


def unpack_directory(filename, extract_dir, progress_filter=default_filter):
Expand All @@ -68,7 +68,7 @@ def unpack_directory(filename, extract_dir, progress_filter=default_filter):
Raises ``UnrecognizedFormat`` if `filename` is not a directory
"""
if not os.path.isdir(filename):
raise UnrecognizedFormat("%s is not a directory" % filename)
raise UnrecognizedFormat(f"{filename} is not a directory")

paths = {
filename: ('', extract_dir),
Expand Down Expand Up @@ -98,7 +98,7 @@ def unpack_zipfile(filename, extract_dir, progress_filter=default_filter):
"""

if not zipfile.is_zipfile(filename):
raise UnrecognizedFormat("%s is not a zip file" % (filename,))
raise UnrecognizedFormat(f"{filename} is not a zip file")

with zipfile.ZipFile(filename) as z:
_unpack_zipfile_obj(z, extract_dir, progress_filter)
Expand Down Expand Up @@ -195,7 +195,7 @@ def unpack_tarfile(filename, extract_dir, progress_filter=default_filter):
tarobj = tarfile.open(filename)
except tarfile.TarError as e:
raise UnrecognizedFormat(
"%s is not a compressed or uncompressed tar file" % (filename,)
f"{filename} is not a compressed or uncompressed tar file"
) from e

for member, final_dst in _iter_open_tar(
Expand Down
4 changes: 2 additions & 2 deletions setuptools/command/alias.py
Original file line number Diff line number Diff line change
Expand Up @@ -56,7 +56,7 @@ def run(self):
print("setup.py alias", format_alias(alias, aliases))
return
else:
print("No alias definition found for %r" % alias)
print(f"No alias definition found for {alias!r}")
return
else:
alias = self.args[0]
Expand All @@ -74,5 +74,5 @@ def format_alias(name, aliases):
elif source == config_file('local'):
source = ''
else:
source = '--filename=%r' % source
source = f'--filename={source!r}'
return source + name + ' ' + command
2 changes: 1 addition & 1 deletion setuptools/command/bdist_egg.py
Original file line number Diff line number Diff line change
Expand Up @@ -253,7 +253,7 @@ def zap_pyfiles(self):
pattern = r'(?P<name>.+)\.(?P<magic>[^.]+)\.pyc'
m = re.match(pattern, name)
path_new = os.path.join(base, os.pardir, m.group('name') + '.pyc')
log.info("Renaming file from [%s] to [%s]" % (path_old, path_new))
log.info(f"Renaming file from [{path_old}] to [{path_new}]")
try:
os.remove(path_new)
except OSError:
Expand Down
Loading
Loading