feat: self-updating README with the generator in the repo
- tools/gen_readme.py: stdlib-only generator, per-block failure isolation - tools/readme.json: featured repos, limits, palette - .gitea/workflows/readme.yml: daily schedule + dispatch + push on tools/** - README: coloured terminal card, status line, working-on, activity, PRs, recently completed (Vikunja)
This commit is contained in:
1 parent
61a2dac6e6
commit
772ec6233d
4 files changed
+510
-12
No files matched your search
@@ -0,0 +1,375 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Regenerate the self-updating blocks of jblu/.profile.
|
||||
|
||||
Runs in Gitea Actions (.gitea/workflows/readme.yml) and locally. Stdlib only.
|
||||
|
||||
Blocks are delimited by HTML comment markers in README.md:
|
||||
|
||||
<!-- terminal:start --> ... <!-- terminal:end --> coloured terminal card
|
||||
<!-- status:start --> ... <!-- status:end --> "N/M services up" line
|
||||
<!-- working-on:start --> ... <!-- working-on:end --> featured repos + release
|
||||
<!-- activity:start --> ... <!-- activity:end --> newest commits
|
||||
<!-- prs:start --> ... <!-- prs:end --> newest pull requests
|
||||
<!-- completed:start --> ... <!-- completed:end --> newest done Vikunja tasks
|
||||
|
||||
A missing marker is a no-op, so a section can be deleted from the README
|
||||
without breaking the job. A failing data source keeps the previous block text
|
||||
and makes the run exit 1, so a dead API never blanks a section.
|
||||
|
||||
Usage:
|
||||
gen_readme.py dry run: print the regenerated README
|
||||
gen_readme.py --write write README.md in place
|
||||
gen_readme.py --check exit 1 if README.md is stale
|
||||
gen_readme.py --check-links exit 1 if any link is not publicly reachable
|
||||
|
||||
Environment:
|
||||
GITEA_TOKEN required in Actions (provided per job); locally it
|
||||
falls back to ~/.config/gitea/qbit-maid-push.token
|
||||
KOMODO_API_KEY/SECRET optional; without them the stack/host counts are kept
|
||||
VIKUNJA_TOKEN optional; without it the completed block is kept
|
||||
"""
|
||||
|
||||
import argparse
|
||||
import json
|
||||
import os
|
||||
import re
|
||||
import sys
|
||||
import urllib.error
|
||||
import urllib.request
|
||||
from datetime import datetime, timezone
|
||||
from pathlib import Path
|
||||
|
||||
HERE = Path(__file__).resolve().parent
|
||||
ROOT = HERE.parent
|
||||
README = ROOT / "README.md"
|
||||
CONFIG = HERE / "readme.json"
|
||||
LOCAL_TOKEN = Path.home() / ".config/gitea/qbit-maid-push.token"
|
||||
|
||||
# Public URLs that legitimately refuse non-browser clients.
|
||||
LINK_ALLOWLIST = {
|
||||
"https://www.linkedin.com/in/jonathanbranan/",
|
||||
}
|
||||
|
||||
|
||||
# ---------------------------------------------------------------- http
|
||||
|
||||
|
||||
def http_json(url, headers=None, data=None, timeout=25):
|
||||
body = json.dumps(data).encode() if data is not None else None
|
||||
req = urllib.request.Request(url, data=body, headers=headers or {})
|
||||
if body is not None:
|
||||
req.add_header("Content-Type", "application/json")
|
||||
with urllib.request.urlopen(req, timeout=timeout) as r:
|
||||
return json.load(r)
|
||||
|
||||
|
||||
def gitea_token():
|
||||
tok = os.environ.get("GITEA_TOKEN", "").strip()
|
||||
if tok:
|
||||
return tok
|
||||
if LOCAL_TOKEN.exists():
|
||||
return LOCAL_TOKEN.read_text().strip()
|
||||
raise SystemExit("no GITEA_TOKEN and no local token file")
|
||||
|
||||
|
||||
def gitea(path, tok):
|
||||
return http_json(
|
||||
"https://git.jonb.io/api/v1" + path,
|
||||
headers={"Authorization": "token " + tok},
|
||||
)
|
||||
|
||||
|
||||
# ---------------------------------------------------------------- helpers
|
||||
|
||||
|
||||
def one_line(text, limit):
|
||||
line = re.sub(r"\s+", " ", (text or "").strip().splitlines()[0] if (text or "").strip() else "")
|
||||
return line if len(line) <= limit else line[: limit - 1].rstrip() + "…"
|
||||
|
||||
|
||||
def ago(iso):
|
||||
if not iso:
|
||||
return ""
|
||||
try:
|
||||
dt = datetime.fromisoformat(iso.replace("Z", "+00:00"))
|
||||
except ValueError:
|
||||
return ""
|
||||
secs = int((datetime.now(timezone.utc) - dt).total_seconds())
|
||||
if secs < 3600:
|
||||
return f"{max(secs // 60, 1)}m ago"
|
||||
if secs < 86400:
|
||||
return f"{secs // 3600}h ago"
|
||||
if secs < 86400 * 30:
|
||||
return f"{secs // 86400}d ago"
|
||||
if secs < 86400 * 365:
|
||||
return f"{secs // (86400 * 30)}mo ago"
|
||||
return f"{secs // (86400 * 365)}y ago"
|
||||
|
||||
|
||||
def replace_block(text, name, body):
|
||||
"""Replace a marked block. A missing marker is a no-op, not an error."""
|
||||
pat = re.compile(rf"(<!-- {name}:start -->)(.*?)(<!-- {name}:end -->)", re.S)
|
||||
if not pat.search(text):
|
||||
return text
|
||||
return pat.sub(lambda m: f"{m.group(1)}\n{body}\n{m.group(3)}", text)
|
||||
|
||||
|
||||
def previous_int(text, pattern, default=0):
|
||||
m = re.search(pattern, text)
|
||||
return int(m.group(1)) if m else default
|
||||
|
||||
|
||||
# ---------------------------------------------------------------- sources
|
||||
|
||||
|
||||
def kuma_counts(cfg):
|
||||
base = cfg["kuma"]["base"]
|
||||
page = cfg["kuma"]["page"]
|
||||
hb = http_json(f"{base}/status-page/heartbeat/{page}").get("heartbeatList", {})
|
||||
up = sum(1 for v in hb.values() if v and v[-1].get("status") == 1)
|
||||
return up, len(hb)
|
||||
|
||||
|
||||
def komodo_counts(cfg):
|
||||
"""(stacks, hosts) from Komodo, or (None, None) when no key is configured."""
|
||||
key = os.environ.get("KOMODO_API_KEY", "").strip()
|
||||
secret = os.environ.get("KOMODO_API_SECRET", "").strip()
|
||||
if not key or not secret:
|
||||
return None, None
|
||||
base = cfg["komodo"]["base"]
|
||||
headers = {"X-Api-Key": key, "X-Api-Secret": secret}
|
||||
stacks = http_json(f"{base}/read/GetStacksSummary", headers=headers, data={})
|
||||
servers = http_json(f"{base}/read/GetServersSummary", headers=headers, data={})
|
||||
return stacks["total"], servers["total"] + cfg["komodo"].get("extra_hosts", 0)
|
||||
|
||||
|
||||
def vikunja_done(cfg):
|
||||
tok = os.environ.get("VIKUNJA_TOKEN", "").strip()
|
||||
if not tok:
|
||||
return None
|
||||
base = cfg["vikunja"]["base"]
|
||||
project = cfg["vikunja"]["project"]
|
||||
tasks = http_json(
|
||||
f"{base}/api/v1/projects/{project}/tasks?per_page=100",
|
||||
headers={"Authorization": "Bearer " + tok},
|
||||
)
|
||||
done = [t for t in tasks if t.get("done") and t.get("done_at")]
|
||||
done.sort(key=lambda t: t["done_at"], reverse=True)
|
||||
return done
|
||||
|
||||
|
||||
# ---------------------------------------------------------------- blocks
|
||||
|
||||
|
||||
def terminal_block(cfg, stacks, hosts):
|
||||
p = cfg["palette"]
|
||||
|
||||
def c(key, text):
|
||||
return f'<span style="color:{p[key]}">{text}</span>'
|
||||
|
||||
prompt = f'{c("prompt", "jonathan@core")}:{c("path", "~")}{c("muted", "$")}'
|
||||
lines = [
|
||||
f"{prompt} whoami",
|
||||
f'Jonathan Branan — {c("value", "technical support engineer")} at Teramind',
|
||||
"",
|
||||
f"{prompt} uptime",
|
||||
f'up {c("value", hosts)} hosts · {c("value", stacks)} stacks · {c("value", "1")} very patient wife',
|
||||
"",
|
||||
f"{prompt} cat how-it-gets-here.txt",
|
||||
f'internet → {c("path", "Cloudflare")} → {c("path", "Pangolin")} (VPS) → '
|
||||
f'{c("path", "newt")} tunnel → {c("path", "core")} → container',
|
||||
"",
|
||||
f'{prompt} {c("prompt", "_")}',
|
||||
]
|
||||
return "<pre>" + "\n".join(lines) + "</pre>"
|
||||
|
||||
|
||||
def status_block(cfg, up, total):
|
||||
p = cfg["palette"]
|
||||
ok = up == total
|
||||
dot = "●" if ok else "◐"
|
||||
colour = p["prompt"] if ok else p["value"]
|
||||
return (
|
||||
f'<span style="color:{colour}">{dot}</span> {up}/{total} services up · '
|
||||
f'<span style="color:{p["muted"]}">refreshed daily</span>'
|
||||
)
|
||||
|
||||
|
||||
def working_on_block(cfg, tok):
|
||||
lines = []
|
||||
for name in cfg["featured_repos"]:
|
||||
repo = gitea(f"/repos/jblu/{name}", tok)
|
||||
desc = one_line(repo.get("description") or "", 88)
|
||||
if not desc: # no description set — say something true instead of a bare dash
|
||||
desc = f'{repo.get("language") or "code"} · updated {ago(repo.get("updated_at"))}'
|
||||
tag = ""
|
||||
try:
|
||||
rel = gitea(f"/repos/jblu/{name}/releases?limit=1", tok)
|
||||
if rel:
|
||||
tag = f' · `{rel[0]["tag_name"]}`'
|
||||
except Exception:
|
||||
pass
|
||||
lines.append(f'- [**{name}**]({repo["html_url"]}) — {desc}{tag}')
|
||||
return "\n".join(lines)
|
||||
|
||||
|
||||
def activity_block(cfg, tok):
|
||||
rows = []
|
||||
for name in cfg["featured_repos"]:
|
||||
for c in gitea(f"/repos/jblu/{name}/commits?limit=5&stat=false", tok):
|
||||
msg = c["commit"]["message"].strip()
|
||||
if msg.startswith(("Merge pull request", "Merge PR")):
|
||||
continue # the PR block already lists it
|
||||
rows.append((c["commit"]["author"]["date"], name, c))
|
||||
rows.sort(key=lambda r: r[0], reverse=True)
|
||||
lines = [
|
||||
f'- [{one_line(c["commit"]["message"], 64)}]({c["html_url"]}) — {name} · {ago(date)}'
|
||||
for date, name, c in rows[: cfg["limits"]["activity"]]
|
||||
]
|
||||
return "\n".join(lines)
|
||||
|
||||
|
||||
def prs_block(cfg, tok):
|
||||
rows = []
|
||||
for name in cfg["featured_repos"]:
|
||||
for p in gitea(f"/repos/jblu/{name}/pulls?state=all&limit=5&sort=recentupdate", tok):
|
||||
rows.append((p["updated_at"], name, p))
|
||||
rows.sort(key=lambda r: r[0], reverse=True)
|
||||
lines = [
|
||||
f'- [{one_line(p["title"], 64)}]({p["html_url"]}) — {name} · {ago(date)}'
|
||||
for date, name, p in rows[: cfg["limits"]["prs"]]
|
||||
]
|
||||
return "\n".join(lines)
|
||||
|
||||
|
||||
def completed_block(cfg, done):
|
||||
lines = [
|
||||
f'- {one_line(t["title"], 80)} · {ago(t["done_at"])}'
|
||||
for t in done[: cfg["limits"]["completed"]]
|
||||
]
|
||||
return "\n".join(lines)
|
||||
|
||||
|
||||
# ---------------------------------------------------------------- build
|
||||
|
||||
|
||||
def build():
|
||||
cfg = json.loads(CONFIG.read_text())
|
||||
text = README.read_text()
|
||||
tok = gitea_token()
|
||||
errors = []
|
||||
|
||||
def apply(name, fn):
|
||||
nonlocal text
|
||||
try:
|
||||
body = fn()
|
||||
except Exception as exc: # keep the previous block, report, fail the run
|
||||
errors.append(f"{name}: {type(exc).__name__}: {exc}")
|
||||
return
|
||||
if body:
|
||||
text = replace_block(text, name, body)
|
||||
|
||||
stacks, hosts = None, None
|
||||
try:
|
||||
stacks, hosts = komodo_counts(cfg)
|
||||
except Exception as exc:
|
||||
errors.append(f"komodo: {type(exc).__name__}: {exc}")
|
||||
if stacks is None:
|
||||
stacks = previous_int(text, r"(\d+) stacks")
|
||||
if hosts is None:
|
||||
hosts = previous_int(text, r"up (\d+) hosts")
|
||||
|
||||
apply("terminal", lambda: terminal_block(cfg, stacks, hosts))
|
||||
|
||||
try:
|
||||
up, total = kuma_counts(cfg)
|
||||
except Exception as exc:
|
||||
errors.append(f"kuma: {type(exc).__name__}: {exc}")
|
||||
else:
|
||||
apply("status", lambda: status_block(cfg, up, total))
|
||||
|
||||
apply("working-on", lambda: working_on_block(cfg, tok))
|
||||
apply("activity", lambda: activity_block(cfg, tok))
|
||||
apply("prs", lambda: prs_block(cfg, tok))
|
||||
|
||||
try:
|
||||
done = vikunja_done(cfg)
|
||||
except Exception as exc:
|
||||
errors.append(f"vikunja: {type(exc).__name__}: {exc}")
|
||||
else:
|
||||
if done is not None:
|
||||
apply("completed", lambda: completed_block(cfg, done))
|
||||
|
||||
for err in errors:
|
||||
print(f"warn: {err}", file=sys.stderr)
|
||||
return text, errors
|
||||
|
||||
|
||||
# ---------------------------------------------------------------- link check
|
||||
|
||||
|
||||
def check_links():
|
||||
text = README.read_text()
|
||||
urls = sorted(set(re.findall(r"https?://[^\s\)\"'<>]+", text)))
|
||||
bad = []
|
||||
for url in urls:
|
||||
if url in LINK_ALLOWLIST:
|
||||
print(f"skip {url} (bot-blocked by design)")
|
||||
continue
|
||||
try:
|
||||
req = urllib.request.Request(
|
||||
url, headers={"User-Agent": "Mozilla/5.0 (profile-readme link check)"}
|
||||
)
|
||||
with urllib.request.urlopen(req, timeout=20) as r:
|
||||
code = r.status
|
||||
except urllib.error.HTTPError as exc:
|
||||
code = exc.code
|
||||
except Exception as exc:
|
||||
code = type(exc).__name__
|
||||
ok = code == 200
|
||||
print(f"{'ok ' if ok else 'FAIL '} {code} {url}")
|
||||
if not ok:
|
||||
bad.append((url, code))
|
||||
if bad:
|
||||
print(f"\n{len(bad)} unreachable link(s) — dead for anyone not logged in.")
|
||||
return 1
|
||||
print(f"\nall {len(urls)} links public")
|
||||
return 0
|
||||
|
||||
|
||||
# ---------------------------------------------------------------- main
|
||||
|
||||
|
||||
def main():
|
||||
ap = argparse.ArgumentParser()
|
||||
ap.add_argument("--write", action="store_true")
|
||||
ap.add_argument("--check", action="store_true")
|
||||
ap.add_argument("--check-links", action="store_true")
|
||||
args = ap.parse_args()
|
||||
|
||||
if args.check_links:
|
||||
return check_links()
|
||||
|
||||
new, errors = build()
|
||||
old = README.read_text()
|
||||
|
||||
if args.check:
|
||||
if new != old:
|
||||
print("README.md is stale")
|
||||
return 1
|
||||
print("README.md is current")
|
||||
return 1 if errors else 0
|
||||
if args.write:
|
||||
if new != old:
|
||||
README.write_text(new)
|
||||
print(f"wrote {README}")
|
||||
else:
|
||||
print("no change")
|
||||
return 1 if errors else 0
|
||||
|
||||
sys.stdout.write(new)
|
||||
return 1 if errors else 0
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
raise SystemExit(main())
|
||||
Reference in new issue
Block a user