-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbuild_binary.py
More file actions
202 lines (156 loc) · 5.76 KB
/
Copy pathbuild_binary.py
File metadata and controls
202 lines (156 loc) · 5.76 KB
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
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
#!/usr/bin/env python3
"""
Build a self-contained executable for testbench-requirement-service using PyInstaller.
The output is a onedir bundle:
dist/testbench-requirement-service/
testbench-requirement-service[.exe] <- launch this
... <- support files
Usage:
python build_binary.py [options]
Options:
--spec PATH Path to the .spec file [default: testbench-requirement-service.spec]
--no-clean Keep previous artefacts (faster incremental rebuild)
"""
from __future__ import annotations
import argparse
import platform
import re
import shutil
import subprocess
import sys
import zipfile
from pathlib import Path
REPO_ROOT = Path(__file__).parent.resolve()
INIT_FILE = REPO_ROOT / "src" / "testbench_requirement_service" / "__init__.py"
DEFAULT_SPEC = REPO_ROOT / "testbench-requirement-service.spec"
DIST_DIR = REPO_ROOT / "dist"
BUILD_DIR = REPO_ROOT / "build"
MIN_PYTHON = (3, 10)
def _check_python_version() -> None:
if sys.version_info < MIN_PYTHON:
sys.exit(
f"ERROR: Python {MIN_PYTHON[0]}.{MIN_PYTHON[1]}+ is required (running {sys.version})."
)
def _read_version() -> str:
text = INIT_FILE.read_text(encoding="utf-8")
match = re.search(r'^__version__\s*=\s*[\'"]([^\'"]+)[\'"]', text, re.MULTILINE)
if not match:
sys.exit(f"ERROR: Could not read __version__ from {INIT_FILE}.")
return match.group(1)
def _binary_name() -> str:
"""Return the platform-specific executable name, e.g. 'testbench-requirement-service.exe'."""
suffix = ".exe" if platform.system() == "Windows" else ""
return f"testbench-requirement-service{suffix}"
def _platform_tag() -> str:
"""Return a compact platform tag, e.g. 'win_amd64' or 'linux_x86_64'."""
system = platform.system().lower()
machine = platform.machine().lower()
if system == "windows":
return "win_amd64" if machine in ("amd64", "x86_64") else f"win_{machine}"
if system == "linux":
arch = "x86_64" if machine in ("amd64", "x86_64") else machine
return f"linux_{arch}"
if system == "darwin":
return f"macos_{machine}"
return f"{system}_{machine}"
def _run(cmd: list[str], *, cwd: Path | None = None) -> None:
print(f"\n>>> {' '.join(cmd)}\n")
result = subprocess.run(cmd, cwd=cwd, check=False)
if result.returncode != 0:
sys.exit(f"ERROR: Command failed with exit code {result.returncode}.")
def _ensure_pyinstaller() -> None:
"""Install PyInstaller into the current environment if it is not present."""
try:
import PyInstaller # noqa: PLC0415, F401
except ImportError:
print("PyInstaller not found — installing …")
_run([sys.executable, "-m", "pip", "install", "pyinstaller"])
def _install_package_editable() -> None:
"""
Install the package in editable mode with the reader extras so that
PyInstaller's collect_data_files() can locate the package data files
(openapi.yaml, static/, readers/jsonl/schemas/, …).
"""
print("Installing package in editable mode with reader extras …")
_run(
[
sys.executable,
"-m",
"pip",
"install",
"--quiet",
"-e",
".[excel,jira]",
],
cwd=REPO_ROOT,
)
def _clean_artefacts() -> None:
for directory in (BUILD_DIR, DIST_DIR):
if directory.exists():
print(f"Removing {directory} …")
shutil.rmtree(directory)
def _build(spec: Path) -> None:
_run(
[
sys.executable,
"-m",
"PyInstaller",
str(spec),
"--noconfirm",
],
cwd=REPO_ROOT,
)
def _zip_output(version: str, platform_tag: str) -> Path:
"""Zip the onedir output folder and return the archive path."""
bundle_dir = DIST_DIR / "testbench-requirement-service"
if not bundle_dir.exists():
sys.exit(f"ERROR: Expected output folder not found: {bundle_dir}")
archive_name = f"testbench-requirement-service-{version}-{platform_tag}.zip"
archive_path = DIST_DIR / archive_name
print(f"\nCreating archive: {archive_path} …")
with zipfile.ZipFile(archive_path, "w", zipfile.ZIP_DEFLATED) as zf:
for file in sorted(bundle_dir.rglob("*")):
if file.is_file():
zf.write(file, file.relative_to(DIST_DIR))
return archive_path
def _parse_args() -> argparse.Namespace:
parser = argparse.ArgumentParser(
description="Build a self-contained executable using PyInstaller.",
)
parser.add_argument(
"--spec",
type=Path,
default=DEFAULT_SPEC,
metavar="PATH",
help=f"Path to the .spec file [default: {DEFAULT_SPEC.name}]",
)
parser.add_argument(
"--no-clean",
dest="clean",
action="store_false",
default=True,
help="Keep previous artefacts (faster incremental rebuild)",
)
return parser.parse_args()
def main() -> None:
args = _parse_args()
_check_python_version()
_ensure_pyinstaller()
_install_package_editable()
version = _read_version()
platform_tag = _platform_tag()
spec: Path = args.spec.resolve()
if not spec.exists():
sys.exit(f"ERROR: Spec file not found: {spec}")
print(f"\nBuilding testbench-requirement-service v{version} for {platform_tag} …")
if args.clean:
_clean_artefacts()
_build(spec)
bundle_dir = DIST_DIR / "testbench-requirement-service"
print(f"\nBuild complete: {bundle_dir}")
archive = _zip_output(version, platform_tag)
print(f"Archive: {archive}")
binary_path = bundle_dir / _binary_name()
print(f"\nTo test the executable, run:\n {binary_path} --version\n")
if __name__ == "__main__":
main()