Skip to content

Commit

Permalink
fixup! feat: expose the Dispatcher's parsed arguments
Browse files Browse the repository at this point in the history
  • Loading branch information
tigarmo committed Oct 19, 2023
1 parent 14706bd commit e87cec9
Show file tree
Hide file tree
Showing 2 changed files with 10 additions and 9 deletions.
9 changes: 6 additions & 3 deletions craft_cli/dispatcher.py
Original file line number Diff line number Diff line change
Expand Up @@ -245,10 +245,13 @@ def load_command(self, app_config: Any) -> BaseCommand:
emit.trace(f"Command parsed sysargs: {self._parsed_command_args}")
return self._loaded_command

@property
def parsed_args(self) -> argparse.Namespace:
"""The map of parsed command-line arguments."""
return self._parsed_command_args or argparse.Namespace()
"""Get the parsed command-line arguments."""
if self._parsed_command_args is None:
raise RuntimeError(
"Need to load the command (call 'load_command') before retrieving the parsed arguments."
)
return self._parsed_command_args

def _get_global_options(self) -> list[tuple[str, str]]:
"""Return the global flags ready to present in the help messages as options."""
Expand Down
10 changes: 4 additions & 6 deletions tests/unit/test_dispatcher.py
Original file line number Diff line number Diff line change
Expand Up @@ -77,16 +77,14 @@ def fill_parser(self, parser):
dispatcher = Dispatcher("appname", groups)
dispatcher.pre_parse_args(["somecommand", "--option1", "1", "--option2", "--option3"])

# Before loading the command: parsed_args is empty.
parsed_before = dispatcher.parsed_args
assert not hasattr(parsed_before, "option1")
assert not hasattr(parsed_before, "option2")
assert not hasattr(parsed_before, "option3")
# Before loading the command: error
with pytest.raises(RuntimeError, match="Need to load the command"):
_ = dispatcher.parsed_args()

dispatcher.load_command("test-config")

# After loading the command: parsed_args is filled.
parsed_after = dispatcher.parsed_args
parsed_after = dispatcher.parsed_args()
assert parsed_after.option1 == "1"
assert parsed_after.option2
assert not parsed_after.option3
Expand Down

0 comments on commit e87cec9

Please sign in to comment.