summaryrefslogtreecommitdiff
path: root/py-nuitka-build
blob: 3b144272d8e6fd064032d4e921ac3b05d5f0493b (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
#!/usr/bin/env bash
#
# Nuitka Build Helper Script
#
# Compiles Python scripts into standalone executables using Nuitka with
# dependency management via uv.

set -euo pipefail

_parse_dependecies() {
  cat <<EOF | python3 - "$1"
import platform
import re
import sys
import tomllib

REGEX = r"(?m)^# /// (?P<type>[a-zA-Z0-9-]+)$\s(?P<content>(^#(| .*)$\s)+)^# ///$"


def read(script: str) -> dict | None:
    name = "script"
    matches = list(filter(lambda m: m.group("type") == name, re.finditer(REGEX, script)))
    if len(matches) > 1:
        raise ValueError(f"Multiple {name} blocks found")
    elif len(matches) == 1:
        content = "".join(
            line[2:] if line.startswith("# ") else line[1:]
            for line in matches[0].group("content").splitlines(keepends=True)
        )
        return tomllib.loads(content)
    else:
        return {}


with open(sys.argv[1], "r") as fd:
    script = fd.read()
    metadata = read(script)
    python_version = metadata.get("requires-python", platform.python_version())
    dependencies = metadata.get("dependencies", [])
    print(python_version)
    if dependencies:
        print("\n".join(dependencies))
EOF
}

main() {

  if [[ $# -ne 1 ]]; then
    echo "Usage: $0 <python_script.py>" >&2
    exit 1
  fi

  local script="$1"

  if [[ ! -f "$script" ]]; then
    echo "Error: Script '$script' not found" >&2
    exit 2
  fi

  {
    local python_version
    local -a dependencies=()
    IFS= read -r python_version
    readarray -t dependencies

    local cmd=(uv run)
    cmd+=(--python "$python_version")
    for dependency in "${dependencies[@]}"; do
      cmd+=(--with "$dependency")
    done

    cmd+=(--with 'Nuitka[onefile]')
    cmd+=(python -m nuitka --standalone --onefile "$script")

    "${cmd[@]}"
  } < <(_parse_dependecies "$script")

}

main "$@"