-
-
Notifications
You must be signed in to change notification settings - Fork 52
Expand file tree
/
Copy path__main__.py
More file actions
360 lines (319 loc) · 12.6 KB
/
__main__.py
File metadata and controls
360 lines (319 loc) · 12.6 KB
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
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
from __future__ import print_function
import sys
import os
import argparse
from pkg_resources import get_distribution, DistributionNotFound
from python_minifier import minify
from python_minifier.transforms.remove_annotations_options import RemoveAnnotationsOptions
from python_minifier.transforms.remove_unused_platform_options import RemoveUnusedPlatformOptions
try:
version = get_distribution('python_minifier').version
except DistributionNotFound:
version = '0.0.0'
def main():
"""
examples:
# Minifying stdin to stdout
pyminify -
# Minifying a file to stdout
pyminify example.py
# Minifying a file and writing to a different file
pyminify example.py --output example.min.py
# Minifying a file in place
pyminify example.py --in-place
# Minifying all *.py files in a directory
pyminify src/ --in-place
# Minifying multiple paths in place
pyminify file1.py file2.py src/ --in-place
"""
args = parse_args()
if len(args.path) == 1 and args.path[0] == '-':
# minify stdin
source = sys.stdin.buffer.read() if sys.version_info >= (3, 0) else sys.stdin.read()
minified = do_minify(source, 'stdin', args)
if args.output:
with open(args.output, 'w') as f:
f.write(minified)
else:
sys.stdout.write(minified)
else:
# minify source paths
for path in source_modules(args):
if args.output or args.in_place:
sys.stdout.write(path + '\n')
with open(path, 'rb') as f:
source = f.read()
minified = do_minify(source, path, args)
if args.in_place:
with open(path, 'w') as f:
f.write(minified)
elif args.output:
with open(args.output, 'w') as f:
f.write(minified)
else:
sys.stdout.write(minified)
def parse_args():
parser = argparse.ArgumentParser(prog='pyminify', description='Minify Python source code', formatter_class=argparse.RawDescriptionHelpFormatter, epilog=main.__doc__)
parser.add_argument(
'path',
nargs='+',
type=str,
help='The source file or directory to minify. Use "-" to read from stdin. Directories are recursively searched for ".py" files to minify. May be used multiple times',
)
output_options = parser.add_mutually_exclusive_group()
output_options.add_argument(
'--output', '-o',
action='store',
help='Path to write minified output. Can only be used when the source is a single module. Outputs to stdout by default',
dest='output'
)
output_options.add_argument(
'--in-place', '-i',
action='store_true',
help='Overwrite existing files. Required when there is more than one source module',
dest='in_place'
)
# Minification arguments
minification_options = parser.add_argument_group('minification options', 'Options that affect how the source is minified')
minification_options.add_argument(
'--no-combine-imports',
action='store_false',
help='Disable combining adjacent import statements',
dest='combine_imports',
)
minification_options.add_argument(
'--no-remove-pass',
action='store_false',
default=True,
help='Disable removing Pass statements',
dest='remove_pass',
)
minification_options.add_argument(
'--remove-literal-statements',
action='store_true',
help='Enable removing statements that are just a literal (including docstrings)',
dest='remove_literal_statements',
)
minification_options.add_argument(
'--no-hoist-literals',
action='store_false',
help='Disable replacing string and bytes literals with variables',
dest='hoist_literals',
)
minification_options.add_argument(
'--no-rename-locals',
action='store_false',
help='Disable shortening of local names',
dest='rename_locals'
)
minification_options.add_argument(
'--preserve-locals',
type=str,
action='append',
help='Comma separated list of local names that will not be shortened',
dest='preserve_locals',
metavar='LOCAL_NAMES'
)
minification_options.add_argument(
'--rename-globals',
action='store_true',
help='Enable shortening of global names',
dest='rename_globals'
)
minification_options.add_argument(
'--preserve-globals',
type=str,
action='append',
help='Comma separated list of global names that will not be shortened',
dest='preserve_globals',
metavar='GLOBAL_NAMES'
)
minification_options.add_argument(
'--no-remove-object-base',
action='store_false',
help='Disable removing object from base class list',
dest='remove_object_base',
)
minification_options.add_argument(
'--no-convert-posargs-to-args',
action='store_false',
help='Disable converting positional only arguments to normal arguments',
dest='convert_posargs_to_args',
)
minification_options.add_argument(
'--no-preserve-shebang',
action='store_false',
help='Preserve any shebang line from the source',
dest='preserve_shebang',
)
minification_options.add_argument(
'--remove-asserts',
action='store_true',
help='Remove assert statements',
dest='remove_asserts',
)
minification_options.add_argument(
'--remove-debug',
action='store_true',
help='Remove conditional statements that test __debug__ is True',
dest='remove_debug',
)
minification_options.add_argument(
'--no-remove-explicit-return-none',
action='store_false',
help='Replace explicit return None with a bare return',
dest='remove_explicit_return_none',
)
minification_options.add_argument(
'--no-remove-builtin-exception-brackets',
action='store_false',
help='Disable removing brackets when raising builtin exceptions with no arguments',
dest='remove_exception_brackets',
)
minification_options.add_argument(
'--no-constant-folding',
action='store_false',
help='Disable evaluating literal expressions',
dest='constant_folding',
)
annotation_options = parser.add_argument_group('remove annotations options', 'Options that affect how annotations are removed')
annotation_options.add_argument(
'--no-remove-annotations',
action='store_false',
help='Disable removing all annotations',
dest='remove_annotations',
)
annotation_options.add_argument(
'--no-remove-variable-annotations',
action='store_false',
help='Disable removing variable annotations',
dest='remove_variable_annotations',
)
annotation_options.add_argument(
'--no-remove-return-annotations',
action='store_false',
help='Disable removing function return annotations',
dest='remove_return_annotations',
)
annotation_options.add_argument(
'--no-remove-argument-annotations',
action='store_false',
help='Disable removing function argument annotations',
dest='remove_argument_annotations',
)
annotation_options.add_argument(
'--remove-class-attribute-annotations',
action='store_true',
help='Enable removing class attribute annotations',
dest='remove_class_attribute_annotations',
)
platform_options = parser.add_argument_group('remove unused platform options', 'Options that affect platform removal')
platform_options.add_argument(
'--remove-unused-platforms',
action='store_true',
help='Remove code blocks that are masked out for a specific platform',
dest='remove_unused_platforms',
)
platform_options.add_argument(
'--platform-test-key',
type=str,
default="_PLATFORM",
help='The variable name that is testing for a platform',
dest='platform_test_key',
)
platform_options.add_argument(
'--platform-preserve-value',
type=str,
default="linux",
help='The value that matches the target platform',
dest='platform_preserve_value',
)
parser.add_argument('--version', '-v', action='version', version=version)
args = parser.parse_args()
# Handle some invalid argument combinations
if '-' in args.path and len(args.path) != 1:
sys.stderr.write('error: multiple path arguments, reading from stdin not allowed\n')
sys.exit(1)
if '-' in args.path and args.in_place:
sys.stderr.write('error: reading from stdin, --in-place is not valid\n')
sys.exit(1)
if len(args.path) > 1 and not args.in_place:
sys.stderr.write('error: multiple path arguments, --in-place required\n')
sys.exit(1)
if len(args.path) == 1 and os.path.isdir(args.path[0]) and not args.in_place:
sys.stderr.write('error: path ' + args.path[0] + ' is a directory, --in-place required\n')
sys.exit(1)
if args.remove_class_attribute_annotations and not args.remove_annotations:
sys.stderr.write('error: --remove-class-attribute-annotations would do nothing when used with --no-remove-annotations\n')
sys.exit(1)
return args
def source_modules(args):
def error(os_error):
raise os_error
for path_arg in args.path:
if os.path.isdir(path_arg):
for root, dirs, files in os.walk(path_arg, onerror=error, followlinks=True):
for file in files:
if file.endswith('.py') or file.endswith('.pyw'):
yield os.path.join(root, file)
else:
yield path_arg
def do_minify(source, filename, minification_args):
preserve_globals = []
if minification_args.preserve_globals:
for arg in minification_args.preserve_globals:
names = [name.strip() for name in arg.split(',') if name]
preserve_globals.extend(names)
preserve_locals = []
if minification_args.preserve_locals:
for arg in minification_args.preserve_locals:
names = [name.strip() for name in arg.split(',') if name]
preserve_locals.extend(names)
if minification_args.remove_annotations is False:
remove_annotations = RemoveAnnotationsOptions(
remove_variable_annotations=False,
remove_return_annotations=False,
remove_argument_annotations=False,
remove_class_attribute_annotations=False,
)
else:
remove_annotations = RemoveAnnotationsOptions(
remove_variable_annotations=minification_args.remove_variable_annotations,
remove_return_annotations=minification_args.remove_return_annotations,
remove_argument_annotations=minification_args.remove_argument_annotations,
remove_class_attribute_annotations=minification_args.remove_class_attribute_annotations,
)
if minification_args.remove_unused_platforms is False:
remove_unused_platforms = RemoveUnusedPlatformOptions(
platform_test_key="",
platform_preserve_value=""
)
else:
remove_unused_platforms = RemoveUnusedPlatformOptions(
platform_test_key=minification_args.platform_test_key,
platform_preserve_value=minification_args.platform_preserve_value
)
return minify(
source,
filename=filename,
combine_imports=minification_args.combine_imports,
remove_pass=minification_args.remove_pass,
remove_annotations=remove_annotations,
remove_literal_statements=minification_args.remove_literal_statements,
hoist_literals=minification_args.hoist_literals,
rename_locals=minification_args.rename_locals,
preserve_locals=preserve_locals,
rename_globals=minification_args.rename_globals,
preserve_globals=preserve_globals,
remove_object_base=minification_args.remove_object_base,
convert_posargs_to_args=minification_args.convert_posargs_to_args,
preserve_shebang=minification_args.preserve_shebang,
remove_asserts=minification_args.remove_asserts,
remove_debug=minification_args.remove_debug,
remove_explicit_return_none=minification_args.remove_explicit_return_none,
remove_builtin_exception_brackets=minification_args.remove_exception_brackets,
constant_folding=minification_args.constant_folding,
remove_unused_platforms=remove_unused_platforms
)
if __name__ == '__main__':
main()