Funktionierender Prototyp des Serious Games zur Vermittlung von Wissen zu Software-Engineering-Arbeitsmodellen.
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.9KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257
  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. from django.core.exceptions import SuspiciousOperation
  26. class ArchiveException(Exception):
  27. """
  28. Base exception class for all archive errors.
  29. """
  30. class UnrecognizedArchiveFormat(ArchiveException):
  31. """
  32. Error raised when passed file is not a recognized archive format.
  33. """
  34. def extract(path, to_path):
  35. """
  36. Unpack the tar or zip file at the specified path to the directory
  37. specified by to_path.
  38. """
  39. with Archive(path) as archive:
  40. archive.extract(to_path)
  41. class Archive:
  42. """
  43. The external API class that encapsulates an archive implementation.
  44. """
  45. def __init__(self, file):
  46. self._archive = self._archive_cls(file)(file)
  47. @staticmethod
  48. def _archive_cls(file):
  49. cls = None
  50. if isinstance(file, str):
  51. filename = file
  52. else:
  53. try:
  54. filename = file.name
  55. except AttributeError:
  56. raise UnrecognizedArchiveFormat(
  57. "File object not a recognized archive format."
  58. )
  59. base, tail_ext = os.path.splitext(filename.lower())
  60. cls = extension_map.get(tail_ext)
  61. if not cls:
  62. base, ext = os.path.splitext(base)
  63. cls = extension_map.get(ext)
  64. if not cls:
  65. raise UnrecognizedArchiveFormat(
  66. "Path not a recognized archive format: %s" % filename
  67. )
  68. return cls
  69. def __enter__(self):
  70. return self
  71. def __exit__(self, exc_type, exc_value, traceback):
  72. self.close()
  73. def extract(self, to_path):
  74. self._archive.extract(to_path)
  75. def list(self):
  76. self._archive.list()
  77. def close(self):
  78. self._archive.close()
  79. class BaseArchive:
  80. """
  81. Base Archive class. Implementations should inherit this class.
  82. """
  83. @staticmethod
  84. def _copy_permissions(mode, filename):
  85. """
  86. If the file in the archive has some permissions (this assumes a file
  87. won't be writable/executable without being readable), apply those
  88. permissions to the unarchived file.
  89. """
  90. if mode & stat.S_IROTH:
  91. os.chmod(filename, mode)
  92. def split_leading_dir(self, path):
  93. path = str(path)
  94. path = path.lstrip("/").lstrip("\\")
  95. if "/" in path and (
  96. ("\\" in path and path.find("/") < path.find("\\")) or "\\" not in path
  97. ):
  98. return path.split("/", 1)
  99. elif "\\" in path:
  100. return path.split("\\", 1)
  101. else:
  102. return path, ""
  103. def has_leading_dir(self, paths):
  104. """
  105. Return True if all the paths have the same leading path name
  106. (i.e., everything is in one subdirectory in an archive).
  107. """
  108. common_prefix = None
  109. for path in paths:
  110. prefix, rest = self.split_leading_dir(path)
  111. if not prefix:
  112. return False
  113. elif common_prefix is None:
  114. common_prefix = prefix
  115. elif prefix != common_prefix:
  116. return False
  117. return True
  118. def target_filename(self, to_path, name):
  119. target_path = os.path.abspath(to_path)
  120. filename = os.path.abspath(os.path.join(target_path, name))
  121. if not filename.startswith(target_path):
  122. raise SuspiciousOperation("Archive contains invalid path: '%s'" % name)
  123. return filename
  124. def extract(self):
  125. raise NotImplementedError(
  126. "subclasses of BaseArchive must provide an extract() method"
  127. )
  128. def list(self):
  129. raise NotImplementedError(
  130. "subclasses of BaseArchive must provide a list() method"
  131. )
  132. class TarArchive(BaseArchive):
  133. def __init__(self, file):
  134. self._archive = tarfile.open(file)
  135. def list(self, *args, **kwargs):
  136. self._archive.list(*args, **kwargs)
  137. def extract(self, to_path):
  138. members = self._archive.getmembers()
  139. leading = self.has_leading_dir(x.name for x in members)
  140. for member in members:
  141. name = member.name
  142. if leading:
  143. name = self.split_leading_dir(name)[1]
  144. filename = self.target_filename(to_path, name)
  145. if member.isdir():
  146. if filename:
  147. os.makedirs(filename, exist_ok=True)
  148. else:
  149. try:
  150. extracted = self._archive.extractfile(member)
  151. except (KeyError, AttributeError) as exc:
  152. # Some corrupt tar files seem to produce this
  153. # (specifically bad symlinks)
  154. print(
  155. "In the tar file %s the member %s is invalid: %s"
  156. % (name, member.name, exc)
  157. )
  158. else:
  159. dirname = os.path.dirname(filename)
  160. if dirname:
  161. os.makedirs(dirname, exist_ok=True)
  162. with open(filename, "wb") as outfile:
  163. shutil.copyfileobj(extracted, outfile)
  164. self._copy_permissions(member.mode, filename)
  165. finally:
  166. if extracted:
  167. extracted.close()
  168. def close(self):
  169. self._archive.close()
  170. class ZipArchive(BaseArchive):
  171. def __init__(self, file):
  172. self._archive = zipfile.ZipFile(file)
  173. def list(self, *args, **kwargs):
  174. self._archive.printdir(*args, **kwargs)
  175. def extract(self, to_path):
  176. namelist = self._archive.namelist()
  177. leading = self.has_leading_dir(namelist)
  178. for name in namelist:
  179. data = self._archive.read(name)
  180. info = self._archive.getinfo(name)
  181. if leading:
  182. name = self.split_leading_dir(name)[1]
  183. if not name:
  184. continue
  185. filename = self.target_filename(to_path, name)
  186. if name.endswith(("/", "\\")):
  187. # A directory
  188. os.makedirs(filename, exist_ok=True)
  189. else:
  190. dirname = os.path.dirname(filename)
  191. if dirname:
  192. os.makedirs(dirname, exist_ok=True)
  193. with open(filename, "wb") as outfile:
  194. outfile.write(data)
  195. # Convert ZipInfo.external_attr to mode
  196. mode = info.external_attr >> 16
  197. self._copy_permissions(mode, filename)
  198. def close(self):
  199. self._archive.close()
  200. extension_map = dict.fromkeys(
  201. (
  202. ".tar",
  203. ".tar.bz2",
  204. ".tbz2",
  205. ".tbz",
  206. ".tz2",
  207. ".tar.gz",
  208. ".tgz",
  209. ".taz",
  210. ".tar.lzma",
  211. ".tlz",
  212. ".tar.xz",
  213. ".txz",
  214. ),
  215. TarArchive,
  216. )
  217. extension_map[".zip"] = ZipArchive