Skip to content

Commit 4b01511

Browse files
authored
chore: enable ruff ALL (#984)
Signed-off-by: Henry Schreiner <[email protected]>
1 parent 505278d commit 4b01511

File tree

9 files changed

+60
-72
lines changed

9 files changed

+60
-72
lines changed

.pre-commit-config.yaml

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -26,9 +26,9 @@ repos:
2626
rev: v1.18.1
2727
hooks:
2828
- id: mypy
29-
exclude: '^(docs|tasks)'
29+
exclude: '^(docs)'
3030
args: []
31-
additional_dependencies: [pyparsing, nox, orjson, 'pytest<9', tomli, tomli_w]
31+
additional_dependencies: [pyparsing, nox, orjson, 'pytest<9', tomli, tomli_w, types-invoke, httpx]
3232

3333
- repo: https://github.com/codespell-project/codespell
3434
rev: "v2.4.1"

noxfile.py

Lines changed: 18 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -1,9 +1,9 @@
1-
# mypy: disallow-untyped-defs=False, disallow-untyped-calls=False
2-
31
# /// script
42
# dependencies = ["nox>=2025.02.09"]
53
# ///
64

5+
from __future__ import annotations
6+
77
import contextlib
88
import datetime
99
import difflib
@@ -18,6 +18,7 @@
1818
import time
1919
import webbrowser
2020
from pathlib import Path
21+
from typing import IO, Generator
2122

2223
import nox
2324

@@ -39,13 +40,15 @@
3940
],
4041
default=False,
4142
)
42-
def tests(session):
43+
def tests(session: nox.Session) -> None:
4344
coverage = ["python", "-m", "coverage"]
4445

4546
session.install(*nox.project.dependency_groups(PYPROJECT, "test"))
4647
session.install("-e.")
4748
env = {} if session.python != "3.14" else {"COVERAGE_CORE": "sysmon"}
4849

50+
assert session.python is not None
51+
assert not isinstance(session.python, bool)
4952
if "pypy" not in session.python:
5053
session.run(
5154
*coverage,
@@ -68,7 +71,7 @@ def tests(session):
6871

6972

7073
@nox.session(python="3.9")
71-
def lint(session):
74+
def lint(session: nox.Session) -> None:
7275
# Run the linters (via pre-commit)
7376
session.install("pre-commit")
7477
session.run("pre-commit", "run", "--all-files", *session.posargs)
@@ -80,7 +83,7 @@ def lint(session):
8083

8184

8285
@nox.session(python="3.9", default=False)
83-
def docs(session):
86+
def docs(session: nox.Session) -> None:
8487
shutil.rmtree("docs/_build", ignore_errors=True)
8588
session.install("-r", "docs/requirements.txt")
8689
session.install("-e", ".")
@@ -106,7 +109,7 @@ def docs(session):
106109

107110

108111
@nox.session(default=False)
109-
def release(session):
112+
def release(session: nox.Session) -> None:
110113
package_name = "packaging"
111114
version_file = Path(f"src/{package_name}/__init__.py")
112115
changelog_file = Path("CHANGELOG.rst")
@@ -193,7 +196,7 @@ def update_licenses(session: nox.Session) -> None:
193196
# -----------------------------------------------------------------------------
194197
# Helpers
195198
# -----------------------------------------------------------------------------
196-
def _get_version_from_arguments(arguments):
199+
def _get_version_from_arguments(arguments: list[str]) -> str:
197200
"""Checks the arguments passed to `nox -s release`.
198201
199202
Only 1 argument that looks like a version? Return the argument.
@@ -217,7 +220,7 @@ def _get_version_from_arguments(arguments):
217220
return version
218221

219222

220-
def _check_working_directory_state(session):
223+
def _check_working_directory_state(session: nox.Session) -> None:
221224
"""Check state of the working directory, prior to making the release."""
222225
should_not_exist = ["build/", "dist/"]
223226

@@ -226,7 +229,7 @@ def _check_working_directory_state(session):
226229
session.error(f"Remove {', '.join(bad_existing_paths)} and try again")
227230

228231

229-
def _check_git_state(session, version_tag):
232+
def _check_git_state(session: nox.Session, version_tag: str) -> None:
230233
"""Check state of the git repository, prior to making the release."""
231234
# Ensure the upstream remote pushes to the correct URL.
232235
allowed_upstreams = [
@@ -277,7 +280,7 @@ def _check_git_state(session, version_tag):
277280
session.run("git", "tag", _release_backup_tag, external=True)
278281

279282

280-
def _bump(session, *, version, file, kind):
283+
def _bump(session: nox.Session, *, version: str, file: Path, kind: str) -> None:
281284
session.log(f"Bump version to {version!r}")
282285
contents = file.read_text()
283286
new_contents = re.sub(
@@ -291,7 +294,9 @@ def _bump(session, *, version, file, kind):
291294

292295

293296
@contextlib.contextmanager
294-
def _replace_file(original_path):
297+
def _replace_file(
298+
original_path: Path,
299+
) -> Generator[tuple[IO[str], IO[str]], None, None]:
295300
# Create a temporary file.
296301
fh, replacement_path = tempfile.mkstemp()
297302

@@ -303,7 +308,7 @@ def _replace_file(original_path):
303308
shutil.move(replacement_path, original_path)
304309

305310

306-
def _changelog_update_unreleased_title(version, *, file):
311+
def _changelog_update_unreleased_title(version: str, *, file: Path) -> None:
307312
"""Update an "*unreleased*" heading to "{version} - {date}" """
308313
yyyy_mm_dd = datetime.datetime.now(tz=datetime.timezone.utc).strftime("%Y-%m-%d")
309314
title = f"{version} - {yyyy_mm_dd}"
@@ -320,7 +325,7 @@ def _changelog_update_unreleased_title(version, *, file):
320325
replacement.write(line)
321326

322327

323-
def _changelog_add_unreleased_title(*, file):
328+
def _changelog_add_unreleased_title(*, file: Path) -> None:
324329
with _replace_file(file) as (original, replacement):
325330
# Duplicate first 3 lines from the original file.
326331
for _ in range(3):

pyproject.toml

Lines changed: 22 additions & 44 deletions
Original file line numberDiff line numberDiff line change
@@ -83,7 +83,7 @@ python_version = "3.8"
8383
files = ["src", "tests", "noxfile.py"]
8484

8585
[[tool.mypy.overrides]]
86-
module = ["_manylinux", "pretend"]
86+
module = ["_manylinux", "pretend", "progress.*", "pkg_resources"]
8787
ignore_missing_imports = true
8888

8989
[tool.ruff]
@@ -93,63 +93,41 @@ extend-exclude = [
9393
show-fixes = true
9494

9595
[tool.ruff.lint]
96-
extend-select = [
97-
"ARG", # flake8-unused-argument
98-
"B", # flake8-bugbear
99-
"BLE", # flake8-blind-except
100-
"C4", # flake8-comprehensions
101-
"DTZ", # flake8-datetimez
102-
"E",
103-
"EXE", # flake8-executable
104-
"F",
105-
"FA", # flake8-future-annotations
106-
"FLY", # flynt
107-
"FURB", # refurb
108-
"G", # flake8-logging-format
109-
"I", # isort
110-
"ICN", # flake8-import-conventions
111-
"ISC", # flake8-implicit-str-concat
112-
"LOG", # flake8-logging
113-
"N", # pep8-naming
114-
"PERF", # perflint
115-
"PGH", # pygrep-hooks
116-
"PIE", # flake8-pie
117-
"PL", # pylint
118-
"PT", # flake8-pytest-style
119-
"PYI", # flake8-pyi
120-
"Q", # flake8-quotes
121-
"RET", # flake8-return
122-
"RSE", # flake8-raise
123-
"RUF", # Ruff-specific rules
124-
"SIM", # flake8-simplify
125-
"SLOT", # flake8-slots
126-
"T10", # flake8-debugger
127-
"T20", # flake8-print
128-
"TC", # flake8-type-checking
129-
"TRY", # tryceratops
130-
"UP", # pyupgrade
131-
"W",
132-
"YTT", # flake8-2020
133-
]
96+
select = ["ALL"]
13497
ignore = [
98+
"A002", # function args shadowing builtins is fine
99+
"C9", # complexity
100+
"COM812", # trailing commas teach the formatter
101+
"D", # doc formatting
102+
"EM", # flake8-errmsg
103+
"ERA", # commented out code
104+
"FBT", # boolean positional args (existing API)
105+
"FIX", # has todos
135106
"N818", # exceptions must end in "*Error"
136107
"PLR09", # too many ...
137108
"PLR2004", # magic value in comparison
138109
"PLW0127", # duplicate of F821
139-
"SIM103", # returning negated value directly not ideal for long chain
140-
"SIM105", # try/except is faster than contextlib.suppress
141-
"TRY003", # long messages outside exception class
110+
"PTH", # pathlib
142111
"RET505", # unused else/elif after return
143112
"RET506", # unused else/elif after raise
144113
"RET507", # unused else/elif after continue
145114
"RET508", # unused else/elif after break
115+
"S101", # assert is used by mypy and pytest
116+
"S105", # the name token doesn't mean it's a password
117+
"S603", # check for untrusted input
118+
"SIM103", # returning negated value directly not ideal for long chain
119+
"SIM105", # try/except is faster than contextlib.suppress
120+
"SLF001", # private member access
121+
"TD", # todo format
122+
"TRY003", # long messages outside exception class
146123
]
147124
flake8-comprehensions.allow-dict-calls-with-keyword-arguments = true
148125
flake8-unused-arguments.ignore-variadic-names = true
149126

150127
[tool.ruff.lint.per-file-ignores]
151-
"tests/test_*.py" = ["PYI024", "PLR", "SIM201", "T20"]
128+
"tests/test_*.py" = ["PYI024", "PLR", "SIM201", "T20", "S301"]
152129
"tasks/check.py" = ["UP032", "T20"]
153130
"tests/test_requirements.py" = ["UP032"]
154131
"src/packaging/_musllinux.py" = ["T20"]
155-
"noxfile.py" = ["T20"]
132+
"docs/conf.py" = ["INP001", "S", "A001"]
133+
"noxfile.py" = ["T20", "S"]

src/packaging/_parser.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -7,7 +7,7 @@
77
from __future__ import annotations
88

99
import ast
10-
from typing import NamedTuple, Sequence, Tuple, Union
10+
from typing import List, NamedTuple, Sequence, Tuple, Union
1111

1212
from ._tokenizer import DEFAULT_RULES, Tokenizer
1313

@@ -44,7 +44,7 @@ def serialize(self) -> str:
4444
MarkerVar = Union[Variable, Value]
4545
MarkerItem = Tuple[MarkerVar, Op, MarkerVar]
4646
MarkerAtom = Union[MarkerItem, Sequence["MarkerAtom"]]
47-
MarkerList = Sequence[Union["MarkerList", MarkerAtom, str]]
47+
MarkerList = List[Union["MarkerList", MarkerAtom, str]]
4848

4949

5050
class ParsedRequirement(NamedTuple):

src/packaging/markers.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -8,7 +8,7 @@
88
import os
99
import platform
1010
import sys
11-
from typing import AbstractSet, Any, Callable, Literal, Mapping, TypedDict, Union, cast
11+
from typing import AbstractSet, Callable, Literal, Mapping, TypedDict, Union, cast
1212

1313
from ._parser import MarkerAtom, MarkerList, Op, Value, Variable
1414
from ._parser import parse_marker as _parse_marker
@@ -121,7 +121,7 @@ class Environment(TypedDict):
121121
"""
122122

123123

124-
def _normalize_extra_values(results: Any) -> Any:
124+
def _normalize_extra_values(results: MarkerList) -> MarkerList:
125125
"""
126126
Normalize extra values.
127127
"""

src/packaging/metadata.py

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -401,16 +401,16 @@ def parse_email(data: bytes | str) -> tuple[RawMetadata, dict[str, list[str]]]:
401401
# can be independently encoded, so we'll need to check each
402402
# of them.
403403
chunks: list[tuple[bytes, str | None]] = []
404-
for bin, _encoding in email.header.decode_header(h):
404+
for binary, _encoding in email.header.decode_header(h):
405405
try:
406-
bin.decode("utf8", "strict")
406+
binary.decode("utf8", "strict")
407407
except UnicodeDecodeError:
408408
# Enable mojibake.
409409
encoding = "latin1"
410410
valid_encoding = False
411411
else:
412412
encoding = "utf8"
413-
chunks.append((bin, encoding))
413+
chunks.append((binary, encoding))
414414

415415
# Turn our chunks back into a Header object, then let that
416416
# Header object do the right thing to turn them into a

src/packaging/pylock.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -63,7 +63,7 @@ def _toml_key(key: str) -> str:
6363
return key.replace("_", "-")
6464

6565

66-
def _toml_value(key: str, value: Any) -> Any:
66+
def _toml_value(key: str, value: Any) -> Any: # noqa: ANN401
6767
if isinstance(value, (Version, Marker, SpecifierSet)):
6868
return str(value)
6969
if isinstance(value, Sequence) and key == "environments":
@@ -225,7 +225,7 @@ def _validate_path_url(path: str | None, url: str | None) -> None:
225225
def _validate_hashes(hashes: Mapping[str, Any]) -> Mapping[str, Any]:
226226
if not hashes:
227227
raise PylockValidationError("At least one hash must be provided")
228-
if not all(isinstance(hash, str) for hash in hashes.values()):
228+
if not all(isinstance(hash_val, str) for hash_val in hashes.values()):
229229
raise PylockValidationError("Hash values must be strings")
230230
return hashes
231231

tasks/check.py

Lines changed: 4 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,8 @@
22
# 2.0, and the BSD License. See the LICENSE file in the root of this repository
33
# for complete details.
44

5+
from __future__ import annotations
6+
57
import contextlib
68
import itertools
79
import json
@@ -17,15 +19,15 @@
1719
from .paths import CACHE
1820

1921

20-
def _parse_version(value):
22+
def _parse_version(value: str) -> Version | None:
2123
try:
2224
return Version(value)
2325
except ValueError:
2426
return None
2527

2628

2729
@invoke.task
28-
def pep440(cached=False):
30+
def pep440(cached: bool = False) -> None:
2931
cache_path = os.path.join(CACHE, "pep440.json")
3032

3133
# If we were given --cached, then we want to attempt to use cached data if

tasks/licenses.py

Lines changed: 5 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,10 @@
1+
from __future__ import annotations
2+
13
import pathlib
24
from contextlib import closing
35
from io import StringIO
46
from textwrap import dedent
7+
from typing import Any
58

69
import httpx
710

@@ -16,7 +19,7 @@
1619
)
1720

1821

19-
def download_data(url):
22+
def download_data(url: str) -> Any: # noqa: ANN401
2023
transport = httpx.HTTPTransport(retries=3)
2124
client = httpx.Client(transport=transport)
2225

@@ -25,7 +28,7 @@ def download_data(url):
2528
return response.json()
2629

2730

28-
def main():
31+
def main() -> None:
2932
latest_version = download_data(LATEST_SPDX_GITHUB_RELEASE_URL)["tag_name"][1:]
3033

3134
licenses = {}

0 commit comments

Comments
 (0)