Debian Codegraph @

mesonbuild/cmdline.py

raw
1 # SPDX-License-Identifier: Apache-2.0
2 # Copyright 2013-2025 The Meson development team
3
4 from __future__ import annotations
5
6 import argparse
7 import ast
8 import configparser
9 import os
10 import shlex
11 import typing as T
12
13 from . import options
14 from .mesonlib import MesonException
15 from .options import OptionKey
16
17 if T.TYPE_CHECKING:
18 from typing_extensions import Protocol
19
20 # typeshed
21 StrOrBytesPath = T.Union[str, bytes, os.PathLike[str], os.PathLike[bytes]]
22
23 class SharedCMDOptions(Protocol):
24 """Representation of command line options from Meson setup, configure,
25 and dist.
26
27 :param cmd_line_options: command line options parsed into an OptionKey:
28 str mapping
29 :param builtin_keys: set of OptionKeys that were passed as --option
30 :param d_keys: set of OptionKeys that were passed as -Doption=value
31 """
32
33 cmd_line_options: T.Dict[OptionKey, T.Optional[str]]
34 builtin_keys: T.Set[OptionKey]
35 d_keys: T.Set[OptionKey]
36 cross_file: T.List[str]
37 native_file: T.List[str]
38
39
40 class CmdLineFileParser(configparser.ConfigParser):
41 def __init__(self) -> None:
42 # We don't want ':' as key delimiter, otherwise it would break when
43 # storing subproject options like "subproject:option=value"
44 super().__init__(delimiters=['='], interpolation=None)
45
46 def read(self, filenames: T.Union['StrOrBytesPath', T.Iterable['StrOrBytesPath']], encoding: T.Optional[str] = 'utf-8') -> T.List[str]:
47 return super().read(filenames, encoding)
48
49 def optionxform(self, optionstr: str) -> str:
50 # Don't call str.lower() on keys
51 return optionstr
52
53
54 def get_cmd_line_file(build_dir: str) -> str:
55 return os.path.join(build_dir, 'meson-private', 'cmd_line.txt')
56
57 def read_cmd_line_file(build_dir: str, options: SharedCMDOptions) -> None:
58 filename = get_cmd_line_file(build_dir)
59 if not os.path.isfile(filename):
60 return
61
62 config = CmdLineFileParser()
63 config.read(filename)
64
65 # Do a copy because config is not really a dict. options.cmd_line_options
66 # overrides values from the file.
67 d: dict[OptionKey, str | None] = {OptionKey.from_string(k): v for k, v in config['options'].items()}
68 d.update(options.cmd_line_options)
69 options.cmd_line_options = d
70 options.builtin_keys = set()
71 options.d_keys = set(d)
72
73 properties = config['properties']
74 if not options.cross_file:
75 options.cross_file = ast.literal_eval(properties.get('cross_file', '[]'))
76 if not options.native_file:
77 # This will be a string in the form: "['first', 'second', ...]", use
78 # literal_eval to get it into the list of strings.
79 options.native_file = ast.literal_eval(properties.get('native_file', '[]'))
80
81 def write_cmd_line_file(build_dir: str, options: SharedCMDOptions) -> None:
82 filename = get_cmd_line_file(build_dir)
83 config = CmdLineFileParser()
84
85 properties: T.Dict[str, T.List[str]] = {}
86 if options.cross_file:
87 properties['cross_file'] = options.cross_file
88 if options.native_file:
89 properties['native_file'] = options.native_file
90
91 config['options'] = {str(k): str(v) for k, v in options.cmd_line_options.items()}
92 config['properties'] = {k: repr(v) for k, v in properties.items()}
93 with open(filename, 'w', encoding='utf-8') as f:
94 config.write(f)
95
96 def update_cmd_line_file(build_dir: str, options: SharedCMDOptions) -> None:
97 filename = get_cmd_line_file(build_dir)
98 config = CmdLineFileParser()
99 config.read(filename)
100 if 'options' not in config:
101 # file missing or corrupted, write it from scratch including
102 # the [properties] section
103 write_cmd_line_file(build_dir, options)
104 return
105 for k, v in options.cmd_line_options.items():
106 keystr = str(k)
107 if v is not None:
108 config['options'][keystr] = str(v)
109 elif keystr in config['options']:
110 del config['options'][keystr]
111
112 with open(filename, 'w', encoding='utf-8') as f:
113 config.write(f)
114
115 def format_cmd_line_options(options: SharedCMDOptions) -> str:
116 cmdline = ['-D{}={}'.format(str(k), v) for k, v in options.cmd_line_options.items()]
117 if options.cross_file:
118 cmdline += [f'--cross-file={f}' for f in options.cross_file]
119 if options.native_file:
120 cmdline += [f'--native-file={f}' for f in options.native_file]
121 return ' '.join([shlex.quote(x) for x in cmdline])
122
123
124 class KeyNoneAction(argparse.Action):
125 """
126 Custom argparse Action that stores values in a dictionary as keys with value None.
127 """
128
129 def __init__(self, option_strings: str, dest: str, nargs: T.Optional[T.Union[int, str]] = None, **kwargs: T.Any) -> None:
130 assert nargs is None or nargs == 1
131 super().__init__(option_strings, dest, nargs=1, **kwargs)
132
133 def __call__(self, parser: argparse.ArgumentParser, namespace: argparse.Namespace,
134 arg: T.List[str], option_string: str | None = None) -> None: # type: ignore[override]
135 current_dict = getattr(namespace, self.dest)
136 if current_dict is None:
137 current_dict = {}
138 setattr(namespace, self.dest, current_dict)
139
140 key = OptionKey.from_string(arg[0])
141 current_dict[key] = None
142
143
144 class BuiltinAction(argparse.Action):
145 """
146 Custom argparse Action for builtin options that stores directly into cmd_line_options.
147 """
148
149 def __init__(self, option_strings: str, dest: str,
150 option_key: OptionKey, option: options.AnyOptionType,
151 help_suffix: str = '', **kwargs: T.Any) -> None:
152 self.option_key = option_key
153
154 h = option.description.rstrip('.')
155 if isinstance(option.default, bool):
156 kwargs['nargs'] = 0
157 else:
158 kwargs['nargs'] = 1
159 if help_suffix:
160 help_suffix += ', '
161 help_suffix += 'default: ' + str(options.argparse_prefixed_default(option, name=option_key))
162 if isinstance(option, (options.EnumeratedUserOption, options.UserArrayOption)):
163 kwargs['choices'] = option.choices
164
165 if help_suffix:
166 help_suffix = f' ({help_suffix})'
167 super().__init__(option_strings, 'cmd_line_options', default=argparse.SUPPRESS,
168 help=f'{h}{help_suffix}.', **kwargs)
169
170 def __call__(self, parser: argparse.ArgumentParser, namespace: argparse.Namespace,
171 arg: T.Optional[T.List[str]], option_string: str | None = None) -> None: # type: ignore[override]
172 current_dict = getattr(namespace, self.dest)
173 if current_dict is None:
174 current_dict = {}
175 setattr(namespace, self.dest, current_dict)
176
177 current_dict[self.option_key] = 'true' if not arg else arg[0]
178 if hasattr(namespace, 'builtin_keys'):
179 namespace.builtin_keys.add(self.option_key)
180
181
182 class KeyValueAction(argparse.Action):
183 """
184 Custom argparse Action that parses KEY=VAL arguments and stores them in a dictionary.
185 """
186
187 def __init__(self, option_strings: str, dest: str, nargs: T.Optional[T.Union[int, str]] = None, **kwargs: T.Any) -> None:
188 assert nargs is None or nargs == 1
189 super().__init__(option_strings, dest, nargs=1, **kwargs)
190
191 def __call__(self, parser: argparse.ArgumentParser, namespace: argparse.Namespace,
192 arg: T.List[str], option_string: str | None = None) -> None: # type: ignore[override]
193 current_dict = getattr(namespace, self.dest)
194 if current_dict is None:
195 current_dict = {}
196 setattr(namespace, self.dest, current_dict)
197
198 try:
199 keystr, value = arg[0].split('=', 1)
200 key = OptionKey.from_string(keystr)
201 current_dict[key] = value
202 except ValueError:
203 parser.error(f'The argument for option {option_string!r} must be in OPTION=VALUE format.')
204
205 if hasattr(namespace, 'd_keys'):
206 namespace.d_keys.add(key)
207
208
209 def register_builtin_arguments(parser: argparse.ArgumentParser) -> None:
210 for n, b in options.BUILTIN_OPTIONS.items():
211 cmdline_name = options.argparse_name_to_arg(str(n))
212 parser.add_argument(cmdline_name, action=BuiltinAction,
213 option_key=n, option=b)
214 for n, b in options.BUILTIN_OPTIONS_PER_MACHINE.items():
215 cmdline_name = options.argparse_name_to_arg(str(n))
216 parser.add_argument(cmdline_name, action=BuiltinAction,
217 option_key=n, option=b, help_suffix='just for host machine')
218 build_n = n.as_build()
219 cmdline_name = options.argparse_name_to_arg(str(build_n))
220 parser.add_argument(cmdline_name, action=BuiltinAction,
221 option_key=build_n, option=b, help_suffix='just for build machine')
222 parser.add_argument('-D', action=KeyValueAction, dest='cmd_line_options', default={}, metavar="option=value",
223 help='Set the value of an option, can be used several times to set multiple options.')
224 parser.set_defaults(builtin_keys=set(), d_keys=set())
225
226 def parse_cmd_line_options(args: SharedCMDOptions) -> None:
227 # Check for options passed as both --option and -Doption=value.
228 overlap = args.builtin_keys & args.d_keys
229 if overlap:
230 name = str(overlap.pop())
231 cmdline_name = options.argparse_name_to_arg(name)
232 raise MesonException(
233 f'Got argument {name} as both -D{name} and {cmdline_name}. Pick one.')
234
235 # Ensure buildtype is processed before debug and optimization, so that
236 # the buildtype expansion sets their defaults and explicit values for
237 # debug/optimization override them.
238 bt_key = OptionKey('buildtype')
239 if bt_key in args.cmd_line_options:
240 bt_val = args.cmd_line_options.pop(bt_key)
241 args.cmd_line_options = {bt_key: bt_val, **args.cmd_line_options}