Files
HomeDash/web/patch-index.py
JianFeeeee c4b0b8abdf build: 用 patch-index.py 幂等注入 navi.css/navi.js
Dashy 的 index.html 不保证有 </body>,原来 sed 替换 </body> 会静默丢掉注入的
<script>(旧镜像里 script 与 </body> 同行,被整行删除后就没有锚点了),
结果新访客加载不到 navi.js。改为 Python 脚本:先清理旧标签,再在
</head>/</body> 前插入,缺 </body> 时在 </html> 前补回来,可重复执行。

同时 .gitignore 忽略 __pycache__。
2026-09-11 16:25:26 +08:00

47 lines
1.6 KiB
Python

#!/usr/bin/env python3
"""Idempotently inject the HomeDash stylesheet and script into Dashy's index.html.
Dashy's index.html does not always contain a `</body>` tag. A naive
`sed s#</body>#...#` therefore silently drops the injected script (and the
`</body>` marker itself). This script inserts before `</head>`/`</body>` when
those exist, otherwise before `</html>`, and restores a missing `</body>`.
"""
import re
import sys
CSS_TAG = '<link rel="stylesheet" href="/navi.css">'
JS_TAG = '<script src="/navi.js"></script>'
def patch(html: str) -> str:
html = re.sub(r'[ \t]*<link rel="stylesheet" href="/navi\.css">\s*', '', html)
html = re.sub(r'[ \t]*<script src="/navi\.js"></script>\s*', '', html)
if '</head>' in html:
html = html.replace('</head>', CSS_TAG + '</head>', 1)
if '</body>' in html:
html = html.replace('</body>', JS_TAG + '</body>', 1)
elif '</html>' in html:
html = html.replace('</html>', JS_TAG + '\n</body>\n</html>', 1)
else:
html = html + '\n' + JS_TAG + '\n'
return html
def main(path: str) -> int:
with open(path, encoding='utf-8') as fh:
original = fh.read()
patched = patch(original)
if 'href="/navi.css"' not in patched or 'src="/navi.js"' not in patched:
print('patch failed: tags missing after patch', file=sys.stderr)
return 1
with open(path, 'w', encoding='utf-8') as fh:
fh.write(patched)
print('patched %s (%s)' % (path, 'changed' if patched != original else 'unchanged'))
return 0
if __name__ == '__main__':
raise SystemExit(main(sys.argv[1] if len(sys.argv) > 1 else '/app/dashy/index.html'))