Skip to content

Commit 3757300

Browse files
authored
pybricksdev.compile: include already compiled .mpy modules
In the `compile_multi_file()` function, also include any imported .mpy files found in addition to .py files. This allows including native modules that were compiled to .mpy from C source code. Also fix cases where `module.__file__` does not exist (it is an optional attribute) while we are touching this.
1 parent e9e74ea commit 3757300

File tree

2 files changed

+21
-1
lines changed

2 files changed

+21
-1
lines changed

CHANGELOG.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,7 @@ The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/),
55
and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).
66

77
## [Unreleased]
8+
- Add support for including precompiled .mpy libraries
89

910
## [1.0.0-alpha.36] - 2023-02-18
1011

pybricksdev/compile.py

Lines changed: 20 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -113,7 +113,8 @@ async def compile_multi_file(path: str, abi: int):
113113
"""
114114

115115
# compile files using Python to find imports contained within the same directory as path
116-
finder = ModuleFinder([os.path.dirname(path)])
116+
search_path = [os.path.dirname(path)]
117+
finder = ModuleFinder(search_path)
117118
finder.run_script(path)
118119

119120
# we expect missing modules, namely builtin MicroPython packages like pybricks.*
@@ -123,12 +124,30 @@ async def compile_multi_file(path: str, abi: int):
123124
parts: List[bytes] = []
124125

125126
for name, module in finder.modules.items():
127+
if not module.__file__:
128+
continue
126129
mpy = await compile_file(module.__file__, abi)
127130

128131
parts.append(len(mpy).to_bytes(4, "little"))
129132
parts.append(name.encode() + b"\x00")
130133
parts.append(mpy)
131134

135+
# look for .mpy modules
136+
for name in finder.any_missing():
137+
for spath in search_path:
138+
try:
139+
with open(os.path.join(spath, f"{name}.mpy"), "rb") as f:
140+
mpy = f.read()
141+
if mpy[1] != abi:
142+
raise ValueError(
143+
f"{name}.mpy has abi version {mpy[1]} while {abi} is required"
144+
)
145+
parts.append(len(mpy).to_bytes(4, "little"))
146+
parts.append(name.encode() + b"\x00")
147+
parts.append(mpy)
148+
except OSError:
149+
continue
150+
132151
return b"".join(parts)
133152

134153

0 commit comments

Comments
 (0)