1# Copyright (C) 2017 The Android Open Source Project
2#
3# Licensed under the Apache License, Version 2.0 (the "License");
4# you may not use this file except in compliance with the License.
5# You may obtain a copy of the License at
6#
7#      http://www.apache.org/licenses/LICENSE-2.0
8#
9# Unless required by applicable law or agreed to in writing, software
10# distributed under the License is distributed on an "AS IS" BASIS,
11# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12# See the License for the specific language governing permissions and
13# limitations under the License.
14""" Wrapper to invoke compiled build tools from the build system.
15
16This is just a workaround for GN assuming that all external scripts are
17python sources. It is used to invoke tools like the protoc compiler.
18"""
19
20from __future__ import print_function
21
22import argparse
23import os
24import subprocess
25import sys
26
27
28def main():
29  parser = argparse.ArgumentParser()
30  parser.add_argument('--chdir', default=None)
31  parser.add_argument('--stamp', default=None)
32  parser.add_argument('--path', default=None)
33  parser.add_argument('--noop', default=False, action='store_true')
34  parser.add_argument('--suppress_stdout', default=False, action='store_true')
35  parser.add_argument('--suppress_stderr', default=False, action='store_true')
36  parser.add_argument('cmd', nargs=argparse.REMAINDER)
37  args = parser.parse_args()
38
39  if args.noop:
40    return 0
41
42  if args.chdir and not os.path.exists(args.chdir):
43    print(
44        'Cannot chdir to %s from %s' % (workdir, os.getcwd()), file=sys.stderr)
45    return 1
46
47  exe = os.path.abspath(args.cmd[0]) if os.sep in args.cmd[0] else args.cmd[0]
48  env = os.environ.copy()
49  if args.path:
50    env['PATH'] = os.path.abspath(args.path) + os.pathsep + env['PATH']
51
52  devnull = open(os.devnull, 'wb')
53  stdout = devnull if args.suppress_stdout else None
54  stderr = devnull if args.suppress_stderr else None
55
56  try:
57    proc = subprocess.Popen(
58        [exe] + args.cmd[1:],
59        cwd=args.chdir,
60        env=env,
61        stderr=stderr,
62        stdout=stdout)
63    ret = proc.wait()
64    if ret == 0 and args.stamp:
65      with open(args.stamp, 'w'):
66        os.utime(args.stamp, None)
67    return ret
68  except OSError as e:
69    print('Error running: "%s" (%s)' % (args.cmd[0], e.strerror))
70    print('PATH=%s' % env.get('PATH'))
71    return 127
72
73
74if __name__ == '__main__':
75  sys.exit(main())
76