| OLD | NEW |
| (Empty) |
| 1 # Copyright (c) 2010 The Chromium Authors. All rights reserved. | |
| 2 # Use of this source code is governed by a BSD-style license that can be | |
| 3 # found in the LICENSE file. | |
| 4 | |
| 5 """Creates a zip archive with relative entry paths, from a list of files with | |
| 6 absolute paths. | |
| 7 """ | |
| 8 | |
| 9 import sys | |
| 10 import zipfile | |
| 11 | |
| 12 def add_files_to_zip(zip_file, base_dir, files): | |
| 13 """Pack a list of files into a zip archive, that is already | |
| 14 opened for writing. | |
| 15 | |
| 16 Args: | |
| 17 zip_file: An object representing the zip archive. | |
| 18 base_dir: A path that will be stripped from the beginning of the paths of | |
| 19 added files. | |
| 20 files: The list of file paths to add. | |
| 21 """ | |
| 22 prefix_len = len(base_dir) | |
| 23 | |
| 24 for file_path in files: | |
| 25 if not file_path.startswith(base_dir): | |
| 26 print "All the input files should be in the base directory." | |
| 27 return 1 | |
| 28 entry_path = file_path[prefix_len:] | |
| 29 zip_file.write(file_path, entry_path) | |
| 30 | |
| 31 return 0 | |
| 32 | |
| 33 | |
| 34 def main(zip_path, base_dir, files): | |
| 35 """Pack a list of files into a zip archive. | |
| 36 | |
| 37 Args: | |
| 38 zip_path: The file name of the zip archive. | |
| 39 base_dir: A path that will be stripped from the beginning of the paths of | |
| 40 added files. | |
| 41 files: The list of file paths to add. | |
| 42 | |
| 43 Example: | |
| 44 main('x.zip', '/a/b', ['/a/b/c/1.txt', '/a/b/d/2.txt']) | |
| 45 Will put the following entries to x.zip: | |
| 46 c/1.txt | |
| 47 d/2.txt | |
| 48 """ | |
| 49 if (base_dir[-1] != '/'): | |
| 50 base_dir = base_dir + '/' | |
| 51 | |
| 52 zip_file = zipfile.ZipFile(zip_path, 'w', zipfile.ZIP_DEFLATED) | |
| 53 try: | |
| 54 return add_files_to_zip(zip_file, base_dir, files) | |
| 55 finally: | |
| 56 zip_file.close() | |
| 57 | |
| 58 if '__main__' == __name__: | |
| 59 if len(sys.argv) < 4: | |
| 60 print "usage: %s output.zip path/to/base/dir list of files" % sys.argv[0] | |
| 61 sys.exit(1) | |
| 62 | |
| 63 sys.exit(main(sys.argv[1], sys.argv[2], sys.argv[3:])) | |
| OLD | NEW |