summaryrefslogtreecommitdiff
path: root/about-filter.py
blob: 5e97bbe35303b4e68487c5ee21cc80e60fa7caa5 (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
#!/usr/bin/env python3

"""Render cgit repository READMEs as safe HTML."""

import html
import os
import subprocess
import sys


MARKDOWN_EXTENSIONS = (".md", ".markdown")
CMARK_COMMAND = (
    "/usr/bin/cmark-gfm",
    "--validate-utf8",
    "--extension",
    "table",
    "--extension",
    "autolink",
    "--extension",
    "strikethrough",
    "--extension",
    "tasklist",
)

STYLE = """<style>
.markdown-body { line-height: 1.6; overflow-wrap: anywhere; }
.markdown-body img { max-width: 100%; }
.markdown-body pre { overflow-x: auto; padding: 1em; background: rgb(255 255 255 / 6%); }
.markdown-body code { padding: .15em .3em; background: rgb(255 255 255 / 8%); }
.markdown-body pre code { padding: 0; background: none; }
.markdown-body blockquote { margin-left: 0; padding-left: 1em; color: #aaa; border-left: .25em solid #555; }
.markdown-body table { display: block; max-width: 100%; overflow-x: auto; border-collapse: collapse; }
.markdown-body th, .markdown-body td { padding: .4em .8em; border: 1px solid #555; }
.markdown-body input[type="checkbox"] { margin-right: .4em; }
</style>
"""


def render_markdown(source: bytes) -> bytes:
    """Render Markdown with cmark-gfm's safe defaults."""
    result = subprocess.run(
        CMARK_COMMAND,
        input=source,
        stdout=subprocess.PIPE,
        check=True,
    )
    return result.stdout


def render_plain_text(source: bytes) -> bytes:
    """Return arbitrary input as escaped, readable text."""
    text = source.decode("utf-8", errors="replace")
    return f"<pre>{html.escape(text)}</pre>\n".encode()


def main() -> None:
    filename = sys.argv[1] if len(sys.argv) > 1 else ""
    source = sys.stdin.buffer.read()

    if os.path.splitext(filename)[1].lower() in MARKDOWN_EXTENSIONS:
        rendered = render_markdown(source)
    else:
        rendered = render_plain_text(source)

    sys.stdout.buffer.write(STYLE.encode())
    sys.stdout.buffer.write(b'<div class="markdown-body">\n')
    sys.stdout.buffer.write(rendered)
    sys.stdout.buffer.write(b"</div>\n")


if __name__ == "__main__":
    main()