zipapp.py 1.3 KB

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