Files
dssc/dsflow_tui.py
T
lucioandClaude Opus 5.5 e58b768963 Add dsflow_tui: terminal UI for the dsflow DesignSync check-in flow
Single-file curses TUI (Python 3.6+, stdlib only) on top of dsflow:
list modified/new files, locks and checked-out copies; run sanity in a
detached runner that locks the files and checks in or unlocks on
completion; batch-tag files with predefined tags; --demo sandbox with a
fake dssc. files.zip holds the original dsflow plan scripts.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-09-23 10:17:37 -07:00

2493 lines
105 KiB
Python
Executable File
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""dsflow_tui - terminal UI for the dsflow DesignSync check-in flow.
Run from the workspace root (the same place you run `dsflow`):
dsflow_tui.py interactive TUI
dsflow_tui.py status [--json] print the sanity-run status and exit
dsflow_tui.py --demo try it in a sandbox driven by a fake dssc
What it does
* lists locally modified / newly added files, your locks (plus the hot-file
lock board) and checked-out-but-unlocked copies
* lets you pick files and fire a sanity regression in a detached runner:
check freshness -> lock picked files -> refresh to Trunk:Latest ->
sanity on every config -> (optional) check in + tag -> release locks
The runner outlives the TUI; reopen it (or run `status`) to follow along.
Locks it took are released whatever happens: pass, fail or cancel.
* batch-tags the selected files with a predefined tag (DSFLOW_TAGS)
All DesignSync access goes through the ds_* helpers in dsflow.conf, like the
bash flow. Helpers the TUI needs that dsflow.conf does not define get the
defaults in BASH_DEFAULTS below; verify them against your dssc version and
override any of them in dsflow.conf.
Optional dsflow.conf settings
DSFLOW_TAGS="wmac_working" tags offered by batch tag / tag-after-check-in
SANITY_SCRIPT='...' external sanity command used instead of the
run_sanity function. {cfg} and {ws} are
substituted and it runs under bash with
dsflow.conf sourced, e.g.
SANITY_SCRIPT='$WS_ROOT/sim/run_sanity.sh {cfg}'
(--sanity-cmd on the command line overrides both)
Needs Python >= 3.6 and bash. No third-party packages.
"""
import argparse
import curses
import fcntl
import getpass
import hashlib
import json
import locale
import os
import shlex
import shutil
import signal
import socket
import subprocess
import sys
import tempfile
import textwrap
import threading
import time
import traceback
VERSION = "1.0"
ME = os.environ.get("USER") or getpass.getuser()
JOB_FILE = "tui_job.json" # state of the current/last sanity run
JOB_LOCK = "tui_job.lock" # flock held by the runner while it lives
JOB_CANCEL = "tui_job.cancel" # touch to ask the runner to stop
RUNNER_LOG = "tui_runner.log" # what the runner did, step by step
RUNNER_OUT = "tui_runner.out" # runner stdout/stderr (crash traces)
HISTORY = "tui_history.json" # last passing duration per config
TERMINAL = ("passed", "failed", "cancelled", "error")
HEARTBEAT_STALE = 60 # s without a runner heartbeat => runner gone
# ---------------------------------------------------------------------------
# bash side. Everything below is appended after `source dsflow.conf`, and only
# defines a helper when dsflow.conf did not. VERIFY against your dssc version.
# ---------------------------------------------------------------------------
BASH_DEFAULTS = r'''
command -v sha1sum >/dev/null 2>&1 || sha1sum() { shasum -a 1 "$@"; }
_dsflow_has() { [ -n "$(type -t "$1" 2>/dev/null)" ]; }
# Every managed file in the workspace, one workspace-relative path per line.
_dsflow_has ds_list_managed || ds_list_managed() { dssc ls -rec -report N . 2>/dev/null | awk 'NF'; }
# "path<TAB>lock-holder" for every writable managed file. DesignSync fetches
# read-only copies unless a file is checked out, so writable == checked out.
_dsflow_has ds_list_writable || ds_list_writable() {
local f
ds_list_managed | while IFS= read -r f; do
[[ -f $f && -w $f && ! -L $f ]] || continue
printf '%s\t%s\n' "$f" "$(ds_lock_holder "$f")"
done
}
# Take the vault lock WITHOUT touching the local copy (it may hold edits).
_dsflow_has ds_lock || ds_lock() { dssc lock "$@"; }
_dsflow_has ds_unlock || ds_unlock() { dssc unlock "$@"; }
_dsflow_has ds_checkin || ds_checkin() { local m=$1; shift; dssc ci -comment "$m" "$@"; }
_dsflow_has ds_checkin_new || ds_checkin_new() { local m=$1; shift; dssc ci -new -comment "$m" "$@"; }
_dsflow_has ds_tag || ds_tag() { local t=$1; shift; dssc tag -replace "$t" "$@"; }
_dsflow_has ds_refresh || ds_refresh() { dssc pop -rec -version "$TRUNK_SEL" .; }
_dsflow_has ds_rebase || ds_rebase() { local f; for f; do dssc pop -merge -version "$TRUNK_SEL" "$f"; done; }
'''
CONF_VARS = ("TRUNK_SEL", "WORKING_TAG", "SANITY_CONFIGS", "MAX_STAMP_AGE",
"HOT_FILES", "CHECKIN_LOG", "DSFLOW_TAGS", "SANITY_SCRIPT")
SNAPSHOT_SH = r'''
ds_list_modified | sort -u | while IFS= read -r f; do
[[ -n $f ]] || continue
printf 'M\t%s\t%s\t%s\t%s\n' "$f" "$(ds_base_version "$f")" "$(ds_latest_version "$f")" "$(ds_lock_holder "$f")"
done
ds_list_writable | while IFS=$'\t' read -r f h; do
[[ -n $f ]] && printf 'W\t%s\t%s\n' "$f" "$h"
done
if [[ -f $HOT_FILES ]]; then
grep -v '^[[:space:]]*#' "$HOT_FILES" | awk 'NF{print $1}' | while IFS= read -r f; do
printf 'H\t%s\t%s\n' "$f" "$(ds_lock_holder "$f")"
done
fi
'''
VERSIONS_SH = r'''for f; do printf '%s\t%s\t%s\n' "$f" "$(ds_base_version "$f")" "$(ds_latest_version "$f")"; done'''
HOLDERS_SH = r'''for f; do printf '%s\t%s\n' "$f" "$(ds_lock_holder "$f")"; done'''
# Same list as all_changes() in dsflow, so the stamp we write is one dsflow accepts.
ALL_CHANGES_SH = r'''{ ds_list_modified; cat "$WS_ROOT/.dsflow/new_files" 2>/dev/null; } | awk 'NF' | sort -u'''
class FlowError(Exception):
pass
class StepFailed(Exception):
pass
class Cancelled(Exception):
pass
# ---------------------------------------------------------------------------
# small helpers
# ---------------------------------------------------------------------------
def read_json(path, default=None):
try:
with open(path) as fh:
return json.load(fh)
except (OSError, ValueError):
return default
def write_json(path, data):
tmp = "%s.%d.tmp" % (path, os.getpid())
with open(tmp, "w") as fh:
json.dump(data, fh, indent=1, sort_keys=True)
os.replace(tmp, path)
def sha1_file(path):
h = hashlib.sha1()
try:
with open(path, "rb") as fh:
for chunk in iter(lambda: fh.read(1 << 20), b""):
h.update(chunk)
except OSError:
return None
return h.hexdigest()
def norm(path):
path = path.strip()
while path.startswith("./"):
path = path[2:]
return path
def fmt_dur(sec):
if sec is None:
return ""
sec = int(max(0, sec))
if sec < 60:
return "%ds" % sec
if sec < 3600:
return "%dm%02ds" % (sec // 60, sec % 60)
return "%dh%02dm" % (sec // 3600, sec % 3600 // 60)
def fmt_ago(epoch):
return "%s ago" % fmt_dur(time.time() - epoch) if epoch else "never"
def fmt_clock(epoch):
return time.strftime("%H:%M:%S", time.localtime(epoch)) if epoch else "--:--:--"
def last_line(text):
lines = [l for l in (text or "").strip().splitlines() if l.strip()]
return lines[-1].strip() if lines else ""
def tail_lines(path, max_bytes=256 * 1024):
try:
with open(path, "rb") as fh:
fh.seek(0, os.SEEK_END)
size = fh.tell()
fh.seek(max(0, size - max_bytes))
data = fh.read()
except OSError:
return None
lines = data.decode("utf-8", "replace").replace("\r", "").expandtabs(4).split("\n")
if size > max_bytes:
lines = lines[1:]
if lines and lines[-1] == "":
lines.pop()
return lines
def job_state(job):
"""none | active | orphaned | done"""
if not job:
return "none"
if job.get("status") in TERMINAL:
return "done"
if time.time() - job.get("heartbeat", job.get("created", 0)) > HEARTBEAT_STALE:
return "orphaned"
return "active"
# ---------------------------------------------------------------------------
# Flow: the workspace plus every call into dsflow.conf
# ---------------------------------------------------------------------------
class Flow(object):
def __init__(self, ws, conf, sanity_cmd=None, tags=None):
self.ws = os.path.abspath(ws)
self.conf = os.path.abspath(conf)
self.sdir = os.path.join(self.ws, ".dsflow")
self.cli_sanity_cmd = sanity_cmd
self.cli_tags = tags
self.vars = {}
if not os.path.isfile(self.conf):
raise FlowError("config not found: %s\n(run from the workspace root, or pass --conf / set DSFLOW_CONF)" % self.conf)
if not os.path.isdir(self.sdir):
os.makedirs(self.sdir)
if not os.path.exists(self.path("new_files")):
open(self.path("new_files"), "a").close()
def path(self, name):
return os.path.join(self.sdir, name)
def wpath(self, rel):
return os.path.join(self.ws, rel)
# -- bash plumbing ------------------------------------------------------
def argv(self, snippet, args=()):
script = 'export WS_ROOT=%s\ncd "$WS_ROOT" || exit 97\nsource %s || exit 98\n%s\n%s\n' % (
shlex.quote(self.ws), shlex.quote(self.conf), BASH_DEFAULTS, snippet)
return ["bash", "-c", script, "dsflow-tui"] + [str(a) for a in args]
def env(self, extra=None):
env = dict(os.environ)
env["DSFLOW_CONF"] = self.conf
env["WS_ROOT"] = self.ws
env.update(extra or {})
return env
def run(self, snippet, args=(), timeout=900):
p = subprocess.Popen(self.argv(snippet, args), stdin=subprocess.DEVNULL,
stdout=subprocess.PIPE, stderr=subprocess.PIPE, cwd=self.ws,
env=self.env(), start_new_session=True,
universal_newlines=True, encoding="utf-8", errors="replace")
try:
out, err = p.communicate(timeout=timeout)
except subprocess.TimeoutExpired:
kill_group(p)
out, err = p.communicate()
return 124, out, err + "\n(timed out after %ds)" % timeout
return p.returncode, out, err
def act(self, fn, *args, **kw):
"""Run one ds_* helper; returns (rc, combined output)."""
rc, out, err = self.run('%s "$@"' % fn, args, timeout=kw.get("timeout", 1800))
return rc, (out + err).strip()
# -- configuration --------------------------------------------------------
def load_vars(self):
snippet = 'for v in %s; do printf "%%s=%%s\\0" "$v" "${!v-}"; done' % " ".join(CONF_VARS)
rc, out, err = self.run(snippet, timeout=60)
if rc != 0:
raise FlowError("cannot source %s:\n%s" % (self.conf, err.strip()))
for item in out.split("\0"):
if "=" in item:
k, v = item.split("=", 1)
self.vars[k] = v
@property
def trunk(self):
return self.vars.get("TRUNK_SEL") or "Trunk:Latest"
@property
def working_tag(self):
return self.vars.get("WORKING_TAG") or "working"
@property
def configs(self):
return self.vars.get("SANITY_CONFIGS", "").split()
@property
def max_age(self):
try:
return int(self.vars.get("MAX_STAMP_AGE") or 4 * 3600)
except ValueError:
return 4 * 3600
@property
def tags(self):
tags = self.cli_tags or self.vars.get("DSFLOW_TAGS", "").split() or ["wmac_working"]
# the working tag belongs to CI: moving it by hand defeats the green gate
return [t for t in tags if t != self.working_tag]
@property
def sanity_cmd(self):
return self.cli_sanity_cmd or self.vars.get("SANITY_SCRIPT") or ""
# -- local state shared with bash dsflow ------------------------------------
def hot_files(self):
out = []
try:
with open(self.vars.get("HOT_FILES") or self.wpath("flow/hot_files.txt")) as fh:
for line in fh:
line = line.strip()
if line and not line.startswith("#"):
out.append(norm(line.split()[0]))
except OSError:
pass
return out
def new_files(self):
try:
with open(self.path("new_files")) as fh:
return sorted(set(norm(l) for l in fh if l.strip()))
except OSError:
return []
def _write_new(self, paths):
with open(self.path("new_files"), "w") as fh:
for p in sorted(set(paths)):
fh.write(p + "\n")
def add_new(self, paths):
self._write_new(self.new_files() + [norm(p) for p in paths])
self.drop_stamp()
def remove_new(self, paths):
gone = set(paths)
self._write_new([p for p in self.new_files() if p not in gone])
def drop_stamp(self):
try:
os.remove(self.path("sanity.stamp"))
except OSError:
pass
# -- queries --------------------------------------------------------------
def snapshot(self):
t0 = time.time()
snap = Snapshot()
rc, out, err = self.run(SNAPSHOT_SH, timeout=1800)
if rc != 0 and not out.strip():
snap.err = last_line(err) or "dssc query failed (rc=%d)" % rc
mods, writable, hot_holder = {}, {}, {}
for line in out.splitlines():
p = line.split("\t")
if p[0] == "M" and len(p) >= 5:
mods[norm(p[1])] = (p[2].strip(), p[3].strip(), p[4].strip())
elif p[0] == "W" and len(p) >= 3:
writable[norm(p[1])] = p[2].strip()
elif p[0] == "H" and len(p) >= 3:
hot_holder[norm(p[1])] = p[2].strip()
hot = set(self.hot_files())
for path in sorted(mods):
base, latest, holder = mods[path]
snap.changes.append(dict(
path=path, kind="M", base=base, latest=latest, holder=holder,
stale=bool(base and latest and base != latest), unknown=not (base and latest),
hot=path in hot, exists=True))
for path in self.new_files():
if path not in mods:
snap.changes.append(dict(
path=path, kind="A", base="", latest="", holder="", stale=False,
unknown=False, hot=path in hot, exists=os.path.exists(self.wpath(path))))
holders = {}
for src in (hot_holder, writable, dict((p, v[2]) for p, v in mods.items())):
for p, h in src.items():
if h:
holders[p] = h
for p in sorted(set(holders) | hot):
h = holders.get(p, hot_holder.get(p, ""))
snap.locks.append(dict(path=p, holder=h, hot=p in hot, modified=p in mods))
snap.locks.sort(key=lambda r: (0 if r["holder"] == ME else 1 if r["holder"] else 2, r["path"]))
for p in sorted(writable):
if not writable[p]:
snap.checkout.append(dict(path=p, holder="", hot=p in hot, modified=p in mods))
snap.took = time.time() - t0
return snap
def versions(self, files):
if not files:
return {}
rc, out, err = self.run(VERSIONS_SH, files)
res = {}
for line in out.splitlines():
p = line.split("\t")
if len(p) >= 3:
res[norm(p[0])] = (p[1].strip(), p[2].strip())
return res
def stale_of(self, files):
return dict((f, v) for f, v in self.versions(files).items() if v[0] and v[1] and v[0] != v[1])
def holders(self, files):
if not files:
return {}
rc, out, err = self.run(HOLDERS_SH, files)
res = {}
for line in out.splitlines():
p = line.split("\t")
if p and p[0]:
res[norm(p[0])] = p[1].strip() if len(p) > 1 else ""
return res
def content_hash(self, files):
"""sha1 of `sha1sum files... | sha1sum`, i.e. dsflow's content_hash."""
if not files:
return "none"
text = "".join("%s %s\n" % (sha1_file(self.wpath(f)) or "0" * 40, f) for f in files)
return hashlib.sha1(text.encode("utf-8")).hexdigest()
# -- actions --------------------------------------------------------------
def checkin(self, msg, mods, news, log):
"""Check in modified + new files the way `dsflow checkin` does."""
for fn, files in (("ds_checkin", mods), ("ds_checkin_new", news)):
if not files:
continue
rc, out = self.act(fn, msg, *files, timeout=3600)
for line in out.splitlines():
log(" " + line)
if rc != 0:
return False, "check-in failed (%s): %s" % (fn, last_line(out) or "rc=%d" % rc)
self.remove_new(news)
self.drop_stamp()
files = list(mods) + list(news)
logpath = self.vars.get("CHECKIN_LOG")
if logpath:
try:
with open(logpath, "a") as fh:
fh.write("%s\t%s\t%s\t%s\n" % (time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime()), ME,
self.content_hash(files), " ".join(files)))
except OSError as e:
log(" warning: could not append to %s: %s" % (logpath, e))
return True, "checked in %d file(s)" % len(files)
def write_bash_stamp(self, files, configs):
"""Write .dsflow/sanity.stamp only if this run covered exactly what dsflow would check in."""
if list(configs) != self.configs:
return False
rc, out, err = self.run(ALL_CHANGES_SH)
allc = [norm(l) for l in out.splitlines() if l.strip()]
if rc != 0 or set(allc) != set(files):
return False
with open(self.path("sanity.stamp"), "w") as fh:
fh.write("stamp_hash=%s\nstamp_epoch=%d\nstamp_when=%s\nstamp_configs=\"%s\"\n" % (
self.content_hash(allc), int(time.time()),
time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime()), " ".join(configs)))
return True
class Snapshot(object):
def __init__(self):
self.changes, self.locks, self.checkout = [], [], []
self.err = None
self.ts = time.time()
self.took = 0.0
def kill_group(p, grace=10):
for sig, wait in ((signal.SIGTERM, grace), (signal.SIGKILL, 5)):
try:
os.killpg(p.pid, sig)
except OSError:
return
t_end = time.time() + wait
while time.time() < t_end:
if p.poll() is not None:
return
time.sleep(0.2)
# ---------------------------------------------------------------------------
# Runner: the detached process that owns one sanity run
# ---------------------------------------------------------------------------
class Runner(object):
def __init__(self, flow):
self.flow = flow
self.jp = flow.path(JOB_FILE)
self.lk = threading.RLock()
self.job = None
self.child = None
self.stop = False
self.done = False
def log(self, msg):
line = "%s %s" % (time.strftime("%H:%M:%S"), msg)
with open(self.flow.path(RUNNER_LOG), "a") as fh:
fh.write(line + "\n")
def save(self):
with self.lk:
self.job["heartbeat"] = time.time()
write_json(self.jp, self.job)
def step(self, key):
for s in self.job["steps"]:
if s["key"] == key:
return s
return {}
def begin(self, key, detail=""):
with self.lk:
s = self.step(key)
s.update(status="running", t0=time.time(), detail=detail)
self.job["phase"] = key
self.log(">> %s" % s.get("label", key))
self.save()
def end(self, key, status="done", detail=None):
with self.lk:
s = self.step(key)
s.update(status=status, t1=time.time())
if detail is not None:
s["detail"] = detail
self.log("<< %s: %s%s" % (s.get("label", key), status, " (%s)" % detail if detail else ""))
self.save()
def fail(self, key, detail):
self.end(key, "failed", detail)
raise StepFailed(detail)
def cancelled(self):
return self.stop or os.path.exists(self.flow.path(JOB_CANCEL))
def check_cancel(self):
if self.cancelled():
raise Cancelled()
def cmd(self, fn, *args, **kw):
self.log(" $ %s %s" % (fn, " ".join(shlex.quote(a) for a in args)))
rc, out = self.flow.act(fn, *args, **kw)
for line in out.splitlines():
self.log(" " + line)
return rc, out
def _signal(self, signum, frame):
self.stop = True
if self.child is not None:
try:
os.killpg(self.child.pid, signal.SIGTERM)
except OSError:
pass
def _heartbeat(self):
while not self.done:
time.sleep(5)
if not self.done:
try:
self.save()
except OSError:
pass
def main(self):
lockfh = open(self.flow.path(JOB_LOCK), "a")
try:
fcntl.flock(lockfh, fcntl.LOCK_EX | fcntl.LOCK_NB)
except OSError:
print("dsflow_tui: another sanity runner is active in this workspace")
return 1
self.job = read_json(self.jp)
if not self.job or self.job.get("status") != "queued":
print("dsflow_tui: no queued job in %s" % self.jp)
return 1
for sig in (signal.SIGTERM, signal.SIGINT, signal.SIGHUP):
signal.signal(sig, self._signal)
open(self.flow.path(RUNNER_LOG), "w").close()
self.job.update(status="running", pid=os.getpid(), host=socket.gethostname(), started=time.time())
self.log("run %s by %s on %s" % (self.job["id"], ME, socket.gethostname()))
self.save()
threading.Thread(target=self._heartbeat, daemon=True).start()
try:
self.execute()
self.job["status"] = "passed"
except Cancelled:
self.job["status"] = "cancelled"
self.job["summary"] = "cancelled by user"
except StepFailed as e:
self.job["status"] = "failed"
self.job["summary"] = str(e)
except Exception as e: # noqa - the runner must always release locks
self.job["status"] = "error"
self.job["summary"] = "runner error: %s" % e
self.log(traceback.format_exc())
finally:
final = self.job["status"]
with self.lk:
for s in self.job["steps"]:
if s["status"] == "running":
s.update(status="cancelled" if final == "cancelled" else "failed", t1=time.time())
self.release_locks()
with self.lk:
for s in self.job["steps"]:
if s["status"] == "pending":
s["status"] = "skipped"
self.job["finished"] = time.time()
self.job["phase"] = "finished"
self.done = True
self.log("finished: %s - %s" % (self.job["status"], self.job.get("summary", "")))
self.save()
try:
os.remove(self.flow.path(JOB_CANCEL))
except OSError:
pass
return 0 if self.job["status"] == "passed" else 1
def execute(self):
j, flow = self.job, self.flow
mods, news = j["files"], j["new_files"]
self.begin("validate")
missing = [f for f in news if not os.path.exists(flow.wpath(f))]
if missing:
self.fail("validate", "new file(s) missing: %s" % ", ".join(missing))
if mods:
stale = flow.stale_of(mods)
if stale:
self.fail("validate", "checked in by someone else since you started (dsflow rebase): %s" %
", ".join("%s %s->%s" % (f, v[0], v[1]) for f, v in sorted(stale.items())))
holders = flow.holders(mods)
others = dict((f, h) for f, h in holders.items() if h and h != ME)
if others:
self.fail("validate", "locked by others: %s" % ", ".join("%s (%s)" % i for i in sorted(others.items())))
j["preheld"] = sorted(f for f, h in holders.items() if h == ME)
self.end("validate", detail="%d modified, %d new" % (len(mods), len(news)))
if mods:
self.begin("lock")
for f in mods:
self.check_cancel()
if f in j["preheld"]:
continue
rc, out = self.cmd("ds_lock", f)
if rc != 0:
self.fail("lock", "could not lock %s: %s" % (f, last_line(out) or "rc=%d" % rc))
with self.lk:
j["locked_by_job"].append(f)
self.save()
self.end("lock", detail="%d locked, %d already yours" % (len(j["locked_by_job"]), len(j["preheld"])))
if j.get("refresh"):
self.check_cancel()
self.begin("refresh")
rc, out = self.cmd("ds_refresh", timeout=7200)
if rc != 0:
self.fail("refresh", "refresh to %s failed: %s" % (flow.trunk, last_line(out)))
self.end("refresh")
j["hashes"] = dict((f, sha1_file(flow.wpath(f))) for f in mods + news)
self.save()
hist = read_json(flow.path(HISTORY), {})
for cfg in j["configs"]:
self.check_cancel()
key = "sanity:" + cfg
logp = flow.path("sanity_%s.log" % cfg)
self.step(key)["log"] = logp
self.begin(key)
rc = self.run_sanity(cfg, logp)
if rc is None:
raise Cancelled()
if rc != 0:
self.fail(key, "sanity FAILED for %s (exit %d) - see %s" % (cfg, rc, os.path.relpath(logp, flow.ws)))
dur = time.time() - self.step(key)["t0"]
hist[cfg] = dur
write_json(flow.path(HISTORY), hist)
self.end(key, detail="passed in %s" % fmt_dur(dur))
j["sanity_ok"] = True
j["sanity_epoch"] = time.time()
self.save()
try:
if flow.write_bash_stamp(mods + news, j["configs"]):
self.log("wrote .dsflow/sanity.stamp - `dsflow checkin` will accept this run too")
except OSError as e:
self.log("could not write sanity.stamp: %s" % e)
if j["mode"] != "checkin":
j["summary"] = "sanity passed on %s - locks released; check in within %s (key c)" % (
" ".join(j["configs"]), fmt_dur(flow.max_age))
return
self.begin("verify")
changed = [f for f in mods + news if sha1_file(flow.wpath(f)) != j["hashes"].get(f)]
if changed:
self.fail("verify", "edited while sanity ran, NOT checked in: %s" % ", ".join(changed))
stale = flow.stale_of(mods)
if stale:
self.fail("verify", "went stale on Trunk during the run, NOT checked in: %s" % ", ".join(sorted(stale)))
self.end("verify")
self.begin("checkin")
ok, msg = flow.checkin(j["msg"], mods, news, self.log)
if not ok:
self.fail("checkin", msg)
self.end("checkin", detail=msg)
j["checked_in"] = True
if j.get("tag"):
self.begin("tag")
rc, out = self.cmd("ds_tag", j["tag"], *(mods + news))
if rc != 0:
self.fail("tag", "checked in, but tagging '%s' failed: %s" % (j["tag"], last_line(out)))
self.end("tag", detail="%d file(s)" % len(mods + news))
j["summary"] = "sanity passed on %s - checked in %d file(s)%s" % (
" ".join(j["configs"]), len(mods + news), " and tagged %s" % j["tag"] if j.get("tag") else "")
def run_sanity(self, cfg, logp):
"""Returns the exit code, or None if the run was cancelled."""
flow, cmd = self.flow, self.job.get("sanity_cmd")
if cmd:
snippet, args = 'eval "$1"', [cmd.replace("{cfg}", shlex.quote(cfg)).replace("{ws}", shlex.quote(flow.ws))]
else:
snippet, args = 'run_sanity "$1"', [cfg]
with open(logp, "w") as fh:
fh.write("# dsflow_tui sanity [%s] %s by %s\n# %s\n" % (
cfg, time.strftime("%Y-%m-%d %H:%M:%S"), ME, args[0] if cmd else "run_sanity %s" % cfg))
self.log(" sanity [%s] -> %s" % (cfg, logp))
with open(logp, "ab") as out:
self.child = subprocess.Popen(flow.argv(snippet, args), stdin=subprocess.DEVNULL, stdout=out,
stderr=subprocess.STDOUT, cwd=flow.ws,
env=flow.env({"DSFLOW_CFG": cfg}), start_new_session=True)
with self.lk:
self.job["child_pid"] = self.child.pid # lets the TUI stop it if this runner dies
self.save()
try:
while True:
rc = self.child.poll()
if rc is not None:
return rc
if self.cancelled():
self.log(" cancelling sanity [%s]" % cfg)
kill_group(self.child)
return None
time.sleep(0.5)
finally:
self.child = None
with self.lk:
self.job.pop("child_pid", None)
def release_locks(self):
j = self.job
mine = []
if j.get("locked_by_job"):
self.begin("unlock")
holders = self.flow.holders(j["locked_by_job"])
mine = [f for f in j["locked_by_job"] if holders.get(f) == ME]
if mine:
rc, out = self.cmd("ds_unlock", *mine)
if rc != 0:
j["summary"] = "%s | WARNING: could not release locks on %s: %s" % (
j.get("summary", ""), ", ".join(mine), last_line(out))
self.end("unlock", "failed", "release by hand: dsflow release %s" % " ".join(mine))
return
j["released"] = mine
self.end("unlock", detail="%d released" % len(mine) if mine else "already released by check-in")
else:
with self.lk:
s = self.step("unlock")
s.update(status="skipped", detail="run took no locks")
def new_job(flow, mods, news, configs, mode, msg, tag, refresh):
hist = read_json(flow.path(HISTORY), {})
steps = [dict(key="validate", label="Check freshness & locks")]
if mods:
steps.append(dict(key="lock", label="Lock %d file(s)" % len(mods)))
if refresh:
steps.append(dict(key="refresh", label="Refresh to %s" % flow.trunk))
for cfg in configs:
steps.append(dict(key="sanity:" + cfg, label="Sanity %s" % cfg, kind="sanity", est=hist.get(cfg)))
if mode == "checkin":
steps.append(dict(key="verify", label="Verify files unchanged"))
steps.append(dict(key="checkin", label="Check in %d file(s)" % (len(mods) + len(news))))
if tag:
steps.append(dict(key="tag", label="Tag %s" % tag))
steps.append(dict(key="unlock", label="Release run locks"))
for s in steps:
s.setdefault("kind", "action")
s.update(status="pending", detail="", t0=None, t1=None)
now = time.time()
return dict(id=time.strftime("%Y%m%d-%H%M%S"), user=ME, host=socket.gethostname(), created=now,
heartbeat=now, status="queued", phase="queued", mode=mode, msg=msg, tag=tag,
refresh=refresh, files=mods, new_files=news, configs=configs,
sanity_cmd=flow.sanity_cmd, locked_by_job=[], preheld=[], hashes={}, steps=steps,
summary="")
def spawn_runner(flow, job):
try:
os.remove(flow.path(JOB_CANCEL))
except OSError:
pass
write_json(flow.path(JOB_FILE), job)
argv = [sys.executable, os.path.abspath(__file__), "--ws", flow.ws, "--conf", flow.conf]
if flow.cli_sanity_cmd:
argv += ["--sanity-cmd", flow.cli_sanity_cmd]
argv.append("_runjob")
with open(flow.path(RUNNER_OUT), "ab") as out:
subprocess.Popen(argv, stdin=subprocess.DEVNULL, stdout=out, stderr=subprocess.STDOUT,
cwd=flow.ws, env=flow.env(), start_new_session=True, close_fds=True)
def runner_alive(flow):
"""True if some process holds the runner flock (same host / working NFS locks)."""
try:
with open(flow.path(JOB_LOCK), "a") as fh:
fcntl.flock(fh, fcntl.LOCK_EX | fcntl.LOCK_NB)
fcntl.flock(fh, fcntl.LOCK_UN)
return False
except OSError:
return True
# ---------------------------------------------------------------------------
# TUI look & feel
# ---------------------------------------------------------------------------
class G(object):
"""Glyphs; ASCII fallbacks are swapped in when the locale is not UTF-8."""
h, v, tl, tr, bl, br = u"─", u"│", u"╭", u"╮", u"╰", u"╯"
on, off, dot, ring = u"◉", u"○", u"●", u"○"
full, empty, part = u"█", u"░", u"▓"
ok, bad, run, pend, skip, warn = u"✔", u"✘", u"▶", u"·", u"–", u"▲"
arrow, ell, diamond, sep = u"→", u"…", u"◆", u"│"
spin = u"⠋⠙⠹⠸⠼⠴⠦⠧⠇⠏"
@classmethod
def ascii(cls):
cls.h, cls.v, cls.tl, cls.tr, cls.bl, cls.br = "-", "|", "+", "+", "+", "+"
cls.on, cls.off, cls.dot, cls.ring = "*", ".", "*", "o"
cls.full, cls.empty, cls.part = "#", "-", "="
cls.ok, cls.bad, cls.run, cls.pend, cls.skip, cls.warn = "+", "x", ">", ".", "-", "!"
cls.arrow, cls.ell, cls.diamond, cls.sep = ">", "~", "*", "|"
cls.spin = "|/-\\"
class C(object):
"""Curses attributes, filled in by init_colors()."""
COLOR_SPEC = (
# name fg256 bg256 fg8 bg8 extra
("accent", 75, None, "CYAN", None, 0),
("good", 114, None, "GREEN", None, 0),
("bad", 203, None, "RED", None, 0),
("warn", 221, None, "YELLOW", None, 0),
("dim", 244, None, "WHITE", None, "DIM"),
("hot", 177, None, "MAGENTA", None, 0),
("title", 231, 24, "WHITE", "BLUE", "BOLD"),
("cursor", 231, 238, "BLACK", "CYAN", 0),
("tab_on", 16, 75, "BLACK", "CYAN", "BOLD"),
("tab_off", 250, 236, "WHITE", None, 0),
("key", 16, 250, "BLACK", "WHITE", "BOLD"),
("keytext", 248, None, "WHITE", None, 0),
("bar", 75, None, "CYAN", None, 0),
("barbg", 238, None, "WHITE", None, "DIM"),
("rule", 238, None, "WHITE", None, "DIM"),
("toast_ok", 16, 114, "BLACK", "GREEN", "BOLD"),
("toast_bad", 231, 160, "WHITE", "RED", "BOLD"),
("toast_info", 16, 75, "BLACK", "CYAN", "BOLD"),
("box", 75, 236, "CYAN", "BLACK", 0),
("panel", 252, 236, "WHITE", "BLACK", 0),
("p_dim", 245, 236, "WHITE", "BLACK", 0),
("p_warn", 221, 236, "YELLOW", "BLACK", 0),
("p_bad", 203, 236, "RED", "BLACK", 0),
("p_good", 114, 236, "GREEN", "BLACK", 0),
("p_accent", 75, 236, "CYAN", "BLACK", "BOLD"),
("p_focus", 231, 24, "BLACK", "CYAN", 0),
("p_field", 231, 238, "BLACK", "WHITE", 0),
("badge_run", 16, 75, "BLACK", "CYAN", "BOLD"),
("badge_ok", 16, 114, "BLACK", "GREEN", "BOLD"),
("badge_bad", 231, 160, "WHITE", "RED", "BOLD"),
("badge_warn", 16, 221, "BLACK", "YELLOW", "BOLD"),
)
def init_colors():
extra = {0: 0, "BOLD": curses.A_BOLD, "DIM": curses.A_DIM}
if not curses.has_colors():
for name, _, bg, _, _, ex in COLOR_SPEC:
setattr(C, name, (curses.A_REVERSE if bg else 0) | extra[ex])
return
curses.start_color()
default = -1
try:
curses.use_default_colors()
except curses.error:
default = curses.COLOR_BLACK
rich = curses.COLORS >= 256
for i, (name, f256, b256, f8, b8, ex) in enumerate(COLOR_SPEC, 1):
if rich:
fg, bg = f256, (default if b256 is None else b256)
ex = 0 if ex == "DIM" else ex
else:
fg = getattr(curses, "COLOR_" + f8)
bg = default if b8 is None else getattr(curses, "COLOR_" + b8)
try:
curses.init_pair(i, fg, bg)
setattr(C, name, curses.color_pair(i) | extra[ex])
except curses.error:
setattr(C, name, extra[ex])
def put(scr, y, x, text, attr=0, maxw=None):
"""addstr that clips instead of raising; returns the x after the text."""
H, W = scr.getmaxyx()
if y < 0 or y >= H or x < 0 or x >= W:
return x
lim = W - x if maxw is None else min(maxw, W - x)
if y == H - 1:
lim = min(lim, W - x - 1)
if lim <= 0 or not text:
return x
text = text[:lim]
try:
scr.addstr(y, x, text, attr)
except curses.error:
pass
return x + len(text)
def puts(scr, y, x, segs, maxw):
end = x + maxw
for text, attr in segs:
if x >= end:
break
x = put(scr, y, x, text, attr, end - x)
return x
def fit(text, width):
if width <= 0:
return ""
return text if len(text) <= width else text[:max(0, width - 1)] + G.ell
def fit_left(text, width):
if width <= 0:
return ""
return text if len(text) <= width else G.ell + text[-(width - 1):]
def seg_len(segs):
return sum(len(t) for t, _ in segs)
def bar(frac, width):
"""[(text, attr)] progress bar; frac None = indeterminate sweep."""
if width <= 0:
return []
if frac is None:
pos = int(time.time() * 8) % (width * 2)
pos = pos if pos < width else 2 * width - pos - 1
cells = [G.empty] * width
for i in range(max(0, pos - 1), min(width, pos + 2)):
cells[i] = G.part
return [("".join(cells), C.bar)]
n = int(round(max(0.0, min(1.0, frac)) * width))
return [(G.full * n, C.bar), (G.empty * (width - n), C.barbg)]
def normkey(k):
if isinstance(k, str):
return {"\n": "ENTER", "\r": "ENTER", "\x1b": "ESC", "\t": "TAB", "\x7f": "BS", "\b": "BS",
"\x15": "CLEAR"}.get(k, k)
return {curses.KEY_UP: "UP", curses.KEY_DOWN: "DOWN", curses.KEY_LEFT: "LEFT", curses.KEY_RIGHT: "RIGHT",
curses.KEY_NPAGE: "PGDN", curses.KEY_PPAGE: "PGUP", curses.KEY_HOME: "HOME", curses.KEY_END: "END",
curses.KEY_ENTER: "ENTER", curses.KEY_BACKSPACE: "BS", curses.KEY_DC: "DEL",
curses.KEY_BTAB: "BTAB", curses.KEY_RESIZE: "RESIZE"}.get(k)
ESC_SEQS = {"A": "UP", "B": "DOWN", "C": "RIGHT", "D": "LEFT", "H": "HOME", "F": "END", "Z": "BTAB",
"5~": "PGUP", "6~": "PGDN", "3~": "DEL", "1~": "HOME", "4~": "END"}
def getkey(scr):
try:
k = normkey(scr.get_wch())
except curses.error:
return None
if k != "ESC":
return k
# a bare ESC, or an escape sequence terminfo didn't know (tmux/screen/odd $TERM)
seq = ""
scr.nodelay(True)
try:
while len(seq) < 4:
try:
c = scr.get_wch()
except curses.error:
break
if not isinstance(c, str):
break
seq += c
if seq[-1].isalpha() or seq[-1] == "~":
break
finally:
scr.nodelay(False)
scr.timeout(200)
if not seq:
return "ESC"
return ESC_SEQS.get(seq[1:]) if seq[0] in "[O" else None
# ---------------------------------------------------------------------------
# modal form: notes + check groups, radios, toggles and text fields
# ---------------------------------------------------------------------------
class Form(object):
NOTE_ATTR = {"warn": "p_warn", "bad": "p_bad", "good": "p_good", "dim": "p_dim", "accent": "p_accent"}
def __init__(self, title, notes=(), fields=(), width=78, hint=None):
self.title = title
self.notes = list(notes)
self.fields = []
for f in fields:
f = dict(f)
if f["type"] == "check":
f["value"] = list(f["value"])
if f["type"] == "text":
f["pos"] = len(f["value"])
self.fields.append(f)
self.width = width
self.focus = 0
self.err = None
self.hint = hint
def items(self):
out = []
for i, f in enumerate(self.fields):
if f["type"] == "check":
out += [(i, j) for j in range(len(f["options"]))]
else:
out.append((i, None))
return out
def values(self):
return dict((f["key"], f["value"]) for f in self.fields)
def run(self, app, validate=None):
while True:
app.poll()
app.draw(flush=False)
self.draw(app.scr)
app.scr.refresh()
k = getkey(app.scr)
if k is None or k == "RESIZE":
continue
items = self.items()
if k == "ESC" or (not items and k in ("q", "Q")):
return None
if k == "ENTER":
vals = self.values()
self.err = validate(vals) if validate else None
if not self.err:
return vals
continue
if not items:
continue
if k in ("TAB", "DOWN"):
self.focus = (self.focus + 1) % len(items)
continue
if k in ("BTAB", "UP"):
self.focus = (self.focus - 1) % len(items)
continue
fi, oj = items[self.focus]
f = self.fields[fi]
t = f["type"]
if t == "text":
v, p = f["value"], f["pos"]
if k == "LEFT":
p = max(0, p - 1)
elif k == "RIGHT":
p = min(len(v), p + 1)
elif k == "HOME":
p = 0
elif k == "END":
p = len(v)
elif k == "BS" and p > 0:
v, p = v[:p - 1] + v[p:], p - 1
elif k == "DEL":
v = v[:p] + v[p + 1:]
elif k == "CLEAR":
v, p = "", 0
elif isinstance(k, str) and len(k) == 1 and k.isprintable():
v, p = v[:p] + k + v[p:], p + 1
f["value"], f["pos"] = v, p
elif t == "check" and k == " ":
opt = f["options"][oj]
if opt in f["value"]:
f["value"].remove(opt)
else:
f["value"] = [o for o in f["options"] if o in f["value"] or o == opt]
elif t == "toggle" and k in (" ", "LEFT", "RIGHT"):
f["value"] = not f["value"]
elif t == "radio" and k in (" ", "RIGHT", "l"):
f["value"] = (f["value"] + 1) % len(f["options"])
elif t == "radio" and k in ("LEFT", "h"):
f["value"] = (f["value"] - 1) % len(f["options"])
def draw(self, scr):
H, W = scr.getmaxyx()
w = max(30, min(self.width, W - 4))
inner = w - 4
items = self.items()
focus_item = items[self.focus] if items else None
lines = [[]]
for text, kind in self.notes:
attr = getattr(C, self.NOTE_ATTR.get(kind, "panel"))
if kind == "bold":
attr = C.panel | curses.A_BOLD
if not text:
lines.append([])
continue
indent = " " if text.startswith((" ", u"• ", "- ")) else ""
for chunk in textwrap.wrap(text, inner, subsequent_indent=indent, drop_whitespace=False) or [""]:
lines.append([(chunk, attr)])
if self.fields:
lines.append([])
lw = max([len(f["label"]) for f in self.fields if f["type"] in ("radio", "text")] + [0]) + 2
for i, f in enumerate(self.fields):
t = f["type"]
if t == "check":
lines.append([(f["label"], C.panel | curses.A_BOLD)])
for j, opt in enumerate(f["options"]):
on = opt in f["value"]
lines.append(dict(focus=(i, j) == focus_item, segs=[
(" ", C.panel), (G.on if on else G.off, C.p_accent if on else C.p_dim), (" " + opt, C.panel)]))
elif t == "radio":
segs = [(f["label"].ljust(lw), C.panel | curses.A_BOLD)]
for j, opt in enumerate(f["options"]):
sel = j == f["value"]
segs.append(((G.dot if sel else G.ring) + " " + opt + " ", C.p_accent if sel else C.p_dim))
lines.append(dict(focus=(i, None) == focus_item, segs=segs))
elif t == "toggle":
on = f["value"]
lines.append(dict(focus=(i, None) == focus_item, segs=[
(G.on if on else G.off, C.p_accent if on else C.p_dim), (" " + f["label"], C.panel)]))
elif t == "text":
fw = max(8, inner - lw)
start = max(0, f["pos"] - fw + 1)
vis = f["value"][start:start + fw].ljust(fw)
focused = (i, None) == focus_item
lines.append(dict(focus=focused, segs=[(f["label"].ljust(lw), C.panel | curses.A_BOLD)],
field=(vis, f["pos"] - start if focused else None)))
if self.err:
lines += [[], [(G.bad + " " + self.err, C.p_bad | curses.A_BOLD)]]
lines.append([])
hint = self.hint or (u"⏎ confirm esc cancel ↑↓/tab move space toggle ←→ choose"
if items else u"⏎/esc close")
if G.h == "-":
hint = hint.replace(u"⏎", "enter").replace(u"↑↓", "up/dn").replace(u"←→", "left/right")
lines.append([(hint, C.p_dim)])
h = min(len(lines) + 2, H - 2)
y0, x0 = max(0, (H - h) // 2), max(0, (W - w) // 2)
for y in range(y0, y0 + h):
put(scr, y, x0, " " * w, C.panel)
put(scr, y, x0, G.v, C.box)
put(scr, y, x0 + w - 1, G.v, C.box)
put(scr, y0, x0, G.tl + G.h * (w - 2) + G.tr, C.box)
put(scr, y0 + h - 1, x0, G.bl + G.h * (w - 2) + G.br, C.box)
put(scr, y0, x0 + 2, " %s " % fit(self.title, w - 6), C.p_accent)
for n, line in enumerate(lines[:h - 2]):
y = y0 + 1 + n
if isinstance(line, list):
line = dict(segs=line)
if line.get("focus"):
put(scr, y, x0 + 1, " " * (w - 2), C.p_focus)
segs = [(t, C.p_focus | (a & curses.A_BOLD)) for t, a in line["segs"]]
else:
segs = line["segs"]
x = puts(scr, y, x0 + 2, segs, inner)
if "field" in line:
vis, cur = line["field"]
put(scr, y, x, vis, C.p_field, x0 + 2 + inner - x)
if cur is not None:
put(scr, y, x + cur, vis[cur] if cur < len(vis) else " ", C.p_field | curses.A_REVERSE)
# ---------------------------------------------------------------------------
# the app
# ---------------------------------------------------------------------------
class App(object):
VIEWS = (("changes", "Changes"), ("locks", "Locks"), ("checkout", "Checked-out"),
("sanity", "Sanity run"), ("logs", "Logs"))
FILE_VIEWS = ("changes", "locks", "checkout")
def __init__(self, scr, flow, auto_refresh):
self.scr, self.flow, self.auto_refresh = scr, flow, auto_refresh
self.view = 0
self.cur = dict((k, 0) for k, _ in self.VIEWS)
self.top = dict((k, 0) for k, _ in self.VIEWS)
self.sel = set()
self.snap = None
self.refreshing = False
self.last_refresh = 0
self.busy = None
self.toast = None
self.activity = []
self.job, self.jstate, self._jmtime, self._locks_seen = None, "none", None, None
self.log_src, self.log_off = 0, 0
self.last_msg = ""
# -- background work ------------------------------------------------------
def note(self, text, kind="info"):
self.toast = (text, kind, time.time())
self.activity.append((time.time(), kind, text))
del self.activity[:-500]
def logact(self, text):
self.activity.append((time.time(), "log", text))
def refresh(self):
if self.refreshing:
return
self.refreshing = True
self.last_refresh = time.time()
def work():
try:
snap = self.flow.snapshot()
except Exception as e: # noqa
snap = Snapshot()
snap.err = str(e)
self.snap = snap
known = set(r["path"] for r in snap.changes + snap.locks + snap.checkout)
self.sel &= known
if snap.err:
self.note("refresh failed: %s" % snap.err, "bad")
self.refreshing = False
threading.Thread(target=work, daemon=True).start()
def background(self, label, fn):
if self.busy:
self.note("busy: %s - wait for it to finish" % self.busy, "bad")
return
self.busy = label
self.logact(label + " ...")
def work():
try:
ok, msg = fn()
except Exception as e: # noqa
ok, msg = False, "%s failed: %s" % (label, e)
self.busy = None
self.note(msg, "ok" if ok else "bad")
self.refresh()
threading.Thread(target=work, daemon=True).start()
def poll(self):
p = self.flow.path(JOB_FILE)
try:
mt = os.stat(p).st_mtime
except OSError:
mt = None
if mt != self._jmtime:
self._jmtime = mt
job = read_json(p) if mt else None
if job or mt is None:
self.job = job
prev, self.jstate = self.jstate, job_state(self.job)
if self.jstate == "active" and self._locks_seen != self.job["id"] and \
any(s["key"] == "lock" and s["status"] == "done" for s in self.job["steps"]):
self._locks_seen = self.job["id"]
self.refresh() # show the run's locks as soon as it has them
if prev == "active" and self.jstate == "done":
st = self.job.get("status")
if self.job.get("checked_in"):
self.sel -= set(self.job["files"] + self.job["new_files"])
self.note("sanity %s: %s" % (st.upper(), self.job.get("summary", "")),
"ok" if st == "passed" else "bad")
try:
curses.beep()
except curses.error:
pass
self.refresh()
if self.auto_refresh and not self.refreshing and time.time() - self.last_refresh > self.auto_refresh:
self.refresh()
# -- rows -----------------------------------------------------------------
def vkey(self):
return self.VIEWS[self.view][0]
def rows(self, key=None):
key = key or self.vkey()
if not self.snap or key not in self.FILE_VIEWS:
return []
return getattr(self.snap, key if key != "checkout" else "checkout")
def cursor_row(self):
rows = self.rows()
if not rows:
return None
self.cur[self.vkey()] = min(self.cur[self.vkey()], len(rows) - 1)
return rows[self.cur[self.vkey()]]
def pick(self, rows, use_cursor=True):
chosen = [r for r in rows if r["path"] in self.sel]
if chosen:
return chosen
cur = self.cursor_row() if use_cursor else None
if cur is not None and any(r["path"] == cur["path"] for r in rows):
return [r for r in rows if r["path"] == cur["path"]]
return []
def job_files(self):
if self.jstate != "active":
return set()
return set(self.job.get("files", []) + self.job.get("new_files", []))
# -- drawing --------------------------------------------------------------
def draw(self, flush=True):
scr = self.scr
scr.erase()
H, W = scr.getmaxyx()
if H < 14 or W < 64:
put(scr, 0, 0, "dsflow_tui: terminal too small (%dx%d, need 64x14)" % (W, H), C.warn)
if flush:
scr.refresh()
return
self.draw_title(0, W)
self.draw_tabs(1, W)
put(scr, 2, 0, G.h * W, C.rule)
body = (3, H - 3)
v = self.vkey()
if v in self.FILE_VIEWS:
self.draw_files(v, body[0], body[1], W)
elif v == "sanity":
self.draw_sanity(body[0], body[1], W)
else:
self.draw_logs(body[0], body[1], W)
put(scr, H - 3, 0, G.h * W, C.rule)
self.draw_status(H - 2, W)
self.draw_footer(H - 1, W)
if flush:
scr.refresh()
def spinner(self):
return G.spin[int(time.time() * 10) % len(G.spin)]
def draw_title(self, y, W):
put(self.scr, y, 0, " " * W, C.title)
home = os.path.expanduser("~")
ws = self.flow.ws.replace(home, "~", 1) if self.flow.ws.startswith(home) else self.flow.ws
left = u" %s dsflow %s ws %s %s %s %s %s %s green tag: %s " % (
G.diamond, G.sep, fit_left(ws, max(12, W // 3)), G.sep, ME, G.sep, self.flow.trunk, G.sep, self.flow.working_tag)
if self.refreshing:
right = u"%s querying DesignSync… " % self.spinner()
elif self.snap:
right = "updated %s (%.1fs) " % (fmt_clock(self.snap.ts), self.snap.took)
else:
right = ""
put(self.scr, y, 0, fit(left, W - len(right) - 1), C.title)
put(self.scr, y, W - len(right) - 1, right, C.title)
def draw_tabs(self, y, W):
s = self.snap
counts = {
"changes": len(s.changes) if s else None,
"locks": len([r for r in s.locks if r["holder"] == ME]) if s else None,
"checkout": len(s.checkout) if s else None,
}
x = 1
for i, (k, label) in enumerate(self.VIEWS):
badge = ""
if counts.get(k) is not None:
badge = " %d" % counts[k]
elif k == "sanity":
badge = " " + {"active": self.spinner(), "orphaned": G.warn,
"done": G.ok if (self.job or {}).get("status") == "passed" else G.bad,
"none": ""}[self.jstate]
text = " %d %s%s " % (i + 1, label, badge.rstrip())
x = put(self.scr, y, x, text, C.tab_on if i == self.view else C.tab_off) + 1
def holder_cell(self, h):
if not h:
return [(u"—" if G.h != "-" else "-", C.dim)]
if h == ME:
return [("you", C.good | curses.A_BOLD)]
return [(h, C.bad | curses.A_BOLD)]
def draw_files(self, v, y0, y1, W):
rows = self.rows(v)
jf = self.job_files()
if v == "changes":
cols = [("", 2), ("St", 3), ("File", None), (u"Base → Latest" if G.h != "-" else "Base > Latest", 17),
("Lock", 12), ("Flags", 18)]
elif v == "locks":
cols = [("", 2), ("File", None), ("Holder", 14), ("Local copy", 12), ("Flags", 14)]
else:
cols = [("", 2), ("File", None), ("Local copy", 12), ("Flags", 14)]
fixed = sum(c[1] for c in cols if c[1]) + len(cols)
widths = [c[1] if c[1] else max(10, W - fixed - 1) for c in cols]
def cells(r):
selected = r["path"] in self.sel
out = [[(G.on if selected else G.off, C.accent | curses.A_BOLD if selected else C.dim)]]
flags = []
if r.get("hot"):
flags.append(("HOT", C.hot | curses.A_BOLD))
if v == "changes":
out.append([("M", C.warn | curses.A_BOLD)] if r["kind"] == "M" else [("A", C.good | curses.A_BOLD)])
out.append([(r["path"], 0)])
if r["kind"] == "A":
out.append([("new file", C.dim)])
elif r["unknown"]:
out.append([("%s %s %s" % (r["base"] or "?", G.arrow, r["latest"] or "?"), C.warn)])
flags.append(("?VER", C.warn))
elif r["stale"]:
out.append([("%s %s %s" % (r["base"], G.arrow, r["latest"]), C.bad | curses.A_BOLD)])
flags.append(("STALE", C.bad | curses.A_BOLD))
else:
out.append([(r["base"], 0), (" latest", C.dim)])
out.append(self.holder_cell(r["holder"]))
if not r["exists"]:
flags.append(("MISSING", C.bad | curses.A_BOLD))
else:
out.append([(r["path"], 0)])
if v == "locks":
out.append(self.holder_cell(r["holder"]) if r["holder"] else [("free", C.good)])
out.append([("modified", C.warn)] if r["modified"] else [("clean", C.dim)])
if r["path"] in jf:
flags.append(("IN-RUN", C.accent | curses.A_BOLD))
fl = []
for t, a in flags:
fl += [(t, a), (" ", 0)]
out.append(fl)
return out
# header
x = 1
for (title, _), cw in zip(cols, widths):
put(self.scr, y0, x, fit(title, cw), C.dim | curses.A_BOLD)
x += cw + 1
top_y, n_vis = y0 + 1, y1 - y0 - 1
if self.snap is None:
put(self.scr, top_y + 1, 3, u"%s Querying DesignSync for workspace state…" % self.spinner(), C.accent)
return
if not rows:
msg = {"changes": u"%s No local changes - workspace matches the vault." % G.ok,
"locks": "No locks held by you, and no hot files configured.",
"checkout": "No checked-out (writable, unlocked) files."}[v]
if self.snap.err:
msg = "%s %s" % (G.bad, self.snap.err)
put(self.scr, top_y + 1, 3, msg, C.bad if self.snap.err else C.good)
if v == "changes":
put(self.scr, top_y + 3, 3, "Brand-new files? press n to register them for check-in.", C.dim)
return
cur = self.cur[v] = max(0, min(self.cur[v], len(rows) - 1))
top = self.top[v]
if cur < top:
top = cur
elif cur >= top + n_vis:
top = cur - n_vis + 1
self.top[v] = top = max(0, min(top, max(0, len(rows) - n_vis)))
for i, r in enumerate(rows[top:top + n_vis]):
y = top_y + i
is_cur = top + i == cur
if is_cur:
put(self.scr, y, 0, " " * W, C.cursor)
x = 1
for c, (cell, cw) in enumerate(zip(cells(r), widths)):
if cols[c][0] == "File":
cell = [(fit_left(cell[0][0], cw), cell[0][1])]
if is_cur:
cell = [(t, C.cursor | (a & curses.A_BOLD)) for t, a in cell]
puts(self.scr, y, x, cell, cw)
x += cw + 1
if len(rows) > n_vis:
info = " %d-%d of %d " % (top + 1, min(len(rows), top + n_vis), len(rows))
put(self.scr, y1, W - len(info) - 2, info, C.dim)
def step_line(self, s, W):
st = s["status"]
running = (G.warn, C.warn | curses.A_BOLD) if self.jstate == "orphaned" else \
(self.spinner(), C.accent | curses.A_BOLD)
glyph, attr = {"pending": (G.pend, C.dim), "running": running,
"done": (G.ok, C.good | curses.A_BOLD), "failed": (G.bad, C.bad | curses.A_BOLD),
"cancelled": (G.skip, C.warn), "skipped": (G.skip, C.dim)}.get(st, ("?", 0))
segs = [(" %s " % glyph, attr), (fit(s["label"], 30).ljust(31),
C.dim if st in ("pending", "skipped") else curses.A_BOLD if st == "running" else 0)]
t0, t1 = s.get("t0"), s.get("t1")
el = (t1 or time.time()) - t0 if t0 else None
if s.get("kind") == "sanity":
est = s.get("est")
if st == "running":
frac = min(0.99, el / est) if est else None
segs += bar(frac, 24)
segs.append((" %3d%%" % (frac * 100) if frac is not None else " ", C.accent))
segs.append((" %s%s" % (fmt_dur(el), " / ~%s" % fmt_dur(est) if est else ""), C.dim))
return segs
if st == "done":
segs += bar(1.0, 24)
elif st == "failed":
segs += [(G.full * 24, C.bad)]
elif st == "pending":
segs += [(G.empty * 24, C.barbg)]
if est:
segs.append((" ~%s" % fmt_dur(est), C.dim))
return segs
segs.append((" ", 0))
if el is not None and st != "running":
segs.append((" %s " % fmt_dur(el), C.dim))
elif st == "running":
segs.append((" %s " % fmt_dur(el), C.accent))
if s.get("detail"):
segs.append((" " + s["detail"], C.bad if st == "failed" else C.dim))
return segs
def badge(self):
j = self.job
if self.jstate == "orphaned":
return " RUNNER LOST ", C.badge_warn
st = j.get("status", "?")
return " %s " % st.upper(), {"passed": C.badge_ok, "failed": C.badge_bad, "error": C.badge_bad,
"cancelled": C.badge_warn}.get(st, C.badge_run)
def draw_sanity(self, y0, y1, W):
scr, j = self.scr, self.job
if not j:
put(scr, y0 + 1, 3, "No sanity run yet.", curses.A_BOLD)
put(scr, y0 + 3, 3, "1. In Changes, mark files with space (or none: the cursor row is used)", C.dim)
put(scr, y0 + 4, 3, "2. Press s - files are locked, sanity runs on every config, and on", C.dim)
put(scr, y0 + 5, 3, " pass they are checked in (or just unlocked). Locks are always released.", C.dim)
return
y = y0
text, attr = self.badge()
x = put(scr, y, 1, "Run %s " % j["id"], curses.A_BOLD)
x = put(scr, y, x + 1, text, attr)
if j.get("host") and j.get("host") != socket.gethostname():
x = put(scr, y, x + 1, " on %s" % j["host"], C.dim)
end = j.get("finished") or time.time()
right = "started %s %s elapsed %s " % (fmt_clock(j.get("started") or j["created"]), G.sep,
fmt_dur(end - (j.get("started") or j["created"])))
put(scr, y, W - len(right) - 1, right, C.dim)
y += 1
if j["mode"] == "checkin":
what = [("On pass: ", C.dim), ("check in", C.good | curses.A_BOLD)]
if j.get("tag"):
what += [(" %s tag " % G.arrow, C.dim), (j["tag"], C.hot | curses.A_BOLD)]
what += [(u" comment: ", C.dim), (u"“%s”" % j.get("msg", "") if G.h != "-" else '"%s"' % j.get("msg", ""), 0)]
else:
what = [("On pass: ", C.dim), ("release locks only", C.warn | curses.A_BOLD),
(" (check in later with c )", C.dim)]
puts(scr, y, 1, what, W - 2)
y += 1
files = j["files"] + j["new_files"]
puts(scr, y, 1, [("Files %d: " % len(files), C.dim),
(fit(", ".join(files), W - 40), 0),
(" locked by run: %d" % len(j.get("locked_by_job", [])), C.accent)], W - 2)
y += 1
put(scr, y, 1, G.h * (W - 2), C.rule)
y += 1
for s in j["steps"]:
if y >= y1:
break
puts(scr, y, 1, self.step_line(s, W), W - 2)
y += 1
if self.jstate == "done" and j.get("summary"):
y += 1
st = j.get("status")
for chunk in textwrap.wrap(j["summary"], W - 6)[:3]:
put(scr, y, 3, chunk, (C.good if st == "passed" else C.bad) | curses.A_BOLD)
y += 1
elif self.jstate == "orphaned":
y += 1
put(scr, y, 3, "%s No heartbeat from the runner for %s. It may have been killed." % (
G.warn, fmt_dur(time.time() - j.get("heartbeat", 0))), C.warn | curses.A_BOLD)
y += 1
put(scr, y, 3, "Press x to release the %d lock(s) it took." % len(j.get("locked_by_job", [])), C.warn)
y += 1
# live log tail for the current / last sanity step
run = [s for s in j["steps"] if s.get("kind") == "sanity" and s.get("log") and s["status"] != "pending"]
y += 1
if run and y < y1 - 2:
s = run[-1]
put(scr, y, 1, G.h * (W - 2), C.rule)
put(scr, y, 3, " log %s %s (5 / Logs for the full log) " % (G.sep, os.path.basename(s["log"])), C.dim)
y += 1
lines = tail_lines(s["log"]) or []
n = y1 - y
for line in lines[-n:] if n > 0 else []:
low = line.lower()
a = C.bad if ("error" in low or "fail" in low) else C.good if "pass" in low else C.dim
put(scr, y, 2, fit(line, W - 4), a)
y += 1
def log_sources(self):
srcs = [("activity", None)]
cfgs = (self.job or {}).get("configs") or self.flow.configs
for cfg in cfgs:
srcs.append((cfg, self.flow.path("sanity_%s.log" % cfg)))
srcs.append(("runner", self.flow.path(RUNNER_LOG)))
return srcs
def draw_logs(self, y0, y1, W):
srcs = self.log_sources()
self.log_src %= len(srcs)
x = 1
for i, (name, _) in enumerate(srcs):
x = put(self.scr, y0, x, " %s " % name, C.tab_on if i == self.log_src else C.tab_off) + 1
put(self.scr, y0, x + 1, u"←→ source ↑↓ scroll End follow" if G.h != "-" else "left/right source", C.dim)
name, path = srcs[self.log_src]
if path is None:
lines = ["%s %s" % (fmt_clock(t), txt) for t, k, txt in self.activity] or ["(no activity yet)"]
else:
lines = tail_lines(path)
if lines is None:
lines = ["(%s does not exist yet)" % path]
n = y1 - y0 - 1
self.log_off = max(0, min(self.log_off, max(0, len(lines) - n)))
end = len(lines) - self.log_off
for i, line in enumerate(lines[max(0, end - n):end]):
low = line.lower()
a = C.bad if ("error" in low or "fail" in low) else C.good if (" pass" in low or "passed" in low) else 0
put(self.scr, y0 + 1 + i, 1, fit(line, W - 2), a)
tag = "following" if self.log_off == 0 else "scrolled %d up" % self.log_off
put(self.scr, y1, W - len(tag) - 3, " %s " % tag, C.dim)
def draw_status(self, y, W):
j, st = self.job, self.jstate
if st == "none":
segs = [(" %s no sanity run yet" % G.ring, C.dim)]
elif st == "orphaned":
segs = [(" %s runner lost - press x to release %d lock(s)" % (G.warn, len(j.get("locked_by_job", []))),
C.warn | curses.A_BOLD)]
elif st == "active":
steps = j["steps"]
cur = next((s for s in steps if s["status"] == "running"), None)
san = [s for s in steps if s.get("kind") == "sanity"]
done = sum(1 for s in san if s["status"] == "done")
frac = None
if cur is not None and cur.get("kind") == "sanity" and cur.get("est") and cur.get("t0"):
frac = min(0.99, (time.time() - cur["t0"]) / cur["est"])
overall = (done + (frac or 0)) / len(san) if san else 0
segs = [(" %s SANITY " % self.spinner(), C.badge_run),
(" %s " % (cur["label"] if cur else j.get("phase", "")), curses.A_BOLD)]
segs += bar(overall if (frac is not None or done) else None, 16)
segs += [(" %d/%d cfg" % (done, len(san)), C.accent),
(" %s %s" % (G.sep, fmt_dur(time.time() - (j.get("started") or j["created"]))), C.dim),
(" %s %d locked by run" % (G.sep, len(j.get("locked_by_job", []))), C.dim)]
else:
text, attr = self.badge()
segs = [(" last run ", C.dim), (text, attr),
(" %s " % fmt_ago(j.get("finished")), C.dim),
(j.get("summary", ""), C.dim)]
right = "%d selected " % len(self.sel)
puts(self.scr, y, 0, segs, W - len(right) - 2)
put(self.scr, y, W - len(right) - 1, right, C.accent if self.sel else C.dim)
KEYS = {
"changes": [("spc", "mark"), ("a", "all"), ("s", "sanity"), ("c", "check in"), ("t", "tag"),
("n", "add new"), ("m", "rebase"), ("r", "refresh"), ("?", "help"), ("q", "quit")],
"locks": [("spc", "mark"), ("u", "unlock"), ("l", "lock"), ("t", "tag"), ("r", "refresh"),
("?", "help"), ("q", "quit")],
"checkout": [("spc", "mark"), ("l", "lock"), ("t", "tag"), ("r", "refresh"), ("?", "help"), ("q", "quit")],
"sanity": [("x", "cancel run"), ("5", "logs"), ("c", "check in"), ("?", "help"), ("q", "quit")],
"logs": [("<>", "source"), ("up/dn", "scroll"), ("End", "follow"), ("?", "help"), ("q", "quit")],
}
def draw_footer(self, y, W):
if self.toast and time.time() - self.toast[2] < 6:
text, kind, _ = self.toast
attr = {"ok": C.toast_ok, "bad": C.toast_bad}.get(kind, C.toast_info)
glyph = {"ok": G.ok, "bad": G.bad}.get(kind, G.dot)
put(self.scr, y, 0, fit(" %s %s" % (glyph, text), W).ljust(W), attr)
return
if self.busy:
put(self.scr, y, 1, u"%s %s…" % (self.spinner(), self.busy), C.accent | curses.A_BOLD)
return
x = 1
for k, desc in self.KEYS[self.vkey()]:
if x + len(k) + len(desc) + 4 >= W:
break
x = put(self.scr, y, x, " %s " % k, C.key)
x = put(self.scr, y, x, " %s " % desc, C.keytext) + 1
# -- dialogs --------------------------------------------------------------
def message(self, title, notes):
Form(title, notes).run(self)
def confirm(self, title, notes):
return Form(title, notes, hint=u"⏎ yes esc no" if G.h != "-" else "enter yes esc no").run(self) is not None
def file_notes(self, paths, limit=8):
out = [(u" • %s" % p if G.h != "-" else " - %s" % p, "") for p in paths[:limit]]
if len(paths) > limit:
out.append((" … and %d more" % (len(paths) - limit), "dim"))
return out
# -- actions --------------------------------------------------------------
def need_snap(self):
if self.snap is None:
self.note("still reading the workspace - one moment", "bad")
return False
return True
def act_sanity(self):
if not self.need_snap():
return
if self.jstate == "active":
return self.note("a sanity run is already in progress (x cancels it)", "bad")
if self.jstate == "orphaned":
return self.note("the previous runner died holding locks - press x to release them first", "bad")
if runner_alive(self.flow):
return self.note("another runner still holds the job lock in this workspace", "bad")
rows = self.pick(self.snap.changes, use_cursor=self.vkey() == "changes")
if not rows:
return self.note("mark files in Changes (space) first", "bad")
mods = [r["path"] for r in rows if r["kind"] == "M"]
news = [r["path"] for r in rows if r["kind"] == "A"]
problems = []
for r in rows:
if r["stale"]:
problems.append((" %s: %s %s %s on Trunk - rebase first (m)" % (r["path"], r["base"], G.arrow, r["latest"]), "bad"))
if r["holder"] and r["holder"] != ME:
problems.append((" %s: locked by %s" % (r["path"], r["holder"]), "bad"))
if not r["exists"]:
problems.append((" %s: registered as new but missing on disk" % r["path"], "bad"))
if problems:
return self.message("Can't start sanity", [("Fix these first:", "bold")] + problems)
chosen = set(mods + news)
others = [r["path"] for r in self.snap.changes if r["path"] not in chosen]
notes = [("%d file(s) will be locked while sanity runs and released when it ends." % len(rows), "bold")]
notes += self.file_notes(mods + news, 6)
if others:
notes += [("", ""), ("%s %d other local change(s) are not marked. They stay in the workspace, so "
"sanity tests them too, but they won't be checked in." % (G.warn, len(others)), "warn")]
unk = [r["path"] for r in rows if r["unknown"] and r["kind"] == "M"]
if unk:
notes.append(("%s couldn't read base/latest version for %d file(s); freshness is unverified." % (
G.warn, len(unk)), "warn"))
if self.flow.sanity_cmd:
notes.append(("sanity command: %s" % self.flow.sanity_cmd, "dim"))
configs = self.flow.configs
if not configs:
return self.message("No sanity configs", [("SANITY_CONFIGS is empty in %s" % self.flow.conf, "bad")])
fields = [
dict(type="check", key="configs", label="Sanity configs", options=configs, value=configs),
dict(type="radio", key="mode", label="On pass", options=["check in", "unlock only"], value=0),
dict(type="text", key="msg", label="Comment", value=self.last_msg),
dict(type="radio", key="tag", label="Then tag", options=["none"] + self.flow.tags, value=0),
dict(type="toggle", key="refresh", label="Refresh unmodified files to %s first" % self.flow.trunk,
value=True),
]
def validate(v):
if not v["configs"]:
return "pick at least one config"
if v["mode"] == 0:
if not v["msg"].strip():
return "a check-in comment is required"
if list(v["configs"]) != configs:
return "check-in needs every config (%s)" % " ".join(configs)
elif v["tag"]:
return "tagging needs 'check in' (tagging now would tag the old vault versions)"
return None
res = Form("Run sanity", notes, fields).run(self, validate)
if res is None:
return
mode = "checkin" if res["mode"] == 0 else "unlock"
self.last_msg = res["msg"]
tag = (["none"] + self.flow.tags)[res["tag"]] if res["tag"] else ""
job = new_job(self.flow, mods, news, list(res["configs"]), mode, res["msg"].strip(), tag, res["refresh"])
try:
spawn_runner(self.flow, job)
except OSError as e:
return self.note("could not start the runner: %s" % e, "bad")
self._jmtime = None
self.note("sanity started on %s for %d file(s)" % (" ".join(job["configs"]), len(rows)), "ok")
self.view = 3
def act_cancel(self):
j = self.job
if self.jstate == "active":
if self.confirm("Cancel sanity run?", [
("Stops the running sanity, then releases the %d lock(s) the run took. Nothing is checked in."
% len(j.get("locked_by_job", [])), "")]):
open(self.flow.path(JOB_CANCEL), "w").write(ME)
self.note("cancel requested - the runner is cleaning up", "info")
elif self.jstate == "orphaned":
locked = j.get("locked_by_job", [])
if not self.confirm("Release the dead runner's locks?", [
("The runner stopped sending heartbeats. Release the lock(s) it took?", "")] + self.file_notes(locked)):
return
def work():
if j.get("child_pid") and j.get("host") == socket.gethostname():
try:
os.killpg(j["child_pid"], signal.SIGTERM) # the orphaned simulation
except OSError:
pass
holders = self.flow.holders(locked)
mine = [f for f in locked if holders.get(f) == ME]
rc, out = self.flow.act("ds_unlock", *mine) if mine else (0, "")
for s in j["steps"]:
if s["status"] == "running":
s.update(status="failed", t1=time.time(), detail="runner lost")
elif s["status"] == "pending":
s["status"] = "skipped"
if s["key"] == "unlock" and rc == 0:
s.update(status="done", detail="%d released from the TUI" % len(mine))
j.update(status="error", finished=time.time(), phase="finished",
summary="runner lost; %d lock(s) released from the TUI" % len(mine))
write_json(self.flow.path(JOB_FILE), j)
return rc == 0, j["summary"] if rc == 0 else "unlock failed: %s" % last_line(out)
self.background("releasing locks", work)
else:
self.note("no sanity run in progress", "info")
def stamp_problems(self, rows):
"""Why the last run does not cover these files as they are now (empty list = ok)."""
j = self.job
if not j or j.get("status") != "passed" or not j.get("sanity_ok"):
return ["no passing sanity run on record"]
probs = []
if list(j["configs"]) != self.flow.configs:
probs.append("last run covered %s, check-in needs %s" % (" ".join(j["configs"]), " ".join(self.flow.configs)))
age = time.time() - j.get("sanity_epoch", 0)
if age > self.flow.max_age:
probs.append("last pass is %s old (limit %s)" % (fmt_dur(age), fmt_dur(self.flow.max_age)))
for r in rows:
h = j.get("hashes", {}).get(r["path"])
if h is None:
probs.append("%s was not part of the last run" % r["path"])
elif sha1_file(self.flow.wpath(r["path"])) != h:
probs.append("%s changed since the last run" % r["path"])
return probs
def act_checkin(self):
if not self.need_snap():
return
if self.jstate == "active":
return self.note("wait for the sanity run to finish - it may check these in itself", "bad")
rows = self.pick(self.snap.changes, use_cursor=self.vkey() == "changes")
if not rows:
return self.note("mark files in Changes (space) first", "bad")
stale = [r for r in rows if r["stale"]]
if stale:
return self.message("Can't check in", [("Went stale on Trunk - rebase (m), then rerun sanity:", "bad")]
+ self.file_notes([r["path"] for r in stale]))
probs = self.stamp_problems(rows)
if probs:
return self.message("Sanity required", [("These files need a passing sanity run first:", "bold")]
+ [(" " + p, "warn") for p in probs]
+ [("", ""), ("Press s and pick 'check in' to test and check in in one go.", "dim")])
mods = [r["path"] for r in rows if r["kind"] == "M"]
news = [r["path"] for r in rows if r["kind"] == "A"]
res = Form("Check in %d file(s)" % len(rows),
[("Sanity passed %s on %s." % (fmt_ago(self.job["sanity_epoch"]), " ".join(self.job["configs"])),
"good")] + self.file_notes(mods + news),
[dict(type="text", key="msg", label="Comment", value=self.job.get("msg") or self.last_msg),
dict(type="radio", key="tag", label="Then tag", options=["none"] + self.flow.tags, value=0)]
).run(self, lambda v: None if v["msg"].strip() else "a check-in comment is required")
if res is None:
return
tag = (["none"] + self.flow.tags)[res["tag"]] if res["tag"] else ""
self.last_msg = res["msg"]
def work():
stale = self.flow.stale_of(mods)
if stale:
return False, "went stale on Trunk: %s - rebase first" % ", ".join(sorted(stale))
probs = self.stamp_problems(rows)
if probs:
return False, probs[0]
ok, msg = self.flow.checkin(res["msg"].strip(), mods, news, self.logact)
if ok and tag:
rc, out = self.flow.act("ds_tag", tag, *(mods + news))
msg += " and tagged %s" % tag if rc == 0 else "; tagging failed: %s" % last_line(out)
ok = rc == 0
if ok:
self.sel -= set(mods + news)
return ok, msg
self.background("checking in %d file(s)" % len(rows), work)
def act_tag(self):
if not self.need_snap():
return
if self.vkey() not in self.FILE_VIEWS:
return self.note("tagging works on files - go to Changes / Locks / Checked-out", "bad")
rows = self.pick(self.rows())
if not rows:
return self.note("mark files (space) first", "bad")
paths = [r["path"] for r in rows if r.get("kind") != "A"]
skipped = [r["path"] for r in rows if r.get("kind") == "A"]
if not paths:
return self.note("new files aren't in the vault yet - check them in before tagging", "bad")
tags = self.flow.tags
if not tags:
return self.note("no tags configured (DSFLOW_TAGS in dsflow.conf)", "bad")
modified = [r["path"] for r in rows if r.get("kind") == "M" or r.get("modified")]
notes = [("Tag %d file(s) in one batch:" % len(paths), "bold")] + self.file_notes(paths, 6)
if modified:
notes += [("", ""), ("%s %d file(s) have local edits. The tag goes on the vault version your copy is "
"based on, not on your edits. Check in first to tag your changes." % (
G.warn, len(modified)), "warn")]
if skipped:
notes.append(("skipping %d new (unmanaged) file(s)" % len(skipped), "dim"))
res = Form("Batch tag", notes, [dict(type="radio", key="tag", label="Tag", options=tags, value=0)]).run(self)
if res is None:
return
tag = tags[res["tag"]]
def work():
rc, out = self.flow.act("ds_tag", tag, *paths)
for line in out.splitlines():
self.logact(" " + line)
return rc == 0, ("tagged %d file(s) %s" % (len(paths), tag)) if rc == 0 else \
"tag failed: %s" % (last_line(out) or "rc=%d" % rc)
self.background("tagging %d file(s) %s" % (len(paths), tag), work)
def act_lock(self, lock):
if not self.need_snap():
return
if self.vkey() not in self.FILE_VIEWS:
return
rows = [r for r in self.pick(self.rows()) if r.get("kind") != "A"]
if not rows:
return self.note("mark files (space) first", "bad")
if lock:
paths = [r["path"] for r in rows if not r["holder"]]
theirs = [r["path"] for r in rows if r["holder"] and r["holder"] != ME]
if theirs:
self.note("skipping %d file(s) locked by others" % len(theirs), "bad")
if not paths:
return self.note("nothing to lock", "info")
fn, label = "ds_lock", "locking"
else:
in_run = set(self.job.get("locked_by_job", [])) if self.jstate == "active" else set()
paths = [r["path"] for r in rows if r["holder"] == ME and r["path"] not in in_run]
if any(r["path"] in in_run for r in rows):
self.note("files locked by the running sanity are released when it ends", "bad")
if not paths:
return self.note("none of the marked files are locked by you", "info")
if not self.confirm("Release %d lock(s)?" % len(paths),
self.file_notes(paths) + [("", ""), ("Local edits are kept.", "dim")]):
return
fn, label = "ds_unlock", "unlocking"
def work():
rc, out = self.flow.act(fn, *paths)
for line in out.splitlines():
self.logact(" " + line)
return rc == 0, ("%s %d file(s): done" % (label, len(paths))) if rc == 0 else \
"%s failed: %s" % (label, last_line(out) or "rc=%d" % rc)
self.background("%s %d file(s)" % (label, len(paths)), work)
def act_add(self):
def validate(v):
paths = shlex.split(v["paths"]) if v["paths"].strip() else []
if not paths:
return "give one or more workspace-relative paths"
bad = [p for p in paths if not os.path.isfile(self.flow.wpath(p))]
return "not a file: %s" % ", ".join(bad) if bad else None
res = Form("Register new files", [
("Brand-new files aren't in the vault, so dssc can't see them as modified. Register them here and "
"they're checked in with the rest (same as `dsflow add`).", "dim")],
[dict(type="text", key="paths", label="Path(s)", value="")]).run(self, validate)
if res is None:
return
paths = [norm(os.path.relpath(self.flow.wpath(p), self.flow.ws)) for p in shlex.split(res["paths"])]
self.flow.add_new(paths)
self.sel |= set(paths)
self.note("registered %d new file(s)" % len(paths), "ok")
self.refresh()
def act_rebase(self):
if not self.need_snap():
return
rows = [r for r in self.pick(self.snap.changes, use_cursor=self.vkey() == "changes") if r["stale"]]
if not rows:
return self.note("none of the marked files are stale", "info")
paths = [r["path"] for r in rows]
if not self.confirm("Merge Trunk:Latest into %d file(s)?" % len(paths), self.file_notes(paths) + [
("", ""), ("Runs ds_rebase (dssc pop -merge). Resolve any conflict markers, then rerun sanity.", "dim")]):
return
def work():
rc, out = self.flow.act("ds_rebase", *paths)
for line in out.splitlines():
self.logact(" " + line)
self.flow.drop_stamp()
return rc == 0, "merged %d file(s) - check for conflicts, then rerun sanity" % len(paths) if rc == 0 \
else "merge failed: %s" % last_line(out)
self.background("merging %d file(s)" % len(paths), work)
def act_help(self):
k = [
("Views", "bold"),
(" 1-5 / tab Changes, Locks, Checked-out, Sanity run, Logs", ""),
(" up/dn j/k move PgUp/PgDn g/G page / top / bottom", ""),
("", ""), ("Files", "bold"),
(" space mark / unmark (no marks = act on the cursor row)", ""),
(" a / esc mark all in view / clear marks", ""),
(" n register brand-new files for check-in", ""),
(" m rebase stale files onto Trunk:Latest", ""),
(" l / u lock / release lock (Locks & Checked-out)", ""),
(" t batch-tag marked files (%s)" % ", ".join(self.flow.tags), ""),
("", ""), ("Sanity", "bold"),
(" s run sanity: lock, refresh, run every config, check in or unlock", ""),
(" c check in marked files covered by a passing run", ""),
(" x cancel the run (or clean up after a lost runner)", ""),
("", ""),
(" r refresh q quit - a running sanity keeps going (`status` to follow)", "dim"),
(" dsflow_tui %s conf %s" % (VERSION, os.path.relpath(self.flow.conf, self.flow.ws)), "dim"),
]
Form("dsflow_tui keys", k, width=84).run(self)
# -- input ----------------------------------------------------------------
def move(self, delta, absolute=None):
v = self.vkey()
n = len(self.rows())
if not n:
return
self.cur[v] = absolute if absolute is not None else self.cur[v] + delta
self.cur[v] = max(0, min(n - 1, self.cur[v]))
def handle(self, k):
v = self.vkey()
H, _ = self.scr.getmaxyx()
page = max(1, H - 8)
if k in ("q", "Q"):
return "quit"
if k in ("1", "2", "3", "4", "5"):
self.view = int(k) - 1
elif k == "TAB":
self.view = (self.view + 1) % len(self.VIEWS)
elif k == "BTAB":
self.view = (self.view - 1) % len(self.VIEWS)
elif k == "?":
self.act_help()
elif k == "r":
self.refresh()
elif k == "s":
self.act_sanity()
elif k == "c":
self.act_checkin()
elif k == "x":
self.act_cancel()
elif v == "logs":
if k in ("LEFT", "h", "["):
self.log_src, self.log_off = self.log_src - 1, 0
elif k in ("RIGHT", "l", "]"):
self.log_src, self.log_off = self.log_src + 1, 0
elif k in ("UP", "k"):
self.log_off += 1
elif k in ("DOWN", "j"):
self.log_off = max(0, self.log_off - 1)
elif k == "PGUP":
self.log_off += page
elif k == "PGDN":
self.log_off = max(0, self.log_off - page)
elif k in ("HOME", "g"):
self.log_off = 10 ** 9
elif k in ("END", "G", "f"):
self.log_off = 0
elif v == "sanity":
if k == "ENTER":
self.view = 4
elif v in self.FILE_VIEWS:
if k in ("UP", "k"):
self.move(-1)
elif k in ("DOWN", "j"):
self.move(1)
elif k == "PGUP":
self.move(-page)
elif k == "PGDN":
self.move(page)
elif k in ("HOME", "g"):
self.move(0, 0)
elif k in ("END", "G"):
self.move(0, 10 ** 9)
elif k in (" ", "ENTER"):
r = self.cursor_row()
if r:
self.sel ^= {r["path"]}
self.move(1)
elif k == "a":
paths = set(r["path"] for r in self.rows())
self.sel = self.sel - paths if paths <= self.sel else self.sel | paths
elif k == "ESC":
self.sel.clear()
elif k == "t":
self.act_tag()
elif k == "l":
self.act_lock(True)
elif k == "u":
self.act_lock(False)
elif k == "n":
self.act_add()
elif k == "m":
self.act_rebase()
return None
def loop(self):
self.refresh()
while True:
self.poll()
try:
self.draw()
except curses.error:
pass
k = getkey(self.scr)
if k is None or k == "RESIZE":
continue
if self.handle(k) == "quit":
return
def run_tui(flow, auto_refresh):
os.environ.setdefault("ESCDELAY", "25")
def main(scr):
init_colors()
try:
curses.curs_set(0)
except curses.error:
pass
scr.keypad(True)
scr.timeout(200)
App(scr, flow, auto_refresh).loop()
curses.wrapper(main)
job = read_json(flow.path(JOB_FILE))
if job_state(job) == "active":
print("dsflow_tui: sanity run %s is still going in the background." % job["id"])
print(" follow it with: %s status (or reopen the TUI)" % os.path.basename(sys.argv[0]))
# ---------------------------------------------------------------------------
# `status` - scriptable progress report
# ---------------------------------------------------------------------------
def cmd_status(flow, as_json):
job = read_json(flow.path(JOB_FILE))
if as_json:
print(json.dumps(dict(state=job_state(job), job=job), indent=1, sort_keys=True))
return 0 if job and job.get("status") in ("passed", "running", "queued") else 1
if not job:
print("no sanity run recorded in %s" % flow.ws)
return 1
st = job_state(job)
label = "RUNNER LOST" if st == "orphaned" else job["status"].upper()
start = job.get("started") or job["created"]
print("run %s %s (%s, elapsed %s)" % (job["id"], label, job.get("host", "?"),
fmt_dur((job.get("finished") or time.time()) - start)))
print("mode: %s%s" % ("check in" if job["mode"] == "checkin" else "unlock only",
", tag %s" % job["tag"] if job.get("tag") else ""))
print("files: %s" % " ".join(job["files"] + job["new_files"]))
if job.get("locked_by_job"):
print("locked by run: %s" % " ".join(job["locked_by_job"]))
for s in job["steps"]:
mark = {"pending": ".", "running": ">", "done": "+", "failed": "x", "cancelled": "-", "skipped": "-"}[s["status"]]
el = ((s.get("t1") or time.time()) - s["t0"]) if s.get("t0") else None
print(" [%s] %-34s %-9s %s" % (mark, s["label"], fmt_dur(el), s.get("detail", "")))
if job.get("summary"):
print(job["summary"])
return 0 if job["status"] in ("passed", "running", "queued") and st != "orphaned" else 1
# ---------------------------------------------------------------------------
# --demo: sandbox workspace driven by a fake dssc
# ---------------------------------------------------------------------------
FAKE_DSSC = r'''#!/usr/bin/env python3
"""Fake dssc for the dsflow_tui demo. Vault state lives in $DSSC_FAKE_VAULT."""
import hashlib, json, os, sys, time, getpass
VAULT = os.environ["DSSC_FAKE_VAULT"]
ROOT = os.path.dirname(VAULT)
ME = os.environ.get("USER") or getpass.getuser()
time.sleep(0.03)
def load():
with open(VAULT) as fh:
return json.load(fh)
def save(v):
with open(VAULT + ".tmp", "w") as fh:
json.dump(v, fh, indent=1)
os.replace(VAULT + ".tmp", VAULT)
def ab(f): return os.path.join(ROOT, f)
def sha(f):
try:
with open(ab(f), "rb") as fh:
return hashlib.sha1(fh.read()).hexdigest()
except OSError:
return None
def modified(v, f): return sha(f) != v["files"][f]["hash"]
def bump(ver):
a, b = ver.rsplit(".", 1)
return "%s.%d" % (a, int(b) + 1)
def die(msg):
sys.stderr.write("dssc: %s\n" % msg)
sys.exit(1)
def parse(argv, valued):
flags, vals, pos, i = set(), {}, [], 0
while i < len(argv):
a = argv[i]
if a.startswith("-") and len(a) > 1:
if a in valued:
vals[a] = argv[i + 1]
i += 2
continue
flags.add(a)
else:
pos.append(a)
i += 1
return flags, vals, pos
def targets(v, pos):
out = []
for p in pos or ["."]:
r = os.path.relpath(os.path.abspath(p), ROOT)
if r == ".":
out += sorted(v["files"])
elif r in v["files"]:
out.append(r)
else:
out += [f for f in sorted(v["files"]) if f.startswith(r.rstrip("/") + "/")]
return out
def fetch(v, f, ver, note):
e, mode = v["files"][f], os.stat(ab(f)).st_mode & 0o777
os.chmod(ab(f), 0o644)
with open(ab(f), "a") as fh:
fh.write("// %s %s\n" % (note, ver))
os.chmod(ab(f), mode)
e["base"] = ver
cmd, argv = sys.argv[1], sys.argv[2:]
v = load()
if cmd == "ls":
fl, vals, pos = parse(argv, {"-report"})
rep = vals.get("-report", "N")
for f in targets(v, pos):
e = v["files"][f]
if "-modified" in fl and not modified(v, f):
continue
print({"N": f, "V": e["base"], "L": e["locker"]}.get(rep, f))
elif cmd == "vhistory":
fl, vals, pos = parse(argv, {"-max", "-branch"})
for f in targets(v, pos):
e = v["files"][f]
print("%s %s 2026-09-22 17:04 %s" % (e["latest"], e.get("author", "bob"), "Trunk"))
elif cmd in ("co", "lock"):
fl, vals, pos = parse(argv, {"-version", "-comment"})
for f in targets(v, pos):
e = v["files"][f]
if e["locker"] and e["locker"] != ME:
die("%s is locked by %s" % (f, e["locker"]))
if cmd == "lock" or "-lock" in fl:
e["locker"] = ME
if cmd == "co":
if not modified(v, f) and e["base"] != e["latest"]:
fetch(v, f, e["latest"], "fetched")
e["hash"] = sha(f)
os.chmod(ab(f), 0o644)
print("%s : Success - %s" % (f, "locked" if e["locker"] == ME else "checked out"))
save(v)
elif cmd == "unlock":
fl, vals, pos = parse(argv, set())
for f in targets(v, pos):
e = v["files"][f]
if e["locker"] and e["locker"] != ME:
die("%s is locked by %s" % (f, e["locker"]))
e["locker"] = ""
print("%s : Success - unlocked" % f)
save(v)
elif cmd == "ci":
fl, vals, pos = parse(argv, {"-comment"})
if "-new" in fl:
for p in pos:
f = os.path.relpath(os.path.abspath(p), ROOT)
if f in v["files"]:
die("%s is already managed" % f)
v["files"][f] = dict(base="1.1", latest="1.1", hash=sha(f), locker="", tags={}, author=ME)
os.chmod(ab(f), 0o444)
print("%s : Success - new version 1.1" % f)
else:
for f in targets(v, pos):
e = v["files"][f]
if e["locker"] and e["locker"] != ME:
die("%s is locked by %s" % (f, e["locker"]))
if e["base"] != e["latest"]:
die("%s: not based on Latest (%s vs %s) - merge first" % (f, e["base"], e["latest"]))
if not modified(v, f):
print("%s : unchanged, skipped" % f)
continue
new = bump(e["latest"])
e.update(base=new, latest=new, hash=sha(f), locker="", author=ME)
os.chmod(ab(f), 0o444)
print("%s : Success - checked in %s" % (f, new))
save(v)
elif cmd == "tag":
fl, vals, pos = parse(argv, set())
tag = pos[0]
for f in targets(v, pos[1:]):
e = v["files"][f]
e["tags"][tag] = e["base"]
print("%s;%s : Success - tagged %s" % (f, e["base"], tag))
save(v)
elif cmd in ("pop", "populate"):
fl, vals, pos = parse(argv, {"-version"})
for f in targets(v, pos):
e = v["files"][f]
if e["base"] == e["latest"]:
continue
if "-merge" in fl:
fetch(v, f, e["latest"], "merged with")
print("%s : merged %s" % (f, e["latest"]))
elif not modified(v, f):
fetch(v, f, e["latest"], "fetched")
e["hash"] = sha(f)
print("%s : fetched %s" % (f, e["latest"]))
save(v)
else:
die("fake dssc: unsupported command '%s'" % cmd)
'''
DEMO_CONF = r'''# dsflow.conf for the dsflow_tui demo sandbox (fake dssc on PATH)
TRUNK_SEL="Trunk:Latest"
WORKING_TAG="working"
SANITY_CONFIGS="kibo_2x2 jaguar_1x1"
CI_EXTRA_CONFIGS=""
MAX_STAMP_AGE=$((4*3600))
HOT_FILES="${WS_ROOT:-.}/flow/hot_files.txt"
CHECKIN_LOG="@SHARE@/dsflow_checkins.log"
CI_STATE="@SHARE@/ci_state"
CI_NOTIFY="[email protected]"
DSFLOW_TAGS="wmac_working wmac_rx_drop"
# Fake regression: DEMO_FAIL="jaguar_1x1" makes that config fail.
run_sanity() {
local n=${DEMO_SANITY_TESTS:-12} i
echo "=== sanity $1 (demo) ==="
for ((i=1; i<=n; i++)); do
sleep "${DEMO_STEP_SECS:-1.5}"
echo "[$1] $(date +%T) test_$(printf %02d $i) ... PASS"
done
if [[ " ${DEMO_FAIL:-} " == *" $1 "* ]]; then
echo "[$1] ERROR: scoreboard mismatch in rx path"; return 1
fi
echo "[$1] all $n tests passed"
}
ds_list_modified() { dssc ls -rec -modified -report N . 2>/dev/null | awk 'NF'; }
ds_base_version() { dssc ls -report V "$1" 2>/dev/null | awk 'NF{v=$NF} END{print v}'; }
ds_latest_version() { dssc vhistory -max 1 -branch Trunk "$1" 2>/dev/null | awk '/^[0-9.]+/{print $1; exit}'; }
ds_lock_holder() { dssc ls -report L "$1" 2>/dev/null | awk 'NF{u=$NF} END{print u}'; }
ds_unlock() { dssc unlock "$@"; }
'''
def setup_demo(base, reset):
base = os.path.abspath(base)
ws, bindir, share = os.path.join(base, "ws"), os.path.join(base, "bin"), os.path.join(base, "share")
vault = os.path.join(ws, ".fakevault.json")
if reset and os.path.isdir(base):
for root, dirs, files in os.walk(base):
for n in dirs + files:
try:
os.chmod(os.path.join(root, n), 0o755)
except OSError:
pass
shutil.rmtree(base)
if not os.path.exists(vault):
for d in (ws, bindir, share, os.path.join(ws, "flow")):
if not os.path.isdir(d):
os.makedirs(d)
with open(os.path.join(bindir, "dssc"), "w") as fh:
fh.write(FAKE_DSSC)
os.chmod(os.path.join(bindir, "dssc"), 0o755)
with open(os.path.join(ws, "flow", "dsflow.conf"), "w") as fh:
fh.write(DEMO_CONF.replace("@SHARE@", share))
with open(os.path.join(ws, "flow", "hot_files.txt"), "w") as fh:
fh.write("# One workspace-relative path per line. Locked on edit.\n"
"rtl/top/wifi_mac_top.sv\nrtl/pkg/wifi_mac_pkg.sv\nrtl/regs/mac_regs.sv\n")
# path: (base, latest, locker, state) - state: ro | co (writable) | mod (edited)
layout = {
"rtl/top/wifi_mac_top.sv": ("1.12", "1.12", ME, "mod"),
"rtl/pkg/wifi_mac_pkg.sv": ("1.31", "1.31", "", "ro"),
"rtl/regs/mac_regs.sv": ("1.9", "1.9", "alice", "ro"),
"rtl/rx/rx_fsm.sv": ("1.4", "1.4", "", "mod"),
"rtl/rx/rx_buf.sv": ("1.6", "1.6", "", "ro"),
"rtl/tx/tx_ctrl.sv": ("1.7", "1.8", "", "mod"),
"rtl/tx/tx_crc.sv": ("1.3", "1.3", "", "co"),
"rtl/tx/tx_fifo.sv": ("1.2", "1.2", "", "mod"),
"sim/tb/tb_top.sv": ("1.20", "1.20", "", "ro"),
}
files = {}
for rel, (b, l, locker, state) in sorted(layout.items()):
p = os.path.join(ws, rel)
if not os.path.isdir(os.path.dirname(p)):
os.makedirs(os.path.dirname(p))
mod = os.path.splitext(os.path.basename(rel))[0]
with open(p, "w") as fh:
fh.write("// %s - version %s\nmodule %s;\nendmodule\n" % (rel, b, mod))
files[rel] = dict(base=b, latest=l, hash=sha1_file(p), locker=locker, tags={}, author="bob")
if state == "mod":
with open(p, "a") as fh:
fh.write("// local edit by %s\n" % ME)
os.chmod(p, 0o444 if state == "ro" else 0o644)
with open(vault, "w") as fh:
json.dump(dict(files=files), fh, indent=1)
newf = os.path.join(ws, "rtl/rx/rx_agg.sv")
with open(newf, "w") as fh:
fh.write("module rx_agg;\nendmodule\n")
if not os.path.isdir(os.path.join(ws, ".dsflow")):
os.makedirs(os.path.join(ws, ".dsflow"))
with open(os.path.join(ws, ".dsflow", "new_files"), "w") as fh:
fh.write("rtl/rx/rx_agg.sv\n")
os.environ["PATH"] = bindir + os.pathsep + os.environ.get("PATH", "")
os.environ["DSSC_FAKE_VAULT"] = vault
return ws, os.path.join(ws, "flow", "dsflow.conf")
# ---------------------------------------------------------------------------
def main(argv=None):
ap = argparse.ArgumentParser(
prog="dsflow_tui.py", description="Terminal UI for the dsflow DesignSync check-in flow.",
formatter_class=argparse.RawDescriptionHelpFormatter,
epilog="examples:\n"
" dsflow_tui.py # from the workspace root\n"
" dsflow_tui.py status # progress of the current sanity run\n"
" dsflow_tui.py --sanity-cmd 'sim/regress.sh --cfg {cfg}'\n"
" dsflow_tui.py --demo # sandbox with a fake dssc\n"
" DEMO_FAIL=jaguar_1x1 dsflow_tui.py --demo # watch a failing run release its locks")
ap.add_argument("command", nargs="?", default="tui", choices=("tui", "status", "_runjob"),
help="tui (default) or status")
ap.add_argument("--ws", default=os.getcwd(), help="workspace root (default: current directory)")
ap.add_argument("--conf", help="dsflow.conf (default: $DSFLOW_CONF or <ws>/flow/dsflow.conf)")
ap.add_argument("--sanity-cmd", help="external sanity command; {cfg} and {ws} are substituted "
"(default: SANITY_SCRIPT from dsflow.conf, else run_sanity)")
ap.add_argument("--tags", help="comma-separated tags offered for batch tagging (default: DSFLOW_TAGS)")
ap.add_argument("--auto-refresh", type=int, default=0, metavar="SEC",
help="re-query DesignSync every SEC seconds (default: only on r / after actions)")
ap.add_argument("--json", action="store_true", help="status: print JSON")
ap.add_argument("--demo", action="store_true", help="run against a sandbox workspace with a fake dssc")
ap.add_argument("--demo-dir", default=os.path.join(tempfile.gettempdir(), "dsflow_tui_demo-" + ME))
ap.add_argument("--demo-reset", action="store_true", help="rebuild the demo sandbox from scratch")
ap.add_argument("--version", action="version", version="dsflow_tui " + VERSION)
args = ap.parse_args(argv)
if args.demo:
args.ws, args.conf = setup_demo(args.demo_dir, args.demo_reset)
conf = args.conf or os.environ.get("DSFLOW_CONF") or os.path.join(args.ws, "flow", "dsflow.conf")
tags = [t for t in (args.tags or "").replace(",", " ").split() if t] or None
try:
flow = Flow(args.ws, conf, args.sanity_cmd, tags)
flow.load_vars()
except FlowError as e:
print("dsflow_tui: %s" % e, file=sys.stderr)
return 2
if args.command == "_runjob":
return Runner(flow).main()
if args.command == "status":
return cmd_status(flow, args.json)
if not sys.stdout.isatty():
print("dsflow_tui: the TUI needs a terminal (use `status` for scripts)", file=sys.stderr)
return 2
try:
locale.setlocale(locale.LC_ALL, "")
codeset = locale.nl_langinfo(locale.CODESET) # what curses will really use
except (locale.Error, AttributeError):
codeset = ""
if "utf" not in codeset.lower().replace("-", ""):
G.ascii()
run_tui(flow, args.auto_refresh)
return 0
if __name__ == "__main__":
sys.exit(main())