-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathbuild.py
executable file
·86 lines (69 loc) · 2.19 KB
/
build.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
#!/usr/bin/env python3
"""
Builder script to compile .py files to .mpy bytecode using mpy-cross
"""
import glob
from errno import ENOTDIR
from os import listdir, makedirs
from os.path import join, splitext
from shutil import copy, copytree, rmtree
from subprocess import PIPE, Popen
SRC = "src"
DST = "build"
def recursive_copy(src: str, dst: str):
"""
Copy a file or directory from src to dst.
Parameters:
src (str): The path of the source file or directory.
dst (str): The path of the destination file or directory.
Returns:
None
"""
try:
copytree(src, dst)
except OSError as exc:
if exc.errno == ENOTDIR:
copy(src, dst)
else:
raise
def to_compile(name: str) -> str:
"""
Check if a given file is a Python source file that needs to be compiled.
Parameters:
name (str): The name of the file.
Returns:
str: The name of the file without the extension if it need compilation,
otherwise None.
"""
base, ext = splitext(name)
if base not in ("code", "boot") and ext == ".py":
return base
return None
def main():
"""
Use mpy-cross to compile .py files to .mpy bytecode
"""
# Remove the build directory if it exists, then create it again
rmtree(DST, ignore_errors=True)
makedirs(DST, exist_ok=True)
makedirs(join(DST, "lib"), exist_ok=True)
# Find the path of the mpy-cross binary
mpy_cross_bin = join(".", glob.glob("mpy-cross.static*")[0])
# Process each entry in the source directory
for entry in listdir(SRC):
src_path = join(SRC, entry)
# If the entry is a Python source file that needs to be compiled
if name := to_compile(entry):
# Compile the file using mpy-cross
with Popen(
[mpy_cross_bin, "-o",
join(DST, "lib", f"{name}.mpy"), src_path],
stdout=PIPE,
) as process:
process.communicate()
else:
# Copy the file or directory to the build directory
dst_path = join(DST, entry)
recursive_copy(src_path, dst_path)
if __name__ == "__main__":
main()