diff --git a/.github/workflows/readme.yml b/.github/workflows/readme.yml index 9f34426..a7f94c9 100644 --- a/.github/workflows/readme.yml +++ b/.github/workflows/readme.yml @@ -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 , so the coloured + # terminal card ships as a committed SVG behind instead of + # the inline
 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
diff --git a/tools/gen_readme.py b/tools/gen_readme.py
index c94fcfb..5233cae 100644
--- a/tools/gen_readme.py
+++ b/tools/gen_readme.py
@@ -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  + SVG
+                                instead of inline 
 (needs --svg)
+
+Gitea keeps style="color:..." on spans, so it gets the inline 
. GitHub's
+sanitizer strips style, class and inline , 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'{man["header"]}']
-    for title, body in man["sections"]:
-        lines.append("")
-        lines.append(f'{title}')
-        lines.extend(body)
-    lines.append("")
-    lines.append(f'{man["footer"]}')
-    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 
 with coloured spans for Gitea (whose
+# sanitizer allows style="color:..."), and a committed SVG for GitHub (whose
+# sanitizer strips style, class and inline  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'{text}'
-
-    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 += ["", f"{prompt} man jonathan", man]
-    return "
" + "\n".join(lines) + "
" + 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("&", "&").replace("<", "<").replace(">", ">") + + +def render_terminal_html(lines, palette): + """Inline coloured
 - Gitea keeps style="color:..." on spans."""
+    out = []
+    for segs in lines:
+        out.append(
+            "".join(
+                f'{_esc(text)}'
+                if key
+                else _esc(text)
+                for text, key in segs
+            )
+        )
+    return "
" + "\n".join(out) + "
" + + +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 .""" + bg, fg = SVG_THEMES[theme] + width, height = terminal_geometry(lines, font_size, pad) + line_h = font_size * 1.5 + out = [ + f'', + f'', + f'', + ] + for i, segs in enumerate(lines): + if not segs: + continue + y = round(pad + font_size * 0.85 + i * line_h, 2) + spans = "".join( + f'{_esc(text)}' + for text, key in segs + ) + # xml:space must sit on the itself - on an ancestor Chrome + # collapses the leading and repeated spaces the card is aligned with + out.append(f'{spans}') + out += ["", ""] + return "\n".join(out) + "\n" + + +def terminal_image_block(width): + """ so the card follows the viewer's light/dark theme.""" + return ( + "\n" + ' \n' + f' \n' + "" + ) 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 + SVG instead of inline
",
+    )
     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  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: