241 lines
8.9 KiB
Python
241 lines
8.9 KiB
Python
"""Build / Run flow for generated Python apps.
|
|
|
|
There is no CMake build for Python apps (see docs/architecture.md):
|
|
"Build" is a syntax check (``python3 -m py_compile``) and "Run"
|
|
executes the generated script with ``python3``. Both show the exact
|
|
command run, like the C console does, and stream their output into a
|
|
build console window whose output area FILLS the dialog and scrolls
|
|
to the end (to the failure on error) — the C cb95f5f fix, built in
|
|
from the start: the ScrolledWindow is packed expanding, and scrolling
|
|
happens in an idle callback after allocation, not right after show.
|
|
|
|
The generated script needs the LightGUI package on PYTHONPATH; the
|
|
Run flow sets it to the repo root (the parent of this package).
|
|
"""
|
|
|
|
import os
|
|
import shlex
|
|
import subprocess
|
|
import sys
|
|
|
|
import gi
|
|
|
|
gi.require_version("Gtk", "3.0")
|
|
|
|
from gi.repository import GLib, Gtk # noqa: E402
|
|
|
|
|
|
def repo_root():
|
|
"""Directory holding the ``lightgui`` package (this file's parent's
|
|
parent)."""
|
|
return os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
|
|
|
|
|
|
def run_env(extra=None):
|
|
"""Environment for running a generated script: PYTHONPATH gains
|
|
the repo root so ``import lightgui`` resolves."""
|
|
env = dict(os.environ)
|
|
root = repo_root()
|
|
path = env.get("PYTHONPATH", "")
|
|
parts = [p for p in path.split(os.pathsep) if p] if path else []
|
|
if root not in parts:
|
|
parts.insert(0, root)
|
|
env["PYTHONPATH"] = os.pathsep.join(parts)
|
|
if extra:
|
|
env.update(extra)
|
|
return env
|
|
|
|
|
|
def command_str(argv):
|
|
"""Shell display form of *argv* (what the console shows after $)."""
|
|
return shlex.join(str(arg) for arg in argv)
|
|
|
|
|
|
class BuildResult:
|
|
"""Outcome of one build/run step: ok, the exact command, its
|
|
combined output, and its exit code (None when never started)."""
|
|
|
|
def __init__(self, ok, output, command, returncode=None,
|
|
script_path=None):
|
|
self.ok = ok
|
|
self.output = output
|
|
self.command = command
|
|
self.returncode = returncode
|
|
self.script_path = script_path
|
|
|
|
def __bool__(self):
|
|
return self.ok
|
|
|
|
|
|
def syntax_check(script_path, python=sys.executable):
|
|
"""'Build': py_compile the generated script. Returns a
|
|
BuildResult whose output starts with the exact command run."""
|
|
argv = [python, "-m", "py_compile", str(script_path)]
|
|
command = command_str(argv)
|
|
try:
|
|
proc = subprocess.run(argv, capture_output=True, text=True,
|
|
timeout=60)
|
|
except subprocess.TimeoutExpired:
|
|
return BuildResult(False, "$ %s\ntimed out after 60s\n" % command,
|
|
command, None, script_path)
|
|
except OSError as exc:
|
|
return BuildResult(False, "$ %s\ncannot run: %s\n" % (command, exc),
|
|
command, None, script_path)
|
|
output = "$ %s\n%s%s" % (command, proc.stdout, proc.stderr)
|
|
return BuildResult(proc.returncode == 0, output, command,
|
|
proc.returncode, script_path)
|
|
|
|
|
|
def run_capture(script_path, timeout=30, python=sys.executable,
|
|
extra_env=None):
|
|
"""Run the generated script synchronously and capture its combined
|
|
stdout+stderr (for tests and for the Build console). A timeout
|
|
kills the script and reports it; the exit code is preserved."""
|
|
argv = [python, str(script_path)]
|
|
command = command_str(argv)
|
|
try:
|
|
proc = subprocess.run(argv, capture_output=True, text=True,
|
|
timeout=timeout, env=run_env(extra_env))
|
|
except subprocess.TimeoutExpired as exc:
|
|
output = "$ %s\n%s%s\n[timed out after %ss — killed]\n" % (
|
|
command, exc.stdout or "", exc.stderr or "", timeout)
|
|
return BuildResult(False, output, command, None, script_path)
|
|
except OSError as exc:
|
|
return BuildResult(False, "$ %s\ncannot run: %s\n" % (command, exc),
|
|
command, None, script_path)
|
|
output = "$ %s\n%s%s" % (command, proc.stdout, proc.stderr)
|
|
return BuildResult(proc.returncode == 0, output, command,
|
|
proc.returncode, script_path)
|
|
|
|
|
|
# --- build console window -----------------------------------------------------
|
|
|
|
|
|
class BuildConsole(Gtk.Dialog):
|
|
"""Scrollable log dialog for build/run output. The log TextView
|
|
fills the dialog (packed expanding — the cb95f5f fix) and the view
|
|
starts scrolled to the end of the log, so a failure is visible
|
|
immediately. Run output streams in live via io watches; a Stop
|
|
button kills the running script.
|
|
"""
|
|
|
|
def __init__(self, title="Build", parent=None):
|
|
super().__init__(title=title, parent=parent,
|
|
flags=Gtk.DialogFlags.DESTROY_WITH_PARENT)
|
|
self.set_default_size(700, 420)
|
|
self.proc = None
|
|
self._stdout_watch = None
|
|
self._child_watch = None
|
|
|
|
self.view = Gtk.TextView()
|
|
self.view.set_editable(False)
|
|
self.view.set_monospace(True)
|
|
self.view.set_wrap_mode(Gtk.WrapMode.CHAR)
|
|
self.buffer = self.view.get_buffer()
|
|
|
|
scroll = Gtk.ScrolledWindow()
|
|
scroll.set_policy(Gtk.PolicyType.AUTOMATIC,
|
|
Gtk.PolicyType.AUTOMATIC)
|
|
scroll.add(self.view)
|
|
# Pack expanding so the log fills the dialog (cb95f5f): the
|
|
# dialog content box's default add() packs expand=FALSE, which
|
|
# left the log at ~2 lines pinned to the top.
|
|
content = self.get_content_area()
|
|
content.pack_start(scroll, True, True, 0)
|
|
content.show_all()
|
|
|
|
self.stop_button = self.add_button("Stop",
|
|
Gtk.ResponseType.CANCEL)
|
|
self.stop_button.set_sensitive(False)
|
|
self.add_button("Close", Gtk.ResponseType.CLOSE)
|
|
self.connect("response", self._on_response)
|
|
|
|
# --- text ---------------------------------------------------------------
|
|
def get_text(self):
|
|
start, end = self.buffer.get_bounds()
|
|
return self.buffer.get_text(start, end, True)
|
|
|
|
def set_text(self, text):
|
|
self.buffer.set_text(text or "")
|
|
self.scroll_to_end()
|
|
|
|
def append(self, text):
|
|
if not text:
|
|
return
|
|
end = self.buffer.get_end_iter()
|
|
self.buffer.insert(end, text)
|
|
self.scroll_to_end()
|
|
|
|
def scroll_to_end(self):
|
|
"""Scroll to the end of the log. Deferred to idle: scrolling
|
|
before the dialog is realized/allocated computes against the
|
|
not-yet-final size and lands short of the true end (C fix)."""
|
|
GLib.idle_add(self._scroll_to_end_idle)
|
|
|
|
def _scroll_to_end_idle(self):
|
|
end = self.buffer.get_end_iter()
|
|
self.view.scroll_to_iter(end, 0.0, False, 0.0, 0.0)
|
|
return False
|
|
|
|
# --- running ------------------------------------------------------------
|
|
def run_command(self, argv, cwd=None, extra_env=None):
|
|
"""Start *argv* async, streaming combined output into the log.
|
|
Shows the exact command first, like the C console."""
|
|
command = command_str(argv)
|
|
self.set_text("$ %s\n" % command)
|
|
self.stop_button.set_sensitive(True)
|
|
try:
|
|
self.proc = subprocess.Popen(
|
|
[str(arg) for arg in argv],
|
|
stdout=subprocess.PIPE, stderr=subprocess.STDOUT,
|
|
text=True, bufsize=1, cwd=cwd, env=run_env(extra_env))
|
|
except OSError as exc:
|
|
self.append("cannot run: %s\n" % exc)
|
|
self.stop_button.set_sensitive(False)
|
|
return False
|
|
self._stdout_watch = GLib.io_add_watch(
|
|
self.proc.stdout, GLib.IO_IN | GLib.IO_HUP,
|
|
self._on_stdout)
|
|
self._child_watch = GLib.child_watch_add(
|
|
self.proc.pid, self._on_child_exit)
|
|
return True
|
|
|
|
def _on_stdout(self, source, _condition):
|
|
chunk = source.readline()
|
|
if chunk:
|
|
self.append(chunk)
|
|
return True
|
|
return False
|
|
|
|
def _on_child_exit(self, _pid, status):
|
|
code = os.waitstatus_to_exitcode(status) \
|
|
if hasattr(os, "waitstatus_to_exitcode") else status
|
|
self.append("\n[exited with code %s]\n" % code)
|
|
self.stop_button.set_sensitive(False)
|
|
self.proc = None
|
|
return False
|
|
|
|
def stop(self):
|
|
"""Kill the running script, if any."""
|
|
if self.proc is not None and self.proc.poll() is None:
|
|
self.proc.kill()
|
|
self.append("\n[stopped]\n")
|
|
self.stop_button.set_sensitive(False)
|
|
|
|
def _on_response(self, _dialog, response):
|
|
if response == Gtk.ResponseType.CANCEL:
|
|
self.stop()
|
|
elif response == Gtk.ResponseType.CLOSE:
|
|
self.hide()
|
|
|
|
|
|
def show_result_dialog(parent, result, title="Build"):
|
|
"""Modal console showing a finished BuildResult (syntax check).
|
|
The log fills the dialog and starts scrolled to the end."""
|
|
console = BuildConsole(title=title, parent=parent)
|
|
head = "Build succeeded.\n\n" if result.ok else "Build FAILED.\n\n"
|
|
console.set_text(head + result.output)
|
|
console.run()
|
|
console.destroy()
|
|
return result.ok
|