25개 이상의 토픽을 선택하실 수 없습니다. Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
 
 
 
 

140 lines
4.1 KiB

  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 optparse
  16. import os
  17. import os.path
  18. import tarfile
  19. import shutil
  20. import sys
  21. import zipfile
  22. def CheckedJoin(output, path):
  23. """
  24. CheckedJoin returns os.path.join(output, path). It does sanity checks to
  25. ensure the resulting path is under output, but shouldn't be used on untrusted
  26. input.
  27. """
  28. path = os.path.normpath(path)
  29. if os.path.isabs(path) or path.startswith('.'):
  30. raise ValueError(path)
  31. return os.path.join(output, path)
  32. def IterateZip(path):
  33. """
  34. IterateZip opens the zip file at path and returns a generator of
  35. (filename, mode, fileobj) tuples for each file in it.
  36. """
  37. with zipfile.ZipFile(path, 'r') as zip_file:
  38. for info in zip_file.infolist():
  39. if info.filename.endswith('/'):
  40. continue
  41. yield (info.filename, None, zip_file.open(info))
  42. def IterateTar(path):
  43. """
  44. IterateTar opens the tar.gz file at path and returns a generator of
  45. (filename, mode, fileobj) tuples for each file in it.
  46. """
  47. with tarfile.open(path, 'r:gz') as tar_file:
  48. for info in tar_file:
  49. if info.isdir():
  50. continue
  51. if not info.isfile():
  52. raise ValueError('Unknown entry type "%s"' % (info.name, ))
  53. yield (info.name, info.mode, tar_file.extractfile(info))
  54. def main(args):
  55. parser = optparse.OptionParser(usage='Usage: %prog ARCHIVE OUTPUT')
  56. parser.add_option('--no-prefix', dest='no_prefix', action='store_true',
  57. help='Do not remove a prefix from paths in the archive.')
  58. options, args = parser.parse_args(args)
  59. if len(args) != 2:
  60. parser.print_help()
  61. return 1
  62. archive, output = args
  63. if not os.path.exists(archive):
  64. # Skip archives that weren't downloaded.
  65. return 0
  66. if archive.endswith('.zip'):
  67. entries = IterateZip(archive)
  68. elif archive.endswith('.tar.gz'):
  69. entries = IterateTar(archive)
  70. else:
  71. raise ValueError(archive)
  72. try:
  73. if os.path.exists(output):
  74. print "Removing %s" % (output, )
  75. shutil.rmtree(output)
  76. print "Extracting %s to %s" % (archive, output)
  77. prefix = None
  78. num_extracted = 0
  79. for path, mode, inp in entries:
  80. # Even on Windows, zip files must always use forward slashes.
  81. if '\\' in path or path.startswith('/'):
  82. raise ValueError(path)
  83. if not options.no_prefix:
  84. new_prefix, rest = path.split('/', 1)
  85. # Ensure the archive is consistent.
  86. if prefix is None:
  87. prefix = new_prefix
  88. if prefix != new_prefix:
  89. raise ValueError((prefix, new_prefix))
  90. else:
  91. rest = path
  92. # Extract the file into the output directory.
  93. fixed_path = CheckedJoin(output, rest)
  94. if not os.path.isdir(os.path.dirname(fixed_path)):
  95. os.makedirs(os.path.dirname(fixed_path))
  96. with open(fixed_path, 'wb') as out:
  97. shutil.copyfileobj(inp, out)
  98. # Fix up permissions if needbe.
  99. # TODO(davidben): To be extra tidy, this should only track the execute bit
  100. # as in git.
  101. if mode is not None:
  102. os.chmod(fixed_path, mode)
  103. # Print every 100 files, so bots do not time out on large archives.
  104. num_extracted += 1
  105. if num_extracted % 100 == 0:
  106. print "Extracted %d files..." % (num_extracted,)
  107. finally:
  108. entries.close()
  109. if num_extracted % 100 == 0:
  110. print "Done. Extracted %d files." % (num_extracted,)
  111. return 0
  112. if __name__ == '__main__':
  113. sys.exit(main(sys.argv[1:]))