Repository navigation
Expand file tree
/
Copy pathbuild.py
More file actions
330 lines (289 loc) · 12.3 KB
/
Copy pathbuild.py
File metadata and controls
330 lines (289 loc) · 12.3 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
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
from pathlib import Path
import tempfile
import os
import subprocess
import sys
import platform
import argparse
import signal
import atexit
import time
import urllib.request
import urllib.error
# Track background processes for cleanup
vite_process = None
cpp_process = None
VITE_DEV_HOST = "127.0.0.1"
VITE_DEV_PORT = 5183
VITE_DEV_URL = f"http://{VITE_DEV_HOST}:{VITE_DEV_PORT}"
TONE3000_CLIENT_ID_ENV_NAMES = (
"TONE3000_PUBLISHABLE_KEY",
"OPENSTUDIO_TONE3000_CLIENT_ID_VALUE",
"OPENSTUDIO_TONE3000_CLIENT_ID",
)
def get_first_env_value(names):
for name in names:
value = os.environ.get(name, "").strip()
if value:
return name, value
return "", ""
def mask_command_for_log(command):
if isinstance(command, (list, tuple)):
command = subprocess.list2cmdline([str(part) for part in command])
else:
command = str(command)
_, tone3000_client_id = get_first_env_value(TONE3000_CLIENT_ID_ENV_NAMES)
if tone3000_client_id:
command = command.replace(tone3000_client_id, "<tone3000_publishable_key>")
return command
def kill_process_tree(pid):
"""Retain the Windows orphan-instance cleanup contract."""
if platform.system() == "Windows":
# /T = kill child processes, /F = force
subprocess.run(["taskkill", "/F", "/T", "/PID", str(pid)],
stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
def start_owned_process(command, **kwargs):
"""Give each POSIX app/server a separate group owned by this invocation."""
if os.name != "nt":
kwargs["start_new_session"] = True
return subprocess.Popen(command, **kwargs)
def stop_owned_process(process, timeout_seconds=5):
"""Stop an owned group even when its original parent has already exited."""
if os.name == "nt":
if process.poll() is None:
kill_process_tree(process.pid)
try:
process.wait(timeout=timeout_seconds)
except subprocess.TimeoutExpired:
process.kill()
process.wait()
return
# start_owned_process makes the child's PID its process-group ID. Do not
# look it up after exit, when a helper may be the only group member left.
group = process.pid
if group == os.getpgrp():
raise RuntimeError("Refusing to stop the builder's own process group")
try:
os.killpg(group, signal.SIGTERM)
except ProcessLookupError:
process.wait()
return
deadline = time.monotonic() + timeout_seconds
while time.monotonic() < deadline:
process.poll() # Reap the group leader without blocking on descendants.
try:
os.killpg(group, 0)
except ProcessLookupError:
break
time.sleep(0.02)
else:
try:
os.killpg(group, signal.SIGKILL)
except ProcessLookupError:
pass
process.wait()
def kill_orphaned_openstudio():
"""Windows retains its historical orphan-instance check."""
if platform.system() == "Windows":
result = subprocess.run(
["tasklist", "/FI", "IMAGENAME eq OpenStudio.exe", "/FO", "CSV", "/NH"],
capture_output=True, text=True
)
for line in result.stdout.strip().splitlines():
if "OpenStudio.exe" in line:
parts = line.split(",")
if len(parts) >= 2:
pid = parts[1].strip('"')
print(f" Killing orphaned OpenStudio.exe (PID {pid}) and its child processes...")
kill_process_tree(int(pid))
time.sleep(0.5)
def cleanup():
"""Kill background processes on exit (including child process trees)"""
global vite_process, cpp_process
if cpp_process is not None:
print("\nStopping C++ app (and WebView2 child processes)...")
stop_owned_process(cpp_process)
cpp_process = None
if vite_process is not None:
print("Stopping Vite dev server...")
stop_owned_process(vite_process)
vite_process = None
# Register cleanup handler
atexit.register(cleanup)
def run_command(command, cwd=None, shell=None):
if shell is None:
shell = isinstance(command, str)
print(f"Running: {mask_command_for_log(command)}")
try:
subprocess.check_call(command, cwd=cwd, shell=shell)
except (OSError, subprocess.CalledProcessError) as error:
print(f"Error running command: {mask_command_for_log(command)}")
print(error)
sys.exit(1)
def get_npm_executable():
return "npm.cmd" if platform.system() == "Windows" else "npm"
def wait_for_http_server(url, timeout_seconds=30, poll_interval=0.5):
"""Wait until an HTTP server responds successfully."""
deadline = time.time() + timeout_seconds
last_error = None
while time.time() < deadline:
global vite_process
if vite_process and vite_process.poll() is not None:
print("Vite dev server exited before becoming ready.")
return False
try:
with urllib.request.urlopen(url, timeout=1) as response:
status = getattr(response, "status", 200)
if 200 <= status < 500:
print(f"Vite dev server is ready at {url}")
return True
except (urllib.error.URLError, OSError) as exc:
last_error = exc
time.sleep(poll_interval)
print(f"Timed out waiting for Vite dev server at {url}")
if last_error is not None:
print(f"Last connection error: {last_error}")
return False
def build_frontend(mode="dev"):
frontend_dir = os.path.join(os.getcwd(), "frontend")
print("--- Building Frontend ---")
# Check if node_modules exists
if not os.path.exists(os.path.join(frontend_dir, "node_modules")):
print("Installing dependencies...")
run_command("npm install", cwd=frontend_dir)
if mode == "prod":
run_command("npm run build", cwd=frontend_dir)
elif mode == "dev":
# Keep packaged fallback assets current even in dev. The native app normally
# loads Vite, but it can fall back to webui if WebView2 startup times out.
run_command("npm run build", cwd=frontend_dir)
def get_cpp_exe_path(config="Debug"):
"""Return the platform-appropriate path to the built C++ executable."""
if platform.system() == "Windows":
return os.path.join("build", "OpenStudio_artefacts", config, "OpenStudio.exe")
elif platform.system() == "Darwin":
return os.path.join("build", "OpenStudio_artefacts", config,
"OpenStudio.app", "Contents", "MacOS", "OpenStudio")
else: # Linux
return os.path.join("build", "OpenStudio_artefacts", config, "OpenStudio")
def build_backend(mode="debug", app_version=None):
print("--- Building Backend ---")
if platform.system() == "Windows":
run_command([
"powershell.exe",
"-NoProfile",
"-ExecutionPolicy", "Bypass",
"-File", os.path.join(os.getcwd(), "tools", "setup-ffmpeg.ps1"),
], shell=False)
build_dir = os.path.join(os.getcwd(), "build")
if not os.path.exists(build_dir):
os.makedirs(build_dir)
config_type = "Debug" if mode == "debug" else "Release"
# Configure CMake. On single-config generators (Linux/macOS Make/Ninja)
# CMAKE_BUILD_TYPE must be set at configure time, not just at build time.
cmd = ["cmake", "-B", build_dir]
# Ordinary launches and production packaging never opt into callback profiling.
cmd.append("-DOPENSTUDIO_ENABLE_CALLBACK_DIAGNOSTICS=OFF")
# Production installs must fetch the managed runtime, never depend on system Python.
cmd.append("-DOPENSTUDIO_ENABLE_EXTERNAL_PYTHON_AI_FALLBACK="
+ ("ON" if mode == "debug" else "OFF"))
if app_version:
cmd.append(f"-DOPENSTUDIO_APP_VERSION={app_version}")
if platform.system() != "Windows":
cmd.append(f"-DCMAKE_BUILD_TYPE={config_type}")
tone3000_env_name, tone3000_client_id = get_first_env_value(TONE3000_CLIENT_ID_ENV_NAMES)
if tone3000_client_id:
print(f"Using TONE3000 publishable client_id from ${tone3000_env_name}.")
cmd.append(f"-DOPENSTUDIO_TONE3000_CLIENT_ID_VALUE={tone3000_client_id}")
else:
print("No TONE3000 publishable client_id env var found; keeping the existing CMake cache value if one is set.")
run_command(cmd, shell=False)
# Build
run_command(["cmake", "--build", build_dir, "--config", config_type], shell=False)
def start_vite_server():
"""Start Vite dev server in background"""
global vite_process
frontend_dir = os.path.join(os.getcwd(), "frontend")
print("\n--- Starting Vite Dev Server ---")
vite_process = start_owned_process(
[
get_npm_executable(),
"run",
"dev",
"--",
"--host",
VITE_DEV_HOST,
"--port",
str(VITE_DEV_PORT),
"--strictPort",
],
cwd=frontend_dir,
shell=False
)
print(f"Waiting for Vite to start on {VITE_DEV_URL}...")
if not wait_for_http_server(VITE_DEV_URL):
cleanup()
print("Unable to confirm the Vite dev server is reachable, so the native app was not launched.")
sys.exit(1)
return vite_process
def run_cpp_app():
"""Run the C++ executable"""
global cpp_process
exe_path = get_cpp_exe_path("Debug")
if not os.path.exists(exe_path):
print(f"ERROR: Executable not found at {exe_path}")
print("Run 'python build.py dev' first to build the app.")
sys.exit(1)
print(f"\n--- Launching {exe_path} ---")
cpp_process = start_owned_process([exe_path])
# Wait for C++ app to finish
try:
cpp_process.wait()
except KeyboardInterrupt:
print("\nShutting down...")
def main():
parser = argparse.ArgumentParser(description="OpenStudio Builder Tool")
parser.add_argument("mode", choices=["dev", "prod"], help="Build mode: dev or prod")
parser.add_argument("--run", action="store_true", help="Auto-start Vite and C++ app (dev mode only)")
parser.add_argument("--version", help="Exact application version (required for prod)")
parser.add_argument("--notes-file", default="", help="Reviewed release notes (defaults to docs/releases/<version>.md)")
args = parser.parse_args()
if args.mode == "dev":
build_frontend("dev")
build_backend("debug")
if args.run:
print("\n" + "="*50)
print("SINGLE COMMAND DEV MODE")
print("="*50)
# Kill any orphaned OpenStudio processes (and their WebView2 children)
# from previous runs that weren't cleaned up properly
print("Checking for orphaned processes...")
kill_orphaned_openstudio()
start_vite_server()
run_cpp_app()
else:
print("\nBuild Complete. To run:")
print("1. Manual: cd frontend && npm run dev (then run exe)")
print("2. Auto: python build.py dev --run")
elif args.mode == "prod":
if not args.version:
parser.error("prod requires --version and reviewed docs/releases/<version>.md")
version = args.version.removeprefix("v")
validation = [sys.executable, "tools/validate-release-notes.py", "--version", version]
if args.notes_file:
validation.extend(["--notes-file", args.notes_file])
run_command(validation, shell=False)
build_frontend("prod")
build_backend("release", app_version=version)
if platform.system() in ("Windows", "Linux", "Darwin"):
with tempfile.TemporaryDirectory(prefix="openstudio-support-") as support_output:
run_command([sys.executable, "tools/build-support-tool.py", "--version", version,
"--output", support_output,
"--stage", (str(Path(get_cpp_exe_path("Release")).parents[2]) if platform.system() == "Darwin"
else os.path.dirname(get_cpp_exe_path("Release")))], shell=False)
run_command([sys.executable, "tools/build-symbols.py", "archive",
"--app", get_cpp_exe_path("Release"), "--build-dir", "build"], shell=False)
print("\nProduction Build Complete.")
print(f"Run: {get_cpp_exe_path('Release')}")
if __name__ == "__main__":
main()