precompile_python.py 2.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061
  1. #!/usr/bin/env python3
  2. # Copyright 2023 Google Inc. All rights reserved.
  3. #
  4. # Licensed under the Apache License, Version 2.0 (the "License");
  5. # you may not use this file except in compliance with the License.
  6. # You may obtain a copy of the License at
  7. #
  8. # http://www.apache.org/licenses/LICENSE-2.0
  9. #
  10. # Unless required by applicable law or agreed to in writing, software
  11. # distributed under the License is distributed on an "AS IS" BASIS,
  12. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  13. # See the License for the specific language governing permissions and
  14. # limitations under the License.
  15. import argparse
  16. import py_compile
  17. import os
  18. import shutil
  19. import tempfile
  20. import zipfile
  21. # This file needs to support both python 2 and 3.
  22. def process_one_file(name, inf, outzip):
  23. if not name.endswith('.py'):
  24. outzip.writestr(name, inf.read())
  25. return
  26. # Unfortunately py_compile requires the input/output files to be written
  27. # out to disk.
  28. with tempfile.NamedTemporaryFile(prefix="Soong_precompile_", delete=False) as tmp:
  29. shutil.copyfileobj(inf, tmp)
  30. in_name = tmp.name
  31. with tempfile.NamedTemporaryFile(prefix="Soong_precompile_", delete=False) as tmp:
  32. out_name = tmp.name
  33. try:
  34. py_compile.compile(in_name, out_name, name, doraise=True)
  35. with open(out_name, 'rb') as f:
  36. outzip.writestr(name + 'c', f.read())
  37. finally:
  38. os.remove(in_name)
  39. os.remove(out_name)
  40. def main():
  41. parser = argparse.ArgumentParser()
  42. parser.add_argument('src_zip')
  43. parser.add_argument('dst_zip')
  44. args = parser.parse_args()
  45. with open(args.dst_zip, 'wb') as outf, open(args.src_zip, 'rb') as inf:
  46. with zipfile.ZipFile(outf, mode='w') as outzip, zipfile.ZipFile(inf, mode='r') as inzip:
  47. for name in inzip.namelist():
  48. with inzip.open(name, mode='r') as inzipf:
  49. process_one_file(name, inzipf, outzip)
  50. if __name__ == "__main__":
  51. main()