67 lines
1.9 KiB
Python
67 lines
1.9 KiB
Python
Import("env")
|
|
|
|
import gzip
|
|
import re
|
|
from pathlib import Path
|
|
|
|
|
|
ROOT = Path(env.subst("$PROJECT_DIR"))
|
|
DATA = ROOT / "data"
|
|
ASSETS = ("index.html", "styles.css", "app.js", "target_interaction.js", "web_audio.js", "game_sounds.js", "ship-sprite.svg", "setup.html", "setup.css", "setup.js")
|
|
|
|
|
|
def minify_html(source):
|
|
return re.sub(r">\s+<", "><", source).strip()
|
|
|
|
|
|
def minify_css(source):
|
|
source = re.sub(r"/\*.*?\*/", "", source, flags=re.S)
|
|
return re.sub(r"\s*([{}:;,>])\s*", r"\1", source).strip()
|
|
|
|
|
|
def minify_js(source):
|
|
output = []
|
|
quote = ""
|
|
escaped = False
|
|
pending_space = False
|
|
for character in source:
|
|
if quote:
|
|
output.append(character)
|
|
if escaped:
|
|
escaped = False
|
|
elif character == "\\":
|
|
escaped = True
|
|
elif character == quote:
|
|
quote = ""
|
|
continue
|
|
if character in ("'", '"', "`"):
|
|
if pending_space and output and (output[-1].isalnum() or output[-1] in "_$"):
|
|
output.append(" ")
|
|
pending_space = False
|
|
quote = character
|
|
output.append(character)
|
|
elif character.isspace():
|
|
pending_space = True
|
|
else:
|
|
if pending_space and output and (output[-1].isalnum() or output[-1] in "_$") and (character.isalnum() or character in "_$"):
|
|
output.append(" ")
|
|
pending_space = False
|
|
output.append(character)
|
|
return "".join(output)
|
|
|
|
|
|
def compress_assets():
|
|
for asset in ASSETS:
|
|
path = DATA / asset
|
|
text = path.read_text(encoding="utf-8")
|
|
if asset.endswith(".html"):
|
|
text = minify_html(text)
|
|
elif asset.endswith(".css"):
|
|
text = minify_css(text)
|
|
elif asset.endswith(".js"):
|
|
text = minify_js(text)
|
|
(DATA / f"{asset}.gz").write_bytes(gzip.compress(text.encode("utf-8"), mtime=0))
|
|
|
|
|
|
compress_assets()
|