Skip to content

Commit 8ae4873

Browse files
authored
nixos-rebuild-ng: refactors (#368619)
2 parents 24f42ee + f25fb0d commit 8ae4873

File tree

6 files changed

+91
-74
lines changed

6 files changed

+91
-74
lines changed

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

Lines changed: 41 additions & 33 deletions
Original file line numberDiff line numberDiff line change
@@ -43,19 +43,19 @@ def get_parser() -> tuple[argparse.ArgumentParser, dict[str, argparse.ArgumentPa
4343
common_build_flags.add_argument("--print-build-logs", "-L", action="store_true")
4444
common_build_flags.add_argument("--show-trace", action="store_true")
4545

46-
flake_build_flags = argparse.ArgumentParser(add_help=False)
47-
flake_build_flags.add_argument("--accept-flake-config", action="store_true")
48-
flake_build_flags.add_argument("--refresh", action="store_true")
49-
flake_build_flags.add_argument("--impure", action="store_true")
50-
flake_build_flags.add_argument("--offline", action="store_true")
51-
flake_build_flags.add_argument("--no-net", action="store_true")
52-
flake_build_flags.add_argument("--recreate-lock-file", action="store_true")
53-
flake_build_flags.add_argument("--no-update-lock-file", action="store_true")
54-
flake_build_flags.add_argument("--no-write-lock-file", action="store_true")
55-
flake_build_flags.add_argument("--no-registries", action="store_true")
56-
flake_build_flags.add_argument("--commit-lock-file", action="store_true")
57-
flake_build_flags.add_argument("--update-input")
58-
flake_build_flags.add_argument("--override-input", nargs=2)
46+
flake_common_flags = argparse.ArgumentParser(add_help=False)
47+
flake_common_flags.add_argument("--accept-flake-config", action="store_true")
48+
flake_common_flags.add_argument("--refresh", action="store_true")
49+
flake_common_flags.add_argument("--impure", action="store_true")
50+
flake_common_flags.add_argument("--offline", action="store_true")
51+
flake_common_flags.add_argument("--no-net", action="store_true")
52+
flake_common_flags.add_argument("--recreate-lock-file", action="store_true")
53+
flake_common_flags.add_argument("--no-update-lock-file", action="store_true")
54+
flake_common_flags.add_argument("--no-write-lock-file", action="store_true")
55+
flake_common_flags.add_argument("--no-registries", action="store_true")
56+
flake_common_flags.add_argument("--commit-lock-file", action="store_true")
57+
flake_common_flags.add_argument("--update-input")
58+
flake_common_flags.add_argument("--override-input", nargs=2)
5959

6060
classic_build_flags = argparse.ArgumentParser(add_help=False)
6161
classic_build_flags.add_argument("--no-build-output", "-Q", action="store_true")
@@ -74,7 +74,7 @@ def get_parser() -> tuple[argparse.ArgumentParser, dict[str, argparse.ArgumentPa
7474
sub_parsers = {
7575
"common_flags": common_flags,
7676
"common_build_flags": common_build_flags,
77-
"flake_build_flags": flake_build_flags,
77+
"flake_common_flags": flake_common_flags,
7878
"classic_build_flags": classic_build_flags,
7979
"copy_flags": copy_flags,
8080
}
@@ -262,19 +262,27 @@ def parser_warn(msg: str) -> None:
262262
def reexec(
263263
argv: list[str],
264264
args: argparse.Namespace,
265-
build_flags: dict[str, Args],
266-
flake_build_flags: dict[str, Args],
265+
build_flags: Args,
266+
flake_build_flags: Args,
267267
) -> None:
268268
drv = None
269269
attr = "config.system.build.nixos-rebuild"
270270
try:
271271
# Parsing the args here but ignore ask_sudo_password since it is not
272272
# needed and we would end up asking sudo password twice
273273
if flake := Flake.from_arg(args.flake, Remote.from_arg(args.target_host, None)):
274-
drv = nix.build_flake(attr, flake, **flake_build_flags, no_link=True)
274+
drv = nix.build_flake(
275+
attr,
276+
flake,
277+
flake_build_flags | {"no_link": True},
278+
)
275279
else:
276280
build_attr = BuildAttr.from_arg(args.attr, args.file)
277-
drv = nix.build(attr, build_attr, **build_flags, no_out_link=True)
281+
drv = nix.build(
282+
attr,
283+
build_attr,
284+
build_flags | {"no_out_link": True},
285+
)
278286
except CalledProcessError:
279287
logger.warning(
280288
"could not build a newer version of nixos-rebuild, "
@@ -319,7 +327,8 @@ def execute(argv: list[str]) -> None:
319327
common_flags = vars(args_groups["common_flags"])
320328
common_build_flags = common_flags | vars(args_groups["common_build_flags"])
321329
build_flags = common_build_flags | vars(args_groups["classic_build_flags"])
322-
flake_build_flags = common_build_flags | vars(args_groups["flake_build_flags"])
330+
flake_common_flags = common_flags | vars(args_groups["flake_common_flags"])
331+
flake_build_flags = common_build_flags | flake_common_flags
323332
copy_flags = common_flags | vars(args_groups["copy_flags"])
324333

325334
if args.upgrade or args.upgrade_all:
@@ -350,7 +359,7 @@ def execute(argv: list[str]) -> None:
350359
flake = Flake.from_arg(args.flake, target_host)
351360

352361
if can_run and not flake:
353-
nixpkgs_path = nix.find_file("nixpkgs", **build_flags)
362+
nixpkgs_path = nix.find_file("nixpkgs", build_flags)
354363
rev = nix.get_nixpkgs_rev(nixpkgs_path)
355364
if nixpkgs_path and rev:
356365
(nixpkgs_path / ".version-suffix").write_text(rev)
@@ -370,7 +379,10 @@ def execute(argv: list[str]) -> None:
370379

371380
dry_run = action == Action.DRY_BUILD
372381
no_link = action in (Action.SWITCH, Action.BOOT)
382+
build_flags |= {"no_out_link": no_link, "dry_run": dry_run}
383+
flake_build_flags |= {"no_link": no_link, "dry_run": dry_run}
373384
rollback = bool(args.rollback)
385+
374386
match action:
375387
case Action.BUILD_VM:
376388
attr = "config.system.build.vm"
@@ -395,24 +407,22 @@ def execute(argv: list[str]) -> None:
395407
case (_, True, _, _):
396408
raise NRError(f"--rollback is incompatible with '{action}'")
397409
case (_, False, Remote(_), Flake(_)):
398-
path_to_config = nix.remote_build_flake(
410+
path_to_config = nix.build_remote_flake(
399411
attr,
400412
flake,
401413
build_host,
414+
eval_flags=flake_common_flags,
402415
flake_build_flags=flake_build_flags,
403416
copy_flags=copy_flags,
404-
build_flags=build_flags,
405417
)
406418
case (_, False, None, Flake(_)):
407419
path_to_config = nix.build_flake(
408420
attr,
409421
flake,
410-
no_link=no_link,
411-
dry_run=dry_run,
412-
**flake_build_flags,
422+
flake_build_flags=flake_build_flags,
413423
)
414424
case (_, False, Remote(_), None):
415-
path_to_config = nix.remote_build(
425+
path_to_config = nix.build_remote(
416426
attr,
417427
build_attr,
418428
build_host,
@@ -424,9 +434,7 @@ def execute(argv: list[str]) -> None:
424434
path_to_config = nix.build(
425435
attr,
426436
build_attr,
427-
no_out_link=no_link,
428-
dry_run=dry_run,
429-
**build_flags,
437+
build_flags=build_flags,
430438
)
431439
case never:
432440
# should never happen, but mypy is not smart enough to
@@ -442,7 +450,7 @@ def execute(argv: list[str]) -> None:
442450
path_to_config,
443451
to_host=target_host,
444452
from_host=build_host,
445-
**copy_flags,
453+
copy_flags=copy_flags,
446454
)
447455
if action in (Action.SWITCH, Action.BOOT):
448456
nix.set_profile(
@@ -468,7 +476,7 @@ def execute(argv: list[str]) -> None:
468476
f"Done. The virtual machine can be started by running '{vm_path}'"
469477
)
470478
case Action.EDIT:
471-
nix.edit(flake, **flake_build_flags)
479+
nix.edit(flake, flake_build_flags)
472480
case Action.DRY_RUN:
473481
assert False, "DRY_RUN should be a DRY_BUILD alias"
474482
case Action.LIST_GENERATIONS:
@@ -488,9 +496,9 @@ def execute(argv: list[str]) -> None:
488496
print(tabulate(generations, headers=headers))
489497
case Action.REPL:
490498
if flake:
491-
nix.repl_flake("toplevel", flake, **flake_build_flags)
499+
nix.repl_flake("toplevel", flake, flake_build_flags)
492500
else:
493-
nix.repl("system", build_attr, **build_flags)
501+
nix.repl("system", build_attr, build_flags)
494502
case _:
495503
assert_never(action)
496504

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

Lines changed: 22 additions & 21 deletions
Original file line numberDiff line numberDiff line change
@@ -32,7 +32,7 @@
3232
def build(
3333
attr: str,
3434
build_attr: BuildAttr,
35-
**build_flags: Args,
35+
build_flags: Args | None = None,
3636
) -> Path:
3737
"""Build NixOS attribute using classic Nix.
3838
@@ -52,7 +52,7 @@ def build(
5252
def build_flake(
5353
attr: str,
5454
flake: Flake,
55-
**flake_build_flags: Args,
55+
flake_build_flags: Args | None = None,
5656
) -> Path:
5757
"""Build NixOS attribute using Flakes.
5858
@@ -70,13 +70,13 @@ def build_flake(
7070
return Path(r.stdout.strip())
7171

7272

73-
def remote_build(
73+
def build_remote(
7474
attr: str,
7575
build_attr: BuildAttr,
7676
build_host: Remote | None,
77-
build_flags: dict[str, Args] | None = None,
78-
instantiate_flags: dict[str, Args] | None = None,
79-
copy_flags: dict[str, Args] | None = None,
77+
build_flags: Args | None = None,
78+
instantiate_flags: Args | None = None,
79+
copy_flags: Args | None = None,
8080
) -> Path:
8181
# We need to use `--add-root` otherwise Nix will print this warning:
8282
# > warning: you did not specify '--add-root'; the result might be removed
@@ -89,12 +89,12 @@ def remote_build(
8989
build_attr.to_attr(attr),
9090
"--add-root",
9191
tmpdir.TMPDIR_PATH / uuid4().hex,
92-
*dict_to_flags(instantiate_flags or {}),
92+
*dict_to_flags(instantiate_flags),
9393
],
9494
stdout=PIPE,
9595
)
9696
drv = Path(r.stdout.strip()).resolve()
97-
copy_closure(drv, to_host=build_host, from_host=None, **(copy_flags or {}))
97+
copy_closure(drv, to_host=build_host, from_host=None, copy_flags=copy_flags)
9898

9999
# Need a temporary directory in remote to use in `nix-store --add-root`
100100
r = run_wrapper(
@@ -109,7 +109,7 @@ def remote_build(
109109
drv,
110110
"--add-root",
111111
remote_tmpdir / uuid4().hex,
112-
*dict_to_flags(build_flags or {}),
112+
*dict_to_flags(build_flags),
113113
],
114114
remote=build_host,
115115
stdout=PIPE,
@@ -124,13 +124,13 @@ def remote_build(
124124
run_wrapper(["rm", "-rf", remote_tmpdir], remote=build_host, check=False)
125125

126126

127-
def remote_build_flake(
127+
def build_remote_flake(
128128
attr: str,
129129
flake: Flake,
130130
build_host: Remote,
131-
flake_build_flags: dict[str, Args] | None = None,
132-
copy_flags: dict[str, Args] | None = None,
133-
build_flags: dict[str, Args] | None = None,
131+
eval_flags: Args | None = None,
132+
copy_flags: Args | None = None,
133+
flake_build_flags: Args | None = None,
134134
) -> Path:
135135
r = run_wrapper(
136136
[
@@ -139,20 +139,20 @@ def remote_build_flake(
139139
"eval",
140140
"--raw",
141141
flake.to_attr(attr, "drvPath"),
142-
*dict_to_flags(flake_build_flags or {}),
142+
*dict_to_flags(eval_flags),
143143
],
144144
stdout=PIPE,
145145
)
146146
drv = Path(r.stdout.strip())
147-
copy_closure(drv, to_host=build_host, from_host=None, **(copy_flags or {}))
147+
copy_closure(drv, to_host=build_host, from_host=None, copy_flags=copy_flags)
148148
r = run_wrapper(
149149
[
150150
"nix",
151151
*FLAKE_FLAGS,
152152
"build",
153153
f"{drv}^*",
154154
"--print-out-paths",
155-
*dict_to_flags(build_flags or {}),
155+
*dict_to_flags(flake_build_flags),
156156
],
157157
remote=build_host,
158158
stdout=PIPE,
@@ -164,7 +164,7 @@ def copy_closure(
164164
closure: Path,
165165
to_host: Remote | None,
166166
from_host: Remote | None = None,
167-
**copy_flags: Args,
167+
copy_flags: Args | None = None,
168168
) -> None:
169169
"""Copy a nix closure to or from host to localhost.
170170
@@ -192,6 +192,7 @@ def nix_copy(to_host: Remote, from_host: Remote) -> None:
192192
[
193193
"nix",
194194
"copy",
195+
*dict_to_flags(copy_flags),
195196
"--from",
196197
f"ssh://{from_host.host}",
197198
"--to",
@@ -221,7 +222,7 @@ def nix_copy(to_host: Remote, from_host: Remote) -> None:
221222
nix_copy_closure(to_host, to=True)
222223

223224

224-
def edit(flake: Flake | None, **flake_flags: Args) -> None:
225+
def edit(flake: Flake | None, flake_flags: Args | None = None) -> None:
225226
"Try to find and open NixOS configuration file in editor."
226227
if flake:
227228
run_wrapper(
@@ -250,7 +251,7 @@ def edit(flake: Flake | None, **flake_flags: Args) -> None:
250251
raise NRError("cannot find NixOS config file")
251252

252253

253-
def find_file(file: str, **nix_flags: Args) -> Path | None:
254+
def find_file(file: str, nix_flags: Args | None = None) -> Path | None:
254255
"Find classic Nix file location."
255256
r = run_wrapper(
256257
["nix-instantiate", "--find-file", file, *dict_to_flags(nix_flags)],
@@ -420,14 +421,14 @@ def get_generation_info(generation: Generation) -> GenerationJson:
420421
)
421422

422423

423-
def repl(attr: str, build_attr: BuildAttr, **nix_flags: Args) -> None:
424+
def repl(attr: str, build_attr: BuildAttr, nix_flags: Args | None = None) -> None:
424425
run_args = ["nix", "repl", "--file", build_attr.path]
425426
if build_attr.attr:
426427
run_args.append(build_attr.attr)
427428
run_wrapper([*run_args, *dict_to_flags(nix_flags)])
428429

429430

430-
def repl_flake(attr: str, flake: Flake, **flake_flags: Args) -> None:
431+
def repl_flake(attr: str, flake: Flake, flake_flags: Args | None = None) -> None:
431432
expr = Template(
432433
files(__package__).joinpath(FLAKE_REPL_TEMPLATE).read_text()
433434
).substitute(

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

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

5-
Args: TypeAlias = bool | str | list[str] | int | None
5+
type Arg = bool | str | list[str] | int | None
6+
type Args = dict[str, Arg]
67

78

89
class LogFormatter(logging.Formatter):
@@ -19,7 +20,10 @@ def format(self, record: logging.LogRecord) -> str:
1920
return formatter.format(record)
2021

2122

22-
def dict_to_flags(d: Mapping[str, Args]) -> list[str]:
23+
def dict_to_flags(d: Args | None) -> list[str]:
24+
if not d:
25+
return []
26+
2327
flags = []
2428
for key, value in d.items():
2529
flag = f"--{'-'.join(key.split('_'))}"

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

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -123,8 +123,8 @@ def run_side_effect(args: list[str], **kwargs: Any) -> CompletedProcess[str]:
123123
"<nixpkgs/nixos>",
124124
"--attr",
125125
"config.system.build.toplevel",
126-
"--no-out-link",
127126
"-vvv",
127+
"--no-out-link",
128128
],
129129
check=True,
130130
stdout=PIPE,
@@ -188,8 +188,8 @@ def run_side_effect(args: list[str], **kwargs: Any) -> CompletedProcess[str]:
188188
"build",
189189
"--print-out-paths",
190190
"/path/to/config#nixosConfigurations.hostname.config.system.build.toplevel",
191-
"--no-link",
192191
"-v",
192+
"--no-link",
193193
],
194194
check=True,
195195
stdout=PIPE,
@@ -371,6 +371,7 @@ def run_side_effect(args: list[str], **kwargs: Any) -> CompletedProcess[str]:
371371
"build",
372372
f"'{config_path}^*'",
373373
"--print-out-paths",
374+
"--no-link",
374375
],
375376
check=True,
376377
stdout=PIPE,

0 commit comments

Comments
 (0)