diff --git a/CHANGELOG.md b/CHANGELOG.md index 4cb3d289a..8aca4b743 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -6,6 +6,12 @@ - Enhancements - Added `Cmd.get_command_category()`, which returns the help category a command is listed under. It was the private `_get_command_category()`. + - Added `Cmd.get_argparse_command_spec()`, which returns what `@with_argparser` or + `@with_annotated` recorded for a command: the source of its parser, and whether argparse is + given its arguments with their quotes. `ArgparseCommandSpec` is now frozen, so its fields + cannot be reassigned. A parser given to `@with_argparser` is the spec's `parser_source` + itself, shared by every application which has not built the command's parser yet: to change + one application's parser, change the one which `self.command_parsers.get(func)` returns. ## 4.4.5 (2026-12-02) diff --git a/cmd2/argparse_utils.py b/cmd2/argparse_utils.py index cb00eeb89..cee16a398 100644 --- a/cmd2/argparse_utils.py +++ b/cmd2/argparse_utils.py @@ -291,7 +291,7 @@ def get_choices(self) -> Choices: ] -@dataclass(kw_only=True) +@dataclass(kw_only=True, frozen=True) class ArgparseCommandSpec: """Metadata for an argparse-based command function. diff --git a/cmd2/cmd2.py b/cmd2/cmd2.py index 6d870a5b7..e8e473447 100644 --- a/cmd2/cmd2.py +++ b/cmd2/cmd2.py @@ -297,6 +297,8 @@ def get(self, command_method: BoundCommandFunc[...]) -> Cmd2ArgumentParser | Non return None command = command_method.__name__[len(COMMAND_FUNC_PREFIX) :] + # The argparse decorators pass their own function here, which is not bound, so the spec is read from it + # directly: Cmd.get_argparse_command_spec() is given only bound methods. spec: ArgparseCommandSpec | None = getattr(command_method, constants.ARGPARSE_COMMAND_ATTR_SPEC, None) if spec is None: return None @@ -2690,14 +2692,15 @@ def _perform_completion( if command_func is not None and parser is not None: # Get arguments for complete() - spec: ArgparseCommandSpec = getattr(command_func, constants.ARGPARSE_COMMAND_ATTR_SPEC) + spec = self.get_argparse_command_spec(command_func) + preserve_quotes = spec is not None and spec.preserve_quotes cmd_set = self.find_commandset_for_command(command) # Create the argparse completer completer = parser.completer_class(parser, self) completer_func = functools.partial( - completer.complete, tokens=raw_tokens[1:] if spec.preserve_quotes else tokens[1:], cmd_set=cmd_set + completer.complete, tokens=raw_tokens[1:] if preserve_quotes else tokens[1:], cmd_set=cmd_set ) else: completer_func = self.completedefault # type: ignore[assignment] # ty: ignore[invalid-assignment] @@ -3676,6 +3679,30 @@ def get_command_category(self, func: BoundCommandFunc[...]) -> str: return category + def get_argparse_command_spec(self, func: BoundCommandFunc[...]) -> ArgparseCommandSpec | None: + """Return the spec which an argparse decorator recorded for a command. + + [@with_argparser][cmd2.with_argparser] and [@with_annotated][cmd2.with_annotated] record + the source of the command's parser and whether argparse is given the command's arguments + with their quotes (``preserve_quotes``). The spec's fields cannot be reassigned. Its + ``parser_source`` is shared by every application: + + - for ``@with_argparser``, the parser or the factory which the decorator was given + - for ``@with_annotated``, a factory which cmd2 made from the command's type hints, not the + command's function + + The parser which this application's command uses is ``self.command_parsers.get(func)``, and + is the one to change. + + :param func: the bound ``do_*`` method of the command, as returned by + [get_command_func()][cmd2.Cmd.get_command_func]. While a command is disabled, + the function which stands in for it carries its spec. + :return: the command's spec, or None for a command which neither decorator made, such as one + made with [@with_argument_list][cmd2.with_argument_list] + """ + spec: ArgparseCommandSpec | None = getattr(func, constants.ARGPARSE_COMMAND_ATTR_SPEC, None) + return spec + def onecmd(self, statement: Statement | str, *, add_to_history: bool = True) -> bool: """Execute the actual do_* method for a command. diff --git a/docs/features/argument_processing.md b/docs/features/argument_processing.md index 6992dbae4..1f6b69fa8 100644 --- a/docs/features/argument_processing.md +++ b/docs/features/argument_processing.md @@ -37,6 +37,19 @@ All of these decorators accept an optional **preserve_quotes** argument which de Setting this argument to `True` is useful for cases where you are passing the arguments to another command which might have its own argument parsing. +For a command made with `@with_argparser` or `@with_annotated`, +[get_argparse_command_spec()][cmd2.Cmd.get_argparse_command_spec] returns what the decorator +recorded, so code which describes an application's commands can ask whether argparse is given a +command's arguments with their quotes. Get the command's function from +[get_command_func()][cmd2.Cmd.get_command_func], and skip a name for which there is none: + +```py +func = self.get_command_func(name) +if func is not None: + spec = self.get_argparse_command_spec(func) + keeps_quotes = spec is not None and spec.preserve_quotes +``` + ## with_argparser decorator The [@with_argparser][cmd2.with_argparser] decorator can accept the following for its first diff --git a/tests/test_argparse.py b/tests/test_argparse.py index d94a2fadb..19b2bcc93 100644 --- a/tests/test_argparse.py +++ b/tests/test_argparse.py @@ -1,10 +1,14 @@ """Cmd2 testing for argument parsing""" import argparse +import dataclasses +import inspect +from typing import Any import pytest import cmd2 +from cmd2.argparse_utils import ArgparseCommandSpec from .conftest import ( run_cmd, @@ -518,3 +522,88 @@ def test_pytest_mock_invalid(mocker) -> None: def test_pytest_mock_valid(mocker, spec_param) -> None: mocker.patch.object(ArgparseApp, "namespace_provider", **spec_param) ArgparseApp() + + +def _spec(app: cmd2.Cmd, command: str) -> ArgparseCommandSpec | None: + func = app.get_command_func(command) + assert func is not None + return app.get_argparse_command_spec(func) + + +def test_get_argparse_command_spec_says_whether_argparse_gets_the_quotes(argparse_app) -> None: + tag = _spec(argparse_app, "tag") + assert tag is not None + assert tag.preserve_quotes + assert tag.parser_source is ArgparseApp.tag_parser + say = _spec(argparse_app, "say") + assert say is not None + assert not say.preserve_quotes + + +def test_get_argparse_command_spec_of_an_annotated_command() -> None: + class AnnotatedApp(cmd2.Cmd): + @cmd2.with_annotated(preserve_quotes=True) + def do_keep(self, word: str) -> None: + self.poutput(word) + + spec = _spec(AnnotatedApp(), "keep") + assert spec is not None + assert spec.preserve_quotes + + +def test_get_argparse_command_spec_of_a_command_set_command() -> None: + class QuotesSet(cmd2.CommandSet): + @cmd2.with_argparser(cmd2.Cmd2ArgumentParser(), preserve_quotes=True) + def do_kept(self, _: argparse.Namespace) -> None: + pass + + spec = _spec(cmd2.Cmd(command_sets=[QuotesSet()]), "kept") + assert spec is not None + assert spec.preserve_quotes + + +def test_get_argparse_command_spec_of_a_disabled_command(argparse_app) -> None: + argparse_app.disable_command("tag", "tag is disabled") + spec = _spec(argparse_app, "tag") + assert spec is not None + assert spec.preserve_quotes + + +def test_get_argparse_command_spec_of_a_command_without_a_parser(argparse_app) -> None: + # @with_argument_list takes preserve_quotes too, but makes no parser and records no spec. + assert _spec(argparse_app, "preservelist") is None + assert _spec(argparse_app, "arglist") is None + + class PlainApp(cmd2.Cmd): + def do_plain(self, statement: cmd2.Statement) -> None: + self.poutput(statement.args) + + assert _spec(PlainApp(), "plain") is None + + +def test_get_argparse_command_spec_cannot_be_changed_through_one_application(argparse_app) -> None: + other = ArgparseApp() + spec = _spec(argparse_app, "tag") + assert spec is not None + with pytest.raises(dataclasses.FrozenInstanceError): + spec.preserve_quotes = False # type: ignore[misc] + other_spec = _spec(other, "tag") + assert other_spec is not None + assert other_spec.preserve_quotes + + +def test_cmd2_gives_get_argparse_command_spec_only_bound_methods() -> None: + class WatchedApp(ArgparseApp): + def __init__(self) -> None: + self.given: list[object] = [] + super().__init__() + + def get_argparse_command_spec(self, func: Any) -> ArgparseCommandSpec | None: + self.given.append(func) + return super().get_argparse_command_spec(func) + + app = WatchedApp() + run_cmd(app, 'tag mytag "hello"') # the first use of the command, which builds its parser + app.complete("", "tag ", 4, 4) + assert app.given + assert all(inspect.ismethod(func) for func in app.given)