Coverage for pyTooling/GitLab/Sphinx/Reference.py: 95%

367 statements  

« prev     ^ index     » next       coverage.py v7.17.4, created at 2026-11-21 03:23 +0000

1# ==================================================================================================================== # 

2# _____ _ _ ____ _ _ _ _ # 

3# _ __ _ |_ _|__ ___ | (_)_ __ __ _ / ___(_) |_| | __ _| |__ # 

4# | '_ \| | | || |/ _ \ / _ \| | | '_ \ / _` || | _| | __| | / _` | '_ \ # 

5# | |_) | |_| || | (_) | (_) | | | | | | (_| || |_| | | |_| |__| (_| | |_) | # 

6# | .__/ \__, ||_|\___/ \___/|_|_|_| |_|\__, (_)____|_|\__|_____\__,_|_.__/ # 

7# |_| |___/ |___/ # 

8# ==================================================================================================================== # 

9# Authors: # 

10# Patrick Lehmann # 

11# # 

12# License: # 

13# ==================================================================================================================== # 

14# Copyright 2026-2026 Patrick Lehmann - Bötzingen, Germany # 

15# # 

16# Licensed under the Apache License, Version 2.0 (the "License"); # 

17# you may not use this file except in compliance with the License. # 

18# You may obtain a copy of the License at # 

19# # 

20# http://www.apache.org/licenses/LICENSE-2.0 # 

21# # 

22# Unless required by applicable law or agreed to in writing, software # 

23# distributed under the License is distributed on an "AS IS" BASIS, # 

24# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # 

25# See the License for the specific language governing permissions and # 

26# limitations under the License. # 

27# # 

28# SPDX-License-Identifier: Apache-2.0 # 

29# ==================================================================================================================== # 

30# 

31""" 

32Directives of the ``glci`` domain summarizing the current pipeline file: its parameters, interface, dependencies and 

33YAML. 

34 

35Each of them reads the pipeline file of the preceding ``glci:pipeline``: 

36 

37.. code-block:: ReST 

38 

39 .. glci:pipeline:: Package 

40 

41 .. glci:parameter-table:: 

42 :kinds: inputs 

43 

44 .. glci:interface:: 

45 

46 .. glci:dependencies:: 

47 

48 * pip 

49 

50 .. glci:yaml:: 

51 :job: Package 

52 

53 .. glci:autoinputs:: 

54 

55* ``glci:parameter-table`` - the summary tables of the inputs and variables; 

56* ``glci:interface`` - the contract with a pipeline including the file: the required inputs, the variables of the run 

57 form, the stages to declare, the jobs and hidden jobs it adds; 

58* ``glci:dependencies`` - the files included, the child and downstream pipelines triggered, the container images used, 

59 merged with hand-written ones; 

60* ``glci:yaml`` - the pipeline file or a part of it, as a code block linked to the file on GitLab; 

61* ``glci:autoinputs`` - an entry for every input the document has no ``glci:input`` for. 

62 

63When a document was read, an input of its pipeline file without an entry is a ``glci.drift`` warning 

64(:func:`checkUndocumentedInputs`). 

65 

66.. seealso:: 

67 

68 :mod:`pyTooling.GitLab.Sphinx` 

69 |rarr| The domain ``glci``, its pipelines and parameter entries. 

70""" 

71from __future__ import annotations 

72 

73from pathlib import Path 

74from typing import TYPE_CHECKING, Any, Callable, Optional as Nullable, TypeVar 

75 

76from docutils import nodes 

77from docutils.parsers.rst import directives 

78from sphinx import addnodes 

79from sphinx.application import Sphinx 

80from sphinx.directives.code import container_wrapper 

81from sphinx.transforms import SphinxTransform 

82from sphinx.util.logging import getLogger 

83 

84from pyTooling.Decorators import export 

85from pyTooling.Sphinx import BaseDirective, SphinxExtensionError, strip 

86from pyTooling.GitLab.Sphinx import NO_DEFAULT, WARNING_TYPE, InputDirective, formatValue 

87 

88if TYPE_CHECKING: # pragma: no cover 

89 from pyTooling.GitLab.PipelineFile import Include, PipelineFile, ValueT 

90 

91 

92__all__ = ["KINDS", "SECTIONS", "MAX_DEFAULT_LENGTH"] 

93 

94KINDS = { 

95 "inputs": ("Parameter Name", "Required", "Type", "Default"), 

96 "variables": ("Variable Name", "Default", "Description"), 

97} 

98""" 

99The kinds of parameters ``glci:parameter-table`` summarizes, in the order it shows them by default: kind |rarr| the 

100columns. 

101""" 

102 

103SECTIONS = ("inputs", "variables", "stages", "include", "workflow", "default") 

104""" 

105The parts of a pipeline file ``glci:yaml`` shows by option ``:section:``: the inputs of the header's ``spec``, and 

106the top-level keys of the configuration. 

107""" 

108 

109MAX_DEFAULT_LENGTH = 120 

110"""The length a default is shortened to in a summary table; a multi-line default is shortened to its first line.""" 

111 

112_logger = getLogger(__name__) 

113 

114_ResultType = TypeVar("_ResultType") 

115 

116 

117@export 

118class PipelineReferenceDirective(BaseDirective): 

119 """ 

120 Base-class of the directives summarizing the current pipeline file, as set by the preceding ``glci:pipeline``. 

121 """ 

122 

123 @staticmethod 

124 def _Reference(objectType: str, target: str, text: str) -> addnodes.pending_xref: 

125 """ 

126 Create a reference to an object of the domain, shown as literal text if the object isn't documented. 

127 

128 :param objectType: The object type, as ``input``. 

129 :param target: The object's name, as ``Package.package_name``. 

130 :param text: The text of the reference. 

131 :returns: The pending reference. 

132 """ 

133 return addnodes.pending_xref( 

134 "", nodes.literal(text, text), refdomain="glci", reftype=objectType, reftarget=target, refexplicit=True, 

135 refwarn=False 

136 ) 

137 

138 def _GitLabURL(self, path: Path, first: Nullable[int] = None, last: Nullable[int] = None) -> Nullable[str]: 

139 """ 

140 Return the URL of a file of the documented repository on GitLab, at the documented ref. 

141 

142 :param path: The file's path. 

143 :param first: Optional, the first line to mark. Default: ``None``. 

144 :param last: Optional, the last line to mark. Default: ``None``. 

145 :returns: The URL, or ``None`` if ``glci_project``, ``glci_ref`` or ``glci_repository_root`` isn't configured, 

146 or the file isn't below the repository's root. 

147 """ 

148 project = self.config.glci_project 

149 ref = self.config.glci_ref 

150 if project is None or ref is None or (root := self.env.get_domain("glci").RepositoryRoot) is None: 

151 return None 

152 

153 try: 

154 relative = path.resolve().relative_to(root).as_posix() 

155 except ValueError: 

156 return None 

157 

158 url = f"{self.config.glci_server.rstrip('/')}/{project}/-/blob/{ref}/{relative}" 

159 if first is None: 159 ↛ 161line 159 didn't jump to line 161 because the condition on line 159 was always true

160 return url 

161 elif last is None or last == first: 

162 return f"{url}#L{first}" 

163 

164 return f"{url}#L{first}-{last}" 

165 

166 def _CurrentPipeline(self) -> Nullable[PipelineFile]: 

167 """ 

168 Return the model of the current pipeline file, and warn if there is no ``glci:pipeline`` before the directive. 

169 

170 :returns: The pipeline file, or ``None`` if there is no ``glci:pipeline`` before the directive, or its file couldn't 

171 be read - which the ``glci:pipeline`` directive reported already. 

172 """ 

173 if self.env.ref_context.get("glci:pipeline", None) is None: 

174 _logger.warning( 

175 f"{self.directiveName} is not preceded by a glci:pipeline.", 

176 location=self.get_location(), type=WARNING_TYPE, subtype="pipeline" 

177 ) 

178 return None 

179 

180 return self.env.get_domain("glci").GetCurrentPipeline() 

181 

182 def _ResolveOrWarn(self, resolve: Callable[[], _ResultType], fallback: Callable[[], _ResultType]) -> _ResultType: 

183 """ 

184 Read a file a pipeline file includes or triggers, and report a file that is malformed as a warning. 

185 

186 :param resolve: The operation reading the file, as :meth:`IncludeResolver.Resolve 

187 <pyTooling.GitLab.PipelineFile.IncludeResolver.Resolve>`. 

188 :param fallback: The operation giving the result, when the file couldn't be read. 

189 :returns: The result of ``resolve``, or of ``fallback`` after a warning. 

190 """ 

191 from pyTooling.GitLab.PipelineFile import PipelineFileError 

192 

193 try: 

194 return resolve() 

195 except PipelineFileError as ex: 

196 _logger.warning( 

197 f"{self.directiveName}: {ex}", location=self.get_location(), type=WARNING_TYPE, subtype="pipeline" 

198 ) 

199 return fallback() 

200 

201 

202@export 

203class ParameterTable(PipelineReferenceDirective): 

204 """ 

205 The directive ``glci:parameter-table``: summary tables of the current pipeline file's inputs and variables. 

206 

207 .. code-block:: ReST 

208 

209 .. glci:parameter-table:: 

210 :kinds: inputs 

211 

212 A table per kind, in the order ``:kinds:`` names them, by default the order of :data:`KINDS`. A table lists the 

213 parameters in file order, each name linked to its entry. An input's row states whether it is required, its type and 

214 its default; a variable's row its value and its description - a long or multi-line default is shortened, the entry 

215 shows it in full. 

216 

217 Without ``:kinds:``, a table is shown for every kind the pipeline file has parameters of. A kind named explicitly, of 

218 which the file has none, is a table with a single row saying so. 

219 """ 

220 

221 directiveName: str = "glci:parameter-table" #: Name the directive is invoked by. 

222 

223 has_content = False #: A boolean; ``True`` if content is allowed. 

224 required_arguments = 0 #: Number of required directive arguments. 

225 optional_arguments = 0 #: Number of optional arguments after the required ones. 

226 final_argument_whitespace = False #: A boolean; ``True`` if the last argument may contain spaces. 

227 option_spec: dict[str, Any] = { # type: ignore[misc] 

228 "kinds": strip, 

229 } #: Mapping of option names to validator functions. 

230 

231 def run(self) -> list[nodes.Node]: 

232 """ 

233 Create the summary tables. 

234 

235 :returns: A table per kind, an error node if option ``:kinds:`` names an unknown kind, or nothing without a 

236 current pipeline. 

237 """ 

238 try: 

239 kinds = self._ParseKinds() 

240 except SphinxExtensionError as ex: 

241 return [self.state.document.reporter.error(str(ex), line=self.lineno)] 

242 

243 if (pipelineFile := self._CurrentPipeline()) is None: 

244 return [] 

245 

246 pipelineName = self.env.ref_context["glci:pipeline"] 

247 tables = [] 

248 for kind in kinds: 

249 parameters = getattr(pipelineFile, kind.capitalize()) 

250 if len(parameters) == 0 and "kinds" not in self.options: 

251 continue 

252 

253 columns = KINDS[kind] 

254 tableGroup = self._CreateSingleRowTableHeader( 

255 columns=[(title, None) for title in columns], 

256 identifier=f"{pipelineName}-{kind}", 

257 classes=["glci-parameter-table", f"glci-{kind}"] 

258 ) 

259 tableGroup += (tableBody := nodes.tbody()) 

260 

261 if len(parameters) == 0: 

262 entry = nodes.entry("", nodes.paragraph("", "", nodes.emphasis(text=f"No {kind}")), morecols=len(columns) - 1) 

263 tableBody += nodes.row("", entry) 

264 

265 for name, parameter in parameters.items(): 

266 row = nodes.row() 

267 row += nodes.entry("", nodes.paragraph("", "", self._Reference(kind[:-1], f"{pipelineName}.{name}", name))) 

268 if kind == "inputs": 

269 row += nodes.entry("", nodes.paragraph(text="yes" if parameter.Required else "no")) 

270 row += nodes.entry("", nodes.paragraph(text=parameter.Type.value)) 

271 row += nodes.entry("", self._DefaultParagraph(parameter.Default)) 

272 else: 

273 description = "" if parameter.Description is None else parameter.Description.strip() 

274 row += nodes.entry("", self._DefaultParagraph(parameter.Value)) 

275 row += nodes.entry("", nodes.paragraph(description, description)) 

276 

277 tableBody += row 

278 

279 tables.append(tableGroup.parent) 

280 

281 return tables 

282 

283 def _ParseKinds(self) -> tuple[str, ...]: 

284 """ 

285 Read option ``:kinds:``, a list of kinds separated by spaces or commas. 

286 

287 :returns: The kinds named, in the order written and each once, or every kind of :data:`KINDS` 

288 without the option. 

289 :raises SphinxExtensionError: If a kind is not one of :data:`KINDS`. 

290 """ 

291 if "kinds" not in self.options: 

292 return tuple(KINDS) 

293 

294 kinds = tuple(dict.fromkeys(self.options["kinds"].replace(",", " ").split())) 

295 for kind in kinds: 

296 if kind not in KINDS: 

297 raise SphinxExtensionError(f"{self.directiveName}::kinds: '{kind}' is not one of {', '.join(KINDS)}.") 

298 

299 return kinds 

300 

301 @staticmethod 

302 def _DefaultParagraph(value: ValueT) -> nodes.paragraph: 

303 """ 

304 Create the paragraph of a table cell showing a default. 

305 

306 A multi-line string is shortened to its first line, and a longer text to :data:`MAX_DEFAULT_LENGTH` characters, 

307 each followed by ``…``. 

308 

309 :param value: The default, as :attr:`Input.Default <pyTooling.GitLab.PipelineFile.Input.Default>`. 

310 :returns: The paragraph, holding :data:`~pyTooling.GitLab.Sphinx.NO_DEFAULT` for ``None``, or the default as 

311 literal text. 

312 """ 

313 if value is None: 

314 return nodes.paragraph(NO_DEFAULT, NO_DEFAULT) 

315 

316 if isinstance(value, str): 

317 lines = value.splitlines() 

318 first = lines[0] if len(lines) > 0 else "" 

319 if len(lines) > 1 or len(first) > MAX_DEFAULT_LENGTH: 

320 value = f"{first[:MAX_DEFAULT_LENGTH]}…" 

321 

322 text = formatValue(value) 

323 return nodes.paragraph("", "", nodes.literal(text, text)) 

324 

325 

326@export 

327class Interface(PipelineReferenceDirective): 

328 """ 

329 The directive ``glci:interface``: the contract of the current pipeline file with a pipeline including it, as a field 

330 list. 

331 

332 .. code-block:: ReST 

333 

334 .. glci:interface:: 

335 

336 * *Required Inputs* - the inputs without a default, which ``include:inputs`` has to set, each linked to its entry. 

337 * *Variables* - the default variables with a ``description``, which the form running a pipeline by hand prefills. 

338 * *Stages* - the stages the file's jobs run in, which the including pipeline has to declare, in the file's order; a 

339 stage given by an input, as ``$[[ inputs.stage ]]``, as written. 

340 * *Jobs* and *Hidden Jobs* - the jobs the file adds to a pipeline, and the hidden jobs others may ``extends``. 

341 

342 The files the pipeline file includes are listed by :class:`Dependencies`. 

343 """ 

344 

345 directiveName: str = "glci:interface" #: Name the directive is invoked by. 

346 

347 has_content = False #: A boolean; ``True`` if content is allowed. 

348 required_arguments = 0 #: Number of required directive arguments. 

349 optional_arguments = 0 #: Number of optional arguments after the required ones. 

350 final_argument_whitespace = False #: A boolean; ``True`` if the last argument may contain spaces. 

351 option_spec: dict[str, Any] = {} #: Mapping of option names to validator functions. 

352 

353 def run(self) -> list[nodes.Node]: 

354 """ 

355 Create the field list. 

356 

357 :returns: The field list, or nothing without a current pipeline. 

358 """ 

359 if (pipelineFile := self._CurrentPipeline()) is None: 359 ↛ 360line 359 didn't jump to line 360 because the condition on line 359 was never true

360 return [] 

361 

362 pipelineName = self.env.ref_context["glci:pipeline"] 

363 

364 fieldList = nodes.field_list(classes=["glci-interface"]) 

365 fieldList += self._Field("Required Inputs", [ 

366 [self._Reference("input", f"{pipelineName}.{name}", name)] 

367 for name, parameter in pipelineFile.Inputs.items() if parameter.Required 

368 ]) 

369 fieldList += self._Field("Variables", [ 

370 [self._Reference("variable", f"{pipelineName}.{name}", name)] 

371 for name, variable in pipelineFile.Variables.items() if variable.Description is not None 

372 ]) 

373 used = dict.fromkeys(job.Stage for job in pipelineFile.IterateJobs()) 

374 stages = [stage for stage in pipelineFile.Stages if stage in used] 

375 stages.extend(stage for stage in used if stage not in pipelineFile.Stages) 

376 fieldList += self._Field("Stages", [[nodes.literal(stage, stage)] for stage in stages]) 

377 fieldList += self._Field("Jobs", [[nodes.literal(name, name)] for name in pipelineFile.Jobs]) 

378 fieldList += self._Field("Hidden Jobs", [[nodes.literal(name, name)] for name in pipelineFile.HiddenJobs]) 

379 

380 return [fieldList] 

381 

382 @staticmethod 

383 def _Field(name: str, items: list[list[nodes.Node]]) -> nodes.field: 

384 """ 

385 Create a field listing items separated by commas, or saying *none*. 

386 

387 :param name: The field's name. 

388 :param items: The items, each as the nodes of an item. 

389 :returns: The field. 

390 """ 

391 if len(items) == 0: 

392 body = nodes.paragraph("", "", nodes.emphasis(text="none")) 

393 else: 

394 body = nodes.paragraph() 

395 for index, item in enumerate(items): 

396 if index > 0: 

397 body += nodes.Text(", ") 

398 body.extend(item) 

399 

400 return nodes.field("", nodes.field_name(text=name), nodes.field_body("", body)) 

401 

402 

403@export 

404class Dependencies(PipelineReferenceDirective): 

405 """ 

406 The directive ``glci:dependencies``: what the current pipeline file uses, as a nested bullet list. 

407 

408 .. code-block:: ReST 

409 

410 .. glci:dependencies:: 

411 

412 * /ci/build.yml 

413 

414 * Python packages given by :glci:input:`Build.requirements`. 

415 

416 From the pipeline file, and the local files it includes and triggers, as far as they are known locally: 

417 

418 * the files ``include`` adds - a local file, another project's files, a URL, a template, a component, a job's 

419 artifact -, each once; a local file read from ``glci_repository_root`` with its own dependencies; 

420 * the child pipelines a trigger job runs, with the files of the child pipeline, and the other projects' pipelines a 

421 trigger job starts; 

422 * the images of the containers and service containers the jobs run in, ``default`` included. 

423 

424 The content is a bullet list of what a file can't tell, like packages installed by a script. It is merged into the 

425 derived list: an item whose text is the name of a derived item - an include as written, a trigger job as 

426 ``trigger <job>``, a container as ``image`` or ``service``, or the image - adds its nested list to that item, 

427 recursively. Any other item is appended to the list it is in. Content after the bullet list follows the list. 

428 """ 

429 

430 directiveName: str = "glci:dependencies" #: Name the directive is invoked by. 

431 

432 has_content = True #: The hand-written dependencies. 

433 required_arguments = 0 #: Number of required directive arguments. 

434 optional_arguments = 0 #: Number of optional arguments after the required ones. 

435 final_argument_whitespace = False #: A boolean; ``True`` if the last argument may contain spaces. 

436 option_spec: dict[str, Any] = {} #: Mapping of option names to validator functions. 

437 

438 _keys: dict[int, set[str]] #: Names of each derived item, by the item's identity. 

439 

440 def run(self) -> list[nodes.Node]: 

441 """ 

442 Create the list: the derived dependencies, merged with the hand-written ones. 

443 

444 :returns: The list and the content following it, a paragraph saying *none* if there are no dependencies, or 

445 nothing without a current pipeline. 

446 """ 

447 if (pipelineFile := self._CurrentPipeline()) is None: 447 ↛ 448line 447 didn't jump to line 448 because the condition on line 447 was never true

448 return [] 

449 

450 self._keys = {} 

451 dependencies = self._FileItems(pipelineFile, {pipelineFile.Path.resolve()}) 

452 dependencies["classes"].append("glci-dependencies") 

453 

454 others = [] 

455 for node in self.parse_content_to_nodes(): 

456 if isinstance(node, nodes.bullet_list): 456 ↛ 459line 456 didn't jump to line 459 because the condition on line 456 was always true

457 self._Merge(dependencies, node) 

458 else: 

459 others.append(node) 

460 

461 if len(dependencies) == 0: 

462 return [nodes.paragraph("", "", nodes.emphasis(text="none")), *others] 

463 

464 return [dependencies, *others] 

465 

466 def _Item(self, paragraph: nodes.paragraph, keys: set[str]) -> nodes.list_item: 

467 """ 

468 Create a derived item, known by the names a hand-written item may refer to it by. 

469 

470 :param paragraph: The item's text. 

471 :param keys: The names of the item. 

472 :returns: The item. 

473 """ 

474 item = nodes.list_item("", paragraph) 

475 self._keys[id(item)] = keys 

476 

477 return item 

478 

479 def _IncludeItem(self, include: Include) -> nodes.list_item: 

480 """ 

481 Create the item of an include. 

482 

483 A local file links to GitLab, if ``glci_project`` and ``glci_ref`` are configured; another project's files link 

484 to that project, a URL to itself, a component to its project. 

485 

486 :param include: The include. 

487 :returns: The item, known by the include as written. 

488 """ 

489 from pyTooling.GitLab.PipelineFile import IncludeKind 

490 

491 text = include.Location 

492 literal = nodes.literal(text, text) 

493 paragraph = nodes.paragraph("", f"{include.Kind.value} ") 

494 server = self.config.glci_server.rstrip("/") 

495 url = None 

496 if include.Kind is IncludeKind.Local and (root := self.env.get_domain("glci").RepositoryRoot) is not None: 

497 url = self._GitLabURL(root / text.lstrip("/")) 

498 elif include.Kind is IncludeKind.Project: 

499 url = f"{server}/{text}" 

500 elif include.Kind is IncludeKind.Remote: 

501 url = text 

502 elif include.Kind is IncludeKind.Component and "/" in (path := text.partition("@")[0]): 

503 url = f"{server}/{path.partition('/')[2].rpartition('/')[0]}" 

504 

505 paragraph += literal if url is None else nodes.reference(text, "", literal, refuri=url) 

506 if len(include.Files) > 0: 

507 paragraph += nodes.Text(f": {', '.join(include.Files)}") 

508 

509 return self._Item(paragraph, {text, text.partition("@")[0], *include.Files}) 

510 

511 def _ImageItem(self, kind: str, image: str) -> nodes.list_item: 

512 """ 

513 Create the item of a container's image. 

514 

515 :param kind: The kind of container, as ``image`` or ``service``. 

516 :param image: The image, as written. 

517 :returns: The item, known by the kind and the image. 

518 """ 

519 return self._Item(nodes.paragraph("", f"{kind} ", nodes.literal(image, image)), {kind, image}) 

520 

521 def _FileItems(self, pipelineFile: PipelineFile, visited: set[Path]) -> nodes.bullet_list: 

522 """ 

523 List a pipeline file's dependencies: its includes, the pipelines its trigger jobs start, and container images. 

524 

525 :param pipelineFile: The pipeline file. 

526 :param visited: The resolved paths of the files on the path to this one, which aren't expanded again. 

527 :returns: A bullet list, empty if the file uses nothing. 

528 """ 

529 resolver = self.env.get_domain("glci").Resolver 

530 bulletList = nodes.bullet_list() 

531 for include in {(include.Kind, include.Location): include for include in pipelineFile.Includes}.values(): 

532 bulletList += self._ResolvedItem(include, resolver, visited) 

533 

534 for job in pipelineFile.IterateJobs(): 

535 if (trigger := job.Trigger) is None: 

536 continue 

537 

538 paragraph = nodes.paragraph("", "trigger ", nodes.emphasis(text=job.Name)) 

539 if trigger.Project is not None: 

540 paragraph += (nodes.Text(" - project "), nodes.literal(trigger.Project, trigger.Project)) 

541 

542 item = self._Item(paragraph, {f"trigger {job.Name}", job.Name}) 

543 if len(childIncludes := trigger.Includes) > 0: 

544 item += nodes.bullet_list("", *(self._ResolvedItem(include, resolver, visited) for include in childIncludes)) 

545 

546 bulletList += item 

547 

548 images: dict[tuple[str, str], None] = {} 

549 if (default := pipelineFile.Default) is not None: 

550 if default.Image is not None: 550 ↛ 552line 550 didn't jump to line 552 because the condition on line 550 was always true

551 images[("image", default.Image)] = None 

552 images.update(dict.fromkeys(("service", service) for service in default.Services)) 

553 

554 for job in pipelineFile.IterateJobs(): 

555 if job.Image is not None: 

556 images[("image", job.Image)] = None 

557 images.update(dict.fromkeys(("service", service) for service in job.Services)) 

558 

559 bulletList.extend(self._ImageItem(kind, image) for kind, image in images) 

560 

561 return bulletList 

562 

563 def _ResolvedItem(self, include: Include, resolver: Any, visited: set[Path]) -> nodes.list_item: 

564 """ 

565 Create the item of an include, with the dependencies of the local file it names, if that is readable. 

566 

567 :param include: The include. 

568 :param resolver: The domain's resolver, or ``None`` if ``glci_repository_root`` isn't configured. 

569 :param visited: The resolved paths of the files on the path, which aren't expanded again. 

570 :returns: The item. 

571 """ 

572 item = self._IncludeItem(include) 

573 if resolver is None: 573 ↛ 574line 573 didn't jump to line 574 because the condition on line 573 was never true

574 return item 

575 

576 included = self._ResolveOrWarn(lambda: resolver.Resolve(include), lambda: None) 

577 if included is not None and (path := included.Path.resolve()) not in visited: 

578 if len(nested := self._FileItems(included, visited | {path})) > 0: 

579 item += nested 

580 

581 return item 

582 

583 def _Merge(self, derived: nodes.bullet_list, handwritten: nodes.bullet_list) -> None: 

584 """ 

585 Merge a hand-written list into a derived one. 

586 

587 A hand-written item whose text is a name of a derived item of this list adds its nested lists to that item, 

588 merged recursively; any other item is appended. 

589 

590 :param derived: The derived list. 

591 :param handwritten: The hand-written list. 

592 """ 

593 for item in list(handwritten.children): 

594 text = item[0].astext().strip() if len(item) > 0 and isinstance(item[0], nodes.paragraph) else None 

595 match = next( 

596 (child for child in derived.children if text is not None and text in self._keys.get(id(child), ())), None 

597 ) 

598 if match is None: 

599 derived += item 

600 continue 

601 

602 for node in item.children[1:]: 

603 nested = next((child for child in match.children if isinstance(child, nodes.bullet_list)), None) 

604 if isinstance(node, nodes.bullet_list) and nested is not None: 

605 self._Merge(nested, node) 

606 else: 

607 match += node 

608 

609 

610@export 

611class YAMLExcerpt(PipelineReferenceDirective): 

612 """ 

613 The directive ``glci:yaml``: the current pipeline file or a part of it, as a YAML code block. 

614 

615 .. code-block:: ReST 

616 

617 .. glci:yaml:: 

618 :section: inputs 

619 

620 Option ``:section:`` selects one of :data:`SECTIONS` - the ``inputs`` of the header's ``spec``, or a top-level key of 

621 the configuration; option ``:job:`` selects one job. Without either, the whole file is shown. 

622 

623 The lines are numbered as in the file, and the part is shifted left by the indentation of its first line. The caption 

624 names the file and the lines, and links to them on GitLab at ``glci_ref``, if ``glci_project``, ``glci_ref`` and 

625 ``glci_repository_root`` are configured. 

626 """ 

627 

628 directiveName: str = "glci:yaml" #: Name the directive is invoked by. 

629 

630 has_content = False #: A boolean; ``True`` if content is allowed. 

631 required_arguments = 0 #: Number of required directive arguments. 

632 optional_arguments = 0 #: Number of optional arguments after the required ones. 

633 final_argument_whitespace = False #: A boolean; ``True`` if the last argument may contain spaces. 

634 option_spec: dict[str, Any] = { # type: ignore[misc] 

635 "caption": directives.unchanged_required, 

636 "job": strip, 

637 "name": strip, 

638 "section": strip, 

639 } #: Mapping of option names to validator functions. 

640 

641 def run(self) -> list[nodes.Node]: 

642 """ 

643 Create the code block. 

644 

645 :returns: The code block in a captioned container, an error node for wrong options, or nothing without a current 

646 pipeline or when the part doesn't exist. 

647 """ 

648 if "section" in self.options and "job" in self.options: 

649 return [self.state.document.reporter.error( 

650 f"{self.directiveName}: Options ':section:' and ':job:' exclude each other.", line=self.lineno 

651 )] 

652 elif (section := self.options.get("section", None)) is not None and section not in SECTIONS: 

653 return [self.state.document.reporter.error( 

654 f"{self.directiveName}::section: '{section}' is not one of {', '.join(SECTIONS)}.", line=self.lineno 

655 )] 

656 

657 if (pipelineFile := self._CurrentPipeline()) is None: 657 ↛ 658line 657 didn't jump to line 658 because the condition on line 657 was never true

658 return [] 

659 

660 pipelineName = self.env.ref_context["glci:pipeline"] 

661 lines = pipelineFile.Path.read_text(encoding="utf-8").splitlines() 

662 if section is not None: 

663 if (line := self._SectionLine(pipelineFile, lines, section)) is None: 

664 _logger.warning( 

665 f"{self.directiveName}: Pipeline '{pipelineName}' has no {section}.", 

666 location=self.get_location(), type=WARNING_TYPE, subtype="drift" 

667 ) 

668 return [] 

669 

670 first, last = self._BlockOf(lines, line) 

671 elif (jobName := self.options.get("job", None)) is not None: 

672 job = pipelineFile.Jobs.get(jobName, None) or pipelineFile.HiddenJobs.get(jobName, None) 

673 if job is None: 

674 _logger.warning( 

675 f"{self.directiveName}: Pipeline '{pipelineName}' has no job '{jobName}'.", 

676 location=self.get_location(), type=WARNING_TYPE, subtype="drift" 

677 ) 

678 return [] 

679 

680 first, last = self._BlockOf(lines, job.Line) 

681 else: 

682 first = 1 

683 last = len(lines) 

684 

685 indentation = self._Indentation(lines[first - 1]) 

686 excerpt = [line[min(indentation, self._Indentation(line)):] for line in lines[first - 1:last]] 

687 

688 text = "\n".join(excerpt) 

689 literal = nodes.literal_block(text, text, language="yaml", linenos=True) 

690 literal["highlight_args"] = {"linenostart": first} 

691 self.set_source_info(literal) 

692 

693 if (caption := self.options.get("caption", None)) is None: 693 ↛ 705line 693 didn't jump to line 705 because the condition on line 693 was always true

694 fileName = pipelineFile.Path.name 

695 if first == 1 and last == len(lines): 

696 caption = fileName 

697 url = self._GitLabURL(pipelineFile.Path) 

698 else: 

699 caption = f"{fileName}, lines {first}-{last}" 

700 url = self._GitLabURL(pipelineFile.Path, first, last) 

701 

702 if url is not None: 

703 caption = f"`{caption} <{url}>`__" 

704 

705 container = container_wrapper(self, literal, caption) 

706 self.add_name(container) 

707 

708 return [container] 

709 

710 @classmethod 

711 def _SectionLine(cls, pipelineFile: PipelineFile, lines: list[str], section: str) -> Nullable[int]: 

712 """ 

713 Return the line of a section's key. 

714 

715 The inputs' key is the key holding the first input. A top-level key is searched in the configuration document, 

716 behind the header document's ``---``, if there is one. 

717 

718 :param pipelineFile: The pipeline file. 

719 :param lines: The lines of the file. 

720 :param section: One of :data:`SECTIONS`. 

721 :returns: The key's line, starting at 1, or ``None`` if the file hasn't the section. 

722 """ 

723 if section == "inputs": 

724 if len(pipelineFile.Inputs) == 0: 724 ↛ 725line 724 didn't jump to line 725 because the condition on line 724 was never true

725 return None 

726 

727 return cls._ParentOf(lines, next(iter(pipelineFile.Inputs.values())).Line) 

728 

729 start = 0 

730 if len(pipelineFile.Inputs) > 0 or pipelineFile.Description is not None: 730 ↛ 733line 730 didn't jump to line 733 because the condition on line 730 was always true

731 start = next((index + 1 for index, line in enumerate(lines) if line.rstrip() == "---"), 0) 

732 

733 for index in range(start, len(lines)): 

734 if lines[index].startswith(f"{section}:"): 

735 return index + 1 

736 

737 return None 

738 

739 @staticmethod 

740 def _Indentation(line: str) -> int: 

741 """ 

742 Return the indentation of a line of a YAML file. 

743 

744 :param line: The line. 

745 :returns: The number of spaces the line starts with. 

746 """ 

747 return len(line) - len(line.lstrip(" ")) 

748 

749 @staticmethod 

750 def _IsBlank(line: str) -> bool: 

751 """ 

752 Return whether a line is empty or a comment. 

753 

754 :param line: The line. 

755 :returns: ``True``, if the line holds nothing but whitespace or a comment. 

756 """ 

757 stripped = line.strip() 

758 return stripped == "" or stripped.startswith("#") 

759 

760 @classmethod 

761 def _ParentOf(cls, lines: list[str], line: int) -> int: 

762 """ 

763 Return the line of the key a line is nested in. 

764 

765 :param lines: The lines of the file. 

766 :param line: The nested line, starting at 1. 

767 :returns: The nearest line above it that is indented less, starting at 1, or ``1``. 

768 """ 

769 indentation = cls._Indentation(lines[line - 1]) 

770 for index in range(line - 2, -1, -1): 770 ↛ 775line 770 didn't jump to line 775 because the loop on line 770 didn't complete

771 text = lines[index] 

772 if not cls._IsBlank(text) and cls._Indentation(text) < indentation: 772 ↛ 770line 772 didn't jump to line 770 because the condition on line 772 was always true

773 return index + 1 

774 

775 return 1 

776 

777 @classmethod 

778 def _BlockOf(cls, lines: list[str], line: int) -> tuple[int, int]: 

779 """ 

780 Return the lines of a key and its value. 

781 

782 The block ends before the next line - not empty and not a comment - indented as much as the key or less. A comment 

783 indented as much as the key or less, and empty lines, at the end aren't part of it. 

784 

785 :param lines: The lines of the file. 

786 :param line: The key's line, starting at 1. 

787 :returns: The first and the last line of the block, starting at 1. 

788 """ 

789 indentation = cls._Indentation(lines[line - 1]) 

790 last = line 

791 for index in range(line, len(lines)): 

792 text = lines[index] 

793 if text.strip() == "": 

794 continue 

795 elif cls._Indentation(text) > indentation: 

796 last = index + 1 

797 elif not cls._IsBlank(text): 797 ↛ 791line 797 didn't jump to line 791 because the condition on line 797 was always true

798 break 

799 

800 return line, last 

801 

802 

803@export 

804class AutoInputs(PipelineReferenceDirective): 

805 """ 

806 The directive ``glci:autoinputs``: an entry for every input of the current pipeline file the document has no 

807 ``glci:input`` for. 

808 

809 .. code-block:: ReST 

810 

811 .. glci:autoinputs:: 

812 

813 An entry is created as a ``glci:input`` without content creates it: the facts of the pipeline file and its 

814 *Description*. Inputs documented by a ``glci:input`` later in the document are left out, too - the entries are 

815 created by :class:`AutoInputsTransform` when the whole document was parsed. 

816 """ 

817 

818 directiveName: str = "glci:autoinputs" #: Name the directive is invoked by. 

819 

820 has_content = False #: A boolean; ``True`` if content is allowed. 

821 required_arguments = 0 #: Number of required directive arguments. 

822 optional_arguments = 0 #: Number of optional arguments after the required ones. 

823 final_argument_whitespace = False #: A boolean; ``True`` if the last argument may contain spaces. 

824 option_spec: dict[str, Any] = {} #: Mapping of option names to validator functions. 

825 

826 def run(self) -> list[nodes.Node]: 

827 """ 

828 Create a placeholder, replaced by the entries once the document was parsed. 

829 

830 :returns: The placeholder, or nothing without a current pipeline. 

831 """ 

832 if (pipelineFile := self._CurrentPipeline()) is None: 

833 return [] 

834 

835 details = {"pipeline": self.env.ref_context["glci:pipeline"], "path": pipelineFile.Path} 

836 pending = nodes.pending(AutoInputsTransform, details) 

837 self.set_source_info(pending) 

838 self.state.document.note_pending(pending) 

839 

840 return [pending] 

841 

842 

843@export 

844class AutoInputsTransform(SphinxTransform): 

845 """ 

846 Replaces the placeholder of a ``glci:autoinputs`` by an entry for every input of its pipeline file the document has 

847 no ``glci:input`` for. 

848 

849 It runs after the document was parsed - so every ``glci:input`` has registered its entry - and before the entries are 

850 collected for the table of contents and the index. 

851 """ 

852 

853 default_priority = 400 #: Priority among the transforms: before the local table of contents and the smart quotes. 

854 

855 def apply(self, **kwargs: Any) -> None: 

856 """ 

857 Replace the placeholder by the entries. 

858 

859 :param kwargs: Unused. 

860 """ 

861 pending: nodes.pending = self.startnode 

862 pipelineName = pending.details["pipeline"] 

863 domain = self.env.get_domain("glci") 

864 pipelineFile = domain.LoadPipelineFile(pending.details["path"]) 

865 

866 entries = [] 

867 for name, parameter in pipelineFile.Inputs.items(): 

868 if domain.Objects.get(("input", f"{pipelineName}.{name}"), ("", ""))[0] != self.env.docname: 

869 entries.extend(InputDirective.CreateEntry( 

870 self.env, self.document, pipelineName, name, parameter, [], [], pending.source, pending.line 

871 )) 

872 

873 pending.replace_self(entries) 

874 

875 

876@export 

877def checkUndocumentedInputs(sphinx: Sphinx, doctree: nodes.document) -> None: 

878 """ 

879 Call-back for Sphinx' ``doctree-read`` event, warning about inputs the document has no entry for. 

880 

881 Every input of a pipeline file the document names by ``glci:pipeline`` needs an entry in the document, by a 

882 ``glci:input`` or a ``glci:autoinputs``; one without is a warning of type ``glci.drift`` at the ``glci:pipeline``. 

883 

884 :param sphinx: The Sphinx application. 

885 :param doctree: The document read. 

886 """ 

887 if (pipelines := sphinx.env.current_document.get("glci:pipelines", None)) is None: 

888 return 

889 

890 domain = sphinx.env.get_domain("glci") 

891 for pipelineName, path, location in pipelines: 

892 for name in domain.LoadPipelineFile(path).Inputs: 

893 if domain.Objects.get(("input", f"{pipelineName}.{name}"), ("", ""))[0] != sphinx.env.docname: 

894 _logger.warning( 

895 f"Input '{name}' of pipeline '{pipelineName}' has no entry: add a glci:input or a glci:autoinputs.", 

896 location=location, type=WARNING_TYPE, subtype="drift" 

897 )