Skip to content
This repository has been archived by the owner on Dec 10, 2024. It is now read-only.

Commit

Permalink
Make more refactor stuff
Browse files Browse the repository at this point in the history
  • Loading branch information
iopapamanoglou committed Aug 29, 2024
1 parent b8daa43 commit b72f3ab
Show file tree
Hide file tree
Showing 2 changed files with 137 additions and 4 deletions.
6 changes: 3 additions & 3 deletions src/faebryk/library/HLK_LD2410B_P.py
Original file line number Diff line number Diff line change
Expand Up @@ -9,10 +9,10 @@

class HLK_LD2410B_P(Module):
class _ld2410b_esphome_config(F.has_esphome_config.impl()):
throttle_ms: F.TBD
throttle: F.TBD

def get_config(self) -> dict:
val = self.throttle_ms.get_most_narrow()
val = self.throttle.get_most_narrow()
assert isinstance(val, F.Constant), "No update interval set!"

obj = self.obj
Expand All @@ -34,7 +34,7 @@ def get_config(self) -> dict:

return {
"ld2410": {
"throttle": f"{val.value}ms",
"throttle": f"{val.value.to('ms')}",
"uart_id": uart_cfg["id"],
},
"binary_sensor": [
Expand Down
135 changes: 134 additions & 1 deletion src/faebryk/tools/refactor.py
Original file line number Diff line number Diff line change
@@ -1,10 +1,12 @@
# This file is part of the faebryk project
# SPDX-License-Identifier: MIT

from lib2to3 import refactor

Check failure on line 4 in src/faebryk/tools/refactor.py

View workflow job for this annotation

GitHub Actions / test

Ruff (F401)

src/faebryk/tools/refactor.py:4:21: F401 `lib2to3.refactor` imported but unused
import re
import subprocess
from dataclasses import dataclass
from pathlib import Path
from textwrap import dedent, indent

import typer

Expand All @@ -27,6 +29,9 @@ def main(ctx: typer.Context):
pass


pyname = r"[_a-zA-Z][_a-zA-Z0-9]*"


@main.command()
def libtof(ctx: typer.Context, root: Path):
file_paths = list(root.rglob("**/*.py"))
Expand All @@ -49,7 +54,6 @@ def libtof(ctx: typer.Context, root: Path):
# has_simple_value_representation,
# )

pyname = r"[_a-zA-Z][_a-zA-Z0-9]*"
import_pattern = re.compile(
r"^from faebryk.library.([^_][^ ]*) import ("
f"{pyname}$"
Expand Down Expand Up @@ -86,5 +90,134 @@ def refactor_file(path: Path):
subprocess.check_call(["ruff", "check", "--fix", root])


maybe_f = r"(?:F\.)?"


@main.command()
def fabll(ctx: typer.Context, root: Path):
file_paths = list(root.rglob("**/*.py"))
print(f"Found {len(file_paths)} files in path.")

types = r"(?:IF|NODE|PARAM)"
ano_class = rf"class _{types}s\("
detection_pattern = re.compile(ano_class)

Check failure on line 103 in src/faebryk/tools/refactor.py

View workflow job for this annotation

GitHub Actions / test

Ruff (F841)

src/faebryk/tools/refactor.py:103:5: F841 Local variable `detection_pattern` is assigned to but never used

refactor_files = file_paths
# refactor_files = [
# path
# for path in file_paths
# if not path.stem.startswith("_") and detection_pattern.search(path.read_text())
# ]

print(f"Found {len(refactor_files)} files to refactor.")

holder_header = rf"[ ]*{ano_class}.*?\):\n"
holder_pattern = re.compile(
rf"({holder_header})(.*?)\n\n", re.MULTILINE | re.DOTALL
)

instance_holder = re.compile(rf"self.{types}s = _{types}s\(self\)", re.MULTILINE)
holder_attr = re.compile(rf"\.{types}s\.")

def refactor_file(path: Path):
text = path.read_text()

print(path, "=" * 40)

def process(m: re.Match) -> str:
# print("Block", "|||")
header, fields = m.groups()
fields: str = fields + "\n"
out = []
for f in fields.split(")\n"):
if not f:
continue
f += ")"
# print(f)
# print(indent("|\nv", " " * 12))

if "times" in f:
f = re.sub(r"\n\s*", "", f)
f = f.replace(",)", ")")

# case 3: screw_holes = times(3, lambda: F.Mounting_Hole())
f = re.sub(r"times\((\d+),", r"L.list_field(\1,", f)

# case 5: leds = times(\n self.pixels.value, \n ...,\n)
f = re.sub(
rf"\s*({pyname}) = (times\(.*\))",
r"@L.rt_field\ndef \1(self):\n return \2",
f,
)

# case 1: uart_in = F.UART_Base()
# case 4: if buffered:\n power_data = F.ElectricPower()
f = re.sub(rf" = ({maybe_f}{pyname})\(\)", r": \1", f)

# case 2: fan_power_switch = F.PowerSwitchMOSFET(lowside=True, ...)
f = re.sub(
rf" = ({maybe_f}{pyname})\((.*)\)", r" = L.f_field(\1)(\2)", f
)

# print(f)
# print("--")
out.append(dedent(f))

outstr = indent("\n".join(out), " " * 4)
# print(outstr)
return outstr

# Holders -------------------------------------
text = holder_pattern.sub(process, text)
text = instance_holder.sub("", text)
text = holder_attr.sub(".", text)

# Init ----------------------------------------
# convert empty constructor to __preinit__
text = re.sub(
r"def __init__\(self\).*?:(.*?)super\(\).__init__\(\)",
r"def __preinit__(self):\1pass",
text,
flags=re.DOTALL | re.MULTILINE,
)

# remove -> None from init
text = re.sub(
r"(def __init__\(self.*?\)).*?:",
r"\1:",
text,
)

def process_constructor(m: re.Match) -> str:
str_: str = m.group(0)
args = m.group(1)
out = str_
prefix = re.match(r"^\s*", str_).group(0)

# find names of args
arg_names = re.findall(rf",\s*({pyname})\s*(?:[:,]|$)", args)
for arg in arg_names:
out += indent(f"\n self._{arg} = {arg}", prefix)

out += indent("\n\ndef __preinit__(self):\n pass", prefix)
return out

# split args of constructor into init and pre_init
text = re.sub(
r"^[ ]*def __init__\(self(, .*?)\):.*?super\(\).__init__\(\)",
process_constructor,
text,
flags=re.DOTALL | re.MULTILINE,
)

# Done ----------------------------------------
text = "\n".join(line.rstrip() for line in text.splitlines())
text = text.strip() + "\n"
path.write_text(text)

for path in refactor_files:
refactor_file(path)


if __name__ == "__main__":
main()

0 comments on commit b72f3ab

Please sign in to comment.