• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
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"""
8Concatenates module scripts based on the module.json descriptor.
9Optionally, minifies the result using rjsmin.
10"""
11
12from cStringIO import StringIO
13from os import path
14import os
15import re
16import sys
17
18try:
19    import simplejson as json
20except ImportError:
21    import json
22
23rjsmin_path = path.abspath(path.join(
24        path.dirname(__file__),
25        '..',
26        '..',
27        'build',
28        'scripts'))
29sys.path.append(rjsmin_path)
30import rjsmin
31
32
33def read_file(filename):
34    with open(path.normpath(filename), 'rt') as file:
35        return file.read()
36
37
38def write_file(filename, content):
39    # This is here to avoid overwriting source tree files due to hard links.
40    if path.exists(filename):
41        os.remove(filename)
42    with open(filename, 'wt') as file:
43        file.write(content)
44
45
46def concatenate_scripts(file_names, module_dir, output_dir, output):
47    for file_name in file_names:
48        output.write('/* %s */\n' % file_name)
49        file_path = path.join(module_dir, file_name)
50
51        # This allows to also concatenate generated files found in output_dir.
52        if not path.isfile(file_path):
53            file_path = path.join(output_dir, path.basename(module_dir), file_name)
54        output.write(read_file(file_path))
55        output.write(';')
56
57
58def main(argv):
59    if len(argv) < 3:
60        print('Usage: %s module_json output_file no_minify' % argv[0])
61        return 1
62
63    module_json_file_name = argv[1]
64    output_file_name = argv[2]
65    no_minify = len(argv) > 3 and argv[3]
66    module_dir = path.dirname(module_json_file_name)
67
68    output = StringIO()
69    descriptor = None
70    try:
71        descriptor = json.loads(read_file(module_json_file_name))
72    except:
73        print 'ERROR: Failed to load JSON from ' + module_json_file_name
74        raise
75
76    # pylint: disable=E1103
77    scripts = descriptor.get('scripts')
78    assert(scripts)
79    output_root_dir = path.join(path.dirname(output_file_name), '..')
80    concatenate_scripts(scripts, module_dir, output_root_dir, output)
81
82    output_script = output.getvalue()
83    output.close()
84    write_file(output_file_name, output_script if no_minify else rjsmin.jsmin(output_script))
85
86if __name__ == '__main__':
87    sys.exit(main(sys.argv))
88