Debian Codegraph @

mesonbuild/scripts/rustdoc.py

raw
1 # SPDX-License-Identifier: Apache-2.0
2 # Copyright 2024 The Meson development team
3
4 from __future__ import annotations
5 from collections import defaultdict
6 import os
7 import tempfile
8 import typing as T
9
10 from .run_tool import run_tool_on_targets, run_with_buffered_output
11 from .. import build, mlog
12 from ..mesonlib import MachineChoice, PerMachine
13 from ..wrap import WrapMode, wrap
14
15 if T.TYPE_CHECKING:
16 from ..compilers.rust import RustCompiler
17
18 async def run_and_confirm_success(cmdlist: T.List[str], environ: T.Dict[str, str], crate: str) -> int:
19 returncode = await run_with_buffered_output(cmdlist, environ)
20 if returncode == 0:
21 print(mlog.green('Generated'), os.path.join('doc', crate))
22 return returncode
23
24 class Rustdoc:
25 def __init__(self, build: build.Build, tempdir: str, subprojects: T.Set[str]) -> None:
26 self.tools: PerMachine[T.List[str]] = PerMachine([], [])
27 self.warned: T.DefaultDict[str, bool] = defaultdict(lambda: False)
28 self.tempdir = tempdir
29 self.subprojects = subprojects
30 for machine in MachineChoice:
31 compilers = build.environment.coredata.compilers[machine]
32 if 'rust' in compilers:
33 compiler = T.cast('RustCompiler', compilers['rust'])
34 self.tools[machine] = compiler.get_rust_tool('rustdoc')
35
36 def warn_missing_rustdoc(self, machine: str) -> None:
37 if self.warned[machine]:
38 return
39 mlog.warning(f'rustdoc not found for {machine} machine')
40 self.warned[machine] = True
41
42 def __call__(self, target: T.Dict[str, T.Any]) -> T.Iterable[T.Coroutine[None, None, int]]:
43 if target['subproject'] is not None and target['subproject'] not in self.subprojects:
44 return
45
46 for src_block in target['target_sources']:
47 if 'compiler' in src_block and src_block['language'] == 'rust':
48 rustdoc = getattr(self.tools, src_block['machine'])
49 if not rustdoc:
50 self.warn_missing_rustdoc(src_block['machine'])
51 continue
52
53 cmdlist = list(rustdoc)
54 prev = None
55 crate_name = None
56 is_test = False
57 environ = dict(os.environ)
58 for arg in src_block['parameters']:
59 if prev:
60 if prev == '--crate-name':
61 cmdlist.extend((prev, arg))
62 crate_name = arg
63 elif prev == '--env-set':
64 try:
65 key, val = arg.split('=', maxsplit=1)
66 environ[key] = val
67 except ValueError:
68 pass
69 prev = None
70 continue
71
72 if arg == '--test':
73 is_test = True
74 break
75 elif arg in {'--crate-name', '--emit', '--out-dir', '-l', '--env-set'}:
76 prev = arg
77 elif arg != '-g' and not arg.startswith('-l'):
78 cmdlist.append(arg)
79
80 if is_test:
81 # --test has a completely different meaning for rustc and rustdoc;
82 # when using rust.test(), only the non-test target is documented
83 continue
84 if crate_name:
85 cmdlist.extend(src_block['sources'])
86 # Assume documentation is generated for the developer's use
87 cmdlist.append('--document-private-items')
88 cmdlist.append('-o')
89 cmdlist.append('doc')
90 yield run_and_confirm_success(cmdlist, environ, crate_name)
91 else:
92 print(mlog.yellow('Skipping'), target['name'], '(no crate name)')
93
94 def get_nonwrap_subprojects(build_data: build.Build) -> T.Set[str]:
95 wrap_resolver = wrap.Resolver(
96 build_data.environment.get_source_dir(),
97 build_data.subproject_dir,
98 wrap_mode=WrapMode.nodownload)
99 return set(sp
100 for sp in build_data.environment.coredata.initialized_subprojects
101 if sp and (sp not in wrap_resolver.wraps or wrap_resolver.wraps[sp].type is None))
102
103 def run(args: T.List[str]) -> int:
104 os.chdir(args[0])
105 build_data = build.load(os.getcwd())
106 subproject_list = get_nonwrap_subprojects(build_data)
107 with tempfile.TemporaryDirectory() as d:
108 return run_tool_on_targets(Rustdoc(build_data, d, subproject_list))