| 1 |
# SPDX-License-Identifier: Apache-2.0 |
| 2 |
# Copyright 2013-2020 The Meson development team |
| 3 |
|
| 4 |
from __future__ import annotations |
| 5 |
|
| 6 |
"""Representations and logic for External and Internal Programs.""" |
| 7 |
|
| 8 |
import functools |
| 9 |
import os |
| 10 |
import shutil |
| 11 |
import stat |
| 12 |
import sys |
| 13 |
import re |
| 14 |
import typing as T |
| 15 |
from pathlib import Path |
| 16 |
from abc import abstractmethod |
| 17 |
|
| 18 |
from . import mesonlib |
| 19 |
from . import mlog |
| 20 |
from .mesonlib import MachineChoice, OrderedSet, SimpleABC |
| 21 |
|
| 22 |
if T.TYPE_CHECKING: |
| 23 |
from typing_extensions import TypeAlias |
| 24 |
from .environment import Environment |
| 25 |
from .interpreter import Interpreter |
| 26 |
|
| 27 |
CommandListEntry: TypeAlias = T.Union[str, 'Program'] |
| 28 |
CommandList: TypeAlias = T.List[CommandListEntry] |
| 29 |
|
| 30 |
|
| 31 |
class Program(mesonlib.HoldableObject, metaclass=SimpleABC): |
| 32 |
'''A base class for LocalProgram and ExternalProgram.''' |
| 33 |
|
| 34 |
name: str |
| 35 |
for_machine = MachineChoice.BUILD |
| 36 |
|
| 37 |
@abstractmethod |
| 38 |
def found(self) -> bool: |
| 39 |
pass |
| 40 |
|
| 41 |
@abstractmethod |
| 42 |
def get_version(self, interpreter: T.Optional[Interpreter] = None) -> str: |
| 43 |
pass |
| 44 |
|
| 45 |
@abstractmethod |
| 46 |
def get_command(self) -> T.List[str]: |
| 47 |
pass |
| 48 |
|
| 49 |
@abstractmethod |
| 50 |
def get_path(self) -> T.Optional[str]: |
| 51 |
pass |
| 52 |
|
| 53 |
@abstractmethod |
| 54 |
def get_name(self) -> T.Optional[str]: |
| 55 |
pass |
| 56 |
|
| 57 |
@abstractmethod |
| 58 |
def runnable(self) -> bool: |
| 59 |
pass |
| 60 |
|
| 61 |
@abstractmethod |
| 62 |
def description(self) -> str: |
| 63 |
'''Human friendly description of the command''' |
| 64 |
|
| 65 |
|
| 66 |
class ExternalProgram(Program): |
| 67 |
|
| 68 |
"""A program that is found on the system. |
| 69 |
:param name: The name of the program |
| 70 |
:param command: Optionally, an argument list constituting the command. Used when |
| 71 |
you already know the command and do not want to search. |
| 72 |
:param silent: Whether to print messages when initializing |
| 73 |
:param search_dirs: A list of directories to search in first, followed by PATH |
| 74 |
:param exclude_paths: A list of directories to exclude when searching in PATH""" |
| 75 |
|
| 76 |
windows_exts = ('exe', 'msc', 'com', 'bat', 'cmd') |
| 77 |
command: list[str] |
| 78 |
|
| 79 |
def __init__(self, name: str, command: T.Optional[T.List[str]] = None, |
| 80 |
silent: bool = False, search_dirs: T.Optional[T.List[T.Optional[str]]] = None, |
| 81 |
exclude_paths: T.Optional[T.List[str]] = None): |
| 82 |
self.name = name |
| 83 |
self.path: T.Optional[str] = None |
| 84 |
self.cached_version: T.Optional[str] = None |
| 85 |
self.version_arg = '--version' |
| 86 |
if command is not None: |
| 87 |
self.command = command.copy() |
| 88 |
if mesonlib.is_windows(): |
| 89 |
cmd = self.command[0] |
| 90 |
args = self.command[1:] |
| 91 |
# Check whether the specified cmd is a path to a script, in |
| 92 |
# which case we need to insert the interpreter. If not, try to |
| 93 |
# use it as-is. |
| 94 |
ret = self._shebang_to_cmd(cmd) |
| 95 |
if ret: |
| 96 |
self.command = ret + args |
| 97 |
else: |
| 98 |
if os.path.isabs(cmd) and not os.path.exists(cmd): |
| 99 |
# Maybe the name is an absolute path to a native Windows |
| 100 |
# executable, but without the extension. This is technically wrong, |
| 101 |
# but many people do it because it works in the MinGW shell. |
| 102 |
for ext in self.windows_exts: |
| 103 |
trial_ext = f'{cmd}.{ext}' |
| 104 |
if os.path.exists(trial_ext): |
| 105 |
cmd = trial_ext |
| 106 |
break |
| 107 |
self.command = [cmd] + args |
| 108 |
else: |
| 109 |
if search_dirs is None: |
| 110 |
# For compat with old behaviour |
| 111 |
search_dirs = [None] |
| 112 |
self.command = self._search(name, search_dirs, exclude_paths) |
| 113 |
|
| 114 |
if self.found(): |
| 115 |
# Set path to be the last item that is actually a file (in order to |
| 116 |
# skip options in something like ['python', '-u', 'file.py']. If we |
| 117 |
# can't find any components, default to the last component of the path. |
| 118 |
for arg in reversed(self.command): |
| 119 |
if arg is not None and os.path.isfile(arg): |
| 120 |
self.path = arg |
| 121 |
break |
| 122 |
else: |
| 123 |
self.path = self.command[-1] |
| 124 |
|
| 125 |
if not silent: |
| 126 |
# ignore the warning because derived classes never call this __init__ |
| 127 |
# method, and thus only the found() method of this class is ever executed |
| 128 |
if self.found(): # lgtm [py/init-calls-subclass] |
| 129 |
mlog.log('Program', mlog.bold(name), 'found:', mlog.green('YES'), |
| 130 |
'(%s)' % ' '.join(self.command)) |
| 131 |
else: |
| 132 |
mlog.log('Program', mlog.bold(name), 'found:', mlog.red('NO')) |
| 133 |
|
| 134 |
def summary_value(self) -> T.Union[str, mlog.AnsiDecorator, None]: |
| 135 |
if not self.found(): |
| 136 |
return mlog.red('NO') |
| 137 |
return self.path |
| 138 |
|
| 139 |
def __repr__(self) -> str: |
| 140 |
r = '<{} {!r} -> {!r}>' |
| 141 |
return r.format(self.__class__.__name__, self.name, self.command) |
| 142 |
|
| 143 |
def description(self) -> str: |
| 144 |
'''Human friendly description of the command''' |
| 145 |
return ' '.join(self.command) |
| 146 |
|
| 147 |
def get_version(self, interpreter: T.Optional['Interpreter'] = None) -> str: |
| 148 |
if not self.cached_version: |
| 149 |
raw_cmd = self.get_command() + [self.version_arg] |
| 150 |
if interpreter: |
| 151 |
res = interpreter.run_command_impl((self, [self.version_arg]), |
| 152 |
{'capture': True, |
| 153 |
'console': False, |
| 154 |
'check': True, |
| 155 |
'env': mesonlib.EnvironmentVariables()}, |
| 156 |
True) |
| 157 |
o, e = res.stdout, res.stderr |
| 158 |
else: |
| 159 |
p, o, e = mesonlib.Popen_safe(raw_cmd) |
| 160 |
if p.returncode != 0: |
| 161 |
cmd_str = mesonlib.join_args(raw_cmd) |
| 162 |
raise mesonlib.MesonException(f'Command {cmd_str!r} failed with status {p.returncode}.') |
| 163 |
output = o.strip() |
| 164 |
if not output: |
| 165 |
output = e.strip() |
| 166 |
|
| 167 |
match = re.search(r'([0-9]+(\.[0-9]+)+)', output) |
| 168 |
if not match: |
| 169 |
match = re.search(r'([0-9][0-9\.]+)', output) |
| 170 |
if not match: |
| 171 |
raise mesonlib.MesonException(f'Could not find a version number in output of {raw_cmd!r}') |
| 172 |
self.cached_version = match.group(1) |
| 173 |
return self.cached_version |
| 174 |
|
| 175 |
@classmethod |
| 176 |
def from_bin_list(cls, env: 'Environment', for_machine: MachineChoice, name: str) -> 'ExternalProgram': |
| 177 |
# This is not the static `for_machine` in this class, which represents |
| 178 |
# that the binary always runs on the build platform. (Its host platform |
| 179 |
# is our build platform.) Some external programs have a target platform, |
| 180 |
# and that is what we are specifying here. |
| 181 |
command = env.lookup_binary_entry(for_machine, name) |
| 182 |
if command is None: |
| 183 |
return NonExistingExternalProgram() |
| 184 |
return cls.from_entry(name, command) |
| 185 |
|
| 186 |
@staticmethod |
| 187 |
@functools.lru_cache(maxsize=None) |
| 188 |
def _windows_sanitize_path(path: str) -> str: |
| 189 |
# Ensure that we use USERPROFILE even when inside MSYS, MSYS2, Cygwin, etc. |
| 190 |
if 'USERPROFILE' not in os.environ: |
| 191 |
return path |
| 192 |
# The WindowsApps directory is a bit of a problem. It contains |
| 193 |
# some zero-sized .exe files which have "reparse points", that |
| 194 |
# might either launch an installed application, or might open |
| 195 |
# a page in the Windows Store to download the application. |
| 196 |
# |
| 197 |
# To handle the case where the python interpreter we're |
| 198 |
# running on came from the Windows Store, if we see the |
| 199 |
# WindowsApps path in the search path, replace it with |
| 200 |
# dirname(sys.executable). |
| 201 |
appstore_dir = Path(os.environ['USERPROFILE']) / 'AppData' / 'Local' / 'Microsoft' / 'WindowsApps' |
| 202 |
paths = [] |
| 203 |
for each in path.split(os.pathsep): |
| 204 |
if Path(each) != appstore_dir: |
| 205 |
paths.append(each) |
| 206 |
elif 'WindowsApps' in sys.executable: |
| 207 |
paths.append(os.path.dirname(sys.executable)) |
| 208 |
return os.pathsep.join(paths) |
| 209 |
|
| 210 |
@staticmethod |
| 211 |
def from_entry(name: str, command: T.Union[str, T.List[str]]) -> 'ExternalProgram': |
| 212 |
if isinstance(command, list): |
| 213 |
if len(command) == 1: |
| 214 |
command = command[0] |
| 215 |
# We cannot do any searching if the command is a list, and we don't |
| 216 |
# need to search if the path is an absolute path. |
| 217 |
if isinstance(command, list) or os.path.isabs(command): |
| 218 |
if isinstance(command, str): |
| 219 |
command = [command] |
| 220 |
return ExternalProgram(name, command=command, silent=True) |
| 221 |
assert isinstance(command, str) |
| 222 |
# Search for the command using the specified string! |
| 223 |
return ExternalProgram(command, silent=True) |
| 224 |
|
| 225 |
@staticmethod |
| 226 |
def _shebang_to_cmd(script: str) -> list[str]: |
| 227 |
""" |
| 228 |
Check if the file has a shebang and manually parse it to figure out |
| 229 |
the interpreter to use. This is useful if the script is not executable |
| 230 |
or if we're on Windows (which does not understand shebangs). |
| 231 |
""" |
| 232 |
try: |
| 233 |
with open(script, encoding='utf-8') as f: |
| 234 |
first_line = f.readline().strip() |
| 235 |
if first_line.startswith('#!'): |
| 236 |
# In a shebang, everything before the first space is assumed to |
| 237 |
# be the command to run and everything after the first space is |
| 238 |
# the single argument to pass to that command. So we must split |
| 239 |
# exactly once. |
| 240 |
commands = first_line[2:].split('#')[0].strip().split(maxsplit=1) |
| 241 |
if mesonlib.is_windows(): |
| 242 |
# Windows does not have UNIX paths so remove them, |
| 243 |
# but don't remove Windows paths |
| 244 |
if commands[0].startswith('/'): |
| 245 |
commands[0] = commands[0].split('/')[-1] |
| 246 |
if len(commands) > 0 and commands[0] == 'env': |
| 247 |
commands = commands[1:] |
| 248 |
# Windows does not ship python3.exe, but we know the path to it |
| 249 |
if len(commands) > 0 and commands[0] == 'python3': |
| 250 |
commands = mesonlib.python_command + commands[1:] |
| 251 |
elif mesonlib.is_haiku(): |
| 252 |
# Haiku does not have /usr, but a lot of scripts assume that |
| 253 |
# /usr/bin/env always exists. Detect that case and run the |
| 254 |
# script with the interpreter after it. |
| 255 |
if commands[0] == '/usr/bin/env': |
| 256 |
commands = commands[1:] |
| 257 |
# We know what python3 is, we're running on it |
| 258 |
if len(commands) > 0 and commands[0] == 'python3': |
| 259 |
commands = mesonlib.python_command + commands[1:] |
| 260 |
else: |
| 261 |
# Replace python3 with the actual python3 that we are using |
| 262 |
if commands[0] == '/usr/bin/env' and commands[1] == 'python3': |
| 263 |
commands = mesonlib.python_command + commands[2:] |
| 264 |
elif commands[0].split('/')[-1] == 'python3': |
| 265 |
commands = mesonlib.python_command + commands[1:] |
| 266 |
return commands + [script] |
| 267 |
except Exception as e: |
| 268 |
mlog.debug(str(e)) |
| 269 |
mlog.debug(f'Unusable script {script!r}') |
| 270 |
return [] |
| 271 |
|
| 272 |
def _is_executable(self, path: str) -> bool: |
| 273 |
suffix = os.path.splitext(path)[-1].lower()[1:] |
| 274 |
execmask = stat.S_IXUSR | stat.S_IXGRP | stat.S_IXOTH |
| 275 |
if mesonlib.is_windows(): |
| 276 |
if suffix in self.windows_exts: |
| 277 |
return True |
| 278 |
elif os.stat(path).st_mode & execmask: |
| 279 |
return not os.path.isdir(path) |
| 280 |
return False |
| 281 |
|
| 282 |
def _search_dir(self, name: str, search_dir: T.Optional[str]) -> list[str]: |
| 283 |
if search_dir is None: |
| 284 |
return [] |
| 285 |
trial = os.path.join(search_dir, name) |
| 286 |
if os.path.exists(trial): |
| 287 |
if self._is_executable(trial): |
| 288 |
return [trial] |
| 289 |
# Now getting desperate. Maybe it is a script file that is |
| 290 |
# a) not chmodded executable, or |
| 291 |
# b) we are on windows so they can't be directly executed. |
| 292 |
return self._shebang_to_cmd(trial) |
| 293 |
else: |
| 294 |
if mesonlib.is_windows(): |
| 295 |
for ext in self.windows_exts: |
| 296 |
trial_ext = f'{trial}.{ext}' |
| 297 |
if os.path.exists(trial_ext): |
| 298 |
return [trial_ext] |
| 299 |
return [] |
| 300 |
|
| 301 |
def _search_windows_special_cases(self, name: str, command: T.Optional[str], exclude_paths: T.Optional[T.List[str]]) -> list[str]: |
| 302 |
''' |
| 303 |
Lots of weird Windows quirks: |
| 304 |
1. PATH search for @name returns files with extensions from PATHEXT, |
| 305 |
but only self.windows_exts are executable without an interpreter. |
| 306 |
2. @name might be an absolute path to an executable, but without the |
| 307 |
extension. This works inside MinGW so people use it a lot. |
| 308 |
3. The script is specified without an extension, in which case we have |
| 309 |
to manually search in PATH. |
| 310 |
4. More special-casing for the shebang inside the script. |
| 311 |
''' |
| 312 |
if command: |
| 313 |
# On Windows, even if the PATH search returned a full path, we can't be |
| 314 |
# sure that it can be run directly if it's not a native executable. |
| 315 |
# For instance, interpreted scripts sometimes need to be run explicitly |
| 316 |
# with an interpreter if the file association is not done properly. |
| 317 |
|
| 318 |
# Lower case the command extension, as clangd requires lower case |
| 319 |
# "exe" to unwrap compiler wrappers in CDB, e.g. "ccache.exe cl ..." |
| 320 |
prefix, ext = os.path.splitext(command) |
| 321 |
ext = ext.lower() |
| 322 |
command = prefix + ext |
| 323 |
|
| 324 |
if ext[1:] in self.windows_exts: |
| 325 |
# Good, it can be directly executed |
| 326 |
return [command] |
| 327 |
# Try to extract the interpreter from the shebang |
| 328 |
commands = self._shebang_to_cmd(command) |
| 329 |
if commands: |
| 330 |
return commands |
| 331 |
return [] |
| 332 |
# Maybe the name is an absolute path to a native Windows |
| 333 |
# executable, but without the extension. This is technically wrong, |
| 334 |
# but many people do it because it works in the MinGW shell. |
| 335 |
if os.path.isabs(name): |
| 336 |
for ext in self.windows_exts: |
| 337 |
command = f'{name}.{ext}' |
| 338 |
if os.path.exists(command): |
| 339 |
return [command] |
| 340 |
# On Windows, interpreted scripts must have an extension otherwise they |
| 341 |
# cannot be found by a standard PATH search. So we do a custom search |
| 342 |
# where we manually search for a script with a shebang in PATH. |
| 343 |
search_dirs = OrderedSet(self._windows_sanitize_path(os.environ.get('PATH', '')).split(';')) |
| 344 |
if exclude_paths: |
| 345 |
search_dirs.difference_update(exclude_paths) |
| 346 |
for search_dir in search_dirs: |
| 347 |
commands = self._search_dir(name, search_dir) |
| 348 |
if commands: |
| 349 |
return commands |
| 350 |
return [] |
| 351 |
|
| 352 |
def _search(self, name: str, search_dirs: T.List[T.Optional[str]], exclude_paths: T.Optional[T.List[str]]) -> list[str]: |
| 353 |
''' |
| 354 |
Search in the specified dirs for the specified executable by name |
| 355 |
and if not found search in PATH |
| 356 |
''' |
| 357 |
for search_dir in search_dirs: |
| 358 |
commands = self._search_dir(name, search_dir) |
| 359 |
if commands: |
| 360 |
return commands |
| 361 |
# If there is a directory component, do not look in PATH |
| 362 |
if os.path.dirname(name) and not os.path.isabs(name): |
| 363 |
return [] |
| 364 |
# Do a standard search in PATH |
| 365 |
path = os.environ.get('PATH', os.defpath) |
| 366 |
if mesonlib.is_windows() and path: |
| 367 |
path = self._windows_sanitize_path(path) |
| 368 |
if exclude_paths: |
| 369 |
paths = OrderedSet(path.split(os.pathsep)).difference(exclude_paths) |
| 370 |
path = os.pathsep.join(paths) |
| 371 |
command = shutil.which(name, path=path) |
| 372 |
if not command and mesonlib.is_os2(): |
| 373 |
for ext in ['exe', 'cmd']: |
| 374 |
command = shutil.which(f'{name}.{ext}', path=path) |
| 375 |
if command: |
| 376 |
return [command] |
| 377 |
if mesonlib.is_windows(): |
| 378 |
return self._search_windows_special_cases(name, command, exclude_paths) |
| 379 |
# On UNIX-like platforms, shutil.which() is enough to find |
| 380 |
# all executables whether in PATH or with an absolute path |
| 381 |
return [command] if command is not None else [] |
| 382 |
|
| 383 |
def runnable(self) -> bool: |
| 384 |
return self.found() |
| 385 |
|
| 386 |
def found(self) -> bool: |
| 387 |
return bool(self.command) |
| 388 |
|
| 389 |
def get_command(self) -> T.List[str]: |
| 390 |
return self.command[:] |
| 391 |
|
| 392 |
def get_path(self) -> T.Optional[str]: |
| 393 |
return self.path |
| 394 |
|
| 395 |
def get_name(self) -> str: |
| 396 |
return self.name |
| 397 |
|
| 398 |
|
| 399 |
class NonExistingExternalProgram(ExternalProgram): # lgtm [py/missing-call-to-init] |
| 400 |
"A program that will never exist" |
| 401 |
|
| 402 |
def __init__(self, name: str = 'nonexistingprogram') -> None: |
| 403 |
self.name = name |
| 404 |
self.command = [] |
| 405 |
self.path = None |
| 406 |
|
| 407 |
def __repr__(self) -> str: |
| 408 |
r = '<{} {!r} -> {!r}>' |
| 409 |
return r.format(self.__class__.__name__, self.name, self.command) |
| 410 |
|
| 411 |
def found(self) -> bool: |
| 412 |
return False |
| 413 |
|
| 414 |
|
| 415 |
def find_external_program(env: 'Environment', for_machine: MachineChoice, name: str, |
| 416 |
display_name: str, default_names: T.List[str], |
| 417 |
allow_default_for_cross: bool = True, |
| 418 |
exclude_paths: T.Optional[T.List[str]] = None) -> T.Generator['ExternalProgram', None, None]: |
| 419 |
"""Find an external program, checking the cross file plus any default options.""" |
| 420 |
potential_names = OrderedSet(default_names) |
| 421 |
potential_names.add(name) |
| 422 |
# Lookup in cross or machine file. |
| 423 |
for potential_name in potential_names: |
| 424 |
potential_cmd = env.lookup_binary_entry(for_machine, potential_name) |
| 425 |
if potential_cmd is not None: |
| 426 |
mlog.debug(f'{display_name} binary for {for_machine} specified from cross file, native file, ' |
| 427 |
f'or env var as {potential_cmd}') |
| 428 |
yield ExternalProgram.from_entry(potential_name, potential_cmd) |
| 429 |
# We never fallback if the user-specified option is no good, so |
| 430 |
# stop returning options. |
| 431 |
return |
| 432 |
mlog.debug(f'{display_name} binary missing from cross or native file, or env var undefined.') |
| 433 |
# Fallback on hard-coded defaults, if a default binary is allowed for use |
| 434 |
# with cross targets, or if this is not a cross target |
| 435 |
if allow_default_for_cross or not (for_machine is MachineChoice.HOST and env.is_cross_build(for_machine)): |
| 436 |
for potential_name in default_names: |
| 437 |
mlog.debug(f'Trying a default {display_name} fallback at', potential_name) |
| 438 |
yield ExternalProgram(potential_name, silent=True, exclude_paths=exclude_paths) |
| 439 |
else: |
| 440 |
mlog.debug('Default target is not allowed for cross use') |