-
Notifications
You must be signed in to change notification settings - Fork 14
/
combine_py_files.py
190 lines (158 loc) · 6.49 KB
/
combine_py_files.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
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
import os.path
class burn_after_reading:
"""Return an empty list if already calculated."""
def __init__(self, f):
self.memo = set()
self.f = f
def __call__(self, *arg):
if arg in self.memo:
return []
else:
self.memo.add(arg) #Do this here to avoid infinite loops
val = self.f(*arg)
return val
#################
# Code snippets #
#################
fake_module_preamble_str = \
"""\
import sys
from types import ModuleType
class MockModule(ModuleType):
def __init__(self, module_name, module_doc=None):
ModuleType.__init__(self, module_name, module_doc)
if '.' in module_name:
package, module = module_name.rsplit('.', 1)
get_mock_module(package).__path__ = []
setattr(get_mock_module(package), module, self)
def _initialize_(self, module_code):
self.__dict__.update(module_code(self.__name__))
self.__doc__ = module_code.__doc__
def get_mock_module(module_name):
if module_name not in sys.modules:
sys.modules[module_name] = MockModule(module_name)
return sys.modules[module_name]
def modulize(module_name, dependencies=[]):
for d in dependencies: get_mock_module(d)
return get_mock_module(module_name)._initialize_
##===========================================================================##
"""
main_section_str = \
"""\n
def {short_name}():
##----- Begin {file} {padded_dashes_0}##
{text}
##----- End {file} {padded_dashes_1}##
{short_name}()
"""
package_section_str = \
"""
@modulize('{name}'{dependencies})
def _{short_name}(__name__):
##----- Begin {file} {padded_dashes_0}##
{text}
##----- End {file} {padded_dashes_1}##
return locals()
"""
module_section_str = \
"""
@modulize('{name}'{dependencies})
def _{short_name}(__name__):
##----- Begin {file} {padded_dashes_0}##
{text}
##----- End {file} {padded_dashes_1}##
return locals()
"""
def get_modules_from_import_line(line):
line = line.strip()
if line.startswith('import'):
# import module1 as x, module2 as y, ...
line = line[7:] # remove "import "
for import_str in line.split(","):
module = import_str.split()[0]
yield module
elif line.startswith('from'):
line = line[5:] # remove "from "
module, names = [s.strip() for s in line.split(" import ")]
yield module
for name in [n.strip() for n in names.split(",")]:
yield module + '.' + name # name is likely not a module, but it could be
#else: # not an import statement
@burn_after_reading
def parse_import_structure(package_dir, file='__main__.py'):
module_list = []
dependencies = set()
with open(package_dir + file, 'r') as f:
for line in f:
for module in get_modules_from_import_line(line):
module_prefix = []
for m in module.split('.'):
module_prefix += [m]
path_prefix = "/".join(module_prefix)
if os.path.isfile(package_dir + path_prefix + '.py'):
module_list += parse_import_structure(package_dir, path_prefix + '.py')
dependencies.add(".".join(module_prefix))
elif os.path.isfile(package_dir + path_prefix + '/__init__.py'):
module_list += parse_import_structure(package_dir, path_prefix + '/__init__.py')
dependencies.add(".".join(module_prefix))
return module_list + [(file, dependencies)]
def file_to_module(file, main_file='__main__.py'):
if file == main_file:
module_type = 'main'
name = file.replace('.py','').replace('/','.')
elif file.endswith('__init__.py'):
module_type = 'package'
name = file.replace('/__init__.py','').replace('/','.')
else:
module_type = 'module'
name = file.replace('.py','').replace('/','.')
return module_type, name
def block(file, module_type, module_name, text_block, dependencies):
short_name = module_name.split('.')[-1]
text = " " + "\n ".join(text_block.split('\n'))
if module_type == 'main':
return(main_section_str.format(short_name = short_name,
text=text,
file=file,
padded_dashes_0 = '-'*(63 - len(file)),
padded_dashes_1 = '-'*(65 - len(file))))
elif module_type in ('module', 'package'):
if dependencies:
dependency_text = ", dependencies=" + str(list(sorted(dependencies)))
else:
dependency_text = ''
return(module_section_str.format(short_name = short_name,
name = module_name,
file=file,
text=text,
dependencies = dependency_text,
padded_dashes_0 = '-'*(63 - len(file)),
padded_dashes_1 = '-'*(65 - len(file))))
def combine_into_one_file(package_dir, main_file='__main__.py', out='_combined.py', verbose=True):
module_list = parse_import_structure(package_dir, main_file)
visited = set()
with open(out, 'w') as combined:
combined.write(fake_module_preamble_str)
for file_name, dependencies in module_list:
if verbose:
print("...", file_name)
module_type, module_name = file_to_module(file_name)
visited.add(module_name)
remaining_dependencies = dependencies - visited
with open(package_dir + file_name, 'r') as f:
b = block(file_name, module_type, module_name, f.read(), remaining_dependencies)
combined.write(b)
if __name__ == '__main__':
import sys # replace with argparser
input_path = sys.argv[1] # entry file or directory
output_file = sys.argv[2]
if os.path.isfile(input_path):
start_dir, start_file = os.path.split(input_path)
combine_into_one_file(start_dir, start_file, out=output_file)
elif os.path.isdir(input_path):
start_dir = os.path.join(input_path, '') # puts in proper form with slash at end
combine_into_one_file(start_dir, out=output_file) # my_file = '__main__.py'
else:
print("Improper input file/dir.")
sys.exit(2)
print("Sucessfully combined files.")