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:
trex Bot committed 2026-11-19 11:00:58 -06:00
1 parent 61a2dac6e6
commit 772ec6233d
4 files changed
+510 -12

No files matched your search

+63
View File
@@ -0,0 +1,63 @@
name: readme
# Regenerates the self-updating blocks in README.md.
#
# The generator lives in tools/gen_readme.py and is stdlib-only, so there is
# nothing to install. Auth is the built-in per-job GITEA_TOKEN (write on this
# repo's contents, read-only on public repos) - no personal access token.
#
# Optional repo secrets, both degrade gracefully when absent:
# KOMODO_API_KEY / KOMODO_API_SECRET live stack + host counts
# VIKUNJA_TOKEN recently completed homelab tasks
#
# Cron is UTC: 10:00 UTC = 04:00 CST.
on:
schedule:
- cron: "0 10 * * *"
workflow_dispatch:
push:
branches: [main]
paths:
- "tools/**"
- ".gitea/workflows/readme.yml"
pull_request:
paths:
- "tools/**"
- "README.md"
- ".gitea/workflows/readme.yml"
jobs:
refresh:
# a bot commit must not re-trigger the job
if: github.event_name != 'push' || github.actor != 'trex'
runs-on: ubuntu-latest
permissions:
contents: write
steps:
- name: Checkout
uses: actions/checkout@v4
- name: Regenerate
env:
GITEA_TOKEN: ${{ secrets.GITEA_TOKEN }}
KOMODO_API_KEY: ${{ secrets.KOMODO_API_KEY }}
KOMODO_API_SECRET: ${{ secrets.KOMODO_API_SECRET }}
VIKUNJA_TOKEN: ${{ secrets.VIKUNJA_TOKEN }}
run: python3 tools/gen_readme.py --write
- name: Check links are public
run: python3 tools/gen_readme.py --check-links
- name: Commit
if: github.event_name != 'pull_request'
run: |
git config user.name trex
git config user.email nanobot@jonb.io
git add README.md
if git diff --cached --quiet; then
echo "no change"
exit 0
fi
git commit -m "chore: refresh profile README"
git push
+44 -12
View File
@@ -1,20 +1,52 @@
<!-- terminal:start -->
```text
jonathan@core:~$ whoami
Jonathan Branan — technical support engineer at Teramind
<pre><span style="color:#22c55e">jonathan@core</span>:<span style="color:#38bdf8">~</span><span style="color:#7c8798">$</span> whoami
Jonathan Branan — <span style="color:#f59e0b">technical support engineer</span> at Teramind
jonathan@core:~$ uptime
up 7 hosts · 76 stacks · 1 very patient wife
<span style="color:#22c55e">jonathan@core</span>:<span style="color:#38bdf8">~</span><span style="color:#7c8798">$</span> uptime
up <span style="color:#f59e0b">7</span> hosts · <span style="color:#f59e0b">76</span> stacks · <span style="color:#f59e0b">1</span> very patient wife
jonathan@core:~$ cat how-it-gets-here.txt
internet → Cloudflare → Pangolin (VPS) → newt tunnel → core → container
<span style="color:#22c55e">jonathan@core</span>:<span style="color:#38bdf8">~</span><span style="color:#7c8798">$</span> cat how-it-gets-here.txt
internet → <span style="color:#38bdf8">Cloudflare</span> → <span style="color:#38bdf8">Pangolin</span> (VPS) → <span style="color:#38bdf8">newt</span> tunnel → <span style="color:#38bdf8">core</span> → container
jonathan@core:~$ _
```
<span style="color:#22c55e">jonathan@core</span>:<span style="color:#38bdf8">~</span><span style="color:#7c8798">$</span> <span style="color:#22c55e">_</span></pre>
<!-- terminal:end -->
<!-- status:start -->
<span style="color:#22c55e">●</span> 76/76 services up · <span style="color:#7c8798">refreshed daily</span>
<!-- status:end -->
[LinkedIn](https://www.linkedin.com/in/jonathanbranan/) · [GitHub](https://github.com/jonbranan) · [Résumé](https://s3.jonb.io/cdn/author/Resume.pdf) · [git.jonb.io](https://git.jonb.io/jblu) · [up.jonb.io](https://up.jonb.io)
<!-- footer:start -->
<sub>76/76 monitors up · refreshed nightly</sub>
<!-- footer:end -->
## What I'm working on
<!-- working-on:start -->
- [**qbit-maid**](https://git.jonb.io/jblu/qbit-maid) — Qbittorrent cleaner that deletes torrents based on age, categories, domains and tags. · `v3.0.0`
- [**jonbio**](https://git.jonb.io/jblu/jonbio) — TypeScript · updated 18m ago
- [**crane**](https://git.jonb.io/jblu/crane) — App to make sure specified containers are running in portainer
<!-- working-on:end -->
## Recent activity
<!-- activity:start -->
- [ci: deploy via Komodo stack webhook, tag images with commit sha](https://git.jonb.io/jblu/jonbio/commit/d2b77e488f85d8e468625ed1a44bfc3b60a62f1f) — jonbio · 19h ago
- [fix: resolve the seven bugs pinned by the test audit (#67)](https://git.jonb.io/jblu/qbit-maid/commit/cc2d75c7778be19597403b485c1db0236b65797e) — qbit-maid · 15d ago
- [test: audit suite for meaningfulness, reach 100% coverage (#66)](https://git.jonb.io/jblu/qbit-maid/commit/0c02cd40b057f497917f3cce19ada4b7c00f5886) — qbit-maid · 15d ago
<!-- activity:end -->
## Recent pull requests
<!-- prs:start -->
- [ci: deploy via Komodo stack webhook, tag images with commit sha](https://git.jonb.io/jblu/jonbio/pulls/3) — jonbio · 18m ago
- [fix: resolve the seven bugs pinned by the test audit](https://git.jonb.io/jblu/qbit-maid/pulls/67) — qbit-maid · 15d ago
- [test: audit suite for meaningfulness, reach 100% coverage](https://git.jonb.io/jblu/qbit-maid/pulls/66) — qbit-maid · 15d ago
<!-- prs:end -->
## Recently completed
<!-- completed:start -->
- Approve email backfill plan for lldap users mike and Jen · 1d ago
- add portainer, filebrowser and ipam into homepage · 14d ago
- Set up mail server for jonb.io · 1mo ago
<!-- completed:end -->
<sub>regenerated daily by [tools/gen_readme.py](https://git.jonb.io/jblu/.profile)</sub>
+375
View File
@@ -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())
+28
View File
@@ -0,0 +1,28 @@
{
"featured_repos": ["qbit-maid", "jonbio", "crane"],
"limits": {
"activity": 3,
"prs": 3,
"completed": 3
},
"palette": {
"prompt": "#22c55e",
"path": "#38bdf8",
"value": "#f59e0b",
"muted": "#7c8798",
"accent": "#a78bfa",
"bad": "#ef4444"
},
"kuma": {
"base": "https://up.jonb.io/api",
"page": "homelab"
},
"komodo": {
"base": "http://10.5.0.3:9120",
"extra_hosts": 1
},
"vikunja": {
"base": "http://10.5.0.3:3456",
"project": 2
}
}