Skip to content

Commit 9db905e

Browse files
committed
Apply some more ruff SIM automated simplifications
1 parent a232620 commit 9db905e

19 files changed

+75
-168
lines changed

cmd2/argparse_completer.py

Lines changed: 2 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -88,9 +88,8 @@ def _looks_like_flag(token: str, parser: argparse.ArgumentParser) -> bool:
8888
return False
8989

9090
# If it looks like a negative number, it is not a flag unless there are negative-number-like flags
91-
if parser._negative_number_matcher.match(token):
92-
if not parser._has_negative_number_optionals:
93-
return False
91+
if parser._negative_number_matcher.match(token) and not parser._has_negative_number_optionals:
92+
return False
9493

9594
# Flags can't have a space
9695
if ' ' in token:

cmd2/argparse_custom.py

Lines changed: 2 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -1056,10 +1056,7 @@ def _format_usage(
10561056
def get_lines(parts: list[str], indent: str, prefix: Optional[str] = None) -> list[str]:
10571057
lines: list[str] = []
10581058
line: list[str] = []
1059-
if prefix is not None:
1060-
line_len = len(prefix) - 1
1061-
else:
1062-
line_len = len(indent) - 1
1059+
line_len = len(prefix) - 1 if prefix is not None else len(indent) - 1
10631060
for part in parts:
10641061
if line_len + 1 + len(part) > text_width and line:
10651062
lines.append(indent + ' '.join(line))
@@ -1172,10 +1169,7 @@ def _format_args(self, action: argparse.Action, default_metavar: Union[str, tupl
11721169
# Handle nargs specified as a range
11731170
nargs_range = action.get_nargs_range() # type: ignore[attr-defined]
11741171
if nargs_range is not None:
1175-
if nargs_range[1] == constants.INFINITY:
1176-
range_str = f'{nargs_range[0]}+'
1177-
else:
1178-
range_str = f'{nargs_range[0]}..{nargs_range[1]}'
1172+
range_str = f'{nargs_range[0]}+' if nargs_range[1] == constants.INFINITY else f'{nargs_range[0]}..{nargs_range[1]}'
11791173

11801174
return '{}{{{}}}'.format('%s' % metavar_formatter(1), range_str)
11811175

cmd2/cmd2.py

Lines changed: 16 additions & 43 deletions
Original file line numberDiff line numberDiff line change
@@ -50,6 +50,7 @@
5050
from collections.abc import Callable, Iterable, Mapping
5151
from contextlib import (
5252
redirect_stdout,
53+
suppress,
5354
)
5455
from types import (
5556
FrameType,
@@ -689,13 +690,13 @@ def register_command_set(self, cmdset: CommandSet) -> None:
689690
if self.always_prefix_settables:
690691
if not cmdset.settable_prefix.strip():
691692
raise CommandSetRegistrationError('CommandSet settable prefix must not be empty')
692-
for key in cmdset.settables.keys():
693+
for key in cmdset.settables:
693694
prefixed_name = f'{cmdset.settable_prefix}.{key}'
694695
if prefixed_name in all_settables:
695696
raise CommandSetRegistrationError(f'Duplicate settable: {key}')
696697

697698
else:
698-
for key in cmdset.settables.keys():
699+
for key in cmdset.settables:
699700
if key in all_settables:
700701
raise CommandSetRegistrationError(f'Duplicate settable {key} is already registered')
701702

@@ -1098,7 +1099,7 @@ def add_settable(self, settable: Settable) -> None:
10981099
:param settable: Settable object being added
10991100
"""
11001101
if not self.always_prefix_settables:
1101-
if settable.name in self.settables.keys() and settable.name not in self._settables.keys():
1102+
if settable.name in self.settables and settable.name not in self._settables:
11021103
raise KeyError(f'Duplicate settable: {settable.name}')
11031104
self._settables[settable.name] = settable
11041105

@@ -1594,10 +1595,7 @@ def index_based_complete(
15941595

15951596
# Check if token is at an index in the dictionary
15961597
match_against: Optional[Union[Iterable[str], CompleterFunc]]
1597-
if index in index_dict:
1598-
match_against = index_dict[index]
1599-
else:
1600-
match_against = all_else
1598+
match_against = index_dict.get(index, all_else)
16011599

16021600
# Perform tab completion using a Iterable
16031601
if isinstance(match_against, Iterable):
@@ -1739,10 +1737,7 @@ def complete_users() -> list[str]:
17391737

17401738
# Remove cwd if it was added to match the text readline expects
17411739
if cwd_added:
1742-
if cwd == os.path.sep:
1743-
to_replace = cwd
1744-
else:
1745-
to_replace = cwd + os.path.sep
1740+
to_replace = cwd if cwd == os.path.sep else cwd + os.path.sep
17461741
matches = [cur_path.replace(to_replace, '', 1) for cur_path in matches]
17471742

17481743
# Restore the tilde string if we expanded one to match the text readline expects
@@ -1962,10 +1957,7 @@ def _display_matches_pyreadline(self, matches: list[str]) -> None: # pragma: no
19621957
# Otherwise use pyreadline3's formatter
19631958
else:
19641959
# Check if we should show display_matches
1965-
if self.display_matches:
1966-
matches_to_display = self.display_matches
1967-
else:
1968-
matches_to_display = matches
1960+
matches_to_display = self.display_matches if self.display_matches else matches
19691961

19701962
# Add padding for visual appeal
19711963
matches_to_display, _ = self._pad_matches_to_display(matches_to_display)
@@ -2154,10 +2146,7 @@ def _perform_completion(
21542146

21552147
if add_quote:
21562148
# Figure out what kind of quote to add and save it as the unclosed_quote
2157-
if any('"' in match for match in self.completion_matches):
2158-
completion_token_quote = "'"
2159-
else:
2160-
completion_token_quote = '"'
2149+
completion_token_quote = "'" if any('"' in match for match in self.completion_matches) else '"'
21612150

21622151
self.completion_matches = [completion_token_quote + match for match in self.completion_matches]
21632152

@@ -2762,7 +2751,7 @@ def _input_line_to_statement(self, line: str, *, orig_rl_history_length: Optiona
27622751
orig_rl_history_length = None
27632752

27642753
# Check if this command matches a macro and wasn't already processed to avoid an infinite loop
2765-
if statement.command in self.macros.keys() and statement.command not in used_macros:
2754+
if statement.command in self.macros and statement.command not in used_macros:
27662755
used_macros.append(statement.command)
27672756
resolve_result = self._resolve_macro(statement)
27682757
if resolve_result is None:
@@ -2795,7 +2784,7 @@ def _resolve_macro(self, statement: Statement) -> Optional[str]:
27952784
:param statement: the parsed statement from the command line
27962785
:return: the resolved macro or None on error
27972786
"""
2798-
if statement.command not in self.macros.keys():
2787+
if statement.command not in self.macros:
27992788
raise KeyError(f"{statement.command} is not a macro")
28002789

28012790
macro = self.macros[statement.command]
@@ -2886,10 +2875,8 @@ def _redirect_output(self, statement: Statement) -> utils.RedirectionSavedState:
28862875
# like: !ls -l | grep user | wc -l > out.txt. But this makes it difficult to know if the pipe process
28872876
# started OK, since the shell itself always starts. Therefore, we will wait a short time and check
28882877
# if the pipe process is still running.
2889-
try:
2878+
with suppress(subprocess.TimeoutExpired):
28902879
proc.wait(0.2)
2891-
except subprocess.TimeoutExpired:
2892-
pass
28932880

28942881
# Check if the pipe process already exited
28952882
if proc.returncode is not None:
@@ -3462,10 +3449,7 @@ def _alias_list(self, args: argparse.Namespace) -> None:
34623449
tokens_to_quote = constants.REDIRECTION_TOKENS
34633450
tokens_to_quote.extend(self.statement_parser.terminators)
34643451

3465-
if args.names:
3466-
to_list = utils.remove_duplicates(args.names)
3467-
else:
3468-
to_list = sorted(self.aliases, key=self.default_sort_key)
3452+
to_list = utils.remove_duplicates(args.names) if args.names else sorted(self.aliases, key=self.default_sort_key)
34693453

34703454
not_found: list[str] = []
34713455
for name in to_list:
@@ -3697,10 +3681,7 @@ def _macro_list(self, args: argparse.Namespace) -> None:
36973681
tokens_to_quote = constants.REDIRECTION_TOKENS
36983682
tokens_to_quote.extend(self.statement_parser.terminators)
36993683

3700-
if args.names:
3701-
to_list = utils.remove_duplicates(args.names)
3702-
else:
3703-
to_list = sorted(self.macros, key=self.default_sort_key)
3684+
to_list = utils.remove_duplicates(args.names) if args.names else sorted(self.macros, key=self.default_sort_key)
37043685

37053686
not_found: list[str] = []
37063687
for name in to_list:
@@ -3865,10 +3846,7 @@ def columnize(self, str_list: Optional[list[str]], display_width: int = 80) -> N
38653846
texts = []
38663847
for col in range(ncols):
38673848
i = row + nrows * col
3868-
if i >= size:
3869-
x = ""
3870-
else:
3871-
x = str_list[i]
3849+
x = "" if i >= size else str_list[i]
38723850
texts.append(x)
38733851
while texts and not texts[-1]:
38743852
del texts[-1]
@@ -4267,10 +4245,8 @@ def _reset_py_display() -> None:
42674245
# Delete any prompts that have been set
42684246
attributes = ['ps1', 'ps2', 'ps3']
42694247
for cur_attr in attributes:
4270-
try:
4248+
with suppress(KeyError):
42714249
del sys.__dict__[cur_attr]
4272-
except KeyError:
4273-
pass
42744250

42754251
# Reset functions
42764252
sys.displayhook = sys.__displayhook__
@@ -4982,10 +4958,7 @@ def _generate_transcript(
49824958
self.perror(f"Error saving transcript file '{transcript_path}': {ex}")
49834959
else:
49844960
# and let the user know what we did
4985-
if commands_run == 1:
4986-
plural = 'command and its output'
4987-
else:
4988-
plural = 'commands and their outputs'
4961+
plural = 'command and its output' if commands_run == 1 else 'commands and their outputs'
49894962
self.pfeedback(f"{commands_run} {plural} saved to transcript file '{transcript_path}'")
49904963
self.last_result = True
49914964

cmd2/command_definition.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -156,11 +156,11 @@ def add_settable(self, settable: Settable) -> None:
156156
"""
157157
if self.__cmd_internal is not None:
158158
if not self._cmd.always_prefix_settables:
159-
if settable.name in self._cmd.settables.keys() and settable.name not in self._settables.keys():
159+
if settable.name in self._cmd.settables and settable.name not in self._settables:
160160
raise KeyError(f'Duplicate settable: {settable.name}')
161161
else:
162162
prefixed_name = f'{self._settable_prefix}.{settable.name}'
163-
if prefixed_name in self._cmd.settables.keys() and settable.name not in self._settables.keys():
163+
if prefixed_name in self._cmd.settables and settable.name not in self._settables:
164164
raise KeyError(f'Duplicate settable: {settable.name}')
165165
self._settables[settable.name] = settable
166166

cmd2/history.py

Lines changed: 1 addition & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -114,10 +114,7 @@ def pr(self, idx: int, script: bool = False, expanded: bool = False, verbose: bo
114114
if raw != expanded_command:
115115
ret_str += '\n' + self._ex_listformat.format(idx, expanded_command)
116116
else:
117-
if expanded:
118-
ret_str = self.expanded
119-
else:
120-
ret_str = single_line_format(self.statement).rstrip()
117+
ret_str = self.expanded if expanded else single_line_format(self.statement).rstrip()
121118

122119
# Display a numbered list if not writing to a script
123120
if not script:

cmd2/parsing.py

Lines changed: 5 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -353,10 +353,9 @@ def is_valid_command(self, word: str, *, is_subcommand: bool = False) -> tuple[b
353353
errmsg += ', '.join([shlex.quote(x) for x in errchars])
354354

355355
match = self._command_pattern.search(word)
356-
if match:
357-
if word == match.group(1):
358-
valid = True
359-
errmsg = ''
356+
if match and word == match.group(1):
357+
valid = True
358+
errmsg = ''
360359
return valid, errmsg
361360

362361
def tokenize(self, line: str) -> list[str]:
@@ -507,10 +506,7 @@ def parse(self, line: str) -> Statement:
507506
arg_list = tokens[1:]
508507

509508
# set multiline
510-
if command in self.multiline_commands:
511-
multiline_command = command
512-
else:
513-
multiline_command = ''
509+
multiline_command = command if command in self.multiline_commands else ''
514510

515511
# build the statement
516512
return Statement(
@@ -580,10 +576,7 @@ def parse_command_only(self, rawinput: str) -> Statement:
580576
args = ''
581577

582578
# set multiline
583-
if command in self.multiline_commands:
584-
multiline_command = command
585-
else:
586-
multiline_command = ''
579+
multiline_command = command if command in self.multiline_commands else ''
587580

588581
# build the statement
589582
return Statement(args, raw=rawinput, command=command, multiline_command=multiline_command)

cmd2/py_bridge.py

Lines changed: 6 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -124,13 +124,12 @@ def __call__(self, command: str, *, echo: Optional[bool] = None) -> CommandResul
124124
stop = False
125125
try:
126126
self._cmd2_app.stdout = cast(TextIO, copy_cmd_stdout)
127-
with redirect_stdout(cast(IO[str], copy_cmd_stdout)):
128-
with redirect_stderr(cast(IO[str], copy_stderr)):
129-
stop = self._cmd2_app.onecmd_plus_hooks(
130-
command,
131-
add_to_history=self._add_to_history,
132-
py_bridge_call=True,
133-
)
127+
with redirect_stdout(cast(IO[str], copy_cmd_stdout)), redirect_stderr(cast(IO[str], copy_stderr)):
128+
stop = self._cmd2_app.onecmd_plus_hooks(
129+
command,
130+
add_to_history=self._add_to_history,
131+
py_bridge_call=True,
132+
)
134133
finally:
135134
with self._cmd2_app.sigint_protection:
136135
self._cmd2_app.stdout = cast(IO[str], copy_cmd_stdout.inner_stream)

cmd2/rl_utils.py

Lines changed: 3 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -187,17 +187,11 @@ def rl_get_prompt() -> str: # pragma: no cover
187187
"""Get Readline's prompt."""
188188
if rl_type == RlType.GNU:
189189
encoded_prompt = ctypes.c_char_p.in_dll(readline_lib, "rl_prompt").value
190-
if encoded_prompt is None:
191-
prompt = ''
192-
else:
193-
prompt = encoded_prompt.decode(encoding='utf-8')
190+
prompt = '' if encoded_prompt is None else encoded_prompt.decode(encoding='utf-8')
194191

195192
elif rl_type == RlType.PYREADLINE:
196193
prompt_data: Union[str, bytes] = readline.rl.prompt
197-
if isinstance(prompt_data, bytes):
198-
prompt = prompt_data.decode(encoding='utf-8')
199-
else:
200-
prompt = prompt_data
194+
prompt = prompt_data.decode(encoding='utf-8') if isinstance(prompt_data, bytes) else prompt_data
201195

202196
else:
203197
prompt = ''
@@ -213,10 +207,7 @@ def rl_get_display_prompt() -> str: # pragma: no cover
213207
"""
214208
if rl_type == RlType.GNU:
215209
encoded_prompt = ctypes.c_char_p.in_dll(readline_lib, "rl_display_prompt").value
216-
if encoded_prompt is None:
217-
prompt = ''
218-
else:
219-
prompt = encoded_prompt.decode(encoding='utf-8')
210+
prompt = '' if encoded_prompt is None else encoded_prompt.decode(encoding='utf-8')
220211
return rl_unescape_prompt(prompt)
221212
return rl_get_prompt()
222213

cmd2/utils.py

Lines changed: 6 additions & 19 deletions
Original file line numberDiff line numberDiff line change
@@ -58,10 +58,7 @@ def is_quoted(arg: str) -> bool:
5858

5959
def quote_string(arg: str) -> str:
6060
"""Quote a string."""
61-
if '"' in arg:
62-
quote = "'"
63-
else:
64-
quote = '"'
61+
quote = "'" if '"' in arg else '"'
6562

6663
return quote + arg + quote
6764

@@ -360,10 +357,7 @@ def find_editor() -> Optional[str]:
360357

361358
# Get a list of every directory in the PATH environment variable and ignore symbolic links
362359
env_path = os.getenv('PATH')
363-
if env_path is None:
364-
paths = []
365-
else:
366-
paths = [p for p in env_path.split(os.path.pathsep) if not os.path.islink(p)]
360+
paths = [] if env_path is None else [p for p in env_path.split(os.path.pathsep) if not os.path.islink(p)]
367361

368362
for possible_editor, path in itertools.product(editors, paths):
369363
editor_path = os.path.join(path, possible_editor)
@@ -422,10 +416,7 @@ def get_exes_in_path(starts_with: str) -> list[str]:
422416

423417
# Get a list of every directory in the PATH environment variable and ignore symbolic links
424418
env_path = os.getenv('PATH')
425-
if env_path is None:
426-
paths = []
427-
else:
428-
paths = [p for p in env_path.split(os.path.pathsep) if not os.path.islink(p)]
419+
paths = [] if env_path is None else [p for p in env_path.split(os.path.pathsep) if not os.path.islink(p)]
429420

430421
# Use a set to store exe names since there can be duplicates
431422
exes_set = set()
@@ -558,9 +549,8 @@ def write(self, b: bytes) -> None:
558549
# and the bytes being written contain a new line character. This is helpful when StdSim
559550
# is being used to capture output of a shell command because it causes the output to print
560551
# to the screen more often than if we waited for the stream to flush its buffer.
561-
if self.std_sim_instance.line_buffering:
562-
if any(newline in b for newline in ByteBuf.NEWLINES):
563-
self.std_sim_instance.flush()
552+
if self.std_sim_instance.line_buffering and any(newline in b for newline in ByteBuf.NEWLINES):
553+
self.std_sim_instance.flush()
564554

565555

566556
class ProcReader:
@@ -862,10 +852,7 @@ def align_text(
862852
# fill characters. Instead of repeating the style characters for each fill character, we'll wrap each sequence.
863853
fill_char_style_begin, fill_char_style_end = fill_char.split(stripped_fill_char)
864854

865-
if text:
866-
lines = text.splitlines()
867-
else:
868-
lines = ['']
855+
lines = text.splitlines() if text else ['']
869856

870857
text_buf = io.StringIO()
871858

0 commit comments

Comments
 (0)