-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcompile.py
executable file
·253 lines (205 loc) · 8.19 KB
/
compile.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
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
# Import required libraries
from distutils.core import setup
from distutils.extension import Extension
from Cython.Distutils import build_ext
import os
from pathlib import Path
import sys
import json
import traceback
# Get the version of Python being used
py_ver = sys.version.split('.')[0] + '.' + sys.version.split('.')[1]
print(f"Python version used to compile: {py_ver}")
# Ask user if they want to compile the app with Cython
run_compile = False
if input('Compile app with Cython? (y/n)').lower() == 'y':
run_compile = True
# Ask user if they want to make an executable binary from compiled files
build = False
do_build_app = input('Make an executable binary from compiled files? (y/n)')
if do_build_app.lower() == 'y':
build = True
# List available projects from the applications directory
# def list_from_json():
# instructions = False
# if os.path.isdir("applications"):
# if os.path.isfile("applications/config.json"):
# with open("applications/config.json") as appslist:
# res = json.load(appslist)
# return res
# else:
# instructions = True
# else:
# instructions = True
# os.mkdir('applications')
#
# if instructions:
# print("Missing config.json file in applications directory")
# print("Creating file now. Add app root folder to applications directory and edit config.json")
# mkconf = {"1": "appname", "2": "another_appname"}
# with open('applications/config.json', 'w') as conf:
# json.dump(mkconf, conf)
# return None
def list_from_applications():
apps_avail = {}
app_key = 1
appdir = './applications'
for item in os.listdir(appdir):
if os.path.isdir(os.path.join(appdir, item)):
if "." not in item:
apps_avail[str(app_key)] = item
app_key += 1
return apps_avail
# Create the cython_output directory if it doesn't already exist
if os.path.isdir("cython_output") is False:
os.mkdir("cython_output")
# Get the list of available projects
d_apps = list_from_applications()
print("Choose Project ID Number: ")
try:
# Print the available projects for the user to choose from
for k, v in d_apps.items():
print(f"{k}: ", v)
except Exception:
print(traceback.format_exc())
home = str(Path.home())
# Get the project name from the user
project_name = d_apps[str(input("Project ID: "))]
ext_modules = []
test_modules = []
if project_name in d_apps:
print(f"Project name: {project_name}")
# Prepare for building the app
def prep_build():
if os.path.isdir(f'{project_name}'):
os.system(f'rm -Rf {project_name}')
# os.mkdir(f'{project_name}')
os.system(f'cp -Rf applications/{project_name} ./')
os.system(f'rm {project_name}/main.py')
# move this file to parent
os.system('cp compile.py applications/compile_backup.py')
# remove old build
os.system(f'rm -Rf cython_output/{project_name}')
# Remove unnecessary files from the app release folder
def clean_release(cmd):
os.system(cmd)
# Get the name and path of the module to be built
def get_module_data(f, sub_level_dirs):
module_name = ''
pathstr = ''
if len(f) > 0:
if '.py' in f:
if 'compile.py' not in f:
file_name = f.split('.')[0]
if f'{project_name}.py' in f:
module_name = f"""{file_name}"""
else:
if len(sub_level_dirs[0].split('/')) > 2:
module_name = f"""{sub_level_dirs[0].split('/')[1]}.{sub_level_dirs[0].split('/')[2]}.{file_name}"""
else:
if len(sub_level_dirs[0].split('/')) > 1:
module_name = f"""{sub_level_dirs[0].split('/')[1]}.{file_name}"""
pathstr = f"""{sub_level_dirs[0]}/{f}"""
return [module_name, pathstr]
def build_modules():
top_level_dirs = [x[0] for x in os.walk(".") if 'pycache' not in x[0] and 'applications' not in x[0]]
for d in top_level_dirs:
sub_level_dirs = [xx[0] for xx in os.walk(d) if 'pycache' not in xx[0]]
for f1 in os.listdir(sub_level_dirs[0]):
moduledata = get_module_data(f1, sub_level_dirs)
if len(moduledata[0]) > 0:
ext_modules.append(Extension(moduledata[0], [moduledata[1]]))
test_modules.append([moduledata[0], [moduledata[1]]])
def build():
for e in ext_modules:
e.cython_directives = {'language_level': "3"}
setup(
name=f"{project_name}",
cmdclass={'build_ext': build_ext},
ext_modules=ext_modules
)
def cleanup(): # cleanup app release folder
appfile = ''
clean_release(f"find .{project_name} -name '*.py' ! -name 'compile.py' -exec rm -Rf {{}} + ")
clean_release(f"find .{project_name} -name '*__pycache__*' -exec rm -Rf {{}} + ")
clean_release(f"find .{project_name} -name '*.c' -exec rm -Rf {{}} + ")
dirs = [fz[0] for fz in os.walk(".")]
for d in dirs:
if os.path.isdir(d):
for file in os.listdir(d):
# print(fi)
if file != 'compile.py':
if '.so' in file:
print(file)
rename = file.split('.')[0] + '.so'
if f'{project_name}.so' == rename:
os.system(f'mv {file} {rename}')
appfile = rename
else:
os.system(f'mv {d}/{file} {d}/{rename}')
print("APPFILE---", appfile)
return appfile
def post_build():
appfile = cleanup()
print('appfile:', appfile)
if len(appfile) > 0:
os.system(f'mv {appfile} {project_name}/{appfile}')
mainpy = f"""# -*- coding: utf-8 -*- \nimport {project_name} \n{project_name}.run()"""
run_sh = f"""#!/bin/bash\npython{py_ver} main"""
with open(f'{project_name}/main', 'w+') as pyfile:
pyfile.write(mainpy)
with open(f'{project_name}/main.py', 'w+') as pyfile:
pyfile.write(mainpy)
with open(f'{project_name}/run.sh', 'w+') as shfile:
shfile.write(run_sh)
os.system(f'chmod +x {project_name}/main')
os.system(f'chmod +x {project_name}/run.sh')
os.system("rm -Rf build")
if os.path.isdir(f'cython_output/{project_name}'):
os.system(f"rm -Rf cython_output/{project_name}")
os.system(f"cp -Rf {project_name} cython_output/{project_name}")
os.system(f"rm -Rf {project_name}")
if run_compile:
# Prepare build
print("Starting...be patient.")
prep_build()
# Remove docs and git data
clean_release(f"rm -Rf {project_name}/docs")
clean_release(f"rm -rf {project_name}/.git {project_name}/.gitignore")
# rename main to {project_name}
os.system(f"cp applications/{project_name}/main.py {project_name}/{project_name}.py")
# Build project modules and paths
build_modules()
# build and compile
build()
# cleanup post build
post_build()
print(f"Done compiling {project_name}... cython program files are located in ./cython_output/{project_name}")
else:
print("Please specify project name as existing project and try again! Goodbye...")
if build:
if os.path.isdir("build"):
if os.path.isdir(f'build/{project_name}'):
os.system(f'rm -Rf build/{project_name}')
else:
os.system("mkdir build")
os.system(f"cp -Rf cython_output/{project_name} build/{project_name}")
print("Building...")
if os.path.isdir("dist"):
os.system(f'rm -Rf dist')
os.system("mkdir dist")
os.system(f"makeself/makeself.sh --nox11 --nocomp build/{project_name} dist/{project_name} '{project_name}' ./run.sh")
os.system(f"""rm -Rf build/output/{project_name}""")
if os.path.isdir("bin"):
if os.path.isfile(f"bin/{project_name}"):
os.system(f"rm -Rf bin/{project_name}")
else:
os.system("mkdir bin")
os.system(f"""cp dist/{project_name} bin/{project_name}""")
os.system(f"rm -Rf {project_name}")
os.system("""rm -Rf build""")
os.system("""rm -Rf dist""")
print('Finished building. Executable can be found in ./bin')
print("Goodbye...")
else:
print('Not building. Goodbye...')