The internal servers have no access to outside package repositories and run Python 3.8/3.9, so the UI moves from hand-drawn curses to Textual 6.2.1 (the last release supporting 3.8.1), vendored with its pure-Python dependencies in vendor/. The launcher puts vendor/ first on sys.path, so a plain checkout runs with no pip and no network. - dsflow/: the single script split into a package (pure moves of the backend sections); action rules moved to ops.py, free of Textual - dsflow/ui/: tabs, detail pane, live sanity-run panel, log viewer, modal dialogs, filter, themes, mouse support - tests/test_ui.py: headless UI tests through Textual's pilot - tools/vendor.py (refresh vendor/), tools/screenshots.py (README images) - README, CLAUDE.md, TODO and the feature doc updated for the new layout, the Python 3.8.1 floor and the vendoring rules Verified: 11 tests green on Python 3.12 and 3.8.20; the shipped file set runs under `python -I -S` on both. Co-Authored-By: Claude Opus 5.5 <[email protected]>
328 lines
13 KiB
Python
328 lines
13 KiB
Python
"""Flow: the workspace plus every call into dsflow.conf.
|
|
|
|
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; verify them against your dssc version and
|
|
override any of them in dsflow.conf.
|
|
"""
|
|
import hashlib
|
|
import os
|
|
import shlex
|
|
import subprocess
|
|
import time
|
|
|
|
from .common import FlowError, ME, kill_group, last_line, norm, sha1_file
|
|
|
|
# ---------------------------------------------------------------------------
|
|
# 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'''
|
|
|
|
|
|
# ---------------------------------------------------------------------------
|
|
# 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
|