From cb0c92ea09c4928ec8c7c6eb1ab7e29959e766e3 Mon Sep 17 00:00:00 2001 From: foefl Date: Fri, 21 Mar 2025 09:44:39 +0100 Subject: [PATCH] add pre-compile option for whole standalone distribution, closes #1 --- src/pycage/compile.py | 74 +++++++++++++++++++++++++++++++++++++++++++ src/pycage/main.py | 2 ++ 2 files changed, 76 insertions(+) create mode 100644 src/pycage/compile.py diff --git a/src/pycage/compile.py b/src/pycage/compile.py new file mode 100644 index 0000000..19f4a2b --- /dev/null +++ b/src/pycage/compile.py @@ -0,0 +1,74 @@ +from __future__ import annotations + +import compileall +import re + +import click + +from pycage.helpers import get_interpreter, print_error + + +@click.command(help="precompile all Python files in the standalone distribution") +@click.option( + "-f", + "--force", + is_flag=True, + default=False, + show_default=True, + help=( + "force re-compilation of files even if the " + "timestamps suggest that they did not change" + ), +) +@click.option( + "-w", + "--workers", + type=click.INT, + default=1, + show_default=True, + help=( + "decide how many workers should be used, if 0: all cores of the machine will be used" + ), +) +@click.option( + "-o", + "--optimise", + type=click.IntRange(min=0, max=2), + default=0, + show_default=True, + help=( + "decide if optimisation should be applied. Following values are allowed: " + "0: no optimisation, 1: remove asserts, 2: also remove docstrings" + ), +) +def compile( + optimise: int, + workers: int, + force: bool, +) -> None: + exclude = re.compile(r"[\\|/]+tcl[\\|/]+") + + try: + pth_intp = get_interpreter() + except RuntimeError: + click.echo("Base interpreter path could not be found", err=True) + return + + base_dir = pth_intp.parent + + try: + success = compileall.compile_dir( + base_dir, + force=force, + optimize=optimise, + workers=workers, + rx=exclude, + ) + except Exception as err: + print_error(err) + + if not success: + err = RuntimeError("The compilation process was not successful.") + print_error(err) + else: + click.echo("The compilation process was successful.") diff --git a/src/pycage/main.py b/src/pycage/main.py index 9344a97..59102db 100644 --- a/src/pycage/main.py +++ b/src/pycage/main.py @@ -2,6 +2,7 @@ from __future__ import annotations import click +import pycage.compile import pycage.files import pycage.get import pycage.venv @@ -15,6 +16,7 @@ def cli(): cli.add_command(pycage.get.get) cli.add_command(pycage.venv.venv) cli.add_command(pycage.files.copy) +cli.add_command(pycage.compile.compile) if __name__ == "__main__": cli()