collect_micropython_lib.py 2.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879
  1. #!/usr/bin/env python3
  2. """
  3. Sometime after v1.9.3, micropython-lib's directory structure was cleaned up and
  4. enhanced with manifest files.
  5. Though cleaner, it means it cannot be directly copied into the target.
  6. This script is during build process to perform that conversion.
  7. It makes use of manifestfile.py, which is normally located in micropython's
  8. tool directory.
  9. It also depends on the micropython-lib that is cloned in lib/micropython-lib
  10. during build.
  11. """
  12. import argparse
  13. import manifestfile
  14. import os
  15. import shutil
  16. def get_library_name_type(manifest_path: str) -> tuple[str, bool]:
  17. split = manifest_path.split("/")
  18. return (split[-2], "unix-ffi" in split) # -1: "manifest.py", -2: library name
  19. def get_all_libraries(mpy_lib_dir: str):
  20. # reuse manifestfile module capabilities to scan the micropython-lib directory
  21. collected_list = manifestfile.ManifestFile(
  22. manifestfile.MODE_FREEZE, {"MPY_LIB_DIR": mpy_lib_dir}
  23. )
  24. collected_list.freeze(mpy_lib_dir)
  25. for file in collected_list.files():
  26. if file.target_path.endswith("manifest.py"):
  27. yield get_library_name_type(file.full_path)
  28. def copy_file(src: str, target: str, destination: str):
  29. s = target.split("/")
  30. s.pop()
  31. d = f"{destination}/{'/'.join(s)}"
  32. os.makedirs(d, exist_ok=True)
  33. shutil.copy(src, f"{destination}/{target}")
  34. def copy_libraries(manifest, destination: str):
  35. for f in manifest.files():
  36. copy_file(f.full_path, f.target_path, destination)
  37. def process_cmdline_args():
  38. parser = argparse.ArgumentParser(
  39. description="Prepare micropython-lib to be installed"
  40. )
  41. parser.add_argument("micropython", help="Path to micropython source directory")
  42. parser.add_argument("destination", help="Destination directory")
  43. args = parser.parse_args()
  44. return os.path.abspath(args.micropython), os.path.abspath(args.destination)
  45. def main():
  46. micropython_dir, destination_dir = process_cmdline_args()
  47. mpy_lib_dir = f"{micropython_dir}/lib/micropython-lib"
  48. manifest = manifestfile.ManifestFile(
  49. manifestfile.MODE_FREEZE, {"MPY_LIB_DIR": mpy_lib_dir}
  50. )
  51. for library, is_ffi in get_all_libraries(mpy_lib_dir):
  52. manifest.require(library, unix_ffi=is_ffi)
  53. copy_libraries(manifest, destination_dir)
  54. main()