Skip to content

Commit

Permalink
feat: use ruff for codegen
Browse files Browse the repository at this point in the history
  • Loading branch information
iisakkirotko committed Dec 13, 2024
1 parent 5bfb28d commit 3f58e69
Showing 1 changed file with 19 additions and 7 deletions.
26 changes: 19 additions & 7 deletions reacton/generate.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,6 @@
from textwrap import indent
from typing import Any, Dict, Generic, Type, TypeVar

import black
import bqplot
import ipywidgets
import ipywidgets as widgets # type: ignore
Expand Down Expand Up @@ -106,6 +105,23 @@ def get_element_class(self, cls):
def get_ignore_props(self, cls):
return self.ignore_props

# Replicated from https://gist.github.com/shner-elmo/b2639a4d1e04ceafaad120acfb31213c
def ruff_format(self, code: str) -> str:
import subprocess
from ruff.__main__ import find_ruff_bin

ruff_args = [
find_ruff_bin(),
"format",
"--stdin-filename",
"foo.py", # you can pass any random string, it wont use it...
# these two lines are optional, but this is how you can pass the config for ruff
f"--line-length {MAX_LINE_LENGTH}",
]
proc = subprocess.run(ruff_args, input=code, text=True, capture_output=True)
proc.check_returncode() # raise an Exception if return code is not 0
return proc.stdout

def generate_component(self, cls: Type[widgets.Widget], blacken=True):
element_class_name = self.get_element_class(cls).__name__
ignore = self.get_ignore_props(cls)
Expand Down Expand Up @@ -293,9 +309,8 @@ def {{ method_name }}(**kwargs):
)

if blacken:
mode = black.Mode(line_length=MAX_LINE_LENGTH)
try:
code = black.format_file_contents(code, fast=False, mode=mode)
code = self.ruff_format(code)
except Exception:
print("code:\n", code)
raise
Expand Down Expand Up @@ -325,10 +340,7 @@ def generate(self, path, blacken=True):
raise ValueError(f"Could not find new line after marker: {marker!r}")
code_total = current_code[: start + 1] + "\n" + code
if blacken:
import black

mode = black.Mode(line_length=MAX_LINE_LENGTH)
code_total = black.format_file_contents(code_total, fast=False, mode=mode)
code_total = self.ruff_format(code_total)
only_valid = True
if only_valid:
try:
Expand Down

0 comments on commit 3f58e69

Please sign in to comment.