commandrunner.py 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354
  1. #!/usr/bin/env python3
  2. # Copyright 2014 The Meson development team
  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. # http://www.apache.org/licenses/LICENSE-2.0
  7. # Unless required by applicable law or agreed to in writing, software
  8. # distributed under the License is distributed on an "AS IS" BASIS,
  9. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  10. # See the License for the specific language governing permissions and
  11. # limitations under the License.
  12. """This program is a wrapper to run external commands. It determines
  13. what to run, sets up the environment and executes the command."""
  14. import sys, os, subprocess, shutil
  15. def run_command(source_dir, build_dir, subdir, command, arguments):
  16. env = {'MESON_SOURCE_ROOT' : source_dir,
  17. 'MESON_BUILD_ROOT' : build_dir,
  18. 'MESON_SUBDIR' : subdir
  19. }
  20. cwd = os.path.join(source_dir, subdir)
  21. child_env = os.environ.copy()
  22. child_env.update(env)
  23. # Is the command an executable in path?
  24. exe = shutil.which(command)
  25. if exe is not None:
  26. command_array = [exe] + arguments
  27. return subprocess.Popen(command_array, env=child_env, cwd=cwd)
  28. # No? Maybe it is a script in the source tree.
  29. fullpath = os.path.join(source_dir, subdir, command)
  30. command_array = [fullpath] + arguments
  31. try:
  32. return subprocess.Popen(command_array,env=child_env, cwd=cwd)
  33. except FileNotFoundError:
  34. print('Could not execute command "%s".' % command)
  35. sys.exit(1)
  36. if __name__ == '__main__':
  37. if len(sys.argv) < 5:
  38. print(sys.argv[0], '<source dir> <build dir> <subdir> <command> [arguments]')
  39. src_dir = sys.argv[1]
  40. build_dir = sys.argv[2]
  41. subdir = sys.argv[3]
  42. command = sys.argv[4]
  43. arguments = sys.argv[5:]
  44. sys.exit(run_command(src_dir, build_dir, subdir, command, arguments).returncode)