8000 mpy-cross/mpy_cross: Add a way to query the mpy version. · micropython/micropython@12b5435 · GitHub
[go: up one dir, main page]

Skip to content

Commit 12b5435

Browse files
committed
mpy-cross/mpy_cross: Add a way to query the mpy version.
This returns the: - mpy_version - mpy_sub_version - native_arch for files compiled with this mpy-cross binary. Signed-off-by: Jim Mussared <jim.mussared@gmail.com>
1 parent 95c184a commit 12b5435

File tree

1 file changed

+24
-2
lines changed

1 file changed

+24
-2
lines changed

mpy-cross/mpy_cross/__init__.py

Lines changed: 24 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -29,6 +29,7 @@
2929
import os
3030
import stat
3131
import subprocess
32+
import tempfile
3233

3334
NATIVE_ARCH_X86 = "x86"
3435
NATIVE_ARCH_X64 = "x64"
@@ -54,14 +55,35 @@
5455
NATIVE_ARCH_XTENSAWIN,
5556
]
5657

57-
__all__ = ["compile", "run", "CrossCompileError"]
58+
__all__ = ["version", "compile", "run", "CrossCompileError"]
5859

5960

6061
class CrossCompileError(Exception):
6162
pass
6263

6364

64-
def find_mpy_cross_binary(mpy_cross):
65+
def version(march=None, mpy_cross=None):
66+
# Compiles an empty .py file and returns the version info from the .mpy.
67+
src_fd, src_path = tempfile.mkstemp(suffix=".py", text=True)
68+
try:
69+
dest_path = src_path[:-3] + ".mpy"
70+
extra_args = ["-X", "emit=native"] if march else None
71+
compile(src_path, march=march, mpy_cross=mpy_cross, extra_args=extra_args)
72+
with open(dest_path, "rb") as f:
73+
header = f.read(3)
74+
mpy_version = header[1]
75+
mpy_sub_version = 0
76+
feature_byte = header[2]
77+
arch = feature_byte >> 2
78+
if arch != 0:
79+
mpy_sub_version = feature_byte & 3
80+
return mpy_version, mpy_sub_version, arch
81+
finally:
82+
os.unlink(src_path)
83+
if os.path.exists(dest_path):
84+
os.unlink(dest_path)
85+
86+
6587

6688
def _find_mpy_cross_binary(mpy_cross):
6789
if mpy_cross:

0 commit comments

Comments
 (0)
0