Skip to content

Commit

Permalink
fix(cli): enable per-command help queries
Browse files Browse the repository at this point in the history
  • Loading branch information
lengau authored and sergiusens committed Sep 22, 2023
1 parent 71d68f4 commit 42c7983
Show file tree
Hide file tree
Showing 3 changed files with 41 additions and 1 deletion.
9 changes: 8 additions & 1 deletion craft_application/commands/base.py
Original file line number Diff line number Diff line change
Expand Up @@ -36,8 +36,15 @@ class AppCommand(BaseCommand):
always_load_project: bool = False
"""The project is also loaded in non-managed mode."""

def __init__(self, config: dict[str, Any]) -> None:
def __init__(self, config: dict[str, Any] | None) -> None:
if config is None:
# This should only be the case when the command is not going to be run.
# For example, when requesting help on the command.
emit.trace("Not completing command configuration")
return

super().__init__(config)

self._app: application.AppMetadata = config["app"]
self._services: service_factory.ServiceFactory = config["services"]

Expand Down
20 changes: 20 additions & 0 deletions tests/integration/test_application.py
Original file line number Diff line number Diff line change
Expand Up @@ -149,3 +149,23 @@ def test_run_always_load_project(monkeypatch, app, cmd):
app.run()

assert str(raised.value).endswith("/testcraft.yaml'") is True


@pytest.mark.parametrize("help_param", ["-h", "--help"])
@pytest.mark.parametrize(
"cmd", ["clean", "pull", "build", "stage", "prime", "pack", "version"]
)
def test_get_command_help(monkeypatch, emitter, capsys, app, cmd, help_param):
monkeypatch.setattr("sys.argv", ["testcraft", cmd, help_param])

with pytest.raises(SystemExit) as exit_info:
app.run()

assert exit_info.value.code == 0

# Ensure the command got help set to true.
emitter.assert_trace(".+'help': True.+", regex=True)

stdout, stderr = capsys.readouterr()

assert f"testcraft {cmd} [options]" in stderr
13 changes: 13 additions & 0 deletions tests/unit/commands/test_base.py
Original file line number Diff line number Diff line change
Expand Up @@ -55,3 +55,16 @@ def test_get_managed_cmd(fake_command, verbosity, app_metadata):
f"--verbosity={verbosity.name.lower()}",
"fake",
]


def test_without_config(emitter):
"""Test that a command can be initialised without a config.
This is necessary for providing per-command help.
"""

command = base.AppCommand(None)

emitter.assert_trace("Not completing command configuration")
assert not hasattr(command, "_app")
assert not hasattr(command, "_services")

0 comments on commit 42c7983

Please sign in to comment.