Debian Codegraph @

mesonbuild/mintro.py

raw
1 # SPDX-License-Identifier: Apache-2.0
2 # Copyright 2014-2016 The Meson development team
3
4 from __future__ import annotations
5
6 """This is a helper script for IDE developers. It allows you to
7 extract information such as list of targets, files, compiler flags,
8 tests and so on. All output is in JSON for simple parsing.
9
10 Currently only works for the Ninja backend. Others use generated
11 project files and don't need this info."""
12
13 from contextlib import redirect_stdout
14 import dataclasses
15 import itertools
16 import json
17 import os
18 from pathlib import Path, PurePath
19 import sys
20 import typing as T
21
22 from . import build, environment, mesonlib, options, coredata as cdata
23 from .ast import IntrospectionInterpreter, AstConditionLevel, AstIDGenerator, AstIndentationGenerator, AstJSONPrinter
24 from .backend import backends
25 from .interpreterbase import UnknownValue
26 from .options import OptionKey
27
28 if T.TYPE_CHECKING:
29 import argparse
30
31 from .dependencies import Dependency
32
33 class IntrospectionEncoder(json.JSONEncoder):
34 def default(self, obj: T.Any) -> T.Any:
35 if isinstance(obj, UnknownValue):
36 return 'unknown'
37 return json.JSONEncoder.default(self, obj)
38
39 def get_meson_info_file(info_dir: str) -> str:
40 return os.path.join(info_dir, 'meson-info.json')
41
42 def get_meson_introspection_version() -> str:
43 return '1.0.0'
44
45 def get_meson_introspection_required_version() -> T.List[str]:
46 return ['>=1.0', '<2.0']
47
48 def dump_ast(intr: IntrospectionInterpreter) -> T.Dict[str, T.Any]:
49 printer = AstJSONPrinter()
50 intr.ast.accept(printer)
51 return printer.result
52
53 def list_installed(coredata: cdata.CoreData, builddata: build.Build, backend: backends.Backend) -> T.Dict[str, str]:
54 res = {}
55 installdata = backend.create_install_data()
56 for t in installdata.targets:
57 res[os.path.join(installdata.build_dir, t.fname)] = \
58 os.path.join(installdata.prefix, t.outdir, os.path.basename(t.fname))
59 for i in installdata.data:
60 res[i.path] = os.path.join(installdata.prefix, i.install_path)
61 for i in installdata.headers:
62 res[i.path] = os.path.join(installdata.prefix, i.install_path, os.path.basename(i.path))
63 for i in installdata.man:
64 res[i.path] = os.path.join(installdata.prefix, i.install_path)
65 for i in installdata.install_subdirs:
66 res[i.path] = os.path.join(installdata.prefix, i.install_path)
67 for s in installdata.symlinks:
68 basename = os.path.basename(s.name)
69 res[basename] = os.path.join(installdata.prefix, s.install_path, basename)
70 return res
71
72 def list_install_plan(coredata: cdata.CoreData, builddata: build.Build, backend: backends.Backend) -> T.Dict[str, T.Dict[str, T.Dict[str, T.Union[str, T.List[str], None]]]]:
73 installdata = backend.create_install_data()
74 plan: T.Dict[str, T.Dict[str, T.Dict[str, T.Union[str, T.List[str], None]]]] = {
75 'targets': {
76 os.path.join(installdata.build_dir, target.fname): {
77 'destination': target.out_name,
78 'tag': target.tag or None,
79 'subproject': target.subproject or None,
80 'install_rpath': target.install_rpath or None,
81 'build_rpaths': sorted(x.decode('utf8') for x in target.rpath_dirs_to_remove),
82 }
83 for target in installdata.targets
84 },
85 }
86 for key, data_list in {
87 'data': installdata.data,
88 'man': installdata.man,
89 'headers': installdata.headers,
90 'install_subdirs': installdata.install_subdirs
91 }.items():
92 # Mypy doesn't recognize SubdirInstallData as a subclass of InstallDataBase
93 for data in data_list: # type: ignore[attr-defined]
94 data_type = data.data_type or key
95 install_path_name = data.install_path_name
96 if key == 'headers': # in the headers, install_path_name is the directory
97 install_path_name = os.path.join(install_path_name, os.path.basename(data.path))
98
99 entry = {
100 'destination': install_path_name,
101 'tag': data.tag or None,
102 'subproject': data.subproject or None,
103 }
104
105 if key == 'install_subdirs':
106 exclude_files, exclude_dirs = data.exclude or ([], [])
107 entry['exclude_dirs'] = list(exclude_dirs)
108 entry['exclude_files'] = list(exclude_files)
109
110 plan[data_type] = plan.get(data_type, {})
111 plan[data_type][data.path] = entry
112
113 return plan
114
115 def get_target_dir(coredata: cdata.CoreData, subdir: str) -> str:
116 if coredata.optstore.get_value_for(OptionKey('layout')) == 'flat':
117 return 'meson-out'
118 else:
119 return subdir
120
121 def list_targets_from_source(intr: IntrospectionInterpreter) -> T.List[T.Dict[str, object]]:
122 tlist: T.List[T.Dict[str, object]] = []
123 root_dir = Path(intr.source_root).resolve()
124
125 for i in intr.targets:
126 sources = intr.nodes_to_pretty_filelist(root_dir, i.subdir, i.source_nodes)
127 extra_files = intr.nodes_to_pretty_filelist(root_dir, i.subdir, [i.extra_files] if i.extra_files else [])
128
129 outdir = get_target_dir(intr.coredata, i.subdir)
130
131 tlist += [{
132 'name': i.name,
133 'id': i.id,
134 'type': i.typename,
135 'defined_in': i.defined_in,
136 'filename': [os.path.join(outdir, x) for x in i.outputs],
137 'build_by_default': i.build_by_default,
138 'target_sources': [{
139 'language': 'unknown',
140 'machine': i.machine,
141 'compiler': [],
142 'parameters': [],
143 'sources': sources,
144 'generated_sources': []
145 }],
146 'depends': [],
147 'extra_files': extra_files,
148 'subproject': None, # Subprojects are not supported
149 'installed': i.installed
150 }]
151
152 return tlist
153
154 def list_targets(coredata: cdata.CoreData, builddata: build.Build, backend: backends.Backend) -> T.List[T.Any]:
155 tlist: T.List[T.Any] = []
156 build_dir = builddata.environment.get_build_dir()
157 src_dir = builddata.environment.get_source_dir()
158
159 # Fast lookup table for installation files
160 install_lookuptable = {}
161 installdata = backend.create_install_data()
162 for i in installdata.targets:
163 basename = os.path.basename(i.fname)
164 install_lookuptable[basename] = [str(PurePath(installdata.prefix, i.outdir, basename))]
165 for s in installdata.symlinks:
166 # Symlink's target must already be in the table. They share the same list
167 # to support symlinks to symlinks recursively, such as .so -> .so.0 -> .so.1.2.3
168 basename = os.path.basename(s.name)
169 try:
170 install_lookuptable[basename] = install_lookuptable[os.path.basename(s.target)]
171 install_lookuptable[basename].append(str(PurePath(installdata.prefix, s.install_path, basename)))
172 except KeyError:
173 pass
174
175 for (idname, target) in builddata.get_targets().items():
176 if not isinstance(target, build.Target):
177 raise RuntimeError('The target object in `builddata.get_targets()` is not of type `build.Target`. Please file a bug with this error message.')
178
179 outdir = get_target_dir(builddata.environment.coredata, target.get_builddir())
180 t = {
181 'name': target.get_basename(),
182 'id': idname,
183 'type': target.get_typename(),
184 'defined_in': os.path.normpath(os.path.join(src_dir, target.get_subdir(), environment.build_filename)),
185 'filename': [os.path.join(build_dir, outdir, x) for x in target.get_outputs()],
186 'build_by_default': target.build_by_default,
187 'target_sources': backend.get_introspection_data(idname, target),
188 'extra_files': [os.path.normpath(os.path.join(src_dir, x.subdir, x.fname)) for x in target.extra_files],
189 'subproject': target.subproject or None,
190 'dependencies': [d.name for d in getattr(target, 'external_deps', [])],
191 'depends': [lib.get_id() for lib in getattr(target, 'dependencies', [])]
192 }
193
194 vs_module_defs = getattr(target, 'vs_module_defs', None)
195 if vs_module_defs is not None:
196 t['vs_module_defs'] = vs_module_defs.relative_name()
197 win_subsystem = getattr(target, 'win_subsystem', None)
198 if win_subsystem is not None:
199 t['win_subsystem'] = win_subsystem
200
201 if target.should_install():
202 t['installed'] = True
203 ifn = [install_lookuptable.get(x, [None]) for x in target.get_outputs()]
204 t['install_filename'] = [x for sublist in ifn for x in sublist] # flatten the list
205 else:
206 t['installed'] = False
207 tlist.append(t)
208 return tlist
209
210 def list_buildoptions(coredata: cdata.CoreData, builddata: build.Build, backend: backends.Backend) -> T.List[T.Dict[str, T.Union[str, bool, int, T.List[str]]]]:
211 return _list_buildoptions(coredata)
212
213 def list_buildoptions_from_source(intr: IntrospectionInterpreter) -> T.List[T.Dict[str, T.Union[str, bool, int, T.List[str]]]]:
214 subprojects = [i['name'] for i in intr.project_data['subprojects']]
215 return _list_buildoptions(intr.coredata, subprojects)
216
217 def _list_buildoptions(coredata: cdata.CoreData, subprojects: T.Optional[T.List[str]] = None) -> T.List[T.Dict[str, T.Union[str, bool, int, T.List[str]]]]:
218 optlist: T.List[T.Dict[str, T.Union[str, bool, int, T.List[str]]]] = []
219 subprojects = subprojects or []
220
221 dir_option_names = set(options.BUILTIN_DIR_OPTIONS)
222 test_option_names = {OptionKey('errorlogs'),
223 OptionKey('stdsplit')}
224
225 dir_options: options.MutableKeyedOptionDictType = {}
226 test_options: options.MutableKeyedOptionDictType = {}
227 core_options: options.MutableKeyedOptionDictType = {}
228 for k, v in coredata.optstore.items():
229 if k in dir_option_names:
230 dir_options[k] = v
231 elif k in test_option_names:
232 test_options[k] = v
233 elif coredata.optstore.is_builtin_option(k):
234 core_options[k] = v
235 if not v.yielding:
236 for s in subprojects:
237 core_options[k.evolve(subproject=s)] = v
238
239 def add_keys(opts: T.Union[options.MutableKeyedOptionDictType, options.OptionStore], section: str) -> None:
240 for key, opt in sorted(opts.items()):
241 optdict = {'name': str(key), 'value': opt.value, 'section': section,
242 'machine': key.machine.get_lower_case_name() if coredata.optstore.is_per_machine_option(key) else 'any'}
243 if isinstance(opt, options.UserStringOption):
244 typestr = 'string'
245 elif isinstance(opt, options.UserBooleanOption):
246 typestr = 'boolean'
247 elif isinstance(opt, options.UserComboOption):
248 optdict['choices'] = opt.printable_choices()
249 typestr = 'combo'
250 elif isinstance(opt, options.UserUmaskOption):
251 # do not print 0o22
252 if isinstance(optdict['value'], int):
253 typestr = 'integer'
254 optdict['value'] = int(optdict['value'])
255 else:
256 typestr = 'string'
257 elif isinstance(opt, options.UserIntegerOption):
258 typestr = 'integer'
259 elif isinstance(opt, options.UserStringArrayOption):
260 typestr = 'array'
261 c = opt.printable_choices()
262 if c:
263 optdict['choices'] = c
264 else:
265 raise RuntimeError('Unknown option type: ', repr(type(opt)))
266 optdict['type'] = typestr
267 optdict['description'] = opt.description
268 optlist.append(optdict)
269
270 add_keys(core_options, 'core')
271 add_keys({k: v for k, v in coredata.optstore.items() if coredata.optstore.is_backend_option(k)}, 'backend')
272 add_keys({k: v for k, v in coredata.optstore.items() if coredata.optstore.is_base_option(k)}, 'base')
273 add_keys(
274 {k: v for k, v in sorted(coredata.optstore.items(), key=lambda i: i[0].machine) if coredata.optstore.is_compiler_option(k)},
275 'compiler',
276 )
277 add_keys(dir_options, 'directory')
278
279 def project_option_key_to_introname(key: OptionKey) -> OptionKey:
280 assert key.subproject is not None
281 if key.subproject == '':
282 return key.evolve(subproject=None)
283 return key
284
285 add_keys({project_option_key_to_introname(k): v
286 for k, v in coredata.optstore.items() if coredata.optstore.is_project_option(k)}, 'user')
287 add_keys(test_options, 'test')
288 return optlist
289
290 def find_buildsystem_files_list(src_dir: str) -> T.List[str]:
291 build_files = frozenset({'meson.build', 'meson.options', 'meson_options.txt'})
292 # I feel dirty about this. But only slightly.
293 filelist: T.List[str] = []
294 for root, _, files in os.walk(src_dir):
295 filelist.extend(os.path.relpath(os.path.join(root, f), src_dir)
296 for f in build_files.intersection(files))
297 return filelist
298
299 def list_buildsystem_files(coredata: cdata.CoreData, builddata: build.Build, backend: backends.Backend) -> T.List[str]:
300 src_dir = builddata.environment.get_source_dir()
301 filelist = [PurePath(src_dir, x).as_posix() for x in builddata.def_files]
302 return filelist
303
304 def list_compilers(coredata: cdata.CoreData, builddata: build.Build, backend: backends.Backend) -> T.Dict[str, T.Dict[str, T.Dict[str, str]]]:
305 compilers: T.Dict[str, T.Dict[str, T.Dict[str, str]]] = {}
306 for machine in ('host', 'build'):
307 compilers[machine] = {}
308 for language, compiler in getattr(coredata.compilers, machine).items():
309 compilers[machine][language] = {
310 'id': compiler.get_id(),
311 'exelist': compiler.get_exelist(),
312 'linker_exelist': compiler.get_linker_exelist(),
313 'file_suffixes': compiler.file_suffixes,
314 'default_suffix': compiler.get_default_suffix(),
315 'version': compiler.version,
316 'full_version': compiler.full_version,
317 'linker_id': compiler.get_linker_id(),
318 }
319 return compilers
320
321 def list_deps_from_source(intr: IntrospectionInterpreter) -> T.List[T.Dict[str, T.Union[str, bool, T.List[str], UnknownValue]]]:
322 result: T.List[T.Dict[str, T.Union[str, bool, T.List[str], UnknownValue]]] = []
323 for i in intr.dependencies:
324 result += [{
325 'name': i.name,
326 'required': i.required,
327 'version': i.version,
328 'has_fallback': i.has_fallback,
329 'conditional': i.conditional,
330 }]
331 return result
332
333 def list_deps(coredata: cdata.CoreData, builddata: build.Build, backend: backends.Backend) -> T.List[T.Dict[str, T.Union[str, T.List[str]]]]:
334 result: T.Dict[str, T.Dict[str, T.Union[str, T.List[str]]]] = {}
335
336 def _src_to_str(src_file: T.Union[str, build.TargetSources, build.StructuredSources]) -> T.List[str]:
337 if isinstance(src_file, str):
338 return [src_file]
339 if isinstance(src_file, mesonlib.File):
340 return [src_file.absolute_path(backend.source_dir, backend.build_dir)]
341 if isinstance(src_file, (build.CustomTarget, build.CustomTargetIndex, build.GeneratedList)):
342 return src_file.get_outputs()
343 if isinstance(src_file, build.StructuredSources):
344 return [f for s in src_file.as_list() for f in _src_to_str(s)]
345 raise mesonlib.MesonBugException(f'Invalid file type {type(src_file)}.')
346
347 def _create_result(d: Dependency) -> T.Dict[str, T.Any]:
348 return {
349 'name': d.name,
350 'type': d.type_name,
351 'version': d.get_version(),
352 'compile_args': d.get_compile_args(),
353 'link_args': d.get_link_args(),
354 'include_directories': [i for idirs in d.get_include_dirs() for i in idirs.abs_string_list(backend.source_dir, backend.build_dir)],
355 'sources': [f for s in d.get_sources() for f in _src_to_str(s)],
356 'extra_files': [f for s in d.get_extra_files() for f in _src_to_str(s)],
357 'dependencies': [e.name for e in d.ext_deps],
358 'depends': [lib.get_id() for lib in getattr(d, 'libraries', [])],
359 'meson_variables': d.meson_variables,
360 }
361
362 for d in coredata.deps.host.values():
363 if d.found():
364 result[d.name] = _create_result(d)
365
366 return list(result.values())
367
368 def get_test_list(testdata: T.List[backends.TestSerialisation]) -> T.List[T.Dict[str, T.Union[str, int, T.List[str], T.Dict[str, str]]]]:
369 result: T.List[T.Dict[str, T.Union[str, int, T.List[str], T.Dict[str, str]]]] = []
370 for t in testdata:
371 to: T.Dict[str, T.Union[str, int, T.List[str], T.Dict[str, str]]] = {}
372 if isinstance(t.fname, str):
373 fname = [t.fname]
374 else:
375 fname = t.fname
376 to['cmd'] = fname + t.cmd_args
377 if isinstance(t.env, mesonlib.EnvironmentVariables):
378 to['env'] = t.env.get_env({})
379 else:
380 to['env'] = t.env
381 to['name'] = t.name
382 to['workdir'] = t.workdir
383 to['timeout'] = t.timeout
384 to['suite'] = t.suite
385 to['is_parallel'] = t.is_parallel
386 to['priority'] = t.priority
387 to['protocol'] = str(t.protocol)
388 to['depends'] = t.depends
389 to['extra_paths'] = t.extra_paths
390 result.append(to)
391 return result
392
393 def list_tests(coredata: cdata.CoreData, builddata: build.Build, backend: backends.Backend) -> T.List[T.Dict[str, T.Union[str, int, T.List[str], T.Dict[str, str]]]]:
394 testdata = backend.create_test_serialisation(builddata.get_tests())
395 return get_test_list(testdata)
396
397 def list_benchmarks(coredata: cdata.CoreData, builddata: build.Build, backend: backends.Backend) -> T.List[T.Dict[str, T.Union[str, int, T.List[str], T.Dict[str, str]]]]:
398 benchdata = backend.create_test_serialisation(builddata.get_benchmarks())
399 return get_test_list(benchdata)
400
401 def list_machines(coredata: cdata.CoreData, builddata: build.Build, backend: backends.Backend) -> T.Dict[str, T.Dict[str, T.Union[str, bool]]]:
402 machines: T.Dict[str, T.Dict[str, T.Union[str, bool]]] = {}
403 for m in ('host', 'build', 'target'):
404 machine = getattr(builddata.environment.machines, m)
405 machines[m] = dataclasses.asdict(machine)
406 machines[m]['is_64_bit'] = machine.is_64_bit
407 machines[m]['exe_suffix'] = machine.get_exe_suffix()
408 machines[m]['object_suffix'] = machine.get_object_suffix()
409 return machines
410
411 def list_projinfo(coredata: cdata.CoreData, builddata: build.Build, backend: backends.Backend) -> T.Dict[str, T.Union[str, T.List[str], T.List[T.Dict[str, str]]]]:
412 result: T.Dict[str, T.Union[str, T.List[str], T.List[T.Dict[str, str]]]] = {
413 'version': builddata.project_version,
414 'descriptive_name': builddata.project_name,
415 'license': builddata.dep_manifest[builddata.project_name].license,
416 'license_files': [f[1].fname for f in builddata.dep_manifest[builddata.project_name].license_files],
417 'subproject_dir': builddata.subproject_dir,
418 }
419 subprojects = []
420 seen = set([''])
421 for k, build_proj in itertools.chain(builddata.projects.host.items(),
422 builddata.projects.build.items()):
423 if k in seen:
424 continue
425 seen.add(k)
426 c: T.Dict[str, str] = {
427 'name': k,
428 'version': build_proj.version,
429 'descriptive_name': build_proj.name,
430 }
431 subprojects.append(c)
432 result['subprojects'] = subprojects
433 return result
434
435 def list_projinfo_from_source(intr: IntrospectionInterpreter) -> T.Dict[str, T.Union[str, T.List[T.Dict[str, str]]]]:
436 sourcedir = intr.source_root
437 files = find_buildsystem_files_list(sourcedir)
438 files = [os.path.normpath(x) for x in files]
439
440 for i in intr.project_data['subprojects']:
441 basedir = os.path.join(intr.subproject_dir, i['name'])
442 i['buildsystem_files'] = [x for x in files if x.startswith(basedir)]
443 files = [x for x in files if not x.startswith(basedir)]
444
445 intr.project_data['buildsystem_files'] = files
446 intr.project_data['subproject_dir'] = intr.subproject_dir
447 return intr.project_data
448
449 def print_results(options: argparse.Namespace, results: T.Sequence[T.Tuple[str, T.Union[dict, T.List[T.Any]]]], indent: T.Optional[int]) -> int:
450 if not results and not options.force_dict:
451 print('No command specified')
452 return 1
453 elif len(results) == 1 and not options.force_dict:
454 # Make to keep the existing output format for a single option
455 print(json.dumps(results[0][1], indent=indent, cls=IntrospectionEncoder))
456 else:
457 out = {}
458 for i in results:
459 out[i[0]] = i[1]
460 print(json.dumps(out, indent=indent, cls=IntrospectionEncoder))
461 return 0
462
463 def get_infodir(builddir: T.Optional[str] = None) -> str:
464 infodir = 'meson-info'
465 if builddir is not None:
466 infodir = os.path.join(builddir, infodir)
467 return infodir
468
469 def get_info_file(infodir: str, kind: T.Optional[str] = None) -> str:
470 return os.path.join(infodir,
471 'meson-info.json' if not kind else f'intro-{kind}.json')
472
473 def load_info_file(infodir: str, kind: T.Optional[str] = None) -> T.Any:
474 with open(get_info_file(infodir, kind), encoding='utf-8') as fp:
475 return json.load(fp)
476
477 @dataclasses.dataclass
478 class IntroCommand:
479 desc: str
480 func: T.Optional[T.Callable[[cdata.CoreData, build.Build, backends.Backend], T.Union[dict, list]]] = None
481 no_bd: T.Optional[T.Callable[[IntrospectionInterpreter], T.Union[dict, list]]] = None
482
483 def __post_init__(self) -> None:
484 self.desc += '.'
485
486 INTRO_TYPES: T.Mapping[str, IntroCommand] = {
487 'ast': IntroCommand('Dump the AST of the meson file', no_bd=dump_ast),
488 'benchmarks': IntroCommand('List all benchmarks', func=list_benchmarks),
489 'buildoptions': IntroCommand('List all build options', func=list_buildoptions, no_bd=list_buildoptions_from_source),
490 'buildsystem_files': IntroCommand('List files that make up the build system', func=list_buildsystem_files),
491 'compilers': IntroCommand('List used compilers', func=list_compilers),
492 'dependencies': IntroCommand('List external dependencies', func=list_deps, no_bd=list_deps_from_source),
493 'scan_dependencies': IntroCommand('Scan for dependencies used in the meson.build file', no_bd=list_deps_from_source),
494 'installed': IntroCommand('List all installed files and directories', func=list_installed),
495 'install_plan': IntroCommand('List all installed files and directories with their details', func=list_install_plan),
496 'machines': IntroCommand('Information about host, build, and target machines', func=list_machines),
497 'projectinfo': IntroCommand('Information about projects', func=list_projinfo, no_bd=list_projinfo_from_source),
498 'targets': IntroCommand('List top level targets', func=list_targets, no_bd=list_targets_from_source),
499 'tests': IntroCommand('List all unit tests', func=list_tests),
500 }
501
502 # Note: when adding arguments, please also add them to the completion
503 # scripts in $MESONSRC/data/shell-completions/
504 def add_arguments(parser: argparse.ArgumentParser) -> None:
505 for key, val in INTRO_TYPES.items():
506 flag = '--' + key.replace('_', '-')
507 parser.add_argument(flag, action='store_true', dest=key, default=False, help=val.desc)
508
509 parser.add_argument('--backend', choices=sorted(options.backendlist), dest='backend', default='ninja',
510 help='The backend to use for the --buildoptions introspection.')
511 parser.add_argument('-a', '--all', action='store_true', dest='all', default=False,
512 help='Print all available information.')
513 parser.add_argument('-i', '--indent', action='store_true', dest='indent', default=False,
514 help='Enable pretty printed JSON.')
515 parser.add_argument('-f', '--force-object-output', action='store_true', dest='force_dict', default=False,
516 help='Always use the new JSON format for multiple entries (even for 0 and 1 introspection commands)')
517 parser.add_argument('builddir', nargs='?', default='.', help='The build directory')
518
519 def run(options: argparse.Namespace) -> int:
520 datadir = 'meson-private'
521 infodir = get_infodir(options.builddir)
522 if options.builddir is not None:
523 datadir = os.path.join(options.builddir, datadir)
524 indent = 4 if options.indent else None
525 results: T.List[T.Tuple[str, T.Union[dict, T.List[T.Any]]]] = []
526
527 # TODO: This if clause is undocumented.
528 if os.path.basename(options.builddir) == environment.build_filename:
529 sourcedir = '.' if options.builddir == environment.build_filename else options.builddir[:-len(environment.build_filename)]
530 # Make sure that log entries in other parts of meson don't interfere with the JSON output
531 with redirect_stdout(sys.stderr):
532 backend = backends.get_backend_from_name(options.backend)
533 intr = IntrospectionInterpreter(sourcedir, '', backend.name, visitors = [AstIDGenerator(), AstIndentationGenerator(), AstConditionLevel()])
534 intr.analyze()
535
536 for key, val in INTRO_TYPES.items():
537 if (not options.all and not getattr(options, key, False)) or not val.no_bd:
538 continue
539 results += [(key, val.no_bd(intr))]
540 return print_results(options, results, indent)
541
542 try:
543 raw = load_info_file(infodir)
544 intro_vers = raw.get('introspection', {}).get('version', {}).get('full', '0.0.0')
545 except FileNotFoundError:
546 if not os.path.isdir(datadir) or not os.path.isdir(infodir):
547 print('Current directory is not a meson build directory.\n'
548 'Please specify a valid build dir or change the working directory to it.')
549 else:
550 print('Introspection file {} does not exist.\n'
551 'It is also possible that the build directory was generated with an old\n'
552 'meson version. Please regenerate it in this case.'.format(get_info_file(infodir)))
553 return 1
554
555 vers_to_check = get_meson_introspection_required_version()
556 for i in vers_to_check:
557 if not mesonlib.version_compare(intro_vers, i):
558 print('Introspection version {} is not supported. '
559 'The required version is: {}'
560 .format(intro_vers, ' and '.join(vers_to_check)))
561 return 1
562
563 # Extract introspection information from JSON
564 for i, v in INTRO_TYPES.items():
565 if not v.func:
566 continue
567 if not options.all and not getattr(options, i, False):
568 continue
569 try:
570 results += [(i, load_info_file(infodir, i))]
571 except FileNotFoundError:
572 print('Introspection file {} does not exist.'.format(get_info_file(infodir, i)))
573 return 1
574
575 return print_results(options, results, indent)
576
577 updated_introspection_files: T.List[str] = []
578
579 def write_intro_info(intro_info: T.Sequence[T.Tuple[str, T.Union[dict, T.List[T.Any]]]], info_dir: str) -> None:
580 for kind, data in intro_info:
581 out_file = os.path.join(info_dir, f'intro-{kind}.json')
582 tmp_file = os.path.join(info_dir, 'tmp_dump.json')
583 with open(tmp_file, 'w', encoding='utf-8') as fp:
584 json.dump(data, fp, indent=2)
585 fp.flush() # Not sure if this is needed
586 os.replace(tmp_file, out_file)
587 updated_introspection_files.append(kind)
588
589 def generate_introspection_file(builddata: build.Build, backend: backends.Backend) -> None:
590 coredata = builddata.environment.get_coredata()
591 intro_info: T.List[T.Tuple[str, T.Union[dict, T.List[T.Any]]]] = []
592
593 for key, val in INTRO_TYPES.items():
594 if not val.func:
595 continue
596 intro_info += [(key, val.func(coredata, builddata, backend))]
597
598 write_intro_info(intro_info, builddata.environment.info_dir)
599
600 def update_build_options(coredata: cdata.CoreData, info_dir: str) -> None:
601 intro_info = [
602 ('buildoptions', _list_buildoptions(coredata))
603 ]
604
605 write_intro_info(intro_info, info_dir)
606
607 def split_version_string(version: str) -> T.Dict[str, T.Union[str, int]]:
608 vers_list = version.split('.')
609 return {
610 'full': version,
611 'major': int(vers_list[0] if len(vers_list) > 0 else 0),
612 'minor': int(vers_list[1] if len(vers_list) > 1 else 0),
613 'patch': int(vers_list[2] if len(vers_list) > 2 else 0)
614 }
615
616 def write_meson_info_file(builddata: build.Build, errors: list, build_files_updated: bool = False) -> None:
617 info_dir = builddata.environment.info_dir
618 info_file = get_meson_info_file(info_dir)
619 intro_info = {}
620
621 for i, v in INTRO_TYPES.items():
622 if not v.func:
623 continue
624 intro_info[i] = {
625 'file': f'intro-{i}.json',
626 'updated': i in updated_introspection_files
627 }
628
629 info_data = {
630 'meson_version': split_version_string(cdata.version),
631 'directories': {
632 'source': builddata.environment.get_source_dir(),
633 'build': builddata.environment.get_build_dir(),
634 'info': info_dir,
635 },
636 'introspection': {
637 'version': split_version_string(get_meson_introspection_version()),
638 'information': intro_info,
639 },
640 'build_files_updated': build_files_updated,
641 }
642
643 if errors:
644 info_data['error'] = True
645 info_data['error_list'] = [x if isinstance(x, str) else str(x) for x in errors]
646 else:
647 info_data['error'] = False
648
649 # Write the data to disc
650 tmp_file = os.path.join(info_dir, 'tmp_dump.json')
651 with open(tmp_file, 'w', encoding='utf-8') as fp:
652 json.dump(info_data, fp)
653 fp.flush()
654 os.replace(tmp_file, info_file)