summaryrefslogtreecommitdiff
path: root/chromium/chrome/browser/resources/chromeos/chromevox/tools/jscompilerwrapper.py
blob: fb4b80dfad74cfe086a9d8b65c5ef7f392efebff (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
#!/usr/bin/env python

# Copyright 2014 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.

'''Uses the closure compiler to check syntax and semantics of a js module
with dependencies.'''

import os
import re
import subprocess
import sys

_SCRIPT_DIR = os.path.dirname(os.path.abspath(__file__))
_CHROME_SOURCE_DIR = os.path.normpath(
    os.path.join(
        _SCRIPT_DIR, *[os.path.pardir] * 6))

# Compiler path.
_CLOSURE_COMPILER_JAR = os.path.join(
    _CHROME_SOURCE_DIR, 'third_party', 'closure_compiler', 'compiler',
    'compiler.jar')

# List of compilation errors to enable with the --jscomp_errors flag.
_JSCOMP_ERRORS = [ 'accessControls', 'checkTypes', 'checkVars', 'invalidCasts',
                   'missingProperties', 'undefinedNames', 'undefinedVars',
                   'visibility' ]

_java_executable = 'java'


def _Error(msg):
  print >>sys.stderr, msg
  sys.exit(1)


def _ExecuteCommand(args, ignore_exit_status=False):
  try:
    return subprocess.check_output(args, stderr=subprocess.STDOUT)
  except subprocess.CalledProcessError as e:
    if ignore_exit_status and e.returncode > 0:
      return e.output
    _Error('%s\nCommand \'%s\' returned non-zero exit status %d' %
           (e.output, ' '.join(e.cmd), e.returncode))
  except (OSError, IOError) as e:
    _Error('Error executing %s: %s' % (_java_executable, str(e)))


def _CheckJava():
  global _java_executable
  java_home = os.environ.get('JAVAHOME')
  if java_home is not None:
    _java_executable = os.path.join(java_home, 'bin', 'java')
  output = _ExecuteCommand([_java_executable, '-version'])
  match = re.search(r'version "(?:\d+)\.(\d+)', output)
  if match is None or int(match.group(1)) < 7:
    _Error('Java 7 or later is required: \n%s' % output)

_CheckJava()


def RunCompiler(js_files, externs=[]):
  args = [_java_executable, '-jar', _CLOSURE_COMPILER_JAR]
  args.extend(['--compilation_level', 'SIMPLE_OPTIMIZATIONS'])
  args.extend(['--jscomp_error=%s' % error for error in _JSCOMP_ERRORS])
  args.extend(['--language_in', 'ECMASCRIPT5'])
  args.extend(['--externs=%s' % extern for extern in externs])
  args.extend(['--js=%s' % js for js in js_files])
  args.extend(['--js_output_file', '/dev/null'])
  output = _ExecuteCommand(args, ignore_exit_status=True)
  success = len(output) == 0
  return success, output