18 lines
922 B
Python
18 lines
922 B
Python
#!/usr/bin/env python3
|
|
"""Stamp ?v=<md5[:8]> onto every images/... ref in built HTML and bundles. Idempotent."""
|
|
import glob, hashlib, os, re
|
|
H = {}
|
|
def h(path):
|
|
if path not in H:
|
|
H[path] = hashlib.md5(open(path, "rb").read()).hexdigest()[:8] if os.path.isfile(path) else None
|
|
return H[path]
|
|
REF = re.compile(r'(/?images/[\w./-]+?\.(?:png|jpe?g|webp|svg|gif|avif))(\?v=[0-9a-f]+)?(?=["\') ,\\&])')
|
|
def sub(m):
|
|
v = h(m[1].lstrip("/"))
|
|
return m[1] + (f"?v={v}" if v else (m[2] or ""))
|
|
files = [f for f in glob.glob("**/index.html", recursive=True) if "node_modules" not in f] + glob.glob("*.min.js")
|
|
for f in files:
|
|
s = open(f).read(); t = REF.sub(sub, s)
|
|
if t != s: open(f, "w").write(t)
|
|
assert REF.sub(sub, 'x "/images/dragon-mark.png?v=deadbeef" y').startswith('x "/images/dragon-mark.png?v=' + h("images/dragon-mark.png"))
|
|
print(f"stamp-images: {sum(1 for v in H.values() if v)} images")
|