1#!/usr/bin/python
2# Copyright 2014 The Chromium Authors. All rights reserved.
3# Use of this source code is governed by a BSD-style license that can be
4# found in the LICENSE file.
5
6import os
7import shutil
8import subprocess
9import sys
10import tempfile
11
12
13def rel_to_abs(rel_path):
14  script_path = os.path.dirname(os.path.abspath(__file__))
15  return os.path.join(script_path, rel_path)
16
17
18java_bin_path = os.getenv('JAVA_HOME', '')
19if java_bin_path:
20  java_bin_path = os.path.join(java_bin_path, 'bin')
21
22main_class = 'org.chromium.closure.compiler.Runner'
23jar_name = 'runner.jar'
24src_dir = 'src'
25closure_jar_relpath = os.path.join('..', 'compiler', 'compiler.jar')
26src_path = rel_to_abs(src_dir)
27
28
29def run_and_communicate(command, error_template):
30  print >> sys.stderr, command
31  proc = subprocess.Popen(command, stdout=subprocess.PIPE, shell=True)
32  proc.communicate()
33  if proc.returncode:
34    print >> sys.stderr, error_template % proc.returncode
35    sys.exit(proc.returncode)
36
37
38def build_artifacts():
39  print 'Compiling...'
40  java_files = []
41  for root, dirs, files in sorted(os.walk(src_path)):
42    for file_name in files:
43      java_files.append(os.path.join(root, file_name))
44
45  bin_path = tempfile.mkdtemp()
46  manifest_file = tempfile.NamedTemporaryFile(mode='wt', delete=False)
47  try:
48    manifest_file.write('Class-Path: %s\n' % closure_jar_relpath)
49    manifest_file.close()
50    javac_path = os.path.join(java_bin_path, 'javac')
51    javac_command = '%s -d %s -cp %s %s' % (
52        javac_path, bin_path, rel_to_abs(closure_jar_relpath),
53        ' '.join(java_files))
54    run_and_communicate(javac_command, 'Error: javac returned %d')
55
56    print 'Building jar...'
57    artifact_path = rel_to_abs(jar_name)
58    jar_path = os.path.join(java_bin_path, 'jar')
59    jar_command = '%s cvfme %s %s %s -C %s .' % (
60        jar_path, artifact_path, manifest_file.name, main_class, bin_path)
61    run_and_communicate(jar_command, 'Error: jar returned %d')
62  finally:
63    os.remove(manifest_file.name)
64    shutil.rmtree(bin_path, True)
65
66  print 'Done.'
67
68
69def show_usage_and_die():
70  print 'usage: %s' % os.path.basename(__file__)
71  print 'Builds runner.jar from the %s directory contents' % src_dir
72  sys.exit(1)
73
74
75def main():
76  if len(sys.argv) > 1:
77    show_usage_and_die()
78
79  build_artifacts()
80
81
82if __name__ == '__main__':
83  main()
84