_zip.py 2.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364
  1. import argparse
  2. import glob
  3. import os
  4. from pathlib import Path
  5. from zipfile import ZipFile
  6. # Exclude some standard library modules to:
  7. # 1. Slim down the final zipped file size
  8. # 2. Remove functionality we don't want to support.
  9. DENY_LIST = [
  10. # Interface to unix databases
  11. "dbm",
  12. # ncurses bindings (terminal interfaces)
  13. "curses",
  14. # Tcl/Tk GUI
  15. "tkinter",
  16. "tkinter",
  17. # Tests for the standard library
  18. "test",
  19. "tests",
  20. "idle_test",
  21. "__phello__.foo.py",
  22. # importlib frozen modules. These are already baked into CPython.
  23. "_bootstrap.py",
  24. "_bootstrap_external.py",
  25. ]
  26. def remove_prefix(text, prefix):
  27. if text.startswith(prefix):
  28. return text[len(prefix):]
  29. return text
  30. def write_to_zip(file_path, strip_file_path, zf, prepend_str=""):
  31. stripped_file_path = prepend_str + remove_prefix(file_path, strip_file_dir + "/")
  32. path = Path(stripped_file_path)
  33. if path.name in DENY_LIST:
  34. return
  35. zf.write(file_path, stripped_file_path)
  36. if __name__ == "__main__":
  37. parser = argparse.ArgumentParser(description="Zip py source")
  38. parser.add_argument("paths", nargs="*", help="Paths to zip.")
  39. parser.add_argument("--install-dir", "--install_dir", help="Root directory for all output files")
  40. parser.add_argument("--strip-dir", "--strip_dir", help="The absolute directory we want to remove from zip")
  41. parser.add_argument(
  42. "--prepend-str", "--prepend_str", help="A string to prepend onto all paths of a file in the zip", default=""
  43. )
  44. parser.add_argument("--zip-name", "--zip_name", help="Output zip name")
  45. args = parser.parse_args()
  46. zip_file_name = args.install_dir + '/' + args.zip_name
  47. strip_file_dir = args.strip_dir
  48. prepend_str = args.prepend_str
  49. zf = ZipFile(zip_file_name, mode='w')
  50. for p in args.paths:
  51. if os.path.isdir(p):
  52. files = glob.glob(p + "/**/*.py", recursive=True)
  53. for file_path in files:
  54. # strip the absolute path
  55. write_to_zip(file_path, strip_file_dir + "/", zf, prepend_str=prepend_str)
  56. else:
  57. write_to_zip(p, strip_file_dir + "/", zf, prepend_str=prepend_str)