1import marshal
2import tokenize
3import os.path
4import sys
5
6PROGRAM_DIR = os.path.dirname(__file__)
7SRC_DIR = os.path.dirname(PROGRAM_DIR)
8
9
10def writecode(fp, mod, data):
11    print('unsigned char M_%s[] = {' % mod, file=fp)
12    indent = ' ' * 4
13    for i in range(0, len(data), 16):
14        print(indent, file=fp, end='')
15        for c in bytes(data[i:i+16]):
16            print('%d,' % c, file=fp, end='')
17        print('', file=fp)
18    print('};', file=fp)
19
20
21def dump(fp, filename, name):
22    # Strip the directory to get reproducible marshal dump
23    code_filename = os.path.basename(filename)
24
25    with tokenize.open(filename) as source_fp:
26        source = source_fp.read()
27        code = compile(source, code_filename, 'exec')
28
29    data = marshal.dumps(code)
30    writecode(fp, name, data)
31
32
33def main():
34    if len(sys.argv) < 2:
35        print(f"usage: {sys.argv[0]} filename")
36        sys.exit(1)
37    filename = sys.argv[1]
38
39    with open(filename, "w") as fp:
40        print("// Auto-generated by Programs/freeze_test_frozenmain.py", file=fp)
41        frozenmain = os.path.join(PROGRAM_DIR, 'test_frozenmain.py')
42        dump(fp, frozenmain, 'test_frozenmain')
43
44    print(f"{filename} written")
45
46
47if __name__ == "__main__":
48    main()
49