Skip to content

Commit

Permalink
Use ruff instead of black and flake8
Browse files Browse the repository at this point in the history
  • Loading branch information
almarklein committed Sep 25, 2024
1 parent bd8dab7 commit cddd6c4
Show file tree
Hide file tree
Showing 31 changed files with 88 additions and 72 deletions.
14 changes: 9 additions & 5 deletions .github/workflows/ci.yml
Original file line number Diff line number Diff line change
Expand Up @@ -25,13 +25,16 @@ jobs:
uses: actions/setup-python@v5
with:
python-version: '3.12'
- name: Install dev dependencies
- name: Install dependencies
run: |
python -m pip install --upgrade pip
pip install -U -e .[lint]
- name: Flake8
pip install ruff
- name: Ruff lint
run: |
ruff check --output-format=github .
- name: Ruff format
run: |
flake8 .
ruff format --check .
test-codegen-build:
name: Test Codegen
Expand Down Expand Up @@ -140,7 +143,8 @@ jobs:
- name: Install dependencies
run: |
python -m pip install --upgrade pip
pip install -U -e .[tests] glfw pyinstaller
pip install -U -e .
pip install -U pytest psutil pyinstaller glfw
- name: Test PyInstaller
run: |
pyinstaller --version
Expand Down
3 changes: 1 addition & 2 deletions codegen/tests/test_codegen_apipatcher.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,4 @@
""" Test some parts of apipatcher.py, and Implicitly tests idlparser.py.
"""
"""Test some parts of apipatcher.py, and Implicitly tests idlparser.py."""

from codegen.utils import blacken
from codegen.apipatcher import CommentRemover, AbstractCommentInjector
Expand Down
3 changes: 1 addition & 2 deletions codegen/tests/test_codegen_rspatcher.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,4 @@
""" Test some parts of rsbackend.py, and implicitly tests hparser.py.
"""
"""Test some parts of rsbackend.py, and implicitly tests hparser.py."""

from codegen.wgpu_native_patcher import patch_wgpu_native_backend

Expand Down
2 changes: 1 addition & 1 deletion codegen/tests/test_codegen_utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -201,7 +201,7 @@ def bar3(self):
for line, i in p.iter_lines():
if line.lstrip().startswith("#"):
p.replace_line(i, "# comment")
with raises(Exception):
with raises(AssertionError):
p.replace_line(i, "# comment")
code2 = p.dumps()
assert code2.count("#") == 4
Expand Down
27 changes: 22 additions & 5 deletions codegen/utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@
import os
import sys
import tempfile
import subprocess

import black

Check failure on line 10 in codegen/utils.py

View workflow job for this annotation

GitHub Actions / Test Linting

Ruff (F401)

codegen/utils.py:10:8: F401 `black` imported but unused

Expand Down Expand Up @@ -103,14 +104,30 @@ def remove_c_comments(code):
return new_code


class FormatException(Exception):
pass

# todo: rename blacken to format_code
def blacken(src, singleline=False):
"""Format the given src string using black. If singleline is True,
all function signatures become single-line, so they can be parsed
and updated.
"""
# Normal black
mode = black.FileMode(line_length=999 if singleline else 88)
result = black.format_str(src, mode=mode)
# Use Ruff to format the line. Ruff does not yet have a Python API, so we use its CLI.
tempfilename = os.path.join(tempfile.gettempdir(), "toruff.py")
with open(tempfilename, "wb") as fp:
fp.write(src.encode())
line_length = 320 if singleline else 88
cmd = [sys.executable, "-m", "ruff", "format","--line-length", str(line_length), tempfilename]
p = subprocess.run(cmd, stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
if p.returncode:
raise FormatException(p.stdout.decode(errors='ignore'))
with open(tempfilename, "rb") as fp:
result = fp.read().decode()

# # Normal black
# mode = black.FileMode(line_length=999 if singleline else 88)
# result = black.format_str(src, mode=mode)

# Make defs single-line. You'd think that setting the line length
# to a very high number would do the trick, but it does not.
Expand Down Expand Up @@ -222,7 +239,7 @@ def dumps(self, format=True):
if format:
try:
text = blacken(text)
except black.InvalidInput as err: # pragma: no cover
except FormatException as err: # pragma: no cover
# If you get this error, it really helps to load the code
# in an IDE to see where the error is. Let's help with that ...
filename = os.path.join(tempfile.gettempdir(), "wgpu_patcher_fail.py")
Expand All @@ -234,7 +251,7 @@ def dumps(self, format=True):
f"It appears that the patcher has generated invalid Python:"
f"\n\n {err}\n\n"
f'Wrote the generated (but unblackened) code to:\n\n "{filename}"'
)
) from None

return text

Expand Down
10 changes: 5 additions & 5 deletions codegen/wgpu_native_patcher.py
Original file line number Diff line number Diff line change
Expand Up @@ -236,7 +236,7 @@ def apply(self, code):
else:
detected.add(var_name)
anno = hp.functions[var_name].replace(var_name, "f").strip(";")
self.insert_line(i, indent + f"# H: " + anno)
self.insert_line(i, indent + "# H: " + anno)
count += 1
elif match := re.search(r"(_\w+_function) = libf?\.(wgpu\w*)", line):
# Assignment of libf function to a class variable. We'll point the
Expand Down Expand Up @@ -266,7 +266,7 @@ def apply(self, code):
count += len(lib_names)
for lib_name in lib_names:
self.insert_line(
i, indent + f"# H: " + hp.functions[lib_name].strip(";")
i, indent + "# H: " + hp.functions[lib_name].strip(";")
)
# At this point, generic_class_var_assignment should be empty.
# If it is not, we've done an assignment to a class variable name, but have
Expand Down Expand Up @@ -363,12 +363,12 @@ def _validate_struct(self, hp, i1, i2):
if name.endswith("*"):
if "new_struct_p" not in lines[0]:
self.insert_line(
i1, indent + f"# FIXME: invalid C struct, use new_struct_p()"
i1, indent + "# FIXME: invalid C struct, use new_struct_p()"
)
else:
if "new_struct_p" in lines[0]:
self.insert_line(
i1, indent + f"# FIXME: invalid C struct, use new_struct()"
i1, indent + "# FIXME: invalid C struct, use new_struct()"
)

# Get struct object and create annotation line
Expand All @@ -380,7 +380,7 @@ def _validate_struct(self, hp, i1, i2):
else:
struct = hp.structs[struct_name]
fields = ", ".join(f"{key}: {val}" for key, val in struct.items())
self.insert_line(i1, indent + f"# H: " + fields)
self.insert_line(i1, indent + "# H: " + fields)

# Check keys
keys_found = []
Expand Down
6 changes: 3 additions & 3 deletions examples/imgui_backend_sea.py
Original file line number Diff line number Diff line change
Expand Up @@ -380,9 +380,9 @@ def render():
global_time = current_time

canvas_texture = present_context.get_current_texture()
render_pass_descriptor["color_attachments"][0][
"view"
] = canvas_texture.create_view()
render_pass_descriptor["color_attachments"][0]["view"] = (
canvas_texture.create_view()
)

# Update uniform buffer
uniform_data["resolution"] = (canvas_texture.size[0], canvas_texture.size[1])
Expand Down
6 changes: 3 additions & 3 deletions examples/imgui_renderer_sea.py
Original file line number Diff line number Diff line change
Expand Up @@ -349,9 +349,9 @@ def render():
global_time = current_time

canvas_texture = present_context.get_current_texture()
render_pass_descriptor["color_attachments"][0][
"view"
] = canvas_texture.create_view()
render_pass_descriptor["color_attachments"][0]["view"] = (
canvas_texture.create_view()
)

# Update uniform buffer
uniform_data["resolution"] = (canvas_texture.size[0], canvas_texture.size[1])
Expand Down
4 changes: 2 additions & 2 deletions examples/triangle_qt.py
Original file line number Diff line number Diff line change
Expand Up @@ -16,9 +16,9 @@
pass


from wgpu.gui.qt import WgpuCanvas # WgpuCanvas is a QWidget subclass
from wgpu.gui.qt import WgpuCanvas # noqa - WgpuCanvas is a QWidget subclass

from triangle import main # The function to call to run the visualization
from triangle import main # noqa - the function to call to run the visualization


app = QtWidgets.QApplication([])
Expand Down
4 changes: 2 additions & 2 deletions examples/triangle_qt_embed.py
Original file line number Diff line number Diff line change
Expand Up @@ -16,9 +16,9 @@
pass


from wgpu.gui.qt import WgpuWidget
from wgpu.gui.qt import WgpuWidget # noqa

from triangle import main
from triangle import main # noqa


class ExampleWidget(QtWidgets.QWidget):
Expand Down
6 changes: 4 additions & 2 deletions examples/wgpu-examples.ipynb
Original file line number Diff line number Diff line change
Expand Up @@ -58,9 +58,9 @@
}
],
"source": [
"from wgpu.gui.auto import WgpuCanvas, run\n",
"from wgpu.gui.auto import WgpuCanvas\n",
"import triangle\n",
" \n",
"\n",
"canvas = WgpuCanvas(size=(640, 480), title=\"wgpu triangle with GLFW\")\n",
"\n",
"triangle.main(canvas)\n",
Expand Down Expand Up @@ -165,11 +165,13 @@
"\n",
"out = ipywidgets.Textarea(rows=10)\n",
"\n",
"\n",
"@canvas.add_event_handler(\"*\")\n",
"def show_events(event):\n",
" if event[\"event_type\"] != \"pointer_move\":\n",
" out.value = str(event)\n",
"\n",
"\n",
"out"
]
},
Expand Down
16 changes: 14 additions & 2 deletions pyproject.toml
Original file line number Diff line number Diff line change
Expand Up @@ -20,10 +20,10 @@ imgui = ["imgui-bundle>=1.2.1"]
build = ["build", "hatchling", "requests", "twine"]
codegen = ["pytest", "numpy", "black"]
lint = ["black", "flake8", "flake8-black", "pep8-naming"]
docs = ["sphinx>7.2", "sphinx_rtd_theme"]
tests = ["numpy", "pytest", "psutil", "imageio"]
examples = []
dev = ["wgpu[build,codegen,lint,docs,tests,examples]"]
docs = ["sphinx>7.2", "sphinx_rtd_theme"]
dev = ["wgpu[build,codegen,lint,tests,examples,docs]"]

[project.entry-points."pyinstaller40"]
hook-dirs = "wgpu.__pyinstaller:get_hook_dirs"
Expand Down Expand Up @@ -65,10 +65,22 @@ path = "tools/hatch_build.py"

# ===== Tooling

[tool.ruff]
line-length = 88

[tool.ruff.lint]
#select = ["F", "E", "W", "N", "B", "RUF"] # todo: add D and DOC for docstrings?
ignore = [
"E501", # Line too long
"B006", # Do not use mutable data structures for argument defaults
"B007", # Loop control variable `x` not used within loop body
]

[tool.coverage.report]
exclude_also = [
# Have to re-enable the standard pragma, plus a less-ugly flavor
"pragma: no cover",
"no-cover",
"raise NotImplementedError",
]
select = ["E", "F"]
2 changes: 1 addition & 1 deletion tests/renderutils.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
""" Utils to render to a texture or screen. Tuned to the tests, so quite some
"""Utils to render to a texture or screen. Tuned to the tests, so quite some
assumptions here.
"""

Expand Down
2 changes: 1 addition & 1 deletion tests/test_gui_base.py
Original file line number Diff line number Diff line change
Expand Up @@ -31,7 +31,7 @@ def bar_method(self):
raise Exception("call-failed-" + "but-test-passed")

def spam_method(self):
1 / 0
raise ZeroDivisionError()


def test_base_canvas_context():
Expand Down
2 changes: 0 additions & 2 deletions tests/test_not_finite.py
Original file line number Diff line number Diff line change
Expand Up @@ -118,7 +118,6 @@ def test_finite_using_uint():


def detect_finites(title, shader, expect_detection_nan, expect_detection_inf):

base_shader = """
@group(0)
Expand Down Expand Up @@ -243,7 +242,6 @@ def detect_finites(title, shader, expect_detection_nan, expect_detection_inf):


if __name__ == "__main__":

test_finite_using_nequal()
test_finite_using_min_max()
test_finite_using_uint()
2 changes: 1 addition & 1 deletion tests/test_set_constant.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@
import pytest

import wgpu.utils
from tests.testutils import can_use_wgpu_lib, run_tests
from testutils import can_use_wgpu_lib, run_tests
from wgpu import TextureFormat
from wgpu.backends.wgpu_native.extras import create_pipeline_layout, set_push_constants

Expand Down
4 changes: 2 additions & 2 deletions tests/test_set_override.py
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import pytest

import wgpu.utils
from tests.testutils import can_use_wgpu_lib, run_tests
from testutils import can_use_wgpu_lib, run_tests
from wgpu import TextureFormat

if not can_use_wgpu_lib:
Expand Down Expand Up @@ -170,7 +170,7 @@ def test_no_overridden_constants_render(runner):


def test_no_constants_compute(runner):
runner.run_test(compute=True) == [1, 2, 3, 0]
assert runner.run_test(compute=True) == [1, 2, 3, 0]


def test_override_vertex_constants(runner):
Expand Down
2 changes: 1 addition & 1 deletion tests/test_wgpu_vertex_instance.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@
import numpy as np
import pytest
import wgpu.utils
from tests.testutils import can_use_wgpu_lib, run_tests
from testutils import can_use_wgpu_lib, run_tests
from wgpu import TextureFormat
from wgpu.backends.wgpu_native.extras import (
multi_draw_indexed_indirect,
Expand Down
1 change: 0 additions & 1 deletion tools/hatch_build.py
Original file line number Diff line number Diff line change
Expand Up @@ -44,7 +44,6 @@ def initialize(self, version, build_data):
# we go pure-Python mode, and expect the user to set WGPU_LIB_PATH.

if self.target_name == "wheel" and is_git_repo():

# Prepare
check_git_status()
remove_all_libs()
Expand Down
7 changes: 3 additions & 4 deletions wgpu/_classes.py
Original file line number Diff line number Diff line change
Expand Up @@ -296,8 +296,8 @@ def configure(
if not isinstance(usage, int):
usage = str_flag_to_int(flags.TextureUsage, usage)

color_space # not really supported, just assume srgb for now
tone_mapping # not supported yet
color_space # noqa - not really supported, just assume srgb for now
tone_mapping # noqa - not supported yet

if alpha_mode not in enums.CanvasAlphaMode:
raise ValueError(
Expand Down Expand Up @@ -393,7 +393,6 @@ def get_current_texture(self):
return self._texture

def _create_texture_image(self):

canvas = self._get_canvas()
width, height = canvas.get_physical_size()
width, height = max(width, 1), max(height, 1)
Expand Down Expand Up @@ -496,7 +495,7 @@ class GPUAdapterInfo:
"""Represents information about an adapter."""

def __init__(self, info):
self._info
self._info = info

# IDL: readonly attribute DOMString vendor;
@property
Expand Down
2 changes: 1 addition & 1 deletion wgpu/_coreutils.py
Original file line number Diff line number Diff line change
Expand Up @@ -149,7 +149,7 @@ def str_flag_to_int(flag, s):
v = flag.__dict__[p.upper()]
value += v
except KeyError:
raise ValueError(f"Invalid flag value for {flag}: '{p}'")
raise ValueError(f"Invalid flag value for {flag}: '{p}'") from None
_flag_cache[cache_key] = value

return value
Expand Down
Loading

0 comments on commit cddd6c4

Please sign in to comment.