zipapp.py 1.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243
  1. from __future__ import annotations
  2. import logging
  3. import os
  4. import zipfile
  5. from virtualenv.info import IS_WIN, ROOT
  6. LOGGER = logging.getLogger(__name__)
  7. def read(full_path):
  8. sub_file = _get_path_within_zip(full_path)
  9. with zipfile.ZipFile(ROOT, "r") as zip_file, zip_file.open(sub_file) as file_handler:
  10. return file_handler.read().decode("utf-8")
  11. def extract(full_path, dest):
  12. LOGGER.debug("extract %s to %s", full_path, dest)
  13. sub_file = _get_path_within_zip(full_path)
  14. with zipfile.ZipFile(ROOT, "r") as zip_file:
  15. info = zip_file.getinfo(sub_file)
  16. info.filename = dest.name
  17. zip_file.extract(info, str(dest.parent))
  18. def _get_path_within_zip(full_path):
  19. full_path = os.path.realpath(os.path.abspath(str(full_path)))
  20. prefix = f"{ROOT}{os.sep}"
  21. if not full_path.startswith(prefix):
  22. msg = f"full_path={full_path} should start with prefix={prefix}."
  23. raise RuntimeError(msg)
  24. sub_file = full_path[len(prefix) :]
  25. if IS_WIN:
  26. # paths are always UNIX separators, even on Windows, though __file__ still follows platform default
  27. sub_file = sub_file.replace(os.sep, "/")
  28. return sub_file
  29. __all__ = [
  30. "extract",
  31. "read",
  32. ]