From 14b5217e49e1bc81143245e70a21444323c6bc8c Mon Sep 17 00:00:00 2001 From: Jakob Husu Date: Wed, 20 May 2026 11:35:05 +0200 Subject: [PATCH] Prompt before overwriting an existing key file, with option to rename --- keygen.py | 27 +++++++++++++++++++++++++-- 1 file changed, 25 insertions(+), 2 deletions(-) diff --git a/keygen.py b/keygen.py index a6921c6..d3274c5 100644 --- a/keygen.py +++ b/keygen.py @@ -72,6 +72,29 @@ def format_mnemonic(words: str) -> str: return "\n".join(lines) +def resolve_output_path(requested: Path) -> Path: + """Return the path to write to, prompting if the file already exists.""" + path = requested + while path.exists(): + print(f"File already exists: {path}") + print(" [o] Overwrite [r] Rename [q] Quit") + choice = input("Choice: ").strip().lower() + if choice == "o": + break + elif choice == "r": + new_name = input(f"New filename (in {path.parent}): ").strip() + if not new_name: + print("No name entered, try again.") + continue + path = path.parent / new_name + elif choice == "q": + print("Aborted.") + sys.exit(0) + else: + print("Please enter o, r, or q.") + return path + + def ask_passphrase(confirm: bool = True) -> bytes | None: passphrase = getpass.getpass("Key passphrase (leave blank for none): ") if not passphrase: @@ -93,7 +116,7 @@ def cmd_generate(args: argparse.Namespace) -> None: passphrase = ask_passphrase(confirm=True) if args.passphrase else None - output = Path(args.output) + output = resolve_output_path(Path(args.output)) key_path, pub_path = save_keypair(private_key, output, args.comment, passphrase) print(f"\nGenerated Ed25519 SSH key pair") @@ -129,7 +152,7 @@ def cmd_recover(args: argparse.Namespace) -> None: passphrase = ask_passphrase(confirm=True) if args.passphrase else None - output = Path(args.output) + output = resolve_output_path(Path(args.output)) key_path, pub_path = save_keypair(private_key, output, args.comment, passphrase) print(f"\nRecovered Ed25519 SSH key pair")