Skip to content

Commit

Permalink
coredata: use a Protocol for shared options between setup configure a…
Browse files Browse the repository at this point in the history
…nd dist

These are all passed around interchangably inside Meson, so use a shared
protocol for them.
  • Loading branch information
dcbaker committed Feb 23, 2024
1 parent 39e1bf1 commit 95b3b9f
Show file tree
Hide file tree
Showing 6 changed files with 45 additions and 24 deletions.
13 changes: 6 additions & 7 deletions mesonbuild/ast/introspection.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,6 @@
# or an interpreter-based tool

from __future__ import annotations
import argparse
import copy
import os
import typing as T
Expand All @@ -31,13 +30,13 @@
'static_library', 'both_libraries'
]

class IntrospectionHelper(argparse.Namespace):
class IntrospectionHelper:
# mimic an argparse namespace
def __init__(self, cross_file: str):
super().__init__()
self.cross_file = cross_file
self.native_file: str = None
self.cmd_line_options: T.Dict[str, str] = {}
def __init__(self, cross_file: T.Optional[str]):
self.cross_file = [cross_file] if cross_file is not None else []
self.native_file: T.List[str] = []
self.cmd_line_options: T.Dict[OptionKey, str] = {}
self.projectoptions: T.List[str] = []

def __eq__(self, other: object) -> bool:
return NotImplemented
Expand Down
32 changes: 25 additions & 7 deletions mesonbuild/coredata.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
# SPDX-License-Identifier: Apache-2.0
# Copyright 2013-2023 The Meson development team
# Copyright © 2023 Intel Corporation

from __future__ import annotations

Expand Down Expand Up @@ -31,13 +32,30 @@
import typing as T

if T.TYPE_CHECKING:
from typing_extensions import Protocol

from . import dependencies
from .compilers.compilers import Compiler, CompileResult, RunResult, CompileCheckMode
from .dependencies.detect import TV_DepID
from .environment import Environment
from .mesonlib import FileOrString
from .cmake.traceparser import CMakeCacheEntry

class SharedCMDOptions(Protocol):

"""Representation of command line options from Meson setup, configure,
and dist.
:param projectoptions: The raw list of command line options given
:param cmd_line_options: command line options parsed into an OptionKey:
str mapping
"""

cmd_line_options: T.Dict[OptionKey, str]
projectoptions: T.List[str]
cross_file: T.List[str]
native_file: T.List[str]

OptionDictType = T.Union[T.Dict[str, 'UserOption[T.Any]'], 'OptionsView']
MutableKeyedOptionDictType = T.Dict['OptionKey', 'UserOption[T.Any]']
KeyedOptionDictType = T.Union[MutableKeyedOptionDictType, 'OptionsView']
Expand Down Expand Up @@ -546,7 +564,7 @@ def languages(self) -> T.Set[str]:

class CoreData:

def __init__(self, options: argparse.Namespace, scratch_dir: str, meson_command: T.List[str]):
def __init__(self, options: SharedCMDOptions, scratch_dir: str, meson_command: T.List[str]):
self.lang_guids = {
'default': '8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942',
'c': '8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942',
Expand Down Expand Up @@ -587,7 +605,7 @@ def __init__(self, options: argparse.Namespace, scratch_dir: str, meson_command:
self.init_builtins('')

@staticmethod
def __load_config_files(options: argparse.Namespace, scratch_dir: str, ftype: str) -> T.List[str]:
def __load_config_files(options: SharedCMDOptions, scratch_dir: str, ftype: str) -> T.List[str]:
# Need to try and make the passed filenames absolute because when the
# files are parsed later we'll have chdir()d.
if ftype == 'cross':
Expand Down Expand Up @@ -1123,7 +1141,7 @@ def parse_machine_files(filenames: T.List[str], sourcedir: str):
def get_cmd_line_file(build_dir: str) -> str:
return os.path.join(build_dir, 'meson-private', 'cmd_line.txt')

def read_cmd_line_file(build_dir: str, options: argparse.Namespace) -> None:
def read_cmd_line_file(build_dir: str, options: SharedCMDOptions) -> None:
filename = get_cmd_line_file(build_dir)
if not os.path.isfile(filename):
return
Expand All @@ -1145,7 +1163,7 @@ def read_cmd_line_file(build_dir: str, options: argparse.Namespace) -> None:
# literal_eval to get it into the list of strings.
options.native_file = ast.literal_eval(properties.get('native_file', '[]'))

def write_cmd_line_file(build_dir: str, options: argparse.Namespace) -> None:
def write_cmd_line_file(build_dir: str, options: SharedCMDOptions) -> None:
filename = get_cmd_line_file(build_dir)
config = CmdLineFileParser()

Expand All @@ -1160,15 +1178,15 @@ def write_cmd_line_file(build_dir: str, options: argparse.Namespace) -> None:
with open(filename, 'w', encoding='utf-8') as f:
config.write(f)

def update_cmd_line_file(build_dir: str, options: argparse.Namespace) -> None:
def update_cmd_line_file(build_dir: str, options: SharedCMDOptions) -> None:
filename = get_cmd_line_file(build_dir)
config = CmdLineFileParser()
config.read(filename)
config['options'].update({str(k): str(v) for k, v in options.cmd_line_options.items()})
with open(filename, 'w', encoding='utf-8') as f:
config.write(f)

def format_cmd_line_options(options: argparse.Namespace) -> str:
def format_cmd_line_options(options: SharedCMDOptions) -> str:
cmdline = ['-D{}={}'.format(str(k), v) for k, v in options.cmd_line_options.items()]
if options.cross_file:
cmdline += [f'--cross-file={f}' for f in options.cross_file]
Expand Down Expand Up @@ -1226,7 +1244,7 @@ def create_options_dict(options: T.List[str], subproject: str = '') -> T.Dict[Op
result[k] = value
return result

def parse_cmd_line_options(args: argparse.Namespace) -> None:
def parse_cmd_line_options(args: SharedCMDOptions) -> None:
args.cmd_line_options = create_options_dict(args.projectoptions)

# Merge builtin options set with --option into the dict.
Expand Down
6 changes: 3 additions & 3 deletions mesonbuild/environment.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
# SPDX-License-Identifier: Apache-2.0
# Copyright 2012-2020 The Meson development team
# Copyright © 2023 Intel Corporation

from __future__ import annotations

Expand Down Expand Up @@ -35,7 +36,6 @@
from mesonbuild import envconfig

if T.TYPE_CHECKING:
import argparse
from configparser import ConfigParser

from .compilers import Compiler
Expand Down Expand Up @@ -485,7 +485,7 @@ class Environment:
log_dir = 'meson-logs'
info_dir = 'meson-info'

def __init__(self, source_dir: str, build_dir: str, options: 'argparse.Namespace') -> None:
def __init__(self, source_dir: str, build_dir: str, options: coredata.SharedCMDOptions) -> None:
self.source_dir = source_dir
self.build_dir = build_dir
# Do not try to create build directories when build_dir is none.
Expand Down Expand Up @@ -780,7 +780,7 @@ def _set_default_properties_from_env(self) -> None:
self.properties[for_machine].properties.setdefault(name, p_env)
break

def create_new_coredata(self, options: 'argparse.Namespace') -> None:
def create_new_coredata(self, options: coredata.SharedCMDOptions) -> None:
# WARNING: Don't use any values from coredata in __init__. It gets
# re-initialized with project options by the interpreter during
# build file parsing.
Expand Down
4 changes: 1 addition & 3 deletions mesonbuild/interpreter/interpreter.py
Original file line number Diff line number Diff line change
Expand Up @@ -106,8 +106,6 @@
import copy

if T.TYPE_CHECKING:
import argparse

from . import kwargs as kwtypes
from ..backend.backends import Backend
from ..interpreterbase.baseobjects import InterpreterObject, TYPE_var, TYPE_kwargs
Expand Down Expand Up @@ -269,7 +267,7 @@ def __init__(
ast: T.Optional[mparser.CodeBlockNode] = None,
is_translated: bool = False,
relaxations: T.Optional[T.Set[InterpreterRuleRelaxation]] = None,
user_defined_options: T.Optional['argparse.Namespace'] = None,
user_defined_options: T.Optional[coredata.SharedCMDOptions] = None,
) -> None:
super().__init__(_build.environment.get_source_dir(), subdir, subproject)
self.active_projectname = ''
Expand Down
3 changes: 2 additions & 1 deletion mesonbuild/mdist.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
# SPDX-License-Identifier: Apache-2.0
# Copyright 2017 The Meson development team
# Copyright © 2023 Intel Corporation

from __future__ import annotations

Expand Down Expand Up @@ -304,7 +305,7 @@ def check_dist(packagename: str, meson_command: ImmutableListProtocol[str], extr
def create_cmdline_args(bld_root: str) -> T.List[str]:
parser = argparse.ArgumentParser()
msetup_argparse(parser)
args = parser.parse_args([])
args = T.cast('coredata.SharedCMDOptions', parser.parse_args([]))
coredata.parse_cmd_line_options(args)
coredata.read_cmd_line_file(bld_root, args)
args.cmd_line_options.pop(OptionKey('backend'), '')
Expand Down
11 changes: 8 additions & 3 deletions run_tests.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,9 @@
#!/usr/bin/env python3
# SPDX-License-Identifier: Apache-2.0
# Copyright 2012-2021 The Meson development team
# Copyright © 2023-2024 Intel Corporation

from __future__ import annotations

# Work around some pathlib bugs...
from mesonbuild import _pathlib
Expand Down Expand Up @@ -33,6 +36,9 @@
from mesonbuild.coredata import backendlist, version as meson_version
from mesonbuild.mesonlib import OptionKey, setup_vsenv

if T.TYPE_CHECKING:
from mesonbuild.coredata import SharedCMDOptions

NINJA_1_9_OR_NEWER = False
NINJA_CMD = None
# If we're on CI, detecting ninja for every subprocess unit test that we run is slow
Expand Down Expand Up @@ -133,9 +139,8 @@ class FakeCompilerOptions:
def __init__(self):
self.value = []

# TODO: use a typing.Protocol here
def get_fake_options(prefix: str = '') -> argparse.Namespace:
opts = argparse.Namespace()
def get_fake_options(prefix: str = '') -> SharedCMDOptions:
opts = T.cast('SharedCMDOptions', argparse.Namespace())
opts.native_file = []
opts.cross_file = None
opts.wrap_mode = None
Expand Down

0 comments on commit 95b3b9f

Please sign in to comment.