pycompile.py 2.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091
  1. #!/usr/bin/env python3
  2. """
  3. Byte compile all .py files from provided directories. This script is an
  4. alternative implementation of compileall.compile_dir written with
  5. cross-compilation in mind.
  6. """
  7. import argparse
  8. import os
  9. import py_compile
  10. import re
  11. import sys
  12. def compile_one(host_path, strip_root=None, verbose=False):
  13. """
  14. Compile a .py file into a .pyc file located next to it.
  15. :arg host_path:
  16. Absolute path to the file to compile on the host running the build.
  17. :arg strip_root:
  18. Prefix to remove from the original source paths encoded in compiled
  19. files.
  20. :arg verbose:
  21. Print compiled file paths.
  22. """
  23. if os.path.islink(host_path) or not os.path.isfile(host_path):
  24. return # only compile real files
  25. if not re.match(r"^[_A-Za-z][_A-Za-z0-9]*\.py$",
  26. os.path.basename(host_path)):
  27. return # only compile "importable" python modules
  28. if strip_root is not None:
  29. # determine the runtime path of the file (i.e.: relative path to root
  30. # dir prepended with "/").
  31. runtime_path = os.path.join("/", os.path.relpath(host_path, strip_root))
  32. else:
  33. runtime_path = host_path
  34. if verbose:
  35. print(" PYC {}".format(runtime_path))
  36. # will raise an error if the file cannot be compiled
  37. py_compile.compile(host_path, cfile=host_path + "c",
  38. dfile=runtime_path, doraise=True)
  39. def existing_dir_abs(arg):
  40. """
  41. argparse type callback that checks that argument is a directory and returns
  42. its absolute path.
  43. """
  44. if not os.path.isdir(arg):
  45. raise argparse.ArgumentTypeError('no such directory: {!r}'.format(arg))
  46. return os.path.abspath(arg)
  47. def main():
  48. parser = argparse.ArgumentParser(description=__doc__)
  49. parser.add_argument("dirs", metavar="DIR", nargs="+", type=existing_dir_abs,
  50. help="Directory to recursively scan and compile")
  51. parser.add_argument("--strip-root", metavar="ROOT", type=existing_dir_abs,
  52. help="""
  53. Prefix to remove from the original source paths encoded
  54. in compiled files
  55. """)
  56. parser.add_argument("--verbose", action="store_true",
  57. help="Print compiled files")
  58. args = parser.parse_args()
  59. try:
  60. for d in args.dirs:
  61. if args.strip_root and ".." in os.path.relpath(d, args.strip_root):
  62. parser.error("DIR: not inside ROOT dir: {!r}".format(d))
  63. for parent, _, files in os.walk(d):
  64. for f in files:
  65. compile_one(os.path.join(parent, f), args.strip_root,
  66. args.verbose)
  67. except Exception as e:
  68. print("error: {}".format(e))
  69. return 1
  70. return 0
  71. if __name__ == "__main__":
  72. sys.exit(main())