forked from beeware/batavia
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcompile_stdlib.py
85 lines (68 loc) · 2.45 KB
/
compile_stdlib.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
#!/usr/bin/env python3
"""
Convert ouroboros modules to JavaScripted pyc files that we can load.
"""
# TODO: we should just import ourboros and generate the pycs from there
import argparse
import base64
import glob
import os
import os.path
import py_compile
import sys
import tempfile
def parse_args():
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument('modules', metavar='module', nargs='*',
help='source modules to compile')
parser.add_argument('--source', help='location of the ouroboros source files')
args = parser.parse_args()
enabled_modules = args.modules or [
'_weakrefset',
'abc',
'bisect',
'colorsys',
'copyreg',
'token',
'operator',
'stat',
'this',
]
# find the ouroboros directory
ouroboros_not_found_msg = "'ouroboros' folder must be present here or in the parent directory to compile stdlib"
if args.source is not None:
if not os.path.exists(args.source):
exit("{} directory doesn't exist".format(args.source))
ouroboros = args.source
elif os.path.exists('ouroboros'):
ouroboros = 'ouroboros'
elif os.path.exists('../ouroboros'):
ouroboros = '../ouroboros'
else:
exit("'ouroboros' folder must be present here or in the parent directory to compile stdlib")
return ouroboros, enabled_modules
def compile_stdlib(ouroboros, enabled_modules):
for module in enabled_modules:
module_fname = os.path.join(ouroboros, 'ouroboros', module + '.py')
if not os.path.exists(module_fname):
exit("Could not find file for module " + module)
outfile = os.path.join('batavia', 'modules', 'stdlib', module + '.js')
print("Compiling %s to %s" % (module_fname, outfile))
fp = tempfile.NamedTemporaryFile(delete=False)
fp.close()
try:
py_compile.compile(module_fname, cfile=fp.name)
with open(fp.name, 'rb') as fin:
pyc = fin.read()
finally:
# make sure we delete the file
os.unlink(fp.name)
with open(outfile, 'w') as fout:
fout.write("batavia.stdlib['" + module + "'] = '")
fout.write(base64.b64encode(pyc).decode('utf8'))
fout.write("';\n")
def main():
ouroboros, enabled_modules = parse_args()
compile_stdlib(ouroboros, enabled_modules)
if __name__ == '__main__':
main()