Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 6 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -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)

Expand Down
2 changes: 1 addition & 1 deletion cmd2/argparse_utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -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.

Expand Down
31 changes: 29 additions & 2 deletions cmd2/cmd2.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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]
Expand Down Expand Up @@ -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.

Expand Down
13 changes: 13 additions & 0 deletions docs/features/argument_processing.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
89 changes: 89 additions & 0 deletions tests/test_argparse.py
Original file line number Diff line number Diff line change
@@ -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,
Expand Down Expand Up @@ -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)
Loading