Skip to content

Commit 5e40748

Browse files
committed
Renamed internal Cmd instance references to _cmd_app in all utility classes
1 parent 4b620f0 commit 5e40748

8 files changed

Lines changed: 155 additions & 155 deletions

File tree

cmd2/argparse_completer.py

Lines changed: 14 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -158,20 +158,20 @@ class ArgparseCompleter:
158158
def __init__(
159159
self,
160160
parser: Cmd2ArgumentParser,
161-
cmd2_app: "Cmd",
161+
cmd_app: "Cmd",
162162
*,
163163
parent_tokens: Mapping[str, MutableSequence[str]] | None = None,
164164
) -> None:
165165
"""Create an ArgparseCompleter.
166166
167167
:param parser: Cmd2ArgumentParser instance
168-
:param cmd2_app: reference to the Cmd2 application that owns this ArgparseCompleter
168+
:param cmd_app: reference to the cmd2.Cmd instance that owns this ArgparseCompleter
169169
:param parent_tokens: optional Mapping of parent parsers' arg names to their tokens
170170
This is only used by ArgparseCompleter when recursing on subcommand parsers
171171
Defaults to None
172172
"""
173173
self._parser = parser
174-
self._cmd2_app = cmd2_app
174+
self._cmd_app = cmd_app
175175

176176
if parent_tokens is None:
177177
parent_tokens = {}
@@ -366,8 +366,8 @@ def consume_argument(arg_state: _ArgumentState, arg_token: str) -> None:
366366
parent_tokens[action.dest] = [token]
367367

368368
parser = self._subcommand_action.choices[token]
369-
completer_type = self._cmd2_app._determine_ap_completer_type(parser)
370-
completer = completer_type(parser, self._cmd2_app, parent_tokens=parent_tokens)
369+
completer_type = self._cmd_app._determine_ap_completer_type(parser)
370+
completer = completer_type(parser, self._cmd_app, parent_tokens=parent_tokens)
371371
return completer.complete(text, line, begidx, endidx, tokens[token_index + 1 :], cmd_set=cmd_set)
372372

373373
# Invalid subcommand entered, so no way to complete remaining tokens
@@ -544,7 +544,7 @@ def _complete_flags(self, text: str, line: str, begidx: int, endidx: int, used_f
544544

545545
# Keep flags sorted in the order provided by argparse so our completion
546546
# suggestions display the same as argparse help text.
547-
matched_flags = self._cmd2_app.basic_complete(text, line, begidx, endidx, match_against, sort=False)
547+
matched_flags = self._cmd_app.basic_complete(text, line, begidx, endidx, match_against, sort=False)
548548

549549
for flag in matched_flags.to_strings():
550550
action = self._flag_to_action[flag]
@@ -613,7 +613,7 @@ def _build_completion_table(self, arg_state: _ArgumentState, completions: Comple
613613
# Skip table generation if results are outside thresholds or no columns are defined
614614
if (
615615
len(completions) < 2
616-
or len(completions) > self._cmd2_app.max_completion_table_items
616+
or len(completions) > self._cmd_app.max_completion_table_items
617617
or table_columns is None
618618
): # fmt: skip
619619
return completions
@@ -668,13 +668,13 @@ def complete_subcommand_help(self, text: str, line: str, begidx: int, endidx: in
668668
for token_index, token in enumerate(tokens):
669669
if token in self._subcommand_action.choices:
670670
parser = self._subcommand_action.choices[token]
671-
completer_type = self._cmd2_app._determine_ap_completer_type(parser)
672-
completer = completer_type(parser, self._cmd2_app)
671+
completer_type = self._cmd_app._determine_ap_completer_type(parser)
672+
completer = completer_type(parser, self._cmd_app)
673673
return completer.complete_subcommand_help(text, line, begidx, endidx, tokens[token_index + 1 :])
674674

675675
if token_index == len(tokens) - 1:
676676
# Since this is the last token, we will attempt to complete it
677-
return self._cmd2_app.basic_complete(text, line, begidx, endidx, self._subcommand_action.choices)
677+
return self._cmd_app.basic_complete(text, line, begidx, endidx, self._subcommand_action.choices)
678678
break
679679
return Completions()
680680

@@ -690,8 +690,8 @@ def print_help(self, tokens: Sequence[str], file: IO[str] | None = None) -> None
690690
if tokens and self._subcommand_action is not None:
691691
parser = self._subcommand_action.choices.get(tokens[0])
692692
if parser is not None:
693-
completer_type = self._cmd2_app._determine_ap_completer_type(parser)
694-
completer = completer_type(parser, self._cmd2_app)
693+
completer_type = self._cmd_app._determine_ap_completer_type(parser)
694+
completer = completer_type(parser, self._cmd_app)
695695
completer.print_help(tokens[1:], file)
696696
return
697697
self._parser.print_help(file)
@@ -732,7 +732,7 @@ def _prepare_callable_params(
732732
kwargs: dict[str, Any] = {}
733733

734734
# Resolve the 'self' instance for the method
735-
self_arg = self._cmd2_app._resolve_func_self(to_call, cmd_set)
735+
self_arg = self._cmd_app._resolve_func_self(to_call, cmd_set)
736736
if self_arg is None:
737737
raise CompletionError("Could not find CommandSet instance matching defining type")
738738

@@ -794,7 +794,7 @@ def _complete_arg(
794794
# Filter used values and run basic completion
795795
used_values = consumed_arg_values.get(arg_state.action.dest, [])
796796
filtered = [choice for choice in all_choices if choice.text not in used_values]
797-
completions = self._cmd2_app.basic_complete(text, line, begidx, endidx, filtered)
797+
completions = self._cmd_app.basic_complete(text, line, begidx, endidx, filtered)
798798

799799
return self._build_completion_table(arg_state, completions)
800800

cmd2/cmd2.py

Lines changed: 5 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -239,12 +239,12 @@ class CommandParsers:
239239
Parser creation and retrieval are accomplished through the get() method.
240240
"""
241241

242-
def __init__(self, cmd: "Cmd") -> None:
242+
def __init__(self, cmd_app: "Cmd") -> None:
243243
"""Initialize CommandParsers.
244244
245-
:param cmd: the Cmd instance whose parsers are being managed
245+
:param cmd_app: the Cmd instance whose parsers are being managed
246246
"""
247-
self._cmd = cmd
247+
self._cmd_app = cmd_app
248248

249249
# Keyed by the fully qualified method names. This is more reliable than
250250
# the methods themselves, since wrapping a method will change its address.
@@ -285,8 +285,8 @@ def get(self, command_method: BoundCommandFunc) -> Cmd2ArgumentParser | None:
285285
if parser_builder is None:
286286
return None
287287

288-
parent = self._cmd.find_commandset_for_command(command) or self._cmd
289-
parser = self._cmd._build_parser(parent, parser_builder)
288+
parent = self._cmd_app.find_commandset_for_command(command) or self._cmd_app
289+
parser = self._cmd_app._build_parser(parent, parser_builder)
290290

291291
# To ensure accurate usage strings, recursively update 'prog' values
292292
# within the parser to match the command name.

cmd2/decorators.py

Lines changed: 10 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -178,13 +178,13 @@ def cmd_wrapper(*args: Any, **kwargs: Any) -> bool | None:
178178
"""Command function wrapper which translates command line into an argument list and calls actual command function.
179179
180180
:param args: All positional arguments to this function. We're expecting there to be:
181-
cmd2_app, statement: Union[Statement, str]
181+
cmd_app, statement: Union[Statement, str]
182182
contiguously somewhere in the list
183183
:param kwargs: any keyword arguments being passed to command function
184184
:return: return value of command function
185185
"""
186-
cmd2_app, statement = _parse_positionals(args)
187-
_, command_arg_list = cmd2_app.statement_parser.get_command_arg_list(command_name, statement, preserve_quotes)
186+
cmd_app, statement = _parse_positionals(args)
187+
_, command_arg_list = cmd_app.statement_parser.get_command_arg_list(command_name, statement, preserve_quotes)
188188
func_arg_list = _arg_swap(args, statement, command_arg_list)
189189
return func(*func_arg_list, **kwargs)
190190

@@ -275,19 +275,19 @@ def cmd_wrapper(*args: Any, **kwargs: Any) -> bool | None:
275275
"""Command function wrapper which translates command line into argparse Namespace and call actual command function.
276276
277277
:param args: All positional arguments to this function. We're expecting there to be:
278-
cmd2_app, statement: Union[Statement, str]
278+
cmd_app, statement: Union[Statement, str]
279279
contiguously somewhere in the list
280280
:param kwargs: any keyword arguments being passed to command function
281281
:return: return value of command function
282282
:raises Cmd2ArgparseError: if argparse has error parsing command line
283283
"""
284-
cmd2_app, statement_arg = _parse_positionals(args)
285-
statement, command_arg_list = cmd2_app.statement_parser.get_command_arg_list(
284+
cmd_app, statement_arg = _parse_positionals(args)
285+
statement, command_arg_list = cmd_app.statement_parser.get_command_arg_list(
286286
command_name, statement_arg, preserve_quotes
287287
)
288288

289289
# Pass cmd_wrapper instead of func, since it contains the parser info.
290-
arg_parser = cmd2_app.command_parsers.get(cmd_wrapper)
290+
arg_parser = cmd_app.command_parsers.get(cmd_wrapper)
291291
if arg_parser is None:
292292
# This shouldn't be possible to reach
293293
raise ValueError(f"No argument parser found for {command_name}") # pragma: no cover
@@ -298,12 +298,12 @@ def cmd_wrapper(*args: Any, **kwargs: Any) -> bool | None:
298298
# The namespace provider may or may not be defined in the same class as the command. Since provider
299299
# functions are registered with the command argparser before anything is instantiated, we
300300
# need to find an instance at runtime that matches the types during declaration
301-
provider_self = cmd2_app._resolve_func_self(ns_provider, args[0])
302-
initial_namespace = ns_provider(provider_self if provider_self is not None else cmd2_app)
301+
provider_self = cmd_app._resolve_func_self(ns_provider, args[0])
302+
initial_namespace = ns_provider(provider_self if provider_self is not None else cmd_app)
303303

304304
try:
305305
parsing_results: tuple[argparse.Namespace] | tuple[argparse.Namespace, list[str]]
306-
with arg_parser.output_to(cmd2_app.stdout):
306+
with arg_parser.output_to(cmd_app.stdout):
307307
if with_unknown_args:
308308
parsing_results = arg_parser.parse_known_args(command_arg_list, initial_namespace)
309309
else:

cmd2/pt_utils.py

Lines changed: 12 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -132,7 +132,7 @@ def __init__(
132132
custom_settings: utils.CustomCompletionSettings | None = None,
133133
) -> None:
134134
"""Initialize prompt_toolkit based completer class."""
135-
self.cmd_app = cmd_app
135+
self._cmd_app = cmd_app
136136
self.custom_settings = custom_settings
137137

138138
def get_completions(self, document: Document, _complete_event: object) -> Iterable[Completion]:
@@ -143,7 +143,7 @@ def get_completions(self, document: Document, _complete_event: object) -> Iterab
143143

144144
# Define delimiters for completion to match cmd2/readline behavior
145145
delimiters = BASE_DELIMITERS
146-
delimiters += "".join(self.cmd_app.statement_parser.terminators)
146+
delimiters += "".join(self._cmd_app.statement_parser.terminators)
147147

148148
# Find last delimiter before cursor to determine the word being completed
149149
begidx = 0
@@ -155,7 +155,7 @@ def get_completions(self, document: Document, _complete_event: object) -> Iterab
155155
endidx = cursor_pos
156156
text = line[begidx:endidx]
157157

158-
completions = self.cmd_app.complete(
158+
completions = self._cmd_app.complete(
159159
text, line=line, begidx=begidx, endidx=endidx, custom_settings=self.custom_settings
160160
)
161161

@@ -165,7 +165,7 @@ def get_completions(self, document: Document, _complete_event: object) -> Iterab
165165

166166
# Print completion table if present
167167
if completions.table is not None:
168-
console = ru.Cmd2GeneralConsole(file=self.cmd_app.stdout)
168+
console = ru.Cmd2GeneralConsole(file=self._cmd_app.stdout)
169169
with console.capture() as capture:
170170
console.print(completions.table, end="", soft_wrap=False)
171171
print_formatted_text(pt_filter_style("\n" + capture.get()))
@@ -252,7 +252,7 @@ def append_string(self, string: str) -> None:
252252
super().append_string(string)
253253

254254
def store_string(self, string: str) -> None:
255-
"""No-op: Persistent history data is stored in cmd_app.history."""
255+
"""No-op: Persistent history data is stored in cmd2.Cmd.history."""
256256

257257
def load_history_strings(self) -> Iterable[str]:
258258
"""Yield strings from newest to oldest."""
@@ -287,7 +287,7 @@ def __init__(
287287
:param cmd_app: cmd2.Cmd instance
288288
"""
289289
super().__init__()
290-
self.cmd_app = cmd_app
290+
self._cmd_app = cmd_app
291291

292292
_lexers.add(self)
293293
self.set_colors()
@@ -306,7 +306,7 @@ def lex_document(self, document: Document) -> Callable[[int], Any]:
306306
"""Lex the document."""
307307
# Get redirection tokens and terminators to avoid highlighting them as values
308308
exclude_tokens = set(constants.REDIRECTION_TOKENS)
309-
exclude_tokens.update(self.cmd_app.statement_parser.terminators)
309+
exclude_tokens.update(self._cmd_app.statement_parser.terminators)
310310
arg_pattern = re.compile(r'(\s+)|(--?[^\s\'"]+)|("[^"]*"?|\'[^\']*\'?)|([^\s\'"]+)')
311311

312312
def highlight_args(text: str, tokens: list[tuple[str, str]]) -> None:
@@ -337,7 +337,7 @@ def get_line(lineno: int) -> list[tuple[str, str]]:
337337
# Only attempt to match a command on the first line
338338
if lineno == 0:
339339
# Use cmd2's command pattern to find the first word (the command)
340-
match = self.cmd_app.statement_parser._command_pattern.search(line)
340+
match = self._cmd_app.statement_parser._command_pattern.search(line)
341341
if match:
342342
# Group 1 is the command, Group 2 is the character(s) that terminated the command match
343343
command = match.group(1)
@@ -351,7 +351,7 @@ def get_line(lineno: int) -> list[tuple[str, str]]:
351351
if command:
352352
# Determine the style for the command
353353
shortcut_found = False
354-
for shortcut, _ in self.cmd_app.statement_parser.shortcuts:
354+
for shortcut, _ in self._cmd_app.statement_parser.shortcuts:
355355
if command.startswith(shortcut):
356356
# Add the shortcut with the command style
357357
tokens.append((self.command_color, shortcut))
@@ -365,11 +365,11 @@ def get_line(lineno: int) -> list[tuple[str, str]]:
365365

366366
if not shortcut_found:
367367
style = ""
368-
if command in self.cmd_app.get_all_commands():
368+
if command in self._cmd_app.get_all_commands():
369369
style = self.command_color
370-
elif command in self.cmd_app.aliases:
370+
elif command in self._cmd_app.aliases:
371371
style = self.alias_color
372-
elif command in self.cmd_app.macros:
372+
elif command in self._cmd_app.macros:
373373
style = self.macro_color
374374

375375
# Add the command with the determined style

cmd2/py_bridge.py

Lines changed: 12 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -74,14 +74,14 @@ def __bool__(self) -> bool:
7474
class PyBridge:
7575
"""Provides a Python API wrapper for application commands.
7676
77-
:param cmd2_app: app being controlled by this PyBridge.
77+
:param cmd_app: app being controlled by this PyBridge.
7878
:param add_to_history: If True, then add all commands run by this PyBridge to history.
7979
Defaults to True.
8080
"""
8181

82-
def __init__(self, cmd2_app: "Cmd", *, add_to_history: bool = True) -> None:
82+
def __init__(self, cmd_app: "Cmd", *, add_to_history: bool = True) -> None:
8383
"""Initialize PyBridge instances."""
84-
self._cmd2_app = cmd2_app
84+
self._cmd_app = cmd_app
8585
self._add_to_history = add_to_history
8686
self.cmd_echo = False
8787

@@ -100,42 +100,42 @@ def __call__(self, command: str, *, echo: bool | None = None) -> CommandResult:
100100
ex: app('help')
101101
:param command: command line being run
102102
:param echo: If provided, this temporarily overrides the value of self.cmd_echo
103-
while the command runs. If True, output will be echoed to _cmd2_app.stdout
103+
while the command runs. If True, output will be echoed to _cmd_app.stdout
104104
and sys.stderr. (Defaults to None)
105105
"""
106106
if echo is None:
107107
echo = self.cmd_echo
108108

109-
# This will be used to capture _cmd2_app.stdout
110-
copy_cmd_stdout = StdSim(cast(TextIO | StdSim, self._cmd2_app.stdout), echo=echo)
109+
# This will be used to capture _cmd_app.stdout
110+
copy_cmd_stdout = StdSim(cast(TextIO | StdSim, self._cmd_app.stdout), echo=echo)
111111

112112
# Pause the storing of stdout until onecmd_plus_hooks enables it
113113
copy_cmd_stdout.pause_storage = True
114114

115115
# This will be used to capture sys.stderr
116116
copy_stderr = StdSim(sys.stderr, echo=echo)
117117

118-
self._cmd2_app.last_result = None
118+
self._cmd_app.last_result = None
119119

120120
stop = False
121121
try:
122-
self._cmd2_app.stdout = cast(TextIO, copy_cmd_stdout)
122+
self._cmd_app.stdout = cast(TextIO, copy_cmd_stdout)
123123

124124
with redirect_stderr(cast(IO[str], copy_stderr)):
125-
stop = self._cmd2_app.onecmd_plus_hooks(
125+
stop = self._cmd_app.onecmd_plus_hooks(
126126
command,
127127
add_to_history=self._add_to_history,
128128
py_bridge_call=True,
129129
)
130130
finally:
131-
with self._cmd2_app.sigint_protection:
132-
self._cmd2_app.stdout = cast(TextIO, copy_cmd_stdout.inner_stream)
131+
with self._cmd_app.sigint_protection:
132+
self._cmd_app.stdout = cast(TextIO, copy_cmd_stdout.inner_stream)
133133
self.stop = stop or self.stop
134134

135135
# Save the result
136136
return CommandResult(
137137
stdout=copy_cmd_stdout.getvalue(),
138138
stderr=copy_stderr.getvalue(),
139139
stop=stop,
140-
data=self._cmd2_app.last_result,
140+
data=self._cmd_app.last_result,
141141
)

tests/conftest.py

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -22,15 +22,15 @@
2222
T = TypeVar("T")
2323

2424

25-
def verify_help_text(cmd2_app: cmd2.Cmd, help_output: str | list[str], verbose_strings: list[str] | None = None) -> None:
25+
def verify_help_text(cmd_app: cmd2.Cmd, help_output: str | list[str], verbose_strings: list[str] | None = None) -> None:
2626
"""This function verifies that all expected commands are present in the help text.
2727
28-
:param cmd2_app: instance of cmd2.Cmd
28+
:param cmd_app: instance of cmd2.Cmd
2929
:param help_output: output of help, either as a string or list of strings
3030
:param verbose_strings: optional list of verbose strings to search for
3131
"""
3232
help_text = help_output if isinstance(help_output, str) else "".join(help_output)
33-
commands = cmd2_app.get_visible_commands()
33+
commands = cmd_app.get_visible_commands()
3434
for command in commands:
3535
assert command in help_text
3636

tests/test_argparse_completer.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1271,7 +1271,7 @@ def _complete_flags(self, text: str, line: str, begidx: int, endidx: int, used_f
12711271
# Find flags which should not be completed and place them in used_flags
12721272
for flag in self._flags:
12731273
action = self._flag_to_action[flag]
1274-
app: CustomCompleterApp = cast(CustomCompleterApp, self._cmd2_app)
1274+
app: CustomCompleterApp = cast(CustomCompleterApp, self._cmd_app)
12751275
if action.get_complete_when_ready() and not app.is_ready:
12761276
used_flags.append(flag)
12771277

0 commit comments

Comments
 (0)