Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add more ruff rules #406

Merged
merged 4 commits into from
Feb 25, 2024
Merged
Show file tree
Hide file tree
Changes from 3 commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
29 changes: 17 additions & 12 deletions pyproject.toml
Original file line number Diff line number Diff line change
Expand Up @@ -62,18 +62,23 @@ unfixable = [
"ERA", # do not autoremove commented out code
]
extend-select = [
"B", # flake8-bugbear
"C4", # flake8-comprehensions
"ERA", # flake8-eradicate/eradicate
"I", # isort
"N", # pep8-naming
"PIE", # flake8-pie
"PGH", # pygrep
"RUF", # ruff checks
"SIM", # flake8-simplify
"TCH", # flake8-type-checking
"TID", # flake8-tidy-imports
"UP", # pyupgrade
"B", # flake8-bugbear
"C4", # flake8-comprehensions
"ERA", # flake8-eradicate/eradicate
"I", # isort
"N", # pep8-naming
"PIE", # flake8-pie
"PGH", # pygrep
"PTH", # flake8-use-pathlib
"ISC", # flake8-implicit-string-concat
"RET", # flake8-return
"FLY", # flynt
"PERF", # perflint
"RUF", # ruff checks
"SIM", # flake8-simplify
"TCH", # flake8-type-checking
"TID", # flake8-tidy-imports
"UP", # pyupgrade
]

[tool.ruff.lint.flake8-tidy-imports]
Expand Down
6 changes: 2 additions & 4 deletions src/cleo/color.py
Original file line number Diff line number Diff line change
Expand Up @@ -69,8 +69,7 @@ def set(self) -> str:
if self._background:
codes.append(self._background)

for option in self._options.values():
codes.append(str(option["set"]))
codes.extend(str(option["set"]) for option in self._options.values())

if not codes:
return ""
Expand All @@ -86,8 +85,7 @@ def unset(self) -> str:
if self._background:
codes.append("49")

for option in self._options.values():
codes.append(str(option["unset"]))
codes.extend(str(option["unset"]) for option in self._options.values())

if not codes:
return ""
Expand Down
3 changes: 1 addition & 2 deletions src/cleo/descriptors/text_descriptor.py
Original file line number Diff line number Diff line change
Expand Up @@ -261,8 +261,7 @@ def _get_column_width(self, commands: Sequence[Command | str]) -> int:
if isinstance(command, Command):
assert command.name is not None
widths.append(len(command.name))
for alias in command.aliases:
widths.append(len(alias))
widths.extend(len(alias) for alias in command.aliases)
else:
widths.append(len(command))

Expand Down
10 changes: 5 additions & 5 deletions src/cleo/io/inputs/input.py
Original file line number Diff line number Diff line change
Expand Up @@ -100,11 +100,11 @@ def bind(self, definition: Definition) -> None:
self._parse()

def validate(self) -> None:
missing_arguments = []

for argument in self._definition.arguments:
if argument.name not in self._arguments and argument.is_required():
missing_arguments.append(argument.name)
missing_arguments = [
argument.name
for argument in self._definition.arguments
if argument.name not in self._arguments and argument.is_required()
]

if missing_arguments:
raise CleoMissingArgumentsError(
Expand Down
3 changes: 2 additions & 1 deletion src/cleo/io/outputs/section_output.py
Original file line number Diff line number Diff line change
Expand Up @@ -76,7 +76,8 @@ def add_content(self, content: str) -> None:

def _write(self, message: str, new_line: bool = False) -> None:
if not self.is_decorated():
return super()._write(message, new_line=new_line)
super()._write(message, new_line=new_line)
return

erased_content = self._pop_stream_content_until_current_section()

Expand Down
20 changes: 9 additions & 11 deletions src/cleo/ui/exception_trace/component.py
Original file line number Diff line number Diff line change
Expand Up @@ -325,15 +325,13 @@ def _render_trace(self, io: IO | Output, frames: FrameCollection) -> None:
i -= len(collection) * (collection.repetitions + 1)

for frame in collection:
relative_file_path = self._get_relative_file_path(frame.filename)
relative_file_path_parts = relative_file_path.split(os.sep)
relative_file_path = (
f"<fg=default;options=dark>{Formatter.escape(os.sep)}</>".join(
relative_file_path_parts[:-1]
+ [
"<fg=default;options=bold>"
f"{relative_file_path_parts[-1]}</>"
]
relative_file_path_parts = self._get_relative_file_path(
frame.filename
).parts
relative_file_path = f"<fg=default;options=dark>{Formatter.escape(os.sep)}</>".join(
(
*relative_file_path_parts[:-1],
f"<fg=default;options=bold>{relative_file_path_parts[-1]}</>",
)
)
self._render_line(
Expand Down Expand Up @@ -388,11 +386,11 @@ def _render_line(
io.write_line(f"{indent * ' '}{line}")

@staticmethod
def _get_relative_file_path(filepath: str) -> str:
def _get_relative_file_path(filepath: str) -> Path:
if cwd := Path.cwd():
filepath = filepath.replace(f"{cwd}{os.sep}", "")

if home := Path("~").expanduser():
filepath = filepath.replace(f"{home}{os.sep}", f"~{os.sep}")

return filepath
return Path(filepath)
2 changes: 1 addition & 1 deletion src/cleo/ui/progress_bar.py
Original file line number Diff line number Diff line change
Expand Up @@ -40,7 +40,7 @@ class ProgressBar(Component):
"verbose": " %current%/%max% [%bar%] %percent:3s%% %elapsed:-6s%",
"verbose_nomax": " %current% [%bar%] %elapsed:6s%",
"very_verbose": (
" %current%/%max% [%bar%] %percent:3s%%" " %elapsed:6s%/%estimated:-6s%"
" %current%/%max% [%bar%] %percent:3s%% %elapsed:6s%/%estimated:-6s%"
),
"very_verbose_nomax": " %current% [%bar%] %elapsed:6s%",
"debug": " %current%/%max% [%bar%] %percent:3s%% %elapsed:6s%/%estimated:-6s%",
Expand Down
2 changes: 1 addition & 1 deletion src/cleo/ui/progress_indicator.py
Original file line number Diff line number Diff line change
Expand Up @@ -190,7 +190,7 @@ def _determine_best_format(self) -> str:
return self.VERY_VERBOSE

return self.VERY_VERBOSE_NO_ANSI
elif self._io.is_verbose():
if self._io.is_verbose():
if decorated:
return self.VERY_VERBOSE

Expand Down
4 changes: 2 additions & 2 deletions src/cleo/ui/table.py
Original file line number Diff line number Diff line change
Expand Up @@ -526,7 +526,7 @@ def _fill_next_rows(self, rows: Rows, line: int) -> Rows:

unmerged_rows = placeholder

for unmerged_row_key, _ in unmerged_rows.items():
for unmerged_row_key in unmerged_rows:
value = ""
if unmerged_row_key - line < len(lines):
value = lines[unmerged_row_key - line]
Expand Down Expand Up @@ -650,7 +650,7 @@ def _calculate_column_widths(self, rows: Rows) -> None:
for position, content in enumerate(content_columns):
try:
row_[i + position] = content
except IndexError:
except IndexError: # noqa: PERF203
row_.append(content)

lengths.append(self._get_cell_width(row_, column))
Expand Down
19 changes: 6 additions & 13 deletions tests/commands/completion/test_completions_command.py
Original file line number Diff line number Diff line change
@@ -1,7 +1,6 @@
from __future__ import annotations

import os

from pathlib import Path
from typing import TYPE_CHECKING

import pytest
Expand All @@ -17,6 +16,8 @@
if TYPE_CHECKING:
from pytest_mock import MockerFixture

FIXTURES_PATH = Path(__file__).parent / "fixtures"


app = Application()
app.add(HelloCommand())
Expand Down Expand Up @@ -48,10 +49,7 @@ def test_bash(mocker: MockerFixture) -> None:
tester = CommandTester(command)
tester.execute("bash")

with open(
os.path.join(os.path.dirname(__file__), "fixtures", "bash.txt"),
encoding="utf-8",
) as f:
with (FIXTURES_PATH / "bash.txt").open(encoding="utf-8") as f:
expected = f.read()

assert expected == tester.io.fetch_output().replace("\r\n", "\n")
Expand All @@ -73,9 +71,7 @@ def test_zsh(mocker: MockerFixture) -> None:
tester = CommandTester(command)
tester.execute("zsh")

with open(
os.path.join(os.path.dirname(__file__), "fixtures", "zsh.txt"), encoding="utf-8"
) as f:
with (FIXTURES_PATH / "zsh.txt").open(encoding="utf-8") as f:
expected = f.read()

assert expected == tester.io.fetch_output().replace("\r\n", "\n")
Expand All @@ -97,10 +93,7 @@ def test_fish(mocker: MockerFixture) -> None:
tester = CommandTester(command)
tester.execute("fish")

with open(
os.path.join(os.path.dirname(__file__), "fixtures", "fish.txt"),
encoding="utf-8",
) as f:
with (FIXTURES_PATH / "fish.txt").open(encoding="utf-8") as f:
expected = f.read()

assert expected == tester.io.fetch_output().replace("\r\n", "\n")
11 changes: 5 additions & 6 deletions tests/ui/exception_trace/test_frame.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,8 @@

import inspect

from pathlib import Path

from cleo.ui.exception_trace.frame import Frame
from tests.ui.exception_trace.helpers import nested_exception
from tests.ui.exception_trace.helpers import simple_exception
Expand All @@ -17,15 +19,12 @@ def test_frame() -> None:
same_frame = Frame(frame_info)
assert frame_info.frame == frame.frame

assert frame.lineno == 12
assert frame.lineno == 14
assert frame.filename == __file__
assert frame.function == "test_frame"
assert frame.line == " simple_exception()\n"

with open(__file__, encoding="utf-8") as f:
assert f.read() == frame.file_content

assert repr(frame) == f"<Frame {__file__}, test_frame, 12>"
assert Path(__file__).read_text(encoding="utf-8") == frame.file_content
assert repr(frame) == f"<Frame {__file__}, test_frame, 14>"

try:
nested_exception()
Expand Down
6 changes: 3 additions & 3 deletions tests/ui/test_exception_trace.py
Original file line number Diff line number Diff line change
Expand Up @@ -90,7 +90,7 @@ def test_render_debug_better_error_message_recursion_error() -> None:
expected = rf"""^
Stack trace:

\d+ {re.escape(trace._get_relative_file_path(__file__))}:{lineno} in test_render_debug_better_error_message_recursion_error
\d+ {re.escape(str(trace._get_relative_file_path(__file__)))}:{lineno} in test_render_debug_better_error_message_recursion_error
{lineno - 2}\│
{lineno - 1}\│ try:
→ {lineno + 0}\│ recursion.recursion_error\(\)
Expand All @@ -99,7 +99,7 @@ def test_render_debug_better_error_message_recursion_error() -> None:

... Previous frame repeated \d+ times

\s*\d+ {re.escape(trace._get_relative_file_path(recursion.__file__))}:2 in recursion_error
\s*\d+ {re.escape(str(trace._get_relative_file_path(recursion.__file__)))}:2 in recursion_error
1\│ def recursion_error\(\) -> None:
→ 2\│ recursion_error\(\)
3\│
Expand All @@ -108,7 +108,7 @@ def test_render_debug_better_error_message_recursion_error() -> None:

maximum recursion depth exceeded

at {re.escape(trace._get_relative_file_path(recursion.__file__))}:2 in recursion_error
at {re.escape(str(trace._get_relative_file_path(recursion.__file__)))}:2 in recursion_error
1\│ def recursion_error\(\) -> None:
→ 2\│ recursion_error\(\)
3\│
Expand Down
30 changes: 15 additions & 15 deletions tests/ui/test_progress_bar.py
Original file line number Diff line number Diff line change
Expand Up @@ -326,21 +326,21 @@ def test_non_decorated_output(io: BufferedIO) -> None:

bar.finish()

expected = "\n".join(
[
" 0/200 [>---------------------------] 0%",
" 20/200 [==>-------------------------] 10%",
" 40/200 [=====>----------------------] 20%",
" 60/200 [========>-------------------] 30%",
" 80/200 [===========>----------------] 40%",
" 100/200 [==============>-------------] 50%",
" 120/200 [================>-----------] 60%",
" 140/200 [===================>--------] 70%",
" 160/200 [======================>-----] 80%",
" 180/200 [=========================>--] 90%",
" 200/200 [============================] 100%",
]
)
output = [
" 0/200 [>---------------------------] 0%",
" 20/200 [==>-------------------------] 10%",
" 40/200 [=====>----------------------] 20%",
" 60/200 [========>-------------------] 30%",
" 80/200 [===========>----------------] 40%",
" 100/200 [==============>-------------] 50%",
" 120/200 [================>-----------] 60%",
" 140/200 [===================>--------] 70%",
" 160/200 [======================>-----] 80%",
" 180/200 [=========================>--] 90%",
" 200/200 [============================] 100%",
]

expected = "\n".join(output)

assert expected == io.fetch_error()

Expand Down
3 changes: 2 additions & 1 deletion tests/ui/test_question.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@
import os
import subprocess

from pathlib import Path
from typing import TYPE_CHECKING

import pytest
Expand All @@ -15,7 +16,7 @@


def has_tty_available() -> bool:
with open(os.devnull, "w", encoding="utf-8") as devnull:
with Path(os.devnull).open("w", encoding="utf-8") as devnull:
exit_code = subprocess.call(["stty", "2"], stdout=devnull, stderr=devnull)

return exit_code == 0
Expand Down