python-minifier 2.11.2__py2-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- python_minifier/__init__.py +269 -0
- python_minifier/__init__.pyi +37 -0
- python_minifier/__main__.py +332 -0
- python_minifier/ast_compare.py +104 -0
- python_minifier/ast_compat.py +40 -0
- python_minifier/ast_printer.py +130 -0
- python_minifier/expression_printer.py +753 -0
- python_minifier/f_string.py +446 -0
- python_minifier/ministring.py +179 -0
- python_minifier/module_printer.py +862 -0
- python_minifier/py.typed +0 -0
- python_minifier/rename/__init__.py +6 -0
- python_minifier/rename/bind_names.py +192 -0
- python_minifier/rename/binding.py +495 -0
- python_minifier/rename/mapper.py +175 -0
- python_minifier/rename/name_generator.py +51 -0
- python_minifier/rename/rename_literals.py +249 -0
- python_minifier/rename/renamer.py +230 -0
- python_minifier/rename/resolve_names.py +106 -0
- python_minifier/rename/util.py +203 -0
- python_minifier/token_printer.py +299 -0
- python_minifier/transforms/__init__.py +0 -0
- python_minifier/transforms/combine_imports.py +76 -0
- python_minifier/transforms/constant_folding.py +114 -0
- python_minifier/transforms/remove_annotations.py +130 -0
- python_minifier/transforms/remove_annotations_options.py +35 -0
- python_minifier/transforms/remove_annotations_options.pyi +17 -0
- python_minifier/transforms/remove_asserts.py +26 -0
- python_minifier/transforms/remove_debug.py +53 -0
- python_minifier/transforms/remove_exception_brackets.py +124 -0
- python_minifier/transforms/remove_explicit_return_none.py +38 -0
- python_minifier/transforms/remove_literal_statements.py +61 -0
- python_minifier/transforms/remove_object_base.py +24 -0
- python_minifier/transforms/remove_pass.py +26 -0
- python_minifier/transforms/remove_posargs.py +13 -0
- python_minifier/transforms/suite_transformer.py +196 -0
- python_minifier/util.py +48 -0
- python_minifier-2.11.2.dist-info/LICENSE +21 -0
- python_minifier-2.11.2.dist-info/METADATA +177 -0
- python_minifier-2.11.2.dist-info/RECORD +44 -0
- python_minifier-2.11.2.dist-info/WHEEL +5 -0
- python_minifier-2.11.2.dist-info/entry_points.txt +3 -0
- python_minifier-2.11.2.dist-info/top_level.txt +1 -0
- python_minifier-2.11.2.dist-info/zip-safe +1 -0
|
@@ -0,0 +1,446 @@
|
|
|
1
|
+
"""
|
|
2
|
+
FString unparsing
|
|
3
|
+
|
|
4
|
+
This whole module feels like a hack.
|
|
5
|
+
Mostly because FStrings feel like a hack.
|
|
6
|
+
|
|
7
|
+
"""
|
|
8
|
+
|
|
9
|
+
import python_minifier.ast_compat as ast
|
|
10
|
+
import copy
|
|
11
|
+
import re
|
|
12
|
+
|
|
13
|
+
from python_minifier import UnstableMinification
|
|
14
|
+
from python_minifier.ast_compare import CompareError
|
|
15
|
+
from python_minifier.ast_compare import compare_ast
|
|
16
|
+
from python_minifier.expression_printer import ExpressionPrinter
|
|
17
|
+
from python_minifier.ministring import MiniString
|
|
18
|
+
from python_minifier.token_printer import TokenTypes
|
|
19
|
+
from python_minifier.util import is_ast_node
|
|
20
|
+
|
|
21
|
+
|
|
22
|
+
class FString(object):
|
|
23
|
+
"""
|
|
24
|
+
An F-string in the expression part of another f-string
|
|
25
|
+
"""
|
|
26
|
+
|
|
27
|
+
def __init__(self, node, allowed_quotes, pep701):
|
|
28
|
+
assert isinstance(node, ast.JoinedStr)
|
|
29
|
+
|
|
30
|
+
self.node = node
|
|
31
|
+
self.allowed_quotes = allowed_quotes
|
|
32
|
+
self.pep701 = pep701
|
|
33
|
+
|
|
34
|
+
def is_correct_ast(self, code):
|
|
35
|
+
try:
|
|
36
|
+
c = ast.parse(code, 'FString candidate', mode='eval')
|
|
37
|
+
compare_ast(self.node, c.body)
|
|
38
|
+
return True
|
|
39
|
+
except Exception as e:
|
|
40
|
+
return False
|
|
41
|
+
|
|
42
|
+
def complete_debug_specifier(self, partial_specifier_candidates, value_node):
|
|
43
|
+
assert isinstance(value_node, ast.FormattedValue)
|
|
44
|
+
|
|
45
|
+
conversion = ''
|
|
46
|
+
if value_node.conversion == 115:
|
|
47
|
+
conversion = '!s'
|
|
48
|
+
elif value_node.conversion == 114 and value_node.format_spec is not None:
|
|
49
|
+
# This is the default for debug specifiers, unless there's a format_spec
|
|
50
|
+
conversion = '!r'
|
|
51
|
+
elif value_node.conversion == 97:
|
|
52
|
+
conversion = '!a'
|
|
53
|
+
|
|
54
|
+
conversion_candidates = [x + conversion for x in partial_specifier_candidates]
|
|
55
|
+
|
|
56
|
+
if value_node.format_spec is not None:
|
|
57
|
+
conversion_candidates = [c + ':' + fs for c in conversion_candidates for fs in FormatSpec(value_node.format_spec, self.allowed_quotes, self.pep701).candidates()]
|
|
58
|
+
|
|
59
|
+
return [x + '}' for x in conversion_candidates]
|
|
60
|
+
|
|
61
|
+
def candidates(self):
|
|
62
|
+
actual_candidates = []
|
|
63
|
+
|
|
64
|
+
for quote in self.allowed_quotes:
|
|
65
|
+
candidates = ['']
|
|
66
|
+
debug_specifier_candidates = []
|
|
67
|
+
nested_allowed = copy.copy(self.allowed_quotes)
|
|
68
|
+
|
|
69
|
+
if not self.pep701:
|
|
70
|
+
nested_allowed.remove(quote)
|
|
71
|
+
|
|
72
|
+
for v in self.node.values:
|
|
73
|
+
if is_ast_node(v, ast.Str):
|
|
74
|
+
|
|
75
|
+
# Could this be used as a debug specifier?
|
|
76
|
+
if len(candidates) < 10:
|
|
77
|
+
debug_specifier = re.match(r'.*=\s*$', v.s)
|
|
78
|
+
if debug_specifier:
|
|
79
|
+
# Maybe!
|
|
80
|
+
try:
|
|
81
|
+
debug_specifier_candidates = [x + '{' + v.s for x in candidates]
|
|
82
|
+
except Exception as e:
|
|
83
|
+
continue
|
|
84
|
+
|
|
85
|
+
try:
|
|
86
|
+
candidates = [x + self.str_for(v.s, quote) for x in candidates]
|
|
87
|
+
except Exception as e:
|
|
88
|
+
continue
|
|
89
|
+
elif isinstance(v, ast.FormattedValue):
|
|
90
|
+
try:
|
|
91
|
+
completed = self.complete_debug_specifier(debug_specifier_candidates, v)
|
|
92
|
+
candidates = [
|
|
93
|
+
x + y for x in candidates for y in FormattedValue(v, nested_allowed, self.pep701).get_candidates()
|
|
94
|
+
] + completed
|
|
95
|
+
debug_specifier_candidates = []
|
|
96
|
+
except Exception as e:
|
|
97
|
+
continue
|
|
98
|
+
else:
|
|
99
|
+
raise RuntimeError('Unexpected JoinedStr value')
|
|
100
|
+
|
|
101
|
+
actual_candidates += ['f' + quote + x + quote for x in candidates]
|
|
102
|
+
|
|
103
|
+
actual_candidates = filter(self.is_correct_ast, actual_candidates)
|
|
104
|
+
return actual_candidates
|
|
105
|
+
|
|
106
|
+
def str_for(self, s, quote):
|
|
107
|
+
return s.replace('{', '{{').replace('}', '}}')
|
|
108
|
+
|
|
109
|
+
|
|
110
|
+
class OuterFString(FString):
|
|
111
|
+
"""
|
|
112
|
+
The outermost f-string
|
|
113
|
+
|
|
114
|
+
Whereas the FString object assumes backslashes are disallowed, this
|
|
115
|
+
OuterFString is free to use backslashes in the Str parts
|
|
116
|
+
"""
|
|
117
|
+
|
|
118
|
+
def __init__(self, node, pep701=False):
|
|
119
|
+
assert isinstance(node, ast.JoinedStr)
|
|
120
|
+
super(OuterFString, self).__init__(node, ['"', "'", '"""', "'''"], pep701=pep701)
|
|
121
|
+
|
|
122
|
+
def __str__(self):
|
|
123
|
+
if len(self.node.values) == 0:
|
|
124
|
+
return 'f' + min(self.allowed_quotes, key=len) * 2
|
|
125
|
+
|
|
126
|
+
candidates = list(self.candidates())
|
|
127
|
+
|
|
128
|
+
for candidate in candidates:
|
|
129
|
+
|
|
130
|
+
try:
|
|
131
|
+
minified_f_string = ast.parse(candidate, 'python_minifier.f_string output', mode='eval').body
|
|
132
|
+
except SyntaxError as syntax_error:
|
|
133
|
+
raise UnstableMinification(syntax_error, '', candidate)
|
|
134
|
+
|
|
135
|
+
try:
|
|
136
|
+
compare_ast(self.node, minified_f_string)
|
|
137
|
+
except CompareError as compare_error:
|
|
138
|
+
raise UnstableMinification(compare_error, '', candidate)
|
|
139
|
+
|
|
140
|
+
if not candidates:
|
|
141
|
+
raise ValueError('Unable to create representation for f-string')
|
|
142
|
+
|
|
143
|
+
return min(candidates, key=len)
|
|
144
|
+
|
|
145
|
+
def str_for(self, s, quote):
|
|
146
|
+
mini_s = str(MiniString(s, quote)).replace('{', '{{').replace('}', '}}')
|
|
147
|
+
|
|
148
|
+
if mini_s == '':
|
|
149
|
+
return '\\\n'
|
|
150
|
+
return mini_s
|
|
151
|
+
|
|
152
|
+
|
|
153
|
+
class FormattedValue(ExpressionPrinter):
|
|
154
|
+
"""
|
|
155
|
+
An F-String Expression Part
|
|
156
|
+
"""
|
|
157
|
+
|
|
158
|
+
def __init__(self, node, allowed_quotes, pep701):
|
|
159
|
+
super(FormattedValue, self).__init__()
|
|
160
|
+
|
|
161
|
+
assert isinstance(node, ast.FormattedValue)
|
|
162
|
+
self.node = node
|
|
163
|
+
self.allowed_quotes = allowed_quotes
|
|
164
|
+
self.pep701 = pep701
|
|
165
|
+
self.candidates = ['']
|
|
166
|
+
|
|
167
|
+
def get_candidates(self):
|
|
168
|
+
|
|
169
|
+
self.printer.delimiter('{')
|
|
170
|
+
|
|
171
|
+
if self.is_curly(self.node.value):
|
|
172
|
+
self.printer.delimiter(' ')
|
|
173
|
+
|
|
174
|
+
self._expression(self.node.value)
|
|
175
|
+
|
|
176
|
+
if self.node.conversion == 115:
|
|
177
|
+
self.printer.append('!s', TokenTypes.Delimiter)
|
|
178
|
+
elif self.node.conversion == 114:
|
|
179
|
+
self.printer.append('!r', TokenTypes.Delimiter)
|
|
180
|
+
elif self.node.conversion == 97:
|
|
181
|
+
self.printer.append('!a', TokenTypes.Delimiter)
|
|
182
|
+
|
|
183
|
+
if self.node.format_spec is not None:
|
|
184
|
+
self.printer.delimiter(':')
|
|
185
|
+
self._append(FormatSpec(self.node.format_spec, self.allowed_quotes, pep701=self.pep701).candidates())
|
|
186
|
+
|
|
187
|
+
self.printer.delimiter('}')
|
|
188
|
+
|
|
189
|
+
self._finalize()
|
|
190
|
+
return self.candidates
|
|
191
|
+
|
|
192
|
+
def is_curly(self, node):
|
|
193
|
+
if isinstance(node, (ast.SetComp, ast.DictComp, ast.Set, ast.Dict)):
|
|
194
|
+
return True
|
|
195
|
+
|
|
196
|
+
if isinstance(node, (ast.Expr, ast.Attribute, ast.Subscript)):
|
|
197
|
+
return self.is_curly(node.value)
|
|
198
|
+
|
|
199
|
+
if isinstance(node, (ast.Compare, ast.BinOp)):
|
|
200
|
+
return self.is_curly(node.left)
|
|
201
|
+
|
|
202
|
+
if isinstance(node, ast.Call):
|
|
203
|
+
return self.is_curly(node.func)
|
|
204
|
+
|
|
205
|
+
if isinstance(node, ast.BoolOp):
|
|
206
|
+
return self.is_curly(node.values[0])
|
|
207
|
+
|
|
208
|
+
if isinstance(node, ast.IfExp):
|
|
209
|
+
return self.is_curly(node.body)
|
|
210
|
+
|
|
211
|
+
return False
|
|
212
|
+
|
|
213
|
+
def visit_Str(self, node):
|
|
214
|
+
self.printer.append(str(Str(node.s, self.allowed_quotes, self.pep701)), TokenTypes.NonNumberLiteral)
|
|
215
|
+
|
|
216
|
+
def visit_Bytes(self, node):
|
|
217
|
+
self.printer.append(str(Bytes(node.s, self.allowed_quotes)), TokenTypes.NonNumberLiteral)
|
|
218
|
+
|
|
219
|
+
def visit_JoinedStr(self, node):
|
|
220
|
+
assert isinstance(node, ast.JoinedStr)
|
|
221
|
+
if self.printer.previous_token in [TokenTypes.Identifier, TokenTypes.Keyword, TokenTypes.SoftKeyword]:
|
|
222
|
+
self.printer.delimiter(' ')
|
|
223
|
+
self._append(FString(node, allowed_quotes=self.allowed_quotes, pep701=self.pep701).candidates())
|
|
224
|
+
|
|
225
|
+
def visit_Lambda(self, node):
|
|
226
|
+
self.printer.delimiter('(')
|
|
227
|
+
super().visit_Lambda(node)
|
|
228
|
+
self.printer.delimiter(')')
|
|
229
|
+
|
|
230
|
+
def _finalize(self):
|
|
231
|
+
self.candidates = [x + str(self.printer) for x in self.candidates]
|
|
232
|
+
self.printer._code = ''
|
|
233
|
+
|
|
234
|
+
def _append(self, candidates):
|
|
235
|
+
self._finalize()
|
|
236
|
+
self.candidates = [x + y for x in self.candidates for y in candidates]
|
|
237
|
+
|
|
238
|
+
|
|
239
|
+
class Str(object):
|
|
240
|
+
"""
|
|
241
|
+
A Str node inside an f-string expression
|
|
242
|
+
|
|
243
|
+
May use any of the allowed quotes. In Python <3.12, backslashes are not allowed.
|
|
244
|
+
|
|
245
|
+
"""
|
|
246
|
+
|
|
247
|
+
def __init__(self, s, allowed_quotes, pep701=False):
|
|
248
|
+
self._s = s
|
|
249
|
+
self.allowed_quotes = allowed_quotes
|
|
250
|
+
self.current_quote = None
|
|
251
|
+
self.pep701 = pep701
|
|
252
|
+
|
|
253
|
+
def _can_quote(self, c):
|
|
254
|
+
if self.current_quote is None:
|
|
255
|
+
return False
|
|
256
|
+
|
|
257
|
+
if (c == '\n' or c == '\r') and len(self.current_quote) == 1 and not self.pep701:
|
|
258
|
+
return False
|
|
259
|
+
|
|
260
|
+
if c == self.current_quote[0]:
|
|
261
|
+
return False
|
|
262
|
+
|
|
263
|
+
return True
|
|
264
|
+
|
|
265
|
+
def _get_quote(self, c):
|
|
266
|
+
for quote in self.allowed_quotes:
|
|
267
|
+
if not self.pep701 and (c == '\n' or c == '\r'):
|
|
268
|
+
if len(quote) == 3:
|
|
269
|
+
return quote
|
|
270
|
+
elif c != quote:
|
|
271
|
+
return quote
|
|
272
|
+
|
|
273
|
+
raise ValueError('Couldn\'t find a quote')
|
|
274
|
+
|
|
275
|
+
def _literals(self):
|
|
276
|
+
l = ''
|
|
277
|
+
for c in self._s:
|
|
278
|
+
if not self._can_quote(c):
|
|
279
|
+
if l:
|
|
280
|
+
l += self.current_quote
|
|
281
|
+
yield l
|
|
282
|
+
l = ''
|
|
283
|
+
|
|
284
|
+
self.current_quote = self._get_quote(c)
|
|
285
|
+
|
|
286
|
+
if l == '':
|
|
287
|
+
l += self.current_quote
|
|
288
|
+
|
|
289
|
+
if c == '\n':
|
|
290
|
+
l += '\\n'
|
|
291
|
+
elif c == '\r':
|
|
292
|
+
l += '\\r'
|
|
293
|
+
elif c == '\\':
|
|
294
|
+
l += '\\\\'
|
|
295
|
+
else:
|
|
296
|
+
l += c
|
|
297
|
+
|
|
298
|
+
if l:
|
|
299
|
+
l += self.current_quote
|
|
300
|
+
yield l
|
|
301
|
+
|
|
302
|
+
def __str__(self):
|
|
303
|
+
if self._s == '':
|
|
304
|
+
return str(min(self.allowed_quotes, key=len)) * 2
|
|
305
|
+
|
|
306
|
+
if '\0' in self._s or ('\\' in self._s and not self.pep701):
|
|
307
|
+
raise ValueError('Impossible to represent a character in f-string expression part')
|
|
308
|
+
|
|
309
|
+
if not self.pep701 and ('\n' in self._s or '\r' in self._s):
|
|
310
|
+
if '"""' not in self.allowed_quotes and "'''" not in self.allowed_quotes:
|
|
311
|
+
raise ValueError(
|
|
312
|
+
'Impossible to represent newline character in f-string expression part without a long quote'
|
|
313
|
+
)
|
|
314
|
+
|
|
315
|
+
candidates = []
|
|
316
|
+
for start_quote in self.allowed_quotes:
|
|
317
|
+
self.current_quote = start_quote
|
|
318
|
+
s = ''
|
|
319
|
+
for l in self._literals():
|
|
320
|
+
if s and s[-1] == l[0]:
|
|
321
|
+
s += ' '
|
|
322
|
+
s += l
|
|
323
|
+
|
|
324
|
+
if eval(s) == self._s:
|
|
325
|
+
candidates.append(s)
|
|
326
|
+
|
|
327
|
+
if candidates:
|
|
328
|
+
return min(candidates, key=len)
|
|
329
|
+
else:
|
|
330
|
+
raise ValueError('Unable to string')
|
|
331
|
+
|
|
332
|
+
|
|
333
|
+
class FormatSpec(object):
|
|
334
|
+
"""
|
|
335
|
+
A FormattedValue format spec
|
|
336
|
+
|
|
337
|
+
The AST looks like another f-string. This time there are no quotes.
|
|
338
|
+
|
|
339
|
+
"""
|
|
340
|
+
|
|
341
|
+
def __init__(self, node, allowed_quotes, pep701):
|
|
342
|
+
assert isinstance(node, ast.JoinedStr)
|
|
343
|
+
|
|
344
|
+
self.node = node
|
|
345
|
+
self.allowed_quotes = allowed_quotes
|
|
346
|
+
self.pep701 = pep701
|
|
347
|
+
|
|
348
|
+
def candidates(self):
|
|
349
|
+
|
|
350
|
+
candidates = ['']
|
|
351
|
+
for v in self.node.values:
|
|
352
|
+
if is_ast_node(v, ast.Str):
|
|
353
|
+
candidates = [x + self.str_for(v.s) for x in candidates]
|
|
354
|
+
elif isinstance(v, ast.FormattedValue):
|
|
355
|
+
candidates = [
|
|
356
|
+
x + y for x in candidates for y in FormattedValue(v, self.allowed_quotes, self.pep701).get_candidates()
|
|
357
|
+
]
|
|
358
|
+
else:
|
|
359
|
+
raise RuntimeError('Unexpected JoinedStr value')
|
|
360
|
+
|
|
361
|
+
return candidates
|
|
362
|
+
|
|
363
|
+
def str_for(self, s):
|
|
364
|
+
return s.replace('{', '{{').replace('}', '}}')
|
|
365
|
+
|
|
366
|
+
|
|
367
|
+
class Bytes(object):
|
|
368
|
+
"""
|
|
369
|
+
A Bytes node inside an f-string expression
|
|
370
|
+
|
|
371
|
+
May use any of the allowed quotes, no backslashes!
|
|
372
|
+
|
|
373
|
+
"""
|
|
374
|
+
|
|
375
|
+
def __init__(self, b, allowed_quotes):
|
|
376
|
+
self._b = b
|
|
377
|
+
self.allowed_quotes = allowed_quotes
|
|
378
|
+
self.current_quote = None
|
|
379
|
+
|
|
380
|
+
def _can_quote(self, c):
|
|
381
|
+
if self.current_quote is None:
|
|
382
|
+
return False
|
|
383
|
+
|
|
384
|
+
if (c == ord(b'\n') or c == ord(b'\r')) and len(self.current_quote) == 1:
|
|
385
|
+
return False
|
|
386
|
+
|
|
387
|
+
if chr(c) == self.current_quote[0]:
|
|
388
|
+
return False
|
|
389
|
+
|
|
390
|
+
return True
|
|
391
|
+
|
|
392
|
+
def _get_quote(self, c):
|
|
393
|
+
for quote in self.allowed_quotes:
|
|
394
|
+
if c == ord(b'\n') or c == ord(b'\r'):
|
|
395
|
+
if len(quote) == 3:
|
|
396
|
+
return quote
|
|
397
|
+
elif chr(c) != quote:
|
|
398
|
+
return quote
|
|
399
|
+
|
|
400
|
+
raise ValueError('Couldn\'t find a quote')
|
|
401
|
+
|
|
402
|
+
def _literals(self):
|
|
403
|
+
l = ''
|
|
404
|
+
for b in self._b:
|
|
405
|
+
if not self._can_quote(b):
|
|
406
|
+
if l:
|
|
407
|
+
l += self.current_quote
|
|
408
|
+
yield l
|
|
409
|
+
l = ''
|
|
410
|
+
|
|
411
|
+
self.current_quote = self._get_quote(b)
|
|
412
|
+
|
|
413
|
+
if l == '':
|
|
414
|
+
l = 'b' + self.current_quote
|
|
415
|
+
l += chr(b)
|
|
416
|
+
|
|
417
|
+
if l:
|
|
418
|
+
l += self.current_quote
|
|
419
|
+
yield l
|
|
420
|
+
|
|
421
|
+
def __str__(self):
|
|
422
|
+
if self._b == b'':
|
|
423
|
+
return 'b' + str(min(self.allowed_quotes, key=len)) * 2
|
|
424
|
+
|
|
425
|
+
if b'\0' in self._b or b'\\' in self._b:
|
|
426
|
+
raise ValueError('Impossible to represent a %r character in f-string expression part')
|
|
427
|
+
|
|
428
|
+
if b'\n' in self._b or b'\r' in self._b:
|
|
429
|
+
if '"""' not in self.allowed_quotes and "'''" not in self.allowed_quotes:
|
|
430
|
+
raise ValueError(
|
|
431
|
+
'Impossible to represent newline character in f-string expression part without a long quote'
|
|
432
|
+
)
|
|
433
|
+
|
|
434
|
+
candidates = []
|
|
435
|
+
for start_quote in self.allowed_quotes:
|
|
436
|
+
self.current_quote = start_quote
|
|
437
|
+
s = ''
|
|
438
|
+
for l in self._literals():
|
|
439
|
+
if s and s[-1] == l[0]:
|
|
440
|
+
s += ' '
|
|
441
|
+
s += l
|
|
442
|
+
|
|
443
|
+
assert eval(s) == self._b
|
|
444
|
+
candidates.append(s)
|
|
445
|
+
|
|
446
|
+
return min(candidates, key=len)
|
|
@@ -0,0 +1,179 @@
|
|
|
1
|
+
BACKSLASH = '\\'
|
|
2
|
+
|
|
3
|
+
|
|
4
|
+
class MiniString(object):
|
|
5
|
+
"""
|
|
6
|
+
Create a representation of a string object
|
|
7
|
+
|
|
8
|
+
:param str string: The string to minify
|
|
9
|
+
|
|
10
|
+
"""
|
|
11
|
+
|
|
12
|
+
def __init__(self, string, quote="'"):
|
|
13
|
+
self._s = string
|
|
14
|
+
self.safe_mode = False
|
|
15
|
+
self.quote = quote
|
|
16
|
+
|
|
17
|
+
def __str__(self):
|
|
18
|
+
"""
|
|
19
|
+
The smallest python literal representation of a string
|
|
20
|
+
|
|
21
|
+
:rtype: str
|
|
22
|
+
|
|
23
|
+
"""
|
|
24
|
+
|
|
25
|
+
if self._s == '':
|
|
26
|
+
return ''
|
|
27
|
+
|
|
28
|
+
if len(self.quote) == 1:
|
|
29
|
+
s = self.to_short()
|
|
30
|
+
else:
|
|
31
|
+
s = self.to_long()
|
|
32
|
+
|
|
33
|
+
try:
|
|
34
|
+
eval(self.quote + s + self.quote)
|
|
35
|
+
except (UnicodeDecodeError, UnicodeEncodeError) as e:
|
|
36
|
+
if self.safe_mode:
|
|
37
|
+
raise
|
|
38
|
+
|
|
39
|
+
self.safe_mode = True
|
|
40
|
+
if len(self.quote) == 1:
|
|
41
|
+
s = self.to_short()
|
|
42
|
+
else:
|
|
43
|
+
s = self.to_long()
|
|
44
|
+
|
|
45
|
+
assert eval(self.quote + s + self.quote) == self._s
|
|
46
|
+
|
|
47
|
+
return s
|
|
48
|
+
|
|
49
|
+
def to_short(self):
|
|
50
|
+
s = ''
|
|
51
|
+
|
|
52
|
+
escaped = {
|
|
53
|
+
'\n': BACKSLASH + 'n',
|
|
54
|
+
'\\': BACKSLASH + BACKSLASH,
|
|
55
|
+
'\a': BACKSLASH + 'a',
|
|
56
|
+
'\b': BACKSLASH + 'b',
|
|
57
|
+
'\f': BACKSLASH + 'f',
|
|
58
|
+
'\r': BACKSLASH + 'r',
|
|
59
|
+
'\t': BACKSLASH + 't',
|
|
60
|
+
'\v': BACKSLASH + 'v',
|
|
61
|
+
'\0': BACKSLASH + 'x00',
|
|
62
|
+
self.quote: BACKSLASH + self.quote,
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
for c in self._s:
|
|
66
|
+
if c in escaped.keys():
|
|
67
|
+
s += escaped[c]
|
|
68
|
+
else:
|
|
69
|
+
if self.safe_mode:
|
|
70
|
+
unicode_value = ord(c)
|
|
71
|
+
if unicode_value <= 0x7F:
|
|
72
|
+
s += c
|
|
73
|
+
elif unicode_value <= 0xFFFF:
|
|
74
|
+
s += BACKSLASH + 'u' + format(unicode_value, '04x')
|
|
75
|
+
else:
|
|
76
|
+
s += BACKSLASH + 'U' + format(unicode_value, '08x')
|
|
77
|
+
else:
|
|
78
|
+
s += c
|
|
79
|
+
|
|
80
|
+
return s
|
|
81
|
+
|
|
82
|
+
def to_long(self):
|
|
83
|
+
s = ''
|
|
84
|
+
|
|
85
|
+
escaped = {
|
|
86
|
+
'\\': BACKSLASH + BACKSLASH,
|
|
87
|
+
'\a': BACKSLASH + 'a',
|
|
88
|
+
'\b': BACKSLASH + 'b',
|
|
89
|
+
'\f': BACKSLASH + 'f',
|
|
90
|
+
'\r': BACKSLASH + 'r',
|
|
91
|
+
'\t': BACKSLASH + 't',
|
|
92
|
+
'\v': BACKSLASH + 'v',
|
|
93
|
+
'\0': BACKSLASH + 'x00',
|
|
94
|
+
self.quote[0]: BACKSLASH + self.quote[0],
|
|
95
|
+
}
|
|
96
|
+
|
|
97
|
+
for c in self._s:
|
|
98
|
+
if c in escaped.keys():
|
|
99
|
+
s += escaped[c]
|
|
100
|
+
else:
|
|
101
|
+
if self.safe_mode:
|
|
102
|
+
unicode_value = ord(c)
|
|
103
|
+
if unicode_value <= 0x7F:
|
|
104
|
+
s += c
|
|
105
|
+
elif unicode_value <= 0xFFFF:
|
|
106
|
+
s += BACKSLASH + 'u' + format(unicode_value, '04x')
|
|
107
|
+
else:
|
|
108
|
+
s += BACKSLASH + 'U' + format(unicode_value, '08x')
|
|
109
|
+
else:
|
|
110
|
+
s += c
|
|
111
|
+
|
|
112
|
+
return s
|
|
113
|
+
|
|
114
|
+
|
|
115
|
+
class MiniBytes(object):
|
|
116
|
+
"""
|
|
117
|
+
Create a representation of a bytes object
|
|
118
|
+
|
|
119
|
+
:param bytes string: The string to minify
|
|
120
|
+
|
|
121
|
+
"""
|
|
122
|
+
|
|
123
|
+
def __init__(self, string, quote="'"):
|
|
124
|
+
self._b = string
|
|
125
|
+
self.quote = quote
|
|
126
|
+
|
|
127
|
+
def __str__(self):
|
|
128
|
+
"""
|
|
129
|
+
The smallest python literal representation of a string
|
|
130
|
+
|
|
131
|
+
:rtype: str
|
|
132
|
+
|
|
133
|
+
"""
|
|
134
|
+
|
|
135
|
+
if self._b == b'':
|
|
136
|
+
return ''
|
|
137
|
+
|
|
138
|
+
if len(self.quote) == 1:
|
|
139
|
+
s = self.to_short()
|
|
140
|
+
else:
|
|
141
|
+
s = self.to_long()
|
|
142
|
+
|
|
143
|
+
assert eval('b' + self.quote + s + self.quote) == self._b
|
|
144
|
+
|
|
145
|
+
return s
|
|
146
|
+
|
|
147
|
+
def to_short(self):
|
|
148
|
+
b = ''
|
|
149
|
+
|
|
150
|
+
for c in self._b:
|
|
151
|
+
if c == b'\\':
|
|
152
|
+
b += BACKSLASH
|
|
153
|
+
elif c == b'\n':
|
|
154
|
+
b += BACKSLASH + 'n'
|
|
155
|
+
elif c == self.quote:
|
|
156
|
+
b += BACKSLASH + self.quote
|
|
157
|
+
else:
|
|
158
|
+
if c >= 128:
|
|
159
|
+
b += BACKSLASH + chr(c)
|
|
160
|
+
else:
|
|
161
|
+
b += chr(c)
|
|
162
|
+
|
|
163
|
+
return b
|
|
164
|
+
|
|
165
|
+
def to_long(self):
|
|
166
|
+
b = ''
|
|
167
|
+
|
|
168
|
+
for c in self._b:
|
|
169
|
+
if c == b'\\':
|
|
170
|
+
b += BACKSLASH
|
|
171
|
+
elif c == self.quote:
|
|
172
|
+
b += BACKSLASH + self.quote
|
|
173
|
+
else:
|
|
174
|
+
if c >= 128:
|
|
175
|
+
b += BACKSLASH + chr(c)
|
|
176
|
+
else:
|
|
177
|
+
b += chr(c)
|
|
178
|
+
|
|
179
|
+
return b
|