34 lines
1.0 KiB
Python
34 lines
1.0 KiB
Python
import re, sys, glob, os
|
|
|
|
def minify(css: str) -> str:
|
|
# 1) strip comments but protect strings
|
|
out=[]; i=0; n=len(css)
|
|
while i<n:
|
|
c=css[i]
|
|
if c in "\"'":
|
|
q=c; out.append(c); i+=1
|
|
while i<n and css[i]!=q:
|
|
if css[i]=="\\": out.append(css[i]); i+=1
|
|
out.append(css[i]); i+=1
|
|
if i<n: out.append(css[i]); i+=1
|
|
elif css[i:i+2]=="/*":
|
|
j=css.find("*/", i+2); i=(j+2) if j>=0 else n
|
|
else:
|
|
out.append(c); i+=1
|
|
s="".join(out)
|
|
# 2) collapse whitespace
|
|
s=re.sub(r"\s+"," ", s).strip()
|
|
# 3) remove spaces around punctuation (string-aware: simple heuristic ok for CSS)
|
|
s=re.sub(r"\s*([{}:;,>~+])\s*", r"\1", s)
|
|
s=s.replace(";}", "}")
|
|
s=re.sub(r"\s+"," ", s)
|
|
return s
|
|
|
|
if __name__=="__main__":
|
|
if len(sys.argv)>1:
|
|
for f in sys.argv[1:]:
|
|
print(minify(open(f,encoding="utf-8").read()))
|
|
else:
|
|
for f in sorted(glob.glob("theme/blog_share_*.css")):
|
|
print(f, "->", len(f""))
|