summaryrefslogtreecommitdiff
path: root/web/prefix.py
blob: 06bf4971215df79de0fdf464b2fdb7a9ffebf4b2 (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
212
213
214
215
216
217
218
219
220
221
222
223
#!/usr/bin/env python3
"""Optional build-time relocation of generated static output, never HTTP rewriting.

HTML URL attributes and CSS URLs/URL selectors only. JavaScript, JSON, authored
text and normal build output are untouched. This is not a JavaScript compiler:
sites constructing absolute asset URLs in JS need their own base-path option.
Published previews are symlinks to complete generations; old generations are
retained so open readers and a failed next build cannot lose their output.
"""
import argparse
from html.parser import HTMLParser
import html as html_lib
from pathlib import Path
import os
import re
import shutil
import tempfile


def check_prefix(prefix):
    if not re.fullmatch(r"/(?:[A-Za-z0-9_-]+/)*[A-Za-z0-9_-]+/?", prefix):
        raise ValueError("prefix must be an absolute path of named segments, e.g. /sites/cafe/")
    return prefix.rstrip("/")


def url(value, prefix):
    if value.startswith("/") and not value.startswith("//"):
        return prefix + value
    return value


def string_end(text, start):
    quote = text[start]
    i = start + 1
    while i < len(text):
        if text[i] == "\\":
            i += 2
        elif text[i] == quote:
            return i + 1
        else:
            i += 1
    raise ValueError("unterminated CSS string")


def css(text, prefix):
    parts, i = [], 0
    while i < len(text):
        start = i
        if text.startswith("/*", i):
            end = text.find("*/", i + 2)
            i = len(text) if end < 0 else end + 2
            parts.append(text[start:i])
        elif text[i:i+4].lower() == "url(" and (i == 0 or not (text[i-1].isalnum() or text[i-1] in "_-")):
            i += 4
            while i < len(text) and text[i].isspace():
                i += 1
            if i < len(text) and text[i] in "\"'":
                end = string_end(text, i)
                parts.extend((text[start:i+1], url(text[i+1:end-1], prefix), text[end-1:end]))
                i = end
            else:
                end = text.find(")", i)
                if end < 0:
                    raise ValueError("unterminated CSS url()")
                parts.extend((text[start:i], url(text[i:end], prefix)))
                i = end
        elif text[i] in "\"'":
            i = string_end(text, i)
            # URL attribute selectors must continue matching relocated links.
            context = text[:start]
            is_url = re.search(r"(?:@import\s*|\[\s*(?:href|src|action)\s*=\s*)$", context, re.I)
            value = text[start+1:i-1]
            parts.append(text[start] + (url(value, prefix) if is_url else value) + text[i-1])
        else:
            parts.append(text[i])
            i += 1
    return "".join(parts)


ATTR = re.compile(r"([\w:-]+)(\s*=\s*)(\"[^\"]*\"|'[^']*'|[^\s>]+)")
URL_ATTRS = {"href", "src", "poster", "action", "formaction", "cite", "data", "xlink:href"}


def srcset(text, prefix):
    # Data URLs may contain commas; do not blindly split every comma.
    parts, i = [], 0
    while i < len(text):
        start = i
        while i < len(text) and (text[i].isspace() or text[i] == ','):
            i += 1
        parts.append(text[start:i])
        start = i
        while i < len(text) and not text[i].isspace():
            i += 1
        value = text[start:i]
        parts.append(url(value, prefix))
        if value.endswith(','):
            continue
        start = i
        depth = 0
        while i < len(text):
            ch = text[i]
            if ch == '(':
                depth += 1
            elif ch == ')':
                depth -= 1
            i += 1
            if ch == ',' and depth == 0:
                break
        parts.append(text[start:i])
    return ''.join(parts)


class Document(HTMLParser):
    def __init__(self, prefix):
        super().__init__(convert_charrefs=False)
        self.prefix, self.parts, self.raw = prefix, [], None

    def tag(self, tag, closed=False):
        def attr(m):
            name, eq, raw = m.groups()
            quote = raw[0] if raw[0] in "\"'" else ""
            value = raw[1:-1] if quote else raw
            original = value
            decoded = html_lib.unescape(value)
            if name.lower() in URL_ATTRS:
                value = url(decoded, self.prefix)
            elif name.lower() == "style":
                value = css(decoded, self.prefix)
            elif name.lower() == "srcset":
                value = srcset(decoded, self.prefix)
            else:
                return m[0]
            value = html_lib.escape(value, quote=True) if value != decoded else original
            return name + eq + quote + value + quote
        self.parts.append(ATTR.sub(attr, self.get_starttag_text()))
        if not closed and tag in ("script", "style"):
            self.raw = tag

    def handle_starttag(self, tag, attrs):
        self.tag(tag)

    def handle_startendtag(self, tag, attrs):
        self.tag(tag, True)

    def handle_endtag(self, tag):
        self.parts.append(f"</{tag}>")
        if tag == self.raw:
            self.raw = None

    def handle_data(self, data):
        self.parts.append(css(data, self.prefix) if self.raw == "style" else data)

    def handle_entityref(self, name):
        self.parts.append(f"&{name};")

    def handle_charref(self, name):
        self.parts.append(f"&#{name};")

    def handle_comment(self, data):
        self.parts.append(f"<!--{data}-->")

    def handle_decl(self, decl):
        self.parts.append(f"<!{decl}>")

    def handle_pi(self, data):
        self.parts.append(f"<?{data}>")


def html(text, prefix):
    parser = Document(prefix)
    parser.feed(text)
    parser.close()
    return "".join(parser.parts)


def publish(source, output, prefix):
    prefix = check_prefix(prefix)
    source, output = Path(source).resolve(), Path(output).absolute()
    if not (source / "index.html").is_file():
        raise ValueError("source must contain an already-built index.html")
    if source == output.resolve() or source in output.resolve().parents:
        raise ValueError("preview output must be outside the normal build output")
    if output.exists() and not output.is_symlink():
        raise ValueError("refusing to replace a non-symlink output; choose a new preview path")
    output.parent.mkdir(parents=True, exist_ok=True)
    stage = Path(tempfile.mkdtemp(prefix=f".{output.name}-build-", dir=output.parent))
    link = stage.with_name(stage.name + ".link")
    try:
        for path in source.rglob("*"):
            if path.is_symlink():
                raise ValueError(f"symlink in build output: {path}")
            target = stage / path.relative_to(source)
            if path.is_dir():
                target.mkdir(exist_ok=True)
            elif path.is_file():
                target.parent.mkdir(parents=True, exist_ok=True)
                if path.suffix.lower() in (".html", ".css"):
                    text = path.read_text(encoding="utf-8")
                    transform = html if path.suffix.lower() == ".html" else css
                    target.write_text(transform(text, prefix), encoding="utf-8")
                else:
                    shutil.copy2(path, target)
        link.symlink_to(stage.name, target_is_directory=True)
        os.replace(link, output)
    except BaseException:
        link.unlink(missing_ok=True)
        shutil.rmtree(stage)
        raise
    print(f"preview: {output} at {prefix}/ (normal output unchanged)")


def main():
    parser = argparse.ArgumentParser(description=__doc__)
    parser.add_argument("--url-prefix", required=True)
    parser.add_argument("--output", required=True)
    parser.add_argument("source")
    args = parser.parse_args()
    publish(args.source, args.output, args.url_prefix)


if __name__ == "__main__":
    main()