| 1 |
# SPDX-License-Identifier: Apache-2.0 |
| 2 |
# Copyright 2014-2016 The Meson development team |
| 3 |
# Copyright © 2023-2025 Intel Corporation |
| 4 |
|
| 5 |
from __future__ import annotations |
| 6 |
|
| 7 |
import itertools |
| 8 |
import hashlib |
| 9 |
import shutil |
| 10 |
import os |
| 11 |
import textwrap |
| 12 |
import typing as T |
| 13 |
import collections |
| 14 |
|
| 15 |
from . import build |
| 16 |
from . import cmdline |
| 17 |
from . import coredata |
| 18 |
from . import options |
| 19 |
from . import environment |
| 20 |
from . import mesonlib |
| 21 |
from . import mintro |
| 22 |
from . import mlog |
| 23 |
from .ast import AstIDGenerator, IntrospectionInterpreter |
| 24 |
from .mesonlib import MachineChoice, unwrap |
| 25 |
from .options import OptionKey |
| 26 |
from .optinterpreter import OptionInterpreter |
| 27 |
|
| 28 |
if T.TYPE_CHECKING: |
| 29 |
from typing_extensions import Protocol |
| 30 |
import argparse |
| 31 |
|
| 32 |
class CMDOptions(cmdline.SharedCMDOptions, Protocol): |
| 33 |
|
| 34 |
builddir: str |
| 35 |
clearcache: bool |
| 36 |
pager: bool |
| 37 |
|
| 38 |
# cannot be TV_Loggable, because non-ansidecorators do direct string concat |
| 39 |
LOGLINE = T.Union[str, mlog.AnsiDecorator] |
| 40 |
|
| 41 |
# Note: when adding arguments, please also add them to the completion |
| 42 |
# scripts in $MESONSRC/data/shell-completions/ |
| 43 |
def add_arguments(parser: 'argparse.ArgumentParser') -> None: |
| 44 |
cmdline.register_builtin_arguments(parser) |
| 45 |
parser.add_argument('builddir', nargs='?', default='.') |
| 46 |
parser.add_argument('--clearcache', action='store_true', default=False, |
| 47 |
help='Clear cached state (e.g. found dependencies)') |
| 48 |
parser.add_argument('--no-pager', action='store_false', dest='pager', |
| 49 |
help='Do not redirect output to a pager') |
| 50 |
parser.add_argument('-U', action=cmdline.KeyNoneAction, dest='cmd_line_options', default={}, |
| 51 |
help='Remove a subproject option.') |
| 52 |
|
| 53 |
def stringify(val: T.Any) -> str: |
| 54 |
if isinstance(val, bool): |
| 55 |
return str(val).lower() |
| 56 |
elif isinstance(val, list): |
| 57 |
s = ', '.join(stringify(i) for i in val) |
| 58 |
return f'[{s}]' |
| 59 |
elif val is None: |
| 60 |
return '' |
| 61 |
else: |
| 62 |
return str(val) |
| 63 |
|
| 64 |
|
| 65 |
class ConfException(mesonlib.MesonException): |
| 66 |
pass |
| 67 |
|
| 68 |
|
| 69 |
class Conf: |
| 70 |
def __init__(self, build_dir: str): |
| 71 |
self.build_dir = os.path.abspath(os.path.realpath(build_dir)) |
| 72 |
if 'meson.build' in [os.path.basename(self.build_dir), self.build_dir]: |
| 73 |
self.build_dir = os.path.dirname(self.build_dir) |
| 74 |
self.build = None |
| 75 |
self.max_choices_line_length = 60 |
| 76 |
self.pending_section: T.Optional[str] = None |
| 77 |
self.name_col: T.List[LOGLINE] = [] |
| 78 |
self.value_col: T.List[LOGLINE] = [] |
| 79 |
self.choices_col: T.List[LOGLINE] = [] |
| 80 |
self.descr_col: T.List[LOGLINE] = [] |
| 81 |
self.all_subprojects: T.Set[str] = set() |
| 82 |
|
| 83 |
if os.path.isdir(os.path.join(self.build_dir, 'meson-private')): |
| 84 |
self.build = build.load(self.build_dir) |
| 85 |
self.source_dir = self.build.environment.get_source_dir() |
| 86 |
self.coredata = self.build.environment.coredata |
| 87 |
self.default_values_only = False |
| 88 |
|
| 89 |
# if the option file has been updated, reload it |
| 90 |
# This cannot handle options for a new subproject that has not yet |
| 91 |
# been configured. |
| 92 |
for sub, conf_options in self.coredata.options_files.items(): |
| 93 |
if conf_options is not None and os.path.exists(conf_options[0]): |
| 94 |
opfile = conf_options[0] |
| 95 |
with open(opfile, 'rb') as f: |
| 96 |
ophash = hashlib.sha1(f.read()).hexdigest() |
| 97 |
if ophash != conf_options[1]: |
| 98 |
oi = OptionInterpreter(self.coredata.optstore, sub) |
| 99 |
oi.process(opfile) |
| 100 |
self.coredata.optstore.update_project_options(oi.options, sub) |
| 101 |
self.coredata.options_files[sub] = (opfile, ophash) |
| 102 |
else: |
| 103 |
opfile = os.path.join(self.source_dir, 'meson.options') |
| 104 |
if not os.path.exists(opfile): |
| 105 |
opfile = os.path.join(self.source_dir, 'meson_options.txt') |
| 106 |
if os.path.exists(opfile): |
| 107 |
oi = OptionInterpreter(self.coredata.optstore, sub) |
| 108 |
oi.process(opfile) |
| 109 |
self.coredata.optstore.update_project_options(oi.options, sub) |
| 110 |
with open(opfile, 'rb') as f: |
| 111 |
ophash = hashlib.sha1(f.read()).hexdigest() |
| 112 |
self.coredata.options_files[sub] = (opfile, ophash) |
| 113 |
else: |
| 114 |
self.coredata.optstore.update_project_options({}, sub) |
| 115 |
elif os.path.isfile(os.path.join(self.build_dir, environment.build_filename)): |
| 116 |
# Make sure that log entries in other parts of meson don't interfere with the JSON output |
| 117 |
with mlog.no_logging(): |
| 118 |
self.source_dir = os.path.abspath(os.path.realpath(self.build_dir)) |
| 119 |
intr = IntrospectionInterpreter(self.source_dir, '', 'ninja', visitors = [AstIDGenerator()]) |
| 120 |
intr.analyze() |
| 121 |
self.coredata = intr.coredata |
| 122 |
self.default_values_only = True |
| 123 |
else: |
| 124 |
raise ConfException(f'Directory {build_dir} is neither a Meson build directory nor a project source directory.') |
| 125 |
|
| 126 |
def clear_cache(self) -> None: |
| 127 |
self.coredata.clear_cache() |
| 128 |
|
| 129 |
def save(self) -> None: |
| 130 |
# Do nothing when using introspection |
| 131 |
if self.default_values_only: |
| 132 |
return |
| 133 |
coredata.save(self.coredata, self.build_dir) |
| 134 |
# We don't write the build file because any changes to it |
| 135 |
# are erased when Meson is executed the next time, i.e. when |
| 136 |
# Ninja is run. |
| 137 |
|
| 138 |
def print_aligned(self) -> None: |
| 139 |
"""Do the actual printing. |
| 140 |
|
| 141 |
This prints the generated output in an aligned, pretty form. it aims |
| 142 |
for a total width of 160 characters, but will use whatever the tty |
| 143 |
reports its value to be. Though this is much wider than the standard |
| 144 |
80 characters of terminals, and even than the newer 120, compressing |
| 145 |
it to those lengths makes the output hard to read. |
| 146 |
|
| 147 |
Each column will have a specific width, and will be line wrapped. |
| 148 |
""" |
| 149 |
total_width = shutil.get_terminal_size(fallback=(160, 0))[0] |
| 150 |
_col = max(total_width // 5, 24) |
| 151 |
last_column = total_width - (3 * _col) - 3 |
| 152 |
four_column = (_col, _col, _col, last_column if last_column > 1 else _col) |
| 153 |
|
| 154 |
for line in zip(self.name_col, self.value_col, self.choices_col, self.descr_col): |
| 155 |
if not any(line): |
| 156 |
mlog.log('') |
| 157 |
continue |
| 158 |
|
| 159 |
# This is a header, like `Subproject foo:`, |
| 160 |
# We just want to print that and get on with it |
| 161 |
if line[0] and not any(line[1:]): |
| 162 |
mlog.log(line[0]) |
| 163 |
continue |
| 164 |
|
| 165 |
def wrap_text(text: LOGLINE, width: int) -> mlog.TV_LoggableList: |
| 166 |
raw = text.text if isinstance(text, mlog.AnsiDecorator) else text |
| 167 |
indent = ' ' if raw.startswith('[') else '' |
| 168 |
wrapped_ = textwrap.wrap(raw, width, subsequent_indent=indent) |
| 169 |
# We cast this because https://github.com/python/mypy/issues/1965 |
| 170 |
# mlog.TV_LoggableList does not provide __len__ for stringprotocol |
| 171 |
if isinstance(text, mlog.AnsiDecorator): |
| 172 |
wrapped = T.cast('T.List[LOGLINE]', [mlog.AnsiDecorator(i, text.code) for i in wrapped_]) |
| 173 |
else: |
| 174 |
wrapped = T.cast('T.List[LOGLINE]', wrapped_) |
| 175 |
# Add padding here to get even rows, as `textwrap.wrap()` will |
| 176 |
# only shorten, not lengthen each item |
| 177 |
return [str(i) + ' ' * (width - len(i)) for i in wrapped] |
| 178 |
|
| 179 |
# wrap will take a long string, and create a list of strings no |
| 180 |
# longer than the size given. Then that list can be zipped into, to |
| 181 |
# print each line of the output, such the that columns are printed |
| 182 |
# to the right width, row by row. |
| 183 |
name = wrap_text(line[0], four_column[0]) |
| 184 |
val = wrap_text(line[1], four_column[1]) |
| 185 |
choice = wrap_text(line[2], four_column[2]) |
| 186 |
desc = wrap_text(line[3], four_column[3]) |
| 187 |
for l in itertools.zip_longest(name, val, choice, desc, fillvalue=''): |
| 188 |
items = [l[i] if l[i] else ' ' * four_column[i] for i in range(4)] |
| 189 |
mlog.log(*items) |
| 190 |
|
| 191 |
def split_options_per_subproject(self, opts: T.Union[options.MutableKeyedOptionDictType, options.OptionStore] |
| 192 |
) -> T.Dict[str | None, options.MutableKeyedOptionDictType]: |
| 193 |
result: T.Dict[str | None, options.MutableKeyedOptionDictType] = {} |
| 194 |
for k, o in opts.items(): |
| 195 |
if k.subproject is not None: |
| 196 |
self.all_subprojects.add(k.subproject) |
| 197 |
result.setdefault(k.subproject, {})[k] = o |
| 198 |
return result |
| 199 |
|
| 200 |
def _add_line(self, name: LOGLINE, value: LOGLINE, choices: LOGLINE, descr: LOGLINE) -> None: |
| 201 |
if isinstance(name, mlog.AnsiDecorator): |
| 202 |
name.text = ' ' * self.print_margin + name.text |
| 203 |
else: |
| 204 |
name = ' ' * self.print_margin + name |
| 205 |
self.name_col.append(name) |
| 206 |
self.value_col.append(value) |
| 207 |
self.choices_col.append(choices) |
| 208 |
self.descr_col.append(descr) |
| 209 |
|
| 210 |
def add_option(self, key: OptionKey, descr: str, value: T.Any, choices: T.Any) -> None: |
| 211 |
self._add_section() |
| 212 |
value = stringify(value) |
| 213 |
choices = stringify(choices) |
| 214 |
self._add_line(mlog.green(str(key.evolve(subproject=None))), mlog.yellow(value), |
| 215 |
mlog.blue(choices), descr) |
| 216 |
|
| 217 |
def add_title(self, title: str) -> None: |
| 218 |
self._add_section() |
| 219 |
newtitle = mlog.cyan(title) |
| 220 |
descr = mlog.cyan('Description') |
| 221 |
value = mlog.cyan('Default Value' if self.default_values_only else 'Current Value') |
| 222 |
choices = mlog.cyan('Possible Values') |
| 223 |
self._add_line('', '', '', '') |
| 224 |
self._add_line(newtitle, value, choices, descr) |
| 225 |
self._add_line('-' * len(newtitle), '-' * len(value), '-' * len(choices), '-' * len(descr)) |
| 226 |
|
| 227 |
def _add_section(self) -> None: |
| 228 |
if not self.pending_section: |
| 229 |
return |
| 230 |
self.print_margin = 0 |
| 231 |
self._add_line('', '', '', '') |
| 232 |
self._add_line(mlog.normal_yellow(self.pending_section + ':'), '', '', '') |
| 233 |
self.print_margin = 2 |
| 234 |
self.pending_section = None |
| 235 |
|
| 236 |
def add_section(self, section: str) -> None: |
| 237 |
self.pending_section = section |
| 238 |
|
| 239 |
def print_options(self, title: str, opts: T.Union[options.MutableKeyedOptionDictType, options.OptionStore]) -> None: |
| 240 |
if not opts: |
| 241 |
return |
| 242 |
if title: |
| 243 |
self.add_title(title) |
| 244 |
for k, o in sorted(opts.items()): |
| 245 |
printable_value = o.printable_value() |
| 246 |
#root = k.as_root() |
| 247 |
#if o.yielding and k.subproject and root in self.coredata.options: |
| 248 |
# printable_value = '<inherited from main project>' |
| 249 |
self.add_option(k, o.description, printable_value, o.printable_choices()) |
| 250 |
|
| 251 |
def print_conf(self, pager: bool) -> None: |
| 252 |
if pager: |
| 253 |
mlog.start_pager() |
| 254 |
|
| 255 |
def print_default_values_warning() -> None: |
| 256 |
mlog.warning('The source directory instead of the build directory was specified.') |
| 257 |
mlog.warning('Only the default values for the project are printed.') |
| 258 |
|
| 259 |
if self.default_values_only: |
| 260 |
print_default_values_warning() |
| 261 |
mlog.log('') |
| 262 |
|
| 263 |
mlog.log('Core properties:') |
| 264 |
mlog.log(' Source dir', self.source_dir) |
| 265 |
if not self.default_values_only: |
| 266 |
mlog.log(' Build dir ', self.build_dir) |
| 267 |
|
| 268 |
dir_option_names = set(options.BUILTIN_DIR_OPTIONS) |
| 269 |
test_option_names = {OptionKey('errorlogs'), |
| 270 |
OptionKey('stdsplit')} |
| 271 |
|
| 272 |
dir_options: options.MutableKeyedOptionDictType = {} |
| 273 |
test_options: options.MutableKeyedOptionDictType = {} |
| 274 |
core_options: options.MutableKeyedOptionDictType = {} |
| 275 |
module_options: T.Dict[str, options.MutableKeyedOptionDictType] = collections.defaultdict(dict) |
| 276 |
for k, v in self.coredata.optstore.options.items(): |
| 277 |
if k in dir_option_names: |
| 278 |
dir_options[k] = v |
| 279 |
elif k in test_option_names: |
| 280 |
test_options[k] = v |
| 281 |
elif (modname := k.get_module_prefix()) is not None: |
| 282 |
# Ignore module options if we did not use that module during |
| 283 |
# configuration. |
| 284 |
if self.build and modname not in self.build.modules: |
| 285 |
continue |
| 286 |
module_options[modname][k] = v |
| 287 |
elif self.coredata.optstore.is_builtin_option(k): |
| 288 |
core_options[k] = v |
| 289 |
|
| 290 |
host_core_options = self.split_options_per_subproject({k: v for k, v in core_options.items() if k.machine is MachineChoice.HOST}) |
| 291 |
build_core_options = self.split_options_per_subproject({k: v for k, v in core_options.items() if k.machine is MachineChoice.BUILD}) |
| 292 |
host_compiler_options = self.split_options_per_subproject({k: v for k, v in self.coredata.optstore.items() if self.coredata.optstore.is_compiler_option(k) and k.machine is MachineChoice.HOST}) |
| 293 |
build_compiler_options = self.split_options_per_subproject({k: v for k, v in self.coredata.optstore.items() if self.coredata.optstore.is_compiler_option(k) and k.machine is MachineChoice.BUILD}) |
| 294 |
project_options = self.split_options_per_subproject({k: v for k, v in self.coredata.optstore.items() if self.coredata.optstore.is_project_option(k)}) |
| 295 |
show_build_options = self.default_values_only or unwrap(self.build).environment.is_cross_build() |
| 296 |
|
| 297 |
self.add_section('Global build options') |
| 298 |
self.print_options('Core options', host_core_options[None]) |
| 299 |
if show_build_options and build_core_options: |
| 300 |
self.print_options('', build_core_options[None]) |
| 301 |
self.print_options('Backend options', {k: v for k, v in self.coredata.optstore.items() if self.coredata.optstore.is_backend_option(k)}) |
| 302 |
self.print_options('Base options', {k: v for k, v in self.coredata.optstore.items() if self.coredata.optstore.is_base_option(k)}) |
| 303 |
self.print_options('Compiler options', host_compiler_options.get(None, {})) |
| 304 |
if show_build_options: |
| 305 |
self.print_options('', build_compiler_options.get(None, {})) |
| 306 |
for mod, mod_options in module_options.items(): |
| 307 |
self.print_options(f'{mod} module options', mod_options) |
| 308 |
self.print_options('Directories', dir_options) |
| 309 |
self.print_options('Testing options', test_options) |
| 310 |
self.print_options('Project options', project_options.get('', {})) |
| 311 |
for subproject in sorted(self.all_subprojects): |
| 312 |
if subproject == '': |
| 313 |
self.add_section('Main project') |
| 314 |
else: |
| 315 |
self.add_section('Subproject ' + subproject) |
| 316 |
if subproject in host_core_options: |
| 317 |
self.print_options('Core options', host_core_options[subproject]) |
| 318 |
if subproject in build_core_options and show_build_options: |
| 319 |
self.print_options('', build_core_options[subproject]) |
| 320 |
if subproject in host_compiler_options: |
| 321 |
self.print_options('Compiler options', host_compiler_options[subproject]) |
| 322 |
if subproject in build_compiler_options and show_build_options: |
| 323 |
self.print_options('', build_compiler_options[subproject]) |
| 324 |
if subproject != '' and subproject in project_options: |
| 325 |
self.print_options('Project options', project_options[subproject]) |
| 326 |
self.print_aligned() |
| 327 |
|
| 328 |
# Print the warning twice so that the user shouldn't be able to miss it |
| 329 |
if self.default_values_only: |
| 330 |
mlog.log('') |
| 331 |
print_default_values_warning() |
| 332 |
|
| 333 |
self.print_nondefault_buildtype_options() |
| 334 |
self.print_augments() |
| 335 |
|
| 336 |
def print_nondefault_buildtype_options(self) -> None: |
| 337 |
mismatching = self.coredata.get_nondefault_buildtype_args() |
| 338 |
if not mismatching: |
| 339 |
return |
| 340 |
items = [(stringify(m[0]), stringify(m[1]), stringify(m[2])) for m in mismatching] |
| 341 |
max_name_len = max(len(item[0]) for item in items) |
| 342 |
max_current_len = max(len(item[1]) for item in items) |
| 343 |
padding1 = ' ' * (max_name_len + 1) |
| 344 |
padding2 = ' ' * (max_current_len - len('Current')) |
| 345 |
mlog.log("\nThe following option(s) have a different value than the build type default:\n") |
| 346 |
mlog.log(' ', padding1, mlog.cyan('Current'), padding2, mlog.cyan('Default')) |
| 347 |
mlog.log(' ', padding1, '-' * len('Current'), padding2, '-' * len('Default')) |
| 348 |
for item in items: |
| 349 |
name, current, default = item |
| 350 |
padding1 = ' ' * (max_name_len - len(name)) |
| 351 |
padding2 = ' ' * (max(max_current_len, len('Current')) - len(current)) |
| 352 |
mlog.log(' ', mlog.green(name), padding1, mlog.yellow(current), padding2, mlog.blue(default)) |
| 353 |
|
| 354 |
def print_augments(self) -> None: |
| 355 |
if self.coredata.optstore.augments: |
| 356 |
mlog.log('\nCurrently set option augments:') |
| 357 |
for k, v in self.coredata.optstore.augments.items(): |
| 358 |
mlog.log(f'{k!s:21}{stringify(v):10}') |
| 359 |
else: |
| 360 |
mlog.log('\nThere are no option augments.') |
| 361 |
|
| 362 |
def has_option_flags(options: CMDOptions) -> bool: |
| 363 |
return bool(options.cmd_line_options) |
| 364 |
|
| 365 |
def is_print_only(options: CMDOptions) -> bool: |
| 366 |
if has_option_flags(options): |
| 367 |
return False |
| 368 |
if options.clearcache: |
| 369 |
return False |
| 370 |
return True |
| 371 |
|
| 372 |
def run_impl(options: CMDOptions, builddir: str) -> int: |
| 373 |
print_only = is_print_only(options) |
| 374 |
c = None |
| 375 |
try: |
| 376 |
c = Conf(builddir) |
| 377 |
if c.default_values_only and not print_only: |
| 378 |
raise mesonlib.MesonException('No valid build directory found, cannot modify options.') |
| 379 |
if c.default_values_only or print_only: |
| 380 |
c.print_conf(options.pager) |
| 381 |
return 0 |
| 382 |
|
| 383 |
save = False |
| 384 |
if has_option_flags(options): |
| 385 |
save |= c.coredata.set_from_configure_command(options) |
| 386 |
cmdline.update_cmd_line_file(builddir, options) |
| 387 |
if options.clearcache: |
| 388 |
c.clear_cache() |
| 389 |
save = True |
| 390 |
if save: |
| 391 |
c.save() |
| 392 |
build = unwrap(c.build) |
| 393 |
mintro.update_build_options(c.coredata, build.environment.info_dir) |
| 394 |
mintro.write_meson_info_file(build, []) |
| 395 |
except ConfException as e: |
| 396 |
mlog.log('Meson configurator encountered an error:') |
| 397 |
if c is not None and c.build is not None: |
| 398 |
mintro.write_meson_info_file(c.build, [e]) |
| 399 |
raise e |
| 400 |
except BrokenPipeError: |
| 401 |
# Pager quit before we wrote everything. |
| 402 |
pass |
| 403 |
return 0 |
| 404 |
|
| 405 |
def run(options: CMDOptions) -> int: |
| 406 |
cmdline.parse_cmd_line_options(options) |
| 407 |
builddir = os.path.abspath(os.path.realpath(options.builddir)) |
| 408 |
return run_impl(options, builddir) |