From a84ed801262a6b3d05427504d30ae90ec2f4b6ba Mon Sep 17 00:00:00 2001 From: Harald Sitter Date: Tue, 4 Mar 2025 19:39:28 +0100 Subject: [PATCH] simplify nsswitch finalize script - remove overbaring debugging - don't print exceptions or handle exceptions when they are meant to be fatal - don't open the file multiple times - don't check uid, it's inconsequental because we really only need a writable file --- mkosi.finalize.d/10-modify-nsswitch.py.chroot | 59 ++++--------------- 1 file changed, 13 insertions(+), 46 deletions(-) diff --git a/mkosi.finalize.d/10-modify-nsswitch.py.chroot b/mkosi.finalize.d/10-modify-nsswitch.py.chroot index fd296f6..42dbeca 100755 --- a/mkosi.finalize.d/10-modify-nsswitch.py.chroot +++ b/mkosi.finalize.d/10-modify-nsswitch.py.chroot @@ -6,54 +6,21 @@ import os import sys -def modify_nsswitch(): - path = "/etc/nsswitch.conf" - - print(f"Checking {path}...") # Debug line - - # Read the file - try: - with open(path, "r") as file: - lines = file.readlines() - except Exception as e: - print(f"Error reading {path}: {e}", file=sys.stderr) - raise # Re-raise the exception - - modified = False - - # Process each line +def replace_lines_in_place(lines): for i, line in enumerate(lines): - print(f"Checking line: {line.strip()}") # Debug line - if line.startswith("hosts:"): - if "mymachines" in line and "mdns_minimal" not in line: - lines[i] = line.replace("mymachines", "mymachines mdns_minimal [NOTFOUND=return]", 1) - modified = True - print("Added mdns_minimal after mymachines.") # Debug line - elif "mymachines" not in line and "mdns_minimal" not in line: - lines[i] = line.replace("hosts:", "hosts: mdns_minimal [NOTFOUND=return] ", 1) - modified = True - print("Added mdns_minimal.") # Debug line - break + if not line.startswith("hosts: mymachines resolve"): + continue - if not modified: - raise RuntimeError("Expected modification but no changes were made.") + lines[i] = line.replace("mymachines", "mymachines mdns_minimal [NOTFOUND=return]", 1) + return + raise RuntimeError("Expected modification but no changes were made.") - # Write back the modified file - try: - with open(path, "w") as file: - file.writelines(lines) - print("Updated /etc/nsswitch.conf") - except Exception as e: - print(f"Error writing to {path}: {e}", file=sys.stderr) - raise # Re-raise the exception +def modify_nsswitch(): + with open("/etc/nsswitch.conf", "r+") as file: + lines = file.readlines() + replace_lines_in_place(lines) + file.seek(0) + file.writelines(lines) if __name__ == "__main__": - if os.geteuid() != 0: - print("This script must be run as root.", file=sys.stderr) - sys.exit(1) - - try: - modify_nsswitch() - except Exception as e: - print(f"Fatal error: {e}", file=sys.stderr) - sys.exit(1) + modify_nsswitch()