From dff3315facda625a85013c1debc483959fd24ecc Mon Sep 17 00:00:00 2001 From: r-vdp Date: Sun, 31 May 2026 21:43:02 +0300 Subject: [PATCH] nixos/systemd-boot-builder: use `with` for the secrets temp file This guarantees the descriptor is closed even when copyfileobj raises, matching the other writer implementations. The append-initrd-secrets script reopens the file by path, so flush() is enough before invoking it and the explicit close() is no longer needed. --- .../systemd-boot/systemd-boot-builder.py | 25 +++++++++---------- 1 file changed, 12 insertions(+), 13 deletions(-) diff --git a/nixos/modules/system/boot/loader/systemd-boot/systemd-boot-builder.py b/nixos/modules/system/boot/loader/systemd-boot/systemd-boot-builder.py index 1f2210133532..61791019338d 100644 --- a/nixos/modules/system/boot/loader/systemd-boot/systemd-boot-builder.py +++ b/nixos/modules/system/boot/loader/systemd-boot/systemd-boot-builder.py @@ -91,24 +91,23 @@ class InitrdWithSecretsWriter: def write_boot_file(self, path: Path) -> None: # Secrets can change between rebuilds, so always rebuild from the # pristine initrd into a temp file and rename into place. - tmp = tempfile.NamedTemporaryFile( + with tempfile.NamedTemporaryFile( mode="wb", dir=path.parent, delete=False, prefix=path.name, suffix=".tmp", - ) - try: - with open(self.source, mode="rb") as source_file: - shutil.copyfileobj(source_file, tmp) - tmp.close() - run([self.initrd_secrets, tmp.name]) - with open(tmp.name, "rb") as f: - os.fsync(f.fileno()) - except BaseException: - os.unlink(tmp.name) - raise - os.rename(tmp.name, path) + ) as tmp: + try: + with open(self.source, mode="rb") as source_file: + shutil.copyfileobj(source_file, tmp) + tmp.flush() + run([self.initrd_secrets, tmp.name]) + os.fsync(tmp.fileno()) + except BaseException: + os.unlink(tmp.name) + raise + os.rename(tmp.name, path) @dataclass