Skip to content

Commit

Permalink
Apply ruff/bugbear rules (B) (#787)
Browse files Browse the repository at this point in the history
* Apply ruff/bugbear rule B904

	B904 Within an `except` clause, raise exceptions with `raise ... from err` or
	     `raise ... from None` to distinguish them from errors in exception handling

* Apply ruff/bugbear rule B028

	B028 No explicit `stacklevel` keyword argument found

* Apply ruff/bugbear rule B018

	B018 Found useless expression. Either assign it to a variable or remove it.

* Do not ignore ruff/bugbear rule (B015)

https://docs.astral.sh/ruff/rules/useless-comparison/

* Do not ignore ruff/bugbear rule (B009)

https://docs.astral.sh/ruff/rules/get-attr-with-constant/
  • Loading branch information
DimitriPapadopoulos authored Aug 8, 2024
1 parent 24e5350 commit 6c5698a
Show file tree
Hide file tree
Showing 5 changed files with 24 additions and 28 deletions.
5 changes: 0 additions & 5 deletions pyproject.toml
Original file line number Diff line number Diff line change
Expand Up @@ -74,12 +74,7 @@ extend-select = [
"W"
]
ignore = [
"B009",
"B015",
"B018",
"B027",
"B028",
"B904",
"N818",
"RUF003",
"RUF012",
Expand Down
8 changes: 4 additions & 4 deletions src/packaging/_elffile.py
Original file line number Diff line number Diff line change
Expand Up @@ -48,8 +48,8 @@ def __init__(self, f: IO[bytes]) -> None:

try:
ident = self._read("16B")
except struct.error:
raise ELFInvalid("unable to parse identification")
except struct.error as e:
raise ELFInvalid("unable to parse identification") from e
magic = bytes(ident[:4])
if magic != b"\x7fELF":
raise ELFInvalid(f"invalid magic: {magic!r}")
Expand All @@ -67,11 +67,11 @@ def __init__(self, f: IO[bytes]) -> None:
(2, 1): ("<HHIQQQIHHH", "<IIQQQQQQ", (0, 2, 5)), # 64-bit LSB.
(2, 2): (">HHIQQQIHHH", ">IIQQQQQQ", (0, 2, 5)), # 64-bit MSB.
}[(self.capacity, self.encoding)]
except KeyError:
except KeyError as e:
raise ELFInvalid(
f"unrecognized capacity ({self.capacity}) or "
f"encoding ({self.encoding})"
)
) from e

try:
(
Expand Down
1 change: 1 addition & 0 deletions src/packaging/_manylinux.py
Original file line number Diff line number Diff line change
Expand Up @@ -164,6 +164,7 @@ def _parse_glibc_version(version_str: str) -> tuple[int, int]:
f"Expected glibc version with 2 components major.minor,"
f" got: {version_str}",
RuntimeWarning,
stacklevel=2,
)
return -1, -1
return int(m.group("major")), int(m.group("minor"))
Expand Down
26 changes: 13 additions & 13 deletions src/packaging/metadata.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
from __future__ import annotations

import builtins
import email.feedparser
import email.header
import email.message
Expand All @@ -21,9 +22,9 @@
T = typing.TypeVar("T")


try:
ExceptionGroup
except NameError: # pragma: no cover
if "ExceptionGroup" in builtins.__dict__: # pragma: no cover
ExceptionGroup = ExceptionGroup
else: # pragma: no cover

class ExceptionGroup(Exception):
"""A minimal implementation of :external:exc:`ExceptionGroup` from Python 3.11.
Expand All @@ -42,9 +43,6 @@ def __init__(self, message: str, exceptions: list[Exception]) -> None:
def __repr__(self) -> str:
return f"{self.__class__.__name__}({self.message!r}, {self.exceptions!r})"

else: # pragma: no cover
ExceptionGroup = ExceptionGroup


class InvalidMetadata(ValueError):
"""A metadata field contains invalid data."""
Expand Down Expand Up @@ -224,8 +222,8 @@ def _get_payload(msg: email.message.Message, source: bytes | str) -> str:
bpayload: bytes = msg.get_payload(decode=True)
try:
return bpayload.decode("utf8", "strict")
except UnicodeDecodeError:
raise ValueError("payload in an invalid encoding")
except UnicodeDecodeError as exc:
raise ValueError("payload in an invalid encoding") from exc


# The various parse_FORMAT functions here are intended to be as lenient as
Expand Down Expand Up @@ -535,7 +533,7 @@ def _process_name(self, value: str) -> str:
except utils.InvalidName as exc:
raise self._invalid_metadata(
f"{value!r} is invalid for {{field}}", cause=exc
)
) from exc
else:
return value

Expand All @@ -547,7 +545,7 @@ def _process_version(self, value: str) -> version_module.Version:
except version_module.InvalidVersion as exc:
raise self._invalid_metadata(
f"{value!r} is invalid for {{field}}", cause=exc
)
) from exc

def _process_summary(self, value: str) -> str:
"""Check the field contains no newlines."""
Expand Down Expand Up @@ -608,7 +606,7 @@ def _process_provides_extra(
except utils.InvalidName as exc:
raise self._invalid_metadata(
f"{name!r} is invalid for {{field}}", cause=exc
)
) from exc
else:
return normalized_names

Expand All @@ -618,7 +616,7 @@ def _process_requires_python(self, value: str) -> specifiers.SpecifierSet:
except specifiers.InvalidSpecifier as exc:
raise self._invalid_metadata(
f"{value!r} is invalid for {{field}}", cause=exc
)
) from exc

def _process_requires_dist(
self,
Expand All @@ -629,7 +627,9 @@ def _process_requires_dist(
for req in value:
reqs.append(requirements.Requirement(req))
except requirements.InvalidRequirement as exc:
raise self._invalid_metadata(f"{req!r} is invalid for {{field}}", cause=exc)
raise self._invalid_metadata(
f"{req!r} is invalid for {{field}}", cause=exc
) from exc
else:
return reqs

Expand Down
12 changes: 6 additions & 6 deletions tests/test_metadata.py
Original file line number Diff line number Diff line change
Expand Up @@ -427,7 +427,7 @@ def test_invalid_metadata_version(self, version):
meta = metadata.Metadata.from_raw({"metadata_version": version}, validate=False)

with pytest.raises(metadata.InvalidMetadata):
meta.metadata_version
meta.metadata_version # noqa: B018

def test_valid_version(self):
version_str = "1.2.3"
Expand All @@ -437,7 +437,7 @@ def test_valid_version(self):
def test_missing_version(self):
meta = metadata.Metadata.from_raw({}, validate=False)
with pytest.raises(metadata.InvalidMetadata) as exc_info:
meta.version
meta.version # noqa: B018
assert exc_info.value.field == "version"

def test_invalid_version(self):
Expand All @@ -456,7 +456,7 @@ def test_invalid_summary(self):
)

with pytest.raises(metadata.InvalidMetadata) as exc_info:
meta.summary
meta.summary # noqa: B018
assert exc_info.value.field == "summary"

def test_valid_name(self):
Expand Down Expand Up @@ -506,7 +506,7 @@ def test_invalid_description_content_type(self, content_type):
)

with pytest.raises(metadata.InvalidMetadata):
meta.description_content_type
meta.description_content_type # noqa: B018

def test_keywords(self):
keywords = ["hello", "world"]
Expand Down Expand Up @@ -602,14 +602,14 @@ def test_invalid_dynamic_value(self):
meta = metadata.Metadata.from_raw({"dynamic": dynamic}, validate=False)

with pytest.raises(metadata.InvalidMetadata):
meta.dynamic
meta.dynamic # noqa: B018

@pytest.mark.parametrize("field_name", ["name", "version", "metadata-version"])
def test_disallowed_dynamic(self, field_name):
meta = metadata.Metadata.from_raw({"dynamic": [field_name]}, validate=False)

with pytest.raises(metadata.InvalidMetadata):
meta.dynamic
meta.dynamic # noqa: B018

@pytest.mark.parametrize(
"field_name",
Expand Down

0 comments on commit 6c5698a

Please sign in to comment.