forge
Explore
Log in

Don't you dare go Hollow

forge

Clone
★ 0

0 watching0 forksRustAGPL-3.010.5 MiB2e29cbcTahinli1 hour ago333 commits

seed.py540 lines, 22.4 KiBHistoryRawDownload
1#!/usr/bin/env python3
2"""Seeds a fresh forge instance with realistic data through its own HTTP forms and REST API.
3
4Usage: seed.py BASE_URL OUT_DIR
5Writes OUT_DIR/seed.json with the session cookies and the ids the screenshot pass substitutes.
6Every step is best effort: a failing step is logged and the rest go on.
7"""
8
9import json
10import os
11import re
12import shutil
13import subprocess
14import sys
15import traceback
16import urllib.parse
17
18sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
19from forgeclient import Client, field, raw_request # noqa: E402
20
21BASE = sys.argv[1].rstrip("/")
22OUT = sys.argv[2]
23PASSWORD = "audit-password-1234"
24ADMIN, OTHER = "tahinli", "kaan"
25REPO, PRIV, ORG, ORG_REPO, TEAM = "forge-demo", "dotfiles", "forge-org", "infra", "core"
26
27seed = {"base": BASE, "admin": ADMIN, "other": OTHER, "repo": REPO, "private_repo": PRIV,
28 "org": ORG, "org_repo": ORG_REPO, "team": TEAM, "failed_steps": []}
29
30
31def step(name):
32 def wrap(fn):
33 try:
34 fn()
35 print(f"[seed] ok {name}", flush=True)
36 except Exception as e: # best effort
37 print(f"[seed] FAIL {name}: {e}", flush=True)
38 traceback.print_exc(limit=2)
39 seed["failed_steps"].append(f"{name}: {e}")
40 return fn
41 return wrap
42
43
44def ok(resp, what):
45 if resp.status >= 400:
46 snippet = re.sub(r"\s+", " ", re.sub(r"<[^>]+>", " ", resp.text))[:300]
47 raise RuntimeError(f"{what} -> HTTP {resp.status}: {snippet}")
48 return resp
49
50
51def load_csrf(c):
52 r = ok(c.get("/settings/profile"), "profile page")
53 c.csrf = field(r.text, "csrf")
54 if not c.csrf:
55 raise RuntimeError("no csrf on /settings/profile")
56
57
58admin = Client(BASE)
59other = Client(BASE)
60
61
62def login(c, user):
63 r = c.get("/login")
64 pre = field(r.text, "precsrf")
65 ok(c.post("/login", {"precsrf": pre, "username": user, "password": PASSWORD, "next": "/"}), "login")
66 load_csrf(c)
67
68
69@step("setup admin")
70def _():
71 r = admin.get("/setup")
72 pre = field(r.text, "precsrf")
73 if r.status == 200 and pre:
74 ok(admin.post("/setup", {"precsrf": pre, "username": ADMIN, "email": "tahinli@example.com",
75 "password": PASSWORD, "confirm": PASSWORD}), "setup")
76 load_csrf(admin)
77 else:
78 login(admin, ADMIN)
79
80
81@step("create second user")
82def _():
83 ok(admin.post("/admin/users", {"username": OTHER, "email": "kaan@example.com",
84 "password": PASSWORD}), "admin create user")
85 login(other, OTHER)
86
87
88@step("profile bio")
89def _():
90 r = admin.get("/settings/profile")
91 names = set(re.findall(r'name="([a-z_]+)"', r.text))
92 fields = {k: "" for k in names if k not in ("csrf",)}
93 fields.update({k: v for k, v in {
94 "full_name": "Ahmet Kaan Gümüş", "display_name": "Ahmet Kaan Gümüş", "name": "Ahmet Kaan Gümüş",
95 "bio": "Building my own forge. Rust, git, and self-hosting.",
96 "location": "Istanbul", "website": "https://example.com", "pronouns": "he/him",
97 }.items() if k in names})
98 ok(admin.post("/settings/profile", fields), "profile save")
99
100
101@step("personal access token")
102def _():
103 r = ok(admin.post("/settings/tokens", {"name": "audit-cli", "expires": "90"}), "token create")
104 m = re.search(r"forge_[A-Za-z0-9_\-]{16,}", r.text)
105 if not m:
106 raise RuntimeError("token not shown")
107 seed["pat"] = m.group(0)
108 admin.post("/settings/tokens", {"name": "ci-deploy", "expires": "never"})
109 r = ok(other.post("/settings/tokens", {"name": "kaan-laptop", "expires": "30"}), "token2")
110 m = re.search(r"forge_[A-Za-z0-9_\-]{16,}", r.text)
111 seed["pat_other"] = m.group(0) if m else None
112
113
114@step("ssh key")
115def _():
116 d = os.path.join(OUT, "sshkey")
117 shutil.rmtree(d, ignore_errors=True)
118 os.makedirs(d)
119 subprocess.run(["ssh-keygen", "-q", "-t", "ed25519", "-N", "", "-C", "tahinli@laptop",
120 "-f", os.path.join(d, "id")], check=True)
121 pub = open(os.path.join(d, "id.pub")).read().strip()
122 ok(admin.post("/settings/keys", {"title": "laptop", "public_key": pub}), "add key")
123
124
125@step("repositories")
126def _():
127 ok(admin.post("/new", {"name": REPO, "description": "A demo project for the visual audit: Rust, docs and CI.",
128 "visibility": "public", "default_branch": "main", "default_labels": "on",
129 "owner": ADMIN}), "new repo")
130 ok(admin.post("/new", {"name": PRIV, "description": "Private config files.", "visibility": "private",
131 "default_branch": "main", "owner": ADMIN}), "new private repo")
132 ok(other.post("/new", {"name": "kaan-scratch", "description": "Kaan's experiments.",
133 "visibility": "public", "default_branch": "main", "owner": OTHER}), "kaan repo")
134
135
136def git(cwd, *args, env=None):
137 e = dict(os.environ, GIT_TERMINAL_PROMPT="0", GIT_CONFIG_NOSYSTEM="1",
138 GIT_AUTHOR_NAME="Ahmet Kaan Gümüş", GIT_AUTHOR_EMAIL="tahinli@example.com",
139 GIT_COMMITTER_NAME="Ahmet Kaan Gümüş", GIT_COMMITTER_EMAIL="tahinli@example.com",
140 HOME=os.path.join(OUT, "githome"))
141 e.update(env or {})
142 os.makedirs(e["HOME"], exist_ok=True)
143 return subprocess.run(["git", *args], cwd=cwd, env=e, check=True, capture_output=True, text=True).stdout
144
145
146def write(root, rel, text):
147 p = os.path.join(root, rel)
148 os.makedirs(os.path.dirname(p), exist_ok=True)
149 with open(p, "w") as f:
150 f.write(text)
151
152
153README = """# forge-demo
154
155A small Rust project used to exercise every page of the forge.
156
157## Features
158
159- Fast `git` hosting with **smart HTTP** and SSH
160- Issues, pull requests, releases and a wiki
161- A commit heatmap that keeps you motivated
162
163## Usage
164
165```sh
166cargo run -- --config config/forge.toml
167```
168
169| Command | What it does |
170| --- | --- |
171| `serve` | Starts the web UI |
172| `backup` | Writes a backup set |
173
174> Tip: keep the data dir on a fast disk.
175"""
176
177MAIN_RS = """//! Entry point of the demo.
178
179use std::env;
180
181/// Greets the person named on the command line.
182fn greet(name: &str) -> String {
183 format!("Hello, {name}!")
184}
185
186fn main() {
187 let name = env::args().nth(1).unwrap_or_else(|| "world".to_owned());
188 println!("{}", greet(&name));
189}
190
191#[cfg(test)]
192mod tests {
193 use super::*;
194
195 #[test]
196 fn greets() {
197 assert_eq!(greet("tahinli"), "Hello, tahinli!");
198 }
199}
200"""
201
202CI = """[on]
203push = ["main"]
204pull_request = true
205manual = true
206
207[jobs.test]
208image = "docker.io/library/rust:1"
209run = \"\"\"
210cargo test
211\"\"\"
212
213[jobs.lint]
214image = "docker.io/library/rust:1"
215run = "cargo clippy"
216
217[jobs.package]
218image = "docker.io/library/rust:1"
219needs = ["test", "lint"]
220run = "cargo build --release"
221
222[jobs.publish]
223image = "docker.io/library/rust:1"
224needs = ["package"]
225run = "echo publish"
226"""
227
228CARGO_LOCK = """version = 4
229
230[[package]]
231name = "forge-demo"
232version = "0.2.0"
233
234[[package]]
235name = "smallvec"
236version = "1.6.0"
237source = "registry+https://github.com/rust-lang/crates.io-index"
238"""
239
240
241@step("push git history")
242def _():
243 work = os.path.join(OUT, "work", REPO)
244 shutil.rmtree(work, ignore_errors=True)
245 os.makedirs(work)
246 git(work, "init", "-q", "-b", "main")
247 commits = [
248 ("2026-09-01T10:00:00", {"README.md": README, "Cargo.toml": '[package]\nname = "forge-demo"\nversion = "0.1.0"\nedition = "2024"\n'},
249 "Initial commit"),
250 ("2026-09-03T12:30:00", {"src/main.rs": MAIN_RS}, "Add greeting binary"),
251 ("2026-09-08T09:15:00", {"docs/guide.md": "# Guide\n\nRun `cargo run`.\n\n## Config\n\nSee `config/forge.toml`.\n",
252 "config/forge.toml": 'listen = "127.0.0.1:7660"\nregistration = "closed"\n'},
253 "Add docs and config"),
254 ("2026-09-15T18:45:00", {".forge/ci.toml": CI, "Cargo.lock": CARGO_LOCK}, "Add CI workflow"),
255 ("2026-10-01T08:00:00", {"src/lib.rs": "//! Library part.\n\npub fn add(a: u32, b: u32) -> u32 {\n a + b\n}\n",
256 "Cargo.toml": '[package]\nname = "forge-demo"\nversion = "0.2.0"\nedition = "2024"\n'},
257 "Release 0.2.0"),
258 ]
259 for i, (date, files, msg) in enumerate(commits):
260 for rel, text in files.items():
261 write(work, rel, text)
262 git(work, "add", "-A")
263 git(work, "commit", "-q", "-m", msg, env={"GIT_AUTHOR_DATE": date, "GIT_COMMITTER_DATE": date})
264 if i == 2:
265 git(work, "tag", "-a", "v0.1.0", "-m", "Version 0.1.0")
266 git(work, "tag", "-a", "v0.2.0", "-m", "Version 0.2.0")
267 git(work, "checkout", "-q", "-b", "feature/heatmap")
268 write(work, "src/heatmap.rs", "//! Commit heatmap.\n\npub fn cells(days: usize) -> Vec<u8> {\n vec![0; days]\n}\n")
269 write(work, "README.md", README + "\n## Heatmap\n\nShows a year of commits.\n")
270 git(work, "add", "-A")
271 git(work, "commit", "-q", "-m", "Add commit heatmap module")
272 write(work, "src/heatmap.rs", "//! Commit heatmap.\n\n/// One cell per day.\npub fn cells(days: usize) -> Vec<u8> {\n vec![0; days]\n}\n")
273 git(work, "commit", "-q", "-am", "Document heatmap cells")
274 git(work, "checkout", "-q", "main")
275 git(work, "checkout", "-q", "-b", "docs/typos")
276 write(work, "docs/guide.md", "# Guide\n\nRun `cargo run --release`.\n")
277 git(work, "commit", "-q", "-am", "Fix guide typos")
278 git(work, "checkout", "-q", "main")
279 host = urllib.parse.urlsplit(BASE).netloc
280 url = f"http://{ADMIN}:{seed['pat']}@{host}/{ADMIN}/{REPO}.git"
281 git(work, "push", "-q", url, "--all")
282 git(work, "push", "-q", url, "--tags")
283 seed["head_oid"] = git(work, "rev-parse", "main").strip()
284 seed["first_oid"] = git(work, "rev-list", "--max-parents=0", "main").strip()
285 seed["blob_path"] = "src/main.rs"
286 seed["tree_path"] = "src"
287 # second repo: a single commit so it is not empty
288 w2 = os.path.join(OUT, "work", PRIV)
289 shutil.rmtree(w2, ignore_errors=True)
290 os.makedirs(w2)
291 git(w2, "init", "-q", "-b", "main")
292 write(w2, ".bashrc", "export EDITOR=hx\n")
293 write(w2, "README.md", "# dotfiles\n\nMy shell setup.\n")
294 git(w2, "add", "-A")
295 git(w2, "commit", "-q", "-m", "Add dotfiles")
296 git(w2, "push", "-q", f"http://{ADMIN}:{seed['pat']}@{host}/{ADMIN}/{PRIV}.git", "main")
297
298
299R = f"/{ADMIN}/{REPO}"
300
301
302@step("labels and milestones")
303def _():
304 ok(admin.post(f"{R}/labels", {"name": "ui", "color": "#7c9a6d", "description": "Visual and layout work"}), "label")
305 ok(admin.post(f"{R}/labels", {"name": "needs-triage", "color": "#d4a72c", "description": ""}), "label2")
306 ok(admin.post(f"{R}/milestones", {"title": "v0.3.0", "description": "Heatmap and wiki polish",
307 "due_on": "2026-12-01", "state": "open"}), "milestone")
308 admin.post(f"{R}/milestones", {"title": "v0.2.0", "description": "Shipped", "due_on": "", "state": "closed"})
309 r = admin.get(f"{R}/milestones")
310 m = re.search(r"/milestones/([^/\"]+)/edit", r.text)
311 seed["milestone_id"] = m.group(1) if m else None
312
313
314@step("issues and comments")
315def _():
316 issues = [
317 ("Heatmap cells overflow on narrow screens", "On a 390px wide phone the heatmap scrolls sideways.\n\n- [ ] fix grid\n- [x] reproduce"),
318 ("Add dark theme screenshots to the docs", "We should show both themes in `docs/`."),
319 ("Release assets are missing checksums", "Each release should ship a `SHA256SUMS` file."),
320 ("Wiki sidebar collapses unexpectedly", "Steps:\n1. open wiki\n2. resize\n\n```rust\nfn main() {}\n```"),
321 ]
322 for title, body in issues:
323 ok(admin.post(f"{R}/issues/new", {"title": title, "body": body}), "issue")
324 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")
325 page = admin.get(f"{R}/issues/1").text
326 labels = re.findall(r'name="label"[^>]*value="([^"]+)"', page) or re.findall(r'value="([^"]+)"[^>]*name="label"', page)
327 if labels:
328 admin.post(f"{R}/issues/1/labels", [("label", v) for v in labels[:3]])
329 admin.post(f"{R}/issues/3/labels", [("label", labels[-1])])
330 mid = seed.get("milestone_id")
331 if mid:
332 admin.post(f"{R}/issues/1/milestone", {"milestone": mid, "milestone_id": mid})
333 ok(other.post(f"{R}/issues/1/comment", {"body": "I can reproduce this on Android too. :+1:"}), "comment kaan")
334 ok(admin.post(f"{R}/issues/1/comment", {"body": "Thanks @kaan, looking into the grid now."}), "comment admin")
335 other.post(f"{R}/issues/2/comment", {"body": "Happy to help with the screenshots."})
336 page = admin.get(f"{R}/issues/1").text
337 m = re.search(r"/issues/1/comments/([^/\"]+)/edit", page)
338 seed["issue_comment_id"] = m.group(1) if m else None
339 admin.post(f"{R}/issues/1/edit", {"title": "Heatmap cells overflow on narrow screens (mobile)",
340 "body": issues[0][1] + "\n\nEdited: also on tablets."})
341 page = admin.get(f"{R}/issues/1").text
342 m = re.search(r"/issues/1/history/([^/\"]+)/([^/\"]+)", page)
343 if m:
344 seed["issue_history"] = [m.group(1), m.group(2)]
345 admin.post(f"{R}/issues/4/comment", {"body": "Fixed in main.", "action": "close_completed"})
346
347
348@step("pull request")
349def _():
350 ok(other.post(f"{R}/pulls", {"title": "Add commit heatmap module", "body": "Adds `src/heatmap.rs`.\n\nCloses #1",
351 "base": "main", "head": "feature/heatmap"}), "pull by kaan")
352 admin.post(f"{R}/pulls", {"title": "Fix guide typos", "body": "Small docs fix.", "base": "main", "head": "docs/typos"})
353 r = admin.get(f"{R}/pulls")
354 nums = sorted({int(n) for n in re.findall(rf"{re.escape(R)}/pulls/(\d+)", r.text)})
355 seed["pull_number"] = nums[0] if nums else 6
356 n = seed["pull_number"]
357 other.post(f"{R}/pulls/{n}/comments", {"body": "Ready for review."})
358 admin.post(f"{R}/pulls/{n}/comments", {"body": "Looks good, one nit on the doc comment."})
359 page = admin.get(f"{R}/pulls/{n}").text
360 m = re.search(rf"/pulls/{n}/comments/([^/\"]+)/edit", page)
361 seed["pull_comment_id"] = m.group(1) if m else None
362 page = admin.get(f"{R}/pulls/{n}/files").text
363 # leave a review comment on the first diff line if the form exposes its fields
364 form = re.search(r'<form[^>]*action="[^"]*/review_comments"[^>]*>(.*?)</form>', page, re.S)
365 if form:
366 fields = dict(re.findall(r'name="([a-z_]+)"[^>]*value="([^"]*)"', form.group(1)))
367 fields["body"] = "Consider documenting the return value."
368 admin.post(f"{R}/pulls/{n}/review_comments", fields)
369 page = admin.get(f"{R}/pulls/{n}/files").text
370 m = re.search(rf"/pulls/{n}/review_comments/([^/\"]+)/edit", page)
371 seed["review_comment_id"] = m.group(1) if m else None
372
373
374@step("release with assets (REST API)")
375def _():
376 h = {"Authorization": f"Bearer {seed['pat']}", "Content-Type": "application/json"}
377 api = f"{BASE}/api/v1/repos/{ADMIN}/{REPO}/releases"
378 r = raw_request(api, "POST", json.dumps({"tag": "v0.2.0", "title": "Version 0.2.0",
379 "body": "## Changes\n\n- Library crate\n- CI workflow\n\n**Full changelog**: v0.1.0...v0.2.0"}).encode(), h)
380 ok(r, "create release")
381 rid = r.json()["id"]
382 seed["release_id"] = rid
383 for name, data, ctype in [("forge-demo-linux-x86_64.tar.gz", os.urandom(40_000), "application/gzip"),
384 ("SHA256SUMS", b"abc123 forge-demo-linux-x86_64.tar.gz\n", "text/plain")]:
385 ok(raw_request(f"{api}/{rid}/assets/{name}", "PUT", data,
386 {"Authorization": f"Bearer {seed['pat']}", "Content-Type": ctype}), "asset")
387 r = raw_request(api, "POST", json.dumps({"tag": "v0.1.0", "title": "Version 0.1.0", "body": "First release."}).encode(), h)
388 raw_request(api, "POST", json.dumps({"tag": "v0.3.0-rc1", "target": "main", "title": "0.3.0 RC 1",
389 "body": "Draft notes.", "draft": True, "prerelease": True}).encode(), h)
390
391
392@step("wiki")
393def _():
394 r = admin.get(f"{R}/wiki/-/new")
395 base = field(r.text, "base") or ""
396 ok(admin.post(f"{R}/wiki/-/new", {"base": base, "name": "Home",
397 "content": "# Welcome\n\nThis is the **forge-demo** wiki.\n\n- [[Install]]\n- [[Architecture]]\n",
398 "message": "Create Home"}), "wiki home")
399 for name, content in [("Install", "# Install\n\n```sh\ncargo install --path .\n```\n"),
400 ("Architecture", "# Architecture\n\n| Crate | Role |\n| --- | --- |\n| core | store |\n| web | UI |\n")]:
401 r = admin.get(f"{R}/wiki/-/new")
402 admin.post(f"{R}/wiki/-/new", {"base": field(r.text, "base") or "", "name": name, "content": content,
403 "message": f"Add {name}"})
404 r = admin.get(f"{R}/wiki/Home/edit")
405 admin.post(f"{R}/wiki/Home/edit", {"base": field(r.text, "base") or "", "name": "Home",
406 "content": "# Welcome\n\nThis is the **forge-demo** wiki. Start with [[Install]].\n",
407 "message": "Tweak Home"})
408
409
410@step("snippets")
411def _():
412 r = ok(admin.post("/snippets/new", {"title": "Backup cron", "description": "Nightly backup with restic",
413 "visibility": "public", "name_0": "backup.sh",
414 "content_0": "#!/bin/sh\nrestic backup /var/lib/forge\n",
415 "name_1": "notes.md", "content_1": "# Notes\n\nRun at 03:00.\n"}), "snippet")
416 m = re.search(r"/snippets/([A-Za-z0-9_-]+)", r.url or "")
417 sid = m.group(1) if m and m.group(1) != "new" else None
418 if not sid:
419 m = re.findall(r'/snippets/([A-Za-z0-9_-]+)"', admin.get("/snippets").text)
420 sid = next((x for x in m if x != "new"), None)
421 seed["snippet_id"] = sid
422 if sid:
423 r = admin.get(f"/snippets/{sid}/edit")
424 admin.post(f"/snippets/{sid}/edit", {"title": "Backup cron", "description": "Nightly backup with restic (edited)",
425 "visibility": "public", "name_0": "backup.sh",
426 "content_0": "#!/bin/sh\nset -eu\nrestic backup /var/lib/forge\n"})
427 other.post("/snippets/new", {"title": "fish prompt", "description": "", "visibility": "public",
428 "name_0": "config.fish", "content_0": "set -g fish_greeting\n"})
429
430
431@step("organization, members and teams")
432def _():
433 ok(admin.post("/org/new", {"name": ORG, "description": "The people building forge."}), "org")
434 ok(admin.post(f"/org/{ORG}/members/add", {"username": OTHER, "role": "member"}), "member add")
435 ok(admin.post("/new", {"name": ORG_REPO, "description": "Deployment and infra scripts.", "visibility": "public",
436 "default_branch": "main", "owner": ORG}), "org repo")
437 ok(admin.post(f"/org/{ORG}/teams/new", {"name": TEAM, "description": "Core maintainers", "role": "write",
438 "all_repos": ""}), "team")
439 r = admin.get(f"/org/{ORG}/teams")
440 m = re.search(rf"/org/{ORG}/teams/([A-Za-z0-9_.-]+)\"", r.text)
441 if m:
442 seed["team"] = m.group(1)
443 admin.post(f"/org/{ORG}/teams/{seed['team']}/members/add", {"username": OTHER})
444 admin.post(f"/org/{ORG}/teams/new", {"name": "docs", "description": "Docs writers", "role": "read", "all_repos": "on"})
445
446
447@step("stars and watches")
448def _():
449 other.post(f"{R}/star", {})
450 admin.post(f"{R}/star", {})
451 admin.post(f"/{OTHER}/kaan-scratch/star", {})
452
453
454@step("collaborator")
455def _():
456 admin.post(f"{R}/settings/collaborators/add", {"username": OTHER, "role": "write"})
457
458
459@step("discussion")
460def _():
461 r = admin.get(f"{R}/discussions/new")
462 if r.status >= 400:
463 admin.post(f"{R}/settings/discussions", {"enabled": "1"})
464 r = admin.get(f"{R}/discussions/new")
465 cats = re.findall(r'<option value="([^"]+)"', r.text)
466 ok(admin.post(f"{R}/discussions/new", {"category": cats[0] if cats else "general",
467 "title": "Roadmap for 0.3", "body": "What should land next?"}), "discussion")
468 # Discussions share the issue/PR number counter, so find the real number.
469 nums = re.findall(rf'{re.escape(R)}/discussions/(\d+)', admin.get(f"{R}/discussions").text)
470 seed["discussion_number"] = int(nums[0]) if nums else 1
471 other.post(f"{R}/discussions/{seed['discussion_number']}/comments", {"body": "Mobile layout fixes please!"})
472
473
474@step("ci runner registration")
475def _():
476 r = ok(admin.post("/admin/runners/tokens", {}), "runner token")
477 m = re.search(r"--token\s+(\S+)", re.sub(r"<[^>]+>", " ", r.text))
478 if not m:
479 raise RuntimeError("token not found")
480 resp = raw_request(f"{BASE}/api/v1/ci/runners/register", "POST",
481 json.dumps({"token": m.group(1), "name": "audit-runner-1", "labels": ["linux", "x86_64"]}).encode(),
482 {"Content-Type": "application/json"})
483 ok(resp, "register")
484
485
486@step("ci run discovery")
487def _():
488 r = admin.get(f"{R}/ci")
489 if "/ci/runs/" not in r.text:
490 admin.post(f"{R}/ci", {"ref": "main", "branch": "main"})
491 r = admin.get(f"{R}/ci")
492 m = re.search(rf"{re.escape(R)}/ci/runs/(\d+)", r.text)
493 seed["run_number"] = int(m.group(1)) if m else None
494 if m:
495 page = admin.get(f"{R}/ci/runs/{m.group(1)}").text
496 j = re.search(rf"{re.escape(R)}/ci/jobs/([^/\"]+)", page)
497 seed["job_id"] = j.group(1) if j else None
498
499
500@step("user id for admin pages")
501def _():
502 r = admin.get("/admin/users")
503 ids = re.findall(r"/admin/users/([^/\"]+)/delete", r.text)
504 seed["user_id"] = ids[-1] if ids else None
505
506
507@step("webhook")
508def _():
509 r = admin.get(f"{R}/settings/hooks/new")
510 names = set(re.findall(r'name="([a-z_]+)"', r.text))
511 fields = {"url": "https://hooks.example.com/forge", "secret": "s3cret", "content_type": "json", "active": "on"}
512 fields = {k: v for k, v in fields.items() if k in names}
513 admin.post(f"{R}/settings/hooks/new", fields)
514 m = re.search(r"/settings/hooks/(\w[\w-]*)\"", admin.get(f"{R}/settings/hooks").text)
515 seed["hook_id"] = m.group(1) if m and m.group(1) != "new" else None
516
517
518@step("branch rule")
519def _():
520 admin.post(f"{R}/settings/branches", {"pattern": "release/*", "restrict_push": "on",
521 "required_approvals": "2", "required_checks": "ci/test"})
522
523
524@step("secret")
525def _():
526 admin.post(f"{R}/settings/secrets", {"name": "DEPLOY_KEY", "value": "hunter2"})
527
528
529@step("final csrf refresh")
530def _():
531 load_csrf(admin)
532 load_csrf(other)
533
534
535seed["admin_cookies"] = admin.cookies
536seed["admin_csrf"] = admin.csrf
537seed["other_cookies"] = other.cookies
538with open(os.path.join(OUT, "seed.json"), "w") as f:
539 json.dump(seed, f, indent=2)
540print(f"[seed] done, {len(seed['failed_steps'])} failed steps", flush=True)