Skip to content

Commit e90a0ab

Browse files
authored
nixos-rebuild-ng: enable more lints (NixOS#379975)
2 parents 7d06208 + 24f5c3a commit e90a0ab

File tree

8 files changed

+40
-19
lines changed

8 files changed

+40
-19
lines changed

pkgs/by-name/ni/nixos-rebuild-ng/src/nixos_rebuild/constants.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,7 @@
22
# Use strings to avoid breaking standalone (e.g.: `python -m nixos_rebuild`)
33
# usage
44
EXECUTABLE = "@executable@"
5-
# Use either `== "true"` if the default (e.g.: `python -m nixos_rebuld`) is
5+
# Use either `== "true"` if the default (e.g.: `python -m nixos_rebuild`) is
66
# `False` or `!= "false"` if the default is `True`
77
WITH_NIX_2_18 = "@withNix218@" != "false" # type: ignore
88
WITH_REEXEC = "@withReexec@" == "true" # type: ignore

pkgs/by-name/ni/nixos-rebuild-ng/src/nixos_rebuild/models.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -14,7 +14,7 @@
1414
class NRError(Exception):
1515
"nixos-rebuild general error."
1616

17-
def __init__(self, message: str):
17+
def __init__(self, message: str) -> None:
1818
self.message = message
1919

2020
@override

pkgs/by-name/ni/nixos-rebuild-ng/src/nixos_rebuild/nix.py

Lines changed: 5 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -433,14 +433,14 @@ def get_generation_info(generation: Generation) -> GenerationJson:
433433
)
434434
try:
435435
nixos_version = (generation_path / "nixos-version").read_text().strip()
436-
except IOError as ex:
436+
except OSError as ex:
437437
logger.debug("could not get nixos-version: %s", ex)
438438
nixos_version = "Unknown"
439439
try:
440440
kernel_version = next(
441441
(generation_path / "kernel-modules/lib/modules").iterdir()
442442
).name
443-
except IOError as ex:
443+
except OSError as ex:
444444
logger.debug("could not get kernel version: %s", ex)
445445
kernel_version = "Unknown"
446446
specialisations = [
@@ -451,7 +451,7 @@ def get_generation_info(generation: Generation) -> GenerationJson:
451451
[generation_path / "sw/bin/nixos-version", "--configuration-revision"],
452452
capture_output=True,
453453
).stdout.strip()
454-
except (CalledProcessError, IOError) as ex:
454+
except (OSError, CalledProcessError) as ex:
455455
logger.debug("could not get configuration revision: %s", ex)
456456
configuration_revision = "Unknown"
457457

@@ -583,15 +583,15 @@ def switch_to_configuration(
583583
)
584584

585585

586-
def upgrade_channels(all: bool = False) -> None:
586+
def upgrade_channels(all_channels: bool = False) -> None:
587587
"""Upgrade channels for classic Nix.
588588
589589
It will either upgrade just the `nixos` channel (including any channel
590590
that has a `.update-on-nixos-rebuild` file) or all.
591591
"""
592592
for channel_path in Path("/nix/var/nix/profiles/per-user/root/channels/").glob("*"):
593593
if channel_path.is_dir() and (
594-
all
594+
all_channels
595595
or channel_path.name == "nixos"
596596
or (channel_path / ".update-on-nixos-rebuild").exists()
597597
):

pkgs/by-name/ni/nixos-rebuild-ng/src/nixos_rebuild/process.py

Lines changed: 5 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -3,9 +3,10 @@
33
import os
44
import shlex
55
import subprocess
6+
from collections.abc import Sequence
67
from dataclasses import dataclass
78
from getpass import getpass
8-
from typing import Final, Self, Sequence, TypedDict, Unpack
9+
from typing import Final, Self, TypedDict, Unpack
910

1011
from . import tmpdir
1112

@@ -91,15 +92,15 @@ def run_wrapper(
9192
) -> subprocess.CompletedProcess[str]:
9293
"Wrapper around `subprocess.run` that supports extra functionality."
9394
env = None
94-
input = None
95+
process_input = None
9596
if remote:
9697
if extra_env:
9798
extra_env_args = [f"{env}={value}" for env, value in extra_env.items()]
9899
args = ["env", *extra_env_args, *args]
99100
if sudo:
100101
if remote.sudo_password:
101102
args = ["sudo", "--prompt=", "--stdin", *args]
102-
input = remote.sudo_password + "\n"
103+
process_input = remote.sudo_password + "\n"
103104
else:
104105
args = ["sudo", *args]
105106
args = [
@@ -132,7 +133,7 @@ def run_wrapper(
132133
args,
133134
check=check,
134135
env=env,
135-
input=input,
136+
input=process_input,
136137
# Hope nobody is using NixOS with non-UTF8 encodings, but "surrogateescape"
137138
# should still work in those systems.
138139
text=True,

pkgs/by-name/ni/nixos-rebuild-ng/src/nixos_rebuild/utils.py

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,13 +1,13 @@
11
import logging
22
from collections.abc import Mapping, Sequence
3-
from typing import Any, assert_never, override
3+
from typing import Any, ClassVar, assert_never, override
44

55
type Arg = bool | str | list[str] | list[list[str]] | int | None
66
type Args = dict[str, Arg]
77

88

99
class LogFormatter(logging.Formatter):
10-
formatters = {
10+
formatters: ClassVar = {
1111
logging.INFO: logging.Formatter("%(message)s"),
1212
logging.DEBUG: logging.Formatter("%(levelname)s: %(name)s: %(message)s"),
1313
"DEFAULT": logging.Formatter("%(levelname)s: %(message)s"),
@@ -37,7 +37,7 @@ def dict_to_flags(d: Args | None) -> list[str]:
3737
case int() if len(key) == 1:
3838
flags.append(f"-{key * value}")
3939
case int():
40-
for i in range(value):
40+
for _ in range(value):
4141
flags.append(flag)
4242
case str():
4343
flags.append(flag)

pkgs/by-name/ni/nixos-rebuild-ng/src/pyproject.toml

Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -39,12 +39,32 @@ ignore_missing_imports = true
3939

4040
[tool.ruff.lint]
4141
extend-select = [
42+
# Enforce type annotations
43+
"ANN",
44+
# don't shadow built-in names
45+
"A",
46+
# Better list/set/dict comprehensions
47+
"C4",
48+
# Check for debugger statements
49+
"T10",
4250
# ensure imports are sorted
4351
"I",
52+
# Automatically upgrade syntax for newer versions
53+
"UP",
54+
# detect common sources of bugs
55+
"B",
56+
# Ruff specific rules
57+
"RUF",
4458
# require `check` argument for `subprocess.run`
4559
"PLW1510",
4660
# check for needless exception names in raise statements
4761
"TRY201",
62+
# Pythonic naming conventions
63+
"N",
64+
]
65+
ignore = [
66+
# allow Any type
67+
"ANN401"
4868
]
4969

5070
[tool.ruff.lint.per-file-ignores]

pkgs/by-name/ni/nixos-rebuild-ng/src/tests/test_nix.py

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -132,7 +132,7 @@ def run_wrapper_side_effect(
132132
Path("/path/to/file"),
133133
],
134134
extra_env={
135-
"NIX_SSHOPTS": " ".join(p.SSH_DEFAULT_OPTS + ["--ssh opts"])
135+
"NIX_SSHOPTS": " ".join([*p.SSH_DEFAULT_OPTS, "--ssh opts"])
136136
},
137137
),
138138
call(
@@ -206,7 +206,7 @@ def test_build_remote_flake(
206206
Path("/path/to/file"),
207207
],
208208
extra_env={
209-
"NIX_SSHOPTS": " ".join(p.SSH_DEFAULT_OPTS + ["--ssh opts"])
209+
"NIX_SSHOPTS": " ".join([*p.SSH_DEFAULT_OPTS, "--ssh opts"])
210210
},
211211
),
212212
call(
@@ -247,14 +247,14 @@ def test_copy_closure(monkeypatch: MonkeyPatch) -> None:
247247
mock_run.assert_called_with(
248248
["nix-copy-closure", "--copy-flag", "--from", "user@build.host", closure],
249249
extra_env={
250-
"NIX_SSHOPTS": " ".join(p.SSH_DEFAULT_OPTS + ["--ssh build-opt"])
250+
"NIX_SSHOPTS": " ".join([*p.SSH_DEFAULT_OPTS, "--ssh build-opt"])
251251
},
252252
)
253253

254254
monkeypatch.setenv("NIX_SSHOPTS", "--ssh build-target-opt")
255255
monkeypatch.setattr(n, "WITH_NIX_2_18", True)
256256
extra_env = {
257-
"NIX_SSHOPTS": " ".join(p.SSH_DEFAULT_OPTS + ["--ssh build-target-opt"])
257+
"NIX_SSHOPTS": " ".join([*p.SSH_DEFAULT_OPTS, "--ssh build-target-opt"])
258258
}
259259
with patch(get_qualified_name(n.run_wrapper, n), autospec=True) as mock_run:
260260
n.copy_closure(closure, target_host, build_host, {"copy_flag": True})

pkgs/by-name/ni/nixos-rebuild-ng/tests/repl.nix

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -28,7 +28,7 @@ let
2828

2929
# In case we want/need to evaluate packages or the assertions or whatever,
3030
# we want to have a linux system.
31-
# TODO: make the non-flake test use thise.
31+
# TODO: make the non-flake test use this.
3232
linuxSystem = lib.replaceStrings [ "darwin" ] [ "linux" ] stdenv.hostPlatform.system;
3333

3434
in

0 commit comments

Comments
 (0)