fuzzyworld-tools / files / server / deploys.py
deploys.py
258a9da8 2026-11-06 Pavel Safronov | 1 | #!/usr/bin/env python3 |
| 2 | """What is deployed where. Python standard library only. | |
| 3 | ||
ab35fc22 2026-11-07 Pavel Safronov | 4 | Usage (on the server: `fw deploys`; from the laptop: `ssh dh ~/bin/fw deploys`, since bin/fw does not forward it yet, Q114): |
258a9da8 2026-11-06 Pavel Safronov | 5 | |
| 6 | deploys [--json] plain text, or JSON for `fw admin`: | |
| 7 | {"repos": [{repo, head, targets: [{target, description, paths, entries: [...]}]}], "apps": [...]} | |
| 8 | ||
| 9 | Two sources, both read-only: | |
| 10 | * the deploy ledger ~/fw/state/deployed.json (FW_STATE), written by `bin/deploy-tools` on the laptop: per | |
ab35fc22 2026-11-07 Pavel Safronov | 11 | "<repo>/<target>" (a per-machine target also "@<hostname>") the commit, the content hash of the folders the |
| 12 | target ships, and the time. <repo> is the bare repo's name (package.json "fuzzyworld": {"repo": ...} when the | |
| 13 | package is named differently). A repo declares its targets in package.json, "fuzzyworld": {"deploy": {<target>: {"paths": | |
258a9da8 2026-11-06 Pavel Safronov | 14 | [...], "description": "..."}}}, read here from the repo's default branch (HEAD of the bare repo = what is shipped). |
| 15 | * each deployed app's apps.fuzzyworld.net/<app>/.fuzzyworld.json (written by `fw deploy`): the repo, the commit and | |
| 16 | the time of its last deploy. | |
| 17 | ||
| 18 | State of a target entry: "current" (the ledger's hash equals the hash of those folders at the repo's HEAD), | |
| 19 | "pending" (it differs), "never" (no ledger entry). `behind` lists the commits at HEAD since the deployed commit that | |
| 20 | touch the target's folders (for an app: any file except documentation and CI config, see APP_IGNORED); it is null when the deployed commit is not in the server's | |
ab35fc22 2026-11-07 Pavel Safronov | 21 | repo (a commit that was never pushed, or a repo or commit field that is missing). A "+uncommitted" suffix is ignored |
| 22 | when looking the commit up. | |
258a9da8 2026-11-06 Pavel Safronov | 23 | """ |
| 24 | ||
| 25 | import json | |
| 26 | import os | |
| 27 | import posixpath | |
| 28 | import re | |
| 29 | import subprocess | |
| 30 | import sys | |
| 31 | ||
| 32 | HOME = os.path.expanduser("~") | |
| 33 | GIT_ROOT = os.environ.get("FW_GIT_ROOT", os.path.join(HOME, "git")) | |
| 34 | STATE = os.environ.get("FW_STATE", os.path.join(HOME, "fw", "state")) | |
| 35 | APPS = os.environ.get("FW_APPS_SITE", os.path.join(HOME, "apps.fuzzyworld.net")) | |
| 36 | NAME_RE = re.compile(r"^[A-Za-z0-9][A-Za-z0-9._-]*\Z") | |
| 37 | COMMIT_RE = re.compile(r"^[0-9a-f]{7,40}\Z") | |
| 38 | SHOWN = 8 # commits listed per "behind" | |
| 39 | # An app's "behind" ignores commits that only touch these (they never change what is built and deployed): | |
| 40 | # Markdown, CI config, the licence, .gitignore, docs/ and screenshots/. Git pathspecs; `*` also crosses folders. | |
| 41 | APP_IGNORED = ("*.md", ".fw-ci.yml", ".gitlab-ci.yml", "LICENSE*", ".gitignore", "docs/", "screenshots/") | |
| 42 | ||
| 43 | ||
| 44 | def git(repo, *args): | |
| 45 | p = subprocess.run(["git", "-C", repo, *args], capture_output=True, text=True, encoding="utf-8", errors="replace") | |
| 46 | return p.stdout.strip() if p.returncode == 0 else None | |
| 47 | ||
| 48 | ||
| 49 | def read_json(path): | |
| 50 | try: | |
| 51 | with open(path) as f: | |
| 52 | data = json.load(f) | |
| 53 | except (OSError, ValueError): | |
| 54 | return None | |
| 55 | return data if isinstance(data, dict) else None | |
| 56 | ||
| 57 | ||
| 58 | def behind(repo, commit, paths=(), ignore=()): | |
| 59 | """{"count", "commits": [[short sha, subject]]} since `commit` at HEAD, or None if `commit` is unknown here. | |
| 60 | `paths` limits it to those folders; `ignore` leaves out commits that touch only those pathspecs.""" | |
| 61 | commit = (commit or "").split("+")[0] | |
| 62 | if not COMMIT_RE.match(commit) or git(repo, "cat-file", "-e", commit + "^{commit}") is None: | |
| 63 | return None | |
| 64 | scope = ["--", *(paths or ["."]), *(f":(exclude){x}" for x in ignore)] if paths or ignore else [] | |
| 65 | count = git(repo, "rev-list", "--count", f"{commit}..HEAD", *scope) | |
| 66 | lines = git(repo, "log", f"-n{SHOWN}", "--format=%h %s", f"{commit}..HEAD", *scope) or "" | |
| 67 | return {"count": int(count or 0), "commits": [(l.split(" ", 1) + [""])[:2] for l in lines.splitlines()]} # a commit may have no subject | |
| 68 | ||
| 69 | ||
| 70 | def clean_path(p): | |
| 71 | """A folder inside the repo, written plainly (no "./", trailing "/", "..", or absolute): the form `bin/deploy-tools` accepts.""" | |
| 72 | return isinstance(p, str) and p != "" and posixpath.normpath(p) == p and not p.startswith(("/", "../")) and p != ".." | |
| 73 | ||
| 74 | ||
| 75 | def declared(repo_dir): | |
| 76 | """{target: {paths, description, perMachine}} from package.json at the repo's HEAD ({} if none or unreadable).""" | |
| 77 | text = git(repo_dir, "show", "HEAD:package.json") | |
| 78 | try: | |
| 79 | deploy = (json.loads(text).get("fuzzyworld") or {}).get("deploy") or {} | |
| 80 | except (ValueError, AttributeError, TypeError): | |
| 81 | return {} | |
| 82 | out = {} | |
| 83 | for name, t in deploy.items() if isinstance(deploy, dict) else []: | |
| 84 | paths = t.get("paths") if isinstance(t, dict) else None | |
| 85 | if NAME_RE.match(name) and isinstance(paths, list) and paths and all(clean_path(p) for p in paths): | |
| 86 | out[name] = {"paths": paths, "description": str(t.get("description", "")), "perMachine": bool(t.get("perMachine"))} | |
| 87 | return out | |
| 88 | ||
| 89 | ||
| 90 | def tree_hash(repo_dir, paths): | |
| 91 | """The same value `bin/deploy-tools` records: the tree hash of each folder, joined by commas.""" | |
| 92 | hashes = [git(repo_dir, "rev-parse", f"HEAD:{p}") for p in paths] | |
| 93 | return None if None in hashes else ",".join(hashes) | |
| 94 | ||
| 95 | ||
| 96 | def collect_repos(ledger): | |
| 97 | repos = [] | |
| 98 | for entry in sorted(os.listdir(GIT_ROOT)) if os.path.isdir(GIT_ROOT) else []: | |
| 99 | name = entry[:-4] | |
| 100 | repo_dir = os.path.join(GIT_ROOT, entry) | |
| 101 | if not entry.endswith(".git") or not NAME_RE.match(name): | |
| 102 | continue | |
| 103 | targets = declared(repo_dir) | |
| 104 | if not targets: | |
| 105 | continue | |
| 106 | head = git(repo_dir, "rev-parse", "HEAD") or "" | |
| 107 | out = [] | |
| 108 | for target, t in targets.items(): | |
| 109 | now = tree_hash(repo_dir, t["paths"]) | |
| 110 | prefix = f"{name}/{target}" | |
| 111 | keys = sorted(k for k in ledger if k == prefix or (t["perMachine"] and k.startswith(prefix + "@"))) | |
| 112 | entries = [] | |
| 113 | for k in keys: | |
| 114 | rec = ledger[k] if isinstance(ledger[k], dict) else {} | |
| 115 | entries.append({"key": k, "machine": k.partition("@")[2] or None, "commit": str(rec.get("commit", "")), | |
| 116 | "at": str(rec.get("at", "")), "state": "current" if rec.get("hash") == now and now else "pending", | |
| 117 | "behind": behind(repo_dir, str(rec.get("commit", "")), t["paths"])}) | |
| 118 | if not entries: | |
| 119 | entries = [{"key": prefix, "machine": None, "commit": "", "at": "", "state": "never", "behind": None}] | |
| 120 | out.append({"target": target, "description": t["description"], "paths": t["paths"], | |
| 121 | "per_machine": t["perMachine"], "entries": entries}) | |
| 122 | repos.append({"repo": name, "head": head[:7], "targets": out}) | |
| 123 | return repos | |
| 124 | ||
| 125 | ||
| 126 | def collect_apps(): | |
| 127 | apps = [] | |
| 128 | for entry in sorted(os.listdir(APPS)) if os.path.isdir(APPS) else []: | |
| 129 | meta = read_json(os.path.join(APPS, entry, ".fuzzyworld.json")) | |
| 130 | if not meta or not NAME_RE.match(entry): | |
| 131 | continue | |
| 132 | repo = str(meta.get("repo") or entry) | |
| 133 | repo_dir = os.path.join(GIT_ROOT, repo + ".git") | |
| 134 | have = NAME_RE.match(repo) and os.path.isdir(repo_dir) | |
| 135 | head = (git(repo_dir, "rev-parse", "HEAD") or "") if have else "" | |
| 136 | commit = str(meta.get("commit", "")) | |
| 137 | b = behind(repo_dir, commit, ignore=APP_IGNORED) if have else None | |
| 138 | state = "unknown" if b is None else "current" if b["count"] == 0 else "pending" | |
| 139 | apps.append({"app": entry, "title": str(meta.get("title") or entry), "repo": repo, "commit": commit[:7], | |
| 140 | "deployed": str(meta.get("deployed", "")), "head": head[:7], "state": state, "behind": b}) | |
| 141 | return apps | |
| 142 | ||
| 143 | ||
| 144 | def collect(): | |
| 145 | ledger = read_json(os.path.join(STATE, "deployed.json")) or {} | |
| 146 | return {"repos": collect_repos(ledger), "apps": collect_apps()} | |
| 147 | ||
| 148 | ||
| 149 | def text(data): | |
| 150 | out = [] | |
| 151 | for r in data["repos"]: | |
| 152 | out.append(f'{r["repo"]} (HEAD {r["head"]})') | |
| 153 | for t in r["targets"]: | |
| 154 | for e in t["entries"]: | |
| 155 | n = f' ({e["behind"]["count"]} commits behind)' if e["behind"] and e["behind"]["count"] else "" | |
| 156 | out.append(f' {t["target"]:14} {e["state"]:8} {e["commit"] or "-":22} {e["at"]}{n}') | |
| 157 | out.append("apps") | |
| 158 | for a in data["apps"]: | |
| 159 | n = f' ({a["behind"]["count"]} commits behind)' if a["behind"] and a["behind"]["count"] else "" | |
| 160 | out.append(f' {a["app"]:24} {a["state"]:8} {a["commit"] or "-":8} {a["deployed"]}{n}') | |
| 161 | return "\n".join(out) | |
| 162 | ||
| 163 | ||
| 164 | def main(argv): | |
| 165 | if argv[1:] not in ([], ["--json"]): | |
| 166 | raise SystemExit(__doc__) | |
| 167 | data = collect() | |
| 168 | print(json.dumps(data) if argv[1:] else text(data)) | |
| 169 | ||
| 170 | ||
| 171 | if __name__ == "__main__": | |
| 172 | main(sys.argv) |