Debian Codegraph @

mesonbuild/modules/hotdoc.py

raw
1 # SPDX-License-Identifier: Apache-2.0
2 # Copyright 2018 The Meson development team
3
4 from __future__ import annotations
5
6 '''This module provides helper functions for generating documentation using hotdoc'''
7
8 import os, subprocess
9 import typing as T
10
11 from . import ExtensionModule, ModuleReturnValue, ModuleInfo
12 from .. import build, mesonlib, mlog
13 from ..build import CustomTarget, CustomTargetIndex
14 from ..dependencies import Dependency, InternalDependency
15 from ..interpreterbase import (
16 InvalidArguments, noPosargs, noKwargs, typed_kwargs, FeatureDeprecated,
17 ContainerTypeInfo, KwargInfo, typed_pos_args, InterpreterObject
18 )
19 from ..interpreter.interpreterobjects import _CustomTargetHolder
20 from ..interpreter.type_checking import NoneType
21 from ..mesonlib import File, MesonException
22 from ..programs import ExternalProgram
23 from ..options import OptionKey
24
25 if T.TYPE_CHECKING:
26 from typing_extensions import TypedDict
27
28 from . import ModuleState
29 from ..build import BuildProject
30 from ..environment import Environment
31 from ..interpreter import Interpreter
32 from ..interpreter.kwargs import TargetDepends
33 from ..interpreterbase import TYPE_kwargs, TYPE_var
34
35 _T = T.TypeVar('_T')
36
37 # there is currently no way to represent the arbitrary key/value paris that
38 # the hotdoc module allows.
39 #
40 # PEP-728, which is due in Python 3.15, will fix this, we can then add a new
41 # extra_items=str keyword argument.
42 class GenerateDocKwargs(TypedDict, total=False):
43 sitemap: T.Union[str, File, CustomTarget, CustomTargetIndex]
44 index: T.Union[str, File, CustomTarget, CustomTargetIndex]
45 project_version: str
46 html_extra_theme: T.Optional[str]
47 include_paths: T.List[str]
48 dependencies: T.List[T.Union[Dependency, build.StaticLibrary, build.SharedLibrary, CustomTarget, CustomTargetIndex]]
49 depends: T.List[T.Union[CustomTarget, CustomTargetIndex]]
50 gi_c_source_roots: T.List[str]
51 extra_assets: T.List[str]
52 extra_extension_paths: T.List[str]
53 subprojects: T.List['HotdocTarget']
54 install: bool
55 build_by_default: bool
56
57
58 def ensure_list(value: T.Union[_T, T.List[_T]]) -> T.List[_T]:
59 if not isinstance(value, list):
60 return [value]
61 return value
62
63
64 MIN_HOTDOC_VERSION = '0.8.100'
65
66 file_types = (str, File, CustomTarget, CustomTargetIndex)
67
68
69 class HotdocExternalProgram(ExternalProgram):
70 def run_hotdoc(self, cmd: T.List[str]) -> int:
71 return subprocess.run(self.get_command() + cmd, stdout=subprocess.DEVNULL).returncode
72
73
74 class HotdocTargetBuilder:
75
76 def __init__(self, name: str, state: ModuleState, hotdoc: HotdocExternalProgram, interpreter: Interpreter, kwargs: GenerateDocKwargs):
77 self.hotdoc = hotdoc
78 self.build_by_default = kwargs.pop('build_by_default', False)
79 self.kwargs = kwargs
80 self.name = name
81 self.state = state
82 self.interpreter = interpreter
83 self.include_paths: mesonlib.OrderedSet[str] = mesonlib.OrderedSet()
84
85 self.builddir = state.environment.get_build_dir()
86 self.sourcedir = state.environment.get_source_dir()
87 self.subdir = state.subdir
88 self.build_command = state.environment.get_build_command()
89
90 self.cmd: T.List[TYPE_var] = ['conf', '--project-name', name, "--disable-incremental-build",
91 '--output', os.path.join(self.builddir, self.subdir, self.name + '-doc')]
92
93 self._extra_extension_paths: set[str] = set()
94 self.extra_depends: list[build.BuildTargetTypes] = []
95 self._subprojects: list[HotdocTarget] = []
96
97 def process_known_arg(self, option: str, argname: T.Optional[str] = None, value_processor: T.Optional[T.Callable] = None) -> None:
98 if not argname:
99 argname = option.strip("-").replace("-", "_")
100
101 value = self.kwargs.pop(argname) # type: ignore[misc]
102 if value is not None and value_processor:
103 value = value_processor(value)
104
105 self.set_arg_value(option, value)
106
107 def set_arg_value(self, option: str, value: TYPE_var) -> None:
108 if value is None:
109 return
110
111 if isinstance(value, bool):
112 if value:
113 self.cmd.append(option)
114 elif isinstance(value, list):
115 # Do not do anything on empty lists
116 if value:
117 # https://bugs.python.org/issue9334 (from 2010 :( )
118 # The syntax with nargs=+ is inherently ambiguous
119 # A workaround for this case is to simply prefix with a space
120 # every value starting with a dash
121 escaped_value = []
122 for e in value:
123 if isinstance(e, str) and e.startswith('-'):
124 escaped_value += [' %s' % e]
125 else:
126 escaped_value += [e]
127 if option:
128 self.cmd.extend([option] + escaped_value)
129 else:
130 self.cmd.extend(escaped_value)
131 else:
132 # argparse gets confused if value(s) start with a dash.
133 # When an option expects a single value, the unambiguous way
134 # to specify it is with =
135 if isinstance(value, str):
136 self.cmd.extend([f'{option}={value}'])
137 else:
138 self.cmd.extend([option, value])
139
140 def check_extra_arg_type(self, arg: str, value: TYPE_var) -> None:
141 if isinstance(value, list):
142 for v in value:
143 self.check_extra_arg_type(arg, v)
144 return
145
146 valid_types = (str, bool, File, build.IncludeDirs, CustomTarget, CustomTargetIndex, build.BuildTarget)
147 if not isinstance(value, valid_types):
148 raise InvalidArguments('Argument "{}={}" should be of type: {}.'.format(
149 arg, value, [t.__name__ for t in valid_types]))
150
151 def process_extra_args(self) -> None:
152 for arg, value in self.kwargs.items():
153 option = "--" + arg.replace("_", "-")
154 self.check_extra_arg_type(arg, value) # type: ignore[arg-type]
155 self.set_arg_value(option, value) # type: ignore[arg-type]
156
157 def add_extension_paths(self, paths: T.Union[T.List[str], T.Set[str]]) -> None:
158 for path in paths:
159 if path in self._extra_extension_paths:
160 continue
161
162 self._extra_extension_paths.add(path)
163 self.cmd.extend(["--extra-extension-path", path])
164
165 def replace_dirs_in_string(self, string: str) -> str:
166 return string.replace("@SOURCE_ROOT@", self.sourcedir).replace("@BUILD_ROOT@", self.builddir)
167
168 def process_gi_c_source_roots(self) -> None:
169 if self.hotdoc.run_hotdoc(['--has-extension=gi-extension']) != 0:
170 return
171
172 value = self.kwargs.pop('gi_c_source_roots')
173 value.extend([
174 os.path.join(self.sourcedir, self.state.root_subdir),
175 os.path.join(self.builddir, self.state.root_subdir)
176 ])
177
178 self.cmd += ['--gi-c-source-roots'] + value
179
180 def process_dependencies(self, deps: T.Sequence[TargetDepends | Dependency | File | build.ExtractedObjects]) -> T.List[str]:
181 # build.ExtractedObjects shouldn't actually
182 # happen here, but we get them from Dependency.
183 cflags = set()
184 for dep in mesonlib.listify(ensure_list(deps)):
185 if isinstance(dep, InternalDependency):
186 inc_args = self.state.get_include_args(dep.include_directories)
187 cflags.update([self.replace_dirs_in_string(x)
188 for x in inc_args])
189 cflags.update(self.process_dependencies(dep.libraries))
190 cflags.update(self.process_dependencies(dep.sources))
191 cflags.update(self.process_dependencies(dep.ext_deps))
192 elif isinstance(dep, Dependency):
193 cflags.update(dep.get_compile_args())
194 elif isinstance(dep, (build.StaticLibrary, build.SharedLibrary)):
195 self.extra_depends.append(dep)
196 for incd in dep.get_include_dirs():
197 cflags.update(incd.incdirs)
198 elif isinstance(dep, HotdocTarget):
199 # Recurse in hotdoc target dependencies
200 self.process_dependencies(dep.get_target_dependencies())
201 self._subprojects.extend(dep.subprojects)
202 self.process_dependencies(dep.subprojects)
203 self.include_paths.add(os.path.join(self.builddir, dep.hotdoc_conf.subdir))
204 self.cmd += ['--extra-assets=' + p for p in dep.extra_assets]
205 self.add_extension_paths(dep.extra_extension_paths)
206 elif isinstance(dep, (CustomTarget, build.BuildTarget, CustomTargetIndex)):
207 self.extra_depends.append(dep.get_target())
208
209 return [f.strip('-I') for f in cflags]
210
211 def process_extra_assets(self) -> None:
212 self._extra_assets = self.kwargs.pop('extra_assets')
213
214 for assets_path in self._extra_assets:
215 self.cmd.extend(["--extra-assets", assets_path])
216
217 def process_subprojects(self) -> None:
218 value = self.kwargs.pop('subprojects')
219
220 self.process_dependencies(value)
221 self._subprojects.extend(value)
222
223 def flatten_config_command(self) -> T.List[str]:
224 cmd = []
225 for arg in mesonlib.listify(self.cmd, flatten=True):
226 if isinstance(arg, File):
227 arg = arg.absolute_path(self.state.environment.get_source_dir(),
228 self.state.environment.get_build_dir())
229 elif isinstance(arg, build.IncludeDirs):
230 cmd.extend(arg.abs_string_list(self.sourcedir, self.builddir))
231 continue
232 elif isinstance(arg, (build.BuildTarget, CustomTarget, CustomTargetIndex)):
233 self.extra_depends.append(arg.get_target())
234 arg = self.interpreter.backend.get_target_filename_abs(arg)
235
236 cmd.append(arg)
237
238 return cmd
239
240 def generate_hotdoc_config(self) -> None:
241 cwd = os.path.abspath(os.curdir)
242 ncwd = os.path.join(self.sourcedir, self.subdir)
243 mlog.log('Generating Hotdoc configuration for: ', mlog.bold(self.name))
244 os.chdir(ncwd)
245 if self.hotdoc.run_hotdoc(self.flatten_config_command()) != 0:
246 raise MesonException('hotdoc failed to configure')
247 os.chdir(cwd)
248
249 @T.overload
250 def ensure_file(self, value: list[str | File | CustomTarget | CustomTargetIndex]
251 ) -> list[File | CustomTarget | CustomTargetIndex]: ...
252
253 @T.overload
254 def ensure_file(self, value: str | File | CustomTarget | CustomTargetIndex
255 ) -> File | CustomTarget | CustomTargetIndex: ...
256
257 def ensure_file(self, value: str | File | CustomTarget | CustomTargetIndex | list[str | File | CustomTarget | CustomTargetIndex]
258 ) -> File | CustomTarget | CustomTargetIndex | list[File | CustomTarget | CustomTargetIndex]:
259 if isinstance(value, list):
260 res: list[File | CustomTarget | CustomTargetIndex] = []
261 for val in value:
262 res.append(self.ensure_file(val))
263 return res
264
265 if isinstance(value, str):
266 return File.from_source_file(self.sourcedir, self.subdir, value)
267
268 return value
269
270 def ensure_dir(self, value: str) -> str:
271 if os.path.isabs(value):
272 _dir = value
273 else:
274 _dir = os.path.join(self.sourcedir, self.subdir, value)
275
276 if not os.path.isdir(_dir):
277 raise InvalidArguments(f'"{_dir}" is not a directory.')
278
279 return os.path.relpath(_dir, os.path.join(self.builddir, self.subdir))
280
281 def check_forbidden_args(self) -> None:
282 for arg in ['conf_file']:
283 if arg in self.kwargs:
284 raise InvalidArguments(f'Argument "{arg}" is forbidden.')
285
286 def make_targets(self) -> T.Tuple[HotdocTarget, mesonlib.ExecutableSerialisation]:
287 self.check_forbidden_args()
288 self.process_known_arg("--index", value_processor=self.ensure_file)
289 self.process_known_arg("--project-version")
290 self.process_known_arg("--sitemap", value_processor=self.ensure_file)
291 self.process_known_arg("--html-extra-theme", value_processor=self.ensure_dir)
292 self.include_paths.update(self.ensure_dir(v) for v in self.kwargs.pop('include_paths'))
293 self.process_known_arg('--c-include-directories', argname="dependencies", value_processor=self.process_dependencies)
294 self.process_gi_c_source_roots()
295 self.process_extra_assets()
296 self.add_extension_paths(self.kwargs.pop('extra_extension_paths'))
297 self.process_subprojects()
298 self.extra_depends.extend(self.kwargs.pop('depends'))
299
300 install = self.kwargs.pop('install')
301 self.process_extra_args()
302
303 fullname = self.name + '-doc'
304 hotdoc_config_name = fullname + '.json'
305 hotdoc_config_path = os.path.join(
306 self.builddir, self.subdir, hotdoc_config_name)
307 with open(hotdoc_config_path, 'w', encoding='utf-8') as f:
308 f.write('{}')
309
310 self.cmd += ['--conf-file', hotdoc_config_path]
311 self.include_paths.add(os.path.join(self.builddir, self.subdir))
312 self.include_paths.add(os.path.join(self.sourcedir, self.subdir))
313
314 depfile = os.path.join(self.builddir, self.subdir, self.name + '.deps')
315 self.cmd += ['--deps-file-dest', depfile]
316
317 for path in self.include_paths:
318 self.cmd.extend(['--include-path', path])
319
320 if self.state.environment.coredata.optstore.get_value_for(OptionKey('werror', subproject=self.state.subproject)):
321 self.cmd.append('--fatal-warnings')
322 self.generate_hotdoc_config()
323
324 target_cmd = self.build_command + ["--internal", "hotdoc"] + \
325 self.hotdoc.get_command() + ['run', '--conf-file', hotdoc_config_name] + \
326 ['--builddir', os.path.join(self.builddir, self.subdir)]
327
328 target = HotdocTarget(fullname,
329 subdir=self.subdir,
330 environment=self.state.environment,
331 hotdoc_conf=File.from_built_file(
332 self.subdir, hotdoc_config_name),
333 extra_extension_paths=self._extra_extension_paths,
334 extra_assets=self._extra_assets,
335 subprojects=self._subprojects,
336 command=target_cmd,
337 extra_depends=self.extra_depends,
338 outputs=[fullname],
339 sources=[],
340 build_project=self.state.current_build_project,
341 depfile=os.path.basename(depfile),
342 build_by_default=self.build_by_default)
343
344 install_script = None
345 if install:
346 prefix = self.state.get_option('prefix')
347 assert isinstance(prefix, str), 'for mypy'
348 datadir = self.state.get_option('datadir')
349 assert isinstance(datadir, str), 'for mypy'
350 datadir = os.path.join(prefix, datadir)
351 devhelp = self.kwargs.get('devhelp_activate', False)
352 if not isinstance(devhelp, bool):
353 FeatureDeprecated.single_use('hotdoc.generate_doc() devhelp_activate must be boolean', '1.1.0', self.state.subproject)
354 devhelp = False
355 if devhelp:
356 install_from = os.path.join(fullname, 'devhelp')
357 install_to = os.path.join(datadir, 'devhelp')
358 else:
359 install_from = os.path.join(fullname, 'html')
360 install_to = os.path.join(datadir, 'doc', self.name, 'html')
361
362 install_script = self.state.backend.get_executable_serialisation(self.build_command + [
363 "--internal", "hotdoc",
364 "--install", install_from,
365 "--docdir", install_to,
366 '--name', self.name,
367 '--builddir', os.path.join(self.builddir, self.subdir)] +
368 self.hotdoc.get_command() +
369 ['run', '--conf-file', hotdoc_config_name])
370 install_script.tag = 'doc'
371
372 return (target, install_script)
373
374
375 class HotdocTargetHolder(_CustomTargetHolder['HotdocTarget']):
376 @noPosargs
377 @noKwargs
378 @InterpreterObject.method('config_path')
379 def config_path_method(self, *args: T.Any, **kwargs: T.Any) -> str:
380 conf = self.held_object.hotdoc_conf.absolute_path(self.interpreter.environment.source_dir,
381 self.interpreter.environment.build_dir)
382 return conf
383
384
385 class HotdocTarget(CustomTarget):
386 def __init__(self, name: str, subdir: str, hotdoc_conf: File,
387 extra_extension_paths: T.Set[str], extra_assets: T.List[str],
388 subprojects: T.List['HotdocTarget'], environment: Environment,
389 build_project: BuildProject, **kwargs: T.Any):
390 super().__init__(name, subdir, environment, **kwargs, build_project=build_project, absolute_paths=True)
391 self.hotdoc_conf = hotdoc_conf
392 self.extra_extension_paths = extra_extension_paths
393 self.extra_assets = extra_assets
394 self.subprojects = subprojects
395
396 def __getstate__(self) -> dict:
397 # Make sure we do not try to pickle subprojects
398 res = self.__dict__.copy()
399 res['subprojects'] = []
400
401 return res
402
403
404 class HotDocModule(ExtensionModule):
405
406 INFO = ModuleInfo('hotdoc', '0.48.0')
407
408 def __init__(self, interpreter: Interpreter):
409 super().__init__(interpreter)
410 self.hotdoc = HotdocExternalProgram('hotdoc')
411 if not self.hotdoc.found():
412 raise MesonException('hotdoc executable not found')
413 version = self.hotdoc.get_version(interpreter)
414 if not mesonlib.version_compare(version, f'>={MIN_HOTDOC_VERSION}'):
415 raise MesonException(f'hotdoc {MIN_HOTDOC_VERSION} required but not found.)')
416
417 self.methods.update({
418 'has_extensions': self.has_extensions,
419 'generate_doc': self.generate_doc,
420 })
421
422 @noKwargs
423 @typed_pos_args('hotdoc.has_extensions', varargs=str, min_varargs=1)
424 def has_extensions(self, state: ModuleState, args: T.Tuple[T.List[str]], kwargs: TYPE_kwargs) -> bool:
425 return self.hotdoc.run_hotdoc([f'--has-extension={extension}' for extension in args[0]]) == 0
426
427 @typed_pos_args('hotdoc.generate_doc', str)
428 @typed_kwargs(
429 'hotdoc.generate_doc',
430 KwargInfo('sitemap', file_types, required=True),
431 KwargInfo('index', file_types, required=True),
432 KwargInfo('project_version', str, required=True),
433 KwargInfo('html_extra_theme', (str, NoneType)),
434 KwargInfo('include_paths', ContainerTypeInfo(list, str), listify=True, default=[]),
435 # --c-include-directories
436 KwargInfo(
437 'dependencies',
438 ContainerTypeInfo(list, (Dependency, build.StaticLibrary, build.SharedLibrary,
439 CustomTarget, CustomTargetIndex)),
440 listify=True,
441 default=[],
442 ),
443 KwargInfo(
444 'depends',
445 ContainerTypeInfo(list, (CustomTarget, CustomTargetIndex)),
446 listify=True,
447 default=[],
448 since='0.64.1',
449 ),
450 KwargInfo('gi_c_source_roots', ContainerTypeInfo(list, str), listify=True, default=[]),
451 KwargInfo('extra_assets', ContainerTypeInfo(list, str), listify=True, default=[]),
452 KwargInfo('extra_extension_paths', ContainerTypeInfo(list, str), listify=True, default=[]),
453 KwargInfo('subprojects', ContainerTypeInfo(list, HotdocTarget), listify=True, default=[]),
454 KwargInfo('install', bool, default=False),
455 KwargInfo('build_by_default', bool, default=False),
456 allow_unknown=True
457 )
458 def generate_doc(self, state: ModuleState, args: T.Tuple[str], kwargs: GenerateDocKwargs) -> ModuleReturnValue:
459 project_name = args[0]
460 if any(isinstance(x, (CustomTarget, CustomTargetIndex)) for x in kwargs['dependencies']):
461 FeatureDeprecated.single_use('hotdoc.generate_doc dependencies argument with custom_target',
462 '0.64.1', state.subproject, 'use `depends`', state.current_node)
463 builder = HotdocTargetBuilder(project_name, state, self.hotdoc, self.interpreter, kwargs)
464 target, install_script = builder.make_targets()
465 targets: T.List[T.Union[HotdocTarget, mesonlib.ExecutableSerialisation]] = [target]
466 if install_script:
467 targets.append(install_script)
468
469 return ModuleReturnValue(target, targets)
470
471
472 def initialize(interpreter: Interpreter) -> HotDocModule:
473 mod = HotDocModule(interpreter)
474 mod.interpreter.append_holder_map(HotdocTarget, HotdocTargetHolder)
475 return mod