Skip to content

Commit

Permalink
Logic improvements (#345)
Browse files Browse the repository at this point in the history
  • Loading branch information
trag1c authored Aug 6, 2023
1 parent 9a7916f commit 0b62843
Show file tree
Hide file tree
Showing 16 changed files with 34 additions and 49 deletions.
5 changes: 1 addition & 4 deletions src/cleo/application.py
Original file line number Diff line number Diff line change
Expand Up @@ -631,10 +631,7 @@ def _extract_all_namespaces(self, name: str) -> list[str]:
namespaces: list[str] = []

for part in parts:
if namespaces:
namespaces.append(namespaces[-1] + " " + part)
else:
namespaces.append(part)
namespaces.append(namespaces[-1] + " " + part if namespaces else part)

return namespaces

Expand Down
5 changes: 1 addition & 4 deletions src/cleo/color.py
Original file line number Diff line number Diff line change
Expand Up @@ -47,11 +47,8 @@ def __init__(
self._foreground = self._parse_color(foreground, False)
self._background = self._parse_color(background, True)

if options is None:
options = []

self._options = {}
for option in options:
for option in options or []:
if option not in self.AVAILABLE_OPTIONS:
raise ValueError(
f'"{option}" is not a valid color option. '
Expand Down
6 changes: 3 additions & 3 deletions src/cleo/descriptors/text_descriptor.py
Original file line number Diff line number Diff line change
Expand Up @@ -199,9 +199,9 @@ def _describe_application(self, application: Application, **options: Any) -> Non
if not namespace["commands"]:
continue

if (
not described_namespace
and namespace["id"] != ApplicationDescription.GLOBAL_NAMESPACE
if not (
described_namespace
or namespace["id"] == ApplicationDescription.GLOBAL_NAMESPACE
):
self._write("\n")
self._write(f" <comment>{namespace['id']}</comment>")
Expand Down
2 changes: 1 addition & 1 deletion src/cleo/events/event_dispatcher.py
Original file line number Diff line number Diff line change
Expand Up @@ -61,7 +61,7 @@ def has_listeners(self, event_name: str | None = None) -> bool:
if event_name not in self._listeners:
return False

return len(self._listeners[event_name]) > 0
return bool(self._listeners[event_name])

return any(self._listeners.values())

Expand Down
2 changes: 1 addition & 1 deletion src/cleo/formatters/formatter.py
Original file line number Diff line number Diff line change
Expand Up @@ -105,7 +105,7 @@ def format_and_wrap(self, message: str, width: int) -> str:
if tag:
style = self._create_style_from_string(tag)

if not open and not tag:
if not (open or tag):
# </>
self._style_stack.pop()
elif style is None:
Expand Down
4 changes: 2 additions & 2 deletions src/cleo/io/inputs/argv_input.py
Original file line number Diff line number Diff line change
Expand Up @@ -114,7 +114,7 @@ def parameter_option(
values = [values]

tokens = self._tokens[:]
while len(tokens) > 0:
while tokens:
token = tokens.pop(0)
if only_params and token == "--":
return default
Expand Down Expand Up @@ -265,7 +265,7 @@ def _add_long_option(self, name: str, value: Any) -> None:

option = self._definition.option(name)

if value is not None and not option.accepts_value():
if not (value is None or option.accepts_value()):
raise CleoRuntimeError(f'The "--{name}" option does not accept a value')

if value in ["", None] and option.accepts_value() and self._parsed:
Expand Down
5 changes: 1 addition & 4 deletions src/cleo/io/inputs/definition.py
Original file line number Diff line number Diff line change
Expand Up @@ -27,10 +27,7 @@ def __init__(self, definition: Sequence[Argument | Option] | None = None) -> Non
self._options: dict[str, Option] = {}
self._shortcuts: dict[str, str] = {}

if definition is None:
definition = []

self.set_definition(definition)
self.set_definition(definition or [])

@property
def arguments(self) -> list[Argument]:
Expand Down
3 changes: 1 addition & 2 deletions src/cleo/io/inputs/token_parser.py
Original file line number Diff line number Diff line change
Expand Up @@ -37,8 +37,7 @@ def _parse(self) -> list[str]:

continue

if self._current is not None:
tokens.append(self._parse_token())
tokens.append(self._parse_token())

return tokens

Expand Down
13 changes: 6 additions & 7 deletions src/cleo/io/outputs/stream_output.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@

from typing import TYPE_CHECKING
from typing import TextIO
from typing import cast

from cleo.io.outputs.output import Output
from cleo.io.outputs.output import Verbosity
Expand Down Expand Up @@ -52,11 +53,9 @@ def _get_utf8_support_info(self) -> bool:
encoding = self._stream.encoding or locale.getpreferredencoding(False)

try:
encoding = codecs.lookup(encoding).name
return codecs.lookup(encoding).name == "utf-8"
except Exception:
encoding = "utf-8"

return encoding == "utf-8"
return True

def flush(self) -> None:
self._stream.flush()
Expand Down Expand Up @@ -138,13 +137,13 @@ def _has_color_support(self) -> bool:
if (mode.value & self.ENABLE_VIRTUAL_TERMINAL_PROCESSING) != 0:
return True

result: bool = (
return cast(
bool,
kernel32.SetConsoleMode(
h, mode.value | self.ENABLE_VIRTUAL_TERMINAL_PROCESSING
)
!= 0
!= 0,
)
return result

if not hasattr(self._stream, "fileno"):
return False
Expand Down
4 changes: 2 additions & 2 deletions src/cleo/terminal.py
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,7 @@ def __init__(
) -> None:
self._width = width
self._height = height
self._fallback = TerminalSize(*(fallback if fallback is not None else (80, 25)))
self._fallback = TerminalSize(*(fallback or (80, 25)))

@property
def width(self) -> int:
Expand All @@ -35,7 +35,7 @@ def size(self) -> TerminalSize:
return self._get_terminal_size()

def _get_terminal_size(self) -> TerminalSize:
if self._width is not None and self._height is not None:
if not (self._width is None or self._height is None):
return TerminalSize(self._width, self._height)

width = 0
Expand Down
2 changes: 1 addition & 1 deletion src/cleo/ui/confirmation_question.py
Original file line number Diff line number Diff line change
Expand Up @@ -41,6 +41,6 @@ def _default_normalizer(self, answer: str) -> bool:

answer_is_true = re.match(self._true_answer_regex, answer) is not None
if self.default is False:
return (answer and answer_is_true) or False
return bool(answer and answer_is_true)

return not answer or answer_is_true
12 changes: 5 additions & 7 deletions src/cleo/ui/progress_bar.py
Original file line number Diff line number Diff line change
Expand Up @@ -366,13 +366,11 @@ def _determine_best_format(self) -> str:
def bar_offset(self) -> int:
if self._max:
return math.floor(self._percent * self.bar_width)
else:
if self.redraw_freq is None:
return math.floor(
(min(5, self.bar_width // 15) * self._write_count) % self.bar_width
)

return math.floor(self._step % self.bar_width)
if self.redraw_freq is None:
return math.floor(
(min(5, self.bar_width // 15) * self._write_count) % self.bar_width
)
return math.floor(self._step % self.bar_width)

def _formatter_bar(self) -> str:
complete_bars = self.bar_offset
Expand Down
4 changes: 2 additions & 2 deletions src/cleo/ui/progress_indicator.py
Original file line number Diff line number Diff line change
Expand Up @@ -115,7 +115,7 @@ def finish(self, message: str, reset_indicator: bool = False) -> None:
if not self._started:
raise RuntimeError("Progress indicator has not yet been started.")

if self._auto_thread is not None and self._auto_running is not None:
if not (self._auto_thread is None or self._auto_running is None):
self._auto_running.set()
self._auto_thread.join()

Expand Down Expand Up @@ -152,7 +152,7 @@ def auto(self, start_message: str, end_message: str) -> Iterator[ProgressIndicat
self.finish(end_message, reset_indicator=True)

def _spin(self) -> None:
while self._auto_running is not None and not self._auto_running.is_set():
while not (self._auto_running is None or self._auto_running.is_set()):
self.advance()

time.sleep(0.1)
Expand Down
2 changes: 1 addition & 1 deletion src/cleo/ui/question.py
Original file line number Diff line number Diff line change
Expand Up @@ -87,7 +87,7 @@ def _do_ask(self, io: IO) -> Any:
"""
self._write_prompt(io)

if not self._autocomplete_values or not self._has_stty_available():
if not (self._autocomplete_values and self._has_stty_available()):
ret: str | None = None

if self.is_hidden():
Expand Down
9 changes: 5 additions & 4 deletions src/cleo/ui/table.py
Original file line number Diff line number Diff line change
Expand Up @@ -335,10 +335,11 @@ def _render_row(
columns = self._get_row_columns(row)
last = len(columns) - 1
for i, column in enumerate(columns):
if first_cell_format and i == 0:
row_content += self._render_cell(row, column, first_cell_format)
else:
row_content += self._render_cell(row, column, cell_format)
row_content += self._render_cell(
row,
column,
first_cell_format if first_cell_format and i == 0 else cell_format,
)

row_content += self._render_column_separator(
self.BORDER_OUTSIDE if i == last else self.BORDER_INSIDE
Expand Down
5 changes: 1 addition & 4 deletions src/cleo/ui/ui.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,10 +8,7 @@ class UI:
def __init__(self, components: list[Component] | None = None) -> None:
self._components: dict[str, Component] = {}

if components is None:
components = []

for component in components:
for component in components or []:
self.register(component)

def register(self, component: Component) -> None:
Expand Down

0 comments on commit 0b62843

Please sign in to comment.