mirror of
https://github.com/kuhyx/steam-backlog-enforcer.git
synced 2026-11-28 07:29:20 +01:00
fix(enforcer): accept flag-style subcommands, explain unknown ones
'./run.sh --abandon-pick <id>' printed the usage block and exited 1 with no reason given: main() matched argv[1] against _ALL_COMMANDS exactly, so a dashed spelling fell into the same catch-all as invoking with no args. - _resolve_command() strips leading dashes from argv[1] (they carry no meaning in that slot) and echoes a note when it normalises. - _print_usage() now names the offending token and suggests the nearest command via difflib, instead of silently reprinting usage. Locks still receive the canonical command name, so a dashed spelling cannot be used to dodge the manual-pick or total-gaming block. Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
This commit is contained in:
parent
a3d7641193
commit
a5dd56941d
@ -3,6 +3,7 @@
|
|||||||
from __future__ import annotations
|
from __future__ import annotations
|
||||||
|
|
||||||
from datetime import datetime, timedelta, timezone
|
from datetime import datetime, timedelta, timezone
|
||||||
|
import difflib
|
||||||
import logging
|
import logging
|
||||||
import sys
|
import sys
|
||||||
from typing import TYPE_CHECKING
|
from typing import TYPE_CHECKING
|
||||||
@ -935,17 +936,65 @@ _ALL_COMMANDS: dict[str, str] = {
|
|||||||
} | _EXTRA_COMMAND_DESCRIPTIONS
|
} | _EXTRA_COMMAND_DESCRIPTIONS
|
||||||
|
|
||||||
|
|
||||||
|
def _resolve_command(raw: str) -> str | None:
|
||||||
|
"""Map a raw argv[1] onto a known command name.
|
||||||
|
|
||||||
|
Subcommands are bare words, but the CLI does use flags elsewhere
|
||||||
|
(``add-exception --reason``), so ``--abandon-pick`` is the natural
|
||||||
|
muscle-memory guess. Leading dashes carry no meaning in this slot,
|
||||||
|
so they are simply stripped rather than rejected.
|
||||||
|
|
||||||
|
Parameters:
|
||||||
|
raw (str): The first CLI argument, exactly as the user typed it.
|
||||||
|
|
||||||
|
Returns:
|
||||||
|
str | None: The canonical command name, or None if unrecognised.
|
||||||
|
"""
|
||||||
|
if raw in _ALL_COMMANDS:
|
||||||
|
return raw
|
||||||
|
if raw.startswith("-"):
|
||||||
|
stripped = raw.lstrip("-")
|
||||||
|
if stripped in _ALL_COMMANDS:
|
||||||
|
return stripped
|
||||||
|
return None
|
||||||
|
|
||||||
|
|
||||||
|
def _print_usage(unknown: str | None = None) -> None:
|
||||||
|
"""Print the command list, optionally explaining a bad command.
|
||||||
|
|
||||||
|
Parameters:
|
||||||
|
unknown (str | None): The unrecognised argument to report. When None
|
||||||
|
(the no-arguments case) only the usage block is printed.
|
||||||
|
"""
|
||||||
|
if unknown is not None:
|
||||||
|
_echo(f"Unknown command: {unknown}")
|
||||||
|
close = difflib.get_close_matches(
|
||||||
|
unknown.lstrip("-"), _ALL_COMMANDS, n=1, cutoff=0.6
|
||||||
|
)
|
||||||
|
if close:
|
||||||
|
_echo(f"Did you mean '{close[0]}'?")
|
||||||
|
_echo("")
|
||||||
|
_echo("Steam Backlog Enforcer\n")
|
||||||
|
_echo("Usage: python -m steam_backlog_enforcer.main <command> [args]\n")
|
||||||
|
_echo("Commands:")
|
||||||
|
for name, desc in _ALL_COMMANDS.items():
|
||||||
|
_echo(f" {name:<14s} {desc}")
|
||||||
|
|
||||||
|
|
||||||
def main() -> None:
|
def main() -> None:
|
||||||
"""CLI entry point."""
|
"""CLI entry point."""
|
||||||
if len(sys.argv) < _MIN_CLI_ARGS or sys.argv[1] not in _ALL_COMMANDS:
|
if len(sys.argv) < _MIN_CLI_ARGS:
|
||||||
_echo("Steam Backlog Enforcer\n")
|
_print_usage()
|
||||||
_echo("Usage: python -m steam_backlog_enforcer.main <command>\n")
|
|
||||||
_echo("Commands:")
|
|
||||||
for name, desc in _ALL_COMMANDS.items():
|
|
||||||
_echo(f" {name:<14s} {desc}")
|
|
||||||
sys.exit(1)
|
sys.exit(1)
|
||||||
|
|
||||||
command = sys.argv[1]
|
# Locks below are always given the canonical name, never raw argv,
|
||||||
|
# so a dashed spelling can never be used to dodge one.
|
||||||
|
command = _resolve_command(sys.argv[1])
|
||||||
|
if command is None:
|
||||||
|
_print_usage(sys.argv[1])
|
||||||
|
sys.exit(1)
|
||||||
|
if command != sys.argv[1]:
|
||||||
|
_echo(f"Note: treating '{sys.argv[1]}' as '{command}'.")
|
||||||
|
|
||||||
config = Config.load()
|
config = Config.load()
|
||||||
|
|
||||||
|
|||||||
@ -12,7 +12,12 @@ from steam_backlog_enforcer._cmd_done import (
|
|||||||
cmd_done,
|
cmd_done,
|
||||||
)
|
)
|
||||||
from steam_backlog_enforcer.config import Config, State
|
from steam_backlog_enforcer.config import Config, State
|
||||||
from steam_backlog_enforcer.main import cmd_pick, main
|
from steam_backlog_enforcer.main import (
|
||||||
|
_print_usage,
|
||||||
|
_resolve_command,
|
||||||
|
cmd_pick,
|
||||||
|
main,
|
||||||
|
)
|
||||||
from steam_backlog_enforcer.steam_api import GameInfo
|
from steam_backlog_enforcer.steam_api import GameInfo
|
||||||
|
|
||||||
CMD_DONE_PKG = "steam_backlog_enforcer._cmd_done"
|
CMD_DONE_PKG = "steam_backlog_enforcer._cmd_done"
|
||||||
@ -207,6 +212,75 @@ class TestMain:
|
|||||||
):
|
):
|
||||||
main()
|
main()
|
||||||
|
|
||||||
|
def test_dashed_command_dispatches_with_note(self) -> None:
|
||||||
|
"""'--status' runs 'status' and says so."""
|
||||||
|
mock_cmd = MagicMock()
|
||||||
|
with (
|
||||||
|
patch.object(sys, "argv", ["prog", "--status"]),
|
||||||
|
patch(f"{PKG}.Config.load", return_value=Config(steam_api_key="k")),
|
||||||
|
patch(f"{PKG}.State.load", return_value=State()),
|
||||||
|
patch.dict(f"{PKG}.COMMANDS", {"status": ("s", mock_cmd)}),
|
||||||
|
patch(f"{PKG}._echo") as mock_echo,
|
||||||
|
):
|
||||||
|
main()
|
||||||
|
mock_cmd.assert_called_once()
|
||||||
|
assert any(
|
||||||
|
"treating '--status' as 'status'" in str(call.args[0])
|
||||||
|
for call in mock_echo.call_args_list
|
||||||
|
if call.args
|
||||||
|
)
|
||||||
|
|
||||||
|
@pytest.mark.parametrize("raw", ["bogus", "--bogus"])
|
||||||
|
def test_unknown_command_names_the_input(self, raw: str) -> None:
|
||||||
|
with (
|
||||||
|
patch.object(sys, "argv", ["prog", raw]),
|
||||||
|
patch(f"{PKG}._echo") as mock_echo,
|
||||||
|
pytest.raises(SystemExit, match="1"),
|
||||||
|
):
|
||||||
|
main()
|
||||||
|
assert any(
|
||||||
|
str(call.args[0]).startswith(f"Unknown command: {raw}")
|
||||||
|
for call in mock_echo.call_args_list
|
||||||
|
if call.args
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
class TestResolveCommand:
|
||||||
|
"""Tests for argv[1] normalisation and the usage printer."""
|
||||||
|
|
||||||
|
@pytest.mark.parametrize(
|
||||||
|
("raw", "expected"),
|
||||||
|
[
|
||||||
|
("status", "status"),
|
||||||
|
("--status", "status"),
|
||||||
|
("--abandon-pick", "abandon-pick"),
|
||||||
|
("-status", "status"),
|
||||||
|
("bogus", None),
|
||||||
|
("--bogus", None),
|
||||||
|
("--", None),
|
||||||
|
],
|
||||||
|
)
|
||||||
|
def test_resolve(self, raw: str, expected: str | None) -> None:
|
||||||
|
assert _resolve_command(raw) == expected
|
||||||
|
|
||||||
|
def test_usage_suggests_close_match(self) -> None:
|
||||||
|
with patch(f"{PKG}._echo") as mock_echo:
|
||||||
|
_print_usage("statu")
|
||||||
|
lines = [str(c.args[0]) for c in mock_echo.call_args_list if c.args]
|
||||||
|
assert "Did you mean 'status'?" in lines
|
||||||
|
|
||||||
|
def test_usage_omits_suggestion_when_far_off(self) -> None:
|
||||||
|
with patch(f"{PKG}._echo") as mock_echo:
|
||||||
|
_print_usage("--zzzzzz")
|
||||||
|
lines = [str(c.args[0]) for c in mock_echo.call_args_list if c.args]
|
||||||
|
assert not any(line.startswith("Did you mean") for line in lines)
|
||||||
|
|
||||||
|
def test_usage_without_unknown_has_no_error_line(self) -> None:
|
||||||
|
with patch(f"{PKG}._echo") as mock_echo:
|
||||||
|
_print_usage()
|
||||||
|
lines = [str(c.args[0]) for c in mock_echo.call_args_list if c.args]
|
||||||
|
assert not any(line.startswith("Unknown command") for line in lines)
|
||||||
|
|
||||||
|
|
||||||
class TestCmdPick:
|
class TestCmdPick:
|
||||||
"""Tests for cmd_pick."""
|
"""Tests for cmd_pick."""
|
||||||
|
|||||||
Loading…
Reference in New Issue
Block a user