|
3 | 3 |
|
4 | 4 | import functools |
5 | 5 | import json |
| 6 | +import re |
6 | 7 | import shutil |
7 | 8 | import subprocess |
8 | 9 | import textwrap |
|
22 | 23 | if TYPE_CHECKING: |
23 | 24 | from collections.abc import Sequence |
24 | 25 |
|
| 26 | +_logger = getLogger(__name__) |
| 27 | + |
| 28 | + |
| 29 | +def minify_python(source: str): |
| 30 | + """Minify Python source code.""" |
| 31 | + # Remove comments |
| 32 | + source = re.sub(r"#.*\n", "\n", source) |
| 33 | + # Remove docstrings |
| 34 | + source = re.sub(r'""".*?"""', "", source, flags=re.DOTALL) |
| 35 | + # Remove extra newlines |
| 36 | + source = re.sub(r"\n+", "\n", source) |
| 37 | + # Remove empty lines |
| 38 | + source = re.sub(r"\s+\n", "\n", source) |
| 39 | + # Remove leading and trailing whitespace |
| 40 | + return source.strip() |
25 | 41 |
|
26 | | -PYSCRIPT_COMPONENT_TEMPLATE = ( |
27 | | - Path(__file__).parent / "component_template.py" |
28 | | -).read_text(encoding="utf-8") |
29 | | -PYSCRIPT_LAYOUT_HANDLER = (Path(__file__).parent / "layout_handler.py").read_text( |
30 | | - encoding="utf-8" |
| 42 | + |
| 43 | +PYSCRIPT_COMPONENT_TEMPLATE = minify_python( |
| 44 | + (Path(__file__).parent / "component_template.py").read_text(encoding="utf-8") |
| 45 | +) |
| 46 | +PYSCRIPT_LAYOUT_HANDLER = minify_python( |
| 47 | + (Path(__file__).parent / "layout_handler.py").read_text(encoding="utf-8") |
31 | 48 | ) |
32 | | -_logger = getLogger(__name__) |
33 | 49 |
|
34 | 50 |
|
35 | 51 | def render_pyscript_executor(file_paths: tuple[str, ...], uuid: str, root: str) -> str: |
@@ -206,5 +222,6 @@ def reactpy_version_string() -> str: # pragma: no cover |
206 | 222 |
|
207 | 223 |
|
208 | 224 | @functools.cache |
209 | | -def cached_file_read(file_path: str) -> str: |
210 | | - return Path(file_path).read_text(encoding="utf-8").strip() |
| 225 | +def cached_file_read(file_path: str, minifiy=True) -> str: |
| 226 | + content = Path(file_path).read_text(encoding="utf-8").strip() |
| 227 | + return minify_python(content) if minifiy else content |
0 commit comments