Debian Codegraph @

src/whitenoise/compress.py

raw
1 from __future__ import annotations
2
3 import argparse
4 import gzip
5 import os
6 import re
7 from concurrent.futures import ThreadPoolExecutor
8 from concurrent.futures import as_completed
9 from io import BytesIO
10
11 try:
12 import brotli
13
14 brotli_installed = True
15 except ImportError: # pragma: no cover
16 brotli_installed = False
17
18
19 class Compressor:
20 # Extensions that it's not worth trying to compress
21 SKIP_COMPRESS_EXTENSIONS = (
22 # Images
23 "jpg",
24 "jpeg",
25 "png",
26 "gif",
27 "webp",
28 # Compressed files
29 "zip",
30 "gz",
31 "tgz",
32 "bz2",
33 "tbz",
34 "xz",
35 "br",
36 # Flash
37 "swf",
38 "flv",
39 # Fonts
40 "woff",
41 "woff2",
42 # Video
43 "3gp",
44 "3gpp",
45 "asf",
46 "avi",
47 "m4v",
48 "mov",
49 "mp4",
50 "mpeg",
51 "mpg",
52 "webm",
53 "wmv",
54 )
55
56 def __init__(
57 self, extensions=None, use_gzip=True, use_brotli=True, log=print, quiet=False
58 ):
59 if extensions is None:
60 extensions = self.SKIP_COMPRESS_EXTENSIONS
61 self.extension_re = self.get_extension_re(extensions)
62 self.use_gzip = use_gzip
63 self.use_brotli = use_brotli and brotli_installed
64 if not quiet:
65 self.log = log
66
67 @staticmethod
68 def get_extension_re(extensions):
69 if not extensions:
70 return re.compile("^$")
71 else:
72 return re.compile(
73 r"\.({})$".format("|".join(map(re.escape, extensions))), re.IGNORECASE
74 )
75
76 def should_compress(self, filename):
77 return not self.extension_re.search(filename)
78
79 def log(self, message):
80 pass
81
82 def compress(self, path):
83 filenames = []
84 with open(path, "rb") as f:
85 stat_result = os.fstat(f.fileno())
86 data = f.read()
87 size = len(data)
88 if self.use_brotli:
89 compressed = self.compress_brotli(data)
90 if self.is_compressed_effectively("Brotli", path, size, compressed):
91 filenames.append(self.write_data(path, compressed, ".br", stat_result))
92 else:
93 # If Brotli compression wasn't effective gzip won't be either
94 return filenames
95 if self.use_gzip:
96 compressed = self.compress_gzip(data)
97 if self.is_compressed_effectively("Gzip", path, size, compressed):
98 filenames.append(self.write_data(path, compressed, ".gz", stat_result))
99 return filenames
100
101 @staticmethod
102 def compress_gzip(data):
103 output = BytesIO()
104 # Explicitly set mtime to 0 so gzip content is fully determined
105 # by file content (0 = "no timestamp" according to gzip spec)
106 with gzip.GzipFile(
107 filename="", mode="wb", fileobj=output, compresslevel=9, mtime=0
108 ) as gz_file:
109 gz_file.write(data)
110 return output.getvalue()
111
112 @staticmethod
113 def compress_brotli(data):
114 return brotli.compress(data)
115
116 def is_compressed_effectively(self, encoding_name, path, orig_size, data):
117 compressed_size = len(data)
118 if orig_size == 0:
119 is_effective = False
120 else:
121 ratio = compressed_size / orig_size
122 is_effective = ratio <= 0.95
123 if is_effective:
124 self.log(
125 "{} compressed {} ({}K -> {}K)".format(
126 encoding_name, path, orig_size // 1024, compressed_size // 1024
127 )
128 )
129 else:
130 self.log(f"Skipping {path} ({encoding_name} compression not effective)")
131 return is_effective
132
133 def write_data(self, path, data, suffix, stat_result):
134 filename = path + suffix
135 with open(filename, "wb") as f:
136 f.write(data)
137 os.utime(filename, (stat_result.st_atime, stat_result.st_mtime))
138 return filename
139
140
141 def main(argv=None):
142 parser = argparse.ArgumentParser(
143 description="Search for all files inside <root> *not* matching "
144 "<extensions> and produce compressed versions with "
145 "'.gz' and '.br' suffixes (as long as this results in a "
146 "smaller file)"
147 )
148 parser.add_argument(
149 "-q", "--quiet", help="Don't produce log output", action="store_true"
150 )
151 parser.add_argument(
152 "--no-gzip",
153 help="Don't produce gzip '.gz' files",
154 action="store_false",
155 dest="use_gzip",
156 )
157 parser.add_argument(
158 "--no-brotli",
159 help="Don't produce brotli '.br' files",
160 action="store_false",
161 dest="use_brotli",
162 )
163 parser.add_argument("root", help="Path root from which to search for files")
164 default_exclude = ", ".join(Compressor.SKIP_COMPRESS_EXTENSIONS)
165 parser.add_argument(
166 "extensions",
167 nargs="*",
168 help=(
169 "File extensions to exclude from compression "
170 + f"(default: {default_exclude})"
171 ),
172 default=Compressor.SKIP_COMPRESS_EXTENSIONS,
173 )
174 args = parser.parse_args(argv)
175
176 compressor = Compressor(
177 extensions=args.extensions,
178 use_gzip=args.use_gzip,
179 use_brotli=args.use_brotli,
180 quiet=args.quiet,
181 )
182
183 with ThreadPoolExecutor() as executor:
184 futures = []
185 for dirpath, _dirs, files in os.walk(args.root):
186 for filename in files:
187 if compressor.should_compress(filename):
188 futures.append(
189 executor.submit(
190 compressor.compress, os.path.join(dirpath, filename)
191 )
192 )
193 # Trigger any errors
194 for future in as_completed(futures):
195 future.result()
196
197 return 0
198
199
200 if __name__ == "__main__": # pragma: no cover
201 raise SystemExit(main())