Debian Codegraph @

mesonbuild/scripts/meson_exe.py

raw
1 # SPDX-License-Identifier: Apache-2.0
2 # Copyright 2013-2016 The Meson development team
3
4 from __future__ import annotations
5
6 import os
7 import sys
8 import argparse
9 import pickle
10 import subprocess
11 import typing as T
12 import locale
13
14 from ..utils.core import ExecutableSerialisation
15
16 def buildparser() -> argparse.ArgumentParser:
17 parser = argparse.ArgumentParser(description='Custom executable wrapper for Meson. Do not run on your own, mmm\'kay?')
18 parser.add_argument('--unpickle')
19 parser.add_argument('--capture')
20 parser.add_argument('--feed')
21 return parser
22
23 def run_exe(exe: ExecutableSerialisation, extra_env: T.Optional[T.Dict[str, str]] = None) -> int:
24 if exe.exe_wrapper:
25 if not exe.exe_wrapper.found():
26 raise AssertionError('BUG: Can\'t run cross-compiled exe {!r} with not-found '
27 'wrapper {!r}'.format(exe.cmd_args[0], exe.exe_wrapper.get_path()))
28 cmd_args = exe.exe_wrapper.get_command() + exe.cmd_args
29 else:
30 cmd_args = exe.cmd_args
31 child_env = os.environ.copy()
32 if extra_env:
33 child_env.update(extra_env)
34 if exe.env:
35 child_env = exe.env.get_env(child_env)
36 if exe.extra_paths:
37 child_env['PATH'] = (os.pathsep.join(exe.extra_paths + ['']) +
38 child_env['PATH'])
39 if exe.exe_wrapper and any('wine' in i for i in exe.exe_wrapper.get_command()):
40 from .. import mesonlib
41 child_env['WINEPATH'] = mesonlib.get_wine_shortpath(
42 exe.exe_wrapper.get_command(),
43 ['Z:' + p for p in exe.extra_paths] + child_env.get('WINEPATH', '').split(';'),
44 exe.workdir
45 )
46
47 stdin = None
48 if exe.feed:
49 stdin = open(exe.feed, 'rb')
50
51 pipe = subprocess.PIPE
52 if exe.verbose:
53 assert not exe.capture, 'Cannot capture and print to console at the same time'
54 pipe = None
55
56 p = subprocess.Popen(cmd_args, env=child_env, cwd=exe.workdir,
57 close_fds=False, stdin=stdin, stdout=pipe, stderr=pipe)
58 stdout, stderr = p.communicate()
59
60 if stdin is not None:
61 stdin.close()
62
63 if p.returncode == 0xc0000135:
64 # STATUS_DLL_NOT_FOUND on Windows indicating a common problem that is otherwise hard to diagnose
65 strerror = 'Failed to run due to missing DLLs, with path: ' + child_env['PATH']
66 raise FileNotFoundError(p.returncode, strerror, cmd_args)
67
68 if p.returncode != 0:
69 if exe.pickled:
70 print(f'while executing {cmd_args!r}')
71 if exe.verbose:
72 return p.returncode
73 encoding = locale.getpreferredencoding()
74 if not exe.capture:
75 print('--- stdout ---')
76 print(stdout.decode(encoding=encoding, errors='replace'))
77 print('--- stderr ---')
78 print(stderr.decode(encoding=encoding, errors='replace'))
79 return p.returncode
80 elif stderr: # Allow a wrapped subprocess to gracefully communicate warnings
81 encoding = locale.getpreferredencoding()
82 print(stderr.decode(encoding=encoding, errors='replace'))
83
84 if exe.capture:
85 skip_write = False
86 try:
87 with open(exe.capture, 'rb') as cur:
88 skip_write = cur.read() == stdout
89 except OSError:
90 pass
91 if not skip_write:
92 with open(exe.capture, 'wb') as output:
93 output.write(stdout)
94
95 return 0
96
97 def run(args: T.List[str]) -> int:
98 parser = buildparser()
99 options, cmd_args = parser.parse_known_args(args)
100 # argparse supports double dash to separate options and positional arguments,
101 # but the user has to remove it manually.
102 if cmd_args and cmd_args[0] == '--':
103 cmd_args = cmd_args[1:]
104 if not options.unpickle and not cmd_args:
105 parser.error('either --unpickle or executable and arguments are required')
106 if options.unpickle:
107 if cmd_args or options.capture or options.feed:
108 parser.error('no other arguments can be used with --unpickle')
109 with open(options.unpickle, 'rb') as f:
110 exe = pickle.load(f)
111 exe.pickled = True
112 else:
113 exe = ExecutableSerialisation(cmd_args, capture=options.capture, feed=options.feed)
114
115 return run_exe(exe)
116
117 if __name__ == '__main__':
118 sys.exit(run(sys.argv[1:]))