blob: 386298ebcca2fc0c235ba8a7a47cb30c605baab8 [file] [log] [blame]
Nan Zhangdb0b9a32017-02-27 10:12:13 -08001#!/usr/bin/env python
2
3import os
4import re
5import tempfile
6import shutil
7import sys
8import subprocess
9import zipfile
10
11PYTHON_BINARY = '%interpreter%'
12MAIN_FILE = '%main%'
13PYTHON_PATH = 'PYTHONPATH'
14ZIP_RUNFILES_DIRECTORY_NAME = 'runfiles'
15
16def SearchPathEnv(name):
17 search_path = os.getenv('PATH', os.defpath).split(os.pathsep)
18 for directory in search_path:
19 if directory == '': continue
20 path = os.path.join(directory, name)
Nan Zhangdb0b9a32017-02-27 10:12:13 -080021 # Check if path is actual executable file.
22 if os.path.isfile(path) and os.access(path, os.X_OK):
23 return path
24 return None
25
26def FindPythonBinary():
27 if PYTHON_BINARY.startswith('/'):
28 # Case 1: Python interpreter is directly provided with absolute path.
29 return PYTHON_BINARY
30 else:
31 # Case 2: Find Python interpreter through environment variable: PATH.
32 return SearchPathEnv(PYTHON_BINARY)
33
34# Create the runfiles tree by extracting the zip file
35def ExtractRunfiles():
36 temp_dir = tempfile.mkdtemp("", "Soong.python_")
37 zf = zipfile.ZipFile(os.path.dirname(__file__))
38 zf.extractall(temp_dir)
39 return os.path.join(temp_dir, ZIP_RUNFILES_DIRECTORY_NAME)
40
41def Main():
42 args = sys.argv[1:]
43
44 new_env = {}
45
46 try:
47 runfiles_path = ExtractRunfiles()
48
49 # Add runfiles path to PYTHONPATH.
50 python_path_entries = [runfiles_path]
51
52 # Add top dirs within runfiles path to PYTHONPATH.
53 top_entries = [os.path.join(runfiles_path, i) for i in os.listdir(runfiles_path)]
54 top_pkg_dirs = [i for i in top_entries if os.path.isdir(i)]
55 python_path_entries += top_pkg_dirs
56
57 old_python_path = os.environ.get(PYTHON_PATH)
58 separator = ':'
59 new_python_path = separator.join(python_path_entries)
60
61 # Copy old PYTHONPATH.
62 if old_python_path:
63 new_python_path += separator + old_python_path
64 new_env[PYTHON_PATH] = new_python_path
65
66 # Now look for main python source file.
67 main_filepath = os.path.join(runfiles_path, MAIN_FILE)
68 assert os.path.exists(main_filepath), \
69 'Cannot exec() %r: file not found.' % main_filepath
70 assert os.access(main_filepath, os.R_OK), \
71 'Cannot exec() %r: file not readable.' % main_filepath
72
73 python_program = FindPythonBinary()
74 if python_program is None:
75 raise AssertionError('Could not find python binary: ' + PYTHON_BINARY)
76 args = [python_program, main_filepath] + args
77
78 os.environ.update(new_env)
79
80 sys.stdout.flush()
81 retCode = subprocess.call(args)
82 exit(retCode)
83 except:
84 raise
85 finally:
86 shutil.rmtree(os.path.dirname(runfiles_path), True)
87
88if __name__ == '__main__':
89 Main()