78
78
argparse_custom ,
79
79
constants ,
80
80
plugin ,
81
- rich_utils ,
82
- string_utils ,
83
81
utils ,
84
82
)
83
+ from . import rich_utils as ru
84
+ from . import string_utils as su
85
85
from .argparse_custom import (
86
86
ChoicesProviderFunc ,
87
87
Cmd2ArgumentParser ,
133
133
Cmd2Console ,
134
134
RichPrintKwargs ,
135
135
)
136
- from .string_utils import (
137
- align_center ,
138
- align_left ,
139
- quote ,
140
- str_width ,
141
- strip_quotes ,
142
- strip_style ,
143
- )
144
136
from .styles import Cmd2Style
145
137
146
138
# 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):
304
296
DEFAULT_EDITOR = utils .find_editor ()
305
297
306
298
# Sorting keys for strings
307
- ALPHABETICAL_SORT_KEY = string_utils .norm_fold
299
+ ALPHABETICAL_SORT_KEY = su .norm_fold
308
300
NATURAL_SORT_KEY = utils .natural_keys
309
301
310
302
# List for storing transcript test file names
@@ -508,7 +500,7 @@ def __init__(
508
500
if startup_script :
509
501
startup_script = os .path .abspath (os .path .expanduser (startup_script ))
510
502
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 )} "
512
504
if silence_startup_script :
513
505
script_cmd += f" { constants .REDIRECTION_OUTPUT } { os .devnull } "
514
506
self ._startup_commands .append (script_cmd )
@@ -1139,24 +1131,23 @@ def build_settables(self) -> None:
1139
1131
1140
1132
def get_allow_style_choices (_cli_self : Cmd ) -> list [str ]:
1141
1133
"""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 ]
1143
1135
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."""
1146
1138
try :
1147
- return rich_utils .AllowStyle [value .upper ()]
1139
+ return ru .AllowStyle [value .upper ()]
1148
1140
except KeyError as ex :
1149
1141
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)"
1152
1143
) from ex
1153
1144
1154
1145
self .add_settable (
1155
1146
Settable (
1156
1147
'allow_style' ,
1157
1148
allow_style_type ,
1158
1149
'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 } )' ,
1160
1151
self ,
1161
1152
choices_provider = cast (ChoicesProviderFunc , get_allow_style_choices ),
1162
1153
)
@@ -1179,14 +1170,14 @@ def allow_style_type(value: str) -> rich_utils.AllowStyle:
1179
1170
# ----- Methods related to presenting output to the user -----
1180
1171
1181
1172
@property
1182
- def allow_style (self ) -> rich_utils .AllowStyle :
1173
+ def allow_style (self ) -> ru .AllowStyle :
1183
1174
"""Read-only property needed to support do_set when it reads allow_style."""
1184
- return rich_utils .allow_style
1175
+ return ru .allow_style
1185
1176
1186
1177
@allow_style .setter
1187
- def allow_style (self , new_val : rich_utils .AllowStyle ) -> None :
1178
+ def allow_style (self , new_val : ru .AllowStyle ) -> None :
1188
1179
"""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
1190
1181
1191
1182
def _completion_supported (self ) -> bool :
1192
1183
"""Return whether tab completion is supported."""
@@ -1201,7 +1192,7 @@ def visible_prompt(self) -> str:
1201
1192
1202
1193
:return: prompt stripped of any ANSI escape codes
1203
1194
"""
1204
- return strip_style (self .prompt )
1195
+ return su . strip_style (self .prompt )
1205
1196
1206
1197
def print_to (
1207
1198
self ,
@@ -1231,7 +1222,7 @@ def print_to(
1231
1222
method and still call `super()` without encountering unexpected keyword argument errors.
1232
1223
These arguments are not passed to Rich's Console.print().
1233
1224
"""
1234
- prepared_objects = rich_utils .prepare_objects_for_rich_print (* objects )
1225
+ prepared_objects = ru .prepare_objects_for_rich_print (* objects )
1235
1226
1236
1227
try :
1237
1228
Cmd2Console (file ).print (
@@ -1522,7 +1513,7 @@ def ppaged(
1522
1513
1523
1514
# Check if we are outputting to a pager.
1524
1515
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 )
1526
1517
1527
1518
# Chopping overrides soft_wrap
1528
1519
if chop :
@@ -1639,7 +1630,7 @@ def tokens_for_completion(self, line: str, begidx: int, endidx: int) -> tuple[li
1639
1630
raw_tokens = self .statement_parser .split_on_punctuation (initial_tokens )
1640
1631
1641
1632
# 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 ]
1643
1634
1644
1635
# If the token being completed had an unclosed quote, we need
1645
1636
# to remove the closing quote that was added in order for it
@@ -2141,7 +2132,7 @@ def _display_matches_gnu_readline(
2141
2132
longest_match_length = 0
2142
2133
2143
2134
for cur_match in matches_to_display :
2144
- cur_length = str_width (cur_match )
2135
+ cur_length = su . str_width (cur_match )
2145
2136
longest_match_length = max (longest_match_length , cur_length )
2146
2137
else :
2147
2138
matches_to_display = matches
@@ -3133,7 +3124,7 @@ def _redirect_output(self, statement: Statement) -> utils.RedirectionSavedState:
3133
3124
mode = 'a' if statement .output == constants .REDIRECTION_APPEND else 'w'
3134
3125
try :
3135
3126
# 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
3137
3128
except OSError as ex :
3138
3129
raise RedirectionError ('Failed to redirect output' ) from ex
3139
3130
@@ -4163,7 +4154,7 @@ def columnize(self, str_list: list[str] | None, display_width: int = 80) -> None
4163
4154
if i >= size :
4164
4155
break
4165
4156
x = str_list [i ]
4166
- colwidth = max (colwidth , str_width (x ))
4157
+ colwidth = max (colwidth , su . str_width (x ))
4167
4158
colwidths .append (colwidth )
4168
4159
totwidth += colwidth + 2
4169
4160
if totwidth > display_width :
@@ -4184,7 +4175,7 @@ def columnize(self, str_list: list[str] | None, display_width: int = 80) -> None
4184
4175
while texts and not texts [- 1 ]:
4185
4176
del texts [- 1 ]
4186
4177
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 ])
4188
4179
self .poutput (" " .join (texts ))
4189
4180
4190
4181
def _help_menu (self , verbose : bool = False ) -> None :
@@ -4480,7 +4471,7 @@ def do_set(self, args: argparse.Namespace) -> None:
4480
4471
# Try to update the settable's value
4481
4472
try :
4482
4473
orig_value = settable .get_value ()
4483
- settable .set_value (strip_quotes (args .value ))
4474
+ settable .set_value (su . strip_quotes (args .value ))
4484
4475
except ValueError as ex :
4485
4476
self .perror (f"Error setting { args .param } : { ex } " )
4486
4477
else :
@@ -5076,7 +5067,7 @@ def do_history(self, args: argparse.Namespace) -> bool | None:
5076
5067
self .run_editor (fname )
5077
5068
5078
5069
# 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 ))
5080
5071
finally :
5081
5072
os .remove (fname )
5082
5073
elif args .output_file :
@@ -5371,9 +5362,9 @@ def run_editor(self, file_path: str | None = None) -> None:
5371
5362
if not self .editor :
5372
5363
raise OSError ("Please use 'set editor' to specify your text editing program of choice." )
5373
5364
5374
- command = quote (os .path .expanduser (self .editor ))
5365
+ command = su . quote (os .path .expanduser (self .editor ))
5375
5366
if file_path :
5376
- command += " " + quote (os .path .expanduser (file_path ))
5367
+ command += " " + su . quote (os .path .expanduser (file_path ))
5377
5368
5378
5369
self .do_shell (command )
5379
5370
@@ -5511,7 +5502,7 @@ def do__relative_run_script(self, args: argparse.Namespace) -> bool | None:
5511
5502
relative_path = os .path .join (self ._current_script_dir or '' , script_path )
5512
5503
5513
5504
# 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 ))
5515
5506
5516
5507
def _run_transcript_tests (self , transcript_paths : list [str ]) -> None :
5517
5508
"""Run transcript tests for provided file(s).
@@ -5543,7 +5534,7 @@ class TestMyAppCase(Cmd2TestCase):
5543
5534
verinfo = "." .join (map (str , sys .version_info [:3 ]))
5544
5535
num_transcripts = len (transcripts_expanded )
5545
5536
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 ))
5547
5538
self .poutput (f'platform { sys .platform } -- Python { verinfo } , cmd2-{ cmd2 .__version__ } , readline-{ rl_type } ' )
5548
5539
self .poutput (f'cwd: { os .getcwd ()} ' )
5549
5540
self .poutput (f'cmd2 app: { sys .argv [0 ]} ' )
@@ -5560,7 +5551,7 @@ class TestMyAppCase(Cmd2TestCase):
5560
5551
if test_results .wasSuccessful ():
5561
5552
self .perror (stream .read (), end = "" , style = None )
5562
5553
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 )
5564
5555
self .psuccess (finish_msg )
5565
5556
else :
5566
5557
# 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: #
5624
5615
5625
5616
# Print a string which replaces the onscreen prompt and input lines with the alert.
5626
5617
terminal_str = async_alert_str (
5627
- terminal_columns = rich_utils .console_width (),
5618
+ terminal_columns = ru .console_width (),
5628
5619
prompt = rl_get_display_prompt (),
5629
5620
line = readline .get_line_buffer (),
5630
5621
cursor_offset = rl_get_point (),
0 commit comments