_zip.py 2.4 KB

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