Skip to content

Commit

Permalink
Switch to Ruff formatting (#259)
Browse files Browse the repository at this point in the history
  • Loading branch information
Avasam authored Aug 18, 2024
1 parent 2ea4c28 commit 8c2949b
Show file tree
Hide file tree
Showing 24 changed files with 225 additions and 273 deletions.
9 changes: 1 addition & 8 deletions .pre-commit-config.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -23,14 +23,7 @@ repos:
hooks:
- id: ruff
args: [--fix]
- repo: https://github.com/hhatto/autopep8
rev: v2.3.1 # Must match requirements-dev.txt
hooks:
- id: autopep8
- repo: https://github.com/asottile/add-trailing-comma
rev: v3.1.0 # Must match requirements-dev.txt
hooks:
- id: add-trailing-comma
- id: ruff-format

ci:
autoupdate_branch: dev
Expand Down
7 changes: 3 additions & 4 deletions .vscode/extensions.json
Original file line number Diff line number Diff line change
@@ -1,11 +1,10 @@
// Keep in alphabetical order
{
"recommendations": [
"charliermarsh.ruff",
"davidanson.vscode-markdownlint",
"eamodio.gitlens",
"emeraldwalk.runonsave",
"github.vscode-github-actions",
"ms-python.autopep8",
"ms-python.python",
"ms-python.vscode-pylance",
"ms-vscode.powershell",
Expand All @@ -32,11 +31,11 @@
// Don't recommend to autoinstall //
//
// Use Ruff instead
"ms-python.autopep8",
"ms-python.black-formatter",
"ms-python.flake8",
"ms-python.isort",
"ms-python.pylint",
// We use autopep8
"ms-python.black-formatter",
// This is a Git project
"johnstoncode.svn-scm",
// Prefer using VSCode itself as a text editor
Expand Down
14 changes: 4 additions & 10 deletions .vscode/settings.json
Original file line number Diff line number Diff line change
Expand Up @@ -25,14 +25,6 @@
// Let dedicated linter (Ruff) organize imports
"source.organizeImports": "never"
},
"emeraldwalk.runonsave": {
"commands": [
{
"match": "\\.pyi?",
"cmd": "add-trailing-comma ${file}"
},
]
},
"files.associations": {
".flake8": "properties",
"*.qrc": "xml",
Expand Down Expand Up @@ -67,8 +59,7 @@
},
"yaml.format.printWidth": 100,
"[python]": {
// Ruff as a formatter doesn't fully satisfy our needs yet: https://github.com/astral-sh/ruff/discussions/7310
"editor.defaultFormatter": "ms-python.autopep8",
"editor.defaultFormatter": "charliermarsh.ruff",
"editor.tabSize": 4,
"editor.rulers": [
72, // PEP8-17 docstrings
Expand All @@ -91,6 +82,9 @@
],
"python.analysis.diagnosticMode": "workspace",
"ruff.importStrategy": "fromEnvironment",
"ruff.enable": true,
"ruff.fixAll": true,
"ruff.organizeImports": true,
// Use the Ruff extension instead
"isort.check": false,
"powershell.codeFormatting.pipelineIndentationStyle": "IncreaseIndentationForFirstPipeline",
Expand Down
2 changes: 1 addition & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@

[![SemVer](https://badgen.net/badge/_/SemVer%20compliant/grey?label)](https://semver.org/)
[![Ruff](https://img.shields.io/endpoint?url=https://raw.githubusercontent.com/astral-sh/ruff/main/assets/badge/v2.json)](https://github.com/astral-sh/ruff)
[![autopep8](https://badgen.net/badge/code%20style/autopep8/blue)](https://github.com/hhatto/autopep8)
[![Ruff format](https://raw.githubusercontent.com/astral-sh/ruff/main/assets/badge/format.json)](https://docs.astral.sh/ruff/settings/#format)
[![Checked with pyright](https://microsoft.github.io/pyright/img/pyright_badge.svg)](https://microsoft.github.io/pyright/)
[![Checked with mypy](https://www.mypy-lang.org/static/mypy_badge.svg)](https://mypy-lang.org/)

Expand Down
24 changes: 0 additions & 24 deletions pyproject.toml
Original file line number Diff line number Diff line change
@@ -1,27 +1,3 @@
# https://github.com/hhatto/autopep8#usage
# https://github.com/hhatto/autopep8#more-advanced-usage
[tool.autopep8]
max_line_length = 100
aggressive = 3
exclude = ".venv/*,src/gen/*"
ignore = [
"E124", # Closing bracket may not match multi-line method invocation style (enforced by add-trailing-comma)
"E70", # Allow ... on same line as def
"E721", # Breaks when needing an exact type
# Autofixed by Ruff
# Check for the "Fix" flag https://docs.astral.sh/ruff/rules/#pycodestyle-e-w
"E2", # Whitespace
"E3", # Blank lines
"E703", # useless-semicolon
"E71", # Statement (comparisons)
"E731", # lambda-assignment
"W29", # Whitespace warning
"W605", # invalid-escape-sequence
# Autofixed by other Ruff rules
"E401", # I001: unsorted-imports
"W690", # UP: pyupgrade
]

# https://github.com/microsoft/pyright/blob/main/docs/configuration.md#sample-pyprojecttoml-file
[tool.pyright]
typeCheckingMode = "strict"
Expand Down
10 changes: 7 additions & 3 deletions ruff.toml
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,9 @@ target-version = "py310" # Change this to the oldest supported version by your a
line-length = 100
preview = true

[format]
docstring-code-format = true

[lint]
select = ["ALL"]
# https://docs.astral.sh/ruff/rules/
Expand Down Expand Up @@ -62,8 +65,9 @@ ignore = [
###
# Conflict with formatter (you can remove this section if you don't use Ruff as a formatter)
###
# "COM812", # missing-trailing-comma
# "ISC001", # single-line-implicit-string-concatenation
"COM812", # missing-trailing-comma
"ISC001", # single-line-implicit-string-concatenation
"RUF028", # invalid-formatter-suppression-comment, Is meant for the formatter, but false-positives

###
# Rules about missing special documentation. Up to you if you wanna enable these, you must also disable D406, D407
Expand All @@ -77,7 +81,7 @@ ignore = [
###
# Specific to this project
###
"D205", # Not all docstrings have a short description + desrciption
"D205", # Not all docstrings have a short description + description
# TODO: Consider for more complete doc
"DOC201", # docstring-extraneous-returns
"DOC501", # docstring-missing-exception
Expand Down
5 changes: 2 additions & 3 deletions scripts/lint.ps1
Original file line number Diff line number Diff line change
Expand Up @@ -3,11 +3,10 @@ Set-Location "$PSScriptRoot/.."
$exitCodes = 0

Write-Host "`nRunning formatting..."
autopep8 src/ --recursive --in-place
add-trailing-comma $(git ls-files '**.py*')
ruff format

Write-Host "`nRunning Ruff ..."
ruff check . --fix
ruff check --fix
$exitCodes += $LastExitCode
if ($LastExitCode -gt 0) {
Write-Host "`Ruff failed ($LastExitCode)" -ForegroundColor Red
Expand Down
2 changes: 0 additions & 2 deletions scripts/requirements-dev.txt
Original file line number Diff line number Diff line change
Expand Up @@ -12,8 +12,6 @@
-r requirements.txt
#
# Linters & Formatters
add-trailing-comma>=3.1.0 # Must match .pre-commit-config.yaml
autopep8>=2.3.1 # Must match .pre-commit-config.yaml
ruff>=0.6.1 # Pre-commit fix # Must match .pre-commit-config.yaml
#
# Types
Expand Down
72 changes: 33 additions & 39 deletions src/AutoSplit.py
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@
# QT doesn't call those from Python/ctypes, meaning we can stop other programs from setting it.
if sys.platform == "win32":
import ctypes

# pyautogui._pyautogui_win.py
ctypes.windll.user32.SetProcessDPIAware = ( # pyright: ignore[reportAttributeAccessIssue]
lambda: None
Expand Down Expand Up @@ -89,6 +90,7 @@

if sys.platform == "win32":
from win32comext.shell import shell as shell32

myappid = f"Toufool.AutoSplit.v{AUTOSPLIT_VERSION}"
shell32.SetCurrentProcessExplicitAppUserModelID(myappid)

Expand Down Expand Up @@ -162,8 +164,8 @@ def _show_error_signal_slot(error_message_box: Callable[..., object]):

self.setupUi(self)
self.setWindowTitle(
f"AutoSplit v{AUTOSPLIT_VERSION}" +
(" (externally controlled)" if self.is_auto_controlled else ""),
f"AutoSplit v{AUTOSPLIT_VERSION}"
+ (" (externally controlled)" if self.is_auto_controlled else "")
)

# Hotkeys need to be initialized to be passed as thread arguments in hotkeys.py
Expand Down Expand Up @@ -210,16 +212,17 @@ def _show_error_signal_slot(error_message_box: Callable[..., object]):
self.undo_split_button.clicked.connect(self.undo_split)
self.next_image_button.clicked.connect(lambda: self.skip_split(navigate_image_only=True))
self.previous_image_button.clicked.connect(
lambda: self.undo_split(navigate_image_only=True),
lambda: self.undo_split(navigate_image_only=True)
)
self.align_region_button.clicked.connect(lambda: align_region(self))
self.select_window_button.clicked.connect(lambda: select_window(self))
self.reload_start_image_button.clicked.connect(
lambda: self.__reload_start_image(started_by_button=True),
lambda: self.__reload_start_image(started_by_button=True)
)
self.action_check_for_updates_on_open.changed.connect(
lambda: user_profile.set_check_for_updates_on_open(
self, self.action_check_for_updates_on_open.isChecked(),
self,
self.action_check_for_updates_on_open.isChecked(),
),
)

Expand All @@ -246,7 +249,7 @@ def _update_checker_widget_signal_slot(latest_version: str, check_on_open: bool)

# live image checkbox
self.timer_live_image.timeout.connect(
lambda: self.__update_live_image_details(None, called_from_timer=True),
lambda: self.__update_live_image_details(None, called_from_timer=True)
)
self.timer_live_image.start(int(ONE_SECOND / self.settings_dict["fps_limit"]))

Expand Down Expand Up @@ -288,7 +291,8 @@ def __browse(self):

def __update_live_image_details(
self,
capture: MatLike | None, *,
capture: MatLike | None,
*,
called_from_timer: bool = False,
):
# HACK: Since this is also called in __get_capture_for_comparison,
Expand Down Expand Up @@ -393,15 +397,12 @@ def __compare_capture_for_auto_start(self):
if below_flag and not self.split_below_threshold and similarity_diff >= 0:
self.split_below_threshold = True
return
if (
( # noqa: PLR0916 # See above TODO
below_flag
and self.split_below_threshold
and similarity_diff < 0
and is_valid_image(capture)
)
or (not below_flag and similarity_diff >= 0)
):
if ( # noqa: PLR0916 # See above TODO
below_flag
and self.split_below_threshold
and similarity_diff < 0
and is_valid_image(capture)
) or (not below_flag and similarity_diff >= 0):
self.timer_start_image.stop()
self.split_below_threshold = False

Expand All @@ -415,7 +416,7 @@ def __compare_capture_for_auto_start(self):
while time_delta < start_delay:
delay_time_left = start_delay - time_delta
self.current_split_image.setText(
f"Delayed Before Starting:\n {seconds_remaining_text(delay_time_left)}",
f"Delayed Before Starting:\n {seconds_remaining_text(delay_time_left)}"
)
# Wait 0.1s. Doesn't need to be shorter as we only show 1 decimal
QTest.qWait(100)
Expand Down Expand Up @@ -547,7 +548,7 @@ def skip_split(self, *, navigate_image_only: bool = False):
not self.is_running
or "Delayed Split" in self.current_split_image.text()
or not (
self.skip_split_button.isEnabled()
self.skip_split_button.isEnabled() # fmt: skip
or self.is_auto_controlled
or navigate_image_only
)
Expand Down Expand Up @@ -583,7 +584,7 @@ def reset(self):
def start_auto_splitter(self):
# If the auto splitter is already running or the button is disabled,
# don't emit the signal to start it.
if (
if ( # fmt: skip
self.is_running
or (not self.start_auto_splitter_button.isEnabled() and not self.is_auto_controlled)
):
Expand Down Expand Up @@ -622,9 +623,8 @@ def __auto_splitter(self): # noqa: C901,PLR0912,PLR0915
self.split_images_and_loop_number = list(
flatten(
((split_image, i + 1) for i in range(split_image.loops))
for split_image
in self.split_images
),
for split_image in self.split_images
)
)

# Construct groups of splits
Expand Down Expand Up @@ -726,9 +726,9 @@ def __auto_splitter(self): # noqa: C901,PLR0912,PLR0915
self.gui_changes_on_reset(safe_to_reload_start_image=True)

def __similarity_threshold_loop(
self,
number_of_split_images: int,
dummy_splits_array: list[bool],
self,
number_of_split_images: int,
dummy_splits_array: list[bool],
):
"""
Wait until the similarity threshold is met.
Expand Down Expand Up @@ -765,7 +765,7 @@ def __similarity_threshold_loop(
# If its the last non-dummy split image and last loop number,
# disable the skip split button
self.skip_split_button.setEnabled(
dummy_splits_array[self.split_image_number :].count(False) > 1,
dummy_splits_array[self.split_image_number :].count(False) > 1
)
self.undo_split_button.setEnabled(self.split_image_number != 0)
QApplication.processEvents()
Expand Down Expand Up @@ -827,7 +827,7 @@ def __pause_loop(self, stop_time: float, message: str):
break

self.current_split_image.setText(
f"{message} {seconds_remaining_text(stop_time - time_delta)}",
f"{message} {seconds_remaining_text(stop_time - time_delta)}"
)

QTest.qWait(1)
Expand Down Expand Up @@ -903,7 +903,7 @@ def __get_capture_for_comparison(self):
message += "\n(captured window may be incompatible with BitBlt)"
self.live_image.setText(message)
recovered = self.capture_method.recover_window(
self.settings_dict["captured_window_title"],
self.settings_dict["captured_window_title"]
)
if recovered:
capture = self.capture_method.get_frame()
Expand All @@ -929,7 +929,7 @@ def __reset_if_should(self, capture: MatLike | None):
should_reset = similarity >= threshold
self.reset_highest_similarity = max(similarity, self.reset_highest_similarity)
self.table_reset_image_highest_label.setText(
decimal(self.reset_highest_similarity),
decimal(self.reset_highest_similarity)
)
self.table_reset_image_live_label.setText(decimal(similarity))

Expand Down Expand Up @@ -960,7 +960,7 @@ def __update_split_image(self, specific_image: AutoSplitImage | None = None):

# Get split image
self.split_image = (
specific_image
specific_image # fmt: skip
or self.split_images_and_loop_number[0 + self.split_image_number][0]
)
if self.split_image.is_ocr:
Expand All @@ -972,7 +972,7 @@ def __update_split_image(self, specific_image: AutoSplitImage | None = None):

self.current_image_file_label.setText(self.split_image.filename)
self.table_current_image_threshold_label.setText(
decimal(self.split_image.get_similarity_threshold(self)),
decimal(self.split_image.get_similarity_threshold(self))
)

# Set Image Loop number
Expand Down Expand Up @@ -1048,19 +1048,13 @@ def set_preview_image(qlabel: QLabel, image: MatLike | None):
image_format = QtGui.QImage.Format.Format_BGR888
capture = image

qimage = QtGui.QImage(
capture.data,
width,
height,
width * channels,
image_format,
)
qimage = QtGui.QImage(capture.data, width, height, width * channels, image_format)
qlabel.setPixmap(
QtGui.QPixmap(qimage).scaled(
qlabel.size(),
QtCore.Qt.AspectRatioMode.IgnoreAspectRatio,
QtCore.Qt.TransformationMode.SmoothTransformation,
),
)
)


Expand Down
Loading

0 comments on commit 8c2949b

Please sign in to comment.