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 6.9 KiB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215
  1. """
  2. Based on "python-archive" -- http://pypi.python.org/pypi/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 tarfile
  23. import zipfile
  24. from django.utils import six
  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(object):
  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, six.string_types):
  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(object):
  77. """
  78. Base Archive class. Implementations should inherit this class.
  79. """
  80. def split_leading_dir(self, path):
  81. path = str(path)
  82. path = path.lstrip('/').lstrip('\\')
  83. if '/' in path and (('\\' in path and path.find('/') < path.find('\\'))
  84. or '\\' not in path):
  85. return path.split('/', 1)
  86. elif '\\' in path:
  87. return path.split('\\', 1)
  88. else:
  89. return path, ''
  90. def has_leading_dir(self, paths):
  91. """
  92. Returns true if all the paths have the same leading path name
  93. (i.e., everything is in one subdirectory in an archive)
  94. """
  95. common_prefix = None
  96. for path in paths:
  97. prefix, rest = self.split_leading_dir(path)
  98. if not prefix:
  99. return False
  100. elif common_prefix is None:
  101. common_prefix = prefix
  102. elif prefix != common_prefix:
  103. return False
  104. return True
  105. def extract(self):
  106. raise NotImplementedError('subclasses of BaseArchive must provide an extract() method')
  107. def list(self):
  108. raise NotImplementedError('subclasses of BaseArchive must provide a list() method')
  109. class TarArchive(BaseArchive):
  110. def __init__(self, file):
  111. self._archive = tarfile.open(file)
  112. def list(self, *args, **kwargs):
  113. self._archive.list(*args, **kwargs)
  114. def extract(self, to_path):
  115. # note: python<=2.5 doesn't seem to know about pax headers, filter them
  116. members = [member for member in self._archive.getmembers()
  117. if member.name != 'pax_global_header']
  118. leading = self.has_leading_dir(x.name for x in members)
  119. for member in members:
  120. name = member.name
  121. if leading:
  122. name = self.split_leading_dir(name)[1]
  123. filename = os.path.join(to_path, name)
  124. if member.isdir():
  125. if filename and not os.path.exists(filename):
  126. os.makedirs(filename)
  127. else:
  128. try:
  129. extracted = self._archive.extractfile(member)
  130. except (KeyError, AttributeError) as exc:
  131. # Some corrupt tar files seem to produce this
  132. # (specifically bad symlinks)
  133. print("In the tar file %s the member %s is invalid: %s" %
  134. (name, member.name, exc))
  135. else:
  136. dirname = os.path.dirname(filename)
  137. if dirname and not os.path.exists(dirname):
  138. os.makedirs(dirname)
  139. with open(filename, 'wb') as outfile:
  140. shutil.copyfileobj(extracted, outfile)
  141. finally:
  142. if extracted:
  143. extracted.close()
  144. def close(self):
  145. self._archive.close()
  146. class ZipArchive(BaseArchive):
  147. def __init__(self, file):
  148. self._archive = zipfile.ZipFile(file)
  149. def list(self, *args, **kwargs):
  150. self._archive.printdir(*args, **kwargs)
  151. def extract(self, to_path):
  152. namelist = self._archive.namelist()
  153. leading = self.has_leading_dir(namelist)
  154. for name in namelist:
  155. data = self._archive.read(name)
  156. if leading:
  157. name = self.split_leading_dir(name)[1]
  158. filename = os.path.join(to_path, name)
  159. dirname = os.path.dirname(filename)
  160. if dirname and not os.path.exists(dirname):
  161. os.makedirs(dirname)
  162. if filename.endswith(('/', '\\')):
  163. # A directory
  164. if not os.path.exists(filename):
  165. os.makedirs(filename)
  166. else:
  167. with open(filename, 'wb') as outfile:
  168. outfile.write(data)
  169. def close(self):
  170. self._archive.close()
  171. extension_map = {
  172. '.tar': TarArchive,
  173. '.tar.bz2': TarArchive,
  174. '.tar.gz': TarArchive,
  175. '.tgz': TarArchive,
  176. '.tz2': TarArchive,
  177. '.zip': ZipArchive,
  178. }