fix: make helper script ask for confirmation on overwrite

This commit is contained in:
mxmehl committed 2026-10-22 14:09:28 +02:00
1 parent 186fe7f9ee
commit 8bc1cfaf27
3 files changed
+84 -13

No files matched your search

Regular → Executable
+40 -5
View File
@@ -40,7 +40,9 @@ def set_host(text, host, digest, zone=None):
header = f'[hosts."{host}"]'
start = next((i for i, line in enumerate(lines) if line.strip() == header), None)
if start is None:
raise ValueError(f"cannot find the line {header} in the config, edit {host} by hand")
raise ValueError(
f"cannot find the line {header} in the config, edit {host} by hand"
)
for i in range(start + 1, len(lines)):
if lines[i].lstrip().startswith("["):
break
@@ -63,11 +65,36 @@ def write_config(path, text):
raise
def confirm(question):
"""Ask on the terminal; anything but yes, including no input, means no."""
try:
return input(question).strip().lower() in ("y", "yes")
except EOFError:
return False
def main(argv=None):
parser = argparse.ArgumentParser(description=__doc__.split("\n")[0])
parser.add_argument("hostname", help="e.g. home.example.com; an existing host gets a new token")
parser.add_argument("-c", "--config", default=DEFAULT_CONFIG, help=f"config file (default: {DEFAULT_CONFIG})")
parser.add_argument("-z", "--zone", help="INWX zone for a new host, if not the last two labels of the hostname")
parser.add_argument(
"hostname", help="e.g. home.example.com; an existing host gets a new token"
)
parser.add_argument(
"-c",
"--config",
default=DEFAULT_CONFIG,
help=f"config file (default: {DEFAULT_CONFIG})",
)
parser.add_argument(
"-y",
"--yes",
action="store_true",
help="replace the token of an existing host without asking",
)
parser.add_argument(
"-z",
"--zone",
help="INWX zone for a new host, if not the last two labels of the hostname",
)
args = parser.parse_args(argv)
host = args.hostname.lower()
@@ -80,7 +107,15 @@ def main(argv=None):
digest = hashlib.sha256(token.encode()).hexdigest()
try:
with open(path) as f:
new_text, created = set_host(f.read(), host, digest, args.zone)
text = f.read()
exists = host in tomllib.loads(text).get("hosts", {})
if (
exists
and not args.yes
and not confirm(f"{host} already exists. Replace its token? [y/N] ")
):
sys.exit("Aborted, config unchanged")
new_text, created = set_host(text, host, digest, args.zone)
tomllib.loads(new_text) # never write a config that does not parse
write_config(path, new_text)
except (OSError, ValueError) as e: # TOMLDecodeError is a ValueError