Skip to content
Closed
2 changes: 2 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,8 @@
- Tab completion now works when a `choices_provider` or `completer` is a module-level lambda.
`get_defining_class()` also handles functions whose module cannot be found and unbound methods
of nested classes without raising `AttributeError`.
- Unbound completers defined on a nested `CommandSet` now receive the registered command set as
`self`. Previously, they received the application, which could cause tab completion to fail.
- `history /` and `History.regex_search("/")` now return only history entries containing a
forward slash. Previously, a lone slash was treated as an empty regex and matched every entry.
- Macros now expand `{1}` correctly when it is followed by an escaped `{{1}}`. For example,
Expand Down
4 changes: 3 additions & 1 deletion cmd2/annotated.py
Original file line number Diff line number Diff line change
Expand Up @@ -301,6 +301,7 @@ def do_build(self, target: str, common: CommonArgs):
ArgparseCommandSpec,
Cmd2ArgumentParser,
SubcommandSpec,
_registered_in_enclosing_factory,
)
from .completion import CompletionItem
from .decorators import _parse_positionals
Expand Down Expand Up @@ -3087,6 +3088,7 @@ def with_annotated(
"Configure these behaviors on the base command instead."
)

inline_ns_provider = _registered_in_enclosing_factory(ns_provider)
options = _ParserBuildOptions(
groups=groups,
mutually_exclusive_groups=mutually_exclusive_groups,
Expand Down Expand Up @@ -3167,7 +3169,7 @@ def cmd_wrapper(*args: Any, **kwargs: Any) -> _CommandReturn:
if ns_provider is None:
namespace = None
else:
provider_self = cmd_app._resolve_func_self(ns_provider, args[0])
provider_self = cmd_app._resolve_func_self(ns_provider, owner, include_enclosing_class=inline_ns_provider)
namespace = ns_provider(provider_self if provider_self is not None else cmd_app)

try:
Expand Down
25 changes: 23 additions & 2 deletions cmd2/argparse_completer.py
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,8 @@
from rich.text import Text

from .argparse_utils import (
_CHOICES_PROVIDER_SOURCE,
_COMPLETER_SOURCE,
Cmd2ArgumentParser,
build_range_error,
)
Expand All @@ -31,7 +33,10 @@
CompletionItem,
Completions,
)
from .constants import INFINITY
from .constants import (
INFINITY,
PARSER_ATTR_OWNER_ID,
)
from .exceptions import CompletionError
from .rich_utils import Cmd2SimpleTable
from .types import (
Expand Down Expand Up @@ -366,6 +371,12 @@ def consume_argument(arg_state: _ArgumentState, arg_token: str) -> None:
parent_tokens[action.dest] = [token]

parser = self._subcommand_action.choices[token]
# An attached subcommand may belong to a different set or to the app itself.
owner_id = getattr(parser, PARSER_ATTR_OWNER_ID, None)
if owner_id is not None:
cmd_set = next(
(owner for owner in self._cmd_app._installed_command_sets if id(owner) == owner_id), None
)
completer = parser.completer_class(parser, self._cmd_app, parent_tokens=parent_tokens)
return completer.complete(text, line, begidx, endidx, tokens[token_index + 1 :], cmd_set=cmd_set)

Expand Down Expand Up @@ -719,6 +730,7 @@ def _choices_to_items(self, arg_state: _ArgumentState) -> list[CompletionItem]:
def _prepare_callable_params(
self,
to_call: UnboundChoicesProvider[CmdOrSetT] | UnboundCompleter[CmdOrSetT],
source_attr: str,
arg_state: _ArgumentState,
text: str,
consumed_arg_values: dict[str, list[str]],
Expand All @@ -729,7 +741,14 @@ def _prepare_callable_params(
kwargs: dict[str, Any] = {}

# Resolve the 'self' instance for the method
self_arg = self._cmd_app._resolve_func_self(to_call, cmd_set)
source_ref = getattr(arg_state.action, source_attr, None)
original = source_ref() if source_ref is not None else None
receiver = self._cmd_app if cmd_set is None else cmd_set
self_arg = self._cmd_app._resolve_func_self(
original if original is not None else to_call,
receiver,
include_enclosing_class=getattr(arg_state.action, f"{source_attr}.inline", False),
)
if self_arg is None:
raise CompletionError("Could not find CommandSet instance matching defining type")

Expand Down Expand Up @@ -765,6 +784,7 @@ def _complete_arg(
if completer is not None:
args, kwargs = self._prepare_callable_params(
completer,
_COMPLETER_SOURCE,
arg_state,
text,
consumed_arg_values,
Expand All @@ -779,6 +799,7 @@ def _complete_arg(
if choices_provider is not None:
args, kwargs = self._prepare_callable_params(
choices_provider,
_CHOICES_PROVIDER_SOURCE,
arg_state,
text,
consumed_arg_values,
Expand Down
48 changes: 45 additions & 3 deletions cmd2/argparse_utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -226,9 +226,12 @@ def get_choices(self) -> Choices:

import argparse
import contextlib
import functools
import inspect
import re
import sys
import threading
import weakref
from argparse import ArgumentError
from collections.abc import (
Callable,
Expand Down Expand Up @@ -425,7 +428,35 @@ def _action_set_custom_parameter(self: argparse.Action, value: Any) -> None:
_CUSTOM_ACTION_ATTRIBS.add(param_name)


def _validate_completion_callable(self: argparse.Action, value: Any) -> Any:
class _CompletionSource(weakref.ref[functools.partial[Any]]):
"""Track a partial's live class identity across parser copies."""

def __deepcopy__(self, memo: dict[int, Any]) -> "_CompletionSource":
return self

def __reduce__(self) -> tuple[type, tuple[()]]:
# Ownership belongs to classes in this process. A deserialized action resolves its own callback.
return type(None), ()


def _registered_in_enclosing_factory(callback: Callable[..., Any] | None) -> bool:
"""Check at registration whether a local callback's enclosing factory is active."""
while isinstance(callback, functools.partial):
callback = callback.func
if not inspect.isfunction(callback):
return False
factory, local_scope, _ = callback.__qualname__.partition(".<locals>.")
if local_scope:
# Helpers and public action setters may sit between the factory and registration.
frame = sys._getframe().f_back
while frame is not None:
if frame.f_globals is callback.__globals__ and frame.f_code.co_qualname == factory:
return True
frame = frame.f_back
return False


def _validate_completion_callable(self: argparse.Action, value: Any, *, source_attr: str) -> Any:
"""Validate choices_provider and completer values for potential conflicts."""
if value is None:
return None
Expand All @@ -438,13 +469,24 @@ def _validate_completion_callable(self: argparse.Action, value: Any) -> Any:
"None of the following parameters can be used on an action that takes no arguments:\nchoices_provider, completer"
)
raise ValueError(err_msg)
# deepcopy creates a new partial (and copies its bound arguments). Keep the
# original identity for receiver lookup while invoking the parser's own copy.
setattr(self, source_attr, _CompletionSource(value) if isinstance(value, functools.partial) else None)
setattr(self, f"{source_attr}.inline", _registered_in_enclosing_factory(value))
return value


# Add new attributes to argparse.Action.
# See _ActionsContainer_add_argument() for details on these attributes.
register_argparse_argument_parameter("choices_provider", validator=_validate_completion_callable)
register_argparse_argument_parameter("completer", validator=_validate_completion_callable)
# Custom parameter names must be Python identifiers, so they cannot collide with these dotted names.
_CHOICES_PROVIDER_SOURCE = constants.cmd2_private_attr_name("choices_provider.source")
_COMPLETER_SOURCE = constants.cmd2_private_attr_name("completer.source")
register_argparse_argument_parameter(
"choices_provider", validator=functools.partial(_validate_completion_callable, source_attr=_CHOICES_PROVIDER_SOURCE)
)
register_argparse_argument_parameter(
"completer", validator=functools.partial(_validate_completion_callable, source_attr=_COMPLETER_SOURCE)
)
register_argparse_argument_parameter("table_columns")
register_argparse_argument_parameter("nargs_range")
register_argparse_argument_parameter("suppress_tab_hint")
Expand Down
57 changes: 21 additions & 36 deletions cmd2/cmd2.py
Original file line number Diff line number Diff line change
Expand Up @@ -215,6 +215,7 @@ def __init__(self, msg: str = "") -> None:
)
from .utils import (
Settable,
_get_defining_classes,
get_defining_class,
get_types,
strip_doc_annotations,
Expand Down Expand Up @@ -6584,6 +6585,8 @@ def _resolve_func_self(
self,
cmd_support_func: Callable[..., Any],
cmd_self: CmdOrSet | None,
*,
include_enclosing_class: bool = False,
) -> object | None:
"""Attempt to resolve a candidate instance to pass as 'self'.

Expand All @@ -6594,40 +6597,22 @@ def _resolve_func_self(

:param cmd_support_func: command support function. This could be a completer or namespace provider
:param cmd_self: The `self` associated with the command or subcommand
:param include_enclosing_class: whether the enclosing factory registered this callback
"""
# figure out what class the command support function was defined in
func_class: type[Any] | None = get_defining_class(cmd_support_func)

# Was there a defining class identified? If so, is it a sub-class of CommandSet?
if func_class is not None and issubclass(func_class, CommandSet):
# Since the support function is provided as an unbound function, we need to locate the instance
# of the CommandSet to pass in as `self` to emulate a bound method call.
# We're searching for candidates that match the support function's defining class type in this order:
# 1. Is the command's CommandSet a sub-class of the support function's class?
# 2. Do any of the registered CommandSets in the Cmd2 application exactly match the type?
# 3. Is there a registered CommandSet that is is the only matching subclass?

func_self: CmdOrSet | None

# check if the command's CommandSet is a sub-class of the support function's defining class
if isinstance(cmd_self, func_class):
# Case 1: Command's CommandSet is a sub-class of the support function's CommandSet
func_self = cmd_self
else:
# Search all registered CommandSets
func_self = None
candidate_sets: list[CommandSet[Any]] = []
for installed_cmd_set in self._installed_command_sets:
if type(installed_cmd_set) == func_class: # noqa: E721
# Case 2: CommandSet is an exact type match for the function's CommandSet
func_self = installed_cmd_set
break

# Add candidate for Case 3:
if isinstance(installed_cmd_set, func_class):
candidate_sets.append(installed_cmd_set)
if func_self is None and len(candidate_sets) == 1:
# Case 3: There exists exactly 1 CommandSet that is a sub-class match of the function's CommandSet
func_self = candidate_sets[0]
return func_self
return self
owners = _get_defining_classes(cmd_support_func, include_enclosing_class=include_enclosing_class)
owner_ids = {id(owner) for owner in owners}

def matches_owner(receiver: object) -> bool:
# A provider may be defined on a Protocol that disallows runtime instance checks.
return any(id(base) in owner_ids for base in type(receiver).__mro__)

if cmd_self is not None and matches_owner(cmd_self):
return cmd_self
if not any(issubclass(owner, CommandSet) for owner in owners):
return self

# Include the app among live owners and prefer an exact owner over an inheriting instance.
matches = [receiver for receiver in (self, *self._installed_command_sets) if matches_owner(receiver)]
exact = [receiver for receiver in matches if id(type(receiver)) in owner_ids]
candidates = exact or matches
return candidates[0] if len(candidates) == 1 else None
4 changes: 3 additions & 1 deletion cmd2/decorators.py
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,7 @@
NoParamParserFactory,
ParserSource,
SubcommandSpec,
_registered_in_enclosing_factory,
)
from .command_set import CommandSet
from .exceptions import Cmd2ArgparseError
Expand Down Expand Up @@ -301,6 +302,7 @@ def do_argprint(self, args: argparse.Namespace, unknown_args: list[str]):
```

"""
inline_ns_provider = _registered_in_enclosing_factory(ns_provider)

def arg_decorator(func: ArgparseCommandFunc[CmdOrSetT]) -> RawCommandFunc[CmdOrSetT]:
"""Decorate function that ingests an Argparse Command Function and returns a raw command function.
Expand Down Expand Up @@ -339,7 +341,7 @@ def cmd_wrapper(*args: Any, **kwargs: Any) -> bool | None:
# The namespace provider may or may not be defined in the same class as the command. Since provider
# functions are registered with the command argparser before anything is instantiated, we
# need to find an instance at runtime that matches the types during declaration
provider_self = cmd_app._resolve_func_self(ns_provider, args[0])
provider_self = cmd_app._resolve_func_self(ns_provider, args[0], include_enclosing_class=inline_ns_provider)
initial_namespace = ns_provider(provider_self if provider_self is not None else cmd_app)

try:
Expand Down
59 changes: 50 additions & 9 deletions cmd2/utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,6 @@
TextIO,
TypeVar,
Union,
cast,
)

from rich.text import Text
Expand Down Expand Up @@ -1570,30 +1569,72 @@ def do_echo(self, arglist):
setattr(cur_func, constants.COMMAND_ATTR_HELP_CATEGORY, category)


def _factory_method_owners(factory_class: type[Any], callback: Callable[..., Any]) -> tuple[type, ...]:
"""Find each class in the factory's hierarchy that installed this callback."""
pending = [factory_class]
visited: set[int] = set()
owners: list[type] = []
while pending:
cls = pending.pop()
if id(cls) in visited:
continue
visited.add(id(cls))
for member in vars(cls).values():
target = member.__func__ if isinstance(member, (staticmethod, classmethod)) else member
if target is callback:
owners.append(cls)
break
pending.extend(type.__subclasses__(cls))
return tuple(owners)


def get_defining_class(meth: Callable[..., Any]) -> type[Any] | None:
"""Attempt to resolve the class that defined a method.

Inspired by implementation published here:
https://stackoverflow.com/a/25959545/1956611

:param meth: method to inspect
:return: class type in which the supplied method was defined. None if it couldn't be resolved.
:return: class type in which the supplied method was defined. None if it couldn't be uniquely resolved.
"""
if isinstance(meth, functools.partial):
return get_defining_class(meth.func)
owners = _get_defining_classes(meth)
return owners[0] if len(owners) == 1 else None


def _get_defining_classes(meth: Callable[..., Any], *, include_enclosing_class: bool = False) -> tuple[type, ...]:
"""Resolve method ownership, including factory callbacks installed on several classes."""
original = meth
while isinstance(meth, functools.partial):
meth = meth.func
if inspect.ismethod(meth) or (
inspect.isbuiltin(meth) and hasattr(meth, "__self__") and hasattr(meth.__self__, "__class__")
):
for cls in inspect.getmro(meth.__self__.__class__):
if meth.__name__ in cls.__dict__:
return cls
return (cls,)
meth = getattr(meth, "__func__", meth) # fallback to __qualname__ parsing
if inspect.isfunction(meth):
# The name isn't necessarily in the module, as with a module-level lambda whose __qualname__ is "<lambda>"
owner = getattr(inspect.getmodule(meth), meth.__qualname__.split(".<locals>", 1)[0].rsplit(".", 1)[0], None)
# For a local function, the reachable path ends at its enclosing factory.
reachable_name, local_scope, _ = meth.__qualname__.partition(".<locals>.")
owner: object = inspect.getmodule(meth)
for name in reachable_name.split(".")[:-1]:
if owner is None:
break
owner = getattr(owner, name, None)
if isinstance(owner, type):
return owner
return cast(type, getattr(meth, "__objclass__", None)) # handle special descriptor objects
if not local_scope:
return (owner,)
owners = _factory_method_owners(owner, original)
if not owners and original is not meth:
# A partial of an installed method inherits that method's owner.
owners = _factory_method_owners(owner, meth)
if owners:
return owners
if include_enclosing_class:
# A class's factory registered its own local callback.
return (owner,)
descriptor_owner = getattr(meth, "__objclass__", None)
return (descriptor_owner,) if descriptor_owner is not None else ()


class CustomCompletionSettings:
Expand Down
Loading
Loading