TarIO.py 1.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273
  1. #
  2. # The Python Imaging Library.
  3. # $Id$
  4. #
  5. # read files from within a tar file
  6. #
  7. # History:
  8. # 95-06-18 fl Created
  9. # 96-05-28 fl Open files in binary mode
  10. #
  11. # Copyright (c) Secret Labs AB 1997.
  12. # Copyright (c) Fredrik Lundh 1995-96.
  13. #
  14. # See the README file for information on usage and redistribution.
  15. #
  16. from __future__ import annotations
  17. import io
  18. from types import TracebackType
  19. from . import ContainerIO
  20. class TarIO(ContainerIO.ContainerIO[bytes]):
  21. """A file object that provides read access to a given member of a TAR file."""
  22. def __init__(self, tarfile: str, file: str) -> None:
  23. """
  24. Create file object.
  25. :param tarfile: Name of TAR file.
  26. :param file: Name of member file.
  27. """
  28. self.fh = open(tarfile, "rb")
  29. while True:
  30. s = self.fh.read(512)
  31. if len(s) != 512:
  32. msg = "unexpected end of tar file"
  33. raise OSError(msg)
  34. name = s[:100].decode("utf-8")
  35. i = name.find("\0")
  36. if i == 0:
  37. msg = "cannot find subfile"
  38. raise OSError(msg)
  39. if i > 0:
  40. name = name[:i]
  41. size = int(s[124:135], 8)
  42. if file == name:
  43. break
  44. self.fh.seek((size + 511) & (~511), io.SEEK_CUR)
  45. # Open region
  46. super().__init__(self.fh, self.fh.tell(), size)
  47. # Context manager support
  48. def __enter__(self) -> TarIO:
  49. return self
  50. def __exit__(
  51. self,
  52. exc_type: type[BaseException] | None,
  53. exc_val: BaseException | None,
  54. exc_tb: TracebackType | None,
  55. ) -> None:
  56. self.close()
  57. def close(self) -> None:
  58. self.fh.close()