-
-
Notifications
You must be signed in to change notification settings - Fork 52
Expand file tree
/
Copy pathremove_literal_statements.py
More file actions
72 lines (52 loc) · 1.92 KB
/
remove_literal_statements.py
File metadata and controls
72 lines (52 loc) · 1.92 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
import ast
from python_minifier.transforms.suite_transformer import SuiteTransformer
from python_minifier.util import is_ast_node
def find_doc(node):
if isinstance(node, ast.Attribute):
if node.attr == '__doc__':
raise ValueError('__doc__ found!')
for child in ast.iter_child_nodes(node):
find_doc(child)
def _doc_in_module(module):
try:
find_doc(module)
return False
except:
return True
class RemoveLiteralStatements(SuiteTransformer):
"""
Remove literal expressions from the code
This includes docstrings
"""
def __init__(self):
super().__init__()
self.doc_in_module = False
def __call__(self, node):
self.doc_in_module = _doc_in_module(node)
return self.visit(node)
def visit_Module(self, node):
for binding in node.bindings:
if binding.name == '__doc__':
node.body = [self.visit(a) for a in node.body]
return node
node.body = self.suite(node.body, parent=node)
return node
def is_literal_statement(self, node):
if not isinstance(node, ast.Expr):
return False
return is_ast_node(node.value, (ast.Num, ast.Str, 'NameConstant', 'Bytes'))
def suite(self, node_list, parent):
without_literals = []
for node in node_list:
if self.is_literal_statement(node):
if self.doc_in_module and is_ast_node(node.value, ast.Str):
node.value.value = 'doc-string stripped by python-minifier'
without_literals.append(node)
else:
without_literals.append(self.visit(node))
if len(without_literals) == 0:
if isinstance(parent, ast.Module):
return []
else:
return [self.add_child(ast.Expr(value=ast.Num(0)), parent=parent)]
return without_literals