TarIO.py 1.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768
  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. __lazy_modules__ = {"io"}
  18. import io
  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. self.fh.close()
  33. msg = "unexpected end of tar file"
  34. raise OSError(msg)
  35. name = s[:100].decode("utf-8")
  36. i = name.find("\0")
  37. if i == 0:
  38. self.fh.close()
  39. msg = "cannot find subfile"
  40. raise OSError(msg)
  41. if i > 0:
  42. name = name[:i]
  43. size = int(s[124:135], 8)
  44. if size < 0:
  45. self.fh.close()
  46. msg = "size must not be negative"
  47. raise ValueError(msg)
  48. if file == name:
  49. break
  50. offset = (size + 511) & ~511
  51. self.fh.seek(offset, io.SEEK_CUR)
  52. # Open region
  53. super().__init__(self.fh, self.fh.tell(), size)