From 27e1c0047fc50ec7da7b933261f346b045d1fb25 Mon Sep 17 00:00:00 2001 From: rainyy21 Date: Wed, 11 Nov 2026 09:03:30 -0500 Subject: [PATCH] build a website --- app/web/app.py | 0 app/web/docker-compose.yml | 47 ++++ app/web/static/style.css | 0 app/web/templates/base.html | 0 app/web/templates/index.html | 0 app/web/watcher_additions.py | 193 +++++++++++++++ app/web/web/app.py | 411 +++++++++++++++++++++++++++++++ app/web/web/static/app.js | 367 +++++++++++++++++++++++++++ app/web/web/static/style.css | 333 +++++++++++++++++++++++++ app/web/web/templates/base.html | 30 +++ app/web/web/templates/index.html | 215 ++++++++++++++++ 11 files changed, 1596 insertions(+) delete mode 100644 app/web/app.py create mode 100644 app/web/docker-compose.yml delete mode 100644 app/web/static/style.css delete mode 100644 app/web/templates/base.html delete mode 100644 app/web/templates/index.html create mode 100644 app/web/watcher_additions.py create mode 100644 app/web/web/app.py create mode 100644 app/web/web/static/app.js create mode 100644 app/web/web/static/style.css create mode 100644 app/web/web/templates/base.html create mode 100644 app/web/web/templates/index.html diff --git a/app/web/app.py b/app/web/app.py deleted file mode 100644 index e69de29..0000000 diff --git a/app/web/docker-compose.yml b/app/web/docker-compose.yml new file mode 100644 index 0000000..e353b9f --- /dev/null +++ b/app/web/docker-compose.yml @@ -0,0 +1,47 @@ +services: + gitops-watcher: + build: . + container_name: gitops-watcher + restart: unless-stopped + stop_grace_period: 2m + environment: + CHECK_INTERVAL: 300 + STACKS_DIR: /opt/gitops + CONFIG_PATH: /config/repos.yml + STATE_PATH: /data/state.json + LOCAL_DIR: /data/local + REQUESTS_DIR: /data/requests + GITEA_TOKEN: ${GITEA_TOKEN} + GITHUB_TOKEN: ${GITHUB_TOKEN} + volumes: + - /var/run/docker.sock:/var/run/docker.sock + # the watcher now WRITES repos.yml (add / stop / start / remove), so no :ro. + # mount the folder, not the file: os.replace() can't swap a single-file bind mount + - ./config:/config + - ./data:/data + - /opt/gitops:/opt/gitops + + gitops-web: + build: . + container_name: gitops-web + restart: unless-stopped + command: ["gunicorn", "--workers", "1", "--threads", "4", "--bind", "0.0.0.0:5000", + "--chdir", "/app/web", "app:app"] + ports: + - "8088:5000" # LAN only until there's a login in front (NPM access list) + environment: + CHECK_INTERVAL: 300 + STACKS_DIR: /opt/gitops + CONFIG_PATH: /config/repos.yml + STATE_PATH: /data/state.json + LOCAL_DIR: /data/local + REQUESTS_DIR: /data/requests + TOKEN_ENVS: GITEA_TOKEN,GITHUB_TOKEN # names only, for the add-repo dropdown + SECRET_KEY: ${WEB_SECRET_KEY} + volumes: + # NO docker socket: the website can't run containers, only ask the watcher + - ./config:/config:ro + - ./data:/data:ro # can read state.json... + - ./data/local:/data/local # ...but only write local files + - ./data/requests:/data/requests # ...and requests + - /opt/gitops:/opt/gitops:ro # read the clones to show repo files diff --git a/app/web/static/style.css b/app/web/static/style.css deleted file mode 100644 index e69de29..0000000 diff --git a/app/web/templates/base.html b/app/web/templates/base.html deleted file mode 100644 index e69de29..0000000 diff --git a/app/web/templates/index.html b/app/web/templates/index.html deleted file mode 100644 index e69de29..0000000 diff --git a/app/web/watcher_additions.py b/app/web/watcher_additions.py new file mode 100644 index 0000000..d3626f6 --- /dev/null +++ b/app/web/watcher_additions.py @@ -0,0 +1,193 @@ +""" +WATCHER SIDE: paste these into watcher.py so the website's buttons do something. + +The website only writes request files and local files. These functions make +the watcher: + - copy data/local// into the clone before every deploy + - add docker-compose.override.yml when it exists + - skip paused repos + - process request files (deploy / stop / start / remove / add) + +Each block says where it goes. Function names match the ones you already have: +run, log, compose, deploy, check_repo, local_hash, load_config, normalize, +record, STACKS_DIR, LOCAL_DIR, CONFIG_PATH. +""" + +# ===================================================================== +# 1. TOP OF FILE: new import + constant +# ===================================================================== + +import shutil # add next to your other imports + +REQUESTS_DIR = Path(os.environ.get("REQUESTS_DIR", "data/requests")) + + +# ===================================================================== +# 2. CONFIG SECTION: save_config (repos.yml is now written by the watcher) +# Note: yaml.safe_dump does NOT keep comments in repos.yml. +# ===================================================================== + +def save_config(config: dict) -> None: + tmp = CONFIG_PATH.with_name(CONFIG_PATH.name + ".tmp") + with open(tmp, "w") as f: + yaml.safe_dump(config, f, sort_keys=False, default_flow_style=False) + os.replace(tmp, CONFIG_PATH) + + +# and in normalize(), add one more fallback: +# repo.setdefault("paused", False) + + +# ===================================================================== +# 3. DOCKER SECTION: replace compose() and deploy() with these +# ===================================================================== + +OVERRIDE = "docker-compose.override.yml" + + +def compose(name: str, *args: str, path: Path | None = None, + compose_file: str | None = None, timeout: int = DEFAULT_TIMEOUT) -> str: + cmd = ["docker", "compose", "-p", name] + if compose_file: + cmd += ["-f", compose_file] + # Compose only auto-loads an override when no -f is given, so add it ourselves + if path is not None and (path / OVERRIDE).is_file(): + cmd += ["-f", OVERRIDE] + return run(cmd + list(args), cwd=path, timeout=timeout) + + +def sync_local_files(name: str, path: Path) -> None: + """Copy data/local//* into the clone, so compose sees .env, overrides, etc.""" + local = LOCAL_DIR / name + if not local.is_dir(): + return + for f in local.iterdir(): + if f.is_file(): + shutil.copy2(f, path / f.name) + + +def deploy(repo: dict, path: Path) -> None: + name = repo["name"] + log(name, "deploying...") + sync_local_files(name, path) # NEW: before anything reads the files + if repo["pull_images"]: + pull_images(name, path, repo["compose_file"]) + compose(name, "up", "-d", "--build", "--remove-orphans", + path=path, compose_file=repo["compose_file"], timeout=BUILD_TIMEOUT) + log(name, "deployed ✓") + +# (DEFAULT_TIMEOUT / BUILD_TIMEOUT are the timeout constants from the timeouts step. +# If you named them differently, use your names.) + + +# ===================================================================== +# 4. NEW SECTION "requests" (put it before main) +# ===================================================================== + +def find_entry(config: dict, name: str) -> dict | None: + for entry in config.get("repos") or []: + if isinstance(entry, dict) and entry.get("name") == name: + return entry + return None + + +def handle_request(req: dict, state: dict) -> None: + action = req.get("action") + name = req.get("repo", "") + config = load_config() + config["repos"] = config.get("repos") or [] + now = datetime.now().isoformat(timespec="seconds") + + if action == "add": + if find_entry(config, name): + raise RuntimeError(f"{name} already exists") + config["repos"].append(req["entry"]) + save_config(config) + log(name, "added from web UI") + return # the normal round clones + deploys it + + entry = find_entry(config, name) + if entry is None: + raise RuntimeError(f"no repo named {name!r}") + repo = normalize(entry, config.get("defaults") or {}) + path = STACKS_DIR / name + + if action in ("deploy", "start"): + if action == "start": + entry["paused"] = False + save_config(config) + repo["paused"] = False + if (path / ".git").exists(): + deploy(repo, path) + commit = local_hash(path) + else: + commit = check_repo(repo)["commit"] # clones + deploys + record(state, name, status="ok", error=None, commit=commit, + last_check=now, last_deploy=now) + + elif action == "stop": + entry["paused"] = True + save_config(config) + if path.exists(): + compose(name, "down", "--remove-orphans") + log(name, "stopped (paused)") + + elif action == "remove": + wipe = bool(req.get("wipe_volumes")) + if path.exists(): + compose(name, "down", "--remove-orphans", *(["-v"] if wipe else [])) + config["repos"] = [e for e in config["repos"] + if not (isinstance(e, dict) and e.get("name") == name)] + save_config(config) + shutil.rmtree(path, ignore_errors=True) + if wipe: + shutil.rmtree(LOCAL_DIR / name, ignore_errors=True) + state.pop(name, None) + log(name, "removed" + (" (volumes + local files deleted)" if wipe else "")) + + else: + raise RuntimeError(f"unknown action {action!r}") + + +def process_requests(state: dict) -> None: + """Run every queued request, oldest first. Each file is deleted once handled.""" + REQUESTS_DIR.mkdir(parents=True, exist_ok=True) + for f in sorted(REQUESTS_DIR.glob("*.json")): + req = {} + try: + req = json.loads(f.read_text()) + log(req.get("repo", "?"), f"request: {req.get('action')}") + handle_request(req, state) + except Exception as e: + name = req.get("repo", "?") if isinstance(req, dict) else "?" + log(name, f"request failed: {e}") + record(state, name, status="error", error=f"request failed: {e}", + last_check=datetime.now().isoformat(timespec="seconds")) + finally: + f.unlink(missing_ok=True) + save_state(state) + + +# ===================================================================== +# 5. main(): three small changes +# ===================================================================== +# +# a) at the START of each round, before load_config(): +# +# process_requests(state) +# +# b) in the per-repo loop, right after `repo = normalize(raw, defaults)`: +# +# if repo["paused"]: +# continue +# +# c) so the website reacts fast: wait in short steps and wake up early +# when a request file shows up. Replace the end-of-round wait with: +# +# deadline = time.monotonic() + max(0, CHECK_INTERVAL - elapsed) +# while not STOP.is_set() and time.monotonic() < deadline: +# if any(REQUESTS_DIR.glob("*.json")): +# break +# STOP.wait(2) +# +# (a full round then runs: requests first, then the normal checks) diff --git a/app/web/web/app.py b/app/web/web/app.py new file mode 100644 index 0000000..23b9225 --- /dev/null +++ b/app/web/web/app.py @@ -0,0 +1,411 @@ +#!/usr/bin/env python3 +""" +gitops-watcher web UI. + +Runs as its own container. It never touches Docker: it only + - READS repos.yml, state.json and the clones (to show status + git files) + - WRITES request files (data/requests/) -> the watcher acts on them + - WRITES local files (data/local/) -> .env, overrides, etc. +""" + +import json +import os +import re +import secrets +import time +from datetime import datetime +from pathlib import Path + +import yaml +from flask import (Flask, abort, flash, jsonify, redirect, render_template, + request, session, url_for) + +# ---------- settings (same env vars as the watcher) ---------- + +STATE_PATH = Path(os.environ.get("STATE_PATH", "data/state.json")) +CONFIG_PATH = Path(os.environ.get("CONFIG_PATH", "repos.yml")) +STACKS_DIR = Path(os.environ.get("STACKS_DIR", "stacks")) +LOCAL_DIR = Path(os.environ.get("LOCAL_DIR", "data/local")) +REQUESTS_DIR = Path(os.environ.get("REQUESTS_DIR", "data/requests")) +CHECK_INTERVAL = int(os.environ.get("CHECK_INTERVAL", "300")) +TOKEN_ENVS = [t for t in os.environ.get("TOKEN_ENVS", "GITEA_TOKEN,GITHUB_TOKEN").split(",") if t] + +MAX_FILE = 256 * 1024 # biggest file the editor will open/save +SAFE_REPO = re.compile(r"^[a-z0-9][a-z0-9_-]{0,62}$") # compose project names are lowercase +SAFE_FILE = re.compile(r"^[A-Za-z0-9._-]{1,100}$") # no slashes = no ../ tricks +SAFE_BRANCH = re.compile(r"^[A-Za-z0-9._/-]{1,100}$") +SAFE_URL = re.compile(r"^https?://[^\s@]+$") # no "@" = no tokens pasted into URLs + +app = Flask(__name__) +app.secret_key = os.environ.get("SECRET_KEY") or secrets.token_hex(32) +app.config["MAX_CONTENT_LENGTH"] = MAX_FILE + 64 * 1024 + + +# ---------- reading data ---------- + +def load_json(path: Path, default): + try: + return json.loads(path.read_text()) + except (OSError, ValueError): + return default + + +def load_repos() -> list[dict]: + """repos.yml entries with defaults filled in (same rules as the watcher's normalize).""" + try: + config = yaml.safe_load(CONFIG_PATH.read_text()) or {} + except (OSError, yaml.YAMLError): + return [] + defaults = config.get("defaults") or {} + repos = [] + for raw in config.get("repos") or []: + if not isinstance(raw, dict) or not raw.get("name"): + continue + repo = {"branch": "main", "compose_file": "docker-compose.yml", + "pull_images": False, "paused": False, **defaults, **raw} + repos.append(repo) + return repos + + +def get_repo(name: str) -> dict: + for repo in load_repos(): + if repo["name"] == name: + return repo + abort(404, f"no repo named {name!r}") + + +def pending_requests() -> dict[str, str]: + """{repo name: action} for requests the watcher hasn't processed yet.""" + pending = {} + if REQUESTS_DIR.is_dir(): + for f in sorted(REQUESTS_DIR.glob("*.json")): + req = load_json(f, None) + if isinstance(req, dict) and req.get("repo"): + pending.setdefault(req["repo"], req.get("action", "?")) + return pending + + +# ---------- writing requests ---------- + +def write_atomic(path: Path, text: str, mode: int | None = None) -> None: + path.parent.mkdir(parents=True, exist_ok=True) + tmp = path.with_name(path.name + ".tmp") + tmp.write_text(text) + if mode is not None: + os.chmod(tmp, mode) + os.replace(tmp, path) + + +def queue_request(action: str, repo: str, **extra) -> None: + req = {"action": action, "repo": repo, + "created": datetime.now().isoformat(timespec="seconds"), **extra} + name = f"{time.time_ns()}-{action}-{repo}.json" + write_atomic(REQUESTS_DIR / name, json.dumps(req, indent=2)) + + +# ---------- files ---------- + +def safe_path(base: Path, filename: str) -> Path: + """Join base + filename, refusing anything that could escape base.""" + if not SAFE_FILE.match(filename) or filename in (".", ".."): + abort(400, "bad file name") + path = (base / filename).resolve() + if path.parent != base.resolve(): + abort(400, "bad file name") + return path + + +def is_secret(filename: str) -> bool: + return filename == ".env" or filename.endswith(".env") + + +def mask(text: str) -> str: + lines = [] + for line in text.splitlines(): + i = line.find("=") + if i > 0 and not line.lstrip().startswith("#"): + line = line[: i + 1] + "••••••••" + lines.append(line) + return "\n".join(lines) + ("\n" if text.endswith("\n") else "") + + +def env_keys(text: str) -> set[str]: + keys = set() + for line in text.splitlines(): + line = line.strip() + if not line or line.startswith("#") or "=" not in line: + continue + if line.startswith("export "): + line = line[len("export "):] + key = line.split("=", 1)[0].strip() + if key: + keys.add(key) + return keys + + +def missing_env(name: str) -> list[str]: + example = STACKS_DIR / name / ".env.example" + env = LOCAL_DIR / name / ".env" + if not example.is_file() or not env.is_file(): + return [] + return sorted(env_keys(example.read_text()) - env_keys(env.read_text())) + + +def local_files(name: str) -> list[str]: + folder = LOCAL_DIR / name + if not folder.is_dir(): + return [] + return sorted(p.name for p in folder.iterdir() if p.is_file() and SAFE_FILE.match(p.name)) + + +def git_files(repo: dict) -> list[str]: + """Readable text files in the root of the clone (not the copied-in local ones).""" + root = STACKS_DIR / repo["name"] + if not root.is_dir(): + return [] + skip = set(local_files(repo["name"])) + names = [] + for p in root.iterdir(): + if (p.is_file() and p.name not in skip and SAFE_FILE.match(p.name) + and (not p.name.startswith(".") or p.name == ".env.example") + and p.stat().st_size <= MAX_FILE): + names.append(p.name) + compose = repo["compose_file"] + return sorted(names, key=lambda n: (n != compose, n.lower())) + + +def read_text(path: Path) -> str: + try: + return path.read_text(encoding="utf-8") + except UnicodeDecodeError: + abort(415, "not a text file") + + +# ---------- CSRF (stops other websites from clicking your buttons) ---------- + +def csrf_token() -> str: + if "csrf" not in session: + session["csrf"] = secrets.token_hex(16) + return session["csrf"] + + +app.jinja_env.globals["csrf_token"] = csrf_token + + +@app.before_request +def check_csrf(): + if request.method == "POST": + sent = request.form.get("csrf") or request.headers.get("X-CSRF-Token") or "" + if not secrets.compare_digest(sent, session.get("csrf", "")): + abort(400, "invalid or missing CSRF token: reload the page and try again") + + +@app.errorhandler(400) +@app.errorhandler(404) +@app.errorhandler(413) +@app.errorhandler(415) +def api_errors(e): + if request.path.startswith("/api/"): + return jsonify(error=e.description), e.code + return e + + +# ---------- template helpers ---------- + +@app.template_filter("ago") +def ago(iso: str | None) -> str: + if not iso: + return "-" + try: + secs = int((datetime.now() - datetime.fromisoformat(iso)).total_seconds()) + except ValueError: + return iso + if secs < 10: + return "just now" + for unit, size in (("d", 86400), ("h", 3600), ("m", 60)): + if secs >= size: + return f"{secs // size}{unit} ago" + return f"{secs}s ago" + + +@app.template_filter("pretty") +def pretty(iso: str | None) -> str: + return iso.replace("T", " ") if iso else "" + + +# ---------- pages ---------- + +ORDER = {"error": 0, "setup": 1, "ok": 2, "new": 3, "paused": 4} + + +@app.get("/") +def index(): + repos = load_repos() + state = load_json(STATE_PATH, {}) + pending = pending_requests() + + rows = [] + for repo in repos: + name = repo["name"] + info = state.get(name, {}) + status = "paused" if repo["paused"] else info.get("status", "new") + if status not in ORDER: + status = "error" + rows.append({ + "name": name, + "status": status, + "commit": (info.get("commit") or "")[:7], + "last_check": info.get("last_check"), + "last_deploy": info.get("last_deploy"), + "error": info.get("error") if status == "error" else None, + "missing_env": missing_env(name), + "busy": pending.get(name), + }) + + # repos that are queued to be added but not in repos.yml yet + known = {r["name"] for r in rows} + for name, action in pending.items(): + if action == "add" and name not in known: + rows.append({"name": name, "status": "new", "commit": "", "last_check": None, + "last_deploy": None, "error": None, "missing_env": [], "busy": "add"}) + + rows.sort(key=lambda r: (ORDER[r["status"]], r["name"])) + + counts = {s: sum(1 for r in rows if r["status"] == s) for s in ORDER} + checks = [r["last_check"] for r in rows if r["last_check"]] + last_round = max(checks) if checks else None + next_in, stale = None, False + if last_round: + since = (datetime.now() - datetime.fromisoformat(last_round)).total_seconds() + next_in = max(0, int(CHECK_INTERVAL - since)) + stale = since > CHECK_INTERVAL * 2 + 60 + + return render_template("index.html", rows=rows, counts=counts, total=len(rows), + next_in=next_in, stale=stale, last_round=last_round, + interval=CHECK_INTERVAL, token_envs=TOKEN_ENVS) + + +# ---------- actions (all become request files) ---------- + +@app.post("/repos//") +def repo_action(name: str, action: str): + if action not in ("deploy", "stop", "start"): + abort(404) + get_repo(name) + queue_request(action, name) + flash(f"queued: {action} {name} · runs on the watcher's next round") + return redirect(url_for("index")) + + +@app.post("/repos//remove") +def remove_repo(name: str): + get_repo(name) + if request.form.get("confirm", "") != name: + flash("the name didn't match, so nothing was removed", "error") + return redirect(url_for("index")) + wipe = request.form.get("wipe") == "on" + queue_request("remove", name, wipe_volumes=wipe) + flash(f"queued: remove {name}" + (" + delete its data" if wipe else "")) + return redirect(url_for("index")) + + +@app.post("/repos") +def add_repo(): + f = request.form + name = f.get("name", "").strip() + url = f.get("url", "").strip() + branch = f.get("branch", "").strip() or "main" + compose_file = f.get("compose_file", "").strip() or "docker-compose.yml" + token_env = f.get("token_env", "").strip() + + problems = [] + if not SAFE_REPO.match(name): + problems.append("name: lowercase letters, numbers, - and _ only") + elif any(r["name"] == name for r in load_repos()) or pending_requests().get(name) == "add": + problems.append(f"a repo named {name} already exists") + if not SAFE_URL.match(url): + problems.append("url: must be http(s) with no username or token in it") + if not SAFE_BRANCH.match(branch): + problems.append("branch name has invalid characters") + if not SAFE_FILE.match(compose_file): + problems.append("compose file must be a plain file name") + if token_env and token_env not in TOKEN_ENVS: + problems.append("unknown token") + if problems: + for p in problems: + flash(p, "error") + return redirect(url_for("index")) + + entry = {"name": name, "url": url, "branch": branch, "compose_file": compose_file} + if token_env: + entry["token_env"] = token_env + if f.get("pull_images") == "on": + entry["pull_images"] = True + if f.get("deploy_now") != "on": + entry["paused"] = True + + queue_request("add", name, entry=entry) + flash(f"queued: add {name}") + return redirect(url_for("index")) + + +# ---------- file editor API (used by app.js) ---------- + +@app.get("/api/repos//files") +def list_files(name: str): + repo = get_repo(name) + local = local_files(name) + return jsonify(local=local, git=git_files(repo), compose_file=repo["compose_file"], + missing_env=missing_env(name)) + + +@app.get("/api/repos//files//") +def read_file(name: str, kind: str, filename: str): + repo = get_repo(name) + if kind == "local": + base = LOCAL_DIR / name + elif kind == "git": + if filename not in git_files(repo): + abort(404, "not a viewable repo file") + base = STACKS_DIR / name + else: + abort(404) + path = safe_path(base, filename) + if not path.is_file(): + abort(404, "file not found") + text = read_text(path) + secret = is_secret(filename) + reveal = request.args.get("reveal") == "1" + return jsonify(content=mask(text) if secret and not reveal else text, + secret=secret, masked=secret and not reveal) + + +@app.post("/api/repos//files/") +def save_file(name: str, filename: str): + repo = get_repo(name) + data = request.get_json(silent=True) or {} + content = data.get("content") + if not isinstance(content, str): + abort(400, "missing content") + if len(content.encode()) > MAX_FILE: + abort(413, "file too large") + if filename.endswith((".yml", ".yaml")): + if "\t" in content: + return jsonify(error="YAML can't use tabs for indentation"), 400 + try: + yaml.safe_load(content) + except yaml.YAMLError as e: + return jsonify(error=f"invalid YAML: {e}"), 400 + + path = safe_path(LOCAL_DIR / name, filename) + is_new = not path.exists() + shadows = is_new and filename in git_files(repo) # check BEFORE writing: git_files hides local names + write_atomic(path, content, mode=0o600 if is_secret(filename) else 0o644) + + if data.get("redeploy"): + queue_request("deploy", name) + return jsonify(ok=True, missing_env=missing_env(name), shadows_git=shadows) + + +if __name__ == "__main__": + app.run(host="0.0.0.0", port=int(os.environ.get("PORT", "5000"))) diff --git a/app/web/web/static/app.js b/app/web/web/static/app.js new file mode 100644 index 0000000..4159895 --- /dev/null +++ b/app/web/web/static/app.js @@ -0,0 +1,367 @@ +/* gitops-watcher web UI + - buttons that change things are plain
, so they work without JS + - this file adds: dialogs, the file editor, toasts, auto-refresh, countdown, rain */ + +const $ = s => document.querySelector(s); +const $$ = s => document.querySelectorAll(s); +const CSRF = document.querySelector('meta[name="csrf-token"]').content; + +const esc = s => String(s).replace(/[&<>"']/g, c => + ({ "&": "&", "<": "<", ">": ">", '"': """, "'": "'" }[c])); + +/* ---------- toasts ---------- */ +function toast(html, kind = "") { + const t = document.createElement("div"); + t.className = `toast ${kind}`; + t.innerHTML = html; + $("#toasts").appendChild(t); + setTimeout(() => t.remove(), 4000); +} +$$("#toasts .toast").forEach(t => setTimeout(() => t.remove(), 4500)); // flashed from Flask + +/* ---------- dialogs ---------- */ +let lastFocus = null; +function openModal(sel, focusSel) { + lastFocus = document.activeElement; + $(sel).classList.add("open"); + if (focusSel) setTimeout(() => $(focusSel)?.focus(), 0); +} +function closeModals() { + if ($("#files-drawer").classList.contains("open") && isDirty() && + !confirm("discard unsaved changes?")) return; + $$(".backdrop.open").forEach(m => m.classList.remove("open")); + lastFocus?.focus(); +} +const anyOpen = () => !!document.querySelector(".backdrop.open"); + +document.addEventListener("click", e => { + const opener = e.target.closest("[data-open]"); + if (opener) { openModal(opener.dataset.open, opener.dataset.focus); return; } + if (e.target.closest("[data-close]")) { closeModals(); return; } + if (e.target.classList.contains("backdrop")) { closeModals(); return; } + + const rm = e.target.closest("[data-remove]"); + if (rm) { openRemove(rm.dataset.remove); return; } + + const files = e.target.closest("[data-files]"); + if (files) { openFiles(files.dataset.files); return; } +}); +document.addEventListener("keydown", e => { if (e.key === "Escape" && anyOpen()) closeModals(); }); + +/* ---------- remove: type the name to enable the button ---------- */ +let removing = null; +function openRemove(name) { + removing = name; + $$(".rm-name").forEach(el => el.textContent = name); + $("#remove-form").action = `/repos/${encodeURIComponent(name)}/remove`; + $("#rm-confirm").value = ""; + $("#rm-wipe").checked = false; + $("#rm-submit").disabled = true; + $("#rm-submit").textContent = "remove"; + openModal("#remove-modal", "#rm-confirm"); +} +$("#rm-confirm")?.addEventListener("input", e => { $("#rm-submit").disabled = e.target.value !== removing; }); +$("#rm-wipe")?.addEventListener("change", e => { + $("#rm-submit").textContent = e.target.checked ? "remove + delete data" : "remove"; +}); + +/* ========================================================= + FILE EDITOR + ========================================================= */ +let fd = { repo: null, kind: null, file: null, original: "", secret: false, revealed: false, + list: { local: [], git: [], missing_env: [] } }; + +const isSecret = f => f === ".env" || f.endsWith(".env"); +const api = (path, opts = {}) => fetch(path, { + ...opts, + headers: { "X-CSRF-Token": CSRF, "Content-Type": "application/json", ...(opts.headers || {}) }, +}).then(async res => { + const data = await res.json().catch(() => ({})); + if (!res.ok) throw new Error(data.error || `request failed (${res.status})`); + return data; +}); +const repoUrl = () => `/api/repos/${encodeURIComponent(fd.repo)}/files`; + +async function openFiles(name) { + fd = { repo: name, kind: null, file: null, original: "", secret: false, revealed: false, + list: { local: [], git: [], missing_env: [] } }; + $("#fd-repo").textContent = name; + $("#fd-text").value = ""; + openModal("#files-drawer"); + await refreshList(); + if (fd.list.local.includes(".env")) selectFile("local", ".env"); + else if (fd.list.git.length) selectFile("git", fd.list.git[0]); + else showEmpty(); +} + +async function refreshList() { + try { fd.list = await api(repoUrl()); } + catch (err) { toast(esc(err.message), "error"); } + renderList(); +} + +function renderList() { + const { local, git, missing_env } = fd.list; + const btn = (kind, file) => { + const active = fd.kind === kind && fd.file === file ? "active" : ""; + let tag = ""; + if (active && isDirty()) tag = `●`; + else if (kind === "local" && file === ".env" && missing_env.length) tag = `⚠ ${missing_env.length} missing`; + else if (kind === "git") tag = `read-only`; + return ``; + }; + const hasEnv = local.includes(".env"); + const hasExample = git.includes(".env.example"); + const hasOverride = local.includes("docker-compose.override.yml"); + $("#fd-list").innerHTML = ` +
LOCALyours · kept across pulls
+ ${local.map(f => btn("local", f)).join("")} + ${!hasEnv && hasExample ? `` : ""} + ${!hasEnv && !hasExample ? `` : ""} + ${hasOverride ? "" : ``} + +
FROM GIToverwritten on every pull
+ ${git.length ? git.map(f => btn("git", f)).join("") : `
not cloned yet
`} + `; +} + +function showEmpty() { + Object.assign(fd, { kind: null, file: null, original: "" }); + $("#fd-fname").textContent = ""; + $("#fd-badges").innerHTML = ""; + $("#fd-banner").innerHTML = `
no files yet · create one from the list
`; + $("#fd-warn").innerHTML = ""; + $("#fd-text").value = ""; + $("#fd-text").readOnly = true; + updateGutter(); updateFoot(); renderList(); +} + +async function selectFile(kind, file, { reveal = false } = {}) { + if (isDirty() && !confirm("discard unsaved changes?")) return; + let data; + try { + data = await api(`${repoUrl()}/${kind}/${encodeURIComponent(file)}${reveal ? "?reveal=1" : ""}`); + } catch (err) { toast(esc(err.message), "error"); return; } + + Object.assign(fd, { kind, file, original: data.content, secret: data.secret, revealed: !data.masked }); + $("#fd-fname").textContent = file; + $("#fd-badges").innerHTML = + (kind === "git" ? `from git` : `local`) + + (data.secret ? ` secrets` : ""); + + const ta = $("#fd-text"); + ta.value = data.content; + ta.readOnly = kind === "git" || data.masked; + + if (kind === "git") { + const isCompose = file === fd.list.compose_file || /^docker-compose.*\.ya?ml$|^compose.*\.ya?ml$/.test(file); + $("#fd-banner").innerHTML = ` + `; + } else if (data.masked) { + $("#fd-banner").innerHTML = ` + `; + $("#fd-reveal").addEventListener("click", () => selectFile(kind, file, { reveal: true }).then(() => ta.focus())); + } else if (data.secret) { + $("#fd-banner").innerHTML = ` + `; + $("#fd-hide").addEventListener("click", () => selectFile(kind, file)); + } else { + $("#fd-banner").innerHTML = ""; + } + updateGutter(); updateFoot(); renderList(); renderWarn(); +} + +/* ---------- missing .env keys (names only, never values) ---------- */ +function envKeys(text) { + const keys = []; + for (let line of text.split("\n")) { + line = line.trim(); + if (!line || line.startsWith("#") || !line.includes("=")) continue; + keys.push(line.replace(/^export\s+/, "").split("=")[0].trim()); + } + return keys; +} +let exampleCache = { repo: null, text: null }; +async function exampleText() { + if (exampleCache.repo === fd.repo) return exampleCache.text; + let text = null; + if (fd.list.git.includes(".env.example")) { + try { text = (await api(`${repoUrl()}/git/.env.example`)).content; } catch { /* ignore */ } + } + exampleCache = { repo: fd.repo, text }; + return text; +} +async function renderWarn() { + const box = $("#fd-warn"); + if (fd.kind !== "local" || fd.file !== ".env") { box.innerHTML = ""; return; } + const example = await exampleText(); + if (!example) { box.innerHTML = ""; return; } + const have = new Set(envKeys(fd.revealed ? $("#fd-text").value : fd.original)); + const miss = envKeys(example).filter(k => !have.has(k)); + box.innerHTML = miss.length ? ` + ` : ""; + if (miss.length) $("#fd-add-missing").addEventListener("click", () => addMissing(miss, example)); +} +async function addMissing(miss, example) { + if (!fd.revealed) await selectFile("local", ".env", { reveal: true }); + const want = new Set(miss); + const lines = example.split("\n").filter(l => { + const t = l.trim(); + return t && !t.startsWith("#") && t.includes("=") && want.has(t.replace(/^export\s+/, "").split("=")[0].trim()); + }); + const ta = $("#fd-text"); + ta.value = ta.value.replace(/\n*$/, "\n") + `\n# added from .env.example: fill these in\n${lines.join("\n")}\n`; + ta.focus(); ta.scrollTop = ta.scrollHeight; + updateGutter(); updateFoot(); renderList(); renderWarn(); + toast(`added ${miss.length} key${miss.length > 1 ? "s" : ""} with example values · fill in, then save`); +} + +/* ---------- editor state ---------- */ +function isDirty() { + if (!fd.file || fd.kind === "git" || !fd.revealed) return false; + return $("#fd-text").value !== fd.original; +} +function updateGutter() { + const n = $("#fd-text").value.split("\n").length; + $("#fd-gutter").textContent = Array.from({ length: n }, (_, i) => i + 1).join("\n"); +} +function updateFoot() { + const dirty = isDirty(); + $("#fd-btns").style.display = fd.kind === "local" ? "" : "none"; + $("#fd-state").className = "state" + (dirty ? " dirty" : ""); + $("#fd-state").textContent = + !fd.file ? "" : + fd.kind === "git" ? "read-only · edit this in the repo" : + !fd.revealed ? "hidden · reveal to edit" : + dirty ? "● unsaved changes" : "no changes"; + ["#fd-discard", "#fd-save", "#fd-save-deploy"].forEach(s => $(s).disabled = !dirty); +} + +const ta = $("#fd-text"); +if (ta) { + ta.addEventListener("scroll", () => { $("#fd-gutter").scrollTop = ta.scrollTop; }); + ta.addEventListener("input", () => { updateGutter(); updateFoot(); renderList(); renderWarn(); }); + ta.addEventListener("keydown", e => { + if (e.key === "Tab" && !ta.readOnly) { + e.preventDefault(); + ta.setRangeText(" ", ta.selectionStart, ta.selectionEnd, "end"); + updateFoot(); + } + if ((e.ctrlKey || e.metaKey) && e.key === "s") { e.preventDefault(); if (isDirty()) save(false); } + }); +} + +async function save(redeploy) { + const content = $("#fd-text").value; + try { + const res = await api(`${repoUrl()}/${encodeURIComponent(fd.file)}`, { + method: "POST", body: JSON.stringify({ content, redeploy }), + }); + fd.original = content; + fd.list.missing_env = res.missing_env; + toast(redeploy + ? `saved ${esc(fd.file)} · redeploy queued` + : `saved ${esc(fd.file)} · takes effect on next deploy`, "ok"); + updateFoot(); renderList(); renderWarn(); + } catch (err) { toast(esc(err.message), "error"); } +} +$("#fd-save")?.addEventListener("click", () => save(false)); +$("#fd-save-deploy")?.addEventListener("click", () => save(true)); +$("#fd-discard")?.addEventListener("click", () => { + $("#fd-text").value = fd.original; + updateGutter(); updateFoot(); renderList(); renderWarn(); +}); + +/* ---------- file list clicks + creating files ---------- */ +const OVERRIDE_TEMPLATE = `# merged on top of the repo's compose file +# only list what you want to change, for example: +services: + web: + ports: + - "8080:80" +`; +document.addEventListener("click", async e => { + const f = e.target.closest(".file[data-kind]"); + if (f) { selectFile(f.dataset.kind, f.dataset.file); return; } + + const n = e.target.closest("[data-new]"); + if (!n) return; + let file = n.dataset.new; + if (file === "?") { + file = (prompt("file name (e.g. app.env, nginx.conf)") || "").trim(); + if (!file) return; + } + if (!/^[A-Za-z0-9._-]{1,100}$/.test(file) || file === "." || file === "..") { + toast("use letters, numbers, dot, dash or underscore only", "error"); return; + } + if (fd.list.local.includes(file)) { selectFile("local", file); return; } + + let content = ""; + if (file === "docker-compose.override.yml") content = OVERRIDE_TEMPLATE; + if ("fromExample" in n.dataset) content = (await exampleText()) || ""; + + try { + const res = await api(`${repoUrl()}/${encodeURIComponent(file)}`, { + method: "POST", body: JSON.stringify({ content }), + }); + toast(`created ${esc(file)} · local` + + (res.shadows_git ? `
this replaces the repo's ${esc(file)} on every deploy` : ""), "ok"); + await refreshList(); + exampleCache = { repo: null, text: null }; + selectFile("local", file, { reveal: isSecret(file) }); + } catch (err) { toast(esc(err.message), "error"); } +}); + +/* ---------- auto-refresh (skipped while a dialog or the editor is open) ---------- */ +setInterval(() => { if (!anyOpen()) location.reload(); }, 30000); + +/* ---------- countdown ---------- */ +(function () { + const el = $("#countdown"); + if (!el) return; + let secs = parseInt(el.dataset.seconds, 10) || 0; + const show = () => { + el.textContent = secs > 0 ? `${Math.floor(secs / 60)}:${String(secs % 60).padStart(2, "0")}` : "any moment"; + }; + show(); + setInterval(() => { if (secs > 0) secs--; show(); }, 1000); +})(); + +/* ---------- rain ---------- */ +(function () { + if (window.matchMedia("(prefers-reduced-motion: reduce)").matches) return; + const canvas = $("#rain"), ctx = canvas.getContext("2d"); + let drops = []; + function resize() { + canvas.width = innerWidth * devicePixelRatio; + canvas.height = innerHeight * devicePixelRatio; + ctx.setTransform(devicePixelRatio, 0, 0, devicePixelRatio, 0, 0); + drops = Array.from({ length: Math.floor(innerWidth / 9) }, () => ({ + x: Math.random() * innerWidth, y: Math.random() * innerHeight, + len: 8 + Math.random() * 14, speed: 2.5 + Math.random() * 4, alpha: 0.04 + Math.random() * 0.09, + })); + } + function tick() { + ctx.clearRect(0, 0, innerWidth, innerHeight); + for (const d of drops) { + ctx.strokeStyle = `rgba(124,183,232,${d.alpha})`; + ctx.beginPath(); ctx.moveTo(d.x, d.y); ctx.lineTo(d.x - 1, d.y + d.len); ctx.stroke(); + d.y += d.speed; + if (d.y > innerHeight) { d.y = -d.len; d.x = Math.random() * innerWidth; } + } + requestAnimationFrame(tick); + } + addEventListener("resize", resize); + resize(); tick(); +})(); diff --git a/app/web/web/static/style.css b/app/web/web/static/style.css new file mode 100644 index 0000000..b3067e7 --- /dev/null +++ b/app/web/web/static/style.css @@ -0,0 +1,333 @@ +/* gitops-watcher web UI */ +:root { + --bg: #0b1017; + --surface: #111925; + --surface-2: #16202e; + --border: #1f2b3b; + --text: #d3dae3; + --muted: #6b7a8d; + --accent: #7cb7e8; + --accent-bg: #142536; + --ok: #6fcf97; + --error: #e07a7a; + --error-bg: #2a1619; + --warn: #e5b567; + --paused: #8796a8; + --radius: 6px; + --font: "JetBrains Mono", ui-monospace, SFMono-Regular, Menlo, monospace; + } + + * { box-sizing: border-box; } + + body { + margin: 0; + min-height: 100vh; + background: var(--bg); + color: var(--text); + font-family: var(--font); + font-size: 14px; + line-height: 1.5; + } + + #rain { position: fixed; inset: 0; width: 100%; height: 100%; pointer-events: none; z-index: 0; } + + .wrap { position: relative; z-index: 1; max-width: 1140px; margin: 0 auto; padding: 24px 16px 64px; } + + /* ---------- buttons ---------- */ + .btn { + font: inherit; + font-size: 13px; + color: var(--text); + background: var(--surface); + border: 1px solid var(--border); + border-radius: 4px; + padding: 6px 12px; + cursor: pointer; + transition: border-color .15s, color .15s, background .15s; + white-space: nowrap; + } + .btn:hover:not(:disabled) { border-color: var(--accent); color: var(--accent); } + .btn:disabled { opacity: .4; cursor: not-allowed; } + .btn.primary { background: var(--accent-bg); border-color: var(--accent); color: var(--accent); } + .btn.primary:hover:not(:disabled) { background: #1a3046; } + .btn.danger { color: var(--error); } + .btn.danger:hover:not(:disabled) { border-color: var(--error); color: var(--error); background: var(--error-bg); } + .btn.danger.solid { background: var(--error-bg); border-color: var(--error); } + + .btn.icon { padding: 4px 9px; font-size: 12px; } + + /* ---------- top bar ---------- */ + .topbar { + display: flex; align-items: center; justify-content: space-between; + gap: 16px; flex-wrap: wrap; + padding-bottom: 16px; border-bottom: 1px solid var(--border); + } + .brand { font-weight: 700; font-size: 16px; color: var(--accent); letter-spacing: .02em; } + .brand span { color: var(--muted); font-weight: 400; } + .top-right { display: flex; align-items: center; gap: 16px; flex-wrap: wrap; } + + .heartbeat { display: flex; align-items: center; gap: 8px; color: var(--muted); font-size: 13px; } + .heartbeat b { color: var(--text); font-weight: 500; } + + .dot { width: 8px; height: 8px; border-radius: 50%; display: inline-block; flex: none; } + .dot.ok { background: var(--ok); box-shadow: 0 0 8px var(--ok); } + .dot.error { background: var(--error); box-shadow: 0 0 8px var(--error); } + .dot.warn { background: var(--warn); box-shadow: 0 0 8px var(--warn); } + .dot.paused { background: transparent; border: 1.5px solid var(--paused); } + .dot.busy { background: var(--accent); box-shadow: 0 0 8px var(--accent); animation: pulse 1s ease-in-out infinite; } + .heartbeat .dot { animation: pulse 2s ease-in-out infinite; } + @keyframes pulse { 50% { opacity: .3; } } + + /* ---------- summary ---------- */ + .summary { display: grid; grid-template-columns: repeat(4, 1fr); gap: 12px; margin: 20px 0; } + .stat { background: var(--surface); border: 1px solid var(--border); border-radius: var(--radius); padding: 14px 16px; } + .stat .label { color: var(--muted); font-size: 12px; } + .stat .value { font-size: 22px; font-weight: 700; margin-top: 2px; } + .stat .value.ok { color: var(--ok); } + .stat .value.error { color: var(--error); } + .stat .value.paused { color: var(--paused); } + .stat.dim { opacity: .5; } + + /* ---------- table ---------- */ + .panel { background: var(--surface); border: 1px solid var(--border); border-radius: var(--radius); overflow: hidden; } + table { width: 100%; border-collapse: collapse; } + th { + text-align: left; font-weight: 500; font-size: 12px; color: var(--muted); + padding: 12px 16px; border-bottom: 1px solid var(--border); white-space: nowrap; + } + th.actions-h { text-align: right; } + td { padding: 12px 16px; border-bottom: 1px solid var(--border); white-space: nowrap; vertical-align: middle; } + + tr.repo { transition: background .15s, opacity .4s; } + tr.repo:hover { background: var(--surface-2); } + tr.repo.has-error { background: var(--error-bg); } + tr.repo.has-warn + tr.warn-row { box-shadow: inset 3px 0 0 var(--warn); } + tr.repo.has-error:hover { background: #321a1e; } + tr.repo.is-paused .name, tr.repo.is-paused .commit, tr.repo.is-paused .time { opacity: .5; } + tr.repo.leaving { opacity: 0; } + + .name { font-weight: 500; } + .status { display: inline-flex; align-items: center; gap: 8px; } + .status.ok { color: var(--ok); } + .status.error { color: var(--error); } + .status.paused { color: var(--paused); } + .status.busy { color: var(--accent); } + + .commit { color: var(--accent); text-decoration: none; } + .commit:hover { text-decoration: underline dotted; } + .time { color: var(--muted); } + + .actions { display: flex; gap: 6px; justify-content: flex-end; } + + tr.error-row td { + padding: 0 16px 14px 40px; background: var(--error-bg); + white-space: pre-wrap; word-break: break-word; color: var(--error); font-size: 12.5px; + } + tr.error-row .tree { color: var(--muted); } + + .footer { + display: flex; justify-content: space-between; flex-wrap: wrap; gap: 8px; + margin-top: 12px; color: var(--muted); font-size: 12px; + } + + /* ---------- modals ---------- */ + .backdrop { + position: fixed; inset: 0; z-index: 10; + background: rgba(5, 8, 12, .72); + display: none; align-items: center; justify-content: center; + padding: 16px; + } + .backdrop.open { display: flex; } + .modal { + width: 100%; max-width: 480px; + background: var(--surface); border: 1px solid var(--border); border-radius: var(--radius); + box-shadow: 0 20px 60px rgba(0,0,0,.5); + } + .modal.danger { border-color: #4a2328; } + .modal-head { padding: 16px 20px; border-bottom: 1px solid var(--border); font-weight: 700; } + .modal.danger .modal-head { color: var(--error); } + .modal-body { padding: 18px 20px; display: grid; gap: 14px; } + .modal-foot { padding: 14px 20px; border-top: 1px solid var(--border); display: flex; justify-content: flex-end; gap: 8px; } + + .field { display: grid; gap: 6px; } + .field label { font-size: 12px; color: var(--muted); } + .field .hint { font-size: 11.5px; color: var(--muted); } + .row2 { display: grid; grid-template-columns: 1fr 1fr; gap: 12px; } + + input[type=text], select { + font: inherit; font-size: 13px; color: var(--text); + background: var(--bg); border: 1px solid var(--border); border-radius: 4px; + padding: 8px 10px; width: 100%; + } + input[type=text]:focus, select:focus { outline: none; border-color: var(--accent); } + input.invalid { border-color: var(--error); } + + .check { display: flex; align-items: flex-start; gap: 10px; font-size: 13px; cursor: pointer; } + .check input { margin-top: 3px; accent-color: var(--accent); } + .check .sub { display: block; color: var(--muted); font-size: 11.5px; } + .check.danger input { accent-color: var(--error); } + .check.danger .warn-text { color: var(--error); } + + .note { color: var(--muted); font-size: 12.5px; } + .note code { color: var(--text); } + .confirm-name { color: var(--text); font-weight: 700; } + + /* ---------- toasts ---------- */ + .toasts { position: fixed; right: 16px; bottom: 16px; z-index: 20; display: grid; gap: 8px; max-width: calc(100vw - 32px); } + .toast { + background: var(--surface-2); border: 1px solid var(--border); border-left: 3px solid var(--accent); + border-radius: 4px; padding: 10px 14px; font-size: 12.5px; + box-shadow: 0 8px 24px rgba(0,0,0,.4); + animation: in .2s ease-out; + } + .toast.ok { border-left-color: var(--ok); } + .toast.error { border-left-color: var(--error); } + .toast .muted { color: var(--muted); } + @keyframes in { from { transform: translateY(8px); opacity: 0; } } + + /* ---------- clickable repo name ---------- */ + .linkish { + font: inherit; color: inherit; background: none; border: 0; padding: 0; + cursor: pointer; text-align: left; + } + .linkish:hover .name { color: var(--accent); } + + /* ---------- file drawer ---------- */ + .backdrop.drawer-bd { justify-content: flex-end; align-items: stretch; padding: 0; } + .drawer { + width: 100%; max-width: 900px; height: 100%; + background: var(--surface); border-left: 1px solid var(--border); + display: flex; flex-direction: column; + animation: slide .2s ease-out; + } + @keyframes slide { from { transform: translateX(24px); opacity: 0; } } + + .drawer-head { + display: flex; align-items: center; justify-content: space-between; gap: 12px; + padding: 16px 20px; border-bottom: 1px solid var(--border); + } + .drawer-head .title { font-weight: 700; } + .drawer-head .title span { color: var(--muted); font-weight: 400; } + + .drawer-main { flex: 1; display: grid; grid-template-columns: 280px 1fr; min-height: 0; } + .file .fn { min-width: 0; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; } + .file .lock { white-space: nowrap; } + + .file-list { border-right: 1px solid var(--border); padding: 14px 0; overflow-y: auto; } + .file-group { padding: 0 16px 6px; margin-top: 10px; font-size: 11px; color: var(--muted); letter-spacing: .04em; } + .file-group:first-child { margin-top: 0; } + .file-group small { display: block; letter-spacing: 0; font-size: 11px; opacity: .8; } + .file { + display: flex; align-items: center; gap: 8px; width: 100%; + font: inherit; font-size: 13px; color: var(--text); text-align: left; + background: none; border: 0; border-left: 2px solid transparent; + padding: 7px 16px; cursor: pointer; + } + .file:hover { background: var(--surface-2); } + .file.active { background: var(--accent-bg); border-left-color: var(--accent); color: var(--accent); } + .file .lock { color: var(--muted); font-size: 11px; margin-left: auto; } + .file .dirty { color: var(--warn); margin-left: auto; } + .file.ghost { color: var(--muted); } + .file.ghost:hover { color: var(--accent); } + + .editor-pane { display: flex; flex-direction: column; min-width: 0; min-height: 0; } + .editor-bar { + display: flex; align-items: center; justify-content: space-between; gap: 10px; flex-wrap: wrap; + padding: 10px 16px; border-bottom: 1px solid var(--border); + } + .editor-bar .fname { font-weight: 500; } + .badge { + font-size: 11px; padding: 2px 7px; border-radius: 3px; border: 1px solid var(--border); color: var(--muted); + } + .badge.local { color: var(--ok); border-color: #24452f; } + .badge.git { color: var(--muted); } + .badge.secret { color: var(--warn); border-color: #4a3a1f; } + + .banner { + padding: 10px 16px; font-size: 12.5px; border-bottom: 1px solid var(--border); + display: flex; gap: 12px; align-items: center; justify-content: space-between; flex-wrap: wrap; + } + .banner.info { background: #121c28; color: var(--muted); } + .banner.warn { background: #211b10; color: var(--warn); border-left: 3px solid var(--warn); } + .banner.warn code { color: var(--text); } + + /* missing .env keys on the dashboard */ + .warn-pill { + font-size: 11px; color: var(--warn); border: 1px solid #4a3a1f; border-radius: 3px; + padding: 1px 6px; margin-left: 8px; + } + tr.repo.has-warn { box-shadow: inset 3px 0 0 var(--warn); } + tr.warn-row td { + padding: 0 16px 12px 40px; color: var(--warn); font-size: 12.5px; + white-space: normal; border-bottom: 1px solid var(--border); + } + tr.warn-row .tree { color: var(--muted); } + tr.warn-row code { color: var(--text); } + tr.warn-row .fix { + font: inherit; color: var(--accent); background: none; border: 0; padding: 0; margin-left: 6px; + cursor: pointer; text-decoration: underline dotted; + } + .file .warnmark { color: var(--warn); margin-left: auto; font-size: 11px; } + .banner.secret { background: #211b10; color: var(--warn); } + + .code { + flex: 1; display: flex; min-height: 0; overflow: hidden; background: var(--bg); + } + .gutter { + padding: 12px 10px 12px 14px; text-align: right; color: #3b4a5c; + font-size: 13px; line-height: 1.6; user-select: none; overflow: hidden; white-space: pre; + } + .code textarea { + flex: 1; resize: none; border: 0; outline: none; + background: transparent; color: var(--text); + font: inherit; font-size: 13px; line-height: 1.6; + padding: 12px 16px 12px 6px; white-space: pre; overflow: auto; tab-size: 2; + } + .code textarea[readonly] { color: #9aa7b6; } + + .drawer-foot { + display: flex; align-items: center; justify-content: space-between; gap: 10px; flex-wrap: wrap; + padding: 12px 16px; border-top: 1px solid var(--border); + } + .drawer-foot .state { font-size: 12px; color: var(--muted); } + .drawer-foot .state.dirty { color: var(--warn); } + .drawer-foot .btns { display: flex; gap: 8px; flex-wrap: wrap; } + + /* ---------- phones ---------- */ + @media (max-width: 760px) { + .drawer-main { grid-template-columns: 1fr; grid-template-rows: auto 1fr; } + .file-list { border-right: 0; border-bottom: 1px solid var(--border); padding: 8px 0; max-height: 34vh; } + .gutter { display: none; } + .code textarea { padding-left: 14px; } + .summary { grid-template-columns: repeat(2, 1fr); } + thead { display: none; } + table, tbody, tr, td { display: block; width: 100%; } + tr.repo { padding: 12px 16px; border-bottom: 1px solid var(--border); } + tr.repo td { border: 0; padding: 2px 0; display: flex; justify-content: space-between; gap: 12px; } + tr.repo td::before { content: attr(data-label); color: var(--muted); font-size: 12px; } + tr.repo td.name-cell::before, tr.repo td.actions-cell::before { content: none; } + tr.repo td.name-cell { font-size: 15px; padding-bottom: 6px; } + tr.repo td.actions-cell { padding-top: 10px; } + .actions { justify-content: flex-start; flex-wrap: wrap; } + tr.error-row td { padding: 0 16px 14px; border-bottom: 1px solid var(--border); } + .row2 { grid-template-columns: 1fr; } + } + + @media (prefers-reduced-motion: reduce) { + .heartbeat .dot, .dot.busy { animation: none; } + .toast { animation: none; } + #rain { display: none; } + } + +/* ---------- additions for the Flask version ---------- */ +.actions form { display: contents; } +.status.new { color: var(--muted); } +.dot.new { background: transparent; border: 1.5px dashed var(--muted); } +span.commit { cursor: default; } +span.commit:hover { text-decoration: none; } +.empty-state { text-align: center; padding: 64px 16px; color: var(--muted); } +.empty-state .big { color: var(--text); font-size: 16px; margin-bottom: 6px; } +.cursor { animation: blink 1s steps(1) infinite; color: var(--accent); } +@keyframes blink { 50% { opacity: 0; } } +.editor-loading { padding: 16px; color: var(--muted); } +@media (prefers-reduced-motion: reduce) { .cursor { animation: none; } } diff --git a/app/web/web/templates/base.html b/app/web/web/templates/base.html new file mode 100644 index 0000000..4d54152 --- /dev/null +++ b/app/web/web/templates/base.html @@ -0,0 +1,30 @@ + + + + + + +{% block title %}gitops-watcher{% endblock %} + + + + + + + + +
+ {% block content %}{% endblock %} +
+ +{% block overlays %}{% endblock %} + +
+ {% for kind, msg in get_flashed_messages(with_categories=true) %} +
{{ msg }}
+ {% endfor %} +
+ + + + diff --git a/app/web/web/templates/index.html b/app/web/web/templates/index.html new file mode 100644 index 0000000..8875b25 --- /dev/null +++ b/app/web/web/templates/index.html @@ -0,0 +1,215 @@ +{% extends "base.html" %} + +{% block title %}{% if counts.error %}({{ counts.error }}) {% endif %}gitops-watcher{% endblock %} + +{% block content %} +
+
☂ gitops-watcher / stacks
+
+
+ {% if not last_round %} + waiting for the watcher's first round… + {% elif stale %} + + watcher may be stuck · last check {{ last_round|ago }} + {% else %} + + watcher up · next check in … + {% endif %} +
+ +
+
+ +
+
repos
{{ total }}
+
ok
{{ counts.ok }}
+
error
{{ counts.error }}
+
paused
{{ counts.paused }}
+
+ +
+ {% if rows %} + + + + + + + + + {% for r in rows %} + {% set warn = r.missing_env and r.status != 'error' and not r.busy %} + + + + + + + + + {% if r.status == 'error' and r.error and not r.busy %} + + {% endif %} + {% if warn %} + + {% endif %} + {% endfor %} + +
repostatuscommitlast checklast deployactions
+ + + {% if r.busy %} + queued · {{ r.busy }} + {% elif r.status == 'new' %} + waiting + {% else %} + {{ r.status }} + {% endif %} + {% if warn %}⚠ .env{% endif %} + {% if r.commit %}{{ r.commit }}{% else %}-{% endif %}{{ r.last_check|ago }}{{ r.last_deploy|ago }} + {% if r.busy != 'add' %} +
+ + {% if r.status != 'paused' %} + + + + +
+ + +
+ {% else %} +
+ + +
+ {% endif %} + +
+ {% endif %} +
└─ {{ r.error }}
└─ .env is missing {{ r.missing_env|length }} key{{ 's' if r.missing_env|length > 1 }} from .env.example: + {% for k in r.missing_env %}{{ k }}{{ ", " if not loop.last }}{% endfor %} +
+ {% else %} +
+
no repos yet_
+
add one with + add repo, or edit repos.yml
+
+ {% endif %} +
+ + +{% endblock %} + + +{% block overlays %} + + + + + + + + +{% endblock %}