feat: render the terminal card as an SVG for GitHub
readme / refresh (push) Skipped

GitHub's markdown sanitizer strips style, class and inline <svg>, so the
coloured card cannot be inline HTML there. Build the card once as
(text, colour) segments and render it two ways: the existing <pre> with
coloured spans for Gitea, and a committed SVG behind <picture> for GitHub
(dark + light variants follow prefers-color-scheme).

--svg DIR writes terminal-{dark,light}.svg; --terminal-image swaps the
block for the <picture>. The Gitea workflow is unchanged.
This commit is contained in:
trex Bot committed 2026-11-19 12:19:36 -06:00
1 parent 0bd015c9a8
commit ec787dc131
2 files changed
+180 -37

No files matched your search

+6 -2
View File
@@ -49,8 +49,12 @@ jobs:
KOMODO_API_SECRET: ${{ secrets.KOMODO_API_SECRET }}
VIKUNJA_TOKEN: ${{ secrets.VIKUNJA_TOKEN }}
run: |
python3 /tmp/src/tools/gen_readme.py --write
# GitHub's sanitizer strips style/class/inline <svg>, so the coloured
# terminal card ships as a committed SVG behind <picture> instead of
# the inline <pre> Gitea gets.
python3 /tmp/src/tools/gen_readme.py --write --svg /tmp/svg --terminal-image
cp /tmp/src/README.md README.md
cp /tmp/svg/terminal-dark.svg /tmp/svg/terminal-light.svg .
- name: Check links are public
run: python3 /tmp/src/tools/gen_readme.py --check-links
@@ -59,7 +63,7 @@ jobs:
run: |
git config user.name trex
git config user.email nanobot@jonb.io
git add README.md
git add README.md terminal-dark.svg terminal-light.svg
if git diff --cached --quiet; then
echo "no change"
exit 0
+174 -35
View File
@@ -21,6 +21,14 @@ Usage:
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
gen_readme.py --svg DIR also write terminal-{dark,light}.svg into DIR
gen_readme.py --terminal-image
render the terminal block as <picture> + SVG
instead of inline <pre> (needs --svg)
Gitea keeps style="color:..." on spans, so it gets the inline <pre>. GitHub's
sanitizer strips style, class and inline <svg>, so the GitHub workflow runs
with --svg + --terminal-image and commits the two SVGs next to README.md.
Environment:
GITEA_TOKEN optional. Set (even empty) wins; unset falls back to
@@ -124,7 +132,14 @@ def previous_int(text, pattern, default=0):
# against the tag-stripped text or the fallback silently yields 0
plain = re.sub(r"<[^>]+>", "", text)
m = re.search(pattern, plain)
return int(m.group(1)) if m else default
if m:
return int(m.group(1))
# image mode: the counts live in the committed SVG, not in the README
for svg in sorted(README.parent.glob("terminal-*.svg")):
m = re.search(pattern, svg.read_text())
if m:
return int(m.group(1))
return default
# ---------------------------------------------------------------- sources
@@ -169,46 +184,138 @@ def vikunja_done(cfg):
# ---------------------------------------------------------------- blocks
def man_block(cfg):
"""The about text as a man page: header, sections, footer."""
p = cfg["palette"]
man = cfg["man"]
lines = [f'<span style="color:{p["muted"]}">{man["header"]}</span>']
for title, body in man["sections"]:
lines.append("")
lines.append(f'<span style="color:{p["path"]}">{title}</span>')
lines.extend(body)
lines.append("")
lines.append(f'<span style="color:{p["muted"]}">{man["footer"]}</span>')
return "\n".join(lines)
# ---------------------------------------------------------------- terminal card
#
# The card is built once as lines of (text, colour-key-or-None) segments and
# then rendered two ways: inline <pre> with coloured spans for Gitea (whose
# sanitizer allows style="color:..."), and a committed SVG for GitHub (whose
# sanitizer strips style, class and inline <svg> entirely).
SVG_FONT = (
'ui-monospace, SFMono-Regular, "SF Mono", Menlo, Consolas, '
'"DejaVu Sans Mono", monospace'
)
SVG_THEMES = {
"dark": ("#0d1117", "#c9d1d9"),
"light": ("#f6f8fa", "#1f2328"),
}
def terminal_block(cfg, stacks, hosts, man):
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", "$")}'
def terminal_lines(cfg, stacks, hosts):
"""The card as lines of (text, colour-key-or-None) segments."""
tr = cfg["traceroute"]
man = cfg["man"]
prompt = [("jonathan@core", "prompt"), (":", None), ("~", "path"), ("$", "muted")]
lines = [
f"{prompt} whoami",
f'Jonathan Branan — {c("value", cfg["role"])} at {cfg["employer"]}',
"",
f"{prompt} uptime",
f'up {c("value", hosts)} hosts · {c("value", stacks)} stacks · {c("value", "1")} very patient wife',
"",
f"{prompt} traceroute {tr['target']}",
c("muted", f"traceroute to {tr['target']} ({tr['target_ip']}), 30 hops max, 60 byte packets"),
prompt + [(" whoami", None)],
[
("Jonathan Branan — ", None),
(cfg["role"], "value"),
(" at " + cfg["employer"], None),
],
[],
prompt + [(" uptime", None)],
[
("up ", None),
(str(hosts), "value"),
(" hosts · ", None),
(str(stacks), "value"),
(" stacks · ", None),
("1", "value"),
(" very patient wife", None),
],
[],
prompt + [(" traceroute " + tr["target"], None)],
[
(
f"traceroute to {tr['target']} ({tr['target_ip']}), "
"30 hops max, 60 byte packets",
"muted",
)
],
]
for i, hop in enumerate(tr["hops"], 1):
a, b, d = hop["ms"]
lines.append(
f'{c("muted", f"{i:2d}")} {c("path", f"{hop["name"]:<18}")}'
f'{c("muted", f"{a:>7.3f} ms {b:>7.3f} ms {d:>7.3f} ms")}'
[
(f"{i:2d}", "muted"),
(" ", None),
(f"{hop['name']:<18}", "path"),
(f"{a:>7.3f} ms {b:>7.3f} ms {d:>7.3f} ms", "muted"),
]
)
lines += [[], prompt + [(" man jonathan", None)], [(man["header"], "muted")]]
for title, body in man["sections"]:
lines += [[], [(title, "path")]]
lines += [[(line, None)] for line in body]
lines += [[], [(man["footer"], "muted")]]
return lines
def _esc(text):
return text.replace("&", "&amp;").replace("<", "&lt;").replace(">", "&gt;")
def render_terminal_html(lines, palette):
"""Inline coloured <pre> - Gitea keeps style="color:..." on spans."""
out = []
for segs in lines:
out.append(
"".join(
f'<span style="color:{palette[key]}">{_esc(text)}</span>'
if key
else _esc(text)
for text, key in segs
)
)
return "<pre>" + "\n".join(out) + "</pre>"
def terminal_geometry(lines, font_size=14, pad=20):
"""Pixel size of the card. 0.62em per column is the widest common
monospace advance, so the box never clips whatever font the viewer has."""
cols = max((sum(len(text) for text, _ in segs) for segs in lines), default=1)
width = int(round(pad * 2 + cols * font_size * 0.62))
height = int(round(pad * 2 + len(lines) * font_size * 1.5))
return width, height
def render_terminal_svg(lines, palette, theme="dark", font_size=14, pad=20):
"""The same card as a standalone SVG - GitHub strips inline <svg>."""
bg, fg = SVG_THEMES[theme]
width, height = terminal_geometry(lines, font_size, pad)
line_h = font_size * 1.5
out = [
f'<svg xmlns="http://www.w3.org/2000/svg" width="{width}" height="{height}" '
f'viewBox="0 0 {width} {height}" role="img" '
f'aria-label="jonathan@core terminal card">',
f'<rect width="{width}" height="{height}" rx="10" fill="{bg}"/>',
f'<g font-family=\'{SVG_FONT}\' font-size="{font_size}">',
]
for i, segs in enumerate(lines):
if not segs:
continue
y = round(pad + font_size * 0.85 + i * line_h, 2)
spans = "".join(
f'<tspan fill="{palette[key] if key else fg}">{_esc(text)}</tspan>'
for text, key in segs
)
# xml:space must sit on the <text> itself - on an ancestor <g> Chrome
# collapses the leading and repeated spaces the card is aligned with
out.append(f'<text x="{pad}" y="{y}" xml:space="preserve">{spans}</text>')
out += ["</g>", "</svg>"]
return "\n".join(out) + "\n"
def terminal_image_block(width):
"""<picture> so the card follows the viewer's light/dark theme."""
return (
"<picture>\n"
' <source media="(prefers-color-scheme: dark)" srcset="terminal-dark.svg">\n'
f' <img src="terminal-light.svg" width="{width}" '
'alt="Terminal card: whoami, uptime, traceroute jonb.io, man jonathan">\n'
"</picture>"
)
lines += ["", f"{prompt} man jonathan", man]
return "<pre>" + "\n".join(lines) + "</pre>"
def status_block(cfg, up, total):
@@ -280,7 +387,7 @@ def completed_block(cfg, done):
# ---------------------------------------------------------------- build
def build():
def build(svg_dir=None, terminal_image=False):
cfg = json.loads(CONFIG.read_text())
text = README.read_text()
tok = gitea_token()
@@ -306,7 +413,24 @@ def build():
if hosts is None:
hosts = previous_int(text, r"up (\d+) hosts")
apply("terminal", lambda: terminal_block(cfg, stacks, hosts, man_block(cfg)))
try:
lines = terminal_lines(cfg, stacks, hosts)
except Exception as exc:
errors.append(f"terminal: {type(exc).__name__}: {exc}")
else:
if svg_dir:
svg_dir.mkdir(parents=True, exist_ok=True)
for theme in SVG_THEMES:
(svg_dir / f"terminal-{theme}.svg").write_text(
render_terminal_svg(lines, cfg["palette"], theme)
)
if terminal_image:
width, _ = terminal_geometry(lines)
text = replace_block(text, "terminal", terminal_image_block(width))
else:
text = replace_block(
text, "terminal", render_terminal_html(lines, cfg["palette"])
)
try:
up, total = kuma_counts(cfg)
@@ -372,12 +496,27 @@ def main():
ap.add_argument("--write", action="store_true")
ap.add_argument("--check", action="store_true")
ap.add_argument("--check-links", action="store_true")
ap.add_argument(
"--svg",
metavar="DIR",
help="also write terminal-{dark,light}.svg into DIR (GitHub needs an image)",
)
ap.add_argument(
"--terminal-image",
action="store_true",
help="render the terminal block as <picture> + SVG instead of inline <pre>",
)
args = ap.parse_args()
if args.check_links:
return check_links()
if args.terminal_image and not args.svg:
ap.error("--terminal-image needs --svg DIR (the <img> points at those files)")
new, errors = build()
new, errors = build(
svg_dir=Path(args.svg) if args.svg else None,
terminal_image=args.terminal_image,
)
old = README.read_text()
if args.check: