-
Notifications
You must be signed in to change notification settings - Fork 0
/
compress.py
executable file
·105 lines (94 loc) · 3.11 KB
/
compress.py
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
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
import gzip
import re
import os
import rcssmin as minicss
import rjsmin as minijs
staticfolder = "static"
whitecompress = False
def static_compress(option):
print(option)
dcompress = False
compress = False
if option == "compress":
dcompress = False
compress = True
elif option == "recompress":
dcompress = True
compress = True
elif option == "dcompress":
dcompress = True
compress = False
if "/" not in staticfolder:
rootDir = "./{}".format(staticfolder)
else:
rootDir = staticfolder
SKIP_COMPRESS_EXTENSIONS = (
# Images
"jpg",
"jpeg",
"png",
"gif",
"webp",
# Compressed files
"zip",
"gz",
"tgz",
"bz2",
"tbz",
# Flash
"swf",
"flv",
# Fonts
"woff",
"woff2",
)
skipfile = re.compile(
r"\.({0})$".format("|".join(map(re.escape, SKIP_COMPRESS_EXTENSIONS))),
re.IGNORECASE,
)
def checkext(fname):
return not skipfile.search(fname)
for dirName, subdirList, fileList in os.walk(rootDir, topdown=False):
for fname in fileList:
if checkext(fname):
newfname = str(fname)
if fname.endswith(".css") and not fname.endswith(".min.css"):
with open(
"".join((dirName, "/", fname)), "r", encoding="utf-8"
) as f:
data = minicss.cssmin(f.read())
newfname = fname.replace(".css", ".min.css")
with open(
"".join((dirName, "/", newfname)), "w", encoding="utf-8"
) as fw:
fw.write(data)
elif fname.endswith(".js") and not fname.endswith(".min.js"):
with open(
"".join((dirName, "/", fname)), "r", encoding="utf-8"
) as f:
data = minijs.jsmin(f.read())
newfname = fname.replace(".js", ".min.js")
with open(
"".join((dirName, "/", newfname)), "w", encoding="utf-8"
) as fw:
fw.write(data)
fullpath = dirName + "/" + newfname
gzippath = fullpath + ".gz"
gzipfile = newfname + ".gz"
if newfname[0] == ".":
try:
os.remove(fullpath)
except Exception as exc:
print(exc)
continue
if dcompress and gzipfile in fileList:
os.remove(gzippath)
if compress and (gzipfile not in fileList or dcompress):
originalfile = open(fullpath, "rb")
compressedfile = gzip.open(gzippath, "wb")
compressedfile.writelines(originalfile)
compressedfile.close()
originalfile.close()
return
if __name__ == "__main__":
static_compress("recompress")