You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

archive.py 7.3KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227
  1. """
  2. Based on "python-archive" -- https://pypi.org/project/python-archive/
  3. Copyright (c) 2010 Gary Wilson Jr. <gary.wilson@gmail.com> and contributors.
  4. Permission is hereby granted, free of charge, to any person obtaining a copy
  5. of this software and associated documentation files (the "Software"), to deal
  6. in the Software without restriction, including without limitation the rights
  7. to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  8. copies of the Software, and to permit persons to whom the Software is
  9. furnished to do so, subject to the following conditions:
  10. The above copyright notice and this permission notice shall be included in
  11. all copies or substantial portions of the Software.
  12. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  13. IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  14. FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  15. AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  16. LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  17. OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  18. THE SOFTWARE.
  19. """
  20. import os
  21. import shutil
  22. import stat
  23. import tarfile
  24. import zipfile
  25. class ArchiveException(Exception):
  26. """
  27. Base exception class for all archive errors.
  28. """
  29. class UnrecognizedArchiveFormat(ArchiveException):
  30. """
  31. Error raised when passed file is not a recognized archive format.
  32. """
  33. def extract(path, to_path=''):
  34. """
  35. Unpack the tar or zip file at the specified path to the directory
  36. specified by to_path.
  37. """
  38. with Archive(path) as archive:
  39. archive.extract(to_path)
  40. class Archive:
  41. """
  42. The external API class that encapsulates an archive implementation.
  43. """
  44. def __init__(self, file):
  45. self._archive = self._archive_cls(file)(file)
  46. @staticmethod
  47. def _archive_cls(file):
  48. cls = None
  49. if isinstance(file, str):
  50. filename = file
  51. else:
  52. try:
  53. filename = file.name
  54. except AttributeError:
  55. raise UnrecognizedArchiveFormat(
  56. "File object not a recognized archive format.")
  57. base, tail_ext = os.path.splitext(filename.lower())
  58. cls = extension_map.get(tail_ext)
  59. if not cls:
  60. base, ext = os.path.splitext(base)
  61. cls = extension_map.get(ext)
  62. if not cls:
  63. raise UnrecognizedArchiveFormat(
  64. "Path not a recognized archive format: %s" % filename)
  65. return cls
  66. def __enter__(self):
  67. return self
  68. def __exit__(self, exc_type, exc_value, traceback):
  69. self.close()
  70. def extract(self, to_path=''):
  71. self._archive.extract(to_path)
  72. def list(self):
  73. self._archive.list()
  74. def close(self):
  75. self._archive.close()
  76. class BaseArchive:
  77. """
  78. Base Archive class. Implementations should inherit this class.
  79. """
  80. @staticmethod
  81. def _copy_permissions(mode, filename):
  82. """
  83. If the file in the archive has some permissions (this assumes a file
  84. won't be writable/executable without being readable), apply those
  85. permissions to the unarchived file.
  86. """
  87. if mode & stat.S_IROTH:
  88. os.chmod(filename, mode)
  89. def split_leading_dir(self, path):
  90. path = str(path)
  91. path = path.lstrip('/').lstrip('\\')
  92. if '/' in path and (('\\' in path and path.find('/') < path.find('\\')) or '\\' not in path):
  93. return path.split('/', 1)
  94. elif '\\' in path:
  95. return path.split('\\', 1)
  96. else:
  97. return path, ''
  98. def has_leading_dir(self, paths):
  99. """
  100. Return True if all the paths have the same leading path name
  101. (i.e., everything is in one subdirectory in an archive).
  102. """
  103. common_prefix = None
  104. for path in paths:
  105. prefix, rest = self.split_leading_dir(path)
  106. if not prefix:
  107. return False
  108. elif common_prefix is None:
  109. common_prefix = prefix
  110. elif prefix != common_prefix:
  111. return False
  112. return True
  113. def extract(self):
  114. raise NotImplementedError('subclasses of BaseArchive must provide an extract() method')
  115. def list(self):
  116. raise NotImplementedError('subclasses of BaseArchive must provide a list() method')
  117. class TarArchive(BaseArchive):
  118. def __init__(self, file):
  119. self._archive = tarfile.open(file)
  120. def list(self, *args, **kwargs):
  121. self._archive.list(*args, **kwargs)
  122. def extract(self, to_path):
  123. members = self._archive.getmembers()
  124. leading = self.has_leading_dir(x.name for x in members)
  125. for member in members:
  126. name = member.name
  127. if leading:
  128. name = self.split_leading_dir(name)[1]
  129. filename = os.path.join(to_path, name)
  130. if member.isdir():
  131. if filename and not os.path.exists(filename):
  132. os.makedirs(filename)
  133. else:
  134. try:
  135. extracted = self._archive.extractfile(member)
  136. except (KeyError, AttributeError) as exc:
  137. # Some corrupt tar files seem to produce this
  138. # (specifically bad symlinks)
  139. print("In the tar file %s the member %s is invalid: %s" %
  140. (name, member.name, exc))
  141. else:
  142. dirname = os.path.dirname(filename)
  143. if dirname and not os.path.exists(dirname):
  144. os.makedirs(dirname)
  145. with open(filename, 'wb') as outfile:
  146. shutil.copyfileobj(extracted, outfile)
  147. self._copy_permissions(member.mode, filename)
  148. finally:
  149. if extracted:
  150. extracted.close()
  151. def close(self):
  152. self._archive.close()
  153. class ZipArchive(BaseArchive):
  154. def __init__(self, file):
  155. self._archive = zipfile.ZipFile(file)
  156. def list(self, *args, **kwargs):
  157. self._archive.printdir(*args, **kwargs)
  158. def extract(self, to_path):
  159. namelist = self._archive.namelist()
  160. leading = self.has_leading_dir(namelist)
  161. for name in namelist:
  162. data = self._archive.read(name)
  163. info = self._archive.getinfo(name)
  164. if leading:
  165. name = self.split_leading_dir(name)[1]
  166. filename = os.path.join(to_path, name)
  167. dirname = os.path.dirname(filename)
  168. if dirname and not os.path.exists(dirname):
  169. os.makedirs(dirname)
  170. if filename.endswith(('/', '\\')):
  171. # A directory
  172. if not os.path.exists(filename):
  173. os.makedirs(filename)
  174. else:
  175. with open(filename, 'wb') as outfile:
  176. outfile.write(data)
  177. # Convert ZipInfo.external_attr to mode
  178. mode = info.external_attr >> 16
  179. self._copy_permissions(mode, filename)
  180. def close(self):
  181. self._archive.close()
  182. extension_map = {
  183. '.tar': TarArchive,
  184. '.tar.bz2': TarArchive,
  185. '.tar.gz': TarArchive,
  186. '.tgz': TarArchive,
  187. '.tz2': TarArchive,
  188. '.zip': ZipArchive,
  189. }