Du kan inte välja fler än 25 ämnen Ämnen måste starta med en bokstav eller siffra, kan innehålla bindestreck ('-') och vara max 35 tecken långa.

extract.py 5.2 KiB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181
  1. # Copyright (c) 2015, Google Inc.
  2. #
  3. # Permission to use, copy, modify, and/or distribute this software for any
  4. # purpose with or without fee is hereby granted, provided that the above
  5. # copyright notice and this permission notice appear in all copies.
  6. #
  7. # THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
  8. # WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
  9. # MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY
  10. # SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
  11. # WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION
  12. # OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN
  13. # CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
  14. """Extracts archives."""
  15. import hashlib
  16. import optparse
  17. import os
  18. import os.path
  19. import tarfile
  20. import shutil
  21. import sys
  22. import zipfile
  23. def CheckedJoin(output, path):
  24. """
  25. CheckedJoin returns os.path.join(output, path). It does sanity checks to
  26. ensure the resulting path is under output, but shouldn't be used on untrusted
  27. input.
  28. """
  29. path = os.path.normpath(path)
  30. if os.path.isabs(path) or path.startswith('.'):
  31. raise ValueError(path)
  32. return os.path.join(output, path)
  33. class FileEntry(object):
  34. def __init__(self, path, mode, fileobj):
  35. self.path = path
  36. self.mode = mode
  37. self.fileobj = fileobj
  38. class SymlinkEntry(object):
  39. def __init__(self, path, mode, target):
  40. self.path = path
  41. self.mode = mode
  42. self.target = target
  43. def IterateZip(path):
  44. """
  45. IterateZip opens the zip file at path and returns a generator of entry objects
  46. for each file in it.
  47. """
  48. with zipfile.ZipFile(path, 'r') as zip_file:
  49. for info in zip_file.infolist():
  50. if info.filename.endswith('/'):
  51. continue
  52. yield FileEntry(info.filename, None, zip_file.open(info))
  53. def IterateTar(path, compression):
  54. """
  55. IterateTar opens the tar.gz or tar.bz2 file at path and returns a generator of
  56. entry objects for each file in it.
  57. """
  58. with tarfile.open(path, 'r:' + compression) as tar_file:
  59. for info in tar_file:
  60. if info.isdir():
  61. pass
  62. elif info.issym():
  63. yield SymlinkEntry(info.name, None, info.linkname)
  64. elif info.isfile():
  65. yield FileEntry(info.name, info.mode, tar_file.extractfile(info))
  66. else:
  67. raise ValueError('Unknown entry type "%s"' % (info.name, ))
  68. def main(args):
  69. parser = optparse.OptionParser(usage='Usage: %prog ARCHIVE OUTPUT')
  70. parser.add_option('--no-prefix', dest='no_prefix', action='store_true',
  71. help='Do not remove a prefix from paths in the archive.')
  72. options, args = parser.parse_args(args)
  73. if len(args) != 2:
  74. parser.print_help()
  75. return 1
  76. archive, output = args
  77. if not os.path.exists(archive):
  78. # Skip archives that weren't downloaded.
  79. return 0
  80. with open(archive) as f:
  81. sha256 = hashlib.sha256()
  82. while True:
  83. chunk = f.read(1024 * 1024)
  84. if not chunk:
  85. break
  86. sha256.update(chunk)
  87. digest = sha256.hexdigest()
  88. stamp_path = os.path.join(output, ".boringssl_archive_digest")
  89. if os.path.exists(stamp_path):
  90. with open(stamp_path) as f:
  91. if f.read().strip() == digest:
  92. print "Already up-to-date."
  93. return 0
  94. if archive.endswith('.zip'):
  95. entries = IterateZip(archive)
  96. elif archive.endswith('.tar.gz'):
  97. entries = IterateTar(archive, 'gz')
  98. elif archive.endswith('.tar.bz2'):
  99. entries = IterateTar(archive, 'bz2')
  100. else:
  101. raise ValueError(archive)
  102. try:
  103. if os.path.exists(output):
  104. print "Removing %s" % (output, )
  105. shutil.rmtree(output)
  106. print "Extracting %s to %s" % (archive, output)
  107. prefix = None
  108. num_extracted = 0
  109. for entry in entries:
  110. # Even on Windows, zip files must always use forward slashes.
  111. if '\\' in entry.path or entry.path.startswith('/'):
  112. raise ValueError(entry.path)
  113. if not options.no_prefix:
  114. new_prefix, rest = entry.path.split('/', 1)
  115. # Ensure the archive is consistent.
  116. if prefix is None:
  117. prefix = new_prefix
  118. if prefix != new_prefix:
  119. raise ValueError((prefix, new_prefix))
  120. else:
  121. rest = entry.path
  122. # Extract the file into the output directory.
  123. fixed_path = CheckedJoin(output, rest)
  124. if not os.path.isdir(os.path.dirname(fixed_path)):
  125. os.makedirs(os.path.dirname(fixed_path))
  126. if isinstance(entry, FileEntry):
  127. with open(fixed_path, 'wb') as out:
  128. shutil.copyfileobj(entry.fileobj, out)
  129. elif isinstance(entry, SymlinkEntry):
  130. os.symlink(entry.target, fixed_path)
  131. else:
  132. raise TypeError('unknown entry type')
  133. # Fix up permissions if needbe.
  134. # TODO(davidben): To be extra tidy, this should only track the execute bit
  135. # as in git.
  136. if entry.mode is not None:
  137. os.chmod(fixed_path, entry.mode)
  138. # Print every 100 files, so bots do not time out on large archives.
  139. num_extracted += 1
  140. if num_extracted % 100 == 0:
  141. print "Extracted %d files..." % (num_extracted,)
  142. finally:
  143. entries.close()
  144. with open(stamp_path, 'w') as f:
  145. f.write(digest)
  146. print "Done. Extracted %d files." % (num_extracted,)
  147. return 0
  148. if __name__ == '__main__':
  149. sys.exit(main(sys.argv[1:]))