Debian Codegraph @

mesonbuild/rewriter.py

raw
1 # SPDX-License-Identifier: Apache-2.0
2 # Copyright 2016 The Meson development team
3
4 # This tool is used to manipulate an existing Meson build definition.
5 #
6 # - add a file to a target
7 # - remove files from a target
8 # - move targets
9 # - reindent?
10 from __future__ import annotations
11
12 from .ast import IntrospectionInterpreter, BUILD_TARGET_FUNCTIONS, AstConditionLevel, AstIDGenerator, AstIndentationGenerator, AstPrinter
13 from .ast.interpreter import IntrospectionBuildTarget, IntrospectionDependency, _symbol
14 from .interpreterbase import UnknownValue
15 from .interpreterbase.helpers import flatten
16 from mesonbuild.mesonlib import MesonException, pathname_sort_key, relpath, setup_vsenv
17 from . import mlog, environment
18 from functools import wraps
19 from .mparser import Token, ArrayNode, ArgumentNode, ArithmeticNode, AssignmentNode, BaseNode, StringNode, BooleanNode, DictNode, ElementaryNode, IdNode, FunctionNode, PlusAssignmentNode
20 from .mintro import IntrospectionEncoder
21 import json, os, re, sys, codecs
22 import typing as T
23 from pathlib import Path
24
25 if T.TYPE_CHECKING:
26 import argparse
27 from argparse import ArgumentParser, _FormatterClass
28
29 from typing_extensions import TypeAlias
30
31 from .mlog import AnsiDecorator
32
33 RewriterKeysT: TypeAlias = dict[str, tuple[type, object | None, list[str] | None]]
34 RewriterFuncT: TypeAlias = T.Callable[['Rewriter', dict[str, object]], None]
35
36 class RewriterException(MesonException):
37 pass
38
39 # Note: when adding arguments, please also add them to the completion
40 # scripts in $MESONSRC/data/shell-completions/
41 def add_arguments(parser: ArgumentParser, formatter: _FormatterClass) -> None:
42 parser.add_argument('-s', '--sourcedir', type=str, default='.', metavar='SRCDIR', help='Path to source directory.')
43 parser.add_argument('-V', '--verbose', action='store_true', default=False, help='Enable verbose output')
44 parser.add_argument('-S', '--skip-errors', dest='skip', action='store_true', default=False, help='Skip errors instead of aborting')
45 subparsers = parser.add_subparsers(dest='type', title='Rewriter commands', description='Rewrite command to execute')
46
47 # Target
48 tgt_parser = subparsers.add_parser('target', aliases=['tgt'], help='Modify a target', formatter_class=formatter)
49 tgt_parser.add_argument('-s', '--subdir', default='', dest='subdir', help='Subdirectory of the new target (only for the "add_target" action)')
50 tgt_parser.add_argument('--type', dest='tgt_type', choices=rewriter_keys['target']['target_type'][2], default='executable',
51 help='Type of the target to add (only for the "add_target" action)')
52 tgt_parser.add_argument('target', help='Name or ID of the target')
53 tgt_parser.add_argument('operation', choices=['add', 'rm', 'add_target', 'rm_target', 'add_extra_files', 'rm_extra_files', 'info'],
54 help='Action to execute')
55 tgt_parser.add_argument('sources', nargs='*', help='Sources to add/remove')
56
57 # KWARGS
58 kw_parser = subparsers.add_parser('kwargs', help='Modify keyword arguments', formatter_class=formatter)
59 kw_parser.add_argument('operation', choices=rewriter_keys['kwargs']['operation'][2],
60 help='Action to execute')
61 kw_parser.add_argument('function', choices=list(rewriter_func_kwargs.keys()),
62 help='Function type to modify')
63 kw_parser.add_argument('id', help='ID of the function to modify (must be "/" for "project")')
64 kw_parser.add_argument('kwargs', nargs='*', help='<keyword> <value> pairs, or list of <keyword> for "delete"')
65
66 # Default options
67 def_parser = subparsers.add_parser('default-options', aliases=['def'], help='Modify the project default options', formatter_class=formatter)
68 def_parser.add_argument('operation', choices=rewriter_keys['default_options']['operation'][2],
69 help='Action to execute')
70 def_parser.add_argument('options', nargs='*', help='<key> <value> pairs for "set"; list of <key> for "delete"')
71
72 # JSON file/command
73 cmd_parser = subparsers.add_parser('command', aliases=['cmd'], help='Execute a JSON array of commands', formatter_class=formatter)
74 cmd_parser.add_argument('json', help='JSON string or file to execute')
75
76 class RequiredKeys:
77 def __init__(self, keys: RewriterKeysT):
78 self.keys = keys
79
80 def __call__(self, f: RewriterFuncT) -> RewriterFuncT:
81 @wraps(f)
82 def wrapped(rewriter: 'Rewriter', cmd: dict[str, object]) -> None:
83 for key, (typ, default, choices) in self.keys.items():
84 if key not in cmd:
85 if default is not None:
86 cmd[key] = default
87 else:
88 raise RewriterException('Key "{}" is missing in object for {}'
89 .format(key, f.__name__))
90 if not isinstance(cmd[key], typ):
91 raise RewriterException('Invalid type of "{}". Required is {} but provided was {}'
92 .format(key, typ.__name__, type(cmd[key]).__name__))
93 if choices is not None:
94 if cmd[key] not in choices:
95 raise RewriterException('Invalid value of "{}": Possible values are {} but provided was "{}"'
96 .format(key, choices, cmd[key]))
97 return f(rewriter, cmd)
98 return wrapped
99
100 class MTypeBase:
101 node: BaseNode
102
103 def __init__(self, node: T.Optional[BaseNode] = None):
104 if node is None:
105 self.node = self.new_node()
106 else:
107 self.node = node
108 self.node_type = None
109 for i in self.supported_nodes():
110 if isinstance(self.node, i):
111 self.node_type = i
112
113 @classmethod
114 def new_node(cls, value: T.Any = None) -> BaseNode:
115 # Overwrite in derived class
116 raise RewriterException('Internal error: new_node of MTypeBase was called')
117
118 @classmethod
119 def supported_nodes(cls) -> T.List[type]:
120 # Overwrite in derived class
121 return []
122
123 def can_modify(self) -> bool:
124 return self.node_type is not None
125
126 def get_node(self) -> BaseNode:
127 return self.node
128
129 def add_value(self, value: T.Any) -> None:
130 # Overwrite in derived class
131 mlog.warning('Cannot add a value of type', mlog.bold(type(self).__name__), '--> skipping')
132
133 def remove_value(self, value: T.Any) -> None:
134 # Overwrite in derived class
135 mlog.warning('Cannot remove a value of type', mlog.bold(type(self).__name__), '--> skipping')
136
137 def remove_regex(self, value: T.Any) -> None:
138 # Overwrite in derived class
139 mlog.warning('Cannot remove a regex in type', mlog.bold(type(self).__name__), '--> skipping')
140
141 class MTypeStr(MTypeBase):
142 def __init__(self, node: T.Optional[BaseNode] = None):
143 super().__init__(node)
144
145 @classmethod
146 def new_node(cls, value: T.Optional[str] = None) -> BaseNode:
147 if value is None:
148 value = ''
149 return StringNode(Token('string', '', 0, 0, 0, None, str(value)))
150
151 @classmethod
152 def supported_nodes(cls) -> T.List[type]:
153 return [StringNode]
154
155 class MTypeBool(MTypeBase):
156 def __init__(self, node: T.Optional[BaseNode] = None):
157 super().__init__(node)
158
159 @classmethod
160 def new_node(cls, value: T.Optional[str] = None) -> BaseNode:
161 return BooleanNode(Token('', '', 0, 0, 0, None, bool(value)))
162
163 @classmethod
164 def supported_nodes(cls) -> T.List[type]:
165 return [BooleanNode]
166
167 class MTypeID(MTypeBase):
168 def __init__(self, node: T.Optional[BaseNode] = None):
169 super().__init__(node)
170
171 @classmethod
172 def new_node(cls, value: T.Optional[str] = None) -> BaseNode:
173 if value is None:
174 value = ''
175 return IdNode(Token('', '', 0, 0, 0, None, str(value)))
176
177 @classmethod
178 def supported_nodes(cls) -> T.List[type]:
179 return [IdNode]
180
181 class MTypeList(MTypeBase):
182 node: ArrayNode
183
184 def __init__(self, node: T.Optional[BaseNode] = None):
185 super().__init__(node)
186
187 @classmethod
188 def new_node(cls, value: T.Optional[T.List[T.Any]] = None) -> ArrayNode:
189 if value is None:
190 value = []
191 elif not isinstance(value, list):
192 return cls._new_element_node(value)
193 args = ArgumentNode(Token('', '', 0, 0, 0, None, ''))
194 args.arguments = [cls._new_element_node(i) for i in value]
195 return ArrayNode(_symbol('['), args, _symbol(']'))
196
197 @classmethod
198 def _new_element_node(cls, value: T.Any) -> BaseNode:
199 # Overwrite in derived class
200 raise RewriterException('Internal error: _new_element_node of MTypeList was called')
201
202 def _ensure_array_node(self) -> None:
203 if not isinstance(self.node, ArrayNode):
204 tmp = self.node
205 self.node = self.new_node()
206 self.node.args.arguments = [tmp]
207
208 @staticmethod
209 def _check_is_equal(node: BaseNode, value: str) -> bool:
210 # Overwrite in derived class
211 return False
212
213 @staticmethod
214 def _check_regex_matches(node: BaseNode, regex: str) -> bool:
215 # Overwrite in derived class
216 return False
217
218 def get_node(self) -> BaseNode:
219 if isinstance(self.node, ArrayNode):
220 if len(self.node.args.arguments) == 1:
221 return self.node.args.arguments[0]
222 return self.node
223
224 @classmethod
225 def supported_element_nodes(cls) -> T.List[T.Type]:
226 # Overwrite in derived class
227 return []
228
229 @classmethod
230 def supported_nodes(cls) -> T.List[T.Type]:
231 return [ArrayNode] + cls.supported_element_nodes()
232
233 def add_value(self, value: T.Any) -> None:
234 if not isinstance(value, list):
235 value = [value]
236 self._ensure_array_node()
237 for i in value:
238 assert hasattr(self.node, 'args') # For mypy
239 assert isinstance(self.node.args, ArgumentNode) # For mypy
240 self.node.args.arguments += [self._new_element_node(i)]
241
242 def _remove_helper(self, value: T.Any, equal_func: T.Callable[[T.Any, T.Any], bool]) -> None:
243 def check_remove_node(node: BaseNode) -> bool:
244 for j in value:
245 if equal_func(i, j):
246 return True
247 return False
248
249 if not isinstance(value, list):
250 value = [value]
251 self._ensure_array_node()
252 assert hasattr(self.node, 'args') # For mypy
253 assert isinstance(self.node.args, ArgumentNode) # For mypy
254 removed_list = []
255 for i in self.node.args.arguments:
256 if not check_remove_node(i):
257 removed_list += [i]
258 self.node.args.arguments = removed_list
259
260 def remove_value(self, value: T.Any) -> None:
261 self._remove_helper(value, self._check_is_equal)
262
263 def remove_regex(self, regex: str) -> None:
264 self._remove_helper(regex, self._check_regex_matches)
265
266 class MTypeStrList(MTypeList):
267 def __init__(self, node: T.Optional[BaseNode] = None):
268 super().__init__(node)
269
270 @classmethod
271 def _new_element_node(cls, value: str) -> StringNode:
272 return StringNode(Token('string', '', 0, 0, 0, None, str(value)))
273
274 @staticmethod
275 def _check_is_equal(node: BaseNode, value: str) -> bool:
276 if isinstance(node, StringNode):
277 return bool(node.value == value)
278 return False
279
280 @staticmethod
281 def _check_regex_matches(node: BaseNode, regex: str) -> bool:
282 if isinstance(node, StringNode):
283 return re.match(regex, node.value) is not None
284 return False
285
286 @classmethod
287 def supported_element_nodes(cls) -> T.List[T.Type]:
288 return [StringNode]
289
290 class MTypeIDList(MTypeList):
291 def __init__(self, node: T.Optional[BaseNode] = None):
292 super().__init__(node)
293
294 @classmethod
295 def _new_element_node(cls, value: str) -> IdNode:
296 return IdNode(Token('', '', 0, 0, 0, None, str(value)))
297
298 @staticmethod
299 def _check_is_equal(node: BaseNode, value: str) -> bool:
300 if isinstance(node, IdNode):
301 return bool(node.value == value)
302 return False
303
304 @staticmethod
305 def _check_regex_matches(node: BaseNode, regex: str) -> bool:
306 if isinstance(node, StringNode):
307 return re.match(regex, node.value) is not None
308 return False
309
310 @classmethod
311 def supported_element_nodes(cls) -> T.List[T.Type]:
312 return [IdNode]
313
314 rewriter_keys: T.Dict[str, RewriterKeysT] = {
315 'default_options': {
316 'operation': (str, None, ['set', 'delete']),
317 'options': (dict, {}, None)
318 },
319 'kwargs': {
320 'function': (str, None, None),
321 'id': (str, None, None),
322 'operation': (str, None, ['set', 'delete', 'add', 'remove', 'remove_regex', 'info']),
323 'kwargs': (dict, {}, None)
324 },
325 'target': {
326 'target': (str, None, None),
327 'operation': (str, None, ['src_add', 'src_rm', 'target_rm', 'target_add', 'extra_files_add', 'extra_files_rm', 'info']),
328 'sources': (list, [], None),
329 'subdir': (str, '', None),
330 'target_type': (str, 'executable', ['both_libraries', 'executable', 'jar', 'library', 'shared_library', 'shared_module', 'static_library']),
331 }
332 }
333
334 rewriter_func_kwargs = {
335 'dependency': {
336 'language': MTypeStr,
337 'method': MTypeStr,
338 'native': MTypeBool,
339 'not_found_message': MTypeStr,
340 'required': MTypeBool,
341 'static': MTypeBool,
342 'version': MTypeStrList,
343 'modules': MTypeStrList
344 },
345 'target': {
346 'build_by_default': MTypeBool,
347 'build_rpath': MTypeStr,
348 'dependencies': MTypeIDList,
349 'gui_app': MTypeBool,
350 'link_with': MTypeIDList,
351 'export_dynamic': MTypeBool,
352 'implib': MTypeBool,
353 'install': MTypeBool,
354 'install_dir': MTypeStr,
355 'install_rpath': MTypeStr,
356 'pie': MTypeBool
357 },
358 'project': {
359 'default_options': MTypeStrList,
360 'meson_version': MTypeStr,
361 'license': MTypeStrList,
362 'license_files': MTypeStrList,
363 'subproject_dir': MTypeStr,
364 'version': MTypeStr
365 }
366 }
367
368 class Rewriter:
369 info_dump: T.Optional[T.Dict[str, T.Dict[str, T.Any]]]
370
371 def __init__(self, sourcedir: str, generator: str = 'ninja', skip_errors: bool = False):
372 self.sourcedir = sourcedir
373 self.interpreter = IntrospectionInterpreter(sourcedir, '', generator, visitors = [AstIDGenerator(), AstIndentationGenerator(), AstConditionLevel()])
374 self.skip_errors = skip_errors
375 self.modified_nodes: T.List[BaseNode] = []
376 self.to_remove_nodes: T.List[BaseNode] = []
377 self.to_add_nodes: T.List[BaseNode] = []
378 self.functions = {
379 'default_options': self.process_default_options,
380 'kwargs': self.process_kwargs,
381 'target': self.process_target,
382 }
383 self.info_dump = None
384
385 def analyze_meson(self) -> None:
386 mlog.log('Analyzing meson file:', mlog.bold(os.path.join(self.sourcedir, environment.build_filename)))
387 self.interpreter.analyze()
388 mlog.log(' -- Project:', mlog.bold(self.interpreter.project_data['descriptive_name']))
389 mlog.log(' -- Version:', mlog.cyan(self.interpreter.project_data['version']))
390
391 def add_info(self, cmd_type: str, cmd_id: str, data: dict) -> None:
392 if self.info_dump is None:
393 self.info_dump = {}
394 if cmd_type not in self.info_dump:
395 self.info_dump[cmd_type] = {}
396 self.info_dump[cmd_type][cmd_id] = data
397
398 def print_info(self) -> None:
399 if self.info_dump is None:
400 return
401 sys.stdout.write(json.dumps(self.info_dump, indent=2, cls=IntrospectionEncoder))
402
403 def on_error(self) -> T.Tuple[AnsiDecorator, AnsiDecorator]:
404 if self.skip_errors:
405 return mlog.cyan('-->'), mlog.yellow('skipping')
406 return mlog.cyan('-->'), mlog.red('aborting')
407
408 def handle_error(self) -> None:
409 if self.skip_errors:
410 return None
411 raise MesonException('Rewriting the meson.build failed')
412
413 def all_assignments(self, varname: str) -> T.List[BaseNode]:
414 assigned_values = []
415 for ass in self.interpreter.all_assignment_nodes[varname]:
416 if isinstance(ass, PlusAssignmentNode):
417 continue
418 assert isinstance(ass, AssignmentNode)
419 assigned_values.append(ass.value)
420 return assigned_values
421
422 def find_target(self, target: str) -> T.Optional[IntrospectionBuildTarget]:
423 for i in self.interpreter.targets:
424 if target == i.id:
425 return i
426
427 potential_tgts = []
428 for i in self.interpreter.targets:
429 if target == i.name:
430 potential_tgts.append(i)
431
432 if not potential_tgts:
433 potenial_tgts_1 = self.all_assignments(target)
434 potenial_tgts_1 = [self.interpreter.node_to_runtime_value(el) for el in potenial_tgts_1]
435 potential_tgts = [el for el in potenial_tgts_1 if isinstance(el, IntrospectionBuildTarget)]
436
437 if not potential_tgts:
438 return None
439 elif len(potential_tgts) == 1:
440 return potential_tgts[0]
441 else:
442 mlog.error('There are multiple targets matching', mlog.bold(target))
443 for i in potential_tgts:
444 mlog.error(' -- Target name', mlog.bold(i.name), 'with ID', mlog.bold(i.id))
445 mlog.error('Please try again with the unique ID of the target', *self.on_error())
446 self.handle_error()
447 return None
448
449 def find_dependency(self, dependency: str) -> T.Optional[IntrospectionDependency]:
450 potential_deps = []
451 for i in self.interpreter.dependencies:
452 if i.name == dependency:
453 potential_deps.append(i)
454
455 checking_varnames = len(potential_deps) == 0
456
457 if checking_varnames:
458 potential_deps1 = self.all_assignments(dependency)
459 potential_deps = [self.interpreter.node_to_runtime_value(el) for el in potential_deps1 if isinstance(el, FunctionNode) and el.func_name.value == 'dependency']
460
461 if not potential_deps:
462 return None
463 elif len(potential_deps) == 1:
464 return potential_deps[0]
465 else:
466 mlog.error('There are multiple dependencies matching', mlog.bold(dependency))
467 for i in potential_deps:
468 mlog.error(' -- Dependency name', i)
469 if checking_varnames:
470 mlog.error('Please try again with the name of the dependency', *self.on_error())
471 self.handle_error()
472 return None
473
474 @RequiredKeys(rewriter_keys['default_options'])
475 def process_default_options(self, cmd: T.Dict[str, T.Any]) -> None:
476 # First, remove the old values
477 kwargs_cmd: T.Dict[str, T.Any] = {
478 'function': 'project',
479 'id': "/",
480 'operation': 'remove_regex',
481 'kwargs': {
482 'default_options': [f'{x}=.*' for x in cmd['options'].keys()]
483 }
484 }
485 self.process_kwargs(kwargs_cmd)
486
487 # Then add the new values
488 if cmd['operation'] != 'set':
489 return
490
491 kwargs_cmd['operation'] = 'add'
492 kwargs_cmd['kwargs']['default_options'] = []
493
494 cdata = self.interpreter.coredata
495 options = {
496 **{str(k): v for k, v in cdata.optstore.items()},
497 }
498
499 for key, val in sorted(cmd['options'].items()):
500 if key not in options:
501 mlog.error('Unknown options', mlog.bold(key), *self.on_error())
502 self.handle_error()
503 continue
504
505 try:
506 val = options[key].validate_value(val)
507 except MesonException as e:
508 mlog.error('Unable to set', mlog.bold(key), mlog.red(str(e)), *self.on_error())
509 self.handle_error()
510 continue
511
512 kwargs_cmd['kwargs']['default_options'] += [f'{key}={val}']
513
514 self.process_kwargs(kwargs_cmd)
515
516 @RequiredKeys(rewriter_keys['kwargs'])
517 def process_kwargs(self, cmd: T.Dict[str, T.Any]) -> None:
518 mlog.log('Processing function type', mlog.bold(cmd['function']), 'with id', mlog.cyan("'" + cmd['id'] + "'"))
519 if cmd['function'] not in rewriter_func_kwargs:
520 mlog.error('Unknown function type', cmd['function'], *self.on_error())
521 return self.handle_error()
522 kwargs_def = rewriter_func_kwargs[cmd['function']]
523
524 # Find the function node to modify
525 node = None
526 arg_node = None
527 if cmd['function'] == 'project':
528 # msys bash may expand '/' to a path. It will mangle '//' to '/'
529 # but in order to keep usage shell-agnostic, also allow `//` as
530 # the function ID such that it will work in both msys bash and
531 # other shells.
532 if {'/', '//'}.isdisjoint({cmd['id']}):
533 mlog.error('The ID for the function type project must be "/" or "//" not "' + cmd['id'] + '"', *self.on_error())
534 return self.handle_error()
535 node = self.interpreter.project_node
536 arg_node = node.args
537 elif cmd['function'] == 'target':
538 tmp_tgt = self.find_target(cmd['id'])
539 if not tmp_tgt:
540 mlog.error('Unable to find the target', mlog.bold(cmd['id']), *self.on_error())
541 return self.handle_error()
542 node = tmp_tgt.node
543 arg_node = node.args
544 elif cmd['function'] == 'dependency':
545 tmp_dep = self.find_dependency(cmd['id'])
546 if not tmp_dep:
547 mlog.error('Unable to find the dependency', mlog.bold(cmd['id']), *self.on_error())
548 return self.handle_error()
549 node = tmp_dep.node
550 arg_node = node.args
551 if not node:
552 mlog.error('Unable to find the function node', *self.on_error())
553 return self.handle_error()
554 assert isinstance(node, FunctionNode)
555 assert isinstance(arg_node, ArgumentNode)
556 # Transform the key nodes to plain strings
557 kwargs = {T.cast(IdNode, k).value: v for k, v in arg_node.kwargs.items()}
558
559 # Print kwargs info
560 if cmd['operation'] == 'info':
561 info_data: T.Dict[str, T.Any] = {}
562 for key, val in sorted(kwargs.items()):
563 info_data[key] = None
564 if isinstance(val, ElementaryNode):
565 info_data[key] = val.value
566 elif isinstance(val, ArrayNode):
567 data_list = []
568 for i in val.args.arguments:
569 element = None
570 if isinstance(i, ElementaryNode):
571 element = i.value
572 data_list += [element]
573 info_data[key] = data_list
574 elif isinstance(val, DictNode):
575 data_dict = {}
576 for k, v in val.args.kwargs.items():
577 if not isinstance(k, StringNode):
578 continue
579 value = None
580 if isinstance(v, ElementaryNode):
581 value = v.value
582 data_dict[k.value] = value
583 info_data[key] = data_dict
584
585 self.add_info('kwargs', '{}#{}'.format(cmd['function'], cmd['id']), info_data)
586 return # Nothing else to do
587
588 # Modify the kwargs
589 num_changed = 0
590 for key, val in sorted(cmd['kwargs'].items()):
591 if key not in kwargs_def:
592 mlog.error('Cannot modify unknown kwarg', mlog.bold(key), *self.on_error())
593 self.handle_error()
594 continue
595
596 if cmd['operation'] == 'delete':
597 # Remove the key from the kwargs
598 if key not in kwargs:
599 mlog.log(' -- Key', mlog.bold(key), 'is already deleted')
600 continue
601 mlog.log(' -- Deleting', mlog.bold(key), 'from the kwargs')
602 del kwargs[key]
603 elif cmd['operation'] == 'set':
604 # Replace the key from the kwargs
605 mlog.log(' -- Setting', mlog.bold(key), 'to', mlog.yellow(str(val)))
606 kwargs[key] = kwargs_def[key].new_node(val)
607 else:
608 # Modify the value from the kwargs
609
610 if key not in kwargs:
611 kwargs[key] = None
612 modifier = kwargs_def[key](kwargs[key])
613 if not modifier.can_modify():
614 mlog.log(' -- Skipping', mlog.bold(key), 'because it is too complex to modify')
615 continue
616
617 # Apply the operation
618 val_str = str(val)
619 if cmd['operation'] == 'add':
620 mlog.log(' -- Adding', mlog.yellow(val_str), 'to', mlog.bold(key))
621 modifier.add_value(val)
622 elif cmd['operation'] == 'remove':
623 mlog.log(' -- Removing', mlog.yellow(val_str), 'from', mlog.bold(key))
624 modifier.remove_value(val)
625 elif cmd['operation'] == 'remove_regex':
626 mlog.log(' -- Removing all values matching', mlog.yellow(val_str), 'from', mlog.bold(key))
627 modifier.remove_regex(val)
628
629 # Write back the result
630 kwargs[key] = modifier.get_node()
631
632 num_changed += 1
633
634 # Convert the keys back to IdNode's
635 arg_node.kwargs = {IdNode(Token('', '', 0, 0, 0, None, k)): v for k, v in kwargs.items()}
636 for k, v in arg_node.kwargs.items():
637 k.level = v.level
638 if num_changed > 0 and node not in self.modified_nodes:
639 self.modified_nodes += [node]
640
641 def find_assignment_node(self, node: BaseNode) -> T.Optional[AssignmentNode]:
642 for k, v in self.interpreter.all_assignment_nodes.items():
643 for ass in v:
644 if ass.value == node:
645 return ass
646 return None
647
648 def affects_no_other_targets(self, candidate: BaseNode) -> bool:
649 affected = self.interpreter.dataflow_dag.reachable({candidate}, False)
650 affected_targets = [x for x in affected if isinstance(x, FunctionNode) and x.func_name.value in BUILD_TARGET_FUNCTIONS]
651 return len(affected_targets) == 1
652
653 def get_relto(self, target_node: BaseNode, node: BaseNode) -> Path:
654 cwd = Path(os.getcwd())
655 all_paths = self.interpreter.dataflow_dag.find_all_paths(node, target_node)
656 # len(all_paths) == 0 would imply that data does not flow from node to
657 # target_node. This would imply that adding sources to node would not
658 # add the source to the target.
659 assert all_paths
660 if len(all_paths) > 1:
661 return None
662 return (cwd / next(x for x in all_paths[0] if isinstance(x, FunctionNode)).filename).parent
663
664 def add_src_or_extra(self, op: str, target: IntrospectionBuildTarget, newfiles: T.List[str], to_sort_nodes: T.List[T.Union[FunctionNode, ArrayNode]]) -> None:
665 assert op in {'src_add', 'extra_files_add'}
666
667 if op == 'src_add':
668 old: T.Set[T.Union[BaseNode, UnknownValue]] = set(target.source_nodes)
669 elif op == 'extra_files_add':
670 if target.extra_files is None:
671 old = set()
672 else:
673 old = {target.extra_files}
674 tgt_function: FunctionNode = target.node
675
676 cwd = Path(os.getcwd())
677 target_dir_abs = cwd / os.path.dirname(target.node.filename)
678 source_root_abs = cwd / self.interpreter.source_root
679
680 candidates1 = self.interpreter.dataflow_dag.reachable(old, True)
681 # A node is a member of the set `candidates1` exactly if data from this node
682 # flow into one of the `dest` nodes. We assume that this implies that if we
683 # add `foo.c` to this node, then 'foo.c' will be added to one of these
684 # nodes. This assumption is not always true:
685 # ar = ['a.c', 'b.c']
686 # srcs = ar[1]
687 # executable('name', srcs)
688 # Data flows from `ar` to `srcs`, but if we add 'foo.c':
689 # ar = ['a.c', 'b.c', 'foo.c']
690 # srcs = ar[1]
691 # executable('name', srcs)
692 # this does not add 'foo.c' to `srcs`. This is a known bug/limitation of
693 # the meson rewriter that could be fixed by replacing `reachable` with a
694 # more advanced analysis. But this is a lot of work and I think e.g.
695 # `srcs = ar[1]` is rare in real-world projects, so I will just leave
696 # this for now.
697
698 candidates2 = {x for x in candidates1 if isinstance(x, (FunctionNode, ArrayNode))}
699
700 # If we have this meson.build file:
701 # shared = ['shared.c']
702 # executable('foo', shared + ['foo.c'])
703 # executable('bar', shared + ['bar.c'])
704 # and we are tasked with adding 'new.c' to 'foo', we should do e.g this:
705 # shared = ['shared.c']
706 # executable('foo', shared + ['foo.c', 'new.c'])
707 # executable('bar', shared + ['bar.c'])
708 # but never this:
709 # shared = ['shared.c', 'new.c']
710 # executable('foo', shared + ['foo.c'])
711 # executable('bar', shared + ['bar.c'])
712 # We do this by removing the `['shared.c']`-node from `candidates2`.
713 candidates2 = {x for x in candidates2 if self.affects_no_other_targets(x)}
714
715 def path_contains_unknowns(candidate: BaseNode) -> bool:
716 all_paths = self.interpreter.dataflow_dag.find_all_paths(candidate, target.node)
717 for path in all_paths:
718 for el in path:
719 if isinstance(el, UnknownValue):
720 return True
721 return False
722
723 candidates2 = {x for x in candidates2 if not path_contains_unknowns(x)}
724
725 candidates2 = {x for x in candidates2 if self.get_relto(target.node, x) is not None}
726
727 chosen: T.Union[FunctionNode, ArrayNode] = None
728 new_kwarg_flag = False
729 if len(candidates2) > 0:
730 # So that files(['a', 'b']) gets modified to files(['a', 'b', 'c']) instead of files(['a', 'b'], 'c')
731 if len({x for x in candidates2 if isinstance(x, ArrayNode)}) > 0:
732 candidates2 = {x for x in candidates2 if isinstance(x, ArrayNode)}
733
734 # We choose one more or less arbitrary candidate
735 chosen = min(candidates2, key=lambda x: (x.lineno, x.colno))
736 elif op == 'src_add':
737 chosen = target.node
738 elif op == 'extra_files_add':
739 chosen = ArrayNode(_symbol('['), ArgumentNode(Token('', tgt_function.filename, 0, 0, 0, None, '[]')), _symbol(']'))
740
741 # this is fundamentally error prone
742 self.interpreter.dataflow_dag.add_edge(chosen, target.node)
743
744 extra_files_idnode = IdNode(Token('string', tgt_function.filename, 0, 0, 0, None, 'extra_files'))
745 if tgt_function not in self.modified_nodes:
746 self.modified_nodes += [tgt_function]
747 new_extra_files_node: BaseNode
748 if target.node.args.get_kwarg_or_default('extra_files', None) is None:
749 # Target has no extra_files kwarg, create one
750 new_kwarg_flag = True
751 new_extra_files_node = chosen
752 else:
753 new_kwarg_flag = True
754 old_extra_files = target.node.args.get_kwarg_or_default('extra_files', None)
755 target.node.args.kwargs = {k: v for k, v in target.node.args.kwargs.items() if not (isinstance(k, IdNode) and k.value == 'extra_files')}
756 new_extra_files_node = ArithmeticNode('+', old_extra_files, _symbol('+'), chosen)
757
758 tgt_function.args.kwargs[extra_files_idnode] = new_extra_files_node
759
760 newfiles_relto = self.get_relto(target.node, chosen)
761 old_src_list: T.List[T.Any] = flatten([self.interpreter.node_to_runtime_value(sn) for sn in old])
762
763 if op == 'src_add':
764 name = 'Source'
765 elif op == 'extra_files_add':
766 name = 'Extra file'
767 # Generate the new String nodes
768 to_append = []
769 added = []
770
771 old_src_list = [(target_dir_abs / x).resolve() if isinstance(x, str) else x.to_abs_path(source_root_abs) for x in old_src_list if not isinstance(x, UnknownValue)]
772 for _newf in sorted(set(newfiles)):
773 newf = Path(_newf)
774 if os.path.isabs(newf):
775 newf = Path(newf)
776 else:
777 newf = source_root_abs / newf
778 if newf in old_src_list:
779 mlog.log(' -- ', name, mlog.green(str(newf)), 'is already defined for the target --> skipping')
780 continue
781
782 mlog.log(' -- Adding ', name.lower(), mlog.green(str(newf)), 'at',
783 mlog.yellow(f'{chosen.filename}:{chosen.lineno}'))
784 added.append(newf)
785 mocktarget = self.interpreter.funcvals[target.node]
786 assert isinstance(mocktarget, IntrospectionBuildTarget)
787 # print("adding ", str(newf), 'to', mocktarget.name) todo: should we write something to stderr?
788
789 path = relpath(newf, newfiles_relto)
790 path = codecs.encode(path, 'unicode_escape').decode() # Because the StringNode constructor does the inverse
791 token = Token('string', chosen.filename, 0, 0, 0, None, path)
792 to_append += [StringNode(token)]
793
794 assert isinstance(chosen, (FunctionNode, ArrayNode))
795 arg_node = chosen.args
796 # Append to the AST at the right place
797 arg_node.arguments += to_append
798
799 # Mark the node as modified
800 if chosen not in to_sort_nodes:
801 to_sort_nodes += [chosen]
802 # If the extra_files array is newly created, i.e. if new_kwarg_flag is
803 # True, don't mark it as its parent function node already is, otherwise
804 # this would cause double modification.
805 if chosen not in self.modified_nodes and not new_kwarg_flag:
806 self.modified_nodes += [chosen]
807
808 # Utility function to get a list of the sources from a node
809 def arg_list_from_node(self, n: BaseNode) -> T.List[BaseNode]:
810 args = []
811 if isinstance(n, FunctionNode):
812 args = list(n.args.arguments)
813 if n.func_name.value in BUILD_TARGET_FUNCTIONS:
814 args.pop(0)
815 elif isinstance(n, ArrayNode):
816 args = n.args.arguments
817 elif isinstance(n, ArgumentNode):
818 args = n.arguments
819 return args
820
821 def rm_src_or_extra(self, op: str, target: IntrospectionBuildTarget, to_be_removed: T.List[str], to_sort_nodes: T.List[T.Union[FunctionNode, ArrayNode]]) -> None:
822 assert op in {'src_rm', 'extra_files_rm'}
823 cwd = Path(os.getcwd())
824 source_root_abs = cwd / self.interpreter.source_root
825
826 # Helper to find the exact string node and its parent
827 def find_node(src: str) -> T.Tuple[T.Optional[BaseNode], T.Optional[StringNode]]:
828 if op == 'src_rm':
829 nodes = self.interpreter.dataflow_dag.reachable(set(target.source_nodes), True).union({target.node})
830 elif op == 'extra_files_rm':
831 nodes = self.interpreter.dataflow_dag.reachable({target.extra_files}, True)
832 for i in nodes:
833 if isinstance(i, UnknownValue):
834 continue
835 relto = self.get_relto(target.node, i)
836 if relto is not None:
837 for j in self.arg_list_from_node(i):
838 if isinstance(j, StringNode):
839 if os.path.normpath(relto / j.value) == os.path.normpath(source_root_abs / src):
840 return i, j
841 return None, None
842
843 if op == 'src_rm':
844 name = 'source'
845 elif op == 'extra_files_rm':
846 name = 'extra file'
847
848 for i in to_be_removed:
849 # Try to find the node with the source string
850 root, string_node = find_node(i)
851 if root is None:
852 mlog.warning(' -- Unable to find', name, mlog.green(i), 'in the target')
853 continue
854 if not self.affects_no_other_targets(string_node):
855 mlog.warning(' -- Removing the', name, mlog.green(i), 'is too compilicated')
856 continue
857
858 if not isinstance(root, (FunctionNode, ArrayNode)):
859 raise NotImplementedError # I'm lazy
860
861 # Remove the found string node from the argument list
862 arg_node = root.args
863 mlog.log(' -- Removing', name, mlog.green(i), 'from',
864 mlog.yellow(f'{string_node.filename}:{string_node.lineno}'))
865 arg_node.arguments.remove(string_node)
866
867 # Mark the node as modified
868 if root not in to_sort_nodes:
869 to_sort_nodes += [root]
870 if root not in self.modified_nodes:
871 self.modified_nodes += [root]
872
873 @RequiredKeys(rewriter_keys['target'])
874 def process_target(self, cmd: T.Dict[str, T.Any]) -> None:
875 mlog.log('Processing target', mlog.bold(cmd['target']), 'operation', mlog.cyan(cmd['operation']))
876 target = self.find_target(cmd['target'])
877 if target is None and cmd['operation'] != 'target_add':
878 mlog.error('Unknown target', mlog.bold(cmd['target']), *self.on_error())
879 return self.handle_error()
880
881 # Make source paths relative to the current subdir
882 def rel_source(src: str) -> str:
883 subdir = os.path.abspath(os.path.join(self.sourcedir, target.subdir))
884 if os.path.isabs(src):
885 return os.path.relpath(src, subdir)
886 elif not os.path.exists(src):
887 return src # Trust the user when the source doesn't exist
888 # Make sure that the path is relative to the subdir
889 return os.path.relpath(os.path.abspath(src), subdir)
890
891 if target is not None:
892 cmd['sources'] = [rel_source(x) for x in cmd['sources']]
893
894 to_sort_nodes: T.List[T.Union[FunctionNode, ArrayNode]] = []
895
896 if cmd['operation'] in {'src_add', 'extra_files_add'}:
897 self.add_src_or_extra(cmd['operation'], target, cmd['sources'], to_sort_nodes)
898
899 elif cmd['operation'] in {'src_rm', 'extra_files_rm'}:
900 self.rm_src_or_extra(cmd['operation'], target, cmd['sources'], to_sort_nodes)
901
902 elif cmd['operation'] == 'target_add':
903 if target is not None:
904 mlog.error('Can not add target', mlog.bold(cmd['target']), 'because it already exists', *self.on_error())
905 return self.handle_error()
906
907 id_base = re.sub(r'[- ]', '_', cmd['target'])
908 target_id = id_base + '_exe' if cmd['target_type'] == 'executable' else '_lib'
909 source_id = id_base + '_sources'
910 filename = os.path.join(os.getcwd(), self.interpreter.source_root, cmd['subdir'], environment.build_filename)
911
912 # Build src list
913 src_arg_node = ArgumentNode(Token('string', filename, 0, 0, 0, None, ''))
914 src_arr_node = ArrayNode(_symbol('['), src_arg_node, _symbol(']'))
915 src_far_node = ArgumentNode(Token('string', filename, 0, 0, 0, None, ''))
916 src_fun_node = FunctionNode(IdNode(Token('id', filename, 0, 0, 0, (0, 0), 'files')), _symbol('('), src_far_node, _symbol(')'))
917 src_ass_node = AssignmentNode(IdNode(Token('id', filename, 0, 0, 0, (0, 0), source_id)), _symbol('='), src_fun_node)
918 src_arg_node.arguments = [StringNode(Token('string', filename, 0, 0, 0, None, x)) for x in cmd['sources']]
919 src_far_node.arguments = [src_arr_node]
920
921 # Build target
922 tgt_arg_node = ArgumentNode(Token('string', filename, 0, 0, 0, None, ''))
923 tgt_fun_node = FunctionNode(IdNode(Token('id', filename, 0, 0, 0, (0, 0), cmd['target_type'])), _symbol('('), tgt_arg_node, _symbol(')'))
924 tgt_ass_node = AssignmentNode(IdNode(Token('id', filename, 0, 0, 0, (0, 0), target_id)), _symbol('='), tgt_fun_node)
925 tgt_arg_node.arguments = [
926 StringNode(Token('string', filename, 0, 0, 0, None, cmd['target'])),
927 IdNode(Token('string', filename, 0, 0, 0, None, source_id))
928 ]
929
930 src_ass_node.accept(AstIndentationGenerator())
931 tgt_ass_node.accept(AstIndentationGenerator())
932 self.to_add_nodes += [src_ass_node, tgt_ass_node]
933
934 elif cmd['operation'] == 'target_rm':
935 to_remove: BaseNode = self.find_assignment_node(target.node)
936 if to_remove is None:
937 to_remove = target.node
938 self.to_remove_nodes += [to_remove]
939 mlog.log(' -- Removing target', mlog.green(cmd['target']), 'at',
940 mlog.yellow(f'{to_remove.filename}:{to_remove.lineno}'))
941
942 elif cmd['operation'] == 'info':
943 # T.List all sources in the target
944
945 cwd = Path(os.getcwd())
946 source_root_abs = cwd / self.interpreter.source_root
947
948 src_list = self.interpreter.nodes_to_pretty_filelist(source_root_abs, target.subdir, target.source_nodes)
949 extra_files_list = self.interpreter.nodes_to_pretty_filelist(source_root_abs, target.subdir, [target.extra_files] if target.extra_files else [])
950
951 src_list = ['unknown' if isinstance(x, UnknownValue) else relpath(x, source_root_abs) for x in src_list]
952 extra_files_list = ['unknown' if isinstance(x, UnknownValue) else relpath(x, source_root_abs) for x in extra_files_list]
953
954 test_data = {
955 'name': target.name,
956 'sources': src_list,
957 'extra_files': extra_files_list
958 }
959 self.add_info('target', target.id, test_data)
960
961 # Sort files
962 for i in to_sort_nodes:
963 if isinstance(i, FunctionNode) and i.func_name.value in BUILD_TARGET_FUNCTIONS:
964 src_args = i.args.arguments[1:]
965 target_name = [i.args.arguments[0]]
966 else:
967 src_args = i.args.arguments
968 target_name = []
969 unknown: T.List[BaseNode] = [x for x in src_args if not isinstance(x, StringNode)]
970 sources: T.List[StringNode] = [x for x in src_args if isinstance(x, StringNode)]
971 sources = sorted(sources, key=lambda x: pathname_sort_key(x.value))
972 i.args.arguments = target_name + unknown + T.cast(T.List[BaseNode], sources)
973
974 def process(self, cmd: T.Dict[str, T.Any]) -> None:
975 if 'type' not in cmd:
976 raise RewriterException('Command has no key "type"')
977 if cmd['type'] not in self.functions:
978 raise RewriterException('Unknown command "{}". Supported commands are: {}'
979 .format(cmd['type'], list(self.functions.keys())))
980 self.functions[cmd['type']](cmd)
981
982 def apply_changes(self) -> None:
983 assert all(hasattr(x, 'lineno') and hasattr(x, 'colno') and hasattr(x, 'filename') for x in self.modified_nodes)
984 assert all(hasattr(x, 'lineno') and hasattr(x, 'colno') and hasattr(x, 'filename') for x in self.to_remove_nodes)
985 assert all(isinstance(x, (ArrayNode, FunctionNode)) for x in self.modified_nodes)
986 assert all(isinstance(x, (ArrayNode, AssignmentNode, FunctionNode)) for x in self.to_remove_nodes)
987 # Sort based on line and column in reversed order
988 work_nodes = [{'node': x, 'action': 'modify'} for x in self.modified_nodes]
989 work_nodes += [{'node': x, 'action': 'rm'} for x in self.to_remove_nodes]
990 work_nodes = sorted(work_nodes, key=lambda x: (T.cast(BaseNode, x['node']).lineno, T.cast(BaseNode, x['node']).colno), reverse=True)
991 work_nodes += [{'node': x, 'action': 'add'} for x in self.to_add_nodes]
992
993 # Generating the new replacement string
994 str_list = []
995 for i in work_nodes:
996 new_data = ''
997 if i['action'] == 'modify' or i['action'] == 'add':
998 printer = AstPrinter()
999 T.cast(BaseNode, i['node']).accept(printer)
1000 printer.post_process()
1001 new_data = printer.result.strip()
1002 data = {
1003 'file': T.cast(BaseNode, i['node']).filename,
1004 'str': new_data,
1005 'node': i['node'],
1006 'action': i['action']
1007 }
1008 str_list += [data]
1009
1010 # Load build files
1011 files: T.Dict[str, T.Any] = {}
1012 for i in str_list:
1013 if i['file'] in files:
1014 continue
1015 fpath = os.path.realpath(T.cast(str, i['file']))
1016 fdata = ''
1017 # Create an empty file if it does not exist
1018 if not os.path.exists(fpath):
1019 with open(fpath, 'w', encoding='utf-8'):
1020 pass
1021 with open(fpath, encoding='utf-8') as fp:
1022 fdata = fp.read()
1023
1024 # Generate line offsets numbers
1025 m_lines = fdata.splitlines(True)
1026 offset = 0
1027 line_offsets = []
1028 for j in m_lines:
1029 line_offsets += [offset]
1030 offset += len(j)
1031
1032 files[T.cast(str, i['file'])] = {
1033 'path': fpath,
1034 'raw': fdata,
1035 'offsets': line_offsets
1036 }
1037
1038 # Replace in source code
1039 def remove_node(i: T.Dict[str, T.Any]) -> None:
1040 offsets = files[i['file']]['offsets']
1041 raw = files[i['file']]['raw']
1042 node = i['node']
1043 line = node.lineno - 1
1044 col = node.colno
1045 start = offsets[line] + col
1046 end = start
1047 if isinstance(node, (ArrayNode, FunctionNode)):
1048 end = offsets[node.end_lineno - 1] + node.end_colno
1049
1050 # Only removal is supported for assignments
1051 elif isinstance(node, AssignmentNode) and i['action'] == 'rm':
1052 if isinstance(node.value, (ArrayNode, FunctionNode)):
1053 remove_node({'file': i['file'], 'str': '', 'node': node.value, 'action': 'rm'})
1054 raw = files[i['file']]['raw']
1055 while raw[end] != '=':
1056 end += 1
1057 end += 1 # Handle the '='
1058 while raw[end] in {' ', '\n', '\t'}:
1059 end += 1
1060
1061 files[i['file']]['raw'] = raw[:start] + i['str'] + raw[end:]
1062
1063 for i in str_list:
1064 if i['action'] in {'modify', 'rm'}:
1065 remove_node(i)
1066 elif i['action'] == 'add':
1067 files[T.cast(str, i['file'])]['raw'] += T.cast(str, i['str']) + '\n'
1068
1069 # Write the files back
1070 for key, val in files.items():
1071 mlog.log('Rewriting', mlog.yellow(key))
1072 with open(val['path'], 'w', encoding='utf-8') as fp:
1073 fp.write(val['raw'])
1074
1075 target_operation_map = {
1076 'add': 'src_add',
1077 'rm': 'src_rm',
1078 'add_target': 'target_add',
1079 'rm_target': 'target_rm',
1080 'add_extra_files': 'extra_files_add',
1081 'rm_extra_files': 'extra_files_rm',
1082 'info': 'info',
1083 }
1084
1085 def list_to_dict(in_list: T.List[str]) -> T.Dict[str, str]:
1086 result = {}
1087 it = iter(in_list)
1088 try:
1089 for i in it:
1090 # calling next(it) is not a mistake, we're taking the next element from
1091 # the iterator, avoiding the need to preprocess it into a sequence of
1092 # key value pairs.
1093 result[i] = next(it)
1094 except StopIteration:
1095 raise RewriterException('List of key/value pairs must have an even length.')
1096 return result
1097
1098 def list_to_dict_for_delete(args: T.List[str]) -> T.Dict[str, T.Optional[str]]:
1099 if len(args) % 2 == 0 and all(a == '' for a in args[1::2]):
1100 mlog.deprecation('Even-numbered arguments are all blank; '
1101 'ignoring these for compatibility with Meson < 1.10')
1102 args = args[::2]
1103 return {a: None for a in args}
1104
1105 def generate_target(options: argparse.Namespace) -> T.List[T.Dict[str, T.Any]]:
1106 return [{
1107 'type': 'target',
1108 'target': options.target,
1109 'operation': target_operation_map[options.operation],
1110 'sources': options.sources,
1111 'subdir': options.subdir,
1112 'target_type': options.tgt_type,
1113 }]
1114
1115 def generate_kwargs(options: argparse.Namespace) -> T.List[T.Dict[str, T.Any]]:
1116 if options.operation == 'delete':
1117 kwargs = list_to_dict_for_delete(options.kwargs)
1118 else:
1119 kwargs = list_to_dict(options.kwargs)
1120 return [{
1121 'type': 'kwargs',
1122 'function': options.function,
1123 'id': options.id,
1124 'operation': options.operation,
1125 'kwargs': kwargs,
1126 }]
1127
1128 def generate_def_opts(options: argparse.Namespace) -> T.List[T.Dict[str, T.Any]]:
1129 if options.operation == 'delete':
1130 kwargs = list_to_dict_for_delete(options.options)
1131 else:
1132 kwargs = list_to_dict(options.options)
1133 return [{
1134 'type': 'default_options',
1135 'operation': options.operation,
1136 'options': kwargs,
1137 }]
1138
1139 def generate_cmd(options: argparse.Namespace) -> T.List[T.Dict[str, T.Any]]:
1140 if os.path.exists(options.json):
1141 with open(options.json, encoding='utf-8') as fp:
1142 return T.cast(T.List[T.Dict[str, T.Any]], json.load(fp))
1143 else:
1144 return T.cast(T.List[T.Dict[str, T.Any]], json.loads(options.json))
1145
1146 # Map options.type to the actual type name
1147 cli_type_map = {
1148 'target': generate_target,
1149 'tgt': generate_target,
1150 'kwargs': generate_kwargs,
1151 'default-options': generate_def_opts,
1152 'def': generate_def_opts,
1153 'command': generate_cmd,
1154 'cmd': generate_cmd,
1155 }
1156
1157 def run(options: argparse.Namespace) -> int:
1158 mlog.redirect(True)
1159 if not options.verbose:
1160 mlog.set_quiet()
1161
1162 try:
1163 setup_vsenv()
1164 rewriter = Rewriter(options.sourcedir, skip_errors=options.skip)
1165 rewriter.analyze_meson()
1166
1167 if options.type is None:
1168 mlog.error('No command specified')
1169 return 1
1170
1171 commands = cli_type_map[options.type](options)
1172
1173 if not isinstance(commands, list):
1174 raise TypeError('Command is not a list')
1175
1176 for i, cmd in enumerate(commands):
1177 if not isinstance(cmd, object):
1178 raise TypeError('Command is not an object')
1179 rewriter.process(cmd)
1180 rewriter.apply_changes()
1181
1182 if i == len(commands) - 1: # Improves the performance, is not necessary for correctness.
1183 break
1184
1185 rewriter.modified_nodes = []
1186 rewriter.to_remove_nodes = []
1187 rewriter.to_add_nodes = []
1188 # The AST changed, so we need to update every information that was derived from the AST
1189 rewriter.interpreter = IntrospectionInterpreter(rewriter.sourcedir, '', rewriter.interpreter.backend, visitors = [AstIDGenerator(), AstIndentationGenerator(), AstConditionLevel()])
1190 rewriter.analyze_meson()
1191
1192 rewriter.print_info()
1193 return 0
1194 except Exception as e:
1195 raise e
1196 finally:
1197 mlog.set_verbose()