aboutsummaryrefslogtreecommitdiffstats
path: root/scripts/gen_bots.py
blob: 392251f4267407a237443248fe1fa5fdb8d373cb (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
#!/usr/bin/env python3
"""Generate bot documentation HTML pages from docs/*.md."""

import os
import re
import sys

BOTS = [
    ("alfred",   "Server management, bot control, file hosting, soju bouncer"),
    ("jeeves",   "DJ queue, duck hunting, recipes, news, quotes, art"),
    ("osterman", "Channel moderation, auto-modes, idle tracking"),
    ("daffy",    "Duck hunting game"),
    ("contessa", "Recipe suggestions"),
    ("shireen",  "News headlines and weather"),
    ("daft",     "YouTube playlist manager"),
    ("herald",   "Owner-follow bot and keyword responder"),
    ("salvador", "Image-to-mIRC-art renderer"),
]

STYLE = """\
@font-face { font-family: "Kawkab Mono"; src: url(/fonts/KawkabMono-Regular.woff2); font-weight: normal; }
@font-face { font-family: "Kawkab Mono"; src: url(/fonts/KawkabMono-Bold.woff2); font-weight: bold; }
* { unicode-bidi: plaintext; box-sizing: border-box; }
html { color: black; background-color: white; }
body { font-family: "Kawkab Mono"; font-size: 16px; line-height: 1.4; margin: 0; padding: 4rem 0; min-height: 100%; overflow-wrap: break-word; }
main, header, footer { max-width: 800px; margin-inline: auto; padding: 0 2rem; }
h1, header, footer { text-align: center; }
main { text-align: left; }
p, h2, h3, h4 { margin: 1em 0 0 0; }
table { margin: auto; border-collapse: collapse; }
th, td { border: 1px solid; padding: 0.3em 0.8em; }
pre { background: rgba(128,128,128,0.08); padding: 1em; overflow-x: auto; margin: 1em 0; }
code { font-size: 85%; }
header { margin-bottom: 1em; }
footer { margin-top: 3em; }
a { color: inherit; }
@media (max-width: 600px) { body { font-size: 0.9em; } h1 { font-size: 1.8em; } }
@media (max-width: 400px) { body { font-size: 0.8em; } h1 { font-size: 1.6em; } }
@media (prefers-color-scheme: dark) { html { filter: invert(1); } img { filter: invert(1); } }"""

FOOTER = ""


def page(title, header_html, content_html):
    return f"""<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width,initial-scale=1">
<link rel="icon" type="image/svg+xml" href="data:image/svg+xml;base64,PHN2ZyB4bWxucz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciIHZpZXdCb3g9IjAgMCA1IDUiPjxyZWN0IHg9IjEiIHk9IjAiIHdpZHRoPSIxIiBoZWlnaHQ9IjEiLz48cmVjdCB4PSIyIiB5PSIxIiB3aWR0aD0iMSIgaGVpZ2h0PSIxIi8+PHJlY3QgeD0iMCIgeT0iMiIgd2lkdGg9IjEiIGhlaWdodD0iMSIvPjxyZWN0IHg9IjEiIHk9IjIiIHdpZHRoPSIxIiBoZWlnaHQ9IjEiLz48cmVjdCB4PSIyIiB5PSIyIiB3aWR0aD0iMSIgaGVpZ2h0PSIxIi8+PC9zdmc+">
<title>{title}</title>
<style>
{STYLE}
</style>
</head>
<body>
<header>
{header_html}
</header>
<main>
{content_html}
</main>
{FOOTER}
</body>
</html>
"""


def md_to_html(text):
    """Minimal markdown → HTML: headers, code blocks, inline code, bold, links, paragraphs."""
    lines = text.splitlines()
    out = []
    i = 0
    while i < len(lines):
        line = lines[i]

        # fenced code block
        if line.strip().startswith("```"):
            lang = line.strip()[3:].strip()
            i += 1
            code_lines = []
            while i < len(lines) and not lines[i].strip().startswith("```"):
                code_lines.append(_esc(lines[i]))
                i += 1
            out.append(f"<pre><code>{chr(10).join(code_lines)}</code></pre>")
            i += 1
            continue

        # ATX headers
        m = re.match(r'^(#{1,4})\s+(.*)', line)
        if m:
            level = len(m.group(1))
            out.append(f"<h{level}>{_inline(m.group(2))}</h{level}>")
            i += 1
            continue

        # table row
        if '|' in line and line.strip().startswith('|'):
            table_lines = []
            while i < len(lines) and '|' in lines[i] and lines[i].strip().startswith('|'):
                table_lines.append(lines[i])
                i += 1
            out.append(_table(table_lines))
            continue

        # blank line
        if not line.strip():
            i += 1
            continue

        # paragraph
        para = [line]
        i += 1
        while i < len(lines) and lines[i].strip() and not lines[i].startswith('#') and not lines[i].strip().startswith('```') and not ('|' in lines[i] and lines[i].strip().startswith('|')):
            para.append(lines[i])
            i += 1
        out.append(f"<p>{_inline(' '.join(para))}</p>")

    return "\n".join(out)


def _table(rows):
    html = ["<table>"]
    for j, row in enumerate(rows):
        cells = [c.strip() for c in row.strip().strip('|').split('|')]
        if all(re.match(r'^[-: ]+$', c) for c in cells):
            continue
        tag = "th" if j == 0 else "td"
        html.append("<tr>" + "".join(f"<{tag}>{_inline(c)}</{tag}>" for c in cells) + "</tr>")
    html.append("</table>")
    return "\n".join(html)


def _inline(text):
    text = _esc(text)
    # bold
    text = re.sub(r'\*\*(.+?)\*\*', r'<strong>\1</strong>', text)
    # inline code
    text = re.sub(r'`([^`]+)`', r'<code>\1</code>', text)
    # links
    text = re.sub(r'\[([^\]]+)\]\(([^)]+)\)', r'<a href="\2">\1</a>', text)
    return text


def _esc(text):
    return text.replace("&", "&amp;").replace("<", "&lt;").replace(">", "&gt;")


def build(src_dir, out_dir):
    os.makedirs(out_dir, exist_ok=True)

    # Copy fonts
    fonts_src = os.path.join(src_dir, "fonts")
    fonts_dst = os.path.join(out_dir, "fonts")
    if os.path.isdir(fonts_src):
        os.makedirs(fonts_dst, exist_ok=True)
        for f in os.listdir(fonts_src):
            src = os.path.join(fonts_src, f)
            dst = os.path.join(fonts_dst, f)
            with open(src, "rb") as fh:
                data = fh.read()
            with open(dst, "wb") as fh:
                fh.write(data)

    # Per-bot pages
    for name, desc in BOTS:
        doc_path = os.path.join(src_dir, "docs", f"{name}.md")
        if not os.path.exists(doc_path):
            continue
        with open(doc_path) as f:
            md = f.read()
        content = md_to_html(md)
        html = page(
            f"{name} — irc.gumx.cc",
            f'<h1><a href="https://irc.gumx.cc">irc.gumx.cc</a> / bots / {name}</h1>',
            content,
        )
        bot_dir = os.path.join(out_dir, name)
        os.makedirs(bot_dir, exist_ok=True)
        with open(os.path.join(bot_dir, "index.html"), "w") as f:
            f.write(html)

    # Index page
    rows = "\n".join(
        f'<tr><td><a href="{name}/">{name}</a></td><td>{desc}</td></tr>'
        for name, desc in BOTS
        if os.path.exists(os.path.join(src_dir, "docs", f"{name}.md"))
    )
    index_content = f"""<h2>bots</h2>
<table>
<tr><th>bot</th><th>purpose</th></tr>
{rows}
</table>
<p>All bots run <a href="https://sopel.chat/">Sopel</a>. Source: <a href="https://git.gumx.cc/irc-bots">git.gumx.cc/irc-bots</a>.</p>"""

    index_html = page(
        "irc bots — irc.gumx.cc",
        '<h1><a href="https://irc.gumx.cc">irc.gumx.cc</a> / bots</h1>',
        index_content,
    )
    with open(os.path.join(out_dir, "index.html"), "w") as f:
        f.write(index_html)

    print(f"Generated {len(BOTS)} bot pages + index in {out_dir}")


if __name__ == "__main__":
    if len(sys.argv) != 3:
        print(f"Usage: {sys.argv[0]} <src_dir> <out_dir>", file=sys.stderr)
        sys.exit(1)
    build(sys.argv[1], sys.argv[2])