-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathinline_data.py
More file actions
65 lines (51 loc) · 2.05 KB
/
Copy pathinline_data.py
File metadata and controls
65 lines (51 loc) · 2.05 KB
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
"""Inline media.json into index.html so the page works under file:// (no fetch).
Idempotent: handles both the first run (placeholder token __MEDIA__) and
subsequent re-runs (replaces the JSON inside the existing
<script id="media-data" type="application/json">...</script> tag).
Re-run after editing media.json.
"""
import json, os, re
ROOT = os.path.dirname(os.path.abspath(__file__))
TPL_PATH = os.path.join(ROOT, "index.html")
DATA_FILES = {
"media-data": os.path.join(ROOT, "media.json"),
}
TOKEN_FALLBACK = {
"media-data": "__MEDIA__",
}
def normalize_json(text):
return json.dumps(json.loads(text), ensure_ascii=False)
def main():
src = open(TPL_PATH, encoding="utf-8").read()
for script_id, path in DATA_FILES.items():
has_tag = re.search(
r'<script\s+id="' + re.escape(script_id) + r'"\s+type="application/json">',
src,
)
token = TOKEN_FALLBACK.get(script_id, "")
has_token = token and token in src
if not has_tag and not has_token:
continue
if not os.path.exists(path):
print(f" skip #{script_id} (data file missing: {path})")
continue
with open(path, encoding="utf-8") as f:
payload = normalize_json(f.read())
payload = payload.replace("</script>", "<\\/script>")
# Replace contents of an existing tag in preference to the placeholder.
pat = re.compile(
r'(<script\s+id="' + re.escape(script_id) + r'"\s+type="application/json">)([\s\S]*?)(</script>)'
)
new_src, n = pat.subn(lambda m: m.group(1) + payload + m.group(3), src, count=1)
if n:
print(f" refreshed #{script_id} ({len(payload):,} chars)")
src = new_src
continue
if has_token:
src = src.replace(token, payload, 1)
print(f" inlined {token} ({len(payload):,} chars)")
with open(TPL_PATH, "w", encoding="utf-8") as f:
f.write(src)
print(f"Wrote {TPL_PATH} ({len(src):,} bytes)")
if __name__ == "__main__":
main()