1#!/usr/bin/env python
2#
3# Copyright 2014 The Chromium Authors. All rights reserved.
4# Use of this source code is governed by a BSD-style license that can be
5# found in the LICENSE file.
6
7# TODO(brettw) bug 582594: merge this with build/android/gn/zip.py and update
8# callers to use the existing template rather than invoking this directly.
9
10"""Archives a set of files.
11"""
12
13import optparse
14import os
15import sys
16import zipfile
17
18sys.path.append(os.path.join(os.path.dirname(__file__),
19                             os.pardir, os.pardir, os.pardir, os.pardir,
20                             "build"))
21import gn_helpers
22
23sys.path.append(os.path.join(os.path.dirname(__file__),
24                             os.pardir, os.pardir, os.pardir, os.pardir,
25                             'build', 'android', 'gyp'))
26from util import build_utils
27
28
29def DoZip(inputs, link_inputs, zip_inputs, output, base_dir):
30  files = []
31  with zipfile.ZipFile(output, 'w', zipfile.ZIP_DEFLATED) as outfile:
32    for f in inputs:
33      file_name = os.path.relpath(f, base_dir)
34      files.append(file_name)
35      build_utils.AddToZipHermetic(outfile, file_name, f)
36    for f in link_inputs:
37      realf = os.path.realpath(f)  # Resolve symlinks.
38      file_name = os.path.relpath(realf, base_dir)
39      files.append(file_name)
40      build_utils.AddToZipHermetic(outfile, file_name, realf)
41    for zf_name in zip_inputs:
42      with zipfile.ZipFile(zf_name, 'r') as zf:
43        for f in zf.namelist():
44          if f not in files:
45            files.append(f)
46            build_utils.AddToZipHermetic(outfile, f, data=zf.read(f))
47
48
49def main():
50  parser = optparse.OptionParser()
51
52  parser.add_option('--inputs',
53      help='GN format list of files to archive.')
54  parser.add_option('--link-inputs',
55      help='GN-format list of files to archive. Symbolic links are resolved.')
56  parser.add_option('--zip-inputs',
57      help='GN-format list of zip files to re-archive.')
58  parser.add_option('--output', help='Path to output archive.')
59  parser.add_option('--base-dir',
60                    help='If provided, the paths in the archive will be '
61                    'relative to this directory', default='.')
62
63  options, _ = parser.parse_args()
64
65  inputs = []
66  if (options.inputs):
67    parser = gn_helpers.GNValueParser(options.inputs)
68    inputs = parser.ParseList()
69
70  link_inputs = []
71  if options.link_inputs:
72    parser = gn_helpers.GNValueParser(options.link_inputs)
73    link_inputs = parser.ParseList()
74
75  zip_inputs = []
76  if options.zip_inputs:
77    parser = gn_helpers.GNValueParser(options.zip_inputs)
78    zip_inputs = parser.ParseList()
79
80  output = options.output
81  base_dir = options.base_dir
82
83  DoZip(inputs, link_inputs, zip_inputs, output, base_dir)
84
85if __name__ == '__main__':
86  sys.exit(main())
87