cli: accept --json and --quiet in either position

The global output flags were only registered on the top-level parser, so
`chaoscrypt info -k my.key -P keypwd --json` failed with "unrecognized
arguments: --json". That is the form most people type first, since the flag
reads naturally at the end of a command.

Both flags are now also registered on every subcommand. They write to
separate destinations (json_local / quiet_local) because argparse would
otherwise let an unset subcommand flag overwrite an explicitly set global
one; the two are merged in main().

Three regression tests cover the flag in both positions plus the bare
ciphertext output when neither flag is given.
This commit is contained in:
dvs
2026-09-27 17:07:13 +08:00
parent 017972d8b4
commit 76a5ea9002
2 changed files with 74 additions and 0 deletions
+40
View File
@@ -80,6 +80,30 @@ def _resolve_password(
return None
def _add_global_flags(parser: argparse.ArgumentParser) -> None:
"""Re-register the global output flags on a subcommand.
``--json`` and ``--quiet`` are also accepted before the subcommand. Adding
them here as well lets users write either form, which is what most people
reach for first::
chaoscrypt --json info -k my.key -P keypwd
chaoscrypt info -k my.key -P keypwd --json
The values are merged in :func:`main` by taking whichever was set.
"""
parser.add_argument(
"-j", "--json", action="store_true", default=False,
dest="json_local",
help="emit machine-readable JSON on stdout",
)
parser.add_argument(
"-q", "--quiet", action="store_true", default=False,
dest="quiet_local",
help="suppress non-essential human-readable output",
)
def _add_password_opts(
parser: argparse.ArgumentParser,
prefix: str,
@@ -163,6 +187,7 @@ def build_parser() -> argparse.ArgumentParser:
"keygen", help="generate a new key file",
description="Generate a new ChaosCrypt key file.",
)
_add_global_flags(p_keygen)
p_keygen.add_argument(
"-k", "--key-file", default=DEFAULT_KEY_FILE, metavar="PATH",
help=f"output key file (default: {DEFAULT_KEY_FILE})",
@@ -179,6 +204,7 @@ def build_parser() -> argparse.ArgumentParser:
"encrypt", help="encrypt text",
description="Encrypt a string into a hexadecimal ciphertext.",
)
_add_global_flags(p_enc)
p_enc.add_argument("text", nargs="?", help="plaintext (use - for stdin)")
p_enc.add_argument(
"-i", "--in", dest="in_file", metavar="PATH",
@@ -202,6 +228,7 @@ def build_parser() -> argparse.ArgumentParser:
"decrypt", help="decrypt text",
description="Decrypt a hexadecimal ciphertext back into text.",
)
_add_global_flags(p_dec)
p_dec.add_argument("text", nargs="?", help="ciphertext (use - for stdin)")
p_dec.add_argument(
"-i", "--in", dest="in_file", metavar="PATH",
@@ -228,6 +255,7 @@ def build_parser() -> argparse.ArgumentParser:
file_sub = p_file.add_subparsers(dest="file_command", metavar="<action>")
p_fe = file_sub.add_parser("encrypt", help="encrypt a file to .cc")
_add_global_flags(p_fe)
p_fe.add_argument("src", help="source file")
p_fe.add_argument(
"-o", "--out", dest="out_file", metavar="PATH",
@@ -240,6 +268,7 @@ def build_parser() -> argparse.ArgumentParser:
dest_prefix="key_", long_prefix="key-pwd")
p_fd = file_sub.add_parser("decrypt", help="decrypt a .cc file")
_add_global_flags(p_fd)
p_fd.add_argument("src", help="source .cc file")
p_fd.add_argument(
"-o", "--out", dest="out_file", metavar="PATH",
@@ -257,6 +286,7 @@ def build_parser() -> argparse.ArgumentParser:
description="Show metadata for a key file. Secret material is "
"redacted unless --show-maps is given.",
)
_add_global_flags(p_info)
p_info.add_argument(
"-k", "--key-file", default=DEFAULT_KEY_FILE, metavar="PATH",
help=f"key file (default: {DEFAULT_KEY_FILE})",
@@ -274,6 +304,7 @@ def build_parser() -> argparse.ArgumentParser:
description="Re-wrap an existing key file under a new password. "
"The key material itself is unchanged.",
)
_add_global_flags(p_chpwd)
p_chpwd.add_argument(
"-k", "--key-file", default=DEFAULT_KEY_FILE, metavar="PATH",
)
@@ -557,6 +588,15 @@ def main(argv: Optional[List[str]] = None) -> int:
parser = build_parser()
args = parser.parse_args(raw)
# `--json` / `--quiet` are accepted both before and after the subcommand.
# The subparser writes to separate destinations so that an unset
# subcommand flag cannot clobber an explicitly set global one; the two are
# merged here.
args.json = bool(getattr(args, "json", False)
or getattr(args, "json_local", False))
args.quiet = bool(getattr(args, "quiet", False)
or getattr(args, "quiet_local", False))
if args.command is None or args.command == "tui":
from .tui import run_tui
return run_tui()
+34
View File
@@ -548,6 +548,40 @@ class TestCLI:
assert r.returncode == 0, r.stderr
assert open(dst, encoding="utf-8").read() == "file cli test"
def test_json_flag_accepted_before_and_after_subcommand(self, tmp_path):
"""--json must work in either position, not only before the subcommand."""
kf = str(tmp_path / "pos.key")
self._run(["keygen", "-k", kf, "-P", KEY_PWD])
for args in (
["--json", "info", "-k", kf, "-P", KEY_PWD],
["info", "-k", kf, "-P", KEY_PWD, "--json"],
):
r = self._run(args)
assert r.returncode == 0, r.stderr
assert json.loads(r.stdout)["ok"] is True, args
def test_quiet_flag_accepted_before_and_after_subcommand(self, tmp_path):
kf = str(tmp_path / "q.key")
self._run(["keygen", "-k", kf, "-P", KEY_PWD])
for args in (
["--quiet", "encrypt", "x", "-p", USER_PWD, "-k", kf, "-P", KEY_PWD],
["encrypt", "x", "-p", USER_PWD, "-k", kf, "-P", KEY_PWD, "--quiet"],
):
r = self._run(args)
assert r.returncode == 0, r.stderr
assert r.stdout.strip() == "", args
def test_plain_output_is_bare_ciphertext(self, tmp_path):
"""Without --json the ciphertext goes to stdout on its own."""
kf = str(tmp_path / "p.key")
self._run(["keygen", "-k", kf, "-P", KEY_PWD])
r = self._run(["encrypt", "x", "-p", USER_PWD, "-k", kf, "-P", KEY_PWD])
out = r.stdout.strip()
assert out and "ciphertext" not in out
int(out, 16)
def test_chpwd(self, tmp_path):
kf = str(tmp_path / "c.key")
self._run(["keygen", "-k", kf, "-P", KEY_PWD])