add pre-compile option for whole standalone distribution, closes #1

This commit is contained in:
Florian Förster 2025-03-21 09:44:39 +01:00
parent 15bef47cc8
commit cb0c92ea09
2 changed files with 76 additions and 0 deletions

74
src/pycage/compile.py Normal file
View File

@ -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.")

View File

@ -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()