Skip to content

Commit 5f91f70

Browse files
committed
Addressing more code review comments.
1 parent 24676aa commit 5f91f70

File tree

9 files changed

+95
-124
lines changed

9 files changed

+95
-124
lines changed

cmd2/argparse_custom.py

Lines changed: 4 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -294,10 +294,8 @@ def get_items(self) -> list[CompletionItems]:
294294
RichHelpFormatter,
295295
)
296296

297-
from . import (
298-
constants,
299-
rich_utils,
300-
)
297+
from . import constants
298+
from . import rich_utils as ru
301299
from .styles import Cmd2Style
302300

303301
if TYPE_CHECKING: # pragma: no cover
@@ -1115,12 +1113,12 @@ def __init__(
11151113
max_help_position: int = 24,
11161114
width: int | None = None,
11171115
*,
1118-
console: rich_utils.Cmd2Console | None = None,
1116+
console: ru.Cmd2Console | None = None,
11191117
**kwargs: Any,
11201118
) -> None:
11211119
"""Initialize Cmd2HelpFormatter."""
11221120
if console is None:
1123-
console = rich_utils.Cmd2Console()
1121+
console = ru.Cmd2Console()
11241122

11251123
super().__init__(prog, indent_increment, max_help_position, width, console=console, **kwargs)
11261124

cmd2/cmd2.py

Lines changed: 30 additions & 39 deletions
Original file line numberDiff line numberDiff line change
@@ -78,10 +78,10 @@
7878
argparse_custom,
7979
constants,
8080
plugin,
81-
rich_utils,
82-
string_utils,
8381
utils,
8482
)
83+
from . import rich_utils as ru
84+
from . import string_utils as su
8585
from .argparse_custom import (
8686
ChoicesProviderFunc,
8787
Cmd2ArgumentParser,
@@ -133,14 +133,6 @@
133133
Cmd2Console,
134134
RichPrintKwargs,
135135
)
136-
from .string_utils import (
137-
align_center,
138-
align_left,
139-
quote,
140-
str_width,
141-
strip_quotes,
142-
strip_style,
143-
)
144136
from .styles import Cmd2Style
145137

146138
# NOTE: When using gnureadline with Python 3.13, start_ipython needs to be imported before any readline-related stuff
@@ -304,7 +296,7 @@ class Cmd(cmd.Cmd):
304296
DEFAULT_EDITOR = utils.find_editor()
305297

306298
# Sorting keys for strings
307-
ALPHABETICAL_SORT_KEY = string_utils.norm_fold
299+
ALPHABETICAL_SORT_KEY = su.norm_fold
308300
NATURAL_SORT_KEY = utils.natural_keys
309301

310302
# List for storing transcript test file names
@@ -508,7 +500,7 @@ def __init__(
508500
if startup_script:
509501
startup_script = os.path.abspath(os.path.expanduser(startup_script))
510502
if os.path.exists(startup_script):
511-
script_cmd = f"run_script {quote(startup_script)}"
503+
script_cmd = f"run_script {su.quote(startup_script)}"
512504
if silence_startup_script:
513505
script_cmd += f" {constants.REDIRECTION_OUTPUT} {os.devnull}"
514506
self._startup_commands.append(script_cmd)
@@ -1139,24 +1131,23 @@ def build_settables(self) -> None:
11391131

11401132
def get_allow_style_choices(_cli_self: Cmd) -> list[str]:
11411133
"""Tab complete allow_style values."""
1142-
return [val.name.lower() for val in rich_utils.AllowStyle]
1134+
return [val.name.lower() for val in ru.AllowStyle]
11431135

1144-
def allow_style_type(value: str) -> rich_utils.AllowStyle:
1145-
"""Convert a string value into an rich_utils.AllowStyle."""
1136+
def allow_style_type(value: str) -> ru.AllowStyle:
1137+
"""Convert a string value into an ru.AllowStyle."""
11461138
try:
1147-
return rich_utils.AllowStyle[value.upper()]
1139+
return ru.AllowStyle[value.upper()]
11481140
except KeyError as ex:
11491141
raise ValueError(
1150-
f"must be {rich_utils.AllowStyle.ALWAYS}, {rich_utils.AllowStyle.NEVER}, or "
1151-
f"{rich_utils.AllowStyle.TERMINAL} (case-insensitive)"
1142+
f"must be {ru.AllowStyle.ALWAYS}, {ru.AllowStyle.NEVER}, or {ru.AllowStyle.TERMINAL} (case-insensitive)"
11521143
) from ex
11531144

11541145
self.add_settable(
11551146
Settable(
11561147
'allow_style',
11571148
allow_style_type,
11581149
'Allow ANSI text style sequences in output (valid values: '
1159-
f'{rich_utils.AllowStyle.ALWAYS}, {rich_utils.AllowStyle.NEVER}, {rich_utils.AllowStyle.TERMINAL})',
1150+
f'{ru.AllowStyle.ALWAYS}, {ru.AllowStyle.NEVER}, {ru.AllowStyle.TERMINAL})',
11601151
self,
11611152
choices_provider=cast(ChoicesProviderFunc, get_allow_style_choices),
11621153
)
@@ -1179,14 +1170,14 @@ def allow_style_type(value: str) -> rich_utils.AllowStyle:
11791170
# ----- Methods related to presenting output to the user -----
11801171

11811172
@property
1182-
def allow_style(self) -> rich_utils.AllowStyle:
1173+
def allow_style(self) -> ru.AllowStyle:
11831174
"""Read-only property needed to support do_set when it reads allow_style."""
1184-
return rich_utils.allow_style
1175+
return ru.allow_style
11851176

11861177
@allow_style.setter
1187-
def allow_style(self, new_val: rich_utils.AllowStyle) -> None:
1178+
def allow_style(self, new_val: ru.AllowStyle) -> None:
11881179
"""Setter property needed to support do_set when it updates allow_style."""
1189-
rich_utils.allow_style = new_val
1180+
ru.allow_style = new_val
11901181

11911182
def _completion_supported(self) -> bool:
11921183
"""Return whether tab completion is supported."""
@@ -1201,7 +1192,7 @@ def visible_prompt(self) -> str:
12011192
12021193
:return: prompt stripped of any ANSI escape codes
12031194
"""
1204-
return strip_style(self.prompt)
1195+
return su.strip_style(self.prompt)
12051196

12061197
def print_to(
12071198
self,
@@ -1231,7 +1222,7 @@ def print_to(
12311222
method and still call `super()` without encountering unexpected keyword argument errors.
12321223
These arguments are not passed to Rich's Console.print().
12331224
"""
1234-
prepared_objects = rich_utils.prepare_objects_for_rich_print(*objects)
1225+
prepared_objects = ru.prepare_objects_for_rich_print(*objects)
12351226

12361227
try:
12371228
Cmd2Console(file).print(
@@ -1522,7 +1513,7 @@ def ppaged(
15221513

15231514
# Check if we are outputting to a pager.
15241515
if functional_terminal and can_block:
1525-
prepared_objects = rich_utils.prepare_objects_for_rich_print(*objects)
1516+
prepared_objects = ru.prepare_objects_for_rich_print(*objects)
15261517

15271518
# Chopping overrides soft_wrap
15281519
if chop:
@@ -1639,7 +1630,7 @@ def tokens_for_completion(self, line: str, begidx: int, endidx: int) -> tuple[li
16391630
raw_tokens = self.statement_parser.split_on_punctuation(initial_tokens)
16401631

16411632
# Save the unquoted tokens
1642-
tokens = [strip_quotes(cur_token) for cur_token in raw_tokens]
1633+
tokens = [su.strip_quotes(cur_token) for cur_token in raw_tokens]
16431634

16441635
# If the token being completed had an unclosed quote, we need
16451636
# to remove the closing quote that was added in order for it
@@ -2141,7 +2132,7 @@ def _display_matches_gnu_readline(
21412132
longest_match_length = 0
21422133

21432134
for cur_match in matches_to_display:
2144-
cur_length = str_width(cur_match)
2135+
cur_length = su.str_width(cur_match)
21452136
longest_match_length = max(longest_match_length, cur_length)
21462137
else:
21472138
matches_to_display = matches
@@ -3133,7 +3124,7 @@ def _redirect_output(self, statement: Statement) -> utils.RedirectionSavedState:
31333124
mode = 'a' if statement.output == constants.REDIRECTION_APPEND else 'w'
31343125
try:
31353126
# Use line buffering
3136-
new_stdout = cast(TextIO, open(strip_quotes(statement.output_to), mode=mode, buffering=1)) # noqa: SIM115
3127+
new_stdout = cast(TextIO, open(su.strip_quotes(statement.output_to), mode=mode, buffering=1)) # noqa: SIM115
31373128
except OSError as ex:
31383129
raise RedirectionError('Failed to redirect output') from ex
31393130

@@ -4163,7 +4154,7 @@ def columnize(self, str_list: list[str] | None, display_width: int = 80) -> None
41634154
if i >= size:
41644155
break
41654156
x = str_list[i]
4166-
colwidth = max(colwidth, str_width(x))
4157+
colwidth = max(colwidth, su.str_width(x))
41674158
colwidths.append(colwidth)
41684159
totwidth += colwidth + 2
41694160
if totwidth > display_width:
@@ -4184,7 +4175,7 @@ def columnize(self, str_list: list[str] | None, display_width: int = 80) -> None
41844175
while texts and not texts[-1]:
41854176
del texts[-1]
41864177
for col in range(len(texts)):
4187-
texts[col] = align_left(texts[col], width=colwidths[col])
4178+
texts[col] = su.align_left(texts[col], width=colwidths[col])
41884179
self.poutput(" ".join(texts))
41894180

41904181
def _help_menu(self, verbose: bool = False) -> None:
@@ -4480,7 +4471,7 @@ def do_set(self, args: argparse.Namespace) -> None:
44804471
# Try to update the settable's value
44814472
try:
44824473
orig_value = settable.get_value()
4483-
settable.set_value(strip_quotes(args.value))
4474+
settable.set_value(su.strip_quotes(args.value))
44844475
except ValueError as ex:
44854476
self.perror(f"Error setting {args.param}: {ex}")
44864477
else:
@@ -5076,7 +5067,7 @@ def do_history(self, args: argparse.Namespace) -> bool | None:
50765067
self.run_editor(fname)
50775068

50785069
# self.last_result will be set by do_run_script()
5079-
return self.do_run_script(quote(fname))
5070+
return self.do_run_script(su.quote(fname))
50805071
finally:
50815072
os.remove(fname)
50825073
elif args.output_file:
@@ -5371,9 +5362,9 @@ def run_editor(self, file_path: str | None = None) -> None:
53715362
if not self.editor:
53725363
raise OSError("Please use 'set editor' to specify your text editing program of choice.")
53735364

5374-
command = quote(os.path.expanduser(self.editor))
5365+
command = su.quote(os.path.expanduser(self.editor))
53755366
if file_path:
5376-
command += " " + quote(os.path.expanduser(file_path))
5367+
command += " " + su.quote(os.path.expanduser(file_path))
53775368

53785369
self.do_shell(command)
53795370

@@ -5511,7 +5502,7 @@ def do__relative_run_script(self, args: argparse.Namespace) -> bool | None:
55115502
relative_path = os.path.join(self._current_script_dir or '', script_path)
55125503

55135504
# self.last_result will be set by do_run_script()
5514-
return self.do_run_script(quote(relative_path))
5505+
return self.do_run_script(su.quote(relative_path))
55155506

55165507
def _run_transcript_tests(self, transcript_paths: list[str]) -> None:
55175508
"""Run transcript tests for provided file(s).
@@ -5543,7 +5534,7 @@ class TestMyAppCase(Cmd2TestCase):
55435534
verinfo = ".".join(map(str, sys.version_info[:3]))
55445535
num_transcripts = len(transcripts_expanded)
55455536
plural = '' if len(transcripts_expanded) == 1 else 's'
5546-
self.poutput(align_center(' cmd2 transcript test ', character=self.ruler), style=Style(bold=True))
5537+
self.poutput(su.align_center(' cmd2 transcript test ', character=self.ruler), style=Style(bold=True))
55475538
self.poutput(f'platform {sys.platform} -- Python {verinfo}, cmd2-{cmd2.__version__}, readline-{rl_type}')
55485539
self.poutput(f'cwd: {os.getcwd()}')
55495540
self.poutput(f'cmd2 app: {sys.argv[0]}')
@@ -5560,7 +5551,7 @@ class TestMyAppCase(Cmd2TestCase):
55605551
if test_results.wasSuccessful():
55615552
self.perror(stream.read(), end="", style=None)
55625553
finish_msg = f' {num_transcripts} transcript{plural} passed in {execution_time:.3f} seconds '
5563-
finish_msg = align_center(finish_msg, character=self.ruler)
5554+
finish_msg = su.align_center(finish_msg, character=self.ruler)
55645555
self.psuccess(finish_msg)
55655556
else:
55665557
# Strip off the initial traceback which isn't particularly useful for end users
@@ -5624,7 +5615,7 @@ def async_alert(self, alert_msg: str, new_prompt: str | None = None) -> None: #
56245615

56255616
# Print a string which replaces the onscreen prompt and input lines with the alert.
56265617
terminal_str = async_alert_str(
5627-
terminal_columns=rich_utils.console_width(),
5618+
terminal_columns=ru.console_width(),
56285619
prompt=rl_get_display_prompt(),
56295620
line=readline.get_line_buffer(),
56305621
cursor_offset=rl_get_point(),

cmd2/history.py

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -14,7 +14,7 @@
1414
overload,
1515
)
1616

17-
from . import string_utils
17+
from . import string_utils as su
1818
from .parsing import (
1919
Statement,
2020
shlex_split,
@@ -285,9 +285,9 @@ def str_search(self, search: str, include_persisted: bool = False) -> 'OrderedDi
285285

286286
def isin(history_item: HistoryItem) -> bool:
287287
"""Filter function for string search of history."""
288-
sloppy = string_utils.norm_fold(search)
289-
inraw = sloppy in string_utils.norm_fold(history_item.raw)
290-
inexpanded = sloppy in string_utils.norm_fold(history_item.expanded)
288+
sloppy = su.norm_fold(search)
289+
inraw = sloppy in su.norm_fold(history_item.raw)
290+
inexpanded = sloppy in su.norm_fold(history_item.expanded)
291291
return inraw or inexpanded
292292

293293
start = 0 if include_persisted else self.session_start_index

cmd2/parsing.py

Lines changed: 6 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -7,18 +7,14 @@
77
dataclass,
88
field,
99
)
10-
from typing import (
11-
Any,
12-
)
10+
from typing import Any
1311

1412
from . import (
1513
constants,
16-
string_utils,
1714
utils,
1815
)
19-
from .exceptions import (
20-
Cmd2ShlexError,
21-
)
16+
from . import string_utils as su
17+
from .exceptions import Cmd2ShlexError
2218

2319

2420
def shlex_split(str_to_split: str) -> list[str]:
@@ -212,8 +208,8 @@ def argv(self) -> list[str]:
212208
If you want to strip quotes from the input, you can use ``argv[1:]``.
213209
"""
214210
if self.command:
215-
rtn = [string_utils.strip_quotes(self.command)]
216-
rtn.extend(string_utils.strip_quotes(cur_token) for cur_token in self.arg_list)
211+
rtn = [su.strip_quotes(self.command)]
212+
rtn.extend(su.strip_quotes(cur_token) for cur_token in self.arg_list)
217213
else:
218214
rtn = []
219215

@@ -489,7 +485,7 @@ def parse(self, line: str) -> Statement:
489485

490486
# Check if we are redirecting to a file
491487
if len(tokens) > output_index + 1:
492-
unquoted_path = string_utils.strip_quotes(tokens[output_index + 1])
488+
unquoted_path = su.strip_quotes(tokens[output_index + 1])
493489
if unquoted_path:
494490
output_to = utils.expand_user(tokens[output_index + 1])
495491

0 commit comments

Comments
 (0)