#!/usr/bin/env python3 """Seeds a fresh forge instance with realistic data through its own HTTP forms and REST API. Usage: seed.py BASE_URL OUT_DIR Writes OUT_DIR/seed.json with the session cookies and the ids the screenshot pass substitutes. Every step is best effort: a failing step is logged and the rest go on. """ import json import os import re import shutil import subprocess import sys import traceback import urllib.parse sys.path.insert(0, os.path.dirname(os.path.abspath(__file__))) from forgeclient import Client, field, raw_request # noqa: E402 BASE = sys.argv[1].rstrip("/") OUT = sys.argv[2] PASSWORD = "audit-password-1234" ADMIN, OTHER = "tahinli", "kaan" REPO, PRIV, ORG, ORG_REPO, TEAM = "forge-demo", "dotfiles", "forge-org", "infra", "core" seed = {"base": BASE, "admin": ADMIN, "other": OTHER, "repo": REPO, "private_repo": PRIV, "org": ORG, "org_repo": ORG_REPO, "team": TEAM, "failed_steps": []} def step(name): def wrap(fn): try: fn() print(f"[seed] ok {name}", flush=True) except Exception as e: # best effort print(f"[seed] FAIL {name}: {e}", flush=True) traceback.print_exc(limit=2) seed["failed_steps"].append(f"{name}: {e}") return fn return wrap def ok(resp, what): if resp.status >= 400: snippet = re.sub(r"\s+", " ", re.sub(r"<[^>]+>", " ", resp.text))[:300] raise RuntimeError(f"{what} -> HTTP {resp.status}: {snippet}") return resp def load_csrf(c): r = ok(c.get("/settings/profile"), "profile page") c.csrf = field(r.text, "csrf") if not c.csrf: raise RuntimeError("no csrf on /settings/profile") admin = Client(BASE) other = Client(BASE) def login(c, user): r = c.get("/login") pre = field(r.text, "precsrf") ok(c.post("/login", {"precsrf": pre, "username": user, "password": PASSWORD, "next": "/"}), "login") load_csrf(c) @step("setup admin") def _(): r = admin.get("/setup") pre = field(r.text, "precsrf") if r.status == 200 and pre: ok(admin.post("/setup", {"precsrf": pre, "username": ADMIN, "email": "tahinli@example.com", "password": PASSWORD, "confirm": PASSWORD}), "setup") load_csrf(admin) else: login(admin, ADMIN) @step("create second user") def _(): ok(admin.post("/admin/users", {"username": OTHER, "email": "kaan@example.com", "password": PASSWORD}), "admin create user") login(other, OTHER) @step("profile bio") def _(): r = admin.get("/settings/profile") names = set(re.findall(r'name="([a-z_]+)"', r.text)) fields = {k: "" for k in names if k not in ("csrf",)} fields.update({k: v for k, v in { "full_name": "Ahmet Kaan Gümüş", "display_name": "Ahmet Kaan Gümüş", "name": "Ahmet Kaan Gümüş", "bio": "Building my own forge. Rust, git, and self-hosting.", "location": "Istanbul", "website": "https://example.com", "pronouns": "he/him", }.items() if k in names}) ok(admin.post("/settings/profile", fields), "profile save") @step("personal access token") def _(): r = ok(admin.post("/settings/tokens", {"name": "audit-cli", "expires": "90"}), "token create") m = re.search(r"forge_[A-Za-z0-9_\-]{16,}", r.text) if not m: raise RuntimeError("token not shown") seed["pat"] = m.group(0) admin.post("/settings/tokens", {"name": "ci-deploy", "expires": "never"}) r = ok(other.post("/settings/tokens", {"name": "kaan-laptop", "expires": "30"}), "token2") m = re.search(r"forge_[A-Za-z0-9_\-]{16,}", r.text) seed["pat_other"] = m.group(0) if m else None @step("ssh key") def _(): d = os.path.join(OUT, "sshkey") shutil.rmtree(d, ignore_errors=True) os.makedirs(d) subprocess.run(["ssh-keygen", "-q", "-t", "ed25519", "-N", "", "-C", "tahinli@laptop", "-f", os.path.join(d, "id")], check=True) pub = open(os.path.join(d, "id.pub")).read().strip() ok(admin.post("/settings/keys", {"title": "laptop", "public_key": pub}), "add key") @step("repositories") def _(): ok(admin.post("/new", {"name": REPO, "description": "A demo project for the visual audit: Rust, docs and CI.", "visibility": "public", "default_branch": "main", "default_labels": "on", "owner": ADMIN}), "new repo") ok(admin.post("/new", {"name": PRIV, "description": "Private config files.", "visibility": "private", "default_branch": "main", "owner": ADMIN}), "new private repo") ok(other.post("/new", {"name": "kaan-scratch", "description": "Kaan's experiments.", "visibility": "public", "default_branch": "main", "owner": OTHER}), "kaan repo") def git(cwd, *args, env=None): e = dict(os.environ, GIT_TERMINAL_PROMPT="0", GIT_CONFIG_NOSYSTEM="1", GIT_AUTHOR_NAME="Ahmet Kaan Gümüş", GIT_AUTHOR_EMAIL="tahinli@example.com", GIT_COMMITTER_NAME="Ahmet Kaan Gümüş", GIT_COMMITTER_EMAIL="tahinli@example.com", HOME=os.path.join(OUT, "githome")) e.update(env or {}) os.makedirs(e["HOME"], exist_ok=True) return subprocess.run(["git", *args], cwd=cwd, env=e, check=True, capture_output=True, text=True).stdout def write(root, rel, text): p = os.path.join(root, rel) os.makedirs(os.path.dirname(p), exist_ok=True) with open(p, "w") as f: f.write(text) README = """# forge-demo A small Rust project used to exercise every page of the forge. ## Features - Fast `git` hosting with **smart HTTP** and SSH - Issues, pull requests, releases and a wiki - A commit heatmap that keeps you motivated ## Usage ```sh cargo run -- --config config/forge.toml ``` | Command | What it does | | --- | --- | | `serve` | Starts the web UI | | `backup` | Writes a backup set | > Tip: keep the data dir on a fast disk. """ MAIN_RS = """//! Entry point of the demo. use std::env; /// Greets the person named on the command line. fn greet(name: &str) -> String { format!("Hello, {name}!") } fn main() { let name = env::args().nth(1).unwrap_or_else(|| "world".to_owned()); println!("{}", greet(&name)); } #[cfg(test)] mod tests { use super::*; #[test] fn greets() { assert_eq!(greet("tahinli"), "Hello, tahinli!"); } } """ CI = """[on] push = ["main"] pull_request = true manual = true [jobs.test] image = "docker.io/library/rust:1" run = \"\"\" cargo test \"\"\" [jobs.lint] image = "docker.io/library/rust:1" run = "cargo clippy" [jobs.package] image = "docker.io/library/rust:1" needs = ["test", "lint"] run = "cargo build --release" [jobs.publish] image = "docker.io/library/rust:1" needs = ["package"] run = "echo publish" """ CARGO_LOCK = """version = 4 [[package]] name = "forge-demo" version = "0.2.0" [[package]] name = "smallvec" version = "1.6.0" source = "registry+https://github.com/rust-lang/crates.io-index" """ @step("push git history") def _(): work = os.path.join(OUT, "work", REPO) shutil.rmtree(work, ignore_errors=True) os.makedirs(work) git(work, "init", "-q", "-b", "main") commits = [ ("2026-09-01T10:00:00", {"README.md": README, "Cargo.toml": '[package]\nname = "forge-demo"\nversion = "0.1.0"\nedition = "2024"\n'}, "Initial commit"), ("2026-09-03T12:30:00", {"src/main.rs": MAIN_RS}, "Add greeting binary"), ("2026-09-08T09:15:00", {"docs/guide.md": "# Guide\n\nRun `cargo run`.\n\n## Config\n\nSee `config/forge.toml`.\n", "config/forge.toml": 'listen = "127.0.0.1:7660"\nregistration = "closed"\n'}, "Add docs and config"), ("2026-09-15T18:45:00", {".forge/ci.toml": CI, "Cargo.lock": CARGO_LOCK}, "Add CI workflow"), ("2026-10-01T08:00:00", {"src/lib.rs": "//! Library part.\n\npub fn add(a: u32, b: u32) -> u32 {\n a + b\n}\n", "Cargo.toml": '[package]\nname = "forge-demo"\nversion = "0.2.0"\nedition = "2024"\n'}, "Release 0.2.0"), ] for i, (date, files, msg) in enumerate(commits): for rel, text in files.items(): write(work, rel, text) git(work, "add", "-A") git(work, "commit", "-q", "-m", msg, env={"GIT_AUTHOR_DATE": date, "GIT_COMMITTER_DATE": date}) if i == 2: git(work, "tag", "-a", "v0.1.0", "-m", "Version 0.1.0") git(work, "tag", "-a", "v0.2.0", "-m", "Version 0.2.0") git(work, "checkout", "-q", "-b", "feature/heatmap") write(work, "src/heatmap.rs", "//! Commit heatmap.\n\npub fn cells(days: usize) -> Vec {\n vec![0; days]\n}\n") write(work, "README.md", README + "\n## Heatmap\n\nShows a year of commits.\n") git(work, "add", "-A") git(work, "commit", "-q", "-m", "Add commit heatmap module") write(work, "src/heatmap.rs", "//! Commit heatmap.\n\n/// One cell per day.\npub fn cells(days: usize) -> Vec {\n vec![0; days]\n}\n") git(work, "commit", "-q", "-am", "Document heatmap cells") git(work, "checkout", "-q", "main") git(work, "checkout", "-q", "-b", "docs/typos") write(work, "docs/guide.md", "# Guide\n\nRun `cargo run --release`.\n") git(work, "commit", "-q", "-am", "Fix guide typos") git(work, "checkout", "-q", "main") host = urllib.parse.urlsplit(BASE).netloc url = f"http://{ADMIN}:{seed['pat']}@{host}/{ADMIN}/{REPO}.git" git(work, "push", "-q", url, "--all") git(work, "push", "-q", url, "--tags") seed["head_oid"] = git(work, "rev-parse", "main").strip() seed["first_oid"] = git(work, "rev-list", "--max-parents=0", "main").strip() seed["blob_path"] = "src/main.rs" seed["tree_path"] = "src" # second repo: a single commit so it is not empty w2 = os.path.join(OUT, "work", PRIV) shutil.rmtree(w2, ignore_errors=True) os.makedirs(w2) git(w2, "init", "-q", "-b", "main") write(w2, ".bashrc", "export EDITOR=hx\n") write(w2, "README.md", "# dotfiles\n\nMy shell setup.\n") git(w2, "add", "-A") git(w2, "commit", "-q", "-m", "Add dotfiles") git(w2, "push", "-q", f"http://{ADMIN}:{seed['pat']}@{host}/{ADMIN}/{PRIV}.git", "main") R = f"/{ADMIN}/{REPO}" @step("labels and milestones") def _(): ok(admin.post(f"{R}/labels", {"name": "ui", "color": "#7c9a6d", "description": "Visual and layout work"}), "label") ok(admin.post(f"{R}/labels", {"name": "needs-triage", "color": "#d4a72c", "description": ""}), "label2") ok(admin.post(f"{R}/milestones", {"title": "v0.3.0", "description": "Heatmap and wiki polish", "due_on": "2026-12-01", "state": "open"}), "milestone") admin.post(f"{R}/milestones", {"title": "v0.2.0", "description": "Shipped", "due_on": "", "state": "closed"}) r = admin.get(f"{R}/milestones") m = re.search(r"/milestones/([^/\"]+)/edit", r.text) seed["milestone_id"] = m.group(1) if m else None @step("issues and comments") def _(): issues = [ ("Heatmap cells overflow on narrow screens", "On a 390px wide phone the heatmap scrolls sideways.\n\n- [ ] fix grid\n- [x] reproduce"), ("Add dark theme screenshots to the docs", "We should show both themes in `docs/`."), ("Release assets are missing checksums", "Each release should ship a `SHA256SUMS` file."), ("Wiki sidebar collapses unexpectedly", "Steps:\n1. open wiki\n2. resize\n\n```rust\nfn main() {}\n```"), ] for title, body in issues: ok(admin.post(f"{R}/issues/new", {"title": title, "body": body}), "issue") ok(other.post(f"{R}/issues/new", {"title": "Clone URL copy button does nothing", "body": "Firefox 158, clicking copy shows no toast."}), "issue by kaan") page = admin.get(f"{R}/issues/1").text labels = re.findall(r'name="label"[^>]*value="([^"]+)"', page) or re.findall(r'value="([^"]+)"[^>]*name="label"', page) if labels: admin.post(f"{R}/issues/1/labels", [("label", v) for v in labels[:3]]) admin.post(f"{R}/issues/3/labels", [("label", labels[-1])]) mid = seed.get("milestone_id") if mid: admin.post(f"{R}/issues/1/milestone", {"milestone": mid, "milestone_id": mid}) ok(other.post(f"{R}/issues/1/comment", {"body": "I can reproduce this on Android too. :+1:"}), "comment kaan") ok(admin.post(f"{R}/issues/1/comment", {"body": "Thanks @kaan, looking into the grid now."}), "comment admin") other.post(f"{R}/issues/2/comment", {"body": "Happy to help with the screenshots."}) page = admin.get(f"{R}/issues/1").text m = re.search(r"/issues/1/comments/([^/\"]+)/edit", page) seed["issue_comment_id"] = m.group(1) if m else None admin.post(f"{R}/issues/1/edit", {"title": "Heatmap cells overflow on narrow screens (mobile)", "body": issues[0][1] + "\n\nEdited: also on tablets."}) page = admin.get(f"{R}/issues/1").text m = re.search(r"/issues/1/history/([^/\"]+)/([^/\"]+)", page) if m: seed["issue_history"] = [m.group(1), m.group(2)] admin.post(f"{R}/issues/4/comment", {"body": "Fixed in main.", "action": "close_completed"}) @step("pull request") def _(): ok(other.post(f"{R}/pulls", {"title": "Add commit heatmap module", "body": "Adds `src/heatmap.rs`.\n\nCloses #1", "base": "main", "head": "feature/heatmap"}), "pull by kaan") admin.post(f"{R}/pulls", {"title": "Fix guide typos", "body": "Small docs fix.", "base": "main", "head": "docs/typos"}) r = admin.get(f"{R}/pulls") nums = sorted({int(n) for n in re.findall(rf"{re.escape(R)}/pulls/(\d+)", r.text)}) seed["pull_number"] = nums[0] if nums else 6 n = seed["pull_number"] other.post(f"{R}/pulls/{n}/comments", {"body": "Ready for review."}) admin.post(f"{R}/pulls/{n}/comments", {"body": "Looks good, one nit on the doc comment."}) page = admin.get(f"{R}/pulls/{n}").text m = re.search(rf"/pulls/{n}/comments/([^/\"]+)/edit", page) seed["pull_comment_id"] = m.group(1) if m else None page = admin.get(f"{R}/pulls/{n}/files").text # leave a review comment on the first diff line if the form exposes its fields form = re.search(r']*action="[^"]*/review_comments"[^>]*>(.*?)', page, re.S) if form: fields = dict(re.findall(r'name="([a-z_]+)"[^>]*value="([^"]*)"', form.group(1))) fields["body"] = "Consider documenting the return value." admin.post(f"{R}/pulls/{n}/review_comments", fields) page = admin.get(f"{R}/pulls/{n}/files").text m = re.search(rf"/pulls/{n}/review_comments/([^/\"]+)/edit", page) seed["review_comment_id"] = m.group(1) if m else None @step("release with assets (REST API)") def _(): h = {"Authorization": f"Bearer {seed['pat']}", "Content-Type": "application/json"} api = f"{BASE}/api/v1/repos/{ADMIN}/{REPO}/releases" r = raw_request(api, "POST", json.dumps({"tag": "v0.2.0", "title": "Version 0.2.0", "body": "## Changes\n\n- Library crate\n- CI workflow\n\n**Full changelog**: v0.1.0...v0.2.0"}).encode(), h) ok(r, "create release") rid = r.json()["id"] seed["release_id"] = rid for name, data, ctype in [("forge-demo-linux-x86_64.tar.gz", os.urandom(40_000), "application/gzip"), ("SHA256SUMS", b"abc123 forge-demo-linux-x86_64.tar.gz\n", "text/plain")]: ok(raw_request(f"{api}/{rid}/assets/{name}", "PUT", data, {"Authorization": f"Bearer {seed['pat']}", "Content-Type": ctype}), "asset") r = raw_request(api, "POST", json.dumps({"tag": "v0.1.0", "title": "Version 0.1.0", "body": "First release."}).encode(), h) raw_request(api, "POST", json.dumps({"tag": "v0.3.0-rc1", "target": "main", "title": "0.3.0 RC 1", "body": "Draft notes.", "draft": True, "prerelease": True}).encode(), h) @step("wiki") def _(): r = admin.get(f"{R}/wiki/-/new") base = field(r.text, "base") or "" ok(admin.post(f"{R}/wiki/-/new", {"base": base, "name": "Home", "content": "# Welcome\n\nThis is the **forge-demo** wiki.\n\n- [[Install]]\n- [[Architecture]]\n", "message": "Create Home"}), "wiki home") for name, content in [("Install", "# Install\n\n```sh\ncargo install --path .\n```\n"), ("Architecture", "# Architecture\n\n| Crate | Role |\n| --- | --- |\n| core | store |\n| web | UI |\n")]: r = admin.get(f"{R}/wiki/-/new") admin.post(f"{R}/wiki/-/new", {"base": field(r.text, "base") or "", "name": name, "content": content, "message": f"Add {name}"}) r = admin.get(f"{R}/wiki/Home/edit") admin.post(f"{R}/wiki/Home/edit", {"base": field(r.text, "base") or "", "name": "Home", "content": "# Welcome\n\nThis is the **forge-demo** wiki. Start with [[Install]].\n", "message": "Tweak Home"}) @step("snippets") def _(): r = ok(admin.post("/snippets/new", {"title": "Backup cron", "description": "Nightly backup with restic", "visibility": "public", "name_0": "backup.sh", "content_0": "#!/bin/sh\nrestic backup /var/lib/forge\n", "name_1": "notes.md", "content_1": "# Notes\n\nRun at 03:00.\n"}), "snippet") m = re.search(r"/snippets/([A-Za-z0-9_-]+)", r.url or "") sid = m.group(1) if m and m.group(1) != "new" else None if not sid: m = re.findall(r'/snippets/([A-Za-z0-9_-]+)"', admin.get("/snippets").text) sid = next((x for x in m if x != "new"), None) seed["snippet_id"] = sid if sid: r = admin.get(f"/snippets/{sid}/edit") admin.post(f"/snippets/{sid}/edit", {"title": "Backup cron", "description": "Nightly backup with restic (edited)", "visibility": "public", "name_0": "backup.sh", "content_0": "#!/bin/sh\nset -eu\nrestic backup /var/lib/forge\n"}) other.post("/snippets/new", {"title": "fish prompt", "description": "", "visibility": "public", "name_0": "config.fish", "content_0": "set -g fish_greeting\n"}) @step("organization, members and teams") def _(): ok(admin.post("/org/new", {"name": ORG, "description": "The people building forge."}), "org") ok(admin.post(f"/org/{ORG}/members/add", {"username": OTHER, "role": "member"}), "member add") ok(admin.post("/new", {"name": ORG_REPO, "description": "Deployment and infra scripts.", "visibility": "public", "default_branch": "main", "owner": ORG}), "org repo") ok(admin.post(f"/org/{ORG}/teams/new", {"name": TEAM, "description": "Core maintainers", "role": "write", "all_repos": ""}), "team") r = admin.get(f"/org/{ORG}/teams") m = re.search(rf"/org/{ORG}/teams/([A-Za-z0-9_.-]+)\"", r.text) if m: seed["team"] = m.group(1) admin.post(f"/org/{ORG}/teams/{seed['team']}/members/add", {"username": OTHER}) admin.post(f"/org/{ORG}/teams/new", {"name": "docs", "description": "Docs writers", "role": "read", "all_repos": "on"}) @step("stars and watches") def _(): other.post(f"{R}/star", {}) admin.post(f"{R}/star", {}) admin.post(f"/{OTHER}/kaan-scratch/star", {}) @step("collaborator") def _(): admin.post(f"{R}/settings/collaborators/add", {"username": OTHER, "role": "write"}) @step("discussion") def _(): r = admin.get(f"{R}/discussions/new") if r.status >= 400: admin.post(f"{R}/settings/discussions", {"enabled": "1"}) r = admin.get(f"{R}/discussions/new") cats = re.findall(r'