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

257 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 directive drawing the pipeline a GitLab CI/CD pipeline file defines as a Graphviz graph. 

33 

34The jobs of a pipeline file and the dependencies between them - the ``needs``, and the stages for a job without - are 

35its pipeline. This directive draws it at build time from the pipeline file: 

36 

37.. code-block:: ReST 

38 

39 .. glci:pipeline-graph:: ../.gitlab-ci.yml 

40 :depth: 1 

41 

42A job is a node labelled with its name and stage. A trigger job starting a child pipeline, whose files are found 

43locally, is expanded into a cluster of the child pipeline's jobs, as many levels deep as ``:depth:`` says. In HTML, a 

44trigger job links to the page documenting its child pipeline, if the ``glci`` domain knows one. 

45 

46.. seealso:: 

47 

48 :mod:`pyTooling.GitLab.PipelineFile` 

49 |rarr| The model of a pipeline file the graph is drawn from. 

50 :mod:`pyTooling.CI` 

51 |rarr| The service-independent model of a pipeline, which a pipeline file is converted into. 

52""" 

53from __future__ import annotations 

54 

55from html import escape as html_escape 

56from pathlib import Path, PurePosixPath 

57from re import Match, compile as re_compile 

58from typing import TYPE_CHECKING, Any, Optional as Nullable 

59 

60from docutils import nodes 

61from docutils.parsers.rst import directives 

62from sphinx.application import Sphinx 

63from sphinx.ext.graphviz import align_spec, figure_wrapper, graphviz 

64 

65from pyTooling.CI import Base as CIBase, Matrix as CIMatrix, RuleOutcome, Workflow as CIWorkflow 

66from pyTooling.Common import getFullyQualifiedName 

67from pyTooling.Decorators import export, readonly 

68from pyTooling.Graph import Vertex 

69from pyTooling.MetaClasses import ExtendedType 

70from pyTooling.Sphinx import BaseDirective, SphinxExtensionError, strip, stripAndNormalize 

71 

72if TYPE_CHECKING: # pragma: no cover 

73 from pyTooling.GitLab.PipelineFile import IncludeResolver, Job, PipelineFile 

74 

75 

76__all__ = ["GRAPH_ATTRIBUTES", "CSS_CLASS", "LINK_MARKER"] 

77 

78GRAPH_ATTRIBUTES = ( 

79 "compound=true;", 

80 "newrank=true;", 

81 'fontname="sans-serif";', 

82 'fontsize="10";', 

83 "nodesep=0.25;", 

84 "ranksep=0.4;", 

85 'node [shape="box", style="rounded,filled", color="#5f6b7a", fillcolor="#fbe7d6", penwidth="1.0",', 

86 ' fontname="sans-serif", fontsize="10"];', 

87 'edge [color="#5f6b7a", arrowsize="0.7"];', 

88) 

89"""Attributes every pipeline graph is drawn with.""" 

90 

91CSS_CLASS = "glci-pipeline-graph" 

92"""CSS class of a pipeline graph's ``graphviz`` node, which is also how :func:`resolveLinks` finds it.""" 

93 

94LINK_MARKER = re_compile(r"(?P<space>\s*)/\*glci-link:(?P<name>[^*]*)\*/") 

95""" 

96A DOT comment, and the whitespace before it, standing where a trigger job's link belongs, until :func:`resolveLinks` 

97replaces it by the link or removes it. 

98""" 

99 

100 

101@export 

102class PipelineDotGraph(metaclass=ExtendedType, slots=True): 

103 """ 

104 The pipeline of a pipeline file in the DOT language: its jobs as nodes, their dependencies as edges. 

105 

106 The pipeline file is converted by :meth:`PipelineFile.ToPipeline 

107 <pyTooling.GitLab.PipelineFile.PipelineFile.ToPipeline>` into a :mod:`pyTooling.CI` model, and that by 

108 :meth:`~pyTooling.CI.Workflow.ToGraph` into a :class:`~pyTooling.Graph.Graph`, which is drawn: a vertex is a node, an 

109 edge an edge, and a trigger job or a parallel job with a :class:`~pyTooling.Graph.Subgraph` a cluster of the vertices 

110 it links to. 

111 

112 The kind of an element is its node's shape and style: 

113 

114 * a job running a script is a box with square corners, labelled with its name and stage; 

115 * a trigger job starting a child pipeline is a rounded box, labelled with the child pipeline's files; one starting 

116 another project's pipeline is a white rounded box, labelled with the project - it is never expanded; 

117 * a job whose rules have conditions - ``rules:if`` - is dashed, and its tooltip lists them, one per rule; a manual 

118 job is dashed too, and labelled *manual*; 

119 * a job with ``parallel`` is a cluster of its instances, labelled with the matrix' dimensions or the count of 

120 instances. 

121 

122 A trigger job whose child pipeline :class:`~pyTooling.GitLab.PipelineFile.IncludeResolver` reads is drawn as a 

123 cluster of the child pipeline's jobs instead, until the depth is used up. An edge to or from a job drawn as a cluster 

124 ends at the cluster's border. 

125 

126 The graph's edges read *needs*; an arrow is drawn the other way round, from the needed job to the job needing it, 

127 in the direction the pipeline runs. The graph is drawn in file order, so the same file is always drawn as the same 

128 DOT. 

129 """ 

130 

131 _link: bool #: Whether a trigger job starting a child pipeline is marked for a link. 

132 _statements: list[str] #: The statements written so far, one per line, already indented. 

133 _jobs: list[Job] #: The jobs drawn, each once, in the order they were drawn. 

134 _files: list[PipelineFile] #: The pipeline files drawn, each once, the drawn file first. 

135 

136 def __init__( 

137 self, 

138 pipelineFile: PipelineFile, 

139 resolver: Nullable[IncludeResolver] = None, 

140 direction: str = "LR", 

141 depth: int = 0, 

142 reduce: bool = True, 

143 link: bool = True 

144 ) -> None: 

145 """ 

146 Initializes the graph by drawing a pipeline file. 

147 

148 :param pipelineFile: The pipeline file to draw. 

149 :param resolver: Optional, the resolver reading the files of the child pipelines. Without it, no child 

150 pipeline is expanded. Default: ``None``. 

151 :param direction: Optional, direction the pipeline flows in: ``LR`` (left to right) or ``TB`` (top to 

152 bottom). Default: ``LR``. 

153 :param depth: Optional, levels of child pipelines expanded into clusters. Default: ``0``. 

154 :param reduce: Optional, drop an edge a longer path implies. Default: ``True``. 

155 :param link: Optional, mark a trigger job starting a child pipeline for :func:`resolveLinks`. 

156 Default: ``True``. 

157 :raises ValueError: If parameter 'pipelineFile' is None. 

158 :raises TypeError: If parameter 'pipelineFile' is not of type 

159 :class:`~pyTooling.GitLab.PipelineFile.PipelineFile`. 

160 :raises TypeError: If parameter 'resolver' is not of type 

161 :class:`~pyTooling.GitLab.PipelineFile.IncludeResolver`. 

162 :raises ValueError: If parameter 'direction' is None. 

163 :raises TypeError: If parameter 'direction' is not of type :class:`str`. 

164 :raises ValueError: If parameter 'direction' is neither ``LR`` nor ``TB``. 

165 :raises ValueError: If parameter 'depth' is None. 

166 :raises TypeError: If parameter 'depth' is not of type :class:`int`. 

167 :raises ValueError: If parameter 'depth' is negative. 

168 :raises ValueError: If parameter 'reduce' is None. 

169 :raises TypeError: If parameter 'reduce' is not of type :class:`bool`. 

170 :raises ValueError: If parameter 'link' is None. 

171 :raises TypeError: If parameter 'link' is not of type :class:`bool`. 

172 :raises PipelineFileError: If a child pipeline's file to expand is not a well-formed configuration. 

173 """ 

174 from pyTooling.GitLab.PipelineFile import IncludeResolver, PipelineFile 

175 

176 if pipelineFile is None: 

177 raise ValueError("Parameter 'pipelineFile' is None.") 

178 elif not isinstance(pipelineFile, PipelineFile): 

179 ex = TypeError("Parameter 'pipelineFile' is not of type 'PipelineFile'.") 

180 ex.add_note(f"Got type '{getFullyQualifiedName(pipelineFile)}'.") 

181 raise ex 

182 

183 if resolver is not None and not isinstance(resolver, IncludeResolver): 

184 ex = TypeError("Parameter 'resolver' is not of type 'IncludeResolver'.") 

185 ex.add_note(f"Got type '{getFullyQualifiedName(resolver)}'.") 

186 raise ex 

187 

188 if direction is None: 

189 raise ValueError("Parameter 'direction' is None.") 

190 elif not isinstance(direction, str): 

191 ex = TypeError("Parameter 'direction' is not of type 'str'.") 

192 ex.add_note(f"Got type '{getFullyQualifiedName(direction)}'.") 

193 raise ex 

194 elif direction not in ("LR", "TB"): 

195 ex = ValueError("Parameter 'direction' is neither 'LR' nor 'TB'.") 

196 ex.add_note(f"Got value '{direction}'.") 

197 raise ex 

198 

199 if depth is None: 

200 raise ValueError("Parameter 'depth' is None.") 

201 elif not isinstance(depth, int) or isinstance(depth, bool): 

202 ex = TypeError("Parameter 'depth' is not of type 'int'.") 

203 ex.add_note(f"Got type '{getFullyQualifiedName(depth)}'.") 

204 raise ex 

205 elif depth < 0: 

206 ex = ValueError("Parameter 'depth' is negative.") 

207 ex.add_note(f"Got value '{depth}'.") 

208 raise ex 

209 

210 for parameterName, value in (("reduce", reduce), ("link", link)): 

211 if value is None: 

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

213 elif not isinstance(value, bool): 

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

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

216 raise ex 

217 

218 self._link = link 

219 self._statements = [f"\trankdir={direction};", *(f"\t{attribute}" for attribute in GRAPH_ATTRIBUTES), ""] 

220 self._jobs = [] 

221 self._files = [pipelineFile] 

222 

223 graph = pipelineFile.ToPipeline(resolver, depth).ToGraph(reduce=reduce) 

224 self._DrawVertices(list(graph.IterateVertices()), "", "\t") 

225 

226 @readonly 

227 def Jobs(self) -> list[Job]: 

228 """ 

229 Read-only property to access the jobs drawn (:attr:`_jobs`). 

230 

231 A child pipeline expanded twice is drawn twice, but its jobs are listed once. 

232 

233 :returns: The jobs of every pipeline file drawn, in the order they were drawn. 

234 """ 

235 return self._jobs 

236 

237 @readonly 

238 def Files(self) -> list[PipelineFile]: 

239 """ 

240 Read-only property to access the pipeline files drawn (:attr:`_files`). 

241 

242 :returns: The drawn pipeline file, followed by every child pipeline's file expanded into a cluster, each once. 

243 """ 

244 return self._files 

245 

246 @staticmethod 

247 def _Quote(text: str) -> str: 

248 """ 

249 Quote a text as a DOT string, keeping its line breaks as escape sequences. 

250 

251 :param text: The text to quote. 

252 :returns: The text in double quotes. 

253 """ 

254 text = text.replace("\\", "\\\\").replace('"', '\\"').replace("\n", "\\n") 

255 

256 return f'"{text}"' 

257 

258 @staticmethod 

259 def _Label(title: str, lines: list[str]) -> str: 

260 """ 

261 Render an HTML-like label: a title and, below it, lines in a smaller font. 

262 

263 :param title: The title, unescaped. 

264 :param lines: The lines below the title, unescaped. 

265 :returns: The label in angle brackets, as DOT writes an HTML-like label. 

266 """ 

267 label = html_escape(title, quote=False) 

268 for line in lines: 

269 label += f'<br/><font point-size="8" color="#3d4652">{html_escape(line, quote=False)}</font>' 

270 

271 return f"<{label}>" 

272 

273 @staticmethod 

274 def _Describe(element: CIBase) -> tuple[list[str], list[str], str]: 

275 """ 

276 Describe an element of the pipeline: the lines of its label, the parts of its style, and its tooltip. 

277 

278 :param element: The job, matrix or trigger job to describe. 

279 :returns: The label's lines below the element's name, the style's parts, and the tooltip - the pipeline 

280 started and the rules' conditions, one per line, or an empty string. 

281 """ 

282 

283 job = element.Definition 

284 lines = [] if isinstance(element.Parent, CIMatrix) else [f"stage: {job.Stage}"] 

285 style = [] 

286 tooltip = [] 

287 

288 if (trigger := job.Trigger) is not None: 

289 if trigger.Project is not None: 

290 lines.append(f"project: {trigger.Project}") 

291 tooltip.append(f"trigger: {trigger.Project}") 

292 else: 

293 locations = [include.Location for include in trigger.Includes] 

294 lines.extend(locations) 

295 tooltip.append(f"trigger: {', '.join(locations)}") 

296 

297 if isinstance(element, CIMatrix) and (parallel := job.Parallel) is not None: 

298 if parallel.IsMatrix: 

299 dimensions = dict.fromkeys(name for entry in parallel.Matrix for name in entry) 

300 lines.append(f"matrix: {', '.join(dimensions)}") 

301 else: 

302 lines.append(f"parallel: {parallel.Count}") 

303 

304 if job.When is RuleOutcome.Manual: 

305 lines.append("manual") 

306 style.append("dashed") 

307 

308 conditions = [rule.Condition for rule in element.Rules if rule.Condition is not None] 

309 if len(conditions) > 0: 

310 if "dashed" not in style: 310 ↛ 313line 310 didn't jump to line 313 because the condition on line 310 was always true

311 style.append("dashed") 

312 

313 tooltip.extend(f"if: {condition}" for condition in conditions) 

314 

315 return lines, style, "\n".join(tooltip) 

316 

317 def _DrawNode(self, element: CIBase, identifier: str, indent: str) -> None: 

318 """ 

319 Draw a job, a matrix or a trigger job that isn't expanded as a node. 

320 

321 :param element: The element to draw. 

322 :param identifier: Identifier of the node. 

323 :param indent: Indentation of the node's statement. 

324 """ 

325 lines, style, tooltip = self._Describe(element) 

326 

327 if (trigger := element.Definition.Trigger) is None: 

328 attributes = {"style": ",".join(("filled", *style)), "fillcolor": "#f2f2f2"} 

329 elif trigger.Project is None: 

330 attributes = {"style": ",".join(("rounded", "filled", *style))} 

331 else: 

332 attributes = {"style": ",".join(("rounded", "filled", *style)), "fillcolor": "#ffffff"} 

333 

334 if isinstance(element, CIMatrix): 334 ↛ 335line 334 didn't jump to line 335 because the condition on line 334 was never true

335 attributes["peripheries"] = "2" 

336 

337 statement = f"{indent}{self._Quote(identifier)} [label={self._Label(str(element), lines)}" 

338 for name, value in attributes.items(): 

339 statement += f", {name}={self._Quote(value)}" 

340 

341 if tooltip != "": 

342 statement += f", tooltip={self._Quote(tooltip)}" 

343 

344 if self._link and (name := self._ChildPipelineName(element)) is not None: 

345 statement += f" /*glci-link:{name}*/" 

346 

347 self._statements.append(f"{statement}];") 

348 

349 @staticmethod 

350 def _ChildPipelineName(element: CIBase) -> Nullable[str]: 

351 """ 

352 Return the name a trigger job's child pipeline is documented by: the stem of its first local file. 

353 

354 :param element: The element. 

355 :returns: The stem, as ``child`` for ``/ci/child.yml``, or ``None`` if the element starts no child pipeline 

356 from a local file. 

357 """ 

358 from pyTooling.GitLab.PipelineFile import IncludeKind 

359 

360 if (trigger := element.Definition.Trigger) is None or trigger.Project is not None: 

361 return None 

362 

363 for include in trigger.Includes: 363 ↛ 367line 363 didn't jump to line 367 because the loop on line 363 didn't complete

364 if include.Kind is IncludeKind.Local: 364 ↛ 363line 364 didn't jump to line 363 because the condition on line 364 was always true

365 return PurePosixPath(include.Location).stem 

366 

367 return None 

368 

369 def _OpenCluster(self, element: CIBase, cluster: str, indent: str) -> None: 

370 """ 

371 Open a cluster drawing a trigger job or a matrix: write its ``subgraph`` statement and its attributes. 

372 

373 :param element: The trigger job or the matrix. 

374 :param cluster: Identifier of the cluster. 

375 :param indent: Indentation of the cluster's statement. 

376 """ 

377 lines, style, tooltip = self._Describe(element) 

378 self._statements.append(f"{indent}subgraph {self._Quote(cluster)} {{") 

379 self._statements.append(f"{indent}\tlabel={self._Label(str(element), lines)};") 

380 self._statements.append(f'{indent}\tlabeljust="l";') 

381 self._statements.append(f"{indent}\tstyle={self._Quote(','.join(('rounded', 'filled', *style)))};") 

382 self._statements.append(f'{indent}\tcolor="#8a9bb2";') 

383 self._statements.append(f'{indent}\tfillcolor="#fdf6f0";') 

384 if tooltip != "": 

385 self._statements.append(f"{indent}\ttooltip={self._Quote(tooltip)};") 

386 

387 def _DrawVertices(self, vertices: list[Vertex], prefix: str, indent: str) -> tuple[str, str]: 

388 """ 

389 Draw the vertices of one level of the graph - the graph itself, or the subgraph of a trigger job or of a matrix - 

390 and their edges. 

391 

392 An edge of the graph goes from the element needing to the element it needs; its arrow is drawn the other way round. 

393 

394 :param vertices: The vertices, in file order. 

395 :param prefix: Prefix of the identifiers of their nodes: the path of the jobs containing them. 

396 :param indent: Indentation of their statements. 

397 :returns: Identifiers of the node an arrow into the level ends at - the first vertex needing nothing - and of 

398 the node an arrow out of it starts at - the last vertex nothing needs. 

399 """ 

400 # per vertex: the node an arrow into it ends at, the node an arrow out of it starts at, and its cluster 

401 anchors: dict[Vertex, tuple[str, str, Nullable[str]]] = {} 

402 for vertex in vertices: 

403 element = vertex.Value 

404 if element.Definition not in self._jobs: 

405 self._jobs.append(element.Definition) 

406 

407 identifier = f"{prefix}{element}" 

408 if not isinstance(element, (CIWorkflow, CIMatrix)) or vertex.OutboundLinkCount == 0: 

409 self._DrawNode(element, identifier, indent) 

410 anchors[vertex] = (identifier, identifier, None) 

411 continue 

412 

413 cluster = f"cluster_{identifier}" 

414 self._OpenCluster(element, cluster, indent) 

415 if isinstance(element, CIWorkflow): 

416 self._files.extend(childFile for childFile in element.ChildFiles if childFile not in self._files) 

417 if self._link and (name := self._ChildPipelineName(element)) is not None: 417 ↛ 420line 417 didn't jump to line 420 because the condition on line 417 was always true

418 self._statements.append(f"{indent}\t/*glci-link:{name}*/") 

419 

420 entryNode, exitNode = self._DrawVertices( 

421 [link.Destination for link in vertex.OutboundLinks], f"{identifier}/", f"{indent}\t" 

422 ) 

423 self._statements.append(f"{indent}}}") 

424 anchors[vertex] = (entryNode, exitNode, cluster) 

425 

426 # the vertices needing nothing start together: in the first rank of the graph, or side by side in their cluster 

427 roots = [self._Quote(anchors[vertex][0]) for vertex in vertices if vertex.OutboundEdgeCount == 0] 

428 if prefix == "": 

429 self._statements.append(f"{indent}{{rank=min; {'; '.join(roots)};}}") 

430 elif len(roots) > 1: 

431 self._statements.append(f"{indent}{{rank=same; {'; '.join(roots)};}}") 

432 

433 for vertex in vertices: 

434 for edge in vertex.OutboundEdges: 

435 _, tail, tailCluster = anchors[edge.Destination] 

436 head, _, headCluster = anchors[vertex] 

437 

438 attributes = [] 

439 if tailCluster is not None: 439 ↛ 440line 439 didn't jump to line 440 because the condition on line 439 was never true

440 attributes.append(f"ltail={self._Quote(tailCluster)}") 

441 

442 if headCluster is not None: 

443 attributes.append(f"lhead={self._Quote(headCluster)}") 

444 

445 statement = f"{indent}{self._Quote(tail)} -> {self._Quote(head)}" 

446 if len(attributes) > 0: 

447 statement += f" [{', '.join(attributes)}]" 

448 

449 self._statements.append(f"{statement};") 

450 

451 first = next(vertex for vertex in vertices if vertex.OutboundEdgeCount == 0) 

452 last = [vertex for vertex in vertices if vertex.InboundEdgeCount == 0][-1] 

453 

454 return anchors[first][0], anchors[last][1] 

455 

456 def __str__(self) -> str: 

457 """ 

458 Render the graph. 

459 

460 :returns: The graph in the DOT language. 

461 """ 

462 statements = "\n".join(self._statements) 

463 

464 return f"digraph pipeline {{\n{statements}\n}}" 

465 

466 

467@export 

468class PipelineGraph(BaseDirective): 

469 """ 

470 The ``glci:pipeline-graph`` directive: the pipeline a pipeline file defines, drawn from the file. 

471 

472 One argument, the path of the pipeline file relative to the document using the directive. 

473 

474 A trigger job's child pipeline is read from ``glci_repository_root`` - relative to the source directory, and by 

475 default the directory of the drawn pipeline file - and expanded, while ``:depth:`` allows. The files are read by the 

476 resolver of the ``glci`` domain, which reads every file once per build; without ``glci_repository_root``, by a 

477 resolver of its own. 

478 """ 

479 

480 directiveName: str = "glci:pipeline-graph" #: Name the directive is invoked by. 

481 

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

483 required_arguments = 1 #: Number of required directive arguments: the pipeline file's path. 

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

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

486 # docutils declares 'option_spec' on 'Directive' and 'BaseDirective' assigns it, so mypy calls every 

487 # spelling of this override a conflict with one of them 

488 #: Mapping of option names to validator functions. 

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

490 "align": align_spec, 

491 "alt": strip, 

492 "caption": strip, 

493 "depth": directives.nonnegative_int, 

494 "direction": strip, 

495 "link": stripAndNormalize, 

496 "name": strip, 

497 "reduce": stripAndNormalize, 

498 } 

499 

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

501 """ 

502 Read the pipeline file and hand its pipeline to :mod:`sphinx.ext.graphviz` for rendering. 

503 

504 Every pipeline file drawn becomes a dependency of the document. 

505 

506 :returns: A ``graphviz`` node, wrapped in a figure when a caption was given, or an error node when the options or 

507 the pipeline files are wrong. 

508 """ 

509 relativePath, absolutePath = self.env.relfn2path(self.arguments[0]) 

510 self.env.note_dependency(relativePath) 

511 path = Path(absolutePath) 

512 

513 from pyTooling.GitLab.PipelineFile import IncludeResolver, PipelineFileError 

514 

515 try: 

516 direction = self._ParseStringOption("direction", "LR", "(?i)(LR|TB)$").upper() 

517 reduce = self._ParseBooleanOption("reduce", True) 

518 link = self._ParseBooleanOption("link", True) 

519 except SphinxExtensionError as ex: 

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

521 

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

523 try: 

524 resolver = domain.Resolver if domain.Resolver is not None else IncludeResolver(path.parent) 

525 graph = PipelineDotGraph( 

526 domain.LoadPipelineFile(path), resolver, direction, self.options.get("depth", 0), reduce, link 

527 ) 

528 except (OSError, ValueError, PipelineFileError) as ex: 

529 message = f"{self.directiveName}: Couldn't draw '{self.arguments[0]}': {ex}" 

530 for note in getattr(ex, "__notes__", []): 

531 message += f" {note}" 

532 

533 return [self.state.document.reporter.error(message, line=self.lineno)] 

534 

535 for pipelineFile in graph.Files[1:]: 

536 self.env.note_dependency(str(pipelineFile.Path)) 

537 

538 node = graphviz() 

539 node["code"] = str(graph) 

540 node["options"] = {"docname": self.env.docname} 

541 node["alt"] = self.options.get("alt", f"Pipeline of {path.name}") 

542 node["classes"] = [CSS_CLASS] 

543 if "align" in self.options: 543 ↛ 544line 543 didn't jump to line 544 because the condition on line 543 was never true

544 node["align"] = self.options["align"] 

545 

546 if (caption := self.options.get("caption", None)) is not None: 546 ↛ 547line 546 didn't jump to line 547 because the condition on line 546 was never true

547 figure = figure_wrapper(self, node, caption) 

548 self.add_name(figure) 

549 return [figure] 

550 

551 self.add_name(node) 

552 return [node] 

553 

554 

555@export 

556def resolveLinks(sphinx: Sphinx, doctree: nodes.document, docname: str) -> None: 

557 """ 

558 Call-back for Sphinx' ``doctree-resolved`` event, linking the trigger jobs of a pipeline graph to their child 

559 pipelines. 

560 

561 A trigger job starting a child pipeline from a local file links to the page documenting that pipeline, as the 

562 ``glci`` domain resolves the file's stem with ``ResolvePipeline``. Without a page for the pipeline, or in a format 

563 other than HTML, the job has no link. 

564 

565 :param sphinx: The Sphinx application. 

566 :param doctree: The resolved document. 

567 :param docname: Name of the document. 

568 """ 

569 if sphinx.builder.format != "html": 

570 for node in doctree.findall(graphviz): 

571 if CSS_CLASS in node["classes"]: 571 ↛ 570line 571 didn't jump to line 570 because the condition on line 571 was always true

572 node["code"] = LINK_MARKER.sub("", node["code"]) 

573 

574 return 

575 

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

577 

578 def link(match: Match[str]) -> str: 

579 """ 

580 Nested function returning the link attributes replacing a marker, or nothing. 

581 

582 :param match: The marker. 

583 :returns: The whitespace before the marker and the attributes ``URL`` and ``target``, or an empty string when 

584 there is nothing to link to. 

585 """ 

586 if (target := domain.ResolvePipeline(match["name"])) is None: 

587 return "" 

588 

589 targetDocname, anchor = target 

590 if (uri := sphinx.builder.get_relative_uri(docname, targetDocname)) == "": 590 ↛ 591line 590 didn't jump to line 591 because the condition on line 590 was never true

591 uri = PurePosixPath(sphinx.builder.get_target_uri(targetDocname)).name 

592 

593 return f'{match["space"]}URL="{uri}#{anchor}" target="_top"' 

594 

595 for node in doctree.findall(graphviz): 

596 if CSS_CLASS in node["classes"]: 596 ↛ 595line 596 didn't jump to line 595 because the condition on line 596 was always true

597 node["code"] = LINK_MARKER.sub(link, node["code"])