1#!/usr/bin/env python
2# Copyright 2015 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
6"""Wrapper script to run java command as action with gn."""
7
8import os
9import subprocess
10import sys
11
12EXIT_SUCCESS = 0
13EXIT_FAILURE = 1
14
15
16def IsExecutable(path):
17  """Returns whether file at |path| exists and is executable.
18
19  Args:
20    path: absolute or relative path to test.
21
22  Returns:
23    True if the file at |path| exists, False otherwise.
24  """
25  return os.path.isfile(path) and os.access(path, os.X_OK)
26
27
28def FindCommand(command):
29  """Looks up for |command| in PATH.
30
31  Args:
32    command: name of the command to lookup, if command is a relative or
33      absolute path (i.e. contains some path separator) then only that
34      path will be tested.
35
36  Returns:
37    Full path to command or None if the command was not found.
38
39    On Windows, this respects the PATHEXT environment variable when the
40    command name does not have an extension.
41  """
42  fpath, _ = os.path.split(command)
43  if fpath:
44    if IsExecutable(command):
45      return command
46
47  if sys.platform == 'win32':
48    # On Windows, if the command does not have an extension, cmd.exe will
49    # try all extensions from PATHEXT when resolving the full path.
50    command, ext = os.path.splitext(command)
51    if not ext:
52      exts = os.environ['PATHEXT'].split(os.path.pathsep)
53    else:
54      exts = [ext]
55  else:
56    exts = ['']
57
58  for path in os.environ['PATH'].split(os.path.pathsep):
59    for ext in exts:
60      path = os.path.join(path, command) + ext
61      if IsExecutable(path):
62        return path
63
64  return None
65
66
67def main():
68  java_path = FindCommand('java')
69  if not java_path:
70    sys.stderr.write('java: command not found\n')
71    sys.exit(EXIT_FAILURE)
72
73  args = sys.argv[1:]
74  if len(args) < 2 or args[0] != '-jar':
75    sys.stderr.write('usage: %s -jar JARPATH [java_args]...\n' % sys.argv[0])
76    sys.exit(EXIT_FAILURE)
77
78  return subprocess.check_call([java_path] + args)
79
80
81if __name__ == '__main__':
82  sys.exit(main())
83