nixos-rebuild-ng: enable more lints (#379975)

This commit is contained in:
Thiago Kenji Okada
2025-02-07 10:36:53 +00:00
committed by GitHub
8 changed files with 40 additions and 19 deletions
@@ -2,7 +2,7 @@
# Use strings to avoid breaking standalone (e.g.: `python -m nixos_rebuild`)
# usage
EXECUTABLE = "@executable@"
# Use either `== "true"` if the default (e.g.: `python -m nixos_rebuld`) is
# Use either `== "true"` if the default (e.g.: `python -m nixos_rebuild`) is
# `False` or `!= "false"` if the default is `True`
WITH_NIX_2_18 = "@withNix218@" != "false" # type: ignore
WITH_REEXEC = "@withReexec@" == "true" # type: ignore
@@ -14,7 +14,7 @@ type ImageVariants = dict[str, str]
class NRError(Exception):
"nixos-rebuild general error."
def __init__(self, message: str):
def __init__(self, message: str) -> None:
self.message = message
@override
@@ -433,14 +433,14 @@ def list_generations(profile: Profile) -> list[GenerationJson]:
)
try:
nixos_version = (generation_path / "nixos-version").read_text().strip()
except IOError as ex:
except OSError as ex:
logger.debug("could not get nixos-version: %s", ex)
nixos_version = "Unknown"
try:
kernel_version = next(
(generation_path / "kernel-modules/lib/modules").iterdir()
).name
except IOError as ex:
except OSError as ex:
logger.debug("could not get kernel version: %s", ex)
kernel_version = "Unknown"
specialisations = [
@@ -451,7 +451,7 @@ def list_generations(profile: Profile) -> list[GenerationJson]:
[generation_path / "sw/bin/nixos-version", "--configuration-revision"],
capture_output=True,
).stdout.strip()
except (CalledProcessError, IOError) as ex:
except (OSError, CalledProcessError) as ex:
logger.debug("could not get configuration revision: %s", ex)
configuration_revision = "Unknown"
@@ -583,7 +583,7 @@ def switch_to_configuration(
)
def upgrade_channels(all: bool = False) -> None:
def upgrade_channels(all_channels: bool = False) -> None:
"""Upgrade channels for classic Nix.
It will either upgrade just the `nixos` channel (including any channel
@@ -591,7 +591,7 @@ def upgrade_channels(all: bool = False) -> None:
"""
for channel_path in Path("/nix/var/nix/profiles/per-user/root/channels/").glob("*"):
if channel_path.is_dir() and (
all
all_channels
or channel_path.name == "nixos"
or (channel_path / ".update-on-nixos-rebuild").exists()
):
@@ -3,9 +3,10 @@ import logging
import os
import shlex
import subprocess
from collections.abc import Sequence
from dataclasses import dataclass
from getpass import getpass
from typing import Final, Self, Sequence, TypedDict, Unpack
from typing import Final, Self, TypedDict, Unpack
from . import tmpdir
@@ -91,7 +92,7 @@ def run_wrapper(
) -> subprocess.CompletedProcess[str]:
"Wrapper around `subprocess.run` that supports extra functionality."
env = None
input = None
process_input = None
if remote:
if extra_env:
extra_env_args = [f"{env}={value}" for env, value in extra_env.items()]
@@ -99,7 +100,7 @@ def run_wrapper(
if sudo:
if remote.sudo_password:
args = ["sudo", "--prompt=", "--stdin", *args]
input = remote.sudo_password + "\n"
process_input = remote.sudo_password + "\n"
else:
args = ["sudo", *args]
args = [
@@ -132,7 +133,7 @@ def run_wrapper(
args,
check=check,
env=env,
input=input,
input=process_input,
# Hope nobody is using NixOS with non-UTF8 encodings, but "surrogateescape"
# should still work in those systems.
text=True,
@@ -1,13 +1,13 @@
import logging
from collections.abc import Mapping, Sequence
from typing import Any, assert_never, override
from typing import Any, ClassVar, assert_never, override
type Arg = bool | str | list[str] | list[list[str]] | int | None
type Args = dict[str, Arg]
class LogFormatter(logging.Formatter):
formatters = {
formatters: ClassVar = {
logging.INFO: logging.Formatter("%(message)s"),
logging.DEBUG: logging.Formatter("%(levelname)s: %(name)s: %(message)s"),
"DEFAULT": logging.Formatter("%(levelname)s: %(message)s"),
@@ -37,7 +37,7 @@ def dict_to_flags(d: Args | None) -> list[str]:
case int() if len(key) == 1:
flags.append(f"-{key * value}")
case int():
for i in range(value):
for _ in range(value):
flags.append(flag)
case str():
flags.append(flag)
@@ -39,12 +39,32 @@ ignore_missing_imports = true
[tool.ruff.lint]
extend-select = [
# Enforce type annotations
"ANN",
# don't shadow built-in names
"A",
# Better list/set/dict comprehensions
"C4",
# Check for debugger statements
"T10",
# ensure imports are sorted
"I",
# Automatically upgrade syntax for newer versions
"UP",
# detect common sources of bugs
"B",
# Ruff specific rules
"RUF",
# require `check` argument for `subprocess.run`
"PLW1510",
# check for needless exception names in raise statements
"TRY201",
# Pythonic naming conventions
"N",
]
ignore = [
# allow Any type
"ANN401"
]
[tool.ruff.lint.per-file-ignores]
@@ -132,7 +132,7 @@ def test_build_remote(mock_uuid4: Any, mock_run: Any, monkeypatch: MonkeyPatch)
Path("/path/to/file"),
],
extra_env={
"NIX_SSHOPTS": " ".join(p.SSH_DEFAULT_OPTS + ["--ssh opts"])
"NIX_SSHOPTS": " ".join([*p.SSH_DEFAULT_OPTS, "--ssh opts"])
},
),
call(
@@ -206,7 +206,7 @@ def test_build_remote_flake(
Path("/path/to/file"),
],
extra_env={
"NIX_SSHOPTS": " ".join(p.SSH_DEFAULT_OPTS + ["--ssh opts"])
"NIX_SSHOPTS": " ".join([*p.SSH_DEFAULT_OPTS, "--ssh opts"])
},
),
call(
@@ -247,14 +247,14 @@ def test_copy_closure(monkeypatch: MonkeyPatch) -> None:
mock_run.assert_called_with(
["nix-copy-closure", "--copy-flag", "--from", "user@build.host", closure],
extra_env={
"NIX_SSHOPTS": " ".join(p.SSH_DEFAULT_OPTS + ["--ssh build-opt"])
"NIX_SSHOPTS": " ".join([*p.SSH_DEFAULT_OPTS, "--ssh build-opt"])
},
)
monkeypatch.setenv("NIX_SSHOPTS", "--ssh build-target-opt")
monkeypatch.setattr(n, "WITH_NIX_2_18", True)
extra_env = {
"NIX_SSHOPTS": " ".join(p.SSH_DEFAULT_OPTS + ["--ssh build-target-opt"])
"NIX_SSHOPTS": " ".join([*p.SSH_DEFAULT_OPTS, "--ssh build-target-opt"])
}
with patch(get_qualified_name(n.run_wrapper, n), autospec=True) as mock_run:
n.copy_closure(closure, target_host, build_host, {"copy_flag": True})
@@ -28,7 +28,7 @@ let
# In case we want/need to evaluate packages or the assertions or whatever,
# we want to have a linux system.
# TODO: make the non-flake test use thise.
# TODO: make the non-flake test use this.
linuxSystem = lib.replaceStrings [ "darwin" ] [ "linux" ] stdenv.hostPlatform.system;
in