Debian Codegraph @

mesonbuild/cmake/executor.py

raw
1 # SPDX-License-Identifier: Apache-2.0
2 # Copyright 2019 The Meson development team
3
4 from __future__ import annotations
5
6 import subprocess as S
7 from threading import Thread
8 import typing as T
9 import re
10 import os
11
12 from .. import mlog
13 from ..mesonlib import PerMachine, Popen_safe, version_compare, is_windows
14 from ..options import OptionKey
15 from ..programs import find_external_program, NonExistingExternalProgram
16
17 if T.TYPE_CHECKING:
18 from pathlib import Path
19
20 from ..environment import Environment
21 from ..mesonlib import MachineChoice
22 from ..programs import ExternalProgram
23
24 TYPE_result = T.Tuple[int, T.Optional[str], T.Optional[str]]
25 TYPE_cache_key = T.Tuple[str, T.Tuple[str, ...], str, T.FrozenSet[T.Tuple[str, str]]]
26
27 class CMakeExecutor:
28 # The class's copy of the CMake path. Avoids having to search for it
29 # multiple times in the same Meson invocation.
30 class_cmakebin: PerMachine[T.Optional[ExternalProgram]] = PerMachine(None, None)
31 class_cmakevers: PerMachine[T.Optional[str]] = PerMachine(None, None)
32 class_cmake_cache: T.Dict[T.Any, TYPE_result] = {}
33
34 def __init__(self, environment: 'Environment', version: str, for_machine: MachineChoice, silent: bool = False):
35 self.min_version = version
36 self.environment = environment
37 self.for_machine = for_machine
38 self.cmakebin, self.cmakevers = self.find_cmake_binary(self.environment, silent=silent)
39 self.always_capture_stderr = True
40 self.print_cmout = False
41 self.prefix_paths: T.List[str] = []
42 self.extra_cmake_args: T.List[str] = []
43
44 if self.cmakebin is None:
45 return
46
47 if not version_compare(self.cmakevers, self.min_version):
48 mlog.warning(
49 'The version of CMake', mlog.bold(self.cmakebin.get_path()),
50 'is', mlog.bold(self.cmakevers), 'but version', mlog.bold(self.min_version),
51 'is required')
52 self.cmakebin = None
53 return
54
55 prefpath = self.environment.coredata.optstore.get_value_for(
56 OptionKey(name='cmake_prefix_path', machine=for_machine))
57 assert isinstance(prefpath, list)
58 self.prefix_paths = prefpath
59 if self.prefix_paths:
60 self.extra_cmake_args += ['-DCMAKE_PREFIX_PATH={}'.format(';'.join(self.prefix_paths))]
61
62 def find_cmake_binary(self, environment: 'Environment', silent: bool = False) -> T.Tuple[T.Optional['ExternalProgram'], T.Optional[str]]:
63 # Only search for CMake the first time and store the result in the class
64 # definition
65 if isinstance(CMakeExecutor.class_cmakebin[self.for_machine], NonExistingExternalProgram):
66 mlog.debug(f'CMake binary for {self.for_machine} is cached as not found')
67 return None, None
68 elif CMakeExecutor.class_cmakebin[self.for_machine] is not None:
69 mlog.debug(f'CMake binary for {self.for_machine} is cached.')
70 else:
71 assert CMakeExecutor.class_cmakebin[self.for_machine] is None
72
73 mlog.debug(f'CMake binary for {self.for_machine} is not cached')
74 for potential_cmakebin in find_external_program(
75 environment, self.for_machine, 'cmake', 'CMake',
76 environment.default_cmake, allow_default_for_cross=False):
77 version_if_ok = self.check_cmake(potential_cmakebin)
78 if not version_if_ok:
79 continue
80 if not silent:
81 mlog.log('Found CMake:', mlog.bold(potential_cmakebin.get_path()),
82 f'({version_if_ok})')
83 CMakeExecutor.class_cmakebin[self.for_machine] = potential_cmakebin
84 CMakeExecutor.class_cmakevers[self.for_machine] = version_if_ok
85 break
86 else:
87 if not silent:
88 mlog.log('Found CMake:', mlog.red('NO'))
89 # Set to False instead of None to signify that we've already
90 # searched for it and not found it
91 CMakeExecutor.class_cmakebin[self.for_machine] = NonExistingExternalProgram()
92 CMakeExecutor.class_cmakevers[self.for_machine] = None
93 return None, None
94
95 return CMakeExecutor.class_cmakebin[self.for_machine], CMakeExecutor.class_cmakevers[self.for_machine]
96
97 def check_cmake(self, cmakebin: 'ExternalProgram') -> T.Optional[str]:
98 if not cmakebin.found():
99 mlog.log(f'Did not find CMake {cmakebin.name!r}')
100 return None
101 try:
102 cmd = cmakebin.get_command()
103 p, out = Popen_safe(cmd + ['--version'])[0:2]
104 if p.returncode != 0:
105 mlog.warning('Found CMake {!r} but couldn\'t run it'
106 ''.format(' '.join(cmd)))
107 return None
108 except FileNotFoundError:
109 mlog.warning('We thought we found CMake {!r} but now it\'s not there. How odd!'
110 ''.format(' '.join(cmd)))
111 return None
112 except PermissionError:
113 msg = 'Found CMake {!r} but didn\'t have permissions to run it.'.format(' '.join(cmd))
114 if not is_windows():
115 msg += '\n\nOn Unix-like systems this is often caused by scripts that are not executable.'
116 mlog.warning(msg)
117 return None
118
119 cmvers = re.search(r'(cmake|cmake3)\s*version\s*([\d.]+)', out)
120 if cmvers is not None:
121 return cmvers.group(2)
122 mlog.warning(f'We thought we found CMake {cmd!r}, but it was missing the expected '
123 'version string in its output.')
124 return None
125
126 def set_exec_mode(self, print_cmout: T.Optional[bool] = None, always_capture_stderr: T.Optional[bool] = None) -> None:
127 if print_cmout is not None:
128 self.print_cmout = print_cmout
129 if always_capture_stderr is not None:
130 self.always_capture_stderr = always_capture_stderr
131
132 def _cache_key(self, args: T.List[str], build_dir: Path, env: T.Optional[T.Dict[str, str]]) -> TYPE_cache_key:
133 fenv = frozenset(env.items()) if env is not None else frozenset()
134 targs = tuple(args)
135 return (self.cmakebin.get_path(), targs, build_dir.as_posix(), fenv)
136
137 def _call_cmout_stderr(self, args: T.List[str], build_dir: Path, env: T.Optional[T.Dict[str, str]]) -> TYPE_result:
138 cmd = self.cmakebin.get_command() + args
139 proc = S.Popen(cmd, stdout=S.PIPE, stderr=S.PIPE, cwd=str(build_dir), env=env) # TODO [PYTHON_37]: drop Path conversion
140
141 # stdout and stderr MUST be read at the same time to avoid pipe
142 # blocking issues. The easiest way to do this is with a separate
143 # thread for one of the pipes.
144 def print_stdout() -> None:
145 while True:
146 line = proc.stdout.readline()
147 if not line:
148 break
149 mlog.log(line.decode(errors='ignore').strip('\n'))
150 proc.stdout.close()
151
152 t = Thread(target=print_stdout)
153 t.start()
154
155 try:
156 # Read stderr line by line and log non trace lines
157 raw_trace = ''
158 tline_start_reg = re.compile(r'^\s*(.*\.(cmake|txt))\(([0-9]+)\):\s*(\w+)\(.*$')
159 inside_multiline_trace = False
160 while True:
161 line_raw = proc.stderr.readline()
162 if not line_raw:
163 break
164 line = line_raw.decode(errors='ignore')
165 if tline_start_reg.match(line):
166 raw_trace += line
167 inside_multiline_trace = not line.endswith(' )\n')
168 elif inside_multiline_trace:
169 raw_trace += line
170 else:
171 mlog.warning(line.strip('\n'))
172
173 finally:
174 proc.stderr.close()
175 t.join()
176 proc.wait()
177
178 return proc.returncode, None, raw_trace
179
180 def _call_cmout(self, args: T.List[str], build_dir: Path, env: T.Optional[T.Dict[str, str]]) -> TYPE_result:
181 cmd = self.cmakebin.get_command() + args
182 proc = S.Popen(cmd, stdout=S.PIPE, stderr=S.STDOUT, cwd=str(build_dir), env=env) # TODO [PYTHON_37]: drop Path conversion
183 while True:
184 line = proc.stdout.readline()
185 if not line:
186 break
187 mlog.log(line.decode(errors='ignore').strip('\n'))
188 proc.stdout.close()
189 proc.wait()
190 return proc.returncode, None, None
191
192 def _call_quiet(self, args: T.List[str], build_dir: Path, env: T.Optional[T.Dict[str, str]]) -> TYPE_result:
193 build_dir.mkdir(parents=True, exist_ok=True)
194 cmd = self.cmakebin.get_command() + args
195 ret = S.run(cmd, env=env, cwd=str(build_dir), close_fds=False,
196 stdout=S.PIPE, stderr=S.PIPE, universal_newlines=False) # TODO [PYTHON_37]: drop Path conversion
197 rc = ret.returncode
198 out = ret.stdout.decode(errors='ignore')
199 err = ret.stderr.decode(errors='ignore')
200 return rc, out, err
201
202 def _call_impl(self, args: T.List[str], build_dir: Path, env: T.Optional[T.Dict[str, str]]) -> TYPE_result:
203 mlog.debug(f'Calling CMake ({self.cmakebin.get_command()}) in {build_dir} with:')
204 for i in args:
205 mlog.debug(f' - "{i}"')
206 if not self.print_cmout:
207 return self._call_quiet(args, build_dir, env)
208 else:
209 if self.always_capture_stderr:
210 return self._call_cmout_stderr(args, build_dir, env)
211 else:
212 return self._call_cmout(args, build_dir, env)
213
214 def call(self, args: T.List[str], build_dir: Path, env: T.Optional[T.Dict[str, str]] = None, disable_cache: bool = False) -> TYPE_result:
215 if env is None:
216 env = os.environ.copy()
217
218 args = args + self.extra_cmake_args
219 if disable_cache:
220 return self._call_impl(args, build_dir, env)
221
222 # First check if cached, if not call the real cmake function
223 cache = CMakeExecutor.class_cmake_cache
224 key = self._cache_key(args, build_dir, env)
225 if key not in cache:
226 cache[key] = self._call_impl(args, build_dir, env)
227 return cache[key]
228
229 def found(self) -> bool:
230 return self.cmakebin is not None
231
232 def version(self) -> str:
233 return self.cmakevers
234
235 def executable_path(self) -> str:
236 return self.cmakebin.get_path()
237
238 def get_command(self) -> T.List[str]:
239 return self.cmakebin.get_command()
240
241 def get_cmake_prefix_paths(self) -> T.List[str]:
242 return self.prefix_paths
243
244 def machine_choice(self) -> MachineChoice:
245 return self.for_machine