Skip to content

Commit 3f58e69

Browse files
committed
feat: use ruff for codegen
1 parent 5bfb28d commit 3f58e69

File tree

1 file changed

+19
-7
lines changed

1 file changed

+19
-7
lines changed

reacton/generate.py

Lines changed: 19 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -5,7 +5,6 @@
55
from textwrap import indent
66
from typing import Any, Dict, Generic, Type, TypeVar
77

8-
import black
98
import bqplot
109
import ipywidgets
1110
import ipywidgets as widgets # type: ignore
@@ -106,6 +105,23 @@ def get_element_class(self, cls):
106105
def get_ignore_props(self, cls):
107106
return self.ignore_props
108107

108+
# Replicated from https://gist.github.com/shner-elmo/b2639a4d1e04ceafaad120acfb31213c
109+
def ruff_format(self, code: str) -> str:
110+
import subprocess
111+
from ruff.__main__ import find_ruff_bin
112+
113+
ruff_args = [
114+
find_ruff_bin(),
115+
"format",
116+
"--stdin-filename",
117+
"foo.py", # you can pass any random string, it wont use it...
118+
# these two lines are optional, but this is how you can pass the config for ruff
119+
f"--line-length {MAX_LINE_LENGTH}",
120+
]
121+
proc = subprocess.run(ruff_args, input=code, text=True, capture_output=True)
122+
proc.check_returncode() # raise an Exception if return code is not 0
123+
return proc.stdout
124+
109125
def generate_component(self, cls: Type[widgets.Widget], blacken=True):
110126
element_class_name = self.get_element_class(cls).__name__
111127
ignore = self.get_ignore_props(cls)
@@ -293,9 +309,8 @@ def {{ method_name }}(**kwargs):
293309
)
294310

295311
if blacken:
296-
mode = black.Mode(line_length=MAX_LINE_LENGTH)
297312
try:
298-
code = black.format_file_contents(code, fast=False, mode=mode)
313+
code = self.ruff_format(code)
299314
except Exception:
300315
print("code:\n", code)
301316
raise
@@ -325,10 +340,7 @@ def generate(self, path, blacken=True):
325340
raise ValueError(f"Could not find new line after marker: {marker!r}")
326341
code_total = current_code[: start + 1] + "\n" + code
327342
if blacken:
328-
import black
329-
330-
mode = black.Mode(line_length=MAX_LINE_LENGTH)
331-
code_total = black.format_file_contents(code_total, fast=False, mode=mode)
343+
code_total = self.ruff_format(code_total)
332344
only_valid = True
333345
if only_valid:
334346
try:

0 commit comments

Comments
 (0)