Skip to content

Commit

Permalink
Make compiler.py as exec, fix whitespaces, and stringify arrays
Browse files Browse the repository at this point in the history
Plus make import progress verbose
  • Loading branch information
nattadasu committed Oct 28, 2024
1 parent e70f927 commit 07f5c49
Showing 1 changed file with 43 additions and 0 deletions.
43 changes: 43 additions & 0 deletions compiler.py
100644 → 100755
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
#!/usr/bin/env python3

import argparse as ap
import os
from pathlib import Path
Expand Down Expand Up @@ -75,6 +77,7 @@ def resolve_imports(script_path: Union[str, Path]) -> str:
Returns:
str: Script with resolved imports
"""
script_path = Path(script_path)
with open(script_path, "r") as f:
script = f.read()
sli = script.splitlines(keepends=True)
Expand All @@ -84,20 +87,60 @@ def resolve_imports(script_path: Union[str, Path]) -> str:
import_path = Path(script_path).parent / match(
r"^@(.*\.groovy)", line
).group(1)
print(f" @ {script_path}:{i+1} <- {import_path.absolute()}")
sli[i] = resolve_imports(import_path)

return "".join(sli)


def remove_leading_whitespace(text: str) -> str:
"""
Remove leading whitespace from each line in the input text.
Args:
text (str): Text to sanitize
Returns:
str: Sanitized text
"""
return sub(r"^\s+", "", text, flags=MULTILINE)


def array_stringify(text: str) -> str:
"""
Convert multiline array into a single line of array, removing trailing commas.
FIX: This function is not perfect, it can't process nested arrays.
Args:
text (str): Text to sanitize
Returns:
str: Sanitized text
"""
# Step 1: Minify arrays by replacing newline characters inside brackets with spaces
# This captures nested arrays and dictionary-like structures in Groovy
text = sub(r"\[([^\[\]]*)\]", lambda m: m.group(0).replace("\n", ""), text)

# Step 2: Remove trailing commas before closing brackets for cleaner output
text = sub(r",\s*([\]\}])", r"\1", text)

return text


def main():
args = parse_args()
inp = Path(args.input)
out = Path(args.output)
print(f"Compiling {inp} to {out}")
script = resolve_imports(args.input)
script = remove_blank_lines(remove_comments(script))
script = array_stringify(remove_leading_whitespace(script))
# test if the output directory exists, if specified, if not create it
if os.path.dirname(args.output):
os.makedirs(os.path.dirname(args.output), exist_ok=True)
with open(args.output, "w") as f:
f.write(script)
print(f'Done! Use "@{out.absolute()}" in FileBot\n')


if __name__ == "__main__":
Expand Down

0 comments on commit 07f5c49

Please sign in to comment.