Coverage for pyTooling/GitLab/PipelineFile.py: 98%

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

31A data model of a GitLab CI/CD configuration file. 

32 

33A configuration file - the project's :file:`.gitlab-ci.yml`, a file it includes, or the file of a child pipeline - is 

34read once into objects: 

35 

36.. tree:: 

37 

38 - :class:`PipelineFile` | a configuration file, e.g. :file:`.gitlab-ci.yml` 

39 - :class:`Input` | an input of the header's ``spec:inputs`` 

40 - :class:`Workflow` | the ``workflow`` key 

41 - :class:`Rule` | a rule deciding whether a pipeline is created 

42 - :class:`Include` | an entry of ``include`` 

43 - :class:`Rule` | a rule deciding whether the file is included 

44 - :class:`Default` | the ``default`` key 

45 - :class:`Variable` | a default variable, declared in the top-level ``variables`` 

46 - :class:`Job` | a job or a hidden job, in file order 

47 - :class:`Need` | an entry of the job's ``needs`` 

48 - :class:`Parallel` | the matrix instances needed 

49 - :class:`Rule` | a rule deciding whether the job is added to a pipeline 

50 - :class:`Variable` | a variable of the job 

51 - :class:`Input` | an input of the job 

52 - :class:`Parallel` | the job's ``parallel``: how often it runs, or its matrix 

53 - :class:`Trigger` | the child pipeline or other project's pipeline the job starts 

54 - :class:`Include` | a file of the child pipeline 

55 

56Every element knows its parent, the file it belongs to and the line it starts at, so a consumer can name the place a 

57finding comes from, as ``.gitlab-ci.yml:42``. 

58 

59:class:`IncludeResolver` reads the local files a file includes, or a trigger job's child pipeline runs. 

60 

61The model is independent of :mod:`pyTooling.GitLab`, which models a pipeline *run* as the REST API reports it. 

62:meth:`PipelineFile.ToPipeline` builds the pipeline a file defines as a :mod:`pyTooling.CI` model, whose elements link 

63back to the jobs they were built from. 

64""" 

65from __future__ import annotations 

66 

67from enum import Enum 

68from itertools import product 

69from pathlib import Path 

70from typing import Any, ClassVar, Generic, Hashable, Iterable, Iterator, Mapping, \ 

71 Optional as Nullable, Self, Sequence, TypeVar, Union 

72 

73from pyTooling.CI import DependencyMixin, Job as CIJob, JobGroup, Matrix as CIMatrix, \ 

74 MatrixJob as CIMatrixJob, MatrixWorkflow as CIMatrixWorkflow, \ 

75 Pipeline as CIPipeline, Rule as CIRule, RuleOutcome, Workflow as CIWorkflow 

76 

77from pyTooling.Common import getFullyQualifiedName, StringEnum 

78from pyTooling.Decorators import export, readonly 

79from pyTooling.MetaClasses import ExtendedType, abstractclass 

80 

81from pyTooling.GitLab import GitLabError 

82 

83from ruamel.yaml import YAML, YAMLError 

84from ruamel.yaml.comments import CommentedMap, CommentedSeq 

85from ruamel.yaml.scalarbool import ScalarBoolean 

86from ruamel.yaml.scalarfloat import ScalarFloat 

87from ruamel.yaml.scalarint import ScalarInt 

88from ruamel.yaml.scalarstring import ScalarString 

89 

90 

91__all__ = ["ValueT", "RESERVED_KEYS", "DEFAULT_STAGES", "MAX_EXTENDS_DEPTH", "MAX_REFERENCE_DEPTH"] 

92 

93ValueT = Union[str, bool, int, float, None, list["ValueT"], dict[str, "ValueT"]] 

94"""A value read from a configuration file, converted to plain Python types.""" 

95 

96ParentType = TypeVar("ParentType", bound="Base") 

97"""A type variable for the type of an element's parent.""" 

98 

99ParentTypes = Nullable[Union[type, tuple[type, ...]]] 

100"""The type of :attr:`Base._PARENT_TYPE`: ``None``, a class, or a tuple of classes.""" 

101 

102DefinitionType = TypeVar("DefinitionType", bound="Base") 

103"""A type variable for the type of the file's element an element of :mod:`pyTooling.CI` is built from.""" 

104 

105RESERVED_KEYS = frozenset(( 

106 "default", "include", "stages", "variables", "workflow", "image", "services", "cache", "before_script", "after_script" 

107)) 

108"""Top-level keys of a configuration file, which declare no job.""" 

109 

110DEFAULT_STAGES = ("build", "test", "deploy") 

111"""Stages of a pipeline, whose configuration declares no ``stages``, between ``.pre`` and ``.post``.""" 

112 

113MAX_EXTENDS_DEPTH = 11 

114"""How many levels of ``extends`` GitLab resolves.""" 

115 

116MAX_REFERENCE_DEPTH = 10 

117"""How many levels of ``!reference`` tags GitLab resolves.""" 

118 

119 

120@export 

121class PipelineFileError(GitLabError): 

122 """ 

123 Base-exception of all exceptions raised by :mod:`pyTooling.GitLab.PipelineFile`. 

124 

125 The exception is raised for a file that is not a well-formed configuration. It carries the file and the line the 

126 problem was found at in :attr:`Path` and :attr:`Line`, and names both in a note. 

127 """ 

128 

129 _path: Nullable[Path] #: Path to the configuration file. 

130 _line: Nullable[int] #: Line in the configuration file, starting at 1. 

131 

132 def __init__(self, message: str, path: Nullable[Path] = None, line: Nullable[int] = None) -> None: 

133 """ 

134 Initializes a configuration error and names the place it was found at in a note. 

135 

136 :param message: The exception's message. 

137 :param path: Optional, path to the configuration file. Default: ``None``. 

138 :param line: Optional, line in the configuration file, starting at 1. Default: ``None``. 

139 """ 

140 super().__init__(message) 

141 

142 self._path = path 

143 self._line = line 

144 

145 if path is not None: 145 ↛ exitline 145 didn't return from function '__init__' because the condition on line 145 was always true

146 self.add_note(f"In '{path}'." if line is None else f"In '{path}:{line}'.") 

147 

148 @readonly 

149 def Path(self) -> Nullable[Path]: 

150 """ 

151 Read-only property to access the path to the configuration file (:attr:`_path`). 

152 

153 :returns: The path, or ``None`` if the problem isn't tied to a file. 

154 """ 

155 return self._path 

156 

157 @readonly 

158 def Line(self) -> Nullable[int]: 

159 """ 

160 Read-only property to access the line the problem was found at (:attr:`_line`). 

161 

162 :returns: The line, starting at 1, or ``None`` if the problem isn't tied to a line. 

163 """ 

164 return self._line 

165 

166 

167@export 

168class IncludeKind(StringEnum): 

169 """Where an included file comes from, as the key of an ``include`` entry names it.""" 

170 

171 Local = "local" #: A file of the same repository. 

172 Project = "project" #: Files of another project. 

173 Remote = "remote" #: A file at a URL. 

174 Template = "template" #: A CI/CD template shipped with GitLab. 

175 Component = "component" #: A CI/CD component. 

176 Artifact = "artifact" #: A file a job of the pipeline created, for a dynamic child pipeline. 

177 

178 

179@export 

180class InputType(StringEnum): 

181 """The type of an input, as ``type`` names it.""" 

182 

183 String = "string" #: A string. 

184 Number = "number" #: A number. 

185 Boolean = "boolean" #: ``true`` or ``false``. 

186 Array = "array" #: A list of values. 

187 

188 

189@export 

190class TriggerStrategy(StringEnum): 

191 """How a trigger job's status follows the pipeline it starts, as ``trigger.strategy`` names it.""" 

192 

193 Depend = "depend" #: The trigger job waits for the pipeline, and reports failed, success or running. 

194 Mirror = "mirror" #: The trigger job waits for the pipeline, and mirrors its status exactly. 

195 

196 

197@export 

198class NeedKind(Enum): 

199 """What an entry of ``needs`` refers to.""" 

200 

201 Job = 1 #: A job of the same pipeline. 

202 PipelineJob = 2 #: A job of another pipeline in the same parent-child hierarchy. 

203 ProjectJob = 3 #: A job of another project's pipeline, whose artifacts are downloaded. 

204 PipelineStatus = 4 #: The status of another project's pipeline, which the job mirrors. 

205 

206 

207@export 

208@abstractclass 

209class Base(Generic[ParentType], metaclass=ExtendedType, slots=True): 

210 """ 

211 Common behaviour of every element of a configuration file. 

212 

213 Every element knows the element containing it, the configuration file it belongs to, and the line it starts at. 

214 """ 

215 

216 _PARENT_TYPE: ClassVar[ParentTypes] = None #: Type a parent must have, or ``None`` when the element has no parent. 

217 

218 _parent: Nullable[ParentType] #: Reference to the containing element. 

219 _pipelineFile: Nullable[PipelineFile] #: Reference to the configuration file this element belongs to. 

220 _line: int #: Line the element starts at in its file, starting at 1. 

221 

222 def __init__(self, line: int, *, parent: Nullable[ParentType] = None) -> None: 

223 """ 

224 Initializes an element of a configuration file. 

225 

226 :param line: Line the element starts at in the configuration file, starting at 1. 

227 :param parent: Optional, reference to the containing element. Default: ``None``. 

228 :raises ValueError: If parameter 'line' is ``None``. 

229 :raises TypeError: If parameter 'line' is not of type :class:`int`. 

230 :raises ValueError: If parameter 'line' is not positive. 

231 :raises TypeError: If parameter 'parent' is not of the type this class declares in :attr:`_PARENT_TYPE`. 

232 """ 

233 if line is None: 

234 raise ValueError("Parameter 'line' is None.") 

235 elif not isinstance(line, int) or isinstance(line, bool): 

236 ex = TypeError("Parameter 'line' is not of type 'int'.") 

237 ex.add_note(f"Got type '{getFullyQualifiedName(line)}'.") 

238 raise ex 

239 elif line < 1: 

240 ex = ValueError("Parameter 'line' is not positive.") 

241 ex.add_note(f"Got value '{line}'.") 

242 raise ex 

243 

244 if parent is not None and not isinstance(parent, self._PARENT_TYPE): 

245 parentTypes = self._PARENT_TYPE if isinstance(self._PARENT_TYPE, tuple) else (self._PARENT_TYPE, ) 

246 ex = TypeError(f"Parameter 'parent' is not of type {' or '.join(f'{t.__name__!r}' for t in parentTypes)}.") 

247 ex.add_note(f"Got type '{getFullyQualifiedName(parent)}'.") 

248 raise ex 

249 

250 self._parent = parent 

251 self._pipelineFile = None if parent is None else parent._pipelineFile 

252 self._line = line 

253 

254 @property 

255 def Parent(self) -> Nullable[ParentType]: 

256 """ 

257 Property to access the containing element (:attr:`_parent`). 

258 

259 Assigning a parent attaches an element constructed before it: the element takes the parent's configuration file, 

260 and so do the elements it contains. 

261 

262 :returns: The containing element, or ``None`` for a :class:`PipelineFile`. 

263 :raises ValueError: If ``None`` is assigned. 

264 :raises TypeError: If a parent is assigned to a :class:`PipelineFile`, which has no parent. 

265 :raises TypeError: If an assigned value is not of the type this class declares in :attr:`_PARENT_TYPE`. 

266 """ 

267 return self._parent 

268 

269 @Parent.setter 

270 def Parent(self, value: ParentType) -> None: 

271 if value is None: 

272 raise ValueError("Parameter 'value' is None.") 

273 elif not isinstance(value, self._PARENT_TYPE): 

274 parentTypes = self._PARENT_TYPE if isinstance(self._PARENT_TYPE, tuple) else (self._PARENT_TYPE, ) 

275 ex = TypeError(f"Parameter 'value' is not of type {' or '.join(f'{t.__name__!r}' for t in parentTypes)}.") 

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

277 raise ex 

278 

279 self._parent = value 

280 self._pipelineFile = value._pipelineFile 

281 

282 @readonly 

283 def PipelineFile(self) -> Nullable[PipelineFile]: 

284 """ 

285 Read-only property to access the configuration file this element belongs to (:attr:`_pipelineFile`). 

286 

287 :returns: The configuration file, or ``None`` for an element outside one. 

288 """ 

289 return self._pipelineFile 

290 

291 @readonly 

292 def Line(self) -> int: 

293 """ 

294 Read-only property to access the line the element starts at in its file (:attr:`_line`). 

295 

296 :returns: The line, starting at 1. 

297 """ 

298 return self._line 

299 

300 @readonly 

301 def Location(self) -> str: 

302 """ 

303 Read-only property to return the place the element is written at, for a message. 

304 

305 :returns: The file's name and the line, as ``.gitlab-ci.yml:42``, or ``line 42`` for an element outside a file. 

306 """ 

307 if self._pipelineFile is None: 

308 return f"line {self._line}" 

309 

310 return f"{self._pipelineFile._path.name}:{self._line}" 

311 

312 @staticmethod 

313 def _KeyLine(mapping: CommentedMap, key: Any) -> int: 

314 """ 

315 Return the line a key of a mapping is written at. 

316 

317 A key brought in by a YAML merge key (``<<: *anchor``) is written at the anchor; its line is the mapping's line. 

318 

319 :param mapping: The mapping read from the file. 

320 :param key: The key. 

321 :returns: The line, starting at 1. 

322 """ 

323 try: 

324 return mapping.lc.key(key)[0] + 1 

325 except KeyError: 

326 return mapping.lc.line + 1 

327 

328 @staticmethod 

329 def _ItemLine(sequence: CommentedSeq, index: int) -> int: 

330 """ 

331 Return the line an item of a sequence is written at. 

332 

333 :param sequence: The sequence read from the file. 

334 :param index: Position of the item, starting at 0. 

335 :returns: The line, starting at 1. 

336 """ 

337 return sequence.lc.item(index)[0] + 1 

338 

339 @staticmethod 

340 def _ToPython(value: Any) -> ValueT: 

341 """ 

342 Convert a value read by ``ruamel.yaml`` into plain Python types. 

343 

344 The round-trip loader returns its own types for mappings, lists, block scalars, anchored booleans, and numbers 

345 written in another notation than a plain decimal. They derive from the Python types, but keep what they were 

346 read with. Every other value is a Python type already. 

347 

348 :param value: The value read from the file. 

349 :returns: The value as :class:`dict`, :class:`list`, :class:`str`, :class:`bool`, :class:`int`, 

350 :class:`float` or ``None``. 

351 """ 

352 if isinstance(value, CommentedMap): 

353 return {str(key): Base._ToPython(item) for key, item in value.items()} 

354 elif isinstance(value, CommentedSeq): 

355 return [Base._ToPython(item) for item in value] 

356 elif isinstance(value, ScalarBoolean): 356 ↛ 357line 356 didn't jump to line 357 because the condition on line 356 was never true

357 return bool(value) 

358 elif isinstance(value, ScalarInt): 358 ↛ 359line 358 didn't jump to line 359 because the condition on line 358 was never true

359 return int(value) 

360 elif isinstance(value, ScalarFloat): 

361 return float(value) 

362 elif isinstance(value, ScalarString): 

363 return str(value) 

364 

365 return value 

366 

367 @staticmethod 

368 def _ToText(value: Any) -> str: 

369 """ 

370 Convert a scalar read from the file into the text GitLab uses, so ``true`` stays ``true`` and not ``True``. 

371 

372 :param value: The scalar. 

373 :returns: The text. 

374 """ 

375 value = Base._ToPython(value) 

376 if isinstance(value, bool): 

377 return "true" if value else "false" 

378 

379 return str(value) 

380 

381 

382@export 

383class PipelineFile(Base[None]): 

384 """ 

385 A GitLab CI/CD configuration file. 

386 

387 A top-level key names a job, unless it is a global keyword (:data:`RESERVED_KEYS`). A job whose name starts with a 

388 dot is a hidden job: GitLab doesn't run it, other jobs extend it. 

389 """ 

390 

391 _path: Path #: Path to the configuration file. 

392 _stages: Nullable[tuple[str, ...]] #: Stages, as the ``stages`` key declares them. 

393 _variables: dict[str, Variable] #: Default variables, by name, in file order. 

394 _jobs: dict[str, Job] #: Jobs, by name, in file order. 

395 _hiddenJobs: dict[str, Job] #: Hidden jobs, by name, in file order. 

396 _workflow: Nullable[Workflow] #: The ``workflow`` key. 

397 _includes: list[Include] #: Entries of ``include``, in file order. 

398 _default: Nullable[Default] #: The ``default`` key. 

399 _inputs: dict[str, Input] #: Inputs of the header's ``spec:inputs``, by name, in file order. 

400 _description: Nullable[str] #: Description of the header's ``spec:description``. 

401 

402 def __init__( 

403 self, 

404 path: Path, 

405 stages: Nullable[Iterable[str]] = None, 

406 variables: Nullable[Iterable[Variable]] = None, 

407 jobs: Nullable[Iterable[Job]] = None, 

408 workflow: Nullable[Workflow] = None, 

409 includes: Nullable[Iterable[Include]] = None, 

410 default: Nullable[Default] = None, 

411 inputs: Nullable[Iterable[Input]] = None, 

412 description: Nullable[str] = None 

413 ) -> None: 

414 """ 

415 Initializes a configuration file. 

416 

417 A variable, job, workflow, include, default or input is attached by passing it, or by constructing it with the 

418 configuration file as parent. Use :meth:`FromFile` to read a configuration file. 

419 

420 :param path: Path to the configuration file. 

421 :param stages: Optional, stages as the ``stages`` key declares them. Default: ``None``, for a file without a 

422 ``stages`` key. 

423 :param variables: Optional, default variables, which are attached to the file. Default: ``None``. 

424 :param jobs: Optional, jobs and hidden jobs, which are attached to the file. Default: ``None``. 

425 :param workflow: Optional, the ``workflow`` key, which is attached to the file. Default: ``None``. 

426 :param includes: Optional, entries of ``include``, which are attached to the file. Default: ``None``. 

427 :param default: Optional, the ``default`` key, which is attached to the file. Default: ``None``. 

428 :param inputs: Optional, inputs of the header's ``spec:inputs``, which are attached to the file. Default: 

429 ``None``. 

430 :param description: Optional, description of the header's ``spec:description``. Default: ``None``. 

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

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

433 :raises TypeError: If an element of parameter 'stages' is not of type :class:`str`. 

434 :raises TypeError: If an element of parameter 'variables' is not of type :class:`Variable`. 

435 :raises TypeError: If an element of parameter 'jobs' is not of type :class:`Job`. 

436 :raises TypeError: If parameter 'workflow' is not of type :class:`Workflow`. 

437 :raises TypeError: If an element of parameter 'includes' is not of type :class:`Include`. 

438 :raises TypeError: If parameter 'default' is not of type :class:`Default`. 

439 :raises TypeError: If an element of parameter 'inputs' is not of type :class:`Input`. 

440 :raises TypeError: If parameter 'description' is not of type :class:`str`. 

441 """ 

442 super().__init__(1) 

443 

444 if path is None: 

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

446 elif not isinstance(path, Path): 

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

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

449 raise ex 

450 

451 if description is not None and not isinstance(description, str): 

452 ex = TypeError("Parameter 'description' is not of type 'str'.") 

453 ex.add_note(f"Got type '{getFullyQualifiedName(description)}'.") 

454 raise ex 

455 

456 self._pipelineFile = self 

457 self._path = path 

458 self._stages = None 

459 self._variables = {} 

460 self._jobs = {} 

461 self._hiddenJobs = {} 

462 self._workflow = None 

463 self._includes = includeList = [] 

464 self._default = None 

465 self._inputs = {} 

466 self._description = description 

467 

468 if stages is not None: 

469 self._stages = tuple(stages) 

470 for stage in self._stages: 

471 if not isinstance(stage, str): 

472 ex = TypeError("An element of parameter 'stages' is not of type 'str'.") 

473 ex.add_note(f"Got type '{getFullyQualifiedName(stage)}'.") 

474 raise ex 

475 

476 if variables is not None: 

477 for variable in variables: 

478 if not isinstance(variable, Variable): 

479 ex = TypeError("An element of parameter 'variables' is not of type 'Variable'.") 

480 ex.add_note(f"Got type '{getFullyQualifiedName(variable)}'.") 

481 raise ex 

482 

483 self._variables[variable._name] = variable 

484 variable.Parent = self 

485 

486 if jobs is not None: 

487 for job in jobs: 

488 if not isinstance(job, Job): 

489 ex = TypeError("An element of parameter 'jobs' is not of type 'Job'.") 

490 ex.add_note(f"Got type '{getFullyQualifiedName(job)}'.") 

491 raise ex 

492 

493 (self._hiddenJobs if job.IsHidden else self._jobs)[job._name] = job 

494 job.Parent = self 

495 

496 if workflow is not None: 

497 if not isinstance(workflow, Workflow): 

498 ex = TypeError("Parameter 'workflow' is not of type 'Workflow'.") 

499 ex.add_note(f"Got type '{getFullyQualifiedName(workflow)}'.") 

500 raise ex 

501 

502 self._workflow = workflow 

503 workflow.Parent = self 

504 

505 if includes is not None: 

506 for include in includes: 

507 if not isinstance(include, Include): 

508 ex = TypeError("An element of parameter 'includes' is not of type 'Include'.") 

509 ex.add_note(f"Got type '{getFullyQualifiedName(include)}'.") 

510 raise ex 

511 

512 includeList.append(include) 

513 include.Parent = self 

514 

515 if default is not None: 

516 if not isinstance(default, Default): 

517 ex = TypeError("Parameter 'default' is not of type 'Default'.") 

518 ex.add_note(f"Got type '{getFullyQualifiedName(default)}'.") 

519 raise ex 

520 

521 self._default = default 

522 default.Parent = self 

523 

524 if inputs is not None: 

525 for parameter in inputs: 

526 if not isinstance(parameter, Input): 

527 ex = TypeError("An element of parameter 'inputs' is not of type 'Input'.") 

528 ex.add_note(f"Got type '{getFullyQualifiedName(parameter)}'.") 

529 raise ex 

530 

531 self._inputs[parameter._name] = parameter 

532 parameter.Parent = self 

533 

534 @Base.Parent.setter 

535 def Parent(self, value: None) -> None: 

536 ex = TypeError(f"A '{getFullyQualifiedName(self)}' has no parent.") 

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

538 raise ex 

539 

540 @readonly 

541 def Path(self) -> Path: 

542 """ 

543 Read-only property to access the path to the configuration file (:attr:`_path`). 

544 

545 :returns: The path. 

546 """ 

547 return self._path 

548 

549 @readonly 

550 def Inputs(self) -> dict[str, Input]: 

551 """ 

552 Read-only property to access the inputs of the header's ``spec:inputs`` (:attr:`_inputs`). 

553 

554 :returns: The inputs, by name, in file order. 

555 """ 

556 return self._inputs 

557 

558 @readonly 

559 def Description(self) -> Nullable[str]: 

560 """ 

561 Read-only property to access the description of the header's ``spec:description`` (:attr:`_description`). 

562 

563 :returns: The description, or ``None`` if the file gives none. 

564 """ 

565 return self._description 

566 

567 @readonly 

568 def DeclaredStages(self) -> Nullable[tuple[str, ...]]: 

569 """ 

570 Read-only property to access the stages as the ``stages`` key declares them (:attr:`_stages`). 

571 

572 :returns: The stages, in the order they run, or ``None`` if the file has no ``stages`` key. 

573 """ 

574 return self._stages 

575 

576 @readonly 

577 def Stages(self) -> tuple[str, ...]: 

578 """ 

579 Read-only property to return the stages of the pipeline, in the order they run. 

580 

581 The stages are those of :attr:`DeclaredStages`, or :data:`DEFAULT_STAGES` without a ``stages`` key, and always 

582 begin with ``.pre`` and end with ``.post``. 

583 

584 :returns: The stages. 

585 """ 

586 stages = DEFAULT_STAGES if self._stages is None else self._stages 

587 return (".pre", *(stage for stage in stages if stage not in (".pre", ".post")), ".post") 

588 

589 @readonly 

590 def Variables(self) -> dict[str, Variable]: 

591 """ 

592 Read-only property to access the default variables (:attr:`_variables`). 

593 

594 :returns: The variables, by name, in file order. 

595 """ 

596 return self._variables 

597 

598 @readonly 

599 def Jobs(self) -> dict[str, Job]: 

600 """ 

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

602 

603 :returns: The jobs, by name, in file order. 

604 """ 

605 return self._jobs 

606 

607 @readonly 

608 def HiddenJobs(self) -> dict[str, Job]: 

609 """ 

610 Read-only property to access the hidden jobs (:attr:`_hiddenJobs`). 

611 

612 :returns: The hidden jobs, by name, in file order. 

613 """ 

614 return self._hiddenJobs 

615 

616 @readonly 

617 def Workflow(self) -> Nullable[Workflow]: 

618 """ 

619 Read-only property to access the ``workflow`` key (:attr:`_workflow`). 

620 

621 :returns: The workflow, or ``None`` if the file has no ``workflow`` key. 

622 """ 

623 return self._workflow 

624 

625 @readonly 

626 def Includes(self) -> list[Include]: 

627 """ 

628 Read-only property to access the entries of ``include`` (:attr:`_includes`). 

629 

630 :returns: The entries, in file order. 

631 """ 

632 return self._includes 

633 

634 @readonly 

635 def Default(self) -> Nullable[Default]: 

636 """ 

637 Read-only property to access the ``default`` key (:attr:`_default`). 

638 

639 :returns: The default, or ``None`` if the file has neither a ``default`` key nor a global keyword it stands for. 

640 """ 

641 return self._default 

642 

643 @readonly 

644 def JobCount(self) -> int: 

645 """ 

646 Read-only property to return the number of jobs, hidden jobs not counted. 

647 

648 :returns: Number of jobs. 

649 """ 

650 return len(self._jobs) 

651 

652 def ContainsJob(self, name: str) -> bool: 

653 """ 

654 Check whether the file has a job of that name. 

655 

656 :param name: Name of the job, the key it is declared under. 

657 :returns: ``True``, if the file has a job of that name. A hidden job isn't a job. 

658 """ 

659 return name in self._jobs 

660 

661 def IterateJobs(self) -> Iterator[Job]: 

662 """ 

663 Iterate the jobs, hidden jobs not included. 

664 

665 :returns: An iterator over the jobs, in file order. 

666 """ 

667 return iter(self._jobs.values()) 

668 

669 def IterateHiddenJobs(self) -> Iterator[Job]: 

670 """ 

671 Iterate the hidden jobs. 

672 

673 :returns: An iterator over the hidden jobs, in file order. 

674 """ 

675 return iter(self._hiddenJobs.values()) 

676 

677 def __str__(self) -> str: 

678 """ 

679 Return the file's name. 

680 

681 :returns: Name of the configuration file. 

682 """ 

683 return self._path.name 

684 

685 def ToPipeline(self, resolver: Nullable[IncludeResolver] = None, depth: Nullable[int] = None) -> DefinedPipeline: 

686 """ 

687 Build the service-independent model of the pipeline this file defines. 

688 

689 Every job - hidden jobs aside - becomes an element of :mod:`pyTooling.CI`, named by its key and linked to the job 

690 by :attr:`~DefinitionMixin.Definition`: 

691 

692 * a job running a script becomes a :class:`DefinedJob`; 

693 * a trigger job becomes a :class:`DefinedWorkflow`, holding the elements of its child pipeline, if the resolver 

694 reads the child pipeline's files and the depth allows it; 

695 * a job with ``parallel`` becomes a :class:`DefinedMatrix`, holding a :class:`DefinedMatrixJob` or a 

696 :class:`DefinedMatrixWorkflow` per instance. 

697 

698 The ``needs`` of a job become the element's :attr:`~pyTooling.CI.DependencyMixin.Needs`; a job without ``needs`` 

699 needs every element of the nearest earlier stage holding elements. A need of some instances of a matrix needs the 

700 whole matrix. So :meth:`~pyTooling.CI.Workflow.ToGraph` converts the result into a graph. 

701 

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

703 pipelines are not expanded. Default: ``None``. 

704 :param depth: Optional, how many levels of child pipelines to expand; ``0`` expands none, ``None`` 

705 every level. Default: ``None``. 

706 :returns: The pipeline. 

707 :raises TypeError: If parameter 'resolver' is not of type :class:`IncludeResolver`. 

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

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

710 :raises PipelineFileError: If a child pipeline's file is not a well-formed configuration, or runs itself. 

711 """ 

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

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

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

715 raise ex 

716 

717 if depth is not None and (not isinstance(depth, int) or isinstance(depth, bool)): 

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

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

720 raise ex 

721 elif depth is not None and depth < 0: 

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

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

724 raise ex 

725 

726 def childFiles(job: Job, level: int, callers: tuple[PipelineFile, ...]) -> list[PipelineFile]: 

727 """ 

728 Nested function reading the files of a trigger job's child pipeline. 

729 

730 :param job: The trigger job. 

731 :param level: How many levels of child pipelines are expanded above this one. 

732 :param callers: The files expanded above this one, this one last. 

733 :returns: The files the resolver reads, if the depth allows expanding them. 

734 :raises PipelineFileError: If a child pipeline runs a file expanded above it. 

735 """ 

736 if resolver is None or job._trigger is None or (depth is not None and level >= depth): 

737 return [] 

738 

739 files = [] 

740 for include in job._trigger._includes: 

741 if (child := resolver.Resolve(include)) is None: 741 ↛ 742line 741 didn't jump to line 742 because the condition on line 741 was never true

742 continue 

743 elif any(caller._path.resolve() == child._path.resolve() for caller in callers): 

744 ex = PipelineFileError(f"Child pipeline '{child._path.name}' runs itself.", callers[-1]._path, include._line) 

745 ex.add_note(f"Runs: {' -> '.join(caller._path.name for caller in (*callers, child))}.") 

746 raise ex 

747 

748 files.append(child) 

749 

750 return files 

751 

752 def addElements( 

753 pipelineFile: PipelineFile, 

754 group: CIWorkflow, 

755 level: int, 

756 callers: tuple[PipelineFile, ...] 

757 ) -> None: 

758 """ 

759 Nested function for recursion, adding the elements of a file's jobs to a group. 

760 

761 :param pipelineFile: The file whose jobs become elements. 

762 :param group: The group the elements are added to. 

763 :param level: How many levels of child pipelines are expanded above this one. 

764 :param callers: The files expanded above this one, this one last. 

765 :raises PipelineFileError: If a child pipeline runs a file expanded above it. 

766 """ 

767 elements: dict[str, DependencyMixin] = {} 

768 for job in pipelineFile._jobs.values(): 

769 children = childFiles(job, level, callers) 

770 if job._parallel is not None: 

771 element = DefinedMatrix(job, parent=group) 

772 if job._parallel._count is not None: 

773 dimensions = [{"CI_NODE_INDEX": str(index)} for index in range(1, job._parallel._count + 1)] 

774 else: 

775 dimensions = job._parallel.Combinations 

776 

777 for dimension in dimensions: 

778 if job._trigger is None: 778 ↛ 781line 778 didn't jump to line 781 because the condition on line 778 was always true

779 DefinedMatrixJob(job, dimension, parent=element) 

780 else: 

781 instance = DefinedMatrixWorkflow(job, dimension, childFiles=children, parent=element) 

782 for child in children: 

783 addElements(child, instance, level + 1, (*callers, child)) 

784 elif job._trigger is not None: 

785 element = DefinedWorkflow(job, childFiles=children, parent=group) 

786 for child in children: 

787 addElements(child, element, level + 1, (*callers, child)) 

788 else: 

789 element = DefinedJob(job, parent=group) 

790 

791 elements[job._name] = element 

792 

793 stages = pipelineFile.Stages 

794 byStage: dict[int, list[str]] = {} 

795 for job in pipelineFile._jobs.values(): 

796 if job._stage in stages: 796 ↛ 795line 796 didn't jump to line 795 because the condition on line 796 was always true

797 byStage.setdefault(stages.index(job._stage), []).append(job._name) 

798 

799 for job in pipelineFile._jobs.values(): 

800 if job._needs is not None: 

801 for need in job._needs: 

802 if need._kind is NeedKind.Job and need._job in elements: 802 ↛ 801line 802 didn't jump to line 801 because the condition on line 802 was always true

803 elements[job._name].AddNeed(elements[need._job]) 

804 elif job._stage in stages: 804 ↛ 799line 804 didn't jump to line 799 because the condition on line 804 was always true

805 earlier = [index for index in byStage if index < stages.index(job._stage)] 

806 for name in byStage[max(earlier)] if len(earlier) > 0 else (): 

807 elements[job._name].AddNeed(elements[name]) 

808 

809 pipeline = DefinedPipeline(self) 

810 addElements(self, pipeline, 0, (self, )) 

811 pipeline.Validate() 

812 

813 return pipeline 

814 

815 @classmethod 

816 def FromFile(cls, path: Path, resolver: Nullable[IncludeResolver] = None) -> Self: 

817 """ 

818 Read a configuration file. 

819 

820 A file may begin with a header document holding the ``spec`` key, separated from the configuration by ``---``. 

821 

822 With a resolver, the local files the file includes are read too, so a job may extend their jobs and a 

823 ``!reference`` tag refer to their keys. The included jobs aren't jobs of this file. 

824 

825 :param path: Path to the configuration file. 

826 :param resolver: Optional, the resolver reading the local files the file includes. Default: ``None``. 

827 :returns: The configuration file, with its variables and jobs attached. 

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

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

830 :raises TypeError: If parameter 'resolver' is not of type :class:`IncludeResolver`. 

831 :raises PipelineFileError: If the file doesn't exist. 

832 :raises PipelineFileError: If the file can't be read. 

833 :raises PipelineFileError: If the file is not a YAML document. 

834 :raises PipelineFileError: If the file holds more than two documents, or its first of two documents has no 

835 ``spec`` key. 

836 :raises PipelineFileError: If the configuration is not a mapping. 

837 :raises PipelineFileError: If a key holds a value of the wrong kind. 

838 :raises PipelineFileError: If an input is malformed, or its default doesn't match its type or options. 

839 :raises PipelineFileError: If a job is in a stage the pipeline doesn't have. |br| 

840 The note lists the stages. 

841 :raises PipelineFileError: If a job needs a job the file doesn't have, or the jobs need each other in a cycle. |br| 

842 For an unknown job, the note lists the file's jobs. 

843 """ 

844 if path is None: 

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

846 elif not isinstance(path, Path): 

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

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

849 raise ex 

850 

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

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

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

854 raise ex 

855 

856 header, document = cls._Load(path) 

857 included: dict[str, Any] = {} 

858 incomplete = "include" in document 

859 if resolver is not None: 

860 included, incomplete = resolver._Included(document, path, (path.resolve(), )) 

861 

862 pipelineFile = cls._Parse(document, path, header, included, incomplete) 

863 pipelineFile._Validate() 

864 

865 return pipelineFile 

866 

867 @staticmethod 

868 def _Load(path: Path) -> tuple[Nullable[CommentedMap], CommentedMap]: 

869 """ 

870 Read the documents of a configuration file. 

871 

872 :param path: Path to the configuration file. 

873 :returns: The header document, or ``None``, and the configuration. 

874 :raises PipelineFileError: If the file doesn't exist, can't be read, or is not a YAML document. 

875 :raises PipelineFileError: If the file holds more than two documents, or its first of two documents has no 

876 ``spec`` key. 

877 :raises PipelineFileError: If the configuration is not a mapping. 

878 """ 

879 if not path.exists(): 

880 raise PipelineFileError("Configuration file doesn't exist.", path) from FileNotFoundError(path) 

881 

882 try: 

883 content = path.read_text(encoding="utf-8") 

884 except OSError as cause: 

885 raise PipelineFileError("Configuration file can't be read.", path) from cause 

886 

887 try: 

888 documents = list(YAML(typ="rt").load_all(content)) 

889 except YAMLError as cause: 

890 mark = getattr(cause, "problem_mark", None) 

891 line = None if mark is None else mark.line + 1 

892 raise PipelineFileError("Configuration file is not a YAML document.", path, line) from cause 

893 

894 header = None 

895 if len(documents) > 2: 

896 raise PipelineFileError("Configuration file holds more than two documents.", path) 

897 elif len(documents) == 2: 

898 header = documents[0] 

899 if not isinstance(header, CommentedMap) or "spec" not in header: 

900 raise PipelineFileError("Header document of configuration file has no 'spec' key.", path, 1) 

901 

902 document = documents[-1] if len(documents) > 0 else None 

903 if document is None: 

904 document = CommentedMap() 

905 elif not isinstance(document, CommentedMap): 

906 ex = PipelineFileError("Configuration is not a mapping.", path) 

907 ex.add_note(f"Got type '{getFullyQualifiedName(document)}'.") 

908 raise ex 

909 

910 return header, document 

911 

912 @classmethod 

913 def _Parse( 

914 cls, 

915 document: CommentedMap, 

916 path: Path, 

917 header: Nullable[CommentedMap] = None, 

918 included: Nullable[Mapping[str, Any]] = None, 

919 incomplete: Nullable[bool] = None 

920 ) -> Self: 

921 """ 

922 Build a configuration file and the elements it contains from the documents read from it. 

923 

924 :param document: The configuration, a mapping. 

925 :param path: Path to the configuration file. 

926 :param header: Optional, the header document, a mapping with key ``spec``. Default: ``None``. 

927 :param included: Optional, the top-level keys of the included files read. Default: ``None``. 

928 :param incomplete: Optional, ``True``, if the file includes files that weren't read. Default: ``None``, 

929 for ``True`` if the file includes files. 

930 :returns: The configuration file, with its variables, jobs, workflow, includes and default 

931 attached. 

932 :raises PipelineFileError: If key ``spec`` or ``spec:inputs`` of the header is not a mapping, or an input is 

933 malformed. 

934 :raises PipelineFileError: If key ``stages`` is not a list. 

935 :raises PipelineFileError: If key ``variables``, ``workflow`` or a job is not a mapping. 

936 :raises PipelineFileError: If a job extends a job, or a ``!reference`` tag refers to a key, the file doesn't have, 

937 though it includes no files. 

938 :raises PipelineFileError: If jobs extend each other in a cycle, or ``extends`` or ``!reference`` tags nest too 

939 deep. 

940 :raises PipelineFileError: If a key of a variable, a job, the workflow or an include holds a value of the wrong 

941 kind. 

942 """ 

943 stages = None 

944 if (stageList := document.get("stages", None)) is not None: 

945 if not isinstance(stageList, CommentedSeq): 

946 ex = PipelineFileError("Key 'stages' is not a list.", path, Base._KeyLine(document, "stages")) 

947 ex.add_note(f"Got type '{getFullyQualifiedName(stageList)}'.") 

948 raise ex 

949 

950 stages = [Base._ToText(stage) for stage in stageList] 

951 

952 variables = None 

953 if "variables" in document: 

954 variables = Variable._FromYAMLMapping(document["variables"], None, path, Base._KeyLine(document, "variables")) 

955 

956 jobs = [] 

957 for name, (mapping, unresolved) in cls._ResolveJobs(document, path, included, incomplete).items(): 

958 jobs.append(Job._FromYAML(name, mapping, path, Base._KeyLine(document, name), unresolved)) 

959 

960 workflow = None 

961 if "workflow" in document: 

962 workflow = Workflow._FromYAML(document["workflow"], path, Base._KeyLine(document, "workflow")) 

963 

964 includes = None 

965 if "include" in document: 

966 includes = Include._FromYAMLEntries(document["include"], path, Base._KeyLine(document, "include")) 

967 

968 default = Default._FromYAML(document, path) 

969 

970 inputs = None 

971 description = None 

972 if header is not None: 

973 spec = header["spec"] 

974 if not isinstance(spec, CommentedMap): 

975 ex = PipelineFileError("Key 'spec' of the header is not a mapping.", path, Base._KeyLine(header, "spec")) 

976 ex.add_note(f"Got type '{getFullyQualifiedName(spec)}'.") 

977 raise ex 

978 

979 if "inputs" in spec: 979 ↛ 982line 979 didn't jump to line 982 because the condition on line 979 was always true

980 inputs = Input._FromYAMLMapping(spec["inputs"], None, path, Base._KeyLine(spec, "inputs")) 

981 

982 if (description := spec.get("description", None)) is not None: 

983 description = Base._ToText(description) 

984 

985 return cls(path, stages, variables, jobs, workflow, includes, default, inputs, description) 

986 

987 @classmethod 

988 def _ResolveJobs( 

989 cls, 

990 document: CommentedMap, 

991 path: Path, 

992 included: Nullable[Mapping[str, Any]] = None, 

993 incomplete: Nullable[bool] = None 

994 ) -> dict[str, tuple[CommentedMap, list[str]]]: 

995 """ 

996 Resolve the ``!reference`` tags, the ``extends`` and the ``default`` of every job, as GitLab merges them. 

997 

998 A ``!reference`` tag is replaced by the value it refers to; one in a list of a list's items is spliced into it. 

999 A job's mapping is the deep merge of the jobs it extends, in order, and of its own keys: mappings merge, other 

1000 values - lists included - replace, and ``null`` removes a key. A job then gets every key of ``default``, and of 

1001 the global keywords standing for it, which it doesn't set, unless ``inherit.default`` says otherwise. 

1002 

1003 A job may extend the jobs, and a reference refer to the keys, of the included files read. Every key keeps the line 

1004 it is written at; a key an included file contributes gets the line of the ``extends`` key or the reference 

1005 bringing it in. What a job refers to, but neither the file nor an included file has, is an error - unless the file 

1006 includes files that weren't read, which may have it: then it is skipped and reported in the job's ``unresolved`` 

1007 list. 

1008 

1009 :param document: The configuration. 

1010 :param path: Path to the configuration file. 

1011 :param included: Optional, the top-level keys of the included files read. Default: ``None``. 

1012 :param incomplete: Optional, ``True``, if the file includes files that weren't read. Default: ``None``, 

1013 for ``True`` if the file includes files. 

1014 :returns: Every job's merged mapping, and what it refers to but the file doesn't have, by name, in 

1015 file order. 

1016 :raises PipelineFileError: If a job is not a mapping. 

1017 :raises PipelineFileError: If a job extends a job, or a ``!reference`` tag refers to a key, the file doesn't have, 

1018 though it includes no files. 

1019 :raises PipelineFileError: If jobs extend each other in a cycle, or ``extends`` or ``!reference`` tags nest too 

1020 deep. 

1021 """ 

1022 included = {} if included is None else dict(included) 

1023 hasIncludes = "include" in document if incomplete is None else incomplete 

1024 scope = included | dict(document) 

1025 foreign = {name for name in included if name not in document} 

1026 unresolved: dict[str, list[str]] = {} 

1027 

1028 def relocate(value: Any, line: int) -> Any: 

1029 """ 

1030 Nested function for recursion, copying a value of an included file with every line set to one of this file. 

1031 

1032 :param value: The value. 

1033 :param line: The line, starting at 0. 

1034 :returns: The copy. 

1035 """ 

1036 if isinstance(value, CommentedMap): 

1037 result = CommentedMap((key, relocate(item, line)) for key, item in value.items()) 

1038 for key in result: 

1039 result.lc.add_kv_line_col(key, [line, 0, line, 0]) 

1040 elif isinstance(value, CommentedSeq): 

1041 result = CommentedSeq(relocate(item, line) for item in value) 

1042 for index in range(len(result)): 

1043 result.lc.add_kv_line_col(index, [line, 0, line, 0]) 

1044 else: 

1045 return value 

1046 

1047 result.lc.line = line 

1048 result.lc.col = 0 

1049 return result 

1050 

1051 def resolve(value: Any, owner: Nullable[str], depth: int) -> Any: 

1052 """ 

1053 Nested function for recursion, resolving the ``!reference`` tags in a value. 

1054 

1055 :param value: The value. 

1056 :param owner: Name of the job the value belongs to, or ``None`` for ``default``. 

1057 :param depth: How many references were followed to reach the value. 

1058 :returns: The resolved value, or ``None`` for a reference of a job the file can't resolve. 

1059 :raises PipelineFileError: If a reference can't be resolved, though the file includes no files, or it is in 

1060 ``default``. 

1061 :raises PipelineFileError: If references nest deeper than :data:`MAX_REFERENCE_DEPTH` levels. 

1062 """ 

1063 if isinstance(value, CommentedSeq) and value.tag.value == "!reference": 

1064 segments = ", ".join(str(segment) for segment in value) 

1065 where = "the default" if owner is None else f"job '{owner}'" 

1066 if depth >= MAX_REFERENCE_DEPTH: 

1067 raise PipelineFileError( 

1068 f"Reference [{segments}] of {where} nests more than {MAX_REFERENCE_DEPTH} levels.", path, value.lc.line + 1 

1069 ) 

1070 

1071 segmentList = [str(segment) for segment in value] 

1072 target: Any = scope 

1073 for segment in segmentList: 

1074 if not isinstance(target, Mapping) or segment not in target: 

1075 if not hasIncludes or owner is None: 

1076 raise PipelineFileError( 

1077 f"Reference [{segments}] of {where} refers to a key the file doesn't have.", path, value.lc.line + 1 

1078 ) 

1079 

1080 unresolved.setdefault(owner, []).append(f"!reference [{segments}]") 

1081 return None 

1082 

1083 target = target[segment] 

1084 

1085 if segmentList[0] in foreign: 

1086 target = relocate(target, value.lc.line) 

1087 

1088 return resolve(target, owner, depth + 1) 

1089 elif isinstance(value, CommentedSeq): 

1090 items = CommentedSeq() 

1091 items.lc.line = value.lc.line 

1092 for index, item in enumerate(value): 

1093 isReference = isinstance(item, CommentedSeq) and item.tag.value == "!reference" 

1094 resolved = resolve(item, owner, depth) 

1095 if isReference and resolved is None: 

1096 continue 

1097 elif isReference and isinstance(resolved, CommentedSeq): 

1098 for position, element in enumerate(resolved): 

1099 items.append(element) 

1100 items.lc.add_kv_line_col(len(items) - 1, resolved.lc.data[position]) 

1101 else: 

1102 items.append(resolved) 

1103 items.lc.add_kv_line_col(len(items) - 1, value.lc.data[index]) 

1104 

1105 return items 

1106 elif isinstance(value, CommentedMap): 

1107 for key in list(value): 

1108 isReference = isinstance(value[key], CommentedSeq) and value[key].tag.value == "!reference" 

1109 resolved = resolve(value[key], owner, depth) 

1110 if resolved is None and isReference: 1110 ↛ 1111line 1110 didn't jump to line 1111 because the condition on line 1110 was never true

1111 del value[key] 

1112 else: 

1113 value[key] = resolved 

1114 

1115 return value 

1116 

1117 def merge(target: CommentedMap, source: CommentedMap) -> None: 

1118 """ 

1119 Nested function for recursion, merging a mapping deeply into another, keeping each key's line. 

1120 

1121 :param target: The mapping merged into. 

1122 :param source: The mapping merged. 

1123 """ 

1124 for key, value in source.items(): 

1125 if value is None: 

1126 target.pop(key, None) 

1127 continue 

1128 elif isinstance(value, CommentedMap) and isinstance(target.get(key, None), CommentedMap): 

1129 merged = copy(target[key]) 

1130 merge(merged, value) 

1131 value = merged 

1132 

1133 target[key] = value 

1134 if key in (source.lc.data or {}): 1134 ↛ 1124line 1134 didn't jump to line 1124 because the condition on line 1134 was always true

1135 target.lc.add_kv_line_col(key, source.lc.data[key]) 

1136 

1137 def copy(mapping: CommentedMap) -> CommentedMap: 

1138 """ 

1139 Nested function copying a mapping with the lines of its keys. 

1140 

1141 :param mapping: The mapping. 

1142 :returns: The copy. 

1143 """ 

1144 result = CommentedMap(mapping) 

1145 result.lc.line = mapping.lc.line 

1146 result.lc.col = mapping.lc.col 

1147 for key in mapping: 

1148 if key in (mapping.lc.data or {}): 1148 ↛ 1147line 1148 didn't jump to line 1147 because the condition on line 1148 was always true

1149 result.lc.add_kv_line_col(key, mapping.lc.data[key]) 

1150 

1151 return result 

1152 

1153 mappings: dict[str, CommentedMap] = {} 

1154 for name in foreign: 

1155 if name not in RESERVED_KEYS and isinstance(included[name], CommentedMap): 1155 ↛ 1154line 1155 didn't jump to line 1154 because the condition on line 1155 was always true

1156 mappings[name] = resolve(included[name], name, 0) 

1157 

1158 for name, job in document.items(): 

1159 name = str(name) 

1160 if name in RESERVED_KEYS: 

1161 continue 

1162 elif not isinstance(job, CommentedMap): 

1163 ex = PipelineFileError(f"Job '{name}' is not a mapping.", path, Base._KeyLine(document, name)) 

1164 ex.add_note(f"Got type '{getFullyQualifiedName(job)}'.") 

1165 raise ex 

1166 

1167 mappings[name] = resolve(job, name, 0) 

1168 

1169 defaults = CommentedMap() 

1170 if isinstance(document.get("default", None), CommentedMap): 

1171 defaults = copy(resolve(document["default"], None, 0)) 

1172 

1173 for key in Default._KEYS: 

1174 if key in document and key not in defaults: 

1175 defaults[key] = document[key] 

1176 defaults.lc.add_kv_line_col(key, document.lc.data[key]) 

1177 

1178 def extended(name: str, chain: tuple[str, ...]) -> CommentedMap: 

1179 """ 

1180 Nested function for recursion, merging the jobs a job extends and its own keys. 

1181 

1182 :param name: Name of the job. 

1183 :param chain: Names of the jobs extending this one, outermost first. 

1184 :returns: The merged mapping. 

1185 :raises PipelineFileError: If a job extends a job the file doesn't have, though it includes no files. 

1186 :raises PipelineFileError: If jobs extend each other in a cycle, or nest deeper than 

1187 :data:`MAX_EXTENDS_DEPTH` levels. 

1188 """ 

1189 own = mappings[name] 

1190 names = own.get("extends", ()) 

1191 names = [names] if isinstance(names, str) else list(names) 

1192 result = CommentedMap() 

1193 result.lc.line = own.lc.line 

1194 result.lc.col = own.lc.col 

1195 for base in (str(base) for base in names): 

1196 if base in chain or base == name: 

1197 cycle = " -> ".join((*chain, name, base)) 

1198 raise PipelineFileError(f"Jobs extend each other in a cycle: {cycle}.", path, Base._KeyLine(document, name)) 

1199 elif len(chain) >= MAX_EXTENDS_DEPTH: 

1200 raise PipelineFileError( 

1201 f"Job '{name}' extends more than {MAX_EXTENDS_DEPTH} levels.", path, Base._KeyLine(document, name) 

1202 ) 

1203 elif base not in mappings: 

1204 if not hasIncludes: 

1205 raise PipelineFileError( 

1206 f"Job '{name}' extends job '{base}', which the file doesn't have.", path, Base._KeyLine(own, "extends") 

1207 ) 

1208 

1209 unresolved.setdefault(chain[0] if len(chain) > 0 else name, []).append(f"extends {base}") 

1210 continue 

1211 

1212 baseMapping = extended(base, (*chain, name)) 

1213 if base in foreign and name not in foreign: 

1214 baseMapping = relocate(baseMapping, Base._KeyLine(own, "extends") - 1) 

1215 

1216 merge(result, baseMapping) 

1217 

1218 merge(result, own) 

1219 return result 

1220 

1221 resolved = {} 

1222 for name in (name for name in mappings if name not in foreign): 

1223 mapping = extended(name, ()) 

1224 inherit = mapping.get("inherit", None) 

1225 inherited = inherit.get("default", True) if isinstance(inherit, CommentedMap) else True 

1226 if not name.startswith(".") and inherited is not False: 

1227 for key, value in defaults.items(): 

1228 if key not in mapping and (inherited is True or key in inherited): 

1229 mapping[key] = value 

1230 mapping.lc.add_kv_line_col(key, defaults.lc.data[key]) 

1231 

1232 resolved[name] = (mapping, unresolved.get(name, [])) 

1233 

1234 return resolved 

1235 

1236 def _Validate(self) -> None: 

1237 """ 

1238 Validate the configuration read from a file. 

1239 

1240 :raises PipelineFileError: If a job is in a stage the pipeline doesn't have. |br| 

1241 The note lists the stages. 

1242 :raises PipelineFileError: If a job needs a job the file doesn't have. |br| 

1243 The note lists the file's jobs. 

1244 :raises PipelineFileError: If the jobs need each other in a cycle. 

1245 """ 

1246 self._ValidateStages() 

1247 self._ValidateNeeds() 

1248 self._ValidateAcyclic() 

1249 

1250 def _ValidateStages(self) -> None: 

1251 """ 

1252 Validate that every job is in a stage of the pipeline. 

1253 

1254 A stage interpolating an input, as ``$[[ inputs.stage ]]``, is known when the file is included only. 

1255 

1256 :raises PipelineFileError: If a job is in a stage the pipeline doesn't have. |br| 

1257 The note lists the stages. 

1258 """ 

1259 stages = self.Stages 

1260 for job in self._jobs.values(): 

1261 if job._stage not in stages and "$[[" not in job._stage: 

1262 ex = PipelineFileError( 

1263 f"Job '{job._name}' is in stage '{job._stage}', which isn't declared.", self._path, job._line 

1264 ) 

1265 ex.add_note(f"Stages: {', '.join(stages)}.") 

1266 raise ex 

1267 

1268 def _ValidateNeeds(self) -> None: 

1269 """ 

1270 Validate that every job needs only jobs of the file, unless the need is optional or refers to another pipeline. 

1271 

1272 A job's name interpolating an input is known when the file is included only. 

1273 

1274 :raises PipelineFileError: If a job needs a job the file doesn't have. |br| 

1275 The note lists the file's jobs. 

1276 """ 

1277 for job in self._jobs.values(): 

1278 if job._needs is None: 

1279 continue 

1280 

1281 for need in job._needs: 

1282 if need._kind is not NeedKind.Job or need._optional or need._job in self._jobs or "$[[" in need._job: 

1283 continue 

1284 

1285 ex = PipelineFileError( 

1286 f"Job '{job._name}' needs job '{need._job}', which the file doesn't have.", self._path, need._line 

1287 ) 

1288 ex.add_note(f"Jobs: {', '.join(self._jobs)}.") 

1289 raise ex 

1290 

1291 def _ValidateAcyclic(self) -> None: 

1292 """ 

1293 Validate that the jobs don't need each other in a cycle. 

1294 

1295 :raises PipelineFileError: If the jobs need each other in a cycle. 

1296 """ 

1297 finished: set[str] = set() 

1298 stack: list[str] = [] 

1299 

1300 def visit(job: Job) -> None: 

1301 """ 

1302 Nested function for recursion. 

1303 

1304 :param job: The job whose needs are followed. 

1305 :raises PipelineFileError: If the job is reached again while its needs are followed. 

1306 """ 

1307 if job._name in finished: 

1308 return 

1309 elif job._name in stack: 

1310 cycle = stack[stack.index(job._name):] + [job._name] 

1311 raise PipelineFileError(f"Jobs need each other in a cycle: {' -> '.join(cycle)}.", self._path, job._line) 

1312 

1313 stack.append(job._name) 

1314 for needed in job.NeededJobs: 

1315 visit(needed) 

1316 stack.pop() 

1317 finished.add(job._name) 

1318 

1319 for job in self._jobs.values(): 

1320 visit(job) 

1321 

1322 

1323@export 

1324class Job(Base[PipelineFile]): 

1325 """ 

1326 A job of a configuration file, or a hidden job. 

1327 

1328 A job runs :attr:`Script` in :attr:`Stage`, after the jobs of the earlier stages - or, with a ``needs`` key, after 

1329 the jobs in :attr:`Needs`. A hidden job, whose name starts with a dot, isn't run; other jobs extend it. 

1330 """ 

1331 

1332 _PARENT_TYPE: ClassVar[ParentTypes] = PipelineFile #: A job is contained in a configuration file. 

1333 

1334 _name: str #: Name of the job, the key it is declared under. 

1335 _stage: str #: Stage the job runs in. 

1336 _needs: Nullable[list[Need]] #: Entries of the job's ``needs``, or ``None`` without a ``needs`` key. 

1337 _rules: list[Rule] #: Rules deciding whether the job is added to a pipeline. 

1338 _when: Nullable[RuleOutcome] #: When the job runs. 

1339 _allowFailure: Nullable[bool] #: ``True``, if the pipeline continues when the job fails. 

1340 _allowedExitCodes: tuple[int, ...] #: Exit codes, with which the job may fail. 

1341 _script: tuple[str, ...] #: Lines of the job's ``script``. 

1342 _beforeScript: tuple[str, ...] #: Lines of the job's ``before_script``. 

1343 _afterScript: tuple[str, ...] #: Lines of the job's ``after_script``. 

1344 _image: Nullable[str] #: Image of the container the job runs in. 

1345 _services: tuple[str, ...] #: Images of the service containers. 

1346 _tags: tuple[str, ...] #: Tags selecting the runner. 

1347 _environment: Nullable[str] #: Name of the environment the job deploys to. 

1348 _variables: dict[str, Variable] #: Variables of the job, by name, in file order. 

1349 _inputs: dict[str, Input] #: Inputs of the job, by name, in file order. 

1350 _parallel: Nullable[Parallel] #: The job's ``parallel``. 

1351 _trigger: Nullable[Trigger] #: The pipeline the job starts. 

1352 _extends: tuple[str, ...] #: Names of the jobs this job extends. 

1353 _unresolved: tuple[str, ...] #: What the job refers to, but its file doesn't have. 

1354 

1355 def __init__( 

1356 self, 

1357 name: str, 

1358 line: int, 

1359 stage: str = "test", 

1360 needs: Nullable[Iterable[Need]] = None, 

1361 when: Nullable[RuleOutcome] = None, 

1362 allowFailure: Nullable[bool] = None, 

1363 allowedExitCodes: Nullable[Iterable[int]] = None, 

1364 script: Nullable[Iterable[str]] = None, 

1365 beforeScript: Nullable[Iterable[str]] = None, 

1366 afterScript: Nullable[Iterable[str]] = None, 

1367 image: Nullable[str] = None, 

1368 services: Nullable[Iterable[str]] = None, 

1369 tags: Nullable[Iterable[str]] = None, 

1370 environment: Nullable[str] = None, 

1371 variables: Nullable[Iterable[Variable]] = None, 

1372 rules: Nullable[Iterable[Rule]] = None, 

1373 inputs: Nullable[Iterable[Input]] = None, 

1374 parallel: Nullable[Parallel] = None, 

1375 trigger: Nullable[Trigger] = None, 

1376 extends: Nullable[Iterable[str]] = None, 

1377 unresolved: Nullable[Iterable[str]] = None, 

1378 *, 

1379 parent: Nullable[PipelineFile] = None 

1380 ) -> None: 

1381 """ 

1382 Initializes a job. 

1383 

1384 A need, a variable, a rule, an input, a parallel or a trigger is attached by passing it, or by constructing it with 

1385 the job as parent. 

1386 

1387 :param name: Name of the job, the key it is declared under. 

1388 :param line: Line the job's name is written at, starting at 1. 

1389 :param stage: Optional, stage the job runs in. Default: ``test``. 

1390 :param needs: Optional, entries of the job's ``needs``, which are attached to the job; an empty 

1391 iterable for ``needs: []``. Default: ``None``, for a job without a ``needs`` key. 

1392 :param when: Optional, when the job runs. Default: ``None``, for a job that doesn't say. 

1393 :param allowFailure: Optional, ``True``, if the pipeline continues when the job fails. Default: ``None``. 

1394 :param allowedExitCodes: Optional, exit codes, with which the job may fail. Default: ``None``. 

1395 :param script: Optional, lines of the job's ``script``. Default: ``None``. 

1396 :param beforeScript: Optional, lines of the job's ``before_script``. Default: ``None``. 

1397 :param afterScript: Optional, lines of the job's ``after_script``. Default: ``None``. 

1398 :param image: Optional, image of the container the job runs in. Default: ``None``. 

1399 :param services: Optional, images of the service containers. Default: ``None``. 

1400 :param tags: Optional, tags selecting the runner. Default: ``None``. 

1401 :param environment: Optional, name of the environment the job deploys to. Default: ``None``. 

1402 :param variables: Optional, variables of the job, which are attached to the job. Default: ``None``. 

1403 :param rules: Optional, rules deciding whether the job is added to a pipeline, which are attached to 

1404 the job. Default: ``None``. 

1405 :param inputs: Optional, inputs of the job, which are attached to the job. Default: ``None``. 

1406 :param parallel: Optional, the job's ``parallel``, which is attached to the job. Default: ``None``. 

1407 :param trigger: Optional, the pipeline the job starts, which is attached to the job. Default: ``None``. 

1408 :param extends: Optional, names of the jobs this job extends. Default: ``None``. 

1409 :param unresolved: Optional, what the job refers to with ``extends`` or a ``!reference`` tag, but its file 

1410 doesn't have. Default: ``None``. 

1411 :param parent: Optional, reference to the configuration file containing the job. Default: ``None``. 

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

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

1414 :raises ValueError: If parameter 'name' is empty. 

1415 :raises ValueError: If parameter 'stage' is ``None``. 

1416 :raises TypeError: If parameter 'stage' is not of type :class:`str`. 

1417 :raises ValueError: If parameter 'stage' is empty. 

1418 :raises TypeError: If an element of parameter 'needs' is not of type :class:`Need`. 

1419 :raises TypeError: If parameter 'when' is not of type :class:`~pyTooling.CI.RuleOutcome`. 

1420 :raises TypeError: If parameter 'allowFailure' is not of type :class:`bool`. 

1421 :raises TypeError: If an element of parameter 'allowedExitCodes' is not of type :class:`int`. 

1422 :raises TypeError: If an element of parameter 'script' is not of type :class:`str`. 

1423 :raises TypeError: If an element of parameter 'beforeScript' is not of type :class:`str`. 

1424 :raises TypeError: If an element of parameter 'afterScript' is not of type :class:`str`. 

1425 :raises TypeError: If parameter 'image' is not of type :class:`str`. 

1426 :raises TypeError: If an element of parameter 'services' is not of type :class:`str`. 

1427 :raises TypeError: If an element of parameter 'tags' is not of type :class:`str`. 

1428 :raises TypeError: If parameter 'environment' is not of type :class:`str`. 

1429 :raises TypeError: If an element of parameter 'variables' is not of type :class:`Variable`. 

1430 :raises TypeError: If an element of parameter 'rules' is not of type :class:`Rule`. 

1431 :raises TypeError: If an element of parameter 'inputs' is not of type :class:`Input`. 

1432 :raises TypeError: If parameter 'parallel' is not of type :class:`Parallel`. 

1433 :raises TypeError: If parameter 'trigger' is not of type :class:`Trigger`. 

1434 :raises TypeError: If an element of parameter 'extends' is not of type :class:`str`. 

1435 :raises TypeError: If an element of parameter 'unresolved' is not of type :class:`str`. 

1436 """ 

1437 super().__init__(line, parent=parent) 

1438 

1439 for parameterName, text in ( 

1440 ("name", name), 

1441 ("stage", stage) 

1442 ): 

1443 if text is None: 

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

1445 elif not isinstance(text, str): 

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

1447 ex.add_note(f"Got type '{getFullyQualifiedName(text)}'.") 

1448 raise ex 

1449 elif text == "": 

1450 raise ValueError(f"Parameter '{parameterName}' is empty.") 

1451 

1452 if when is not None and not isinstance(when, RuleOutcome): 

1453 ex = TypeError("Parameter 'when' is not of type 'RuleOutcome'.") 

1454 ex.add_note(f"Got type '{getFullyQualifiedName(when)}'.") 

1455 raise ex 

1456 

1457 if allowFailure is not None and not isinstance(allowFailure, bool): 

1458 ex = TypeError("Parameter 'allowFailure' is not of type 'bool'.") 

1459 ex.add_note(f"Got type '{getFullyQualifiedName(allowFailure)}'.") 

1460 raise ex 

1461 

1462 for parameterName, text in ( 

1463 ("image", image), 

1464 ("environment", environment) 

1465 ): 

1466 if text is not None and not isinstance(text, str): 

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

1468 ex.add_note(f"Got type '{getFullyQualifiedName(text)}'.") 

1469 raise ex 

1470 

1471 self._allowedExitCodes = () if allowedExitCodes is None else tuple(allowedExitCodes) 

1472 for code in self._allowedExitCodes: 

1473 if not isinstance(code, int) or isinstance(code, bool): 

1474 ex = TypeError("An element of parameter 'allowedExitCodes' is not of type 'int'.") 

1475 ex.add_note(f"Got type '{getFullyQualifiedName(code)}'.") 

1476 raise ex 

1477 

1478 self._script = () if script is None else tuple(script) 

1479 self._beforeScript = () if beforeScript is None else tuple(beforeScript) 

1480 self._afterScript = () if afterScript is None else tuple(afterScript) 

1481 self._services = () if services is None else tuple(services) 

1482 self._tags = () if tags is None else tuple(tags) 

1483 self._extends = () if extends is None else tuple(extends) 

1484 self._unresolved = () if unresolved is None else tuple(unresolved) 

1485 for parameterName, texts in ( 

1486 ("script", self._script), 

1487 ("beforeScript", self._beforeScript), 

1488 ("afterScript", self._afterScript), 

1489 ("services", self._services), 

1490 ("tags", self._tags), 

1491 ("extends", self._extends), 

1492 ("unresolved", self._unresolved) 

1493 ): 

1494 for text in texts: 

1495 if not isinstance(text, str): 

1496 ex = TypeError(f"An element of parameter '{parameterName}' is not of type 'str'.") 

1497 ex.add_note(f"Got type '{getFullyQualifiedName(text)}'.") 

1498 raise ex 

1499 

1500 self._name = name 

1501 self._stage = stage 

1502 self._needs = None 

1503 self._rules = ruleList = [] 

1504 self._inputs = {} 

1505 self._parallel = None 

1506 self._trigger = None 

1507 self._when = when 

1508 self._allowFailure = allowFailure 

1509 self._image = image 

1510 self._environment = environment 

1511 self._variables = {} 

1512 

1513 if needs is not None: 

1514 self._needs = needList = [] 

1515 for need in needs: 

1516 if not isinstance(need, Need): 

1517 ex = TypeError("An element of parameter 'needs' is not of type 'Need'.") 

1518 ex.add_note(f"Got type '{getFullyQualifiedName(need)}'.") 

1519 raise ex 

1520 

1521 needList.append(need) 

1522 need.Parent = self 

1523 

1524 if variables is not None: 

1525 for variable in variables: 

1526 if not isinstance(variable, Variable): 

1527 ex = TypeError("An element of parameter 'variables' is not of type 'Variable'.") 

1528 ex.add_note(f"Got type '{getFullyQualifiedName(variable)}'.") 

1529 raise ex 

1530 

1531 self._variables[variable._name] = variable 

1532 variable.Parent = self 

1533 

1534 if rules is not None: 

1535 for rule in rules: 

1536 if not isinstance(rule, Rule): 

1537 ex = TypeError("An element of parameter 'rules' is not of type 'Rule'.") 

1538 ex.add_note(f"Got type '{getFullyQualifiedName(rule)}'.") 

1539 raise ex 

1540 

1541 ruleList.append(rule) 

1542 rule.Parent = self 

1543 

1544 if inputs is not None: 

1545 for parameter in inputs: 

1546 if not isinstance(parameter, Input): 

1547 ex = TypeError("An element of parameter 'inputs' is not of type 'Input'.") 

1548 ex.add_note(f"Got type '{getFullyQualifiedName(parameter)}'.") 

1549 raise ex 

1550 

1551 self._inputs[parameter._name] = parameter 

1552 parameter.Parent = self 

1553 

1554 for parameterName, element, elementClass in ( 

1555 ("parallel", parallel, Parallel), 

1556 ("trigger", trigger, Trigger) 

1557 ): 

1558 if element is not None and not isinstance(element, elementClass): 

1559 ex = TypeError(f"Parameter '{parameterName}' is not of type '{elementClass.__name__}'.") 

1560 ex.add_note(f"Got type '{getFullyQualifiedName(element)}'.") 

1561 raise ex 

1562 

1563 if parallel is not None: 

1564 self._parallel = parallel 

1565 parallel.Parent = self 

1566 

1567 if trigger is not None: 

1568 self._trigger = trigger 

1569 trigger.Parent = self 

1570 

1571 if parent is not None: 

1572 (parent._hiddenJobs if self.IsHidden else parent._jobs)[name] = self 

1573 

1574 @Base.Parent.setter 

1575 def Parent(self, value: PipelineFile) -> None: 

1576 Base.Parent.fset(self, value) 

1577 

1578 for need in () if self._needs is None else self._needs: 

1579 need.Parent = self 

1580 

1581 for variable in self._variables.values(): 

1582 variable.Parent = self 

1583 

1584 for rule in self._rules: 

1585 rule.Parent = self 

1586 

1587 for parameter in self._inputs.values(): 

1588 parameter.Parent = self 

1589 

1590 for element in (self._parallel, self._trigger): 

1591 if element is not None: 

1592 element.Parent = self 

1593 

1594 @readonly 

1595 def Name(self) -> str: 

1596 """ 

1597 Read-only property to access the job's name, the key it is declared under (:attr:`_name`). 

1598 

1599 :returns: Name of the job. 

1600 """ 

1601 return self._name 

1602 

1603 @readonly 

1604 def IsHidden(self) -> bool: 

1605 """ 

1606 Read-only property to return whether the job is a hidden job, which GitLab doesn't run. 

1607 

1608 :returns: ``True``, if the job's name starts with a dot. 

1609 """ 

1610 return self._name.startswith(".") 

1611 

1612 @readonly 

1613 def Extends(self) -> tuple[str, ...]: 

1614 """ 

1615 Read-only property to access the names of the jobs this job extends (:attr:`_extends`). 

1616 

1617 The job's keys are the merge of theirs and its own already. 

1618 

1619 :returns: The names, in the order ``extends`` lists them. 

1620 """ 

1621 return self._extends 

1622 

1623 @readonly 

1624 def Unresolved(self) -> tuple[str, ...]: 

1625 """ 

1626 Read-only property to access what the job refers to, but its file doesn't have (:attr:`_unresolved`). 

1627 

1628 A file including other files may extend or refer to their jobs; then the job lacks what they contribute. 

1629 

1630 :returns: The jobs it extends and the ``!reference`` tags, as ``extends .base`` and ``!reference [.setup, 

1631 script]``, or an empty tuple if the job is complete. 

1632 """ 

1633 return self._unresolved 

1634 

1635 @readonly 

1636 def Stage(self) -> str: 

1637 """ 

1638 Read-only property to access the stage the job runs in (:attr:`_stage`). 

1639 

1640 :returns: The stage, ``test`` for a job that doesn't name one. 

1641 """ 

1642 return self._stage 

1643 

1644 @readonly 

1645 def Needs(self) -> Nullable[tuple[Need, ...]]: 

1646 """ 

1647 Read-only property to return the entries of the job's ``needs`` (:attr:`_needs`). 

1648 

1649 :returns: The entries, in file order; an empty tuple for ``needs: []``; or ``None`` for a job without a ``needs`` 

1650 key, which runs after the jobs of the earlier stages. 

1651 """ 

1652 return None if self._needs is None else tuple(self._needs) 

1653 

1654 @readonly 

1655 def NeededJobs(self) -> tuple[Job, ...]: 

1656 """ 

1657 Read-only property to return the jobs of the same file this job needs, as its ``needs`` names them. 

1658 

1659 An optional need of a job the file doesn't have is skipped, as are needs of other pipelines. 

1660 

1661 :returns: The jobs, in the order the ``needs`` key lists them. 

1662 """ 

1663 if self._needs is None or self._pipelineFile is None: 

1664 return () 

1665 

1666 jobs = self._pipelineFile._jobs 

1667 return tuple(jobs[need._job] for need in self._needs if need._kind is NeedKind.Job and need._job in jobs) 

1668 

1669 @readonly 

1670 def Rules(self) -> list[Rule]: 

1671 """ 

1672 Read-only property to access the rules deciding whether the job is added to a pipeline (:attr:`_rules`). 

1673 

1674 :returns: The rules, in the order GitLab evaluates them. 

1675 """ 

1676 return self._rules 

1677 

1678 @readonly 

1679 def Inputs(self) -> dict[str, Input]: 

1680 """ 

1681 Read-only property to access the inputs of the job (:attr:`_inputs`). 

1682 

1683 :returns: The inputs, by name, in file order. 

1684 """ 

1685 return self._inputs 

1686 

1687 @readonly 

1688 def Parallel(self) -> Nullable[Parallel]: 

1689 """ 

1690 Read-only property to access the job's ``parallel`` (:attr:`_parallel`). 

1691 

1692 :returns: How often the job runs, or its matrix, or ``None`` for a job running once. 

1693 """ 

1694 return self._parallel 

1695 

1696 @readonly 

1697 def Trigger(self) -> Nullable[Trigger]: 

1698 """ 

1699 Read-only property to access the pipeline the job starts (:attr:`_trigger`). 

1700 

1701 :returns: The trigger, or ``None`` for a job running a script. 

1702 """ 

1703 return self._trigger 

1704 

1705 @readonly 

1706 def When(self) -> Nullable[RuleOutcome]: 

1707 """ 

1708 Read-only property to access when the job runs (:attr:`_when`). 

1709 

1710 :returns: The ``when`` key, or ``None`` if the job doesn't say - GitLab runs it on success then. 

1711 """ 

1712 return self._when 

1713 

1714 @readonly 

1715 def AllowFailure(self) -> Nullable[bool]: 

1716 """ 

1717 Read-only property to access whether the pipeline continues when the job fails (:attr:`_allowFailure`). 

1718 

1719 :returns: The ``allow_failure`` key, ``True`` for a mapping of exit codes, or ``None`` if the job doesn't say. 

1720 """ 

1721 return self._allowFailure 

1722 

1723 @readonly 

1724 def AllowedExitCodes(self) -> tuple[int, ...]: 

1725 """ 

1726 Read-only property to access the exit codes, with which the job may fail (:attr:`_allowedExitCodes`). 

1727 

1728 :returns: The exit codes of ``allow_failure.exit_codes``, in file order. 

1729 """ 

1730 return self._allowedExitCodes 

1731 

1732 @readonly 

1733 def Script(self) -> tuple[str, ...]: 

1734 """ 

1735 Read-only property to access the lines of the job's ``script`` (:attr:`_script`). 

1736 

1737 :returns: The lines, nested lists flattened. 

1738 """ 

1739 return self._script 

1740 

1741 @readonly 

1742 def BeforeScript(self) -> tuple[str, ...]: 

1743 """ 

1744 Read-only property to access the lines of the job's ``before_script`` (:attr:`_beforeScript`). 

1745 

1746 :returns: The lines, nested lists flattened. 

1747 """ 

1748 return self._beforeScript 

1749 

1750 @readonly 

1751 def AfterScript(self) -> tuple[str, ...]: 

1752 """ 

1753 Read-only property to access the lines of the job's ``after_script`` (:attr:`_afterScript`). 

1754 

1755 :returns: The lines, nested lists flattened. 

1756 """ 

1757 return self._afterScript 

1758 

1759 @readonly 

1760 def Image(self) -> Nullable[str]: 

1761 """ 

1762 Read-only property to access the image of the container the job runs in (:attr:`_image`). 

1763 

1764 :returns: The image, as ``python:3.14``, or ``None`` if the job names none. 

1765 """ 

1766 return self._image 

1767 

1768 @readonly 

1769 def Services(self) -> tuple[str, ...]: 

1770 """ 

1771 Read-only property to access the images of the service containers (:attr:`_services`). 

1772 

1773 :returns: The images, in file order. 

1774 """ 

1775 return self._services 

1776 

1777 @readonly 

1778 def Tags(self) -> tuple[str, ...]: 

1779 """ 

1780 Read-only property to access the tags selecting the runner (:attr:`_tags`). 

1781 

1782 :returns: The tags, in file order. 

1783 """ 

1784 return self._tags 

1785 

1786 @readonly 

1787 def Environment(self) -> Nullable[str]: 

1788 """ 

1789 Read-only property to access the name of the environment the job deploys to (:attr:`_environment`). 

1790 

1791 :returns: The environment's name, or ``None`` if the job deploys to none. 

1792 """ 

1793 return self._environment 

1794 

1795 @readonly 

1796 def Variables(self) -> dict[str, Variable]: 

1797 """ 

1798 Read-only property to access the variables of the job (:attr:`_variables`). 

1799 

1800 :returns: The variables, by name, in file order. 

1801 """ 

1802 return self._variables 

1803 

1804 def __str__(self) -> str: 

1805 """ 

1806 Return the job's name. 

1807 

1808 :returns: Name of the job. 

1809 """ 

1810 return self._name 

1811 

1812 @staticmethod 

1813 def _Lines(value: Any, key: str, owner: str, mapping: CommentedMap, path: Path) -> list[str]: 

1814 """ 

1815 Read a script key: a line, or a list of lines and nested lists of lines. 

1816 

1817 :param value: The key's value. 

1818 :param key: The key, for a message. 

1819 :param owner: The element holding the key, for a message, as ``job 'build'``. 

1820 :param mapping: The job's mapping, for the key's line. 

1821 :param path: Path to the configuration file. 

1822 :returns: The lines, nested lists flattened. 

1823 :raises PipelineFileError: If the value is a mapping, or a list holds a mapping. 

1824 """ 

1825 if isinstance(value, CommentedSeq): 

1826 lines = [] 

1827 for item in value: 

1828 lines.extend(Job._Lines(item, key, owner, mapping, path)) 

1829 

1830 return lines 

1831 elif isinstance(value, CommentedMap): 

1832 ex = PipelineFileError(f"Key '{key}' of {owner} is not a script.", path, Base._KeyLine(mapping, key)) 

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

1834 raise ex 

1835 

1836 return [] if value is None else [Base._ToText(value)] 

1837 

1838 @staticmethod 

1839 def _Name(value: Any) -> Nullable[str]: 

1840 """ 

1841 Read a key naming something by a string or by the ``name`` of a mapping, as ``image`` and ``environment`` do. 

1842 

1843 :param value: The key's value. 

1844 :returns: The name, or ``None``. 

1845 """ 

1846 if isinstance(value, CommentedMap): 

1847 value = value.get("name", None) 

1848 

1849 return None if value is None else Base._ToText(value) 

1850 

1851 @classmethod 

1852 def _FromYAML( 

1853 cls, 

1854 name: str, 

1855 mapping: CommentedMap, 

1856 path: Path, 

1857 line: int, 

1858 unresolved: Nullable[Iterable[str]] = None 

1859 ) -> Self: 

1860 """ 

1861 Build a job and the elements it contains from its mapping in the configuration file. 

1862 

1863 :param name: Name of the job. 

1864 :param mapping: The job's mapping, merged with the jobs it extends and the default. 

1865 :param path: Path to the configuration file. 

1866 :param line: Line the job's name is written at, starting at 1. 

1867 :param unresolved: Optional, what the job refers to, but the file doesn't have. Default: ``None``. 

1868 :returns: The job. 

1869 :raises PipelineFileError: If key ``when`` is not a value GitLab knows. |br| 

1870 The note lists the allowed values. 

1871 :raises PipelineFileError: If a key of the job holds a value of the wrong kind. 

1872 :raises PipelineFileError: If an entry of key ``needs`` is malformed. 

1873 """ 

1874 needs = None 

1875 if "needs" in mapping: 

1876 needs = Need._FromYAMLEntries(mapping["needs"], name, path, Base._KeyLine(mapping, "needs")) 

1877 

1878 when = None 

1879 if (whenValue := mapping.get("when", None)) is not None: 

1880 try: 

1881 when = RuleOutcome.Parse(Base._ToText(whenValue)) 

1882 except ValueError as cause: 

1883 ex = PipelineFileError( 

1884 f"Key 'when' of job '{name}' is not a known value.", path, Base._KeyLine(mapping, "when") 

1885 ) 

1886 ex.add_note(f"Got '{whenValue}'.") 

1887 ex.add_note(f"Allowed values: {', '.join(member.value for member in RuleOutcome)}.") 

1888 raise ex from cause 

1889 

1890 allowFailure = Base._ToPython(mapping.get("allow_failure", None)) 

1891 exitCodes = None 

1892 if isinstance(allowFailure, dict): 

1893 exitCodes = allowFailure.get("exit_codes", ()) 

1894 exitCodes = [exitCodes] if isinstance(exitCodes, int) else exitCodes 

1895 allowFailure = True 

1896 

1897 if allowFailure is not None and not isinstance(allowFailure, bool): 

1898 ex = PipelineFileError( 

1899 f"Key 'allow_failure' of job '{name}' is not a boolean.", path, Base._KeyLine(mapping, "allow_failure") 

1900 ) 

1901 ex.add_note(f"Got '{allowFailure}'.") 

1902 raise ex 

1903 

1904 services = None 

1905 if (serviceList := mapping.get("services", None)) is not None: 

1906 if not isinstance(serviceList, CommentedSeq): 

1907 ex = PipelineFileError( 

1908 f"Key 'services' of job '{name}' is not a list.", path, Base._KeyLine(mapping, "services") 

1909 ) 

1910 ex.add_note(f"Got type '{getFullyQualifiedName(serviceList)}'.") 

1911 raise ex 

1912 

1913 services = [service for item in serviceList if (service := cls._Name(item)) is not None] 

1914 

1915 tags = None 

1916 if (tagList := mapping.get("tags", None)) is not None: 

1917 if not isinstance(tagList, CommentedSeq): 

1918 ex = PipelineFileError(f"Key 'tags' of job '{name}' is not a list.", path, Base._KeyLine(mapping, "tags")) 

1919 ex.add_note(f"Got type '{getFullyQualifiedName(tagList)}'.") 

1920 raise ex 

1921 

1922 tags = [Base._ToText(tag) for tag in tagList] 

1923 

1924 variables = None 

1925 if "variables" in mapping: 

1926 keyLine = Base._KeyLine(mapping, "variables") 

1927 variables = Variable._FromYAMLMapping(mapping["variables"], f"job '{name}'", path, keyLine) 

1928 

1929 rules = None 

1930 if "rules" in mapping: 

1931 rules = Rule._FromYAMLEntries(mapping["rules"], f"job '{name}'", path, Base._KeyLine(mapping, "rules")) 

1932 

1933 inputs = None 

1934 if "inputs" in mapping: 

1935 inputs = Input._FromYAMLMapping(mapping["inputs"], name, path, Base._KeyLine(mapping, "inputs")) 

1936 

1937 parallel = None 

1938 if "parallel" in mapping: 

1939 parallel = Parallel._FromYAML(mapping["parallel"], f"job '{name}'", path, Base._KeyLine(mapping, "parallel")) 

1940 

1941 trigger = None 

1942 if "trigger" in mapping: 

1943 trigger = Trigger._FromYAML(mapping["trigger"], name, path, Base._KeyLine(mapping, "trigger")) 

1944 

1945 extends = mapping.get("extends", ()) 

1946 extends = [extends] if isinstance(extends, str) else extends 

1947 stage = mapping.get("stage", None) 

1948 

1949 return cls( 

1950 name, line, 

1951 stage="test" if stage is None else Base._ToText(stage), 

1952 needs=needs, 

1953 when=when, 

1954 allowFailure=allowFailure, 

1955 allowedExitCodes=exitCodes, 

1956 script=cls._Lines(mapping.get("script", None), "script", f"job '{name}'", mapping, path), 

1957 beforeScript=cls._Lines(mapping.get("before_script", None), "before_script", f"job '{name}'", mapping, path), 

1958 afterScript=cls._Lines(mapping.get("after_script", None), "after_script", f"job '{name}'", mapping, path), 

1959 image=cls._Name(mapping.get("image", None)), 

1960 services=services, 

1961 tags=tags, 

1962 environment=cls._Name(mapping.get("environment", None)), 

1963 variables=variables, 

1964 rules=rules, 

1965 inputs=inputs, 

1966 parallel=parallel, 

1967 trigger=trigger, 

1968 extends=[Base._ToText(base) for base in extends], 

1969 unresolved=unresolved 

1970 ) 

1971 

1972 

1973@export 

1974class Variable(Base[Union[PipelineFile, Job]]): 

1975 """ 

1976 A CI/CD variable, declared in a ``variables`` key. 

1977 

1978 A default variable - declared in the top-level ``variables`` - may carry a :attr:`Description`, which makes GitLab 

1979 prefill it in the form running a pipeline by hand, and :attr:`Options` to select its value from. 

1980 """ 

1981 

1982 _PARENT_TYPE: ClassVar[ParentTypes] = (PipelineFile, Job) #: A variable is declared by a configuration file or a job. 

1983 

1984 _name: str #: Name of the variable. 

1985 _value: Nullable[str] #: Value of the variable. 

1986 _description: Nullable[str] #: Description of the variable, shown when running a pipeline by hand. 

1987 _options: tuple[str, ...] #: Values to select from, when running a pipeline by hand. 

1988 _expand: Nullable[bool] #: ``False``, if variables in the value are not expanded. 

1989 

1990 _KEYS: ClassVar[tuple[str, ...]] = ("value", "description", "options", "expand") #: Keys of a declaration as mapping. 

1991 

1992 def __init__( 

1993 self, 

1994 name: str, 

1995 line: int, 

1996 value: Nullable[str] = None, 

1997 description: Nullable[str] = None, 

1998 options: Nullable[Iterable[str]] = None, 

1999 expand: Nullable[bool] = None, 

2000 *, 

2001 parent: Nullable[Union[PipelineFile, Job]] = None 

2002 ) -> None: 

2003 """ 

2004 Initializes a variable. 

2005 

2006 :param name: Name of the variable. 

2007 :param line: Line the variable's name is written at, starting at 1. 

2008 :param value: Optional, value of the variable. Default: ``None``. 

2009 :param description: Optional, description of the variable. Default: ``None``. 

2010 :param options: Optional, values to select from when running a pipeline by hand. Default: ``None``. 

2011 :param expand: Optional, ``False``, if variables in the value are not expanded. Default: ``None``, for a 

2012 variable that doesn't say. 

2013 :param parent: Optional, reference to the configuration file or the job declaring the variable. Default: 

2014 ``None``. 

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

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

2017 :raises ValueError: If parameter 'name' is empty. 

2018 :raises TypeError: If parameter 'value' is not of type :class:`str`. 

2019 :raises TypeError: If parameter 'description' is not of type :class:`str`. 

2020 :raises TypeError: If an element of parameter 'options' is not of type :class:`str`. 

2021 :raises TypeError: If parameter 'expand' is not of type :class:`bool`. 

2022 """ 

2023 super().__init__(line, parent=parent) 

2024 

2025 if name is None: 

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

2027 elif not isinstance(name, str): 

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

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

2030 raise ex 

2031 elif name == "": 

2032 raise ValueError("Parameter 'name' is empty.") 

2033 

2034 for parameterName, text in ( 

2035 ("value", value), 

2036 ("description", description) 

2037 ): 

2038 if text is not None and not isinstance(text, str): 

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

2040 ex.add_note(f"Got type '{getFullyQualifiedName(text)}'.") 

2041 raise ex 

2042 

2043 self._options = () if options is None else tuple(options) 

2044 for option in self._options: 

2045 if not isinstance(option, str): 

2046 ex = TypeError("An element of parameter 'options' is not of type 'str'.") 

2047 ex.add_note(f"Got type '{getFullyQualifiedName(option)}'.") 

2048 raise ex 

2049 

2050 if expand is not None and not isinstance(expand, bool): 

2051 ex = TypeError("Parameter 'expand' is not of type 'bool'.") 

2052 ex.add_note(f"Got type '{getFullyQualifiedName(expand)}'.") 

2053 raise ex 

2054 

2055 self._name = name 

2056 self._value = value 

2057 self._description = description 

2058 self._expand = expand 

2059 

2060 if parent is not None: 

2061 parent._variables[name] = self 

2062 

2063 @readonly 

2064 def Name(self) -> str: 

2065 """ 

2066 Read-only property to access the variable's name (:attr:`_name`). 

2067 

2068 :returns: Name of the variable. 

2069 """ 

2070 return self._name 

2071 

2072 @readonly 

2073 def Value(self) -> Nullable[str]: 

2074 """ 

2075 Read-only property to access the variable's value (:attr:`_value`). 

2076 

2077 A value written as a number or a boolean is its text, as ``3.14`` or ``true``. 

2078 

2079 :returns: The value, or ``None`` if the declaration gives none. 

2080 """ 

2081 return self._value 

2082 

2083 @readonly 

2084 def Description(self) -> Nullable[str]: 

2085 """ 

2086 Read-only property to access the variable's description (:attr:`_description`). 

2087 

2088 :returns: The description, or ``None`` if the declaration gives none. 

2089 """ 

2090 return self._description 

2091 

2092 @readonly 

2093 def Options(self) -> tuple[str, ...]: 

2094 """ 

2095 Read-only property to access the values to select from, when running a pipeline by hand (:attr:`_options`). 

2096 

2097 :returns: The values, in the order the ``options`` key lists them. 

2098 """ 

2099 return self._options 

2100 

2101 @readonly 

2102 def Expand(self) -> Nullable[bool]: 

2103 """ 

2104 Read-only property to access whether variables in the value are expanded (:attr:`_expand`). 

2105 

2106 :returns: The ``expand`` key, or ``None`` if the declaration gives none - GitLab expands then. 

2107 """ 

2108 return self._expand 

2109 

2110 def __str__(self) -> str: 

2111 """ 

2112 Return the variable's name. 

2113 

2114 :returns: Name of the variable. 

2115 """ 

2116 return self._name 

2117 

2118 @classmethod 

2119 def _FromYAML(cls, name: str, declaration: Any, path: Path, line: int) -> Self: 

2120 """ 

2121 Read a variable's declaration: a value, or a mapping of the keys in :attr:`_KEYS`. 

2122 

2123 :param name: Name of the variable. 

2124 :param declaration: The declaration. 

2125 :param path: Path to the configuration file. 

2126 :param line: Line the variable's name is written at, starting at 1. 

2127 :returns: The variable. 

2128 :raises PipelineFileError: If the declaration is neither a value nor a mapping. 

2129 :raises PipelineFileError: If the mapping has a key GitLab doesn't know for a variable. |br| 

2130 The note lists the allowed keys. 

2131 :raises PipelineFileError: If key ``options`` is not a list of values, or key ``expand`` not a boolean. 

2132 """ 

2133 if declaration is None: 

2134 return cls(name, line) 

2135 elif isinstance(declaration, CommentedSeq): 

2136 ex = PipelineFileError(f"Variable '{name}' is neither a value nor a mapping.", path, line) 

2137 ex.add_note(f"Got type '{getFullyQualifiedName(declaration)}'.") 

2138 raise ex 

2139 elif not isinstance(declaration, CommentedMap): 

2140 return cls(name, line, Base._ToText(declaration)) 

2141 

2142 for key in declaration: 

2143 if key not in cls._KEYS: 

2144 ex = PipelineFileError(f"Variable '{name}' has unknown key '{key}'.", path, Base._KeyLine(declaration, key)) 

2145 ex.add_note(f"Allowed keys: {', '.join(cls._KEYS)}.") 

2146 raise ex 

2147 

2148 options = None 

2149 if (optionList := declaration.get("options", None)) is not None: 

2150 isList = isinstance(optionList, CommentedSeq) 

2151 if not isList or any(isinstance(item, (CommentedMap, CommentedSeq)) for item in optionList): 

2152 ex = PipelineFileError( 

2153 f"Key 'options' of variable '{name}' is not a list of values.", path, Base._KeyLine(declaration, "options") 

2154 ) 

2155 ex.add_note(f"Got '{Base._ToPython(optionList)}'.") 

2156 raise ex 

2157 

2158 options = [Base._ToText(option) for option in optionList] 

2159 

2160 expand = Base._ToPython(declaration.get("expand", None)) 

2161 if expand is not None and not isinstance(expand, bool): 

2162 ex = PipelineFileError( 

2163 f"Key 'expand' of variable '{name}' is not a boolean.", path, Base._KeyLine(declaration, "expand") 

2164 ) 

2165 ex.add_note(f"Got '{expand}'.") 

2166 raise ex 

2167 

2168 value = declaration.get("value", None) 

2169 description = declaration.get("description", None) 

2170 

2171 return cls( 

2172 name, line, 

2173 value=None if value is None else Base._ToText(value), 

2174 description=None if description is None else str(description), 

2175 options=options, 

2176 expand=expand 

2177 ) 

2178 

2179 @classmethod 

2180 def _FromYAMLMapping(cls, mapping: Any, owner: Nullable[str], path: Path, line: int) -> list[Self]: 

2181 """ 

2182 Read the variables of a ``variables`` key. 

2183 

2184 :param mapping: The key's value. 

2185 :param owner: The element declaring the variables, for a message, as ``job 'build'``, or ``None`` 

2186 for the top-level ``variables``. 

2187 :param path: Path to the configuration file. 

2188 :param line: Line the ``variables`` key is written at, starting at 1. 

2189 :returns: The variables, in file order. 

2190 :raises PipelineFileError: If the value is not a mapping. 

2191 :raises PipelineFileError: If a variable is malformed. 

2192 """ 

2193 if not isinstance(mapping, CommentedMap): 

2194 ex = PipelineFileError( 

2195 "Key 'variables' is not a mapping." if owner is None else f"Key 'variables' of {owner} is not a mapping.", 

2196 path, line 

2197 ) 

2198 ex.add_note(f"Got type '{getFullyQualifiedName(mapping)}'.") 

2199 raise ex 

2200 

2201 return [cls._FromYAML(str(name), value, path, Base._KeyLine(mapping, name)) for name, value in mapping.items()] 

2202 

2203 

2204@export 

2205class Need(Base[Job]): 

2206 """ 

2207 An entry of a job's ``needs``. 

2208 

2209 An entry names a job of the same pipeline, as a string or as ``job`` of a mapping; a job of another pipeline of 

2210 the parent-child hierarchy, with ``pipeline`` and ``job``; a job of another project's pipeline, with ``project``, 

2211 ``job`` and ``ref``; or, with ``pipeline`` only, another project's pipeline, whose status the job mirrors. 

2212 :attr:`Kind` says which. 

2213 """ 

2214 

2215 _PARENT_TYPE: ClassVar[ParentTypes] = Job #: A need is an entry of a job's ``needs``. 

2216 

2217 _kind: NeedKind #: What the entry refers to. 

2218 _job: Nullable[str] #: Name of the needed job. 

2219 _artifacts: bool #: ``True``, if the needed job's artifacts are downloaded. 

2220 _optional: bool #: ``True``, if the needed job may be missing in the pipeline. 

2221 _pipeline: Nullable[str] #: The other pipeline: its ID, or the project whose pipeline's status is mirrored. 

2222 _project: Nullable[str] #: Path of the other project. 

2223 _ref: Nullable[str] #: Reference of the other project, whose latest pipeline's artifacts are downloaded. 

2224 _parallel: Nullable[Parallel] #: The matrix instances of the needed job, which are needed. 

2225 

2226 _KEYS: ClassVar[tuple[str, ...]] = ( 

2227 "job", "artifacts", "optional", "pipeline", "project", "ref", "parallel" 

2228 ) #: Keys of an entry as mapping. 

2229 

2230 def __init__( 

2231 self, 

2232 job: Nullable[str], 

2233 line: int, 

2234 kind: NeedKind = NeedKind.Job, 

2235 artifacts: bool = True, 

2236 optional: bool = False, 

2237 pipeline: Nullable[str] = None, 

2238 project: Nullable[str] = None, 

2239 ref: Nullable[str] = None, 

2240 parallel: Nullable[Parallel] = None, 

2241 *, 

2242 parent: Nullable[Job] = None 

2243 ) -> None: 

2244 """ 

2245 Initializes an entry of a job's ``needs``. 

2246 

2247 :param job: Name of the needed job, or ``None`` for a need of kind :attr:`NeedKind.PipelineStatus`. 

2248 :param line: Line the entry is written at, starting at 1. 

2249 :param kind: Optional, what the entry refers to. Default: a job of the same pipeline. 

2250 :param artifacts: Optional, ``True``, if the needed job's artifacts are downloaded. Default: ``True``. 

2251 :param optional: Optional, ``True``, if the needed job may be missing in the pipeline. Default: ``False``. 

2252 :param pipeline: Optional, the other pipeline: its ID, or the project whose pipeline's status is mirrored. 

2253 Default: ``None``. 

2254 :param project: Optional, path of the other project. Default: ``None``. 

2255 :param ref: Optional, reference of the other project. Default: ``None``. 

2256 :param parallel: Optional, the matrix instances of the needed job, which are needed, which is attached to 

2257 the need. Default: ``None``, for every instance. 

2258 :param parent: Optional, reference to the job whose ``needs`` holds the entry. Default: ``None``. 

2259 :raises TypeError: If parameter 'job' is not of type :class:`str`. 

2260 :raises ValueError: If parameter 'job' is ``None``, but the kind names a job. 

2261 :raises ValueError: If parameter 'kind' is ``None``. 

2262 :raises TypeError: If parameter 'kind' is not of type :class:`NeedKind`. 

2263 :raises TypeError: If parameter 'artifacts' is not of type :class:`bool`. 

2264 :raises TypeError: If parameter 'optional' is not of type :class:`bool`. 

2265 :raises TypeError: If parameter 'pipeline' is not of type :class:`str`. 

2266 :raises ValueError: If parameter 'pipeline' is ``None``, but the kind refers to another pipeline. 

2267 :raises TypeError: If parameter 'project' is not of type :class:`str`. 

2268 :raises ValueError: If parameter 'project' is ``None``, but the kind refers to another project's job. 

2269 :raises TypeError: If parameter 'ref' is not of type :class:`str`. 

2270 :raises ValueError: If parameter 'ref' is ``None``, but the kind refers to another project's job. 

2271 :raises TypeError: If parameter 'parallel' is not of type :class:`Parallel`. 

2272 """ 

2273 super().__init__(line, parent=parent) 

2274 

2275 if kind is None: 

2276 raise ValueError("Parameter 'kind' is None.") 

2277 elif not isinstance(kind, NeedKind): 

2278 ex = TypeError("Parameter 'kind' is not of type 'NeedKind'.") 

2279 ex.add_note(f"Got type '{getFullyQualifiedName(kind)}'.") 

2280 raise ex 

2281 

2282 for parameterName, text in ( 

2283 ("job", job), 

2284 ("pipeline", pipeline), 

2285 ("project", project), 

2286 ("ref", ref) 

2287 ): 

2288 if text is not None and not isinstance(text, str): 

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

2290 ex.add_note(f"Got type '{getFullyQualifiedName(text)}'.") 

2291 raise ex 

2292 

2293 for parameterName, flag in ( 

2294 ("artifacts", artifacts), 

2295 ("optional", optional) 

2296 ): 

2297 if not isinstance(flag, bool): 

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

2299 ex.add_note(f"Got type '{getFullyQualifiedName(flag)}'.") 

2300 raise ex 

2301 

2302 for parameterName, text, kinds in ( 

2303 ("job", job, (NeedKind.Job, NeedKind.PipelineJob, NeedKind.ProjectJob)), 

2304 ("pipeline", pipeline, (NeedKind.PipelineJob, NeedKind.PipelineStatus)), 

2305 ("project", project, (NeedKind.ProjectJob, )), 

2306 ("ref", ref, (NeedKind.ProjectJob, )) 

2307 ): 

2308 if text is None and kind in kinds: 

2309 ex = ValueError(f"Parameter '{parameterName}' is None.") 

2310 ex.add_note(f"A need of kind '{kind.name}' needs it.") 

2311 raise ex 

2312 

2313 self._kind = kind 

2314 self._job = job 

2315 self._artifacts = artifacts 

2316 self._optional = optional 

2317 self._pipeline = pipeline 

2318 self._project = project 

2319 self._ref = ref 

2320 self._parallel = None 

2321 

2322 if parallel is not None: 

2323 if not isinstance(parallel, Parallel): 

2324 ex = TypeError("Parameter 'parallel' is not of type 'Parallel'.") 

2325 ex.add_note(f"Got type '{getFullyQualifiedName(parallel)}'.") 

2326 raise ex 

2327 

2328 self._parallel = parallel 

2329 parallel.Parent = self 

2330 

2331 if parent is not None: 

2332 if parent._needs is None: 2332 ↛ 2335line 2332 didn't jump to line 2335 because the condition on line 2332 was always true

2333 parent._needs = [] 

2334 

2335 parent._needs.append(self) 

2336 

2337 @Base.Parent.setter 

2338 def Parent(self, value: Job) -> None: 

2339 Base.Parent.fset(self, value) 

2340 

2341 if self._parallel is not None: 

2342 self._parallel.Parent = self 

2343 

2344 @readonly 

2345 def Parallel(self) -> Nullable[Parallel]: 

2346 """ 

2347 Read-only property to access the matrix instances of the needed job, which are needed (:attr:`_parallel`). 

2348 

2349 :returns: The instances' matrix, or ``None`` if every instance is needed. 

2350 """ 

2351 return self._parallel 

2352 

2353 @readonly 

2354 def Kind(self) -> NeedKind: 

2355 """ 

2356 Read-only property to access what the entry refers to (:attr:`_kind`). 

2357 

2358 :returns: The kind of the need. 

2359 """ 

2360 return self._kind 

2361 

2362 @readonly 

2363 def JobName(self) -> Nullable[str]: 

2364 """ 

2365 Read-only property to access the name of the needed job (:attr:`_job`). 

2366 

2367 :returns: Name of the job, or ``None`` for a need mirroring another pipeline's status. 

2368 """ 

2369 return self._job 

2370 

2371 @readonly 

2372 def NeededJob(self) -> Nullable[Job]: 

2373 """ 

2374 Read-only property to return the needed job of the same file. 

2375 

2376 :returns: The job, or ``None`` for a need of another pipeline, or of a job the file doesn't have. 

2377 """ 

2378 if self._kind is not NeedKind.Job or self._pipelineFile is None: 

2379 return None 

2380 

2381 return self._pipelineFile._jobs.get(self._job, None) 

2382 

2383 @readonly 

2384 def Artifacts(self) -> bool: 

2385 """ 

2386 Read-only property to access whether the needed job's artifacts are downloaded (:attr:`_artifacts`). 

2387 

2388 :returns: ``True``, if the artifacts are downloaded. 

2389 """ 

2390 return self._artifacts 

2391 

2392 @readonly 

2393 def IsOptional(self) -> bool: 

2394 """ 

2395 Read-only property to access whether the needed job may be missing in the pipeline (:attr:`_optional`). 

2396 

2397 :returns: ``True``, if the need is optional. 

2398 """ 

2399 return self._optional 

2400 

2401 @readonly 

2402 def Pipeline(self) -> Nullable[str]: 

2403 """ 

2404 Read-only property to access the other pipeline (:attr:`_pipeline`). 

2405 

2406 :returns: The pipeline's ID, as ``$PARENT_PIPELINE_ID``, or the project whose pipeline's status is mirrored, or 

2407 ``None`` for a need of the same pipeline or of another project's job. 

2408 """ 

2409 return self._pipeline 

2410 

2411 @readonly 

2412 def Project(self) -> Nullable[str]: 

2413 """ 

2414 Read-only property to access the path of the other project (:attr:`_project`). 

2415 

2416 :returns: The project's path, or ``None`` for a need of a job of the same project. 

2417 """ 

2418 return self._project 

2419 

2420 @readonly 

2421 def Ref(self) -> Nullable[str]: 

2422 """ 

2423 Read-only property to access the reference of the other project (:attr:`_ref`). 

2424 

2425 :returns: The reference, or ``None`` for a need of a job of the same project. 

2426 """ 

2427 return self._ref 

2428 

2429 def __str__(self) -> str: 

2430 """ 

2431 Return the needed job's name, or the pipeline whose status is mirrored. 

2432 

2433 :returns: The job's name, prefixed by the project for another project's job. 

2434 """ 

2435 if self._kind is NeedKind.PipelineStatus: 

2436 return f"pipeline {self._pipeline}" 

2437 elif self._kind is NeedKind.ProjectJob: 

2438 return f"{self._project}: {self._job}" 

2439 

2440 return self._job 

2441 

2442 @classmethod 

2443 def _FromYAML(cls, entry: Any, jobName: str, path: Path, line: int) -> Self: 

2444 """ 

2445 Read an entry of a job's ``needs``: a job's name, or a mapping of the keys in :attr:`_KEYS`. 

2446 

2447 :param entry: The entry. 

2448 :param jobName: Name of the job, whose ``needs`` holds the entry, for a message. 

2449 :param path: Path to the configuration file. 

2450 :param line: Line the entry is written at, starting at 1. 

2451 :returns: The need. 

2452 :raises PipelineFileError: If the entry is neither a job's name nor a mapping. 

2453 :raises PipelineFileError: If the mapping has a key GitLab doesn't know for a need. |br| 

2454 The note lists the allowed keys. 

2455 :raises PipelineFileError: If key ``artifacts`` or ``optional`` is not a boolean. 

2456 :raises PipelineFileError: If the mapping lacks a key its kind needs: ``job``, or ``ref`` with ``project``. 

2457 """ 

2458 if isinstance(entry, CommentedSeq) or entry is None: 

2459 ex = PipelineFileError(f"Need of job '{jobName}' is neither a job's name nor a mapping.", path, line) 

2460 ex.add_note(f"Got type '{getFullyQualifiedName(entry)}'.") 

2461 raise ex 

2462 elif not isinstance(entry, CommentedMap): 

2463 return cls(Base._ToText(entry), line) 

2464 

2465 for key in entry: 

2466 if key not in cls._KEYS: 

2467 ex = PipelineFileError(f"Need of job '{jobName}' has unknown key '{key}'.", path, Base._KeyLine(entry, key)) 

2468 ex.add_note(f"Allowed keys: {', '.join(cls._KEYS)}.") 

2469 raise ex 

2470 

2471 flags = {} 

2472 for key, default in ( 

2473 ("artifacts", True), 

2474 ("optional", False) 

2475 ): 

2476 flags[key] = Base._ToPython(entry.get(key, default)) 

2477 if not isinstance(flags[key], bool): 

2478 ex = PipelineFileError( 

2479 f"Key '{key}' of a need of job '{jobName}' is not a boolean.", path, Base._KeyLine(entry, key) 

2480 ) 

2481 ex.add_note(f"Got '{flags[key]}'.") 

2482 raise ex 

2483 

2484 texts = {} 

2485 for key in ("job", "pipeline", "project", "ref"): 

2486 texts[key] = None if entry.get(key, None) is None else Base._ToText(entry[key]) 

2487 

2488 if texts["project"] is not None: 

2489 kind = NeedKind.ProjectJob 

2490 elif texts["pipeline"] is not None: 

2491 kind = NeedKind.PipelineStatus if texts["job"] is None else NeedKind.PipelineJob 

2492 else: 

2493 kind = NeedKind.Job 

2494 

2495 if texts["job"] is None and kind is not NeedKind.PipelineStatus: 

2496 raise PipelineFileError(f"Need of job '{jobName}' has no 'job' key.", path, line) 

2497 elif texts["ref"] is None and kind is NeedKind.ProjectJob: 

2498 raise PipelineFileError(f"Need of job '{jobName}' with key 'project' has no 'ref' key.", path, line) 

2499 

2500 parallel = None 

2501 if "parallel" in entry: 

2502 keyLine = Base._KeyLine(entry, "parallel") 

2503 parallel = Parallel._FromYAML(entry["parallel"], f"a need of job '{jobName}'", path, keyLine) 

2504 if parallel._count is not None: 

2505 raise PipelineFileError(f"Key 'parallel' of a need of job '{jobName}' has no 'matrix' key.", path, line) 

2506 

2507 return cls( 

2508 texts["job"], line, kind, flags["artifacts"], flags["optional"], 

2509 texts["pipeline"], texts["project"], texts["ref"], parallel 

2510 ) 

2511 

2512 @classmethod 

2513 def _FromYAMLEntries(cls, value: Any, jobName: str, path: Path, line: int) -> list[Self]: 

2514 """ 

2515 Read a job's ``needs``: a list of entries, or a single mapping, as ``pipeline: other/project``. 

2516 

2517 :param value: The key's value. 

2518 :param jobName: Name of the job, for a message. 

2519 :param path: Path to the configuration file. 

2520 :param line: Line the ``needs`` key is written at, starting at 1. 

2521 :returns: The needs, in file order. 

2522 :raises PipelineFileError: If the value is neither a list nor a mapping. 

2523 :raises PipelineFileError: If an entry is malformed. 

2524 """ 

2525 if isinstance(value, CommentedMap): 

2526 return [cls._FromYAML(value, jobName, path, line)] 

2527 elif not isinstance(value, CommentedSeq): 

2528 ex = PipelineFileError(f"Key 'needs' of job '{jobName}' is neither a list nor a mapping.", path, line) 

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

2530 raise ex 

2531 

2532 return [cls._FromYAML(entry, jobName, path, Base._ItemLine(value, index)) for index, entry in enumerate(value)] 

2533 

2534 

2535@export 

2536class Workflow(Base[PipelineFile]): 

2537 """The ``workflow`` key of a configuration file: the pipeline's name and the rules deciding whether it is created.""" 

2538 

2539 _PARENT_TYPE: ClassVar[ParentTypes] = PipelineFile #: A workflow belongs to a configuration file. 

2540 

2541 _name: Nullable[str] #: Name of the pipeline. 

2542 _rules: list[Rule] #: Rules deciding whether a pipeline is created. 

2543 

2544 def __init__( 

2545 self, 

2546 line: int, 

2547 name: Nullable[str] = None, 

2548 rules: Nullable[Iterable[Rule]] = None, 

2549 *, 

2550 parent: Nullable[PipelineFile] = None 

2551 ) -> None: 

2552 """ 

2553 Initializes the ``workflow`` key. 

2554 

2555 :param line: Line the ``workflow`` key is written at, starting at 1. 

2556 :param name: Optional, name of the pipeline. Default: ``None``. 

2557 :param rules: Optional, rules deciding whether a pipeline is created, which are attached to the workflow. 

2558 Default: ``None``. 

2559 :param parent: Optional, reference to the configuration file. Default: ``None``. 

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

2561 :raises TypeError: If an element of parameter 'rules' is not of type :class:`Rule`. 

2562 """ 

2563 super().__init__(line, parent=parent) 

2564 

2565 if name is not None and not isinstance(name, str): 

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

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

2568 raise ex 

2569 

2570 self._name = name 

2571 self._rules = ruleList = [] 

2572 

2573 if rules is not None: 

2574 for rule in rules: 

2575 if not isinstance(rule, Rule): 

2576 ex = TypeError("An element of parameter 'rules' is not of type 'Rule'.") 

2577 ex.add_note(f"Got type '{getFullyQualifiedName(rule)}'.") 

2578 raise ex 

2579 

2580 ruleList.append(rule) 

2581 rule.Parent = self 

2582 

2583 if parent is not None: 

2584 parent._workflow = self 

2585 

2586 @Base.Parent.setter 

2587 def Parent(self, value: PipelineFile) -> None: 

2588 Base.Parent.fset(self, value) 

2589 

2590 for rule in self._rules: 

2591 rule.Parent = self 

2592 

2593 @readonly 

2594 def Name(self) -> Nullable[str]: 

2595 """ 

2596 Read-only property to access the pipeline's name (:attr:`_name`). 

2597 

2598 :returns: The ``name`` key, as written, or ``None`` if the workflow gives none. 

2599 """ 

2600 return self._name 

2601 

2602 @readonly 

2603 def Rules(self) -> list[Rule]: 

2604 """ 

2605 Read-only property to access the rules deciding whether a pipeline is created (:attr:`_rules`). 

2606 

2607 :returns: The rules, in the order GitLab evaluates them. 

2608 """ 

2609 return self._rules 

2610 

2611 @classmethod 

2612 def _FromYAML(cls, mapping: Any, path: Path, line: int) -> Self: 

2613 """ 

2614 Read the ``workflow`` key. 

2615 

2616 :param mapping: The key's value. 

2617 :param path: Path to the configuration file. 

2618 :param line: Line the ``workflow`` key is written at, starting at 1. 

2619 :returns: The workflow. 

2620 :raises PipelineFileError: If the value is not a mapping. 

2621 :raises PipelineFileError: If a rule is malformed. 

2622 """ 

2623 if not isinstance(mapping, CommentedMap): 

2624 ex = PipelineFileError("Key 'workflow' is not a mapping.", path, line) 

2625 ex.add_note(f"Got type '{getFullyQualifiedName(mapping)}'.") 

2626 raise ex 

2627 

2628 rules = None 

2629 if "rules" in mapping: 

2630 rules = Rule._FromYAMLEntries(mapping["rules"], "the workflow", path, Base._KeyLine(mapping, "rules")) 

2631 

2632 name = mapping.get("name", None) 

2633 return cls(line, None if name is None else Base._ToText(name), rules) 

2634 

2635 

2636@export 

2637class Trigger(Base[Job]): 

2638 """ 

2639 A job's ``trigger``: the child pipeline, or the other project's pipeline, the job starts. 

2640 

2641 A child pipeline runs the configuration of the files in :attr:`Includes`; another project's pipeline runs that 

2642 project's configuration on :attr:`Branch`. 

2643 """ 

2644 

2645 _PARENT_TYPE: ClassVar[ParentTypes] = Job #: A trigger belongs to a job. 

2646 

2647 _project: Nullable[str] #: Path of the other project, whose pipeline is started. 

2648 _branch: Nullable[str] #: Branch of the other project. 

2649 _strategy: Nullable[TriggerStrategy] #: How the job's status follows the started pipeline. 

2650 _includes: list[Include] #: Files of the child pipeline's configuration. 

2651 

2652 def __init__( 

2653 self, 

2654 line: int, 

2655 project: Nullable[str] = None, 

2656 branch: Nullable[str] = None, 

2657 strategy: Nullable[TriggerStrategy] = None, 

2658 includes: Nullable[Iterable[Include]] = None, 

2659 *, 

2660 parent: Nullable[Job] = None 

2661 ) -> None: 

2662 """ 

2663 Initializes a job's ``trigger``. 

2664 

2665 :param line: Line the ``trigger`` key is written at, starting at 1. 

2666 :param project: Optional, path of the other project, whose pipeline is started. Default: ``None``. 

2667 :param branch: Optional, branch of the other project. Default: ``None``, for its default branch. 

2668 :param strategy: Optional, how the job's status follows the started pipeline. Default: ``None``, for a job 

2669 succeeding as soon as the pipeline is created. 

2670 :param includes: Optional, files of the child pipeline's configuration, which are attached to the trigger. 

2671 Default: ``None``. 

2672 :param parent: Optional, reference to the job. Default: ``None``. 

2673 :raises TypeError: If parameter 'project' is not of type :class:`str`. 

2674 :raises TypeError: If parameter 'branch' is not of type :class:`str`. 

2675 :raises TypeError: If parameter 'strategy' is not of type :class:`TriggerStrategy`. 

2676 :raises TypeError: If an element of parameter 'includes' is not of type :class:`Include`. 

2677 """ 

2678 super().__init__(line, parent=parent) 

2679 

2680 for parameterName, text in ( 

2681 ("project", project), 

2682 ("branch", branch) 

2683 ): 

2684 if text is not None and not isinstance(text, str): 

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

2686 ex.add_note(f"Got type '{getFullyQualifiedName(text)}'.") 

2687 raise ex 

2688 

2689 if strategy is not None and not isinstance(strategy, TriggerStrategy): 

2690 ex = TypeError("Parameter 'strategy' is not of type 'TriggerStrategy'.") 

2691 ex.add_note(f"Got type '{getFullyQualifiedName(strategy)}'.") 

2692 raise ex 

2693 

2694 self._project = project 

2695 self._branch = branch 

2696 self._strategy = strategy 

2697 self._includes = includeList = [] 

2698 

2699 if includes is not None: 

2700 for include in includes: 

2701 if not isinstance(include, Include): 

2702 ex = TypeError("An element of parameter 'includes' is not of type 'Include'.") 

2703 ex.add_note(f"Got type '{getFullyQualifiedName(include)}'.") 

2704 raise ex 

2705 

2706 includeList.append(include) 

2707 include.Parent = self 

2708 

2709 if parent is not None: 

2710 parent._trigger = self 

2711 

2712 @Base.Parent.setter 

2713 def Parent(self, value: Job) -> None: 

2714 Base.Parent.fset(self, value) 

2715 

2716 for include in self._includes: 

2717 include.Parent = self 

2718 

2719 @readonly 

2720 def Project(self) -> Nullable[str]: 

2721 """ 

2722 Read-only property to access the path of the other project, whose pipeline is started (:attr:`_project`). 

2723 

2724 :returns: The project's path, or ``None`` for a child pipeline. 

2725 """ 

2726 return self._project 

2727 

2728 @readonly 

2729 def Branch(self) -> Nullable[str]: 

2730 """ 

2731 Read-only property to access the branch of the other project (:attr:`_branch`). 

2732 

2733 :returns: The branch, or ``None`` for the project's default branch. 

2734 """ 

2735 return self._branch 

2736 

2737 @readonly 

2738 def Strategy(self) -> Nullable[TriggerStrategy]: 

2739 """ 

2740 Read-only property to access how the job's status follows the started pipeline (:attr:`_strategy`). 

2741 

2742 :returns: The strategy, or ``None`` if the trigger doesn't say. 

2743 """ 

2744 return self._strategy 

2745 

2746 @readonly 

2747 def Includes(self) -> list[Include]: 

2748 """ 

2749 Read-only property to access the files of the child pipeline's configuration (:attr:`_includes`). 

2750 

2751 :returns: The files, in file order; empty for another project's pipeline. 

2752 """ 

2753 return self._includes 

2754 

2755 @readonly 

2756 def IsChildPipeline(self) -> bool: 

2757 """ 

2758 Read-only property to return whether the job starts a child pipeline. 

2759 

2760 :returns: ``True``, if the trigger includes files; ``False`` for another project's pipeline. 

2761 """ 

2762 return len(self._includes) > 0 

2763 

2764 @classmethod 

2765 def _FromYAML(cls, value: Any, jobName: str, path: Path, line: int) -> Self: 

2766 """ 

2767 Read a job's ``trigger``: another project's path, or a mapping with ``include`` or ``project``. 

2768 

2769 :param value: The key's value. 

2770 :param jobName: Name of the job, for a message. 

2771 :param path: Path to the configuration file. 

2772 :param line: Line the ``trigger`` key is written at, starting at 1. 

2773 :returns: The trigger. 

2774 :raises PipelineFileError: If the value is neither a project's path nor a mapping with ``include`` or 

2775 ``project``. 

2776 :raises PipelineFileError: If key ``strategy`` is not a value GitLab knows. |br| 

2777 The note lists the allowed values. 

2778 :raises PipelineFileError: If an include is malformed. 

2779 """ 

2780 if isinstance(value, (str, ScalarString)): 

2781 return cls(line, project=Base._ToText(value)) 

2782 elif not isinstance(value, CommentedMap) or ("include" not in value and "project" not in value): 

2783 ex = PipelineFileError( 

2784 f"Key 'trigger' of job '{jobName}' is neither a project nor a mapping with 'include' or 'project'.", path, line 

2785 ) 

2786 ex.add_note(f"Got '{Base._ToPython(value)}'.") 

2787 raise ex 

2788 

2789 strategy = None 

2790 if (strategyValue := value.get("strategy", None)) is not None: 

2791 try: 

2792 strategy = TriggerStrategy.Parse(Base._ToText(strategyValue)) 

2793 except ValueError as cause: 

2794 ex = PipelineFileError( 

2795 f"Key 'strategy' of the trigger of job '{jobName}' is not a known value.", 

2796 path, Base._KeyLine(value, "strategy") 

2797 ) 

2798 ex.add_note(f"Got '{strategyValue}'.") 

2799 ex.add_note(f"Allowed values: {', '.join(member.value for member in TriggerStrategy)}.") 

2800 raise ex from cause 

2801 

2802 includes = None 

2803 if "include" in value: 

2804 includes = Include._FromYAMLEntries(value["include"], path, Base._KeyLine(value, "include")) 

2805 

2806 project = value.get("project", None) 

2807 branch = value.get("branch", None) 

2808 return cls( 

2809 line, 

2810 project=None if project is None else Base._ToText(project), 

2811 branch=None if branch is None else Base._ToText(branch), 

2812 strategy=strategy, 

2813 includes=includes 

2814 ) 

2815 

2816 

2817@export 

2818class Include(Base[Union[PipelineFile, Trigger]]): 

2819 """ 

2820 An entry of ``include``, which adds the configuration of other files. 

2821 

2822 :attr:`Kind` says where the files come from, :attr:`Location` names them: a path of the same repository, a URL, a 

2823 template's name, a component's reference, the path of another project, whose files are in :attr:`Files`, or the 

2824 artifact of the job :attr:`ArtifactJob`. 

2825 """ 

2826 

2827 _PARENT_TYPE: ClassVar[ParentTypes] = (PipelineFile, Trigger) #: Included by a configuration file or a trigger. 

2828 

2829 _kind: IncludeKind #: Where the included files come from. 

2830 _location: str #: Path, URL, template's name, component's reference, or project's path. 

2831 _ref: Nullable[str] #: Reference of the project the files are read from. 

2832 _files: tuple[str, ...] #: Paths of the files of another project. 

2833 _job: Nullable[str] #: Name of the job, whose artifact is included. 

2834 _inputs: dict[str, ValueT] #: Inputs passed to the included files, by name. 

2835 _rules: list[Rule] #: Rules deciding whether the files are included. 

2836 

2837 _KINDS: ClassVar[tuple[str, ...]] = tuple(member.value for member in IncludeKind) #: Keys naming an include's kind. 

2838 

2839 def __init__( 

2840 self, 

2841 kind: IncludeKind, 

2842 location: str, 

2843 line: int, 

2844 files: Nullable[Iterable[str]] = None, 

2845 ref: Nullable[str] = None, 

2846 inputs: Nullable[Mapping[str, ValueT]] = None, 

2847 rules: Nullable[Iterable[Rule]] = None, 

2848 job: Nullable[str] = None, 

2849 *, 

2850 parent: Nullable[Union[PipelineFile, Trigger]] = None 

2851 ) -> None: 

2852 """ 

2853 Initializes an entry of ``include``. 

2854 

2855 :param kind: Where the included files come from. 

2856 :param location: Path, URL, template's name, component's reference, or - for another project - its path. 

2857 :param line: Line the entry is written at, starting at 1. 

2858 :param files: Optional, paths of the files of another project. Default: ``None``. 

2859 :param ref: Optional, reference of the project the files are read from. Default: ``None``. 

2860 :param inputs: Optional, inputs passed to the included files, by name. Default: ``None``. 

2861 :param rules: Optional, rules deciding whether the files are included, which are attached to the entry. 

2862 Default: ``None``. 

2863 :param job: Optional, name of the job, whose artifact is included. Default: ``None``. 

2864 :param parent: Optional, reference to the configuration file or the trigger. Default: ``None``. 

2865 :raises ValueError: If parameter 'kind' is ``None``. 

2866 :raises TypeError: If parameter 'kind' is not of type :class:`IncludeKind`. 

2867 :raises ValueError: If parameter 'location' is ``None``. 

2868 :raises TypeError: If parameter 'location' is not of type :class:`str`. 

2869 :raises ValueError: If parameter 'location' is empty. 

2870 :raises TypeError: If an element of parameter 'files' is not of type :class:`str`. 

2871 :raises TypeError: If parameter 'ref' is not of type :class:`str`. 

2872 :raises TypeError: If an element of parameter 'rules' is not of type :class:`Rule`. 

2873 :raises TypeError: If parameter 'job' is not of type :class:`str`. 

2874 """ 

2875 super().__init__(line, parent=parent) 

2876 

2877 if kind is None: 

2878 raise ValueError("Parameter 'kind' is None.") 

2879 elif not isinstance(kind, IncludeKind): 

2880 ex = TypeError("Parameter 'kind' is not of type 'IncludeKind'.") 

2881 ex.add_note(f"Got type '{getFullyQualifiedName(kind)}'.") 

2882 raise ex 

2883 

2884 if location is None: 

2885 raise ValueError("Parameter 'location' is None.") 

2886 elif not isinstance(location, str): 

2887 ex = TypeError("Parameter 'location' is not of type 'str'.") 

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

2889 raise ex 

2890 elif location == "": 

2891 raise ValueError("Parameter 'location' is empty.") 

2892 

2893 for parameterName, text in ( 

2894 ("ref", ref), 

2895 ("job", job) 

2896 ): 

2897 if text is not None and not isinstance(text, str): 

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

2899 ex.add_note(f"Got type '{getFullyQualifiedName(text)}'.") 

2900 raise ex 

2901 

2902 self._files = () if files is None else tuple(files) 

2903 for file in self._files: 

2904 if not isinstance(file, str): 

2905 ex = TypeError("An element of parameter 'files' is not of type 'str'.") 

2906 ex.add_note(f"Got type '{getFullyQualifiedName(file)}'.") 

2907 raise ex 

2908 

2909 self._kind = kind 

2910 self._location = location 

2911 self._ref = ref 

2912 self._job = job 

2913 self._inputs = {} if inputs is None else dict(inputs) 

2914 self._rules = ruleList = [] 

2915 

2916 if rules is not None: 

2917 for rule in rules: 

2918 if not isinstance(rule, Rule): 

2919 ex = TypeError("An element of parameter 'rules' is not of type 'Rule'.") 

2920 ex.add_note(f"Got type '{getFullyQualifiedName(rule)}'.") 

2921 raise ex 

2922 

2923 ruleList.append(rule) 

2924 rule.Parent = self 

2925 

2926 if parent is not None: 

2927 parent._includes.append(self) 

2928 

2929 @Base.Parent.setter 

2930 def Parent(self, value: PipelineFile) -> None: 

2931 Base.Parent.fset(self, value) 

2932 

2933 for rule in self._rules: 

2934 rule.Parent = self 

2935 

2936 @readonly 

2937 def Kind(self) -> IncludeKind: 

2938 """ 

2939 Read-only property to access where the included files come from (:attr:`_kind`). 

2940 

2941 :returns: The kind of the include. 

2942 """ 

2943 return self._kind 

2944 

2945 @readonly 

2946 def Location(self) -> str: 

2947 """ 

2948 Read-only property to access what the entry includes (:attr:`_location`). 

2949 

2950 :returns: A path, a URL, a template's name, a component's reference, or another project's path, as written. 

2951 """ 

2952 return self._location 

2953 

2954 @readonly 

2955 def Ref(self) -> Nullable[str]: 

2956 """ 

2957 Read-only property to access the reference of the project the files are read from (:attr:`_ref`). 

2958 

2959 :returns: The ``ref`` key, or ``None`` - the project's default branch then. 

2960 """ 

2961 return self._ref 

2962 

2963 @readonly 

2964 def Files(self) -> tuple[str, ...]: 

2965 """ 

2966 Read-only property to access the paths of the files of another project (:attr:`_files`). 

2967 

2968 :returns: The paths of ``file``, in file order. 

2969 """ 

2970 return self._files 

2971 

2972 @readonly 

2973 def ArtifactJob(self) -> Nullable[str]: 

2974 """ 

2975 Read-only property to access the name of the job, whose artifact is included (:attr:`_job`). 

2976 

2977 :returns: The ``job`` key of an artifact's include, or ``None``. 

2978 """ 

2979 return self._job 

2980 

2981 @readonly 

2982 def Inputs(self) -> dict[str, ValueT]: 

2983 """ 

2984 Read-only property to access the inputs passed to the included files (:attr:`_inputs`). 

2985 

2986 :returns: The inputs' values, by name, with the types they are written with. 

2987 """ 

2988 return self._inputs 

2989 

2990 @readonly 

2991 def Rules(self) -> list[Rule]: 

2992 """ 

2993 Read-only property to access the rules deciding whether the files are included (:attr:`_rules`). 

2994 

2995 :returns: The rules, in the order GitLab evaluates them. 

2996 """ 

2997 return self._rules 

2998 

2999 def __str__(self) -> str: 

3000 """ 

3001 Return the include's kind and location. 

3002 

3003 :returns: The kind and the location, as ``local: /ci/build.yml``. 

3004 """ 

3005 return f"{self._kind.value}: {self._location}" 

3006 

3007 @classmethod 

3008 def _FromYAML(cls, entry: Any, path: Path, line: int) -> Self: 

3009 """ 

3010 Read an entry of ``include``: a path or a URL, or a mapping with one key of :attr:`_KINDS`. 

3011 

3012 :param entry: The entry. 

3013 :param path: Path to the configuration file. 

3014 :param line: Line the entry is written at, starting at 1. 

3015 :returns: The include. 

3016 :raises PipelineFileError: If the entry is neither a string nor a mapping. 

3017 :raises PipelineFileError: If the mapping has none, or more than one, of the keys of :attr:`_KINDS`. 

3018 :raises PipelineFileError: If key ``file`` of another project's include is missing, or not a path or a list. 

3019 :raises PipelineFileError: If key ``inputs`` is not a mapping. 

3020 :raises PipelineFileError: If a rule is malformed. 

3021 """ 

3022 if isinstance(entry, CommentedSeq) or entry is None: 

3023 ex = PipelineFileError("Include is neither a path nor a mapping.", path, line) 

3024 ex.add_note(f"Got type '{getFullyQualifiedName(entry)}'.") 

3025 raise ex 

3026 elif not isinstance(entry, CommentedMap): 

3027 location = Base._ToText(entry) 

3028 kind = IncludeKind.Remote if location.startswith(("https://", "http://")) else IncludeKind.Local 

3029 return cls(kind, location, line) 

3030 

3031 kinds = [key for key in cls._KINDS if key in entry] 

3032 if len(kinds) != 1: 

3033 count = "none" if len(kinds) == 0 else "more than one" 

3034 ex = PipelineFileError(f"Include has {count} of its kinds' keys.", path, line) 

3035 ex.add_note(f"Kinds: {', '.join(cls._KINDS)}.") 

3036 raise ex 

3037 

3038 kind = IncludeKind(kinds[0]) 

3039 files = None 

3040 if kind is IncludeKind.Project: 

3041 if (fileValue := entry.get("file", None)) is None: 

3042 raise PipelineFileError("Include of another project has no 'file' key.", path, line) 

3043 elif isinstance(fileValue, CommentedMap): 

3044 ex = PipelineFileError("Key 'file' of an include is neither a path nor a list.", path, line) 

3045 ex.add_note(f"Got type '{getFullyQualifiedName(fileValue)}'.") 

3046 raise ex 

3047 

3048 fileList = fileValue if isinstance(fileValue, CommentedSeq) else [fileValue] 

3049 files = [Base._ToText(file) for file in fileList] 

3050 

3051 inputs = entry.get("inputs", None) 

3052 if inputs is not None and not isinstance(inputs, CommentedMap): 

3053 ex = PipelineFileError("Key 'inputs' of an include is not a mapping.", path, Base._KeyLine(entry, "inputs")) 

3054 ex.add_note(f"Got type '{getFullyQualifiedName(inputs)}'.") 

3055 raise ex 

3056 

3057 rules = None 

3058 if "rules" in entry: 

3059 rules = Rule._FromYAMLEntries(entry["rules"], "an include", path, Base._KeyLine(entry, "rules")) 

3060 

3061 ref = entry.get("ref", None) 

3062 job = entry.get("job", None) 

3063 return cls( 

3064 kind, Base._ToText(entry[kinds[0]]), line, 

3065 files=files, 

3066 ref=None if ref is None else Base._ToText(ref), 

3067 inputs=None if inputs is None else Base._ToPython(inputs), 

3068 rules=rules, 

3069 job=None if job is None else Base._ToText(job) 

3070 ) 

3071 

3072 @classmethod 

3073 def _FromYAMLEntries(cls, value: Any, path: Path, line: int) -> list[Self]: 

3074 """ 

3075 Read the ``include`` key: an entry, or a list of entries. 

3076 

3077 :param value: The key's value. 

3078 :param path: Path to the configuration file. 

3079 :param line: Line the ``include`` key is written at, starting at 1. 

3080 :returns: The includes, in file order. 

3081 :raises PipelineFileError: If an entry is malformed. 

3082 """ 

3083 if not isinstance(value, CommentedSeq): 

3084 return [cls._FromYAML(value, path, line)] 

3085 

3086 return [cls._FromYAML(entry, path, Base._ItemLine(value, index)) for index, entry in enumerate(value)] 

3087 

3088 

3089@export 

3090class Rule(Base[Union[Job, Workflow, Include]]): 

3091 """ 

3092 A rule of ``rules``, deciding whether a job is added to a pipeline, a pipeline is created, or a file is included. 

3093 

3094 GitLab evaluates the rules in order; the first one matching decides. A rule matches if its :attr:`Condition`, its 

3095 :attr:`Changes` and its :attr:`Exists` match, as far as it has them. 

3096 """ 

3097 

3098 _PARENT_TYPE: ClassVar[ParentTypes] = (Job, Workflow, Include) #: A rule belongs to a job, a workflow or an include. 

3099 

3100 _condition: Nullable[str] #: Expression of the rule's ``if``. 

3101 _changes: tuple[str, ...] #: Paths of the rule's ``changes``. 

3102 _compareTo: Nullable[str] #: Reference ``changes`` is compared to. 

3103 _exists: tuple[str, ...] #: Paths of the rule's ``exists``. 

3104 _when: Nullable[RuleOutcome] #: When the job runs, if the rule matches. 

3105 _allowFailure: Nullable[bool] #: ``True``, if the pipeline continues when the job fails, if the rule matches. 

3106 _variables: dict[str, str] #: Variables set, if the rule matches, by name. 

3107 

3108 def __init__( 

3109 self, 

3110 line: int, 

3111 condition: Nullable[str] = None, 

3112 changes: Nullable[Iterable[str]] = None, 

3113 compareTo: Nullable[str] = None, 

3114 exists: Nullable[Iterable[str]] = None, 

3115 when: Nullable[RuleOutcome] = None, 

3116 allowFailure: Nullable[bool] = None, 

3117 variables: Nullable[Mapping[str, str]] = None, 

3118 *, 

3119 parent: Nullable[Union[Job, Workflow, Include]] = None 

3120 ) -> None: 

3121 """ 

3122 Initializes a rule. 

3123 

3124 :param line: Line the rule is written at, starting at 1. 

3125 :param condition: Optional, expression of the rule's ``if``. Default: ``None``. 

3126 :param changes: Optional, paths of the rule's ``changes``. Default: ``None``. 

3127 :param compareTo: Optional, reference ``changes`` is compared to. Default: ``None``. 

3128 :param exists: Optional, paths of the rule's ``exists``. Default: ``None``. 

3129 :param when: Optional, when the job runs, if the rule matches. Default: ``None``. 

3130 :param allowFailure: Optional, ``True``, if the pipeline continues when the job fails. Default: ``None``. 

3131 :param variables: Optional, variables set, if the rule matches, by name. Default: ``None``. 

3132 :param parent: Optional, reference to the job, workflow or include the rule belongs to. Default: ``None``. 

3133 :raises TypeError: If parameter 'condition' is not of type :class:`str`. 

3134 :raises TypeError: If an element of parameter 'changes' is not of type :class:`str`. 

3135 :raises TypeError: If parameter 'compareTo' is not of type :class:`str`. 

3136 :raises TypeError: If an element of parameter 'exists' is not of type :class:`str`. 

3137 :raises TypeError: If parameter 'when' is not of type :class:`~pyTooling.CI.RuleOutcome`. 

3138 :raises TypeError: If parameter 'allowFailure' is not of type :class:`bool`. 

3139 """ 

3140 super().__init__(line, parent=parent) 

3141 

3142 for parameterName, text in ( 

3143 ("condition", condition), 

3144 ("compareTo", compareTo) 

3145 ): 

3146 if text is not None and not isinstance(text, str): 

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

3148 ex.add_note(f"Got type '{getFullyQualifiedName(text)}'.") 

3149 raise ex 

3150 

3151 self._changes = () if changes is None else tuple(changes) 

3152 self._exists = () if exists is None else tuple(exists) 

3153 for parameterName, paths in ( 

3154 ("changes", self._changes), 

3155 ("exists", self._exists) 

3156 ): 

3157 for path in paths: 

3158 if not isinstance(path, str): 

3159 ex = TypeError(f"An element of parameter '{parameterName}' is not of type 'str'.") 

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

3161 raise ex 

3162 

3163 if when is not None and not isinstance(when, RuleOutcome): 

3164 ex = TypeError("Parameter 'when' is not of type 'RuleOutcome'.") 

3165 ex.add_note(f"Got type '{getFullyQualifiedName(when)}'.") 

3166 raise ex 

3167 

3168 if allowFailure is not None and not isinstance(allowFailure, bool): 

3169 ex = TypeError("Parameter 'allowFailure' is not of type 'bool'.") 

3170 ex.add_note(f"Got type '{getFullyQualifiedName(allowFailure)}'.") 

3171 raise ex 

3172 

3173 self._condition = condition 

3174 self._compareTo = compareTo 

3175 self._when = when 

3176 self._allowFailure = allowFailure 

3177 self._variables = {} if variables is None else dict(variables) 

3178 

3179 if parent is not None: 

3180 parent._rules.append(self) 

3181 

3182 @readonly 

3183 def Condition(self) -> Nullable[str]: 

3184 """ 

3185 Read-only property to access the expression of the rule's ``if`` (:attr:`_condition`). 

3186 

3187 :returns: The expression, as written, or ``None`` if the rule has no ``if``. 

3188 """ 

3189 return self._condition 

3190 

3191 @readonly 

3192 def Changes(self) -> tuple[str, ...]: 

3193 """ 

3194 Read-only property to access the paths of the rule's ``changes`` (:attr:`_changes`). 

3195 

3196 :returns: The paths, as written in ``changes`` or ``changes.paths``. 

3197 """ 

3198 return self._changes 

3199 

3200 @readonly 

3201 def CompareTo(self) -> Nullable[str]: 

3202 """ 

3203 Read-only property to access the reference ``changes`` is compared to (:attr:`_compareTo`). 

3204 

3205 :returns: The reference of ``changes.compare_to``, or ``None``. 

3206 """ 

3207 return self._compareTo 

3208 

3209 @readonly 

3210 def Exists(self) -> tuple[str, ...]: 

3211 """ 

3212 Read-only property to access the paths of the rule's ``exists`` (:attr:`_exists`). 

3213 

3214 :returns: The paths, as written in ``exists`` or ``exists.paths``. 

3215 """ 

3216 return self._exists 

3217 

3218 @readonly 

3219 def When(self) -> Nullable[RuleOutcome]: 

3220 """ 

3221 Read-only property to access when the job runs, if the rule matches (:attr:`_when`). 

3222 

3223 :returns: The rule's ``when``, or ``None`` if the rule doesn't say. 

3224 """ 

3225 return self._when 

3226 

3227 @readonly 

3228 def AllowFailure(self) -> Nullable[bool]: 

3229 """ 

3230 Read-only property to access whether the pipeline continues when the job fails (:attr:`_allowFailure`). 

3231 

3232 :returns: The rule's ``allow_failure``, or ``None`` if the rule doesn't say. 

3233 """ 

3234 return self._allowFailure 

3235 

3236 @readonly 

3237 def Variables(self) -> dict[str, str]: 

3238 """ 

3239 Read-only property to access the variables set, if the rule matches (:attr:`_variables`). 

3240 

3241 :returns: The variables' values, by name. 

3242 """ 

3243 return self._variables 

3244 

3245 @staticmethod 

3246 def _Paths(value: Any, key: str, owner: str, entry: CommentedMap, path: Path) -> tuple[list[str], Nullable[str]]: 

3247 """ 

3248 Read the paths of ``changes`` or ``exists``: a list, or a mapping with ``paths``. 

3249 

3250 :param value: The key's value. 

3251 :param key: The key, for a message. 

3252 :param owner: The element the rule belongs to, for a message. 

3253 :param entry: The rule's mapping, for the key's line. 

3254 :param path: Path to the configuration file. 

3255 :returns: The paths, and the reference of ``compare_to``. 

3256 :raises PipelineFileError: If the value is neither a list nor a mapping with a list ``paths``. 

3257 """ 

3258 compareTo = None 

3259 if isinstance(value, CommentedMap): 

3260 compareTo = value.get("compare_to", None) 

3261 value = value.get("paths", None) 

3262 

3263 if not isinstance(value, CommentedSeq): 

3264 ex = PipelineFileError( 

3265 f"Key '{key}' of a rule of {owner} is not a list of paths.", path, Base._KeyLine(entry, key) 

3266 ) 

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

3268 raise ex 

3269 

3270 return [Base._ToText(item) for item in value], None if compareTo is None else Base._ToText(compareTo) 

3271 

3272 @classmethod 

3273 def _FromYAMLEntries(cls, value: Any, owner: str, path: Path, line: int) -> list[Self]: 

3274 """ 

3275 Read a ``rules`` key: a list of rules, each a mapping. 

3276 

3277 :param value: The key's value. 

3278 :param owner: The element the rules belong to, for a message, as ``job 'build'``. 

3279 :param path: Path to the configuration file. 

3280 :param line: Line the ``rules`` key is written at, starting at 1. 

3281 :returns: The rules, in file order. 

3282 :raises PipelineFileError: If the value is not a list, or a rule is not a mapping. 

3283 :raises PipelineFileError: If key ``when`` of a rule is not a value GitLab knows. |br| 

3284 The note lists the allowed values. 

3285 :raises PipelineFileError: If a key of a rule holds a value of the wrong kind. 

3286 """ 

3287 if not isinstance(value, CommentedSeq): 

3288 ex = PipelineFileError(f"Key 'rules' of {owner} is not a list.", path, line) 

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

3290 raise ex 

3291 

3292 rules = [] 

3293 for index, entry in enumerate(value): 

3294 entryLine = Base._ItemLine(value, index) 

3295 if not isinstance(entry, CommentedMap): 

3296 ex = PipelineFileError(f"Rule of {owner} is not a mapping.", path, entryLine) 

3297 ex.add_note(f"Got type '{getFullyQualifiedName(entry)}'.") 

3298 raise ex 

3299 

3300 changes = None 

3301 compareTo = None 

3302 if "changes" in entry: 

3303 changes, compareTo = cls._Paths(entry["changes"], "changes", owner, entry, path) 

3304 

3305 exists = None 

3306 if "exists" in entry: 

3307 exists, _ = cls._Paths(entry["exists"], "exists", owner, entry, path) 

3308 

3309 when = None 

3310 if (whenValue := entry.get("when", None)) is not None: 

3311 try: 

3312 when = RuleOutcome.Parse(Base._ToText(whenValue)) 

3313 except ValueError as cause: 

3314 ex = PipelineFileError(f"Key 'when' of a rule of {owner} is not a known value.", path, entryLine) 

3315 ex.add_note(f"Got '{whenValue}'.") 

3316 ex.add_note(f"Allowed values: {', '.join(member.value for member in RuleOutcome)}.") 

3317 raise ex from cause 

3318 

3319 allowFailure = Base._ToPython(entry.get("allow_failure", None)) 

3320 if allowFailure is not None and not isinstance(allowFailure, bool): 

3321 ex = PipelineFileError(f"Key 'allow_failure' of a rule of {owner} is not a boolean.", path, entryLine) 

3322 ex.add_note(f"Got '{allowFailure}'.") 

3323 raise ex 

3324 

3325 variables = entry.get("variables", None) 

3326 if variables is not None and not isinstance(variables, CommentedMap): 

3327 ex = PipelineFileError(f"Key 'variables' of a rule of {owner} is not a mapping.", path, entryLine) 

3328 ex.add_note(f"Got type '{getFullyQualifiedName(variables)}'.") 

3329 raise ex 

3330 

3331 condition = entry.get("if", None) 

3332 rules.append(cls( 

3333 entryLine, 

3334 condition=None if condition is None else Base._ToText(condition), 

3335 changes=changes, 

3336 compareTo=compareTo, 

3337 exists=exists, 

3338 when=when, 

3339 allowFailure=allowFailure, 

3340 variables=None if variables is None else {str(k): Base._ToText(v) for k, v in variables.items()} 

3341 )) 

3342 

3343 return rules 

3344 

3345 

3346@export 

3347class Default(Base[PipelineFile]): 

3348 """ 

3349 The ``default`` key of a configuration file: keys every job gets, unless it sets them itself. 

3350 

3351 The global keywords ``image``, ``services``, ``before_script`` and ``after_script`` - deprecated forms of 

3352 ``default`` - are read into it too, unless ``default`` sets them. 

3353 """ 

3354 

3355 _PARENT_TYPE: ClassVar[ParentTypes] = PipelineFile #: A default belongs to a configuration file. 

3356 

3357 _image: Nullable[str] #: Image of the container a job runs in. 

3358 _services: tuple[str, ...] #: Images of the service containers. 

3359 _tags: tuple[str, ...] #: Tags selecting the runner. 

3360 _beforeScript: tuple[str, ...] #: Lines of ``before_script``. 

3361 _afterScript: tuple[str, ...] #: Lines of ``after_script``. 

3362 

3363 _KEYS: ClassVar[tuple[str, ...]] = ("image", "services", "before_script", "after_script") #: The global keywords. 

3364 

3365 def __init__( 

3366 self, 

3367 line: int, 

3368 image: Nullable[str] = None, 

3369 services: Nullable[Iterable[str]] = None, 

3370 tags: Nullable[Iterable[str]] = None, 

3371 beforeScript: Nullable[Iterable[str]] = None, 

3372 afterScript: Nullable[Iterable[str]] = None, 

3373 *, 

3374 parent: Nullable[PipelineFile] = None 

3375 ) -> None: 

3376 """ 

3377 Initializes the ``default`` key. 

3378 

3379 :param line: Line the ``default`` key, or the first global keyword, is written at, starting at 1. 

3380 :param image: Optional, image of the container a job runs in. Default: ``None``. 

3381 :param services: Optional, images of the service containers. Default: ``None``. 

3382 :param tags: Optional, tags selecting the runner. Default: ``None``. 

3383 :param beforeScript: Optional, lines of ``before_script``. Default: ``None``. 

3384 :param afterScript: Optional, lines of ``after_script``. Default: ``None``. 

3385 :param parent: Optional, reference to the configuration file. Default: ``None``. 

3386 :raises TypeError: If parameter 'image' is not of type :class:`str`. 

3387 :raises TypeError: If an element of parameter 'services' is not of type :class:`str`. 

3388 :raises TypeError: If an element of parameter 'tags' is not of type :class:`str`. 

3389 :raises TypeError: If an element of parameter 'beforeScript' is not of type :class:`str`. 

3390 :raises TypeError: If an element of parameter 'afterScript' is not of type :class:`str`. 

3391 """ 

3392 super().__init__(line, parent=parent) 

3393 

3394 if image is not None and not isinstance(image, str): 

3395 ex = TypeError("Parameter 'image' is not of type 'str'.") 

3396 ex.add_note(f"Got type '{getFullyQualifiedName(image)}'.") 

3397 raise ex 

3398 

3399 self._services = () if services is None else tuple(services) 

3400 self._tags = () if tags is None else tuple(tags) 

3401 self._beforeScript = () if beforeScript is None else tuple(beforeScript) 

3402 self._afterScript = () if afterScript is None else tuple(afterScript) 

3403 for parameterName, texts in ( 

3404 ("services", self._services), 

3405 ("tags", self._tags), 

3406 ("beforeScript", self._beforeScript), 

3407 ("afterScript", self._afterScript) 

3408 ): 

3409 for text in texts: 

3410 if not isinstance(text, str): 

3411 ex = TypeError(f"An element of parameter '{parameterName}' is not of type 'str'.") 

3412 ex.add_note(f"Got type '{getFullyQualifiedName(text)}'.") 

3413 raise ex 

3414 

3415 self._image = image 

3416 

3417 if parent is not None: 

3418 parent._default = self 

3419 

3420 @readonly 

3421 def Image(self) -> Nullable[str]: 

3422 """ 

3423 Read-only property to access the image of the container a job runs in (:attr:`_image`). 

3424 

3425 :returns: The image, or ``None`` if the default names none. 

3426 """ 

3427 return self._image 

3428 

3429 @readonly 

3430 def Services(self) -> tuple[str, ...]: 

3431 """ 

3432 Read-only property to access the images of the service containers (:attr:`_services`). 

3433 

3434 :returns: The images, in file order. 

3435 """ 

3436 return self._services 

3437 

3438 @readonly 

3439 def Tags(self) -> tuple[str, ...]: 

3440 """ 

3441 Read-only property to access the tags selecting the runner (:attr:`_tags`). 

3442 

3443 :returns: The tags, in file order. 

3444 """ 

3445 return self._tags 

3446 

3447 @readonly 

3448 def BeforeScript(self) -> tuple[str, ...]: 

3449 """ 

3450 Read-only property to access the lines of ``before_script`` (:attr:`_beforeScript`). 

3451 

3452 :returns: The lines, nested lists flattened. 

3453 """ 

3454 return self._beforeScript 

3455 

3456 @readonly 

3457 def AfterScript(self) -> tuple[str, ...]: 

3458 """ 

3459 Read-only property to access the lines of ``after_script`` (:attr:`_afterScript`). 

3460 

3461 :returns: The lines, nested lists flattened. 

3462 """ 

3463 return self._afterScript 

3464 

3465 @classmethod 

3466 def _FromYAML(cls, document: CommentedMap, path: Path) -> Nullable[Self]: 

3467 """ 

3468 Read the ``default`` key and the global keywords standing for it. 

3469 

3470 :param document: The configuration. 

3471 :param path: Path to the configuration file. 

3472 :returns: The default, or ``None`` if the configuration has neither. 

3473 :raises PipelineFileError: If key ``default`` is not a mapping. 

3474 :raises PipelineFileError: If a key holds a value of the wrong kind. 

3475 """ 

3476 mapping = CommentedMap() 

3477 line = None 

3478 if "default" in document: 

3479 line = Base._KeyLine(document, "default") 

3480 if not isinstance(document["default"], CommentedMap): 

3481 ex = PipelineFileError("Key 'default' is not a mapping.", path, line) 

3482 ex.add_note(f"Got type '{getFullyQualifiedName(document['default'])}'.") 

3483 raise ex 

3484 

3485 mapping = document["default"] 

3486 

3487 globalKeys = {key: document[key] for key in cls._KEYS if key in document and key not in mapping} 

3488 if line is None and len(globalKeys) == 0: 

3489 return None 

3490 elif line is None: 

3491 line = min(Base._KeyLine(document, key) for key in globalKeys) 

3492 

3493 def value(key: str) -> Any: 

3494 """ 

3495 Nested function returning a key of ``default``, or else the global keyword. 

3496 

3497 :param key: The key. 

3498 :returns: The key's value, or ``None``. 

3499 """ 

3500 return mapping[key] if key in mapping else globalKeys.get(key, None) 

3501 

3502 owner = mapping if "default" in document else document 

3503 services = None 

3504 if (serviceList := value("services")) is not None: 

3505 if not isinstance(serviceList, CommentedSeq): 

3506 ex = PipelineFileError("Key 'services' of the default is not a list.", path, line) 

3507 ex.add_note(f"Got type '{getFullyQualifiedName(serviceList)}'.") 

3508 raise ex 

3509 

3510 services = [service for item in serviceList if (service := Job._Name(item)) is not None] 

3511 

3512 tags = None 

3513 if (tagList := value("tags")) is not None: 

3514 if not isinstance(tagList, CommentedSeq): 

3515 ex = PipelineFileError("Key 'tags' of the default is not a list.", path, line) 

3516 ex.add_note(f"Got type '{getFullyQualifiedName(tagList)}'.") 

3517 raise ex 

3518 

3519 tags = [Base._ToText(tag) for tag in tagList] 

3520 

3521 return cls( 

3522 line, 

3523 image=Job._Name(value("image")), 

3524 services=services, 

3525 tags=tags, 

3526 beforeScript=Job._Lines(value("before_script"), "before_script", "the default", owner, path), 

3527 afterScript=Job._Lines(value("after_script"), "after_script", "the default", owner, path) 

3528 ) 

3529 

3530 

3531@export 

3532class Parallel(Base[Union[Job, Need]]): 

3533 """ 

3534 A ``parallel`` key: how often a job runs, or the matrix of variables its instances run with. 

3535 

3536 A job runs :attr:`Count` times, or once per combination of :attr:`Matrix`: an entry maps variables to values, and 

3537 contributes the product of their lists. A need's ``parallel`` names the matrix instances it needs. 

3538 """ 

3539 

3540 _PARENT_TYPE: ClassVar[ParentTypes] = (Job, Need) #: A parallel belongs to a job or a need. 

3541 

3542 _count: Nullable[int] #: How often the job runs. 

3543 _matrix: tuple[dict[str, tuple[str, ...]], ...] #: Entries of the matrix: variables to their values. 

3544 

3545 def __init__( 

3546 self, 

3547 line: int, 

3548 count: Nullable[int] = None, 

3549 matrix: Nullable[Iterable[Mapping[str, Iterable[str]]]] = None, 

3550 *, 

3551 parent: Nullable[Union[Job, Need]] = None 

3552 ) -> None: 

3553 """ 

3554 Initializes a ``parallel`` key. 

3555 

3556 :param line: Line the ``parallel`` key is written at, starting at 1. 

3557 :param count: Optional, how often the job runs. Default: ``None``, for a matrix. 

3558 :param matrix: Optional, entries of the matrix, each mapping variables to their values. Default: ``None``, 

3559 for a count. 

3560 :param parent: Optional, reference to the job or the need. Default: ``None``. 

3561 :raises ValueError: If both or neither of parameters 'count' and 'matrix' are given. 

3562 :raises TypeError: If parameter 'count' is not of type :class:`int`. 

3563 :raises ValueError: If parameter 'count' is out of range 1..200. 

3564 :raises TypeError: If an entry of parameter 'matrix' is not a mapping, or a variable's values are not strings. 

3565 """ 

3566 super().__init__(line, parent=parent) 

3567 

3568 if (count is None) == (matrix is None): 

3569 raise ValueError("Parameters 'count' and 'matrix' are both given, or both None.") 

3570 elif count is not None and (not isinstance(count, int) or isinstance(count, bool)): 

3571 ex = TypeError("Parameter 'count' is not of type 'int'.") 

3572 ex.add_note(f"Got type '{getFullyQualifiedName(count)}'.") 

3573 raise ex 

3574 elif count is not None and not (1 <= count <= 200): 

3575 ex = ValueError("Parameter 'count' is out of range 1..200.") 

3576 ex.add_note(f"Got value '{count}'.") 

3577 raise ex 

3578 

3579 entries = [] 

3580 for entry in () if matrix is None else matrix: 

3581 if not isinstance(entry, Mapping): 

3582 ex = TypeError("An entry of parameter 'matrix' is not a mapping.") 

3583 ex.add_note(f"Got type '{getFullyQualifiedName(entry)}'.") 

3584 raise ex 

3585 

3586 variables = {} 

3587 for variable, values in entry.items(): 

3588 variables[variable] = tuple(values) 

3589 if not isinstance(variable, str) or any(not isinstance(value, str) for value in variables[variable]): 

3590 ex = TypeError(f"Variable '{variable}' of parameter 'matrix' has values not of type 'str'.") 

3591 ex.add_note(f"Got '{variables[variable]}'.") 

3592 raise ex 

3593 

3594 entries.append(variables) 

3595 

3596 self._count = count 

3597 self._matrix = tuple(entries) 

3598 

3599 if parent is not None: 

3600 parent._parallel = self 

3601 

3602 @readonly 

3603 def Count(self) -> Nullable[int]: 

3604 """ 

3605 Read-only property to access how often the job runs (:attr:`_count`). 

3606 

3607 :returns: The count of ``parallel: N``, or ``None`` for a matrix. 

3608 """ 

3609 return self._count 

3610 

3611 @readonly 

3612 def Matrix(self) -> tuple[dict[str, tuple[str, ...]], ...]: 

3613 """ 

3614 Read-only property to access the entries of the matrix (:attr:`_matrix`). 

3615 

3616 :returns: The entries, each mapping variables to their values, in file order; empty for a count. 

3617 """ 

3618 return self._matrix 

3619 

3620 @readonly 

3621 def IsMatrix(self) -> bool: 

3622 """ 

3623 Read-only property to return whether the key is a matrix. 

3624 

3625 :returns: ``True`` for ``parallel: matrix``, ``False`` for ``parallel: N``. 

3626 """ 

3627 return self._count is None 

3628 

3629 @readonly 

3630 def Combinations(self) -> list[dict[str, str]]: 

3631 """ 

3632 Read-only property to return the combinations of the matrix, one per instance. 

3633 

3634 :returns: The combinations, each mapping the variables to a value, in the order GitLab creates the instances. 

3635 """ 

3636 combinations = [] 

3637 for entry in self._matrix: 

3638 for values in product(*entry.values()): 

3639 combinations.append(dict(zip(entry, values))) 

3640 

3641 return combinations 

3642 

3643 @readonly 

3644 def InstanceNames(self) -> list[str]: 

3645 """ 

3646 Read-only property to return the names GitLab gives the instances. 

3647 

3648 :returns: The names, as ``test 1/3`` for a count, or ``deploy: [aws, app1]`` for a matrix. 

3649 """ 

3650 if isinstance(self._parent, Need): 

3651 name = self._parent._job 

3652 else: 

3653 name = "" if self._parent is None else self._parent._name 

3654 

3655 if self._count is not None: 

3656 return [self._InstanceName(name, self._count, {"CI_NODE_INDEX": index}) for index in range(1, self._count + 1)] 

3657 

3658 return [self._InstanceName(name, None, combination) for combination in self.Combinations] 

3659 

3660 @staticmethod 

3661 def _InstanceName(name: str, count: Nullable[int], dimensions: Mapping[str, Any]) -> str: 

3662 """ 

3663 Return the name GitLab gives an instance. 

3664 

3665 :param name: Name of the job. 

3666 :param count: The count of ``parallel: N``, or ``None`` for a matrix. 

3667 :param dimensions: The instance's variables, ``CI_NODE_INDEX`` for ``parallel: N``. 

3668 :returns: The name, as ``test 1/3`` for a count, or ``deploy: [aws, app1]`` for a matrix. 

3669 """ 

3670 if count is not None: 

3671 return f"{name} {dimensions['CI_NODE_INDEX']}/{count}" 

3672 

3673 return f"{name}: [{', '.join(str(value) for value in dimensions.values())}]" 

3674 

3675 @classmethod 

3676 def _FromYAML(cls, value: Any, owner: str, path: Path, line: int) -> Self: 

3677 """ 

3678 Read a ``parallel`` key: a count, or a mapping with key ``matrix``. 

3679 

3680 :param value: The key's value. 

3681 :param owner: The element holding the key, for a message, as ``job 'test'``. 

3682 :param path: Path to the configuration file. 

3683 :param line: Line the ``parallel`` key is written at, starting at 1. 

3684 :returns: The parallel. 

3685 :raises PipelineFileError: If the value is neither a count nor a mapping with key ``matrix``. 

3686 :raises PipelineFileError: If the count is out of range 1..200. 

3687 :raises PipelineFileError: If the matrix is not a list of mappings of variables to a value or a list of values. 

3688 """ 

3689 count = Base._ToPython(value) 

3690 if isinstance(count, int) and not isinstance(count, bool): 

3691 if not (1 <= count <= 200): 

3692 ex = PipelineFileError(f"Key 'parallel' of {owner} is out of range 1..200.", path, line) 

3693 ex.add_note(f"Got '{count}'.") 

3694 raise ex 

3695 

3696 return cls(line, count) 

3697 elif not isinstance(value, CommentedMap) or "matrix" not in value: 

3698 ex = PipelineFileError(f"Key 'parallel' of {owner} is neither a count nor a mapping with 'matrix'.", path, line) 

3699 ex.add_note(f"Got '{count}'.") 

3700 raise ex 

3701 

3702 entries = value["matrix"] 

3703 if not isinstance(entries, CommentedSeq) or any(not isinstance(entry, CommentedMap) for entry in entries): 

3704 ex = PipelineFileError(f"Key 'parallel.matrix' of {owner} is not a list of mappings.", path, line) 

3705 ex.add_note(f"Got '{Base._ToPython(entries)}'.") 

3706 raise ex 

3707 

3708 matrix = [] 

3709 for entry in entries: 

3710 variables = {} 

3711 for variable, values in entry.items(): 

3712 values = values if isinstance(values, CommentedSeq) else [values] 

3713 if any(isinstance(item, (CommentedMap, CommentedSeq)) for item in values): 

3714 ex = PipelineFileError( 

3715 f"Variable '{variable}' of the matrix of {owner} is neither a value nor a list of values.", 

3716 path, Base._KeyLine(entry, variable) 

3717 ) 

3718 ex.add_note(f"Got '{Base._ToPython(values)}'.") 

3719 raise ex 

3720 

3721 variables[str(variable)] = [Base._ToText(item) for item in values] 

3722 

3723 matrix.append(variables) 

3724 

3725 return cls(line, matrix=matrix) 

3726 

3727 

3728@export 

3729class Input(Base[Union[PipelineFile, Job]]): 

3730 """ 

3731 An input of the header's ``spec:inputs``, or of a job's ``inputs``. 

3732 

3733 An input of a file is a parameter of its configuration, which ``include:inputs`` or ``trigger:include:inputs`` set, or 

3734 the form running a pipeline by hand; it is mandatory without a default. An input of a job is set when the job is 

3735 run or retried by hand, and always has a default. 

3736 """ 

3737 

3738 _PARENT_TYPE: ClassVar[ParentTypes] = (PipelineFile, Job) #: An input belongs to a configuration file or a job. 

3739 

3740 _name: str #: Name of the input. 

3741 _type: InputType #: Type of the input. 

3742 _required: bool #: ``True``, if the input has no default. 

3743 _default: ValueT #: Value of the input, if it isn't set. 

3744 _description: Nullable[str] #: Description of the input. 

3745 _options: tuple[ValueT, ...] #: Values the input may have. 

3746 _regex: Nullable[str] #: Regular expression the input's value must match. 

3747 _rules: tuple[dict[str, ValueT], ...] #: Conditional options and defaults of ``rules``. 

3748 

3749 _KEYS: ClassVar[tuple[str, ...]] = ( 

3750 "default", "type", "description", "options", "regex", "rules" 

3751 ) #: Keys of an input as mapping. 

3752 

3753 def __init__( 

3754 self, 

3755 name: str, 

3756 line: int, 

3757 inputType: InputType = InputType.String, 

3758 required: bool = True, 

3759 default: ValueT = None, 

3760 description: Nullable[str] = None, 

3761 options: Nullable[Iterable[ValueT]] = None, 

3762 regex: Nullable[str] = None, 

3763 rules: Nullable[Iterable[Mapping[str, ValueT]]] = None, 

3764 *, 

3765 parent: Nullable[Union[PipelineFile, Job]] = None 

3766 ) -> None: 

3767 """ 

3768 Initializes an input. 

3769 

3770 :param name: Name of the input. 

3771 :param line: Line the input's name is written at, starting at 1. 

3772 :param inputType: Optional, type of the input. Default: :attr:`InputType.String`. 

3773 :param required: Optional, ``True``, if the input has no default. Default: ``True``. 

3774 :param default: Optional, value of the input, if it isn't set. Default: ``None``. 

3775 :param description: Optional, description of the input. Default: ``None``. 

3776 :param options: Optional, values the input may have. Default: ``None``. 

3777 :param regex: Optional, regular expression the input's value must match. Default: ``None``. 

3778 :param rules: Optional, conditional options and defaults, each a mapping of ``if``, ``options`` and 

3779 ``default``. Default: ``None``. 

3780 :param parent: Optional, reference to the configuration file or the job. Default: ``None``. 

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

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

3783 :raises ValueError: If parameter 'name' is empty. 

3784 :raises TypeError: If parameter 'inputType' is not of type :class:`InputType`. 

3785 :raises TypeError: If parameter 'required' is not of type :class:`bool`. 

3786 :raises TypeError: If parameter 'description' is not of type :class:`str`. 

3787 :raises TypeError: If parameter 'regex' is not of type :class:`str`. 

3788 """ 

3789 super().__init__(line, parent=parent) 

3790 

3791 if name is None: 

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

3793 elif not isinstance(name, str): 

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

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

3796 raise ex 

3797 elif name == "": 

3798 raise ValueError("Parameter 'name' is empty.") 

3799 

3800 if not isinstance(inputType, InputType): 

3801 ex = TypeError("Parameter 'inputType' is not of type 'InputType'.") 

3802 ex.add_note(f"Got type '{getFullyQualifiedName(inputType)}'.") 

3803 raise ex 

3804 

3805 if not isinstance(required, bool): 

3806 ex = TypeError("Parameter 'required' is not of type 'bool'.") 

3807 ex.add_note(f"Got type '{getFullyQualifiedName(required)}'.") 

3808 raise ex 

3809 

3810 for parameterName, text in ( 

3811 ("description", description), 

3812 ("regex", regex) 

3813 ): 

3814 if text is not None and not isinstance(text, str): 

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

3816 ex.add_note(f"Got type '{getFullyQualifiedName(text)}'.") 

3817 raise ex 

3818 

3819 self._name = name 

3820 self._type = inputType 

3821 self._required = required 

3822 self._default = default 

3823 self._description = description 

3824 self._options = () if options is None else tuple(options) 

3825 self._regex = regex 

3826 self._rules = () if rules is None else tuple(dict(rule) for rule in rules) 

3827 

3828 if parent is not None: 

3829 parent._inputs[name] = self 

3830 

3831 @readonly 

3832 def Name(self) -> str: 

3833 """ 

3834 Read-only property to access the input's name (:attr:`_name`). 

3835 

3836 :returns: Name of the input. 

3837 """ 

3838 return self._name 

3839 

3840 @readonly 

3841 def Type(self) -> InputType: 

3842 """ 

3843 Read-only property to access the input's type (:attr:`_type`). 

3844 

3845 :returns: The ``type`` key, :attr:`InputType.String` if the input doesn't say. 

3846 """ 

3847 return self._type 

3848 

3849 @readonly 

3850 def Required(self) -> bool: 

3851 """ 

3852 Read-only property to access whether the input has to be set (:attr:`_required`). 

3853 

3854 :returns: ``True``, if the input has no ``default`` key. 

3855 """ 

3856 return self._required 

3857 

3858 @readonly 

3859 def Default(self) -> ValueT: 

3860 """ 

3861 Read-only property to access the input's value, if it isn't set (:attr:`_default`). 

3862 

3863 :returns: The default, with the type it is written with, or ``None`` if the input has none. 

3864 """ 

3865 return self._default 

3866 

3867 @readonly 

3868 def Description(self) -> Nullable[str]: 

3869 """ 

3870 Read-only property to access the input's description (:attr:`_description`). 

3871 

3872 :returns: The description, or ``None`` if the input gives none. 

3873 """ 

3874 return self._description 

3875 

3876 @readonly 

3877 def Options(self) -> tuple[ValueT, ...]: 

3878 """ 

3879 Read-only property to access the values the input may have (:attr:`_options`). 

3880 

3881 :returns: The options, in file order; empty if the input may have any value. 

3882 """ 

3883 return self._options 

3884 

3885 @readonly 

3886 def Regex(self) -> Nullable[str]: 

3887 """ 

3888 Read-only property to access the regular expression the input's value must match (:attr:`_regex`). 

3889 

3890 :returns: The expression, as written, or ``None``. 

3891 """ 

3892 return self._regex 

3893 

3894 @readonly 

3895 def Rules(self) -> tuple[dict[str, ValueT], ...]: 

3896 """ 

3897 Read-only property to access the input's conditional options and defaults (:attr:`_rules`). 

3898 

3899 :returns: The rules, each mapping ``if``, ``options`` and ``default``, in the order GitLab evaluates them. 

3900 """ 

3901 return self._rules 

3902 

3903 def __str__(self) -> str: 

3904 """ 

3905 Return the input's name. 

3906 

3907 :returns: Name of the input. 

3908 """ 

3909 return self._name 

3910 

3911 @classmethod 

3912 def _FromYAML(cls, name: str, declaration: Any, jobName: Nullable[str], path: Path, line: int) -> Self: 

3913 """ 

3914 Read an input's declaration: empty, or a mapping of the keys in :attr:`_KEYS`. 

3915 

3916 :param name: Name of the input. 

3917 :param declaration: The declaration. 

3918 :param jobName: Name of the job declaring the input, or ``None`` for ``spec:inputs``. 

3919 :param path: Path to the configuration file. 

3920 :param line: Line the input's name is written at, starting at 1. 

3921 :returns: The input. 

3922 :raises PipelineFileError: If the declaration is neither empty nor a mapping. 

3923 :raises PipelineFileError: If the mapping has a key GitLab doesn't know for an input. |br| 

3924 The note lists the allowed keys. 

3925 :raises PipelineFileError: If key ``type`` is not an input type. |br| 

3926 The note lists the allowed values. 

3927 :raises PipelineFileError: If an input of a job has no default. 

3928 :raises PipelineFileError: If the default doesn't match the type, or isn't one of the options. 

3929 :raises PipelineFileError: If key ``options`` or ``rules`` is not a list, or ``regex`` is used with a type other 

3930 than ``string``. 

3931 """ 

3932 subject = f"input '{name}'" if jobName is None else f"input '{name}' of job '{jobName}'" 

3933 if declaration is None: 

3934 declaration = CommentedMap() 

3935 elif not isinstance(declaration, CommentedMap): 

3936 ex = PipelineFileError(f"I{subject[1:]} is not a mapping.", path, line) 

3937 ex.add_note(f"Got type '{getFullyQualifiedName(declaration)}'.") 

3938 raise ex 

3939 

3940 for key in declaration: 

3941 if key not in cls._KEYS: 

3942 ex = PipelineFileError(f"I{subject[1:]} has unknown key '{key}'.", path, Base._KeyLine(declaration, key)) 

3943 ex.add_note(f"Allowed keys: {', '.join(cls._KEYS)}.") 

3944 raise ex 

3945 

3946 try: 

3947 inputType = InputType.Parse(Base._ToText(declaration.get("type", "string"))) 

3948 except ValueError as cause: 

3949 ex = PipelineFileError(f"Key 'type' of {subject} is not an input type.", path, line) 

3950 ex.add_note(f"Got '{declaration['type']}'.") 

3951 ex.add_note(f"Allowed values: {', '.join(member.value for member in InputType)}.") 

3952 raise ex from cause 

3953 

3954 required = "default" not in declaration 

3955 if required and jobName is not None: 

3956 raise PipelineFileError(f"I{subject[1:]} has no default.", path, line) 

3957 

3958 for key in ("options", "rules"): 

3959 if key in declaration and not isinstance(declaration[key], CommentedSeq): 

3960 ex = PipelineFileError( 

3961 f"Key '{key}' of {subject} is not a list.", path, Base._KeyLine(declaration, key) 

3962 ) 

3963 ex.add_note(f"Got type '{getFullyQualifiedName(declaration[key])}'.") 

3964 raise ex 

3965 

3966 default = Base._ToPython(declaration.get("default", None)) 

3967 options = Base._ToPython(declaration.get("options", [])) 

3968 types = { 

3969 InputType.String: (str, ), 

3970 InputType.Number: (int, float), 

3971 InputType.Boolean: (bool, ), 

3972 InputType.Array: (list, ) 

3973 }[inputType] 

3974 if default is not None and (not isinstance(default, types) or (isinstance(default, bool) and bool not in types)): 

3975 ex = PipelineFileError(f"Default of {subject} is not of type '{inputType.value}'.", path, line) 

3976 ex.add_note(f"Got '{default}'.") 

3977 raise ex 

3978 elif default is not None and len(options) > 0 and default not in options: 

3979 ex = PipelineFileError(f"Default of {subject} is not one of its options.", path, line) 

3980 ex.add_note(f"Options: {', '.join(str(option) for option in options)}.") 

3981 raise ex 

3982 elif "regex" in declaration and inputType is not InputType.String: 

3983 raise PipelineFileError(f"Key 'regex' of {subject} needs type 'string'.", path, line) 

3984 

3985 description = declaration.get("description", None) 

3986 regex = declaration.get("regex", None) 

3987 return cls( 

3988 name, line, inputType, required, default, 

3989 description=None if description is None else Base._ToText(description), 

3990 options=options, 

3991 regex=None if regex is None else Base._ToText(regex), 

3992 rules=Base._ToPython(declaration.get("rules", [])) 

3993 ) 

3994 

3995 @classmethod 

3996 def _FromYAMLMapping(cls, mapping: Any, jobName: Nullable[str], path: Path, line: int) -> list[Self]: 

3997 """ 

3998 Read the inputs of ``spec:inputs`` or of a job's ``inputs``. 

3999 

4000 :param mapping: The key's value. 

4001 :param jobName: Name of the job declaring the inputs, or ``None`` for ``spec:inputs``. 

4002 :param path: Path to the configuration file. 

4003 :param line: Line the key is written at, starting at 1. 

4004 :returns: The inputs, in file order. 

4005 :raises PipelineFileError: If the value is not a mapping. 

4006 :raises PipelineFileError: If an input is malformed. 

4007 """ 

4008 if not isinstance(mapping, CommentedMap): 

4009 message = "Key 'spec:inputs'" if jobName is None else f"Key 'inputs' of job '{jobName}'" 

4010 ex = PipelineFileError(f"{message} is not a mapping.", path, line) 

4011 ex.add_note(f"Got type '{getFullyQualifiedName(mapping)}'.") 

4012 raise ex 

4013 

4014 return [ 

4015 cls._FromYAML(str(name), value, jobName, path, Base._KeyLine(mapping, name)) for name, value in mapping.items() 

4016 ] 

4017 

4018 

4019@export 

4020class IncludeResolver(metaclass=ExtendedType, slots=True): 

4021 """ 

4022 Reads the local files a configuration includes, or a trigger job's child pipeline runs, from a repository's directory. 

4023 

4024 A local include's path, as ``/ci/build.yml`` or ``ci/build.yml``, is relative to the repository's root. Includes of 

4025 another kind - another project's files, a URL, a template, a component, an artifact - aren't read. 

4026 

4027 Every file is read once; asking for it again returns the same :class:`PipelineFile`. A file read is read with this 

4028 resolver, so its own local includes are read too. 

4029 """ 

4030 

4031 _root: Path #: The repository's root directory. 

4032 _files: dict[Path, PipelineFile] #: Files already read, by resolved path. 

4033 _documents: dict[Path, CommentedMap] #: Configurations of included files already read, by resolved path. 

4034 

4035 def __init__(self, root: Path) -> None: 

4036 """ 

4037 Initializes a resolver. 

4038 

4039 :param root: The repository's root directory. 

4040 :raises ValueError: If parameter 'root' is ``None``. 

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

4042 """ 

4043 if root is None: 

4044 raise ValueError("Parameter 'root' is None.") 

4045 elif not isinstance(root, Path): 

4046 ex = TypeError("Parameter 'root' is not of type 'Path'.") 

4047 ex.add_note(f"Got type '{getFullyQualifiedName(root)}'.") 

4048 raise ex 

4049 

4050 self._root = root 

4051 self._files = {} 

4052 self._documents = {} 

4053 

4054 @readonly 

4055 def Root(self) -> Path: 

4056 """ 

4057 Read-only property to access the repository's root directory (:attr:`_root`). 

4058 

4059 :returns: The directory. 

4060 """ 

4061 return self._root 

4062 

4063 def Resolve(self, include: Include) -> Nullable[PipelineFile]: 

4064 """ 

4065 Read the file a local include names. 

4066 

4067 :param include: The include. 

4068 :returns: The file, or ``None`` for an include of another kind, or of a file that doesn't exist. 

4069 :raises ValueError: If parameter 'include' is ``None``. 

4070 :raises TypeError: If parameter 'include' is not of type :class:`Include`. 

4071 :raises PipelineFileError: If the file is not a well-formed configuration. 

4072 """ 

4073 if include is None: 

4074 raise ValueError("Parameter 'include' is None.") 

4075 elif not isinstance(include, Include): 

4076 ex = TypeError("Parameter 'include' is not of type 'Include'.") 

4077 ex.add_note(f"Got type '{getFullyQualifiedName(include)}'.") 

4078 raise ex 

4079 

4080 if include._kind is not IncludeKind.Local: 

4081 return None 

4082 

4083 path = (self._root / include._location.lstrip("/")).resolve() 

4084 if (known := self._files.get(path, None)) is not None: 

4085 return known 

4086 elif not path.exists(): 

4087 return None 

4088 

4089 self._files[path] = PipelineFile.FromFile(path, self) 

4090 return self._files[path] 

4091 

4092 def _Included( 

4093 self, 

4094 document: CommentedMap, 

4095 path: Path, 

4096 visited: tuple[Path, ...] 

4097 ) -> tuple[dict[str, Any], bool]: 

4098 """ 

4099 Read the local files a configuration includes, and those they include in turn. 

4100 

4101 A file included again, by itself or another, is read once. 

4102 

4103 :param document: The configuration. 

4104 :param path: Path to the configuration file. 

4105 :param visited: Resolved paths of the files read on the way to this one, this one last. 

4106 :returns: The top-level keys of the included files, a later file's key replacing an earlier one's; 

4107 and ``True``, if an include couldn't be read. 

4108 :raises PipelineFileError: If an include is malformed, or an included file is not a well-formed configuration. 

4109 """ 

4110 keys: dict[str, Any] = {} 

4111 incomplete = False 

4112 if "include" not in document: 

4113 return keys, incomplete 

4114 

4115 for include in Include._FromYAMLEntries(document["include"], path, Base._KeyLine(document, "include")): 

4116 if include._kind is not IncludeKind.Local: 

4117 incomplete = True 

4118 continue 

4119 

4120 includedPath = (self._root / include._location.lstrip("/")).resolve() 

4121 if includedPath in visited: 4121 ↛ 4122line 4121 didn't jump to line 4122 because the condition on line 4121 was never true

4122 continue 

4123 elif not includedPath.exists(): 4123 ↛ 4124line 4123 didn't jump to line 4124 because the condition on line 4123 was never true

4124 incomplete = True 

4125 continue 

4126 elif includedPath not in self._documents: 4126 ↛ 4129line 4126 didn't jump to line 4129 because the condition on line 4126 was always true

4127 self._documents[includedPath] = PipelineFile._Load(includedPath)[1] 

4128 

4129 nested, nestedIncomplete = self._Included(self._documents[includedPath], includedPath, (*visited, includedPath)) 

4130 incomplete = incomplete or nestedIncomplete 

4131 keys.update(nested) 

4132 keys.update((str(key), value) for key, value in self._documents[includedPath].items()) 

4133 

4134 return keys, incomplete 

4135 

4136 

4137@export 

4138class DefinitionMixin(Generic[DefinitionType], metaclass=ExtendedType, mixin=True, expects=("_DEFINITION_TYPE",)): 

4139 """ 

4140 Mixin-class for an element of :mod:`pyTooling.CI` built from a configuration file, linking it to its definition. 

4141 

4142 :meth:`PipelineFile.ToPipeline` builds the elements, so a consumer of the generic model still reaches the facts only 

4143 the file has: the line an element is written at, its stage, its trigger. 

4144 """ 

4145 

4146 _definition: DefinitionType #: The element of the configuration file this element was built from. 

4147 

4148 @classmethod 

4149 def _CheckDefinition(cls, definition: DefinitionType) -> None: 

4150 """ 

4151 Check a definition before the element is built from it. 

4152 

4153 The host class names the element by its definition, so it checks the definition before calling 

4154 ``super().__init__()``. 

4155 

4156 :param definition: The element of the configuration file the element is built from. 

4157 :raises ValueError: If parameter 'definition' is ``None``. 

4158 :raises TypeError: If parameter 'definition' is not of the type the host class declares in 

4159 :attr:`_DEFINITION_TYPE`. 

4160 """ 

4161 if definition is None: 

4162 raise ValueError("Parameter 'definition' is None.") 

4163 elif not isinstance(definition, cls._DEFINITION_TYPE): 

4164 ex = TypeError(f"Parameter 'definition' is not of type '{cls._DEFINITION_TYPE.__name__}'.") 

4165 ex.add_note(f"Got type '{getFullyQualifiedName(definition)}'.") 

4166 raise ex 

4167 

4168 @staticmethod 

4169 def _Rules(rules: Sequence[Rule], when: Nullable[RuleOutcome], default: RuleOutcome) -> list[CIRule]: 

4170 """ 

4171 Return the :mod:`pyTooling.CI` rules of an element built from a configuration file. 

4172 

4173 Each of the file's rules becomes a rule deciding the rule's ``when``, else the element's, else ``default``. Its 

4174 ``changes``, ``compare_to``, ``exists``, ``allow_failure`` and ``variables`` are the rule's key-value-pairs, as 

4175 far as it has them. An element with ``when``, but without rules, gets one rule without condition. The rules are 

4176 built anew for every element, as the instances of a matrix share one definition. 

4177 

4178 :param rules: The rules of the file's element, in the order GitLab evaluates them. 

4179 :param when: The ``when`` of the file's element, or ``None``. 

4180 :param default: What a rule decides, if neither the rule nor the element say. 

4181 :returns: The rules, empty for an element with neither rules nor ``when``. 

4182 """ 

4183 if len(rules) == 0: 

4184 return [] if when is None else [CIRule(None, when)] 

4185 

4186 ciRules = [] 

4187 for rule in rules: 

4188 keyValuePairs: dict[Hashable, Any] = {} 

4189 if len(rule._changes) > 0: 

4190 keyValuePairs["changes"] = rule._changes 

4191 

4192 if rule._compareTo is not None: 

4193 keyValuePairs["compare_to"] = rule._compareTo 

4194 

4195 if len(rule._exists) > 0: 

4196 keyValuePairs["exists"] = rule._exists 

4197 

4198 if rule._allowFailure is not None: 

4199 keyValuePairs["allow_failure"] = rule._allowFailure 

4200 

4201 if len(rule._variables) > 0: 

4202 keyValuePairs["variables"] = dict(rule._variables) 

4203 

4204 if rule._when is not None: 

4205 outcome = rule._when 

4206 elif when is not None: 

4207 outcome = when 

4208 else: 

4209 outcome = default 

4210 

4211 ciRules.append(CIRule(rule._condition, outcome, keyValuePairs=keyValuePairs)) 

4212 

4213 return ciRules 

4214 

4215 def __init__(self, definition: DefinitionType) -> None: 

4216 """ 

4217 Initializes the link of an element to its definition, which :meth:`_CheckDefinition` checked. 

4218 

4219 :param definition: The element of the configuration file this element is built from. 

4220 """ 

4221 self._definition = definition 

4222 

4223 @readonly 

4224 def Definition(self) -> DefinitionType: 

4225 """ 

4226 Read-only property to access the file's element this element was built from (:attr:`_definition`). 

4227 

4228 :returns: The :class:`PipelineFile` of a pipeline, or the :class:`Job` of any other element. 

4229 """ 

4230 return self._definition 

4231 

4232 

4233@export 

4234class ChildPipelineMixin(metaclass=ExtendedType, mixin=True): 

4235 """Mixin-class for a trigger job built from a configuration file, holding the files its child pipeline runs.""" 

4236 

4237 _childFiles: tuple[PipelineFile, ...] #: The files the child pipeline's elements were built from. 

4238 

4239 def __init__(self, childFiles: Nullable[Iterable[PipelineFile]] = None) -> None: 

4240 """ 

4241 Initializes the child pipeline's files. 

4242 

4243 :param childFiles: Optional, the files the child pipeline's elements are built from. Default: ``None``. 

4244 :raises TypeError: If an element of parameter 'childFiles' is not of type :class:`PipelineFile`. 

4245 """ 

4246 self._childFiles = () if childFiles is None else tuple(childFiles) 

4247 for childFile in self._childFiles: 

4248 if not isinstance(childFile, PipelineFile): 

4249 ex = TypeError("An element of parameter 'childFiles' is not of type 'PipelineFile'.") 

4250 ex.add_note(f"Got type '{getFullyQualifiedName(childFile)}'.") 

4251 raise ex 

4252 

4253 @readonly 

4254 def ChildFiles(self) -> tuple[PipelineFile, ...]: 

4255 """ 

4256 Read-only property to access the files the child pipeline was expanded from (:attr:`_childFiles`). 

4257 

4258 :returns: The files, empty if the child pipeline wasn't expanded - its files aren't at hand, the depth was used 

4259 up, or the job starts another project's pipeline. 

4260 """ 

4261 return self._childFiles 

4262 

4263 

4264@export 

4265class DefinedPipeline(CIPipeline, DefinitionMixin[PipelineFile]): 

4266 """The pipeline a configuration file defines, as :meth:`PipelineFile.ToPipeline` builds it.""" 

4267 

4268 _DEFINITION_TYPE: ClassVar[type] = PipelineFile #: A pipeline is built from a configuration file. 

4269 

4270 def __init__(self, definition: PipelineFile, *, keyValuePairs: Nullable[Mapping[Hashable, Any]] = None) -> None: 

4271 """ 

4272 Initializes a pipeline built from a configuration file, named by ``workflow:name``, or else by the file's name. 

4273 

4274 :param definition: The configuration file. 

4275 :param keyValuePairs: Optional, mapping (dictionary) of key-value-pairs. Default: ``None``. 

4276 """ 

4277 self._CheckDefinition(definition) 

4278 

4279 workflow = definition._workflow 

4280 name = definition._path.name if workflow is None or workflow._name is None else workflow._name 

4281 rules = [] if workflow is None else self._Rules(workflow._rules, None, RuleOutcome.Always) 

4282 super().__init__(name, rules=rules, keyValuePairs=keyValuePairs) 

4283 DefinitionMixin.__init__(self, definition) 

4284 

4285 

4286@export 

4287class DefinedWorkflow(CIWorkflow, ChildPipelineMixin, DefinitionMixin[Job]): 

4288 """A trigger job, as :meth:`PipelineFile.ToPipeline` builds it: the pipeline it starts, as a workflow.""" 

4289 

4290 _DEFINITION_TYPE: ClassVar[type] = Job #: A workflow is built from a trigger job. 

4291 

4292 def __init__( 

4293 self, 

4294 definition: Job, 

4295 *, 

4296 childFiles: Nullable[Iterable[PipelineFile]] = None, 

4297 keyValuePairs: Nullable[Mapping[Hashable, Any]] = None, 

4298 parent: Nullable[CIWorkflow] = None 

4299 ) -> None: 

4300 """ 

4301 Initializes a workflow built from a trigger job, named by the job's key. 

4302 

4303 The other project, or the child pipeline's files, are the workflow's :attr:`~pyTooling.CI.Workflow.Reference`, 

4304 the job's rules the workflow's :attr:`~pyTooling.CI.RulesMixin.Rules`. 

4305 

4306 :param definition: The trigger job. 

4307 :param childFiles: Optional, the files the child pipeline's elements are built from. Default: ``None``. 

4308 :param keyValuePairs: Optional, mapping (dictionary) of key-value-pairs. Default: ``None``. 

4309 :param parent: Optional, reference to the workflow containing the trigger job. Default: ``None``. 

4310 :raises ValueError: If parameter 'definition' starts no pipeline. 

4311 """ 

4312 self._CheckDefinition(definition) 

4313 

4314 if definition._trigger is None: 

4315 ex = ValueError("Parameter 'definition' starts no pipeline.") 

4316 ex.add_note(f"Got job '{definition._name}'.") 

4317 raise ex 

4318 

4319 super().__init__( 

4320 definition._name, reference=DefinedWorkflow._Reference(definition), 

4321 rules=self._Rules(definition._rules, definition._when, RuleOutcome.DEFAULT), keyValuePairs=keyValuePairs, 

4322 parent=parent 

4323 ) 

4324 ChildPipelineMixin.__init__(self, childFiles) 

4325 DefinitionMixin.__init__(self, definition) 

4326 

4327 @staticmethod 

4328 def _Reference(definition: Job) -> str: 

4329 """ 

4330 Return what a trigger job starts, for :attr:`~pyTooling.CI.Workflow.Reference`. 

4331 

4332 :param definition: The trigger job. 

4333 :returns: The other project's path, or the child pipeline's files, as ``local: /ci/child.yml``. 

4334 """ 

4335 trigger = definition._trigger 

4336 if trigger._project is not None: 

4337 return trigger._project 

4338 

4339 return ", ".join(str(include) for include in trigger._includes) 

4340 

4341 

4342@export 

4343class DefinedMatrix(CIMatrix, DefinitionMixin[Job]): 

4344 """A job with ``parallel``, as :meth:`PipelineFile.ToPipeline` builds it: a matrix of its instances.""" 

4345 

4346 _DEFINITION_TYPE: ClassVar[type] = Job #: A matrix is built from a job with ``parallel``. 

4347 

4348 def __init__( 

4349 self, 

4350 definition: Job, 

4351 *, 

4352 keyValuePairs: Nullable[Mapping[Hashable, Any]] = None, 

4353 parent: Nullable[CIWorkflow] = None 

4354 ) -> None: 

4355 """ 

4356 Initializes a matrix built from a job with ``parallel``, named by the job's key. 

4357 

4358 :param definition: The job. 

4359 :param keyValuePairs: Optional, mapping (dictionary) of key-value-pairs. Default: ``None``. 

4360 :param parent: Optional, reference to the workflow containing the matrix. Default: ``None``. 

4361 :raises ValueError: If parameter 'definition' has no ``parallel``. 

4362 """ 

4363 self._CheckDefinition(definition) 

4364 

4365 if definition._parallel is None: 

4366 ex = ValueError("Parameter 'definition' has no 'parallel'.") 

4367 ex.add_note(f"Got job '{definition._name}'.") 

4368 raise ex 

4369 

4370 super().__init__( 

4371 definition._name, rules=self._Rules(definition._rules, definition._when, RuleOutcome.DEFAULT), 

4372 keyValuePairs=keyValuePairs, parent=parent 

4373 ) 

4374 DefinitionMixin.__init__(self, definition) 

4375 

4376 

4377@export 

4378class DefinedMatrixWorkflow(CIMatrixWorkflow, ChildPipelineMixin, DefinitionMixin[Job]): 

4379 """One instance of a trigger job with ``parallel``, as :meth:`PipelineFile.ToPipeline` builds it.""" 

4380 

4381 _DEFINITION_TYPE: ClassVar[type] = Job #: A matrix instance is built from the job with ``parallel``. 

4382 

4383 def __init__( 

4384 self, 

4385 definition: Job, 

4386 dimensions: Mapping[str, Any], 

4387 *, 

4388 childFiles: Nullable[Iterable[PipelineFile]] = None, 

4389 keyValuePairs: Nullable[Mapping[Hashable, Any]] = None, 

4390 parent: Nullable[CIMatrix] = None 

4391 ) -> None: 

4392 """ 

4393 Initializes one instance of a trigger job with ``parallel``, named by the job's key. 

4394 

4395 :param definition: The trigger job. 

4396 :param dimensions: The variables this instance runs with, as ``{"PROVIDER": "aws"}``, or 

4397 ``{"CI_NODE_INDEX": "2"}`` for ``parallel: N``. 

4398 :param childFiles: Optional, the files the child pipeline's elements are built from. Default: ``None``. 

4399 :param keyValuePairs: Optional, mapping (dictionary) of key-value-pairs. Default: ``None``. 

4400 :param parent: Optional, reference to the matrix containing the instance. Default: ``None``. 

4401 :raises ValueError: If parameter 'definition' starts no pipeline. 

4402 :raises ValueError: If parameter 'dimensions' is ``None``. 

4403 """ 

4404 self._CheckDefinition(definition) 

4405 

4406 if definition._trigger is None: 

4407 ex = ValueError("Parameter 'definition' starts no pipeline.") 

4408 ex.add_note(f"Got job '{definition._name}'.") 

4409 raise ex 

4410 elif dimensions is None: 

4411 raise ValueError("Parameter 'dimensions' is None.") 

4412 

4413 super().__init__( 

4414 definition._name, dimensions, reference=DefinedWorkflow._Reference(definition), 

4415 rules=self._Rules(definition._rules, definition._when, RuleOutcome.DEFAULT), keyValuePairs=keyValuePairs, 

4416 parent=parent 

4417 ) 

4418 ChildPipelineMixin.__init__(self, childFiles) 

4419 DefinitionMixin.__init__(self, definition) 

4420 

4421 def __str__(self) -> str: 

4422 """ 

4423 Return the name GitLab gives the instance. 

4424 

4425 :returns: The name, as ``test 1/3`` for ``parallel: N``, or ``test: [3.14, linux]`` for a matrix. 

4426 """ 

4427 return Parallel._InstanceName(self._name, self._definition._parallel._count, self._dimensions) 

4428 

4429 

4430@export 

4431class DefinedJob(CIJob, DefinitionMixin[Job]): 

4432 """A job running a script, as :meth:`PipelineFile.ToPipeline` builds it.""" 

4433 

4434 _DEFINITION_TYPE: ClassVar[type] = Job #: A job is built from its job in the configuration file. 

4435 

4436 def __init__( 

4437 self, 

4438 definition: Job, 

4439 *, 

4440 keyValuePairs: Nullable[Mapping[Hashable, Any]] = None, 

4441 parent: Nullable[JobGroup] = None 

4442 ) -> None: 

4443 """ 

4444 Initializes a job built from its job in the configuration file, named by the job's key. 

4445 

4446 :param definition: The job. 

4447 :param keyValuePairs: Optional, mapping (dictionary) of key-value-pairs. Default: ``None``. 

4448 :param parent: Optional, reference to the group containing the job. Default: ``None``. 

4449 """ 

4450 self._CheckDefinition(definition) 

4451 

4452 super().__init__( 

4453 definition._name, rules=self._Rules(definition._rules, definition._when, RuleOutcome.DEFAULT), 

4454 keyValuePairs=keyValuePairs, parent=parent 

4455 ) 

4456 DefinitionMixin.__init__(self, definition) 

4457 

4458 

4459@export 

4460class DefinedMatrixJob(CIMatrixJob, DefinitionMixin[Job]): 

4461 """One instance of a job with ``parallel``, as :meth:`PipelineFile.ToPipeline` builds it.""" 

4462 

4463 _DEFINITION_TYPE: ClassVar[type] = Job #: A matrix instance is built from the job with ``parallel``. 

4464 

4465 def __init__( 

4466 self, 

4467 definition: Job, 

4468 dimensions: Mapping[str, Any], 

4469 *, 

4470 keyValuePairs: Nullable[Mapping[Hashable, Any]] = None, 

4471 parent: Nullable[CIMatrix] = None 

4472 ) -> None: 

4473 """ 

4474 Initializes one instance of a job with ``parallel``, named by the job's key. 

4475 

4476 :param definition: The job. 

4477 :param dimensions: The variables this instance runs with, as ``{"PROVIDER": "aws"}``, or 

4478 ``{"CI_NODE_INDEX": "2"}`` for ``parallel: N``. 

4479 :param keyValuePairs: Optional, mapping (dictionary) of key-value-pairs. Default: ``None``. 

4480 :param parent: Optional, reference to the matrix containing the instance. Default: ``None``. 

4481 :raises ValueError: If parameter 'dimensions' is ``None``. 

4482 """ 

4483 self._CheckDefinition(definition) 

4484 

4485 if dimensions is None: 

4486 raise ValueError("Parameter 'dimensions' is None.") 

4487 

4488 super().__init__( 

4489 definition._name, dimensions, rules=self._Rules(definition._rules, definition._when, RuleOutcome.DEFAULT), 

4490 keyValuePairs=keyValuePairs, parent=parent 

4491 ) 

4492 DefinitionMixin.__init__(self, definition) 

4493 

4494 def __str__(self) -> str: 

4495 """ 

4496 Return the name GitLab gives the instance. 

4497 

4498 :returns: The name, as ``test 1/3`` for ``parallel: N``, or ``test: [3.14, linux]`` for a matrix. 

4499 """ 

4500 return Parallel._InstanceName(self._name, self._definition._parallel._count, self._dimensions)