Skip to content

Commit e5f711f

Browse files
committed
Fix: require subcommand to prevent KeyError with -v/--verbose (closes #173)
1 parent 9b04670 commit e5f711f

2 files changed

Lines changed: 14 additions & 7 deletions

File tree

‎fixit/cli.py‎

Lines changed: 2 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -275,7 +275,7 @@ def build_parser() -> argparse.ArgumentParser:
275275
action="store_true",
276276
help="enable verbose logging",
277277
)
278-
sub = parser.add_subparsers(dest="command")
278+
sub = parser.add_subparsers(dest="command", required=True)
279279

280280
wc = sub.add_parser("wc", help="count words, lines and characters")
281281
wc.add_argument("text", nargs="?")
@@ -390,10 +390,6 @@ def main(argv: Optional[Sequence[str]] = None) -> int:
390390
if argv is None:
391391
argv = sys.argv[1:]
392392

393-
if not argv:
394-
parser.print_usage(sys.stderr)
395-
parser.exit(2)
396-
397393
try:
398394
args = parser.parse_args(argv)
399395
logging.basicConfig(
@@ -403,8 +399,7 @@ def main(argv: Optional[Sequence[str]] = None) -> int:
403399
force=True,
404400
)
405401

406-
if args.command is not None:
407-
logger.debug("running command %s", args.command)
402+
logger.debug("running command %s", args.command)
408403

409404
if args.command == "shell":
410405
from fixit.shell import run_shell

‎tests/test_cli.py‎

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -208,6 +208,18 @@ def test_no_command_shows_error(capsys):
208208
assert "usage" in captured.err.lower()
209209

210210

211+
@pytest.mark.parametrize("flag", ["-v", "--verbose"])
212+
def test_verbose_without_command_shows_usage_error(capsys, flag):
213+
with pytest.raises(SystemExit) as exc_info:
214+
main([flag])
215+
216+
assert exc_info.value.code == 2
217+
218+
captured = capsys.readouterr()
219+
assert "usage" in captured.err.lower()
220+
assert captured.out == ""
221+
222+
211223
def test_help_shows_examples(capsys):
212224
parser = build_parser()
213225

0 commit comments

Comments
 (0)