Coverage for pyTooling/GitLab/Sphinx/__init__.py: 97%

327 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""" 

32A Sphinx domain ``glci`` documenting GitLab CI/CD pipeline files from their YAML files. 

33 

34The facts of a pipeline file's parameters - an input's type, whether it is required, its default, its options - are 

35read from the file by :mod:`pyTooling.GitLab.PipelineFile`, so a page states them without copying them. What the file 

36can't say stays hand-written, as the content of a directive: 

37 

38.. code-block:: rst 

39 

40 .. glci:pipeline:: Package 

41 :file: ../templates/Package/template.yml 

42 

43 Package 

44 ####### 

45 

46 .. glci:input:: package_name 

47 

48 :Example: ``myPackage`` 

49 

50.. rubric:: What it registers 

51 

52* Directives 

53 

54 * ``glci:pipeline`` 

55 * ``glci:input`` 

56 * ``glci:variable`` 

57 

58* Roles 

59 

60 * ``:glci:pipeline:`` 

61 * ``:glci:input:`` 

62 * ``:glci:variable:`` 

63 

64* Configuration values, as listed in :attr:`GitLabCIDomain.configValues` 

65 

66 * ``glci_server`` 

67 * ``glci_project`` 

68 * ``glci_repository_root`` 

69 * ``glci_pipeline_directory`` 

70 * ``glci_ref`` 

71 * ``glci_label_prefix`` 

72 

73The pipeline files are read with ``ruamel.yaml`` when a directive runs, not when this module is imported. 

74 

75.. seealso:: 

76 

77 :mod:`pyTooling.GitLab.PipelineFile` 

78 |rarr| The model of a pipeline file the domain reads. 

79 :mod:`pyTooling.GitLab.Sphinx.Graph` 

80 |rarr| The ``glci:pipeline-graph`` directive, drawing a pipeline file's jobs and their dependencies. 

81 :mod:`pyTooling.GitLab.Sphinx.Reference` 

82 |rarr| The directives summarizing a pipeline file: its parameters, its interface, its dependencies, its YAML. 

83""" 

84from __future__ import annotations 

85 

86from pathlib import Path 

87from typing import TYPE_CHECKING, Any, ClassVar, Iterable, Optional as Nullable, Union 

88 

89from docutils import nodes 

90from docutils.nodes import Element, Node, fully_normalize_name 

91from docutils.parsers.rst import directives 

92from sphinx import addnodes 

93from sphinx.application import Sphinx 

94from sphinx.builders import Builder 

95from sphinx.domains import Domain, ObjType 

96from sphinx.environment import BuildEnvironment 

97from sphinx.roles import XRefRole 

98from sphinx.util.logging import getLogger 

99from sphinx.util.nodes import make_id, make_refnode 

100 

101from pyTooling.Common import getFullyQualifiedName 

102from pyTooling.Decorators import export, readonly 

103from pyTooling.Sphinx import BaseDirective 

104 

105if TYPE_CHECKING: # pragma: no cover 

106 from pyTooling.GitLab.PipelineFile import IncludeResolver, Input, PipelineFile, ValueT, Variable 

107 

108 

109__all__ = ["NO_DEFAULT", "WARNING_TYPE", "LEADING_FIELDS", "FILE_SUFFIXES"] 

110 

111NO_DEFAULT = "— — — —" 

112"""The text of the field *Default Value* when a parameter has no default.""" 

113 

114WARNING_TYPE = "glci" 

115""" 

116The type of the warnings this domain emits; the drift warnings have the subtype ``drift``, so 

117``suppress_warnings = ["glci.drift"]`` silences them. 

118""" 

119 

120LEADING_FIELDS = ("Type", "Required", "Default Value", "Possible Values", "Pattern") 

121"""The fields a *Description* taken from the pipeline file follows.""" 

122 

123FILE_SUFFIXES = ("{name}.yml", "{name}.yaml", "{name}/template.yml", "{name}/template.yaml") 

124""" 

125The file names a ``glci:pipeline`` without ``:file:`` tries in ``glci_pipeline_directory``, in this order; ``{name}`` 

126is the pipeline's name. The last is a CI/CD component's layout. 

127""" 

128 

129_logger = getLogger(__name__) 

130 

131 

132@export 

133def formatValue(value: ValueT) -> str: 

134 """ 

135 Format a value read from a pipeline file the way the file writes it. 

136 

137 A string is quoted as YAML quotes it - ``'3.14'`` -, a boolean is ``true`` or ``false``, a number is written as it is, 

138 and a list is written in YAML's flow style - ``['a', 'b']``. 

139 

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

141 :returns: The value as text, or :data:`NO_DEFAULT` for ``None``. 

142 """ 

143 if value is None: 

144 return NO_DEFAULT 

145 elif isinstance(value, bool): 

146 return "true" if value else "false" 

147 elif isinstance(value, str): 

148 escaped = value.replace("'", "''") 

149 return f"'{escaped}'" 

150 elif isinstance(value, list): 

151 return f"[{', '.join(formatValue(item) for item in value)}]" 

152 elif isinstance(value, dict): 

153 return f"{{{', '.join(f'{key}: {formatValue(item)}' for key, item in value.items())}}}" 

154 

155 return str(value) 

156 

157 

158@export 

159class PipelineDirective(BaseDirective): 

160 """ 

161 The directive ``glci:pipeline``: a pipeline file's target, its index entry, and the current pipeline of the document. 

162 

163 .. code-block:: rst 

164 

165 .. glci:pipeline:: Package 

166 :file: ../templates/Package/template.yml 

167 

168 The argument is the pipeline's name. Without ``:file:``, the file is looked up in ``glci_pipeline_directory`` by the 

169 names of :data:`FILE_SUFFIXES`. Every ``glci:input`` and ``glci:variable`` following it in the document belongs to 

170 this pipeline. 

171 

172 The directive writes no visible output. Placed above a page's title, its target is the title, as a label is. 

173 """ 

174 

175 directiveName: str = "glci:pipeline" #: Name the directive is invoked by. 

176 

177 has_content = False #: The directive has no content. 

178 required_arguments = 1 #: The pipeline's name. 

179 option_spec = {"file": directives.unchanged_required} #: Path to the pipeline file, relative to the document. 

180 

181 def run(self) -> list[Node]: 

182 """ 

183 Register the pipeline, read its file, and make it the current pipeline. 

184 

185 :returns: An index node and the pipeline's target. 

186 """ 

187 name = self.arguments[0].strip() 

188 domain: GitLabCIDomain = self.env.get_domain("glci") 

189 

190 path = None 

191 if "file" in self.options: 

192 path = Path(self.env.relfn2path(self.options["file"], self.env.docname)[1]) 

193 elif (directory := domain.PipelineDirectory) is not None: 

194 candidates = [directory / suffix.format(name=name) for suffix in FILE_SUFFIXES] 

195 path = next((candidate for candidate in candidates if candidate.exists()), candidates[0]) 

196 

197 if path is None: 

198 _logger.warning( 

199 f"{self.directiveName} '{name}' has no file: give option ':file:' or set 'glci_pipeline_directory'.", 

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

201 ) 

202 elif not path.exists(): 

203 _logger.warning( 

204 f"{self.directiveName} '{name}': file '{path}' doesn't exist.", 

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

206 ) 

207 else: 

208 self.env.note_dependency(str(path)) 

209 self._Load(domain, name, path) 

210 

211 self.env.ref_context["glci:pipeline"] = name 

212 

213 nodeID = make_id(self.env, self.state.document, "glci-pipeline", name) 

214 target = nodes.target("", "", ids=[nodeID]) 

215 if (prefix := self.config.glci_label_prefix) is not None: 

216 label = f"{prefix}/{name}" 

217 target["ids"].append(nodes.make_id(label)) 

218 target["names"].append(fully_normalize_name(label)) 

219 

220 self.set_source_info(target) 

221 self.state.document.note_explicit_target(target) 

222 domain.NoteObject("pipeline", name, nodeID, target) 

223 

224 return [addnodes.index(entries=[("single", f"GitLab CI/CD pipeline; {name}", nodeID, "", None)]), target] 

225 

226 def _Load(self, domain: GitLabCIDomain, name: str, path: Path) -> None: 

227 """ 

228 Read the pipeline file and make it the current one. 

229 

230 A file that isn't a well-formed configuration is reported as a warning at the place in the file, and the document 

231 has no current pipeline model then. A pipeline read is added to the document's list ``glci:pipelines`` of (name, 

232 path, location of the directive), which is checked when the document was read. 

233 

234 :param domain: The domain. 

235 :param name: The pipeline's name, as given as argument. 

236 :param path: Path to the pipeline file. 

237 """ 

238 from pyTooling.GitLab.PipelineFile import PipelineFileError 

239 

240 try: 

241 domain.LoadPipelineFile(path) 

242 except PipelineFileError as ex: 

243 if ex.Path is None: 243 ↛ 244line 243 didn't jump to line 244 because the condition on line 243 was never true

244 location = self.get_location() 

245 elif ex.Line is None: 245 ↛ 246line 245 didn't jump to line 246 because the condition on line 245 was never true

246 location = str(ex.Path) 

247 else: 

248 location = f"{ex.Path}:{ex.Line}" 

249 

250 _logger.warning(f"{self.directiveName} '{name}': {ex}", location=location, type=WARNING_TYPE, subtype="pipeline") 

251 return 

252 

253 self.env.current_document["glci:pipeline-file"] = path 

254 self.env.current_document.setdefault("glci:pipelines", []).append((name, path, self.get_location())) 

255 

256 

257@export 

258class ParameterDirective(BaseDirective): 

259 """ 

260 Base-class of the directives documenting one parameter of the current pipeline. 

261 

262 The entry is a section titled by the parameter's name, holding a field list: first the fields read from the pipeline 

263 file (:meth:`_FactFields`), then the fields of the directive's content, in the order written. Without a hand-written 

264 *Description*, the pipeline file's ``description`` is used, placed behind the :data:`LEADING_FIELDS`. Content after 

265 the field list follows it. 

266 

267 A hand-written field repeating a fact of the file is a warning, and the file's value is shown. 

268 

269 Besides its anchor ``glci-<type>-<Pipeline>.<name>``, the section carries the anchor of its label and - unless the 

270 document uses it already - the anchor docutils derives from a title, as a hand-written section has. 

271 """ 

272 

273 OBJECT_TYPE: ClassVar[str] #: The domain's object type, as ``input``. 

274 LABEL_KIND: ClassVar[str] #: The kind in a label, as ``Input`` in ``PIPELINE/Package/Input/name``. 

275 COLLECTION: ClassVar[str] #: The pipeline file's property holding the parameters, as ``Inputs``. 

276 FACT_FIELDS: ClassVar[tuple[str, ...]] #: The fields the pipeline file may state. 

277 

278 has_content = True #: The hand-written fields and text. 

279 required_arguments = 1 #: The parameter's name. 

280 

281 def run(self) -> list[Node]: 

282 """ 

283 Create the parameter's entry and register it. 

284 

285 :returns: An index node and the entry's section, or nothing outside a ``glci:pipeline``. 

286 """ 

287 name = self.arguments[0].strip() 

288 if (pipelineName := self.env.ref_context.get("glci:pipeline", None)) is None: 

289 _logger.warning( 

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

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

292 ) 

293 return [] 

294 

295 domain: GitLabCIDomain = self.env.get_domain("glci") 

296 parameter = None 

297 if (pipelineFile := domain.GetCurrentPipeline()) is not None: 297 ↛ 304line 297 didn't jump to line 304 because the condition on line 297 was always true

298 if (parameter := getattr(pipelineFile, self.COLLECTION).get(name, None)) is None: 

299 _logger.warning( 

300 f"Pipeline '{pipelineName}' has no {self.OBJECT_TYPE} '{name}' ({pipelineFile.Path.name}).", 

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

302 ) 

303 

304 facts = self.FACT_FIELDS if parameter is None else [field[0].astext() for field in self._FactFields(parameter)] 

305 

306 content = self.parse_content_to_nodes() 

307 handwritten = [] 

308 if len(content) > 0 and isinstance(content[0], nodes.field_list): 

309 handwritten = list(content[0].children) 

310 content = content[1:] 

311 

312 fields = [] 

313 for field in handwritten: 

314 fieldName = field[0].astext().strip() 

315 if fieldName in facts: 

316 _logger.warning( 

317 f"{self.directiveName} '{pipelineName}.{name}': field '{fieldName}' is taken from the pipeline file; " 

318 "remove it.", 

319 location=field, type=WARNING_TYPE, subtype="drift" 

320 ) 

321 if parameter is not None: 321 ↛ 324line 321 didn't jump to line 324 because the condition on line 321 was always true

322 continue 

323 

324 fields.append(field) 

325 

326 source, line = self.get_source_info() 

327 return self.CreateEntry(self.env, self.state.document, pipelineName, name, parameter, fields, content, source, line) 

328 

329 @classmethod 

330 def CreateEntry( 

331 cls, 

332 env: BuildEnvironment, 

333 document: nodes.document, 

334 pipelineName: str, 

335 name: str, 

336 parameter: Nullable[Union[Input, Variable]], 

337 fields: list[nodes.field], 

338 content: list[Node], 

339 source: str, 

340 line: Nullable[int] 

341 ) -> list[Node]: 

342 """ 

343 Create a parameter's entry and register it in the domain. 

344 

345 :param env: The build environment. 

346 :param document: The document the entry is placed in. 

347 :param pipelineName: The pipeline's name. 

348 :param name: The parameter's name. 

349 :param parameter: The parameter, as read from the pipeline file, or ``None`` if the pipeline file wasn't read or 

350 hasn't this parameter. 

351 :param fields: The hand-written fields, without those repeating a fact of the pipeline file. 

352 :param content: The nodes following the field list. 

353 :param source: The source file the entry is reported at. 

354 :param line: The line the entry is reported at, or ``None``. 

355 :returns: An index node and the entry's section. 

356 """ 

357 fullName = f"{pipelineName}.{name}" 

358 nodeID = make_id(env, document, f"glci-{cls.OBJECT_TYPE}", fullName) 

359 section = nodes.section("", nodes.title(name, name), ids=[nodeID]) 

360 if (titleID := nodes.make_id(name)) not in document.ids: 360 ↛ 364line 360 didn't jump to line 364 because the condition on line 360 was always true

361 section["ids"].append(titleID) 

362 

363 # The label's anchor comes last: docutils links a name to a node's last anchor, so a link keeps its target. 

364 if (prefix := env.config.glci_label_prefix) is not None: 364 ↛ 369line 364 didn't jump to line 369 because the condition on line 364 was always true

365 label = f"{prefix}/{pipelineName}/{cls.LABEL_KIND}/{name}" 

366 section["ids"].append(nodes.make_id(label)) 

367 section["names"].append(fully_normalize_name(label)) 

368 

369 section.source = source 

370 section.line = line 

371 document.note_explicit_target(section) 

372 

373 if parameter is not None: 

374 fields = [*cls._FactFields(parameter), *fields] 

375 

376 fieldNames = [field[0].astext().strip() for field in fields] 

377 if "Description" not in fieldNames and parameter is not None and parameter.Description: 

378 leading = [index + 1 for index, fieldName in enumerate(fieldNames) if fieldName in LEADING_FIELDS] 

379 position = max(leading, default=0) 

380 fields.insert(position, cls._TextField("Description", parameter.Description.strip())) 

381 

382 if len(fields) > 0: 

383 section += nodes.field_list("", *fields) 

384 section.extend(content) 

385 

386 domain: GitLabCIDomain = env.get_domain("glci") 

387 domain.NoteObject(cls.OBJECT_TYPE, fullName, nodeID, section) 

388 return [ 

389 addnodes.index(entries=[("single", f"{name} ({cls.OBJECT_TYPE} of {pipelineName})", nodeID, "", None)]), 

390 section 

391 ] 

392 

393 @staticmethod 

394 def _Field(name: str, *body: Node) -> nodes.field: 

395 """ 

396 Create a field of a field list. 

397 

398 :param name: Name of the field, as ``Type``. 

399 :param body: The nodes of the field's body. 

400 :returns: The field. 

401 """ 

402 return nodes.field("", nodes.field_name(name, name), nodes.field_body("", *body)) 

403 

404 @classmethod 

405 def _TextField(cls, name: str, text: str) -> nodes.field: 

406 """ 

407 Create a field of a field list, whose body is a line of text. 

408 

409 :param name: Name of the field, as ``Required``. 

410 :param text: Text of the field's body. 

411 :returns: The field. 

412 """ 

413 return cls._Field(name, nodes.paragraph(text, text)) 

414 

415 @classmethod 

416 def _LiteralField(cls, name: str, texts: Iterable[str]) -> nodes.field: 

417 """ 

418 Create a field of a field list, whose body is a line of literals separated by commas. 

419 

420 :param name: Name of the field, as ``Possible Values``. 

421 :param texts: The literals' texts. 

422 :returns: The field. 

423 """ 

424 paragraph = nodes.paragraph() 

425 for index, text in enumerate(texts): 

426 if index > 0: 

427 paragraph += nodes.Text(", ") 

428 paragraph += nodes.literal(text, text) 

429 

430 return cls._Field(name, paragraph) 

431 

432 @classmethod 

433 def _DefaultField(cls, value: ValueT) -> nodes.field: 

434 """ 

435 Create the field *Default Value*. 

436 

437 A multi-line string becomes a literal block, keeping its line breaks; no default becomes :data:`NO_DEFAULT`. 

438 

439 :param value: The default value. 

440 :returns: The field. 

441 """ 

442 if value is None: 

443 return cls._TextField("Default Value", NO_DEFAULT) 

444 elif isinstance(value, str) and "\n" in value: 

445 return cls._Field("Default Value", nodes.literal_block(value, value, language="text")) 

446 

447 return cls._LiteralField("Default Value", (formatValue(value), )) 

448 

449 @classmethod 

450 def _FactFields(cls, parameter: Union[Input, Variable]) -> list[nodes.field]: 

451 """ 

452 Create the fields taken from the pipeline file. 

453 

454 :param parameter: The parameter, as read from the pipeline file. 

455 :returns: The fields the file states for this parameter, in the order of :attr:`FACT_FIELDS`. 

456 """ 

457 return [] 

458 

459 

460@export 

461class InputDirective(ParameterDirective): 

462 """ 

463 The directive ``glci:input``: an input of the current pipeline file's ``spec:inputs``. 

464 

465 The fields *Type*, *Required* and *Default Value* are taken from the pipeline file, and - where the file states them - 

466 *Possible Values* (``options``) and *Pattern* (``regex``). 

467 """ 

468 

469 directiveName: str = "glci:input" #: Name the directive is invoked by. 

470 

471 OBJECT_TYPE = "input" #: The domain's object type. 

472 LABEL_KIND = "Input" #: The kind in a label. 

473 COLLECTION = "Inputs" #: The pipeline file's property holding the parameters. 

474 

475 #: The fields the file may state. 

476 FACT_FIELDS = ("Type", "Required", "Default Value", "Possible Values", "Pattern") 

477 

478 @classmethod 

479 def _FactFields(cls, parameter: Input) -> list[nodes.field]: 

480 """ 

481 Create the fields *Type*, *Required*, *Default Value*, and *Possible Values* and *Pattern* if the input has them. 

482 

483 :param parameter: The input, as read from the pipeline file. 

484 :returns: The fields. 

485 """ 

486 fields = [ 

487 cls._TextField("Type", parameter.Type.value), 

488 cls._TextField("Required", "yes" if parameter.Required else "no"), 

489 cls._DefaultField(parameter.Default) 

490 ] 

491 if len(parameter.Options) > 0: 

492 fields.append(cls._LiteralField("Possible Values", (formatValue(option) for option in parameter.Options))) 

493 

494 if parameter.Regex is not None: 

495 fields.append(cls._LiteralField("Pattern", (parameter.Regex, ))) 

496 

497 return fields 

498 

499 

500@export 

501class VariableDirective(ParameterDirective): 

502 """ 

503 The directive ``glci:variable``: a default variable of the current pipeline file, declared in its ``variables``. 

504 

505 The fields *Type* - a variable is a string -, *Default Value* (``value``) and - where the file states them - *Possible 

506 Values* (``options``) are taken from the pipeline file. A variable with a ``description`` is prefilled in the form 

507 running a pipeline by hand. 

508 """ 

509 

510 directiveName: str = "glci:variable" #: Name the directive is invoked by. 

511 

512 OBJECT_TYPE = "variable" #: The domain's object type. 

513 LABEL_KIND = "Variable" #: The kind in a label. 

514 COLLECTION = "Variables" #: The pipeline file's property holding the parameters. 

515 FACT_FIELDS = ("Type", "Default Value", "Possible Values") #: The fields the file may state. 

516 

517 @classmethod 

518 def _FactFields(cls, parameter: Variable) -> list[nodes.field]: 

519 """ 

520 Create the fields *Type* and *Default Value*, and *Possible Values* if the variable has options. 

521 

522 :param parameter: The variable, as read from the pipeline file. 

523 :returns: The fields. 

524 """ 

525 fields = [cls._TextField("Type", "string"), cls._DefaultField(parameter.Value)] 

526 if len(parameter.Options) > 0: 

527 fields.append(cls._LiteralField("Possible Values", (formatValue(option) for option in parameter.Options))) 

528 

529 return fields 

530 

531 

532@export 

533class GitLabCIXRefRole(XRefRole): 

534 """ 

535 The roles ``:glci:pipeline:``, ``:glci:input:`` and ``:glci:variable:``. 

536 

537 A parameter is named as ``<Pipeline>.<name>``; inside a ``glci:pipeline``, the name alone refers to the current 

538 pipeline's parameter. A leading ``~`` shows only the part behind the last dot. 

539 """ 

540 

541 def process_link( 

542 self, 

543 env: BuildEnvironment, 

544 refnode: Element, 

545 has_explicit_title: bool, 

546 title: str, 

547 target: str 

548 ) -> tuple[str, str]: 

549 """ 

550 Remember the current pipeline on the reference, and shorten the title for a leading ``~``. 

551 

552 :param env: The build environment. 

553 :param refnode: The reference node. 

554 :param has_explicit_title: ``True``, if the role was written with a title, as ``text <target>``. 

555 :param title: The title. 

556 :param target: The target. 

557 :returns: The title and the target. 

558 """ 

559 refnode["glci:pipeline"] = env.ref_context.get("glci:pipeline", None) 

560 if not has_explicit_title and target.startswith("~"): 

561 target = target[1:] 

562 title = target.rpartition(".")[2] 

563 

564 return title, target 

565 

566 

567@export 

568class GitLabCIDomain(Domain): 

569 """ 

570 The Sphinx domain ``glci``, documenting GitLab CI/CD pipeline files. 

571 

572 Its objects are keyed by type and name - ``("pipeline", "Package")``, ``("input", "Package.package_name")`` - and 

573 located by document and anchor. Directives of other modules reach the domain by ``self.env.get_domain("glci")``, and 

574 use :meth:`GetCurrentPipeline`, :meth:`LoadPipelineFile`, :attr:`Resolver` and :meth:`ResolvePipeline`. 

575 """ 

576 

577 name = "glci" #: Name of the domain, the prefix of its directives and roles. 

578 label = "GitLab CI/CD" #: Name of the domain, as displayed. 

579 data_version = 1 #: Version of the data layout; a change discards pickled environments. 

580 

581 object_types: ClassVar[dict[str, ObjType]] = { # type: ignore[misc] 

582 "pipeline": ObjType("pipeline", "pipeline"), 

583 "input": ObjType("input", "input"), 

584 "variable": ObjType("variable", "variable"), 

585 } #: The object types, each referenced by the role of the same name. 

586 

587 directives: ClassVar[dict[str, type]] = { # type: ignore[misc] 

588 "pipeline": PipelineDirective, 

589 "input": InputDirective, 

590 "variable": VariableDirective, 

591 } #: The directives, by name. 

592 

593 roles: ClassVar[dict[str, XRefRole]] = { # type: ignore[misc] 

594 "pipeline": GitLabCIXRefRole(innernodeclass=nodes.literal, warn_dangling=True), 

595 "input": GitLabCIXRefRole(innernodeclass=nodes.literal, warn_dangling=True), 

596 "variable": GitLabCIXRefRole(innernodeclass=nodes.literal, warn_dangling=True), 

597 } #: The roles, by name. 

598 

599 initial_data: ClassVar[dict[str, Any]] = { # type: ignore[misc] 

600 "objects": {}, 

601 } #: The domain's data: ``objects`` maps (type, name) to (document, anchor). 

602 

603 #: The configuration values the domain adds to :file:`conf.py`, as ``name: (default, rebuild, types)``. Each is 

604 #: registered with the domain's name as prefix, e.g. ``glci_project``. 

605 #: 

606 #: ``server`` 

607 #: The URL of the GitLab instance links point to, ``https://gitlab.com`` by default, or a self-managed instance's, 

608 #: as ``https://gitlab.example.com``. 

609 #: ``project`` 

610 #: The documented project, as ``group/project`` or ``group/subgroup/project``. 

611 #: ``repository_root`` 

612 #: The documented repository's root directory, relative to the Sphinx source directory, as ``..``. A local 

613 #: ``include`` and a child pipeline's file are read from it. 

614 #: ``pipeline_directory`` 

615 #: The directory holding the pipeline files, relative to the Sphinx source directory, as ``../templates``. A 

616 #: ``glci:pipeline`` without ``:file:`` reads its file from it; without it, from ``repository_root``. 

617 #: ``ref`` 

618 #: The ref - a branch or tag - of the documented project the documentation describes, as ``v1``, or ``None``. 

619 #: ``label_prefix`` 

620 #: The root of the ``:ref:`` labels the directives register besides their domain targets, as 

621 #: ``PIPELINE/Package/Input/package_name``, or ``None`` for none. 

622 configValues: ClassVar[dict[str, tuple[Any, str, Any]]] = { 

623 "server": ("https://gitlab.com", "env", str), 

624 "project": (None, "env", (str, type(None))), 

625 "repository_root": (None, "env", (str, type(None))), 

626 "pipeline_directory": (None, "env", (str, type(None))), 

627 "ref": (None, "env", (str, type(None))), 

628 "label_prefix": ("PIPELINE", "env", (str, type(None))), 

629 } 

630 

631 _files: dict[Path, PipelineFile] #: Pipeline files already read, by resolved path. 

632 _resolver: Nullable[IncludeResolver] #: Resolver reading included files and child pipelines, created when needed. 

633 

634 def __init__(self, env: BuildEnvironment) -> None: 

635 """ 

636 Initializes the domain. 

637 

638 :param env: The build environment. 

639 """ 

640 super().__init__(env) 

641 

642 self._files = {} 

643 self._resolver = None 

644 

645 @readonly 

646 def Objects(self) -> dict[tuple[str, str], tuple[str, str]]: 

647 """ 

648 Read-only property to return the documented objects. 

649 

650 :returns: A mapping of (object type, name) to (document, anchor). 

651 """ 

652 return self.data["objects"] 

653 

654 @readonly 

655 def RepositoryRoot(self) -> Nullable[Path]: 

656 """ 

657 Read-only property to return the documented repository's root directory. 

658 

659 :returns: ``glci_repository_root`` resolved against the Sphinx source directory, or ``None`` if it isn't set. 

660 """ 

661 if (directory := self.env.config.glci_repository_root) is None: 

662 return None 

663 

664 return (Path(self.env.srcdir) / directory).resolve() 

665 

666 @readonly 

667 def PipelineDirectory(self) -> Nullable[Path]: 

668 """ 

669 Read-only property to return the directory holding the pipeline files. 

670 

671 :returns: ``glci_pipeline_directory`` resolved against the Sphinx source directory, else :attr:`RepositoryRoot`. 

672 """ 

673 if (directory := self.env.config.glci_pipeline_directory) is None: 

674 return self.RepositoryRoot 

675 

676 return (Path(self.env.srcdir) / directory).resolve() 

677 

678 @readonly 

679 def Resolver(self) -> Nullable[IncludeResolver]: 

680 """ 

681 Read-only property to access the resolver reading local includes and child pipeline files (:attr:`_resolver`), 

682 created when first needed. 

683 

684 :returns: The resolver reading from :attr:`RepositoryRoot`, or ``None`` if ``glci_repository_root`` isn't set. 

685 """ 

686 if self._resolver is None and (root := self.RepositoryRoot) is not None: 

687 from pyTooling.GitLab.PipelineFile import IncludeResolver 

688 

689 self._resolver = IncludeResolver(root) 

690 

691 return self._resolver 

692 

693 def LoadPipelineFile(self, path: Path) -> PipelineFile: 

694 """ 

695 Read a pipeline file, once per build and process - a parallel build reads a file once in every process needing it. 

696 

697 The local files it includes are read by :attr:`Resolver`, so ``extends`` and ``!reference`` reach the jobs they 

698 define. 

699 

700 :param path: Path to the pipeline file. 

701 :returns: The pipeline file's model. 

702 :raises ValueError: If parameter 'path' is ``None``. 

703 :raises TypeError: If parameter 'path' is not of type :class:`~pathlib.Path`. 

704 :raises PipelineFileError: If the file doesn't exist or is not a well-formed configuration. 

705 """ 

706 if path is None: 

707 raise ValueError("Parameter 'path' is None.") 

708 elif not isinstance(path, Path): 

709 ex = TypeError("Parameter 'path' is not of type 'Path'.") 

710 ex.add_note(f"Got type '{getFullyQualifiedName(path)}'.") 

711 raise ex 

712 

713 resolved = path.resolve() 

714 if (known := self._files.get(resolved, None)) is not None: 

715 return known 

716 

717 from pyTooling.GitLab.PipelineFile import PipelineFile 

718 

719 self._files[resolved] = PipelineFile.FromFile(path, self.Resolver) 

720 return self._files[resolved] 

721 

722 def GetCurrentPipeline(self) -> Nullable[PipelineFile]: 

723 """ 

724 Return the model of the current document's pipeline file, as set by the last ``glci:pipeline``. 

725 

726 :returns: The pipeline file, or ``None`` if the document has no ``glci:pipeline``, or its file couldn't be read - 

727 which the ``glci:pipeline`` directive reported already. 

728 """ 

729 if (path := self.env.current_document.get("glci:pipeline-file", None)) is None: 729 ↛ 730line 729 didn't jump to line 730 because the condition on line 729 was never true

730 return None 

731 

732 return self.LoadPipelineFile(path) 

733 

734 def ResolvePipeline(self, name: str) -> Nullable[tuple[str, str]]: 

735 """ 

736 Return where a pipeline is documented. 

737 

738 :param name: The pipeline's name, as its ``glci:pipeline`` names it. 

739 :returns: The document and the anchor of its ``glci:pipeline``, or ``None`` if it isn't documented. 

740 :raises ValueError: If parameter 'name' is ``None``. 

741 :raises TypeError: If parameter 'name' is not of type :class:`str`. 

742 """ 

743 if name is None: 

744 raise ValueError("Parameter 'name' is None.") 

745 elif not isinstance(name, str): 

746 ex = TypeError("Parameter 'name' is not of type 'str'.") 

747 ex.add_note(f"Got type '{getFullyQualifiedName(name)}'.") 

748 raise ex 

749 

750 return self.data["objects"].get(("pipeline", name), None) 

751 

752 def NoteObject(self, objectType: str, name: str, nodeID: str, location: Nullable[Node] = None) -> None: 

753 """ 

754 Register a documented object. 

755 

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

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

758 :param nodeID: The anchor of the object's node. 

759 :param location: Optional, the node a duplicate is reported at. Default: ``None``. 

760 :raises ValueError: If parameter 'objectType' is ``None``. 

761 :raises TypeError: If parameter 'objectType' is not of type :class:`str`. 

762 :raises ValueError: If parameter 'name' is ``None``. 

763 :raises TypeError: If parameter 'name' is not of type :class:`str`. 

764 :raises ValueError: If parameter 'nodeID' is ``None``. 

765 :raises TypeError: If parameter 'nodeID' is not of type :class:`str`. 

766 :raises TypeError: If parameter 'location' is not of type :class:`~docutils.nodes.Node`. 

767 """ 

768 for parameterName, value in ( 

769 ("objectType", objectType), 

770 ("name", name), 

771 ("nodeID", nodeID) 

772 ): 

773 if value is None: 

774 raise ValueError(f"Parameter '{parameterName}' is None.") 

775 elif not isinstance(value, str): 

776 ex = TypeError(f"Parameter '{parameterName}' is not of type 'str'.") 

777 ex.add_note(f"Got type '{getFullyQualifiedName(value)}'.") 

778 raise ex 

779 

780 if location is not None and not isinstance(location, Node): 

781 ex = TypeError("Parameter 'location' is not of type 'Node'.") 

782 ex.add_note(f"Got type '{getFullyQualifiedName(location)}'.") 

783 raise ex 

784 

785 objects = self.data["objects"] 

786 if (known := objects.get((objectType, name), None)) is not None: 

787 _logger.warning( 

788 f"Duplicate description of glci:{objectType} '{name}', other instance in '{known[0]}'.", 

789 location=location, type=WARNING_TYPE, subtype="duplicate" 

790 ) 

791 

792 objects[(objectType, name)] = (self.env.docname, nodeID) 

793 

794 def clear_doc(self, docname: str) -> None: 

795 """ 

796 Remove the objects of a document, before it is read again. 

797 

798 :param docname: The document. 

799 """ 

800 objects = self.data["objects"] 

801 for key in [key for key, (document, _) in objects.items() if document == docname]: 

802 del objects[key] 

803 

804 def merge_domaindata(self, docnames: Iterable[str], otherdata: dict[str, Any]) -> None: 

805 """ 

806 Merge the objects a parallel reader collected for its documents. 

807 

808 :param docnames: The documents the other reader read. 

809 :param otherdata: The other reader's data. 

810 """ 

811 documents = set(docnames) 

812 objects = self.data["objects"] 

813 for key, (document, nodeID) in otherdata["objects"].items(): 

814 if document in documents: 

815 objects[key] = (document, nodeID) 

816 

817 def resolve_xref( 

818 self, 

819 env: BuildEnvironment, 

820 fromdocname: str, 

821 builder: Builder, 

822 typ: str, 

823 target: str, 

824 node: addnodes.pending_xref, 

825 contnode: Element 

826 ) -> Nullable[nodes.reference]: 

827 """ 

828 Resolve a reference by one of the domain's roles. 

829 

830 A parameter's name without a pipeline is looked up in the pipeline current where the role was written. 

831 

832 :param env: The build environment. 

833 :param fromdocname: The document containing the reference. 

834 :param builder: The builder. 

835 :param typ: The role's name, as ``input``. 

836 :param target: The target, as ``Package.package_name`` or ``package_name``. 

837 :param node: The pending reference. 

838 :param contnode: The node rendering the reference's title. 

839 :returns: The reference, or ``None`` if the target isn't documented. 

840 """ 

841 if typ != "pipeline" and "." not in target and (pipelineName := node.get("glci:pipeline", None)) is not None: 

842 target = f"{pipelineName}.{target}" 

843 

844 if (location := self.data["objects"].get((typ, target), None)) is None: 

845 return None 

846 

847 return make_refnode(builder, fromdocname, location[0], location[1], contnode, target) 

848 

849 def resolve_any_xref( 

850 self, 

851 env: BuildEnvironment, 

852 fromdocname: str, 

853 builder: Builder, 

854 target: str, 

855 node: addnodes.pending_xref, 

856 contnode: Element 

857 ) -> list[tuple[str, nodes.reference]]: 

858 """ 

859 Resolve a reference by the ``:any:`` role, trying every object type. 

860 

861 :param env: The build environment. 

862 :param fromdocname: The document containing the reference. 

863 :param builder: The builder. 

864 :param target: The target. 

865 :param node: The pending reference. 

866 :param contnode: The node rendering the reference's title. 

867 :returns: A pair of role and reference per object type the target resolves for. 

868 """ 

869 results = [] 

870 for objectType in self.object_types: 

871 if (reference := self.resolve_xref(env, fromdocname, builder, objectType, target, node, contnode)) is not None: 

872 results.append((f"glci:{objectType}", reference)) 

873 

874 return results 

875 

876 def get_objects(self) -> Iterable[tuple[str, str, str, str, str, int]]: 

877 """ 

878 Iterate the documented objects, for the search index and the inventory. 

879 

880 :returns: An iterator of (name, display name, type, document, anchor, priority). 

881 """ 

882 for (objectType, name), (document, nodeID) in self.data["objects"].items(): 

883 yield name, name, objectType, document, nodeID, 1 

884 

885 

886@export 

887def setup(sphinx: Sphinx) -> dict[str, Any]: 

888 """ 

889 Register the domain ``glci``, its directives and its configuration values with Sphinx. 

890 

891 The directives derive from :class:`~pyTooling.Sphinx.BaseDirective` and draw graphs with 

892 :mod:`sphinx.ext.graphviz`, so the extension :mod:`pyTooling.Sphinx` is set up first. 

893 

894 :param sphinx: The Sphinx application to register with. 

895 :returns: The extension's metadata. 

896 """ 

897 from pyTooling.GitLab import __version__ 

898 from pyTooling.GitLab.Sphinx.Graph import PipelineGraph, resolveLinks 

899 from pyTooling.GitLab.Sphinx.Reference import AutoInputs, Dependencies, Interface, ParameterTable, YAMLExcerpt, \ 

900 checkUndocumentedInputs 

901 

902 sphinx.setup_extension("pyTooling.Sphinx") 

903 

904 sphinx.add_domain(GitLabCIDomain) 

905 sphinx.add_directive_to_domain("glci", "pipeline-graph", PipelineGraph) 

906 sphinx.add_directive_to_domain("glci", "parameter-table", ParameterTable) 

907 sphinx.add_directive_to_domain("glci", "interface", Interface) 

908 sphinx.add_directive_to_domain("glci", "dependencies", Dependencies) 

909 sphinx.add_directive_to_domain("glci", "yaml", YAMLExcerpt) 

910 sphinx.add_directive_to_domain("glci", "autoinputs", AutoInputs) 

911 

912 for configName, (default, rebuild, types) in GitLabCIDomain.configValues.items(): 

913 sphinx.add_config_value(f"{GitLabCIDomain.name}_{configName}", default, rebuild, types) 

914 

915 sphinx.connect("doctree-read", checkUndocumentedInputs) 

916 sphinx.connect("doctree-resolved", resolveLinks) 

917 

918 return {"version": __version__, "parallel_read_safe": True, "parallel_write_safe": True}