Skip to content

Commit 4dab936

Browse files
committed
various fixes to ruff lint
Signed-off-by: Arthur Zamarin <arthurzam@gentoo.org>
1 parent 19d6690 commit 4dab936

14 files changed

Lines changed: 78 additions & 87 deletions

‎pyproject.toml‎

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -71,6 +71,12 @@ exclude = [
7171
line-length = 100
7272
target-version = "py311"
7373

74+
[tool.ruff.lint.per-file-ignores]
75+
"tests/**" = [
76+
"C408", # Unnecessary `dict()` call"
77+
"SIM117", # multiple-with-statements
78+
]
79+
7480
[tool.black]
7581
line-length = 100
7682

‎src/pkgdev/mangle.py‎

Lines changed: 4 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -6,7 +6,8 @@
66
import re
77
import signal
88
import traceback
9-
from datetime import datetime
9+
from datetime import UTC, datetime
10+
from typing import ClassVar
1011

1112
from pkgcore.ebuild.misc import sort_keywords
1213
from snakeoil.cli.exceptions import UserException
@@ -41,7 +42,7 @@ class Mangler:
4142
"""File-mangling iterator using path-based parallelism."""
4243

4344
# mapping of mangling types to functions
44-
_mangle_funcs = {}
45+
_mangle_funcs: ClassVar[dict[str, callable]] = {}
4546

4647
def __init__(self, changes, skip_regex=None):
4748
self.jobs = os.cpu_count()
@@ -52,7 +53,7 @@ def __init__(self, changes, skip_regex=None):
5253
# setup for parallelizing the mangling procedure across files
5354
self._mp_ctx = multiprocessing.get_context("fork")
5455
self._mangled_paths_q = self._mp_ctx.SimpleQueue()
55-
self._current_year = str(datetime.today().year)
56+
self._current_year = str(datetime.now(tz=UTC).year)
5657

5758
# initialize settings used by iterator support
5859
self._runner = self._mp_ctx.Process(target=self._run)

‎src/pkgdev/scripts/pkgdev_bugs.py‎

Lines changed: 12 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -9,7 +9,7 @@
99
import tomllib
1010
import urllib.request as urllib
1111
from collections import defaultdict
12-
from datetime import datetime
12+
from datetime import UTC, datetime
1313
from functools import partial
1414
from itertools import chain
1515
from os.path import join as pjoin
@@ -77,7 +77,7 @@ def __call__(self, parser, namespace, values, option_string=None):
7777
if not sys.stdin.isatty():
7878
values = [x.strip() for x in sys.stdin.readlines() if x.strip()]
7979
# reassign stdin to allow interactivity (currently only works for unix)
80-
sys.stdin = open("/dev/tty")
80+
sys.stdin = open("/dev/tty") # noqa: SIM115
8181
else:
8282
parser.error("'-' is only valid when piping data in")
8383

@@ -408,11 +408,12 @@ def file_bug(
408408

409409
description = [f"Please {self.category.verb}", ""]
410410
if modified_repo is not None:
411+
now = datetime.now(tz=UTC)
411412
for pkg, _ in self.pkgs:
412413
with contextlib.suppress(StopIteration):
413414
match = next(modified_repo.itermatch(pkg.versioned_atom))
414-
modified = datetime.fromtimestamp(match.time)
415-
days_old = (datetime.today() - modified).days
415+
modified = datetime.fromtimestamp(match.time, tz=UTC)
416+
days_old = (now - modified).days
416417
description.append(
417418
f" {pkg.versioned_atom.cpvstr}: no change for {days_old} days, since {modified:%Y-%m-%d}"
418419
)
@@ -889,19 +890,20 @@ def output_graph_toml(self):
889890
):
890891
toml.write(f"blocks = [{node_blocks}]\n")
891892
toml.write(f"obsoletes = {sorted(node.obsoletes)}\n")
893+
now = datetime.now(tz=UTC)
892894
for pkg, arches in node.pkgs:
893895
try:
894896
match = next(self.modified_repo.itermatch(pkg.versioned_atom))
895-
modified = datetime.fromtimestamp(match.time)
896-
age = (datetime.today() - modified).days
897+
modified = datetime.fromtimestamp(match.time, tz=UTC)
898+
age = (now - modified).days
897899
modified_text = f"{modified:%Y-%m-%d} (age {age} days)"
898900
except StopIteration:
899901
modified_text = "<unknown>"
900902

901903
try:
902904
match = next(self.added_repo.itermatch(pkg.versioned_atom))
903-
added = datetime.fromtimestamp(match.time)
904-
age = (datetime.today() - added).days
905+
added = datetime.fromtimestamp(match.time, tz=UTC)
906+
age = (now - added).days
905907
added_text = f"{added:%Y-%m-%d} (age {age} days)"
906908
except StopIteration:
907909
added_text = "<unknown>"
@@ -1177,7 +1179,7 @@ def _load_from_stdin(out: Formatter):
11771179
atom_str, *arches = line.split()
11781180
yield atom_str, parserestrict.parse_match(atom_str), frozenset(arches)
11791181
# reassign stdin to allow interactivity (currently only works for unix)
1180-
sys.stdin = open("/dev/tty")
1182+
sys.stdin = open("/dev/tty") # noqa: SIM115
11811183
else:
11821184
bugs.error("reading from stdin is only valid when piping data in")
11831185

@@ -1237,7 +1239,7 @@ def main(options, out: Formatter, err: Formatter):
12371239
try:
12381240
subprocess.run(editor + [toml.name], check=True)
12391241
except subprocess.CalledProcessError:
1240-
bugs.error("failed writing mask comment")
1242+
bugs.error("failed opening editor, aborting")
12411243
except FileNotFoundError:
12421244
bugs.error(f"nonexistent editor: {editor[0]!r}")
12431245
try:

‎src/pkgdev/scripts/pkgdev_commit.py‎

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -14,6 +14,7 @@
1414
from functools import partial
1515
from itertools import chain
1616
from os.path import join as pjoin
17+
from typing import ClassVar
1718

1819
from pkgcheck import reporters, scan
1920
from pkgcore.ebuild.atom import MalformedAtom
@@ -384,7 +385,7 @@ def __str__(self):
384385
class MetadataSummary(ChangeSummary):
385386
"""Summary generation support for metadata.xml changes."""
386387

387-
status_funcs = {}
388+
status_funcs: ClassVar[dict[str, callable]] = {}
388389

389390
def __init__(self, options, changes):
390391
super().__init__(options)
@@ -440,7 +441,7 @@ def modify(self):
440441
class PkgSummary(ChangeSummary):
441442
"""Summary generation support for single package ebuild changes."""
442443

443-
status_funcs = {}
444+
status_funcs: ClassVar[dict[str, callable]] = {}
444445

445446
def __init__(self, options, changes):
446447
super().__init__(options)

‎src/pkgdev/scripts/pkgdev_mask.py‎

Lines changed: 7 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -353,14 +353,13 @@ def _mask(options, out, err):
353353
email = p.stdout.strip()
354354

355355
message = get_comment()
356-
if options.file_bug:
357-
if bug_no := file_last_rites_bug(options, message):
358-
out.write(out.fg("green"), f"filed bug https://bugs.gentoo.org/{bug_no}", out.reset)
359-
out.flush()
360-
if not update_bugs_pmasked(options.bugzilla, options.bugs):
361-
err.write(err.fg("red"), "failed to update referenced bugs", err.reset)
362-
err.flush()
363-
options.bugs.insert(0, bug_no)
356+
if options.file_bug and (bug_no := file_last_rites_bug(options, message)):
357+
out.write(out.fg("green"), f"filed bug https://bugs.gentoo.org/{bug_no}", out.reset)
358+
out.flush()
359+
if not update_bugs_pmasked(options.bugzilla, options.bugs):
360+
err.write(err.fg("red"), "failed to update referenced bugs", err.reset)
361+
err.flush()
362+
options.bugs.insert(0, bug_no)
364363
if removal := message_removal_notice(options.bugs, options.rites):
365364
message.append(removal)
366365

‎src/pkgdev/scripts/pkgdev_showkw.py‎

Lines changed: 1 addition & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -11,7 +11,6 @@
1111
from .. import cli
1212
from .._vendor.tabulate import tabulate, tabulate_formats
1313

14-
1514
showkw = cli.ArgumentParser(prog="pkgdev showkw", description="show package keywords")
1615
showkw.add_argument(
1716
"targets",
@@ -123,7 +122,7 @@ def _setup_arches(namespace, attr):
123122
if disabled_arches:
124123
arches = arches - disabled_arches
125124

126-
prefix_arches = set(x for x in arches if "-" in x)
125+
prefix_arches = {x for x in arches if "-" in x}
127126
native_arches = arches.difference(prefix_arches)
128127
arches = native_arches
129128
if namespace.prefix:

‎tests/scripts/test_cli.py‎

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,9 +1,10 @@
11
import textwrap
22

33
import pytest
4-
from pkgdev import cli
54
from snakeoil.cli import arghparse
65

6+
from pkgdev import cli
7+
78

89
class TestConfigFileParser:
910
@pytest.fixture(autouse=True)

‎tests/scripts/test_pkgdev.py‎

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -19,7 +19,7 @@ def test_script_run(capsys):
1919
with pytest.raises(SystemExit) as excinfo:
2020
script()
2121
assert excinfo.value.code == 1
22-
out, err = capsys.readouterr()
22+
_out, err = capsys.readouterr()
2323
err = err.strip().split("\n")
2424
assert len(err) == 3
2525
assert err[0] == "Failed importing: baz module doesn't exist!"
@@ -30,7 +30,7 @@ def test_script_run(capsys):
3030
with patch("sys.argv", [project, "--debug"]):
3131
with pytest.raises(ImportError):
3232
script()
33-
out, err = capsys.readouterr()
33+
_out, err = capsys.readouterr()
3434
err = err.strip().split("\n")
3535
assert len(err) == 2
3636
assert err[0] == "Failed importing: baz module doesn't exist!"
@@ -47,5 +47,5 @@ def test_version(self, capsys):
4747
with pytest.raises(SystemExit) as excinfo:
4848
self.script()
4949
assert excinfo.value.code == 0
50-
out, err = capsys.readouterr()
50+
out, _err = capsys.readouterr()
5151
assert out.startswith(project)

‎tests/scripts/test_pkgdev_commit.py‎

Lines changed: 6 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,7 @@
22
import shutil
33
import textwrap
44
from contextlib import chdir
5-
from datetime import datetime
5+
from datetime import UTC, datetime
66
from functools import partial
77
from io import StringIO
88
from os.path import join as pjoin
@@ -20,22 +20,22 @@ def test_non_repo_cwd(self, capsys, tool):
2020
with pytest.raises(SystemExit) as excinfo:
2121
tool.parse_args(["commit"])
2222
assert excinfo.value.code == 2
23-
out, err = capsys.readouterr()
23+
_out, err = capsys.readouterr()
2424
assert err.strip() == "pkgdev commit: error: not in ebuild repo"
2525

2626
def test_bad_repo_cwd(self, make_repo, capsys, tool):
2727
repo = make_repo(masters=("nonexistent",))
2828
with pytest.raises(SystemExit) as excinfo, chdir(repo.location):
2929
tool.parse_args(["commit"])
3030
assert excinfo.value.code == 2
31-
out, err = capsys.readouterr()
31+
_out, err = capsys.readouterr()
3232
assert err.strip().startswith("pkgdev commit: error: repo init failed")
3333

3434
def test_non_git_repo_cwd(self, repo, capsys, tool):
3535
with pytest.raises(SystemExit) as excinfo, chdir(repo.location):
3636
tool.parse_args(["commit"])
3737
assert excinfo.value.code == 2
38-
out, err = capsys.readouterr()
38+
_out, err = capsys.readouterr()
3939
assert err.strip() == "pkgdev commit: error: not in git repo"
4040

4141
def test_non_ebuild_git_repo_cwd(self, make_repo, git_repo, capsys, tool):
@@ -44,7 +44,7 @@ def test_non_ebuild_git_repo_cwd(self, make_repo, git_repo, capsys, tool):
4444
with pytest.raises(SystemExit) as excinfo, chdir(repo.location):
4545
tool.parse_args(["commit"])
4646
assert excinfo.value.code == 2
47-
out, err = capsys.readouterr()
47+
_out, err = capsys.readouterr()
4848
assert err.strip() == "pkgdev commit: error: not in ebuild git repo"
4949

5050
def test_commit_signing(self, repo, make_git_repo, tool):
@@ -1039,7 +1039,7 @@ def commit(args):
10391039
with open(ebuild_path) as f:
10401040
lines = f.read().splitlines()
10411041
mo = copyright_regex.match(lines[0])
1042-
assert mo.group("end") == str(datetime.today().year)
1042+
assert mo.group("end") == str(datetime.now(tz=UTC).year)
10431043
assert mo.group("begin") == years[:4] + "-"
10441044
assert mo.group("holder") == "Gentoo Authors"
10451045

‎tests/scripts/test_pkgdev_manifest.py‎

Lines changed: 7 additions & 26 deletions
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,6 @@
22
from contextlib import chdir
33
from functools import partial
44
from os.path import join as pjoin
5-
from typing import List, Set
65
from unittest.mock import patch
76

87
import pytest
@@ -16,7 +15,7 @@ def test_non_repo_cwd(self, capsys, tool):
1615
with pytest.raises(SystemExit) as excinfo:
1716
tool.parse_args(["manifest"])
1817
assert excinfo.value.code == 2
19-
out, err = capsys.readouterr()
18+
_out, err = capsys.readouterr()
2019
assert err.strip() == "pkgdev manifest: error: not in ebuild repo"
2120

2221
@pytest.mark.skip
@@ -57,7 +56,7 @@ def test_repo_relative_outside(self, tmp_path, repo, capsys, tool):
5756
with chdir(repo.location):
5857
tool.parse_args(["manifest", str(ebuild)])
5958
assert excinfo.value.code == 2
60-
out, err = capsys.readouterr()
59+
_out, err = capsys.readouterr()
6160
assert (
6261
err.strip()
6362
== f"pkgdev manifest: error: {repo.repo_id!r} repo doesn't contain: {str(ebuild)!r}"
@@ -86,7 +85,7 @@ def test_atom_target(self, repo, capsys, tool):
8685
assert matches == ["cat/pkg-0"]
8786

8887
def test_if_modified_target(self, repo, make_git_repo, tool):
89-
def manifest_matches() -> Set[str]:
88+
def manifest_matches() -> set[str]:
9089
repo.sync()
9190
with chdir(repo.location):
9291
options, _ = tool.parse_args(["manifest", "--if-modified"])
@@ -136,7 +135,7 @@ def manifest_matches() -> Set[str]:
136135

137136
@pytest.mark.skip
138137
def test_ignore_fetch_restricted(self, repo, tool):
139-
def manifest_matches() -> List[str]:
138+
def manifest_matches() -> list[str]:
140139
with chdir(repo.location):
141140
options, _ = tool.parse_args(["manifest", "--ignore-fetch-restricted"])
142141
return [x.cpvstr for x in repo.itermatch(options.restriction)]
@@ -161,14 +160,14 @@ def test_non_repo_dir_target(self, tmp_path, repo, capsys, tool):
161160
with pytest.raises(SystemExit) as excinfo, chdir(repo.location):
162161
tool.parse_args(["manifest", str(tmp_path)])
163162
assert excinfo.value.code == 2
164-
out, err = capsys.readouterr()
163+
_out, err = capsys.readouterr()
165164
assert err.startswith("pkgdev manifest: error: 'fake' repo doesn't contain:")
166165

167166
def test_invalid_atom_target(self, repo, capsys, tool):
168167
with pytest.raises(SystemExit) as excinfo, chdir(repo.location):
169168
tool.parse_args(["manifest", "=cat/pkg"])
170169
assert excinfo.value.code == 2
171-
out, err = capsys.readouterr()
170+
_out, err = capsys.readouterr()
172171
assert err.startswith("pkgdev manifest: error: invalid atom: '=cat/pkg'")
173172

174173

@@ -207,7 +206,7 @@ def test_target_within_pkgdir(self, capsys, repo):
207206
):
208207
self.script()
209208
assert excinfo.value.code == 0
210-
out, err = capsys.readouterr()
209+
_out, err = capsys.readouterr()
211210
assert err == ""
212211

213212
def test_good_manifest_quiet(self, capsys, repo):
@@ -222,24 +221,6 @@ def test_good_manifest_quiet(self, capsys, repo):
222221
out, err = capsys.readouterr()
223222
assert out == err == ""
224223

225-
def test_target_within_pkgdir(self, capsys, repo):
226-
"""Any file inside a package dir manifests that package."""
227-
repo.create_ebuild("cat/pkg-0")
228-
pkgdir = os.path.dirname(repo.create_ebuild("cat/pkg-1"))
229-
os.makedirs(pjoin(pkgdir, "files"), exist_ok=True)
230-
touch(pjoin(pkgdir, "files", "a.patch"))
231-
for target in ("files/a.patch", "files", "metadata.xml"):
232-
touch(pjoin(pkgdir, "metadata.xml"))
233-
with (
234-
patch("sys.argv", self.args + [target]),
235-
pytest.raises(SystemExit) as excinfo,
236-
chdir(pkgdir),
237-
):
238-
self.script()
239-
assert excinfo.value.code == 0
240-
out, err = capsys.readouterr()
241-
assert err == ""
242-
243224
def test_bad_manifest(self, capsys, repo):
244225
repo.create_ebuild("cat/pkg-0")
245226
repo.create_ebuild("cat/pkg-1", eapi="-1")

0 commit comments

Comments
 (0)