1#!/usr/bin/env python3
2import argparse
3import os
4import os.path
5
6argparser = argparse.ArgumentParser(description="Compile all .py files to .mpy recursively")
7argparser.add_argument("-o", "--out", help="output directory (default: input dir)")
8argparser.add_argument("--target", help="select MicroPython target config")
9argparser.add_argument(
10    "-mcache-lookup-bc", action="store_true", help="cache map lookups in the bytecode"
11)
12argparser.add_argument("dir", help="input directory")
13args = argparser.parse_args()
14
15TARGET_OPTS = {
16    "unix": "-mcache-lookup-bc",
17    "baremetal": "",
18}
19
20args.dir = args.dir.rstrip("/")
21
22if not args.out:
23    args.out = args.dir
24
25path_prefix_len = len(args.dir) + 1
26
27for path, subdirs, files in os.walk(args.dir):
28    for f in files:
29        if f.endswith(".py"):
30            fpath = path + "/" + f
31            # print(fpath)
32            out_fpath = args.out + "/" + fpath[path_prefix_len:-3] + ".mpy"
33            out_dir = os.path.dirname(out_fpath)
34            if not os.path.isdir(out_dir):
35                os.makedirs(out_dir)
36            cmd = "mpy-cross -v -v %s -s %s %s -o %s" % (
37                TARGET_OPTS.get(args.target, ""),
38                fpath[path_prefix_len:],
39                fpath,
40                out_fpath,
41            )
42            # print(cmd)
43            res = os.system(cmd)
44            assert res == 0
45