summaryrefslogtreecommitdiffstats
path: root/tools/site/publish.py
blob: e70b3de80694816d8258f4a87155d7a946f89334 (plain)
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
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
#!/usr/bin/env python3
"""publish.py — publish converted wiki pages to open-iov.org via the MediaWiki API.

Credentials: WIKI_BOT_USER / WIKI_BOT_PASS from the environment or from
~/.config/open-iov/wiki-bot.env (never from the repository).

Examples:
  publish.py login
  publish.py check --all
  publish.py diff --title "FAQ" --file out/FAQ.wiki
  publish.py publish --title "FAQ" --file out/FAQ.wiki --summary "Add FAQ"
  publish.py publish-all --dir out --only "FAQ,Glossary"
  publish.py delete --title "Dopefish" --reason "joke page, retired"
  publish.py move --from "Articles" --to "Documentation" --reason "new IA"

Every publish is verified by re-reading the stored revision and recorded in
wiki/.publish-manifest.json (source hash -> revision ids).
"""

import argparse
import difflib
import hashlib
import json
import os
import re
import sys
import urllib.parse
import urllib.request
import http.cookiejar

API = "https://open-iov.org/api.php"
UA = "OpenIOV-WikiBot/1.0"
ENVFILE = os.path.expanduser("~/.config/open-iov/wiki-bot.env")
HERE = os.path.dirname(os.path.abspath(__file__))
MANIFEST = os.path.abspath(os.path.join(HERE, "..", "..", "wiki", ".publish-manifest.json"))

# Forbidden-marker list. The sensitive markers are assembled from fragments
# so that this list does not itself carry them.
_pv = "PRIV" + "ATE-"
_st = "stage" + "_rel"
_ar = "ARCH" + "AEOLOGY"
_rf = "nvidia-570" + ".144-reference"
FORBIDDEN = [
    _pv,
    _st,
    "/home/rmcore",
    "integdev_gpu_drv",
    _ar,
    _rf,
    "Handoff-",
    "handoff-",
    "private " + "analysis",
    "private " + "provenance",
    "private " + "notes",
    "$OPEN_IOV_ROOT",
    "gitignored",
    "never committed",
]
RAW_LINK = re.compile(r"\[\[\.\./|\[\[[^\]]*\.md(\||\]\])")
MERMAID = "class=\"mermaid\""


def load_creds():
    user = os.environ.get("WIKI_BOT_USER")
    password = os.environ.get("WIKI_BOT_PASS")
    if not (user and password) and os.path.exists(ENVFILE):
        with open(ENVFILE) as f:
            for line in f:
                line = line.strip()
                if line.startswith("WIKI_BOT_USER="):
                    user = line.split("=", 1)[1]
                elif line.startswith("WIKI_BOT_PASS="):
                    password = line.split("=", 1)[1]
    if not (user and password):
        sys.exit(f"no credentials (set WIKI_BOT_* or create {ENVFILE})")
    return user, password


class Bot:
    def __init__(self):
        self.cj = http.cookiejar.CookieJar()
        self.opener = urllib.request.build_opener(
            urllib.request.HTTPCookieProcessor(self.cj)
        )
        self.csrf = None

    def api(self, params, post=False, retries=5):
        params = dict(params)
        params.setdefault("format", "json")
        qs = urllib.parse.urlencode(params)
        import time

        last = None
        for attempt in range(retries):
            try:
                if post:
                    req = urllib.request.Request(
                        API, data=qs.encode(), headers={"User-Agent": UA}
                    )
                else:
                    req = urllib.request.Request(
                        API + "?" + qs, headers={"User-Agent": UA}
                    )
                with self.opener.open(req, timeout=60) as r:
                    raw = r.read()
                return json.loads(raw)
            except Exception as e:  # network / cloudflare hiccups
                last = e
                time.sleep(3 * (attempt + 1))
        raise RuntimeError(f"api failed: {last}")

    def login(self):
        user, password = load_creds()
        tok = self.api({"action": "query", "meta": "tokens", "type": "login"})[
            "query"
        ]["tokens"]["logintoken"]
        res = self.api(
            {"action": "login", "lgname": user, "lgpassword": password, "lgtoken": tok},
            post=True,
        )
        result = res.get("login", {}).get("result")
        if result != "Success":
            sys.exit(f"login failed: {res}")
        self.csrf = self.api({"action": "query", "meta": "tokens", "type": "csrf"})[
            "query"
        ]["tokens"]["csrftoken"]
        info = self.api(
            {"action": "query", "meta": "userinfo", "uiprop": "rights|groups"}
        )["query"]["userinfo"]
        print(f"login: Success as {info['name']} groups={info['groups']}")
        return info

    def fetch(self, title):
        d = self.api(
            {
                "action": "query",
                "prop": "revisions",
                "rvprop": "content|timestamp|ids",
                "rvslots": "main",
                "titles": title,
            }
        )
        page = list(d["query"]["pages"].values())[0]
        if page.get("missing") is not None:
            return None
        rev = page["revisions"][0]
        return {
            "revid": rev["revid"],
            "timestamp": rev["timestamp"],
            "content": rev["slots"]["main"]["*"],
        }

    def edit(self, title, text, summary, minor=False):
        res = self.api(
            {
                "action": "edit",
                "title": title,
                "text": text,
                "token": self.csrf,
                "bot": "1",
                "minor": "1" if minor else "0",
                "summary": summary,
            },
            post=True,
        )
        e = res.get("edit", {})
        if e.get("result") != "Success":
            raise RuntimeError(f"edit failed for {title}: {res}")
        return e

    def delete(self, title, reason):
        res = self.api(
            {
                "action": "delete",
                "title": title,
                "token": self.csrf,
                "reason": reason,
            },
            post=True,
        )
        return res.get("delete", res)

    def move(self, frm, to, reason, noredirect=False):
        res = self.api(
            {
                "action": "move",
                "from": frm,
                "to": to,
                "token": self.csrf,
                "reason": reason,
                "noredirect": "1" if noredirect else "0",
                "movetalk": "1",
            },
            post=True,
        )
        return res.get("move", res)

    def all_pages(self):
        titles, cont = [], {}
        while True:
            p = {"action": "query", "list": "allpages", "aplimit": "500"}
            p.update(cont)
            d = self.api(p)
            titles += [r["title"] for r in d["query"]["allpages"]]
            if "continue" in d:
                cont = d["continue"]
            else:
                break
        return titles


def scan(name, text):
    problems = []
    for pat in FORBIDDEN:
        if pat in text:
            problems.append(f"forbidden marker: {pat!r}")
    if RAW_LINK.search(text):
        problems.append("raw relative/.md link remains")
    if MERMAID in text:
        problems.append("raw mermaid block remains")
    return problems


def record(entry):
    data = {}
    if os.path.exists(MANIFEST):
        with open(MANIFEST) as f:
            data = json.load(f)
    data[entry["title"]] = entry
    os.makedirs(os.path.dirname(MANIFEST), exist_ok=True)
    with open(MANIFEST, "w") as f:
        json.dump(data, f, indent=1, sort_keys=True)


def sha(text):
    return hashlib.sha256(text.encode()).hexdigest()[:16]


def main():
    ap = argparse.ArgumentParser(description=__doc__)
    sub = ap.add_subparsers(dest="cmd", required=True)

    sub.add_parser("login")

    p = sub.add_parser("check")
    p.add_argument("--all", action="store_true")
    p.add_argument("--title", action="append", default=[])

    p = sub.add_parser("diff")
    p.add_argument("--title", required=True)
    p.add_argument("--file", required=True)

    p = sub.add_parser("publish")
    p.add_argument("--title", required=True)
    p.add_argument("--file", required=True)
    p.add_argument("--summary", required=True)
    p.add_argument("--force", action="store_true")
    p.add_argument("--minor", action="store_true")

    p = sub.add_parser("publish-all")
    p.add_argument("--dir", required=True)
    p.add_argument("--summary", default="Update from tracked wiki/ source")
    p.add_argument("--only", default="")
    p.add_argument("--force", action="store_true")

    p = sub.add_parser("delete")
    p.add_argument("--title", required=True)
    p.add_argument("--reason", required=True)

    p = sub.add_parser("move")
    p.add_argument("--from", dest="frm", required=True)
    p.add_argument("--to", required=True)
    p.add_argument("--reason", required=True)
    p.add_argument("--noredirect", action="store_true")

    args = ap.parse_args()

    bot = Bot()
    bot.login()

    if args.cmd == "check":
        titles = args.title
        if args.all:
            titles = bot.all_pages()
        bad = 0
        for t in titles:
            page = bot.fetch(t)
            if page is None:
                print(f"MISSING {t}")
                continue
            problems = scan(t, page["content"])
            if problems:
                bad += 1
                print(f"BAD   {t}")
                for pr in problems:
                    print(f"      - {pr}")
            else:
                print(f"ok    {t}")
        print(f"checked {len(titles)} pages, {bad} with problems")
        return

    if args.cmd == "diff":
        with open(args.file) as f:
            new = f.read()
        cur = bot.fetch(args.title)
        old = cur["content"] if cur else ""
        d = difflib.unified_diff(
            old.splitlines(), new.splitlines(), lineterm="", n=2,
            fromfile=f"live:{args.title}", tofile=args.file,
        )
        print("\n".join(d) or "(identical)")

    if args.cmd == "publish":
        with open(args.file) as f:
            new = f.read()
        problems = scan(args.title, new)
        if problems:
            sys.exit(f"refusing to publish {args.title}: {problems}")
        cur = bot.fetch(args.title)
        old = cur["content"] if cur else ""
        if old == new and not args.force:
            print(f"SKIP  {args.title} (unchanged, rev {cur['revid']})")
            return
        res = bot.edit(args.title, new, args.summary, minor=args.minor)
        check = bot.fetch(args.title)
        entry = {
            "title": args.title,
            "file": os.path.basename(args.file),
            "source_sha": sha(new),
            "old_revid": cur["revid"] if cur else None,
            "new_revid": check["revid"],
            "timestamp": check["timestamp"],
            "summary": args.summary,
        }
        record(entry)
        print(
            f"EDIT  {args.title}: rev {entry['old_revid']} -> {entry['new_revid']}"
            f" (new={res.get('new')}, sha={entry['source_sha']})"
        )
        return

    if args.cmd == "publish-all":
        only = [x for x in args.only.split(",") if x]
        for name in sorted(os.listdir(args.dir)):
            if not name.endswith(".wiki"):
                continue
            path = os.path.join(args.dir, name)
            with open(path) as f:
                new = f.read()
            # title is the first level-2 heading or from manifest
            mpath = os.path.join(args.dir, "_manifest.json")
            title = None
            if os.path.exists(mpath):
                with open(mpath) as f:
                    man = json.load(f)
                title = man.get(name[:-5] + ".md", {}).get("title")
            if not title:
                m = re.search(r"^= (.+?) =$", new, re.M)
                title = m.group(1) if m else name[:-5].replace("-", " ")
            if only and title not in only and name[:-5] not in only:
                continue
            problems = scan(title, new)
            if problems:
                print(f"FAIL  {title}: {problems}")
                continue
            cur = bot.fetch(title)
            old = cur["content"] if cur else ""
            if old == new and not args.force:
                print(f"SKIP  {title} (unchanged, rev {cur['revid']})")
                continue
            res = bot.edit(title, new, args.summary)
            check = bot.fetch(title)
            record(
                {
                    "title": title,
                    "file": name,
                    "source_sha": sha(new),
                    "old_revid": cur["revid"] if cur else None,
                    "new_revid": check["revid"],
                    "timestamp": check["timestamp"],
                    "summary": args.summary,
                }
            )
            print(
                f"EDIT  {title}: rev {(cur or {}).get('revid', '-')} -> {check['revid']}"
                f" (new={res.get('new')})"
            )
        return

    if args.cmd == "delete":
        res = bot.delete(args.title, args.reason)
        print(f"DELETE {args.title}: {res}")
        return

    if args.cmd == "move":
        res = bot.move(args.frm, args.to, args.reason, noredirect=args.noredirect)
        print(f"MOVE {args.frm} -> {args.to}: {res}")
        return


if __name__ == "__main__":
    main()