Skip to content

Commit b4f143c

Browse files
committed
Accept various automated refactorings from ruff RET ruleset that eliminated else case when the if had a return
1 parent 1733245 commit b4f143c

File tree

10 files changed

+79
-103
lines changed

10 files changed

+79
-103
lines changed

cmd2/argparse_custom.py

Lines changed: 18 additions & 21 deletions
Original file line numberDiff line numberDiff line change
@@ -477,7 +477,7 @@ def _action_set_choices_callable(self: argparse.Action, choices_callable: Choice
477477
if self.choices is not None:
478478
err_msg = "None of the following parameters can be used alongside a choices parameter:\nchoices_provider, completer"
479479
raise (TypeError(err_msg))
480-
elif self.nargs == 0:
480+
if self.nargs == 0:
481481
err_msg = (
482482
"None of the following parameters can be used on an action that takes no arguments:\nchoices_provider, completer"
483483
)
@@ -1155,24 +1155,22 @@ def _format_action_invocation(self, action: argparse.Action) -> str:
11551155
(metavar,) = self._metavar_formatter(action, default)(1)
11561156
return metavar
11571157

1158-
else:
1159-
parts: List[str] = []
1158+
parts: List[str] = []
11601159

1161-
# if the Optional doesn't take a value, format is:
1162-
# -s, --long
1163-
if action.nargs == 0:
1164-
parts.extend(action.option_strings)
1165-
return ', '.join(parts)
1160+
# if the Optional doesn't take a value, format is:
1161+
# -s, --long
1162+
if action.nargs == 0:
1163+
parts.extend(action.option_strings)
1164+
return ', '.join(parts)
11661165

1167-
# Begin cmd2 customization (less verbose)
1168-
# if the Optional takes a value, format is:
1169-
# -s, --long ARGS
1170-
else:
1171-
default = self._get_default_metavar_for_optional(action)
1172-
args_string = self._format_args(action, default)
1166+
# Begin cmd2 customization (less verbose)
1167+
# if the Optional takes a value, format is:
1168+
# -s, --long ARGS
1169+
default = self._get_default_metavar_for_optional(action)
1170+
args_string = self._format_args(action, default)
11731171

1174-
return ', '.join(action.option_strings) + ' ' + args_string
1175-
# End cmd2 customization
1172+
return ', '.join(action.option_strings) + ' ' + args_string
1173+
# End cmd2 customization
11761174

11771175
def _determine_metavar(
11781176
self,
@@ -1201,8 +1199,7 @@ def _metavar_formatter(
12011199
def format_tuple(tuple_size: int) -> Tuple[str, ...]:
12021200
if isinstance(metavar, tuple):
12031201
return metavar
1204-
else:
1205-
return (metavar,) * tuple_size
1202+
return (metavar,) * tuple_size
12061203

12071204
return format_tuple
12081205

@@ -1223,12 +1220,12 @@ def _format_args(self, action: argparse.Action, default_metavar: Union[str, Tupl
12231220

12241221
# Make this output less verbose. Do not customize the output when metavar is a
12251222
# tuple of strings. Allow argparse's formatter to handle that instead.
1226-
elif isinstance(metavar, str):
1223+
if isinstance(metavar, str):
12271224
if action.nargs == ZERO_OR_MORE:
12281225
return '[%s [...]]' % metavar_formatter(1)
1229-
elif action.nargs == ONE_OR_MORE:
1226+
if action.nargs == ONE_OR_MORE:
12301227
return '%s [...]' % metavar_formatter(1)
1231-
elif isinstance(action.nargs, int) and action.nargs > 1:
1228+
if isinstance(action.nargs, int) and action.nargs > 1:
12321229
return '{}{{{}}}'.format('%s' % metavar_formatter(1), action.nargs)
12331230

12341231
return super()._format_args(action, default_metavar) # type: ignore[arg-type]

cmd2/cmd2.py

Lines changed: 22 additions & 29 deletions
Original file line numberDiff line numberDiff line change
@@ -1728,12 +1728,11 @@ def complete_users() -> List[str]:
17281728
return complete_users()
17291729

17301730
# Otherwise expand the user dir
1731-
else:
1732-
search_str = os.path.expanduser(search_str)
1731+
search_str = os.path.expanduser(search_str)
17331732

1734-
# Get what we need to restore the original tilde path later
1735-
orig_tilde_path = text[:sep_index]
1736-
expanded_tilde_path = os.path.expanduser(orig_tilde_path)
1733+
# Get what we need to restore the original tilde path later
1734+
orig_tilde_path = text[:sep_index]
1735+
expanded_tilde_path = os.path.expanduser(orig_tilde_path)
17371736

17381737
# If the search text does not have a directory, then use the cwd
17391738
elif not os.path.dirname(text):
@@ -1804,10 +1803,9 @@ def shell_cmd_complete(self, text: str, line: str, begidx: int, endidx: int, *,
18041803
return utils.get_exes_in_path(text)
18051804

18061805
# Otherwise look for executables in the given path
1807-
else:
1808-
return self.path_complete(
1809-
text, line, begidx, endidx, path_filter=lambda path: os.path.isdir(path) or os.access(path, os.X_OK)
1810-
)
1806+
return self.path_complete(
1807+
text, line, begidx, endidx, path_filter=lambda path: os.path.isdir(path) or os.access(path, os.X_OK)
1808+
)
18111809

18121810
def _redirect_complete(self, text: str, line: str, begidx: int, endidx: int, compfunc: CompleterFunc) -> List[str]:
18131811
"""Called by complete() as the first tab completion function for all commands
@@ -1878,12 +1876,12 @@ def _redirect_complete(self, text: str, line: str, begidx: int, endidx: int, com
18781876
if do_shell_completion:
18791877
return self.shell_cmd_complete(text, line, begidx, endidx)
18801878

1881-
elif do_path_completion:
1879+
if do_path_completion:
18821880
return self.path_complete(text, line, begidx, endidx)
18831881

18841882
# If there were redirection strings anywhere on the command line, then we
18851883
# are no longer tab completing for the current command
1886-
elif has_redirection:
1884+
if has_redirection:
18871885
return []
18881886

18891887
# Call the command's completer function
@@ -2771,9 +2769,8 @@ def combine_rl_history(statement: Statement) -> None:
27712769

27722770
if not statement.command:
27732771
raise EmptyStatement
2774-
else:
2775-
# If necessary, update history with completed multiline command.
2776-
combine_rl_history(statement)
2772+
# If necessary, update history with completed multiline command.
2773+
combine_rl_history(statement)
27772774

27782775
return statement
27792776

@@ -2940,10 +2937,9 @@ def _redirect_output(self, statement: Statement) -> utils.RedirectionSavedState:
29402937
subproc_stdin.close()
29412938
new_stdout.close()
29422939
raise RedirectionError(f'Pipe process exited with code {proc.returncode} before command could run')
2943-
else:
2944-
redir_saved_state.redirecting = True # type: ignore[unreachable]
2945-
cmd_pipe_proc_reader = utils.ProcReader(proc, cast(TextIO, self.stdout), sys.stderr)
2946-
sys.stdout = self.stdout = new_stdout
2940+
redir_saved_state.redirecting = True # type: ignore[unreachable]
2941+
cmd_pipe_proc_reader = utils.ProcReader(proc, cast(TextIO, self.stdout), sys.stderr)
2942+
sys.stdout = self.stdout = new_stdout
29472943

29482944
elif statement.output:
29492945
if statement.output_to:
@@ -3080,14 +3076,13 @@ def default(self, statement: Statement) -> Optional[bool]: # type: ignore[overr
30803076
self.history.append(statement)
30813077

30823078
return self.do_shell(statement.command_and_args)
3083-
else:
3084-
err_msg = self.default_error.format(statement.command)
3085-
if self.suggest_similar_command and (suggested_command := self._suggest_similar_command(statement.command)):
3086-
err_msg += f"\n{self.default_suggestion_message.format(suggested_command)}"
3079+
err_msg = self.default_error.format(statement.command)
3080+
if self.suggest_similar_command and (suggested_command := self._suggest_similar_command(statement.command)):
3081+
err_msg += f"\n{self.default_suggestion_message.format(suggested_command)}"
30873082

3088-
# Set apply_style to False so styles for default_error and default_suggestion_message are not overridden
3089-
self.perror(err_msg, apply_style=False)
3090-
return None
3083+
# Set apply_style to False so styles for default_error and default_suggestion_message are not overridden
3084+
self.perror(err_msg, apply_style=False)
3085+
return None
30913086

30923087
def _suggest_similar_command(self, command: str) -> Optional[str]:
30933088
return suggest_similar(command, self.get_visible_commands())
@@ -5092,8 +5087,7 @@ def _current_script_dir(self) -> Optional[str]:
50925087
"""Accessor to get the current script directory from the _script_dir LIFO queue."""
50935088
if self._script_dir:
50945089
return self._script_dir[-1]
5095-
else:
5096-
return None
5090+
return None
50975091

50985092
run_script_description = (
50995093
"Run commands in script file that is encoded as either ASCII or UTF-8 text\n"
@@ -5748,5 +5742,4 @@ def _resolve_func_self(
57485742
# Case 3: There exists exactly 1 CommandSet that is a sub-class match of the function's CommandSet
57495743
func_self = candidate_sets[0]
57505744
return func_self
5751-
else:
5752-
return self
5745+
return self

cmd2/decorators.py

Lines changed: 2 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -195,8 +195,7 @@ def cmd_wrapper(*args: Any, **kwargs: Any) -> Optional[bool]:
195195

196196
if callable(func_arg):
197197
return arg_decorator(func_arg)
198-
else:
199-
return arg_decorator
198+
return arg_decorator
200199

201200

202201
def _set_parser_prog(parser: argparse.ArgumentParser, prog: str) -> None:
@@ -245,7 +244,7 @@ def _set_parser_prog(parser: argparse.ArgumentParser, prog: str) -> None:
245244
break
246245

247246
# Need to save required args so they can be prepended to the subcommand usage
248-
elif action.required:
247+
if action.required:
249248
req_args.append(action.dest)
250249

251250

cmd2/history.py

Lines changed: 2 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -211,10 +211,9 @@ def get(self, index: int) -> HistoryItem:
211211
"""
212212
if index == 0:
213213
raise IndexError('The first command in history is command 1.')
214-
elif index < 0:
214+
if index < 0:
215215
return self[index]
216-
else:
217-
return self[index - 1]
216+
return self[index - 1]
218217

219218
# This regular expression parses input for the span() method. There are five parts:
220219
#

cmd2/parsing.py

Lines changed: 1 addition & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -636,8 +636,7 @@ def get_command_arg_list(
636636

637637
if preserve_quotes:
638638
return to_parse, to_parse.arg_list
639-
else:
640-
return to_parse, to_parse.argv[1:]
639+
return to_parse, to_parse.argv[1:]
641640

642641
def _expand(self, line: str) -> str:
643642
"""Expand aliases and shortcuts"""

cmd2/py_bridge.py

Lines changed: 1 addition & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -78,8 +78,7 @@ def __bool__(self) -> bool:
7878
return bool(self.data)
7979

8080
# Otherwise check if stderr was filled out
81-
else:
82-
return not self.stderr
81+
return not self.stderr
8382

8483

8584
class PyBridge:

cmd2/rl_utils.py

Lines changed: 6 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -187,11 +187,10 @@ def rl_get_point() -> int: # pragma: no cover
187187
if rl_type == RlType.GNU:
188188
return ctypes.c_int.in_dll(readline_lib, "rl_point").value
189189

190-
elif rl_type == RlType.PYREADLINE:
190+
if rl_type == RlType.PYREADLINE:
191191
return int(readline.rl.mode.l_buffer.point)
192192

193-
else:
194-
return 0
193+
return 0
195194

196195

197196
def rl_get_prompt() -> str: # pragma: no cover
@@ -230,8 +229,7 @@ def rl_get_display_prompt() -> str: # pragma: no cover
230229
else:
231230
prompt = encoded_prompt.decode(encoding='utf-8')
232231
return rl_unescape_prompt(prompt)
233-
else:
234-
return rl_get_prompt()
232+
return rl_get_prompt()
235233

236234

237235
def rl_set_prompt(prompt: str) -> None: # pragma: no cover
@@ -278,8 +276,7 @@ def rl_escape_prompt(prompt: str) -> str:
278276

279277
return result
280278

281-
else:
282-
return prompt
279+
return prompt
283280

284281

285282
def rl_unescape_prompt(prompt: str) -> str:
@@ -302,7 +299,7 @@ def rl_in_search_mode() -> bool: # pragma: no cover
302299

303300
readline_state = ctypes.c_int.in_dll(readline_lib, "rl_readline_state").value
304301
return bool(IN_SEARCH_MODE & readline_state)
305-
elif rl_type == RlType.PYREADLINE:
302+
if rl_type == RlType.PYREADLINE:
306303
from pyreadline3.modes.emacs import ( # type: ignore[import]
307304
EmacsMode,
308305
)
@@ -317,5 +314,4 @@ def rl_in_search_mode() -> bool: # pragma: no cover
317314
readline.rl.mode._process_non_incremental_search_keyevent,
318315
)
319316
return readline.rl.mode.process_keyevent_queue[-1] in search_funcs
320-
else:
321-
return False
317+
return False

cmd2/table_creator.py

Lines changed: 3 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -98,8 +98,7 @@ def __init__(
9898

9999
if width is not None and width < 1:
100100
raise ValueError("Column width cannot be less than 1")
101-
else:
102-
self.width: int = width if width is not None else -1
101+
self.width: int = width if width is not None else -1
103102

104103
self.header_horiz_align = header_horiz_align
105104
self.header_vert_align = header_vert_align
@@ -1100,10 +1099,9 @@ def apply_data_bg(self, value: Any) -> str:
11001099
"""
11011100
if self.row_num % 2 == 0 and self.even_bg is not None:
11021101
return ansi.style(value, bg=self.even_bg)
1103-
elif self.row_num % 2 != 0 and self.odd_bg is not None:
1102+
if self.row_num % 2 != 0 and self.odd_bg is not None:
11041103
return ansi.style(value, bg=self.odd_bg)
1105-
else:
1106-
return str(value)
1104+
return str(value)
11071105

11081106
def generate_data_row(self, row_data: Sequence[Any]) -> str:
11091107
"""

cmd2/transcript.py

Lines changed: 19 additions & 20 deletions
Original file line numberDiff line numberDiff line change
@@ -162,25 +162,24 @@ def _transform_transcript_expected(self, s: str) -> str:
162162
# no more slashes, add the rest of the string and bail
163163
regex += re.escape(s[start:])
164164
break
165+
# there is a slash, add everything we have found so far
166+
# add stuff before the first slash as plain text
167+
regex += re.escape(s[start:first_slash_pos])
168+
start = first_slash_pos + 1
169+
# and go find the next one
170+
(regex, second_slash_pos, start) = self._escaped_find(regex, s, start, True)
171+
if second_slash_pos > 0:
172+
# add everything between the slashes (but not the slashes)
173+
# as a regular expression
174+
regex += s[start:second_slash_pos]
175+
# and change where we start looking for slashed on the
176+
# turn through the loop
177+
start = second_slash_pos + 1
165178
else:
166-
# there is a slash, add everything we have found so far
167-
# add stuff before the first slash as plain text
168-
regex += re.escape(s[start:first_slash_pos])
169-
start = first_slash_pos + 1
170-
# and go find the next one
171-
(regex, second_slash_pos, start) = self._escaped_find(regex, s, start, True)
172-
if second_slash_pos > 0:
173-
# add everything between the slashes (but not the slashes)
174-
# as a regular expression
175-
regex += s[start:second_slash_pos]
176-
# and change where we start looking for slashed on the
177-
# turn through the loop
178-
start = second_slash_pos + 1
179-
else:
180-
# No closing slash, we have to add the first slash,
181-
# and the rest of the text
182-
regex += re.escape(s[start - 1 :])
183-
break
179+
# No closing slash, we have to add the first slash,
180+
# and the rest of the text
181+
regex += re.escape(s[start - 1 :])
182+
break
184183
return regex
185184

186185
@staticmethod
@@ -200,12 +199,12 @@ def _escaped_find(regex: str, s: str, start: int, in_regex: bool) -> Tuple[str,
200199
if pos == -1:
201200
# no match, return to caller
202201
break
203-
elif pos == 0:
202+
if pos == 0:
204203
# slash at the beginning of the string, so it can't be
205204
# escaped. We found it.
206205
break
207206
# check if the slash is preceded by a backslash
208-
elif s[pos - 1 : pos] == '\\':
207+
if s[pos - 1 : pos] == '\\':
209208
# it is.
210209
if in_regex:
211210
# add everything up to the backslash as a

0 commit comments

Comments
 (0)