pyTooling.GitLab.PipelineFile

pyTooling/GitLab/PipelineFile.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
4264
4265
4266
4267
4268
4269
4270
4271
4272
4273
4274
4275
4276
4277
4278
4279
4280
4281
4282
4283
4284
4285
4286
4287
4288
4289
4290
4291
4292
4293
4294
4295
4296
4297
4298
4299
4300
4301
4302
4303
4304
4305
4306
4307
4308
4309
4310
4311
4312
4313
4314
4315
4316
4317
4318
4319
4320
4321
4322
4323
4324
4325
4326
4327
4328
4329
4330
4331
4332
4333
4334
4335
4336
4337
4338
4339
4340
4341
4342
4343
4344
4345
4346
4347
4348
4349
4350
4351
4352
4353
4354
4355
4356
4357
4358
4359
4360
4361
4362
4363
4364
4365
4366
4367
4368
4369
4370
4371
4372
4373
4374
4375
4376
4377
4378
4379
4380
4381
4382
4383
4384
4385
4386
4387
4388
4389
4390
4391
4392
4393
4394
4395
4396
4397
4398
4399
4400
4401
4402
4403
4404
4405
4406
4407
4408
4409
4410
4411
4412
4413
4414
4415
4416
4417
4418
4419
4420
4421
4422
4423
4424
4425
4426
4427
4428
4429
4430
4431
4432
4433
4434
4435
4436
4437
4438
4439
4440
4441
4442
4443
4444
4445
4446
4447
4448
4449
4450
4451
4452
4453
4454
4455
4456
4457
4458
4459
4460
4461
4462
4463
4464
4465
4466
4467
4468
4469
4470
4471
4472
4473
4474
4475
4476
# ==================================================================================================================== #
#             _____           _ _               ____ _ _   _          _                                                #
#  _ __  _   |_   _|__   ___ | (_)_ __   __ _  / ___(_) |_| |    __ _| |__                                             #
# | '_ \| | | || |/ _ \ / _ \| | | '_ \ / _` || |  _| | __| |   / _` | '_ \                                            #
# | |_) | |_| || | (_) | (_) | | | | | | (_| || |_| | | |_| |__| (_| | |_) |                                           #
# | .__/ \__, ||_|\___/ \___/|_|_|_| |_|\__, (_)____|_|\__|_____\__,_|_.__/                                            #
# |_|    |___/                          |___/                                                                          #
# ==================================================================================================================== #
# Authors:                                                                                                             #
#   Patrick Lehmann                                                                                                    #
#                                                                                                                      #
# License:                                                                                                             #
# ==================================================================================================================== #
# Copyright 2026-2026 Patrick Lehmann - Bötzingen, Germany                                                             #
#                                                                                                                      #
# Licensed under the Apache License, Version 2.0 (the "License");                                                      #
# you may not use this file except in compliance with the License.                                                     #
# You may obtain a copy of the License at                                                                              #
#                                                                                                                      #
#   http://www.apache.org/licenses/LICENSE-2.0                                                                         #
#                                                                                                                      #
# Unless required by applicable law or agreed to in writing, software                                                  #
# distributed under the License is distributed on an "AS IS" BASIS,                                                    #
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.                                             #
# See the License for the specific language governing permissions and                                                  #
# limitations under the License.                                                                                       #
#                                                                                                                      #
# SPDX-License-Identifier: Apache-2.0                                                                                  #
# ==================================================================================================================== #
"""
A data model of a GitLab CI/CD configuration file.

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

.. tree::

   - :class:`PipelineFile` | a configuration file, e.g. :file:`.gitlab-ci.yml`
     - :class:`Input`      | an input of the header's ``spec:inputs``
     - :class:`Workflow`   | the ``workflow`` key
       - :class:`Rule`     | a rule deciding whether a pipeline is created
     - :class:`Include`    | an entry of ``include``
       - :class:`Rule`     | a rule deciding whether the file is included
     - :class:`Default`    | the ``default`` key
     - :class:`Variable`   | a default variable, declared in the top-level ``variables``
     - :class:`Job`        | a job or a hidden job, in file order
       - :class:`Need`     | an entry of the job's ``needs``
         - :class:`Parallel` | the matrix instances needed
       - :class:`Rule`     | a rule deciding whether the job is added to a pipeline
       - :class:`Variable` | a variable of the job
       - :class:`Input`    | an input of the job
       - :class:`Parallel` | the job's ``parallel``: how often it runs, or its matrix
       - :class:`Trigger`  | the child pipeline or other project's pipeline the job starts
         - :class:`Include` | a file of the child pipeline

Every element knows its parent, the file it belongs to and the line it starts at, so a consumer can name the place a
finding comes from, as ``.gitlab-ci.yml:42``.

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

The model is independent of :mod:`pyTooling.GitLab`, which models a pipeline *run* as the REST API reports it.
:meth:`PipelineFile.ToPipeline` builds the pipeline a file defines as a :mod:`pyTooling.CI` model, whose elements link
back to the jobs they were built from.
"""
from __future__               import annotations

from itertools                import product
from pathlib                  import Path
from typing                   import Any, ClassVar, Generic, Hashable, Iterable, Iterator, Mapping, Optional as Nullable
from typing                   import Self, Sequence, TypeVar, Union

from pyTooling.CI             import DependencyMixin, Job as CIJob, JobGroup, Matrix as CIMatrix
from pyTooling.CI             import MatrixJob as CIMatrixJob, MatrixWorkflow as CIMatrixWorkflow
from pyTooling.CI             import Pipeline as CIPipeline, Rule as CIRule, RuleOutcome, Workflow as CIWorkflow

from pyTooling.Common         import getFullyQualifiedName, StringEnum
from pyTooling.Decorators     import export, readonly
from pyTooling.MetaClasses    import ExtendedType, abstractclass

from pyTooling.GitLab         import GitLabError

from ruamel.yaml              import YAML, YAMLError
from ruamel.yaml.comments     import CommentedMap, CommentedSeq
from ruamel.yaml.scalarbool   import ScalarBoolean
from ruamel.yaml.scalarfloat  import ScalarFloat
from ruamel.yaml.scalarint    import ScalarInt
from ruamel.yaml.scalarstring import ScalarString


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

ValueT = Union[str, bool, int, float, None, list["ValueT"], dict[str, "ValueT"]]
"""A value read from a configuration file, converted to plain Python types."""

ParentType = TypeVar("ParentType", bound="Base")
"""A type variable for the type of an element's parent."""

ParentTypes = Nullable[Union[type, tuple[type, ...]]]
"""The type of :attr:`Base._PARENT_TYPE`: ``None``, a class, or a tuple of classes."""

DefinitionType = TypeVar("DefinitionType", bound="Base")
"""A type variable for the type of the file's element an element of :mod:`pyTooling.CI` is built from."""

RESERVED_KEYS = frozenset((
	"default", "include", "stages", "variables", "workflow", "image", "services", "cache", "before_script", "after_script"
))
"""Top-level keys of a configuration file, which declare no job."""

DEFAULT_STAGES = ("build", "test", "deploy")
"""Stages of a pipeline, whose configuration declares no ``stages``, between ``.pre`` and ``.post``."""

MAX_EXTENDS_DEPTH = 11
"""How many levels of ``extends`` GitLab resolves."""

MAX_REFERENCE_DEPTH = 10
"""How many levels of ``!reference`` tags GitLab resolves."""


@export
class PipelineFileError(GitLabError):
	"""
	Base-exception of all exceptions raised by :mod:`pyTooling.GitLab.PipelineFile`.

	The exception is raised for a file that is not a well-formed configuration. It carries the file and the line the
	problem was found at in :attr:`Path` and :attr:`Line`, and names both in a note.
	"""

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

	def __init__(self, message: str, path: Nullable[Path] = None, line: Nullable[int] = None) -> None:
		"""
		Initializes a configuration error and names the place it was found at in a note.

		:param message: The exception's message.
		:param path:    Optional, path to the configuration file. Default: ``None``.
		:param line:    Optional, line in the configuration file, starting at 1. Default: ``None``.
		"""
		super().__init__(message)

		self._path = path
		self._line = line

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

	@readonly
	def Path(self) -> Nullable[Path]:
		"""
		Read-only property to access the path to the configuration file (:attr:`_path`).

		:returns: The path, or ``None`` if the problem isn't tied to a file.
		"""
		return self._path

	@readonly
	def Line(self) -> Nullable[int]:
		"""
		Read-only property to access the line the problem was found at (:attr:`_line`).

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


@export
class IncludeKind(StringEnum):
	"""Where an included file comes from, as the key of an ``include`` entry names it."""

	Local =     "local"      #: A file of the same repository.
	Project =   "project"    #: Files of another project.
	Remote =    "remote"     #: A file at a URL.
	Template =  "template"   #: A CI/CD template shipped with GitLab.
	Component = "component"  #: A CI/CD component.
	Artifact =  "artifact"   #: A file a job of the pipeline created, for a dynamic child pipeline.


@export
class InputType(StringEnum):
	"""The type of an input, as ``type`` names it."""

	String =  "string"   #: A string.
	Number =  "number"   #: A number.
	Boolean = "boolean"  #: ``true`` or ``false``.
	Array =   "array"    #: A list of values.


@export
class TriggerStrategy(StringEnum):
	"""How a trigger job's status follows the pipeline it starts, as ``trigger.strategy`` names it."""

	Depend = "depend"  #: The trigger job waits for the pipeline, and reports failed, success or running.
	Mirror = "mirror"  #: The trigger job waits for the pipeline, and mirrors its status exactly.


@export
class NeedKind(StringEnum):
	"""What an entry of ``needs`` refers to."""

	Job =            "job"              #: A job of the same pipeline.
	PipelineJob =    "pipeline-job"     #: A job of another pipeline in the same parent-child hierarchy.
	ProjectJob =     "project-job"      #: A job of another project's pipeline, whose artifacts are downloaded.
	PipelineStatus = "pipeline-status"  #: The status of another project's pipeline, which the job mirrors.


@export
@abstractclass
class Base(Generic[ParentType], metaclass=ExtendedType, slots=True):
	"""
	Common behaviour of every element of a configuration file.

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

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

	_parent:       Nullable[ParentType]    #: Reference to the containing element.
	_pipelineFile: Nullable[PipelineFile]  #: Reference to the configuration file this element belongs to.
	_line:         int                     #: Line the element starts at in its file, starting at 1.

	def __init__(self, line: int, *, parent: Nullable[ParentType] = None) -> None:
		"""
		Initializes an element of a configuration file.

		:param line:        Line the element starts at in the configuration file, starting at 1.
		:param parent:      Optional, reference to the containing element. Default: ``None``.
		:raises ValueError: If parameter 'line' is ``None``.
		:raises TypeError:  If parameter 'line' is not of type :class:`int`.
		:raises ValueError: If parameter 'line' is not positive.
		:raises TypeError:  If parameter 'parent' is not of the type this class declares in :attr:`_PARENT_TYPE`.
		"""
		if line is None:
			raise ValueError("Parameter 'line' is None.")
		elif not isinstance(line, int) or isinstance(line, bool):
			ex = TypeError("Parameter 'line' is not of type 'int'.")
			ex.add_note(f"Got type '{getFullyQualifiedName(line)}'.")
			raise ex
		elif line < 1:
			ex = ValueError("Parameter 'line' is not positive.")
			ex.add_note(f"Got value '{line}'.")
			raise ex

		if parent is not None and not isinstance(parent, self._PARENT_TYPE):
			parentTypes = self._PARENT_TYPE if isinstance(self._PARENT_TYPE, tuple) else (self._PARENT_TYPE, )
			ex = TypeError(f"Parameter 'parent' is not of type {' or '.join(f'{t.__name__!r}' for t in parentTypes)}.")
			ex.add_note(f"Got type '{getFullyQualifiedName(parent)}'.")
			raise ex

		self._parent =       parent
		self._pipelineFile = None if parent is None else parent._pipelineFile
		self._line =         line

	@property
	def Parent(self) -> Nullable[ParentType]:
		"""
		Property to access the containing element (:attr:`_parent`).

		Assigning a parent attaches an element constructed before it: the element takes the parent's configuration file,
		and so do the elements it contains.

		:returns:           The containing element, or ``None`` for a :class:`PipelineFile`.
		:raises ValueError: If ``None`` is assigned.
		:raises TypeError:  If a parent is assigned to a :class:`PipelineFile`, which has no parent.
		:raises TypeError:  If an assigned value is not of the type this class declares in :attr:`_PARENT_TYPE`.
		"""
		return self._parent

	@Parent.setter
	def Parent(self, value: ParentType) -> None:
		if value is None:
			raise ValueError("Parameter 'value' is None.")
		elif not isinstance(value, self._PARENT_TYPE):
			parentTypes = self._PARENT_TYPE if isinstance(self._PARENT_TYPE, tuple) else (self._PARENT_TYPE, )
			ex = TypeError(f"Parameter 'value' is not of type {' or '.join(f'{t.__name__!r}' for t in parentTypes)}.")
			ex.add_note(f"Got type '{getFullyQualifiedName(value)}'.")
			raise ex

		self._parent =       value
		self._pipelineFile = value._pipelineFile

	@readonly
	def PipelineFile(self) -> Nullable[PipelineFile]:
		"""
		Read-only property to access the configuration file this element belongs to (:attr:`_pipelineFile`).

		:returns: The configuration file, or ``None`` for an element outside one.
		"""
		return self._pipelineFile

	@readonly
	def Line(self) -> int:
		"""
		Read-only property to access the line the element starts at in its file (:attr:`_line`).

		:returns: The line, starting at 1.
		"""
		return self._line

	@readonly
	def Location(self) -> str:
		"""
		Read-only property to return the place the element is written at, for a message.

		:returns: The file's name and the line, as ``.gitlab-ci.yml:42``, or ``line 42`` for an element outside a file.
		"""
		if self._pipelineFile is None:
			return f"line {self._line}"

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

	@staticmethod
	def _KeyLine(mapping: CommentedMap, key: Any) -> int:
		"""
		Return the line a key of a mapping is written at.

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

		:param mapping: The mapping read from the file.
		:param key:     The key.
		:returns:       The line, starting at 1.
		"""
		try:
			return mapping.lc.key(key)[0] + 1
		except KeyError:
			return mapping.lc.line + 1

	@staticmethod
	def _ItemLine(sequence: CommentedSeq, index: int) -> int:
		"""
		Return the line an item of a sequence is written at.

		:param sequence: The sequence read from the file.
		:param index:    Position of the item, starting at 0.
		:returns:        The line, starting at 1.
		"""
		return sequence.lc.item(index)[0] + 1

	@staticmethod
	def _ToPython(value: Any) -> ValueT:
		"""
		Convert a value read by ``ruamel.yaml`` into plain Python types.

		The round-trip loader returns its own types for mappings, lists, block scalars, anchored booleans, and numbers
		written in another notation than a plain decimal. They derive from the Python types, but keep what they were
		read with. Every other value is a Python type already.

		:param value: The value read from the file.
		:returns:     The value as :class:`dict`, :class:`list`, :class:`str`, :class:`bool`, :class:`int`,
		              :class:`float` or ``None``.
		"""
		if isinstance(value, CommentedMap):
			return {str(key): Base._ToPython(item) for key, item in value.items()}
		elif isinstance(value, CommentedSeq):
			return [Base._ToPython(item) for item in value]
		elif isinstance(value, ScalarBoolean):
			return bool(value)
		elif isinstance(value, ScalarInt):
			return int(value)
		elif isinstance(value, ScalarFloat):
			return float(value)
		elif isinstance(value, ScalarString):
			return str(value)

		return value

	@staticmethod
	def _ToText(value: Any) -> str:
		"""
		Convert a scalar read from the file into the text GitLab uses, so ``true`` stays ``true`` and not ``True``.

		:param value: The scalar.
		:returns:     The text.
		"""
		value = Base._ToPython(value)
		if isinstance(value, bool):
			return "true" if value else "false"

		return str(value)


@export
class PipelineFile(Base[None]):
	"""
	A GitLab CI/CD configuration file.

	A top-level key names a job, unless it is a global keyword (:data:`RESERVED_KEYS`). A job whose name starts with a
	dot is a hidden job: GitLab doesn't run it, other jobs extend it.
	"""

	_path:        Path                       #: Path to the configuration file.
	_stages:      Nullable[tuple[str, ...]]  #: Stages, as the ``stages`` key declares them.
	_variables:   dict[str, Variable]        #: Default variables, by name, in file order.
	_jobs:        dict[str, Job]             #: Jobs, by name, in file order.
	_hiddenJobs:  dict[str, Job]             #: Hidden jobs, by name, in file order.
	_workflow:    Nullable[Workflow]         #: The ``workflow`` key.
	_includes:    list[Include]              #: Entries of ``include``, in file order.
	_default:     Nullable[Default]          #: The ``default`` key.
	_inputs:      dict[str, Input]           #: Inputs of the header's ``spec:inputs``, by name, in file order.
	_description: Nullable[str]              #: Description of the header's ``spec:description``.

	def __init__(
		self,
		path:        Path,
		stages:      Nullable[Iterable[str]]      = None,
		variables:   Nullable[Iterable[Variable]] = None,
		jobs:        Nullable[Iterable[Job]]      = None,
		workflow:    Nullable[Workflow]           = None,
		includes:    Nullable[Iterable[Include]]  = None,
		default:     Nullable[Default]            = None,
		inputs:      Nullable[Iterable[Input]]    = None,
		description: Nullable[str]                = None
	) -> None:
		"""
		Initializes a configuration file.

		A variable, job, workflow, include, default or input is attached by passing it, or by constructing it with the
		configuration file as parent. Use :meth:`FromFile` to read a configuration file.

		:param path:        Path to the configuration file.
		:param stages:      Optional, stages as the ``stages`` key declares them. Default: ``None``, for a file without a
		                    ``stages`` key.
		:param variables:   Optional, default variables, which are attached to the file. Default: ``None``.
		:param jobs:        Optional, jobs and hidden jobs, which are attached to the file. Default: ``None``.
		:param workflow:    Optional, the ``workflow`` key, which is attached to the file. Default: ``None``.
		:param includes:    Optional, entries of ``include``, which are attached to the file. Default: ``None``.
		:param default:     Optional, the ``default`` key, which is attached to the file. Default: ``None``.
		:param inputs:      Optional, inputs of the header's ``spec:inputs``, which are attached to the file. Default:
		                    ``None``.
		:param description: Optional, description of the header's ``spec:description``. Default: ``None``.
		:raises ValueError: If parameter 'path' is ``None``.
		:raises TypeError:  If parameter 'path' is not of type :class:`~pathlib.Path`.
		:raises TypeError:  If an element of parameter 'stages' is not of type :class:`str`.
		:raises TypeError:  If an element of parameter 'variables' is not of type :class:`Variable`.
		:raises TypeError:  If an element of parameter 'jobs' is not of type :class:`Job`.
		:raises TypeError:  If parameter 'workflow' is not of type :class:`Workflow`.
		:raises TypeError:  If an element of parameter 'includes' is not of type :class:`Include`.
		:raises TypeError:  If parameter 'default' is not of type :class:`Default`.
		:raises TypeError:  If an element of parameter 'inputs' is not of type :class:`Input`.
		:raises TypeError:  If parameter 'description' is not of type :class:`str`.
		"""
		super().__init__(1)

		if path is None:
			raise ValueError("Parameter 'path' is None.")
		elif not isinstance(path, Path):
			ex = TypeError("Parameter 'path' is not of type 'Path'.")
			ex.add_note(f"Got type '{getFullyQualifiedName(path)}'.")
			raise ex

		if description is not None and not isinstance(description, str):
			ex = TypeError("Parameter 'description' is not of type 'str'.")
			ex.add_note(f"Got type '{getFullyQualifiedName(description)}'.")
			raise ex

		self._pipelineFile = self
		self._path =         path
		self._stages =       None
		self._variables =    {}
		self._jobs =         {}
		self._hiddenJobs =   {}
		self._workflow =     None
		self._includes =     []
		self._default =      None
		self._inputs =       {}
		self._description =  description

		if stages is not None:
			self._stages = tuple(stages)
			for stage in self._stages:
				if not isinstance(stage, str):
					ex = TypeError("An element of parameter 'stages' is not of type 'str'.")
					ex.add_note(f"Got type '{getFullyQualifiedName(stage)}'.")
					raise ex

		if variables is not None:
			for variable in variables:
				if not isinstance(variable, Variable):
					ex = TypeError("An element of parameter 'variables' is not of type 'Variable'.")
					ex.add_note(f"Got type '{getFullyQualifiedName(variable)}'.")
					raise ex

				self._variables[variable._name] = variable
				variable.Parent = self

		if jobs is not None:
			for job in jobs:
				if not isinstance(job, Job):
					ex = TypeError("An element of parameter 'jobs' is not of type 'Job'.")
					ex.add_note(f"Got type '{getFullyQualifiedName(job)}'.")
					raise ex

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

		if workflow is not None:
			if not isinstance(workflow, Workflow):
				ex = TypeError("Parameter 'workflow' is not of type 'Workflow'.")
				ex.add_note(f"Got type '{getFullyQualifiedName(workflow)}'.")
				raise ex

			self._workflow = workflow
			workflow.Parent = self

		if includes is not None:
			for include in includes:
				if not isinstance(include, Include):
					ex = TypeError("An element of parameter 'includes' is not of type 'Include'.")
					ex.add_note(f"Got type '{getFullyQualifiedName(include)}'.")
					raise ex

				self._includes.append(include)
				include.Parent = self

		if default is not None:
			if not isinstance(default, Default):
				ex = TypeError("Parameter 'default' is not of type 'Default'.")
				ex.add_note(f"Got type '{getFullyQualifiedName(default)}'.")
				raise ex

			self._default = default
			default.Parent = self

		if inputs is not None:
			for parameter in inputs:
				if not isinstance(parameter, Input):
					ex = TypeError("An element of parameter 'inputs' is not of type 'Input'.")
					ex.add_note(f"Got type '{getFullyQualifiedName(parameter)}'.")
					raise ex

				self._inputs[parameter._name] = parameter
				parameter.Parent = self

	@Base.Parent.setter
	def Parent(self, value: None) -> None:
		ex = TypeError(f"A '{getFullyQualifiedName(self)}' has no parent.")
		ex.add_note(f"Got type '{getFullyQualifiedName(value)}'.")
		raise ex

	@readonly
	def Path(self) -> Path:
		"""
		Read-only property to access the path to the configuration file (:attr:`_path`).

		:returns: The path.
		"""
		return self._path

	@readonly
	def Inputs(self) -> dict[str, Input]:
		"""
		Read-only property to access the inputs of the header's ``spec:inputs`` (:attr:`_inputs`).

		:returns: The inputs, by name, in file order.
		"""
		return self._inputs

	@readonly
	def Description(self) -> Nullable[str]:
		"""
		Read-only property to access the description of the header's ``spec:description`` (:attr:`_description`).

		:returns: The description, or ``None`` if the file gives none.
		"""
		return self._description

	@readonly
	def DeclaredStages(self) -> Nullable[tuple[str, ...]]:
		"""
		Read-only property to access the stages as the ``stages`` key declares them (:attr:`_stages`).

		:returns: The stages, in the order they run, or ``None`` if the file has no ``stages`` key.
		"""
		return self._stages

	@readonly
	def Stages(self) -> tuple[str, ...]:
		"""
		Read-only property to return the stages of the pipeline, in the order they run.

		The stages are those of :attr:`DeclaredStages`, or :data:`DEFAULT_STAGES` without a ``stages`` key, and always
		begin with ``.pre`` and end with ``.post``.

		:returns: The stages.
		"""
		stages = DEFAULT_STAGES if self._stages is None else self._stages
		return (".pre", *(stage for stage in stages if stage not in (".pre", ".post")), ".post")

	@readonly
	def Variables(self) -> dict[str, Variable]:
		"""
		Read-only property to access the default variables (:attr:`_variables`).

		:returns: The variables, by name, in file order.
		"""
		return self._variables

	@readonly
	def Jobs(self) -> dict[str, Job]:
		"""
		Read-only property to access the jobs (:attr:`_jobs`).

		:returns: The jobs, by name, in file order.
		"""
		return self._jobs

	@readonly
	def HiddenJobs(self) -> dict[str, Job]:
		"""
		Read-only property to access the hidden jobs (:attr:`_hiddenJobs`).

		:returns: The hidden jobs, by name, in file order.
		"""
		return self._hiddenJobs

	@readonly
	def Workflow(self) -> Nullable[Workflow]:
		"""
		Read-only property to access the ``workflow`` key (:attr:`_workflow`).

		:returns: The workflow, or ``None`` if the file has no ``workflow`` key.
		"""
		return self._workflow

	@readonly
	def Includes(self) -> list[Include]:
		"""
		Read-only property to access the entries of ``include`` (:attr:`_includes`).

		:returns: The entries, in file order.
		"""
		return self._includes

	@readonly
	def Default(self) -> Nullable[Default]:
		"""
		Read-only property to access the ``default`` key (:attr:`_default`).

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

	@readonly
	def JobCount(self) -> int:
		"""
		Read-only property to return the number of jobs, hidden jobs not counted.

		:returns: Number of jobs.
		"""
		return len(self._jobs)

	def ContainsJob(self, name: str) -> bool:
		"""
		Check whether the file has a job of that name.

		:param name: Name of the job, the key it is declared under.
		:returns:    ``True``, if the file has a job of that name. A hidden job isn't a job.
		"""
		return name in self._jobs

	def IterateJobs(self) -> Iterator[Job]:
		"""
		Iterate the jobs, hidden jobs not included.

		:returns: An iterator over the jobs, in file order.
		"""
		return iter(self._jobs.values())

	def IterateHiddenJobs(self) -> Iterator[Job]:
		"""
		Iterate the hidden jobs.

		:returns: An iterator over the hidden jobs, in file order.
		"""
		return iter(self._hiddenJobs.values())

	def __str__(self) -> str:
		"""
		Return the file's name.

		:returns: Name of the configuration file.
		"""
		return self._path.name

	def ToPipeline(self, resolver: Nullable[IncludeResolver] = None, depth: Nullable[int] = None) -> DefinedPipeline:
		"""
		Build the service-independent model of the pipeline this file defines.

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

		* a job running a script becomes a :class:`DefinedJob`;
		* a trigger job becomes a :class:`DefinedWorkflow`, holding the elements of its child pipeline, if the resolver
		  reads the child pipeline's files and the depth allows it;
		* a job with ``parallel`` becomes a :class:`DefinedMatrix`, holding a :class:`DefinedMatrixJob` or a
		  :class:`DefinedMatrixWorkflow` per instance.

		The ``needs`` of a job become the element's :attr:`~pyTooling.CI.DependencyMixin.Needs`; a job without ``needs``
		needs every element of the nearest earlier stage holding elements. A need of some instances of a matrix needs the
		whole matrix. So :meth:`~pyTooling.CI.Workflow.ToGraph` converts the result into a graph.

		:param resolver:           Optional, the resolver reading the files of the child pipelines. Without it, child
		                           pipelines are not expanded. Default: ``None``.
		:param depth:              Optional, how many levels of child pipelines to expand; ``0`` expands none, ``None``
		                           every level. Default: ``None``.
		:returns:                  The pipeline.
		:raises TypeError:         If parameter 'resolver' is not of type :class:`IncludeResolver`.
		:raises TypeError:         If parameter 'depth' is not of type :class:`int`.
		:raises ValueError:        If parameter 'depth' is negative.
		:raises PipelineFileError: If a child pipeline's file is not a well-formed configuration, or runs itself.
		"""
		if resolver is not None and not isinstance(resolver, IncludeResolver):
			ex = TypeError("Parameter 'resolver' is not of type 'IncludeResolver'.")
			ex.add_note(f"Got type '{getFullyQualifiedName(resolver)}'.")
			raise ex

		if depth is not None and (not isinstance(depth, int) or isinstance(depth, bool)):
			ex = TypeError("Parameter 'depth' is not of type 'int'.")
			ex.add_note(f"Got type '{getFullyQualifiedName(depth)}'.")
			raise ex
		elif depth is not None and depth < 0:
			ex = ValueError("Parameter 'depth' is negative.")
			ex.add_note(f"Got value '{depth}'.")
			raise ex

		def childFiles(job: Job, level: int, callers: tuple[PipelineFile, ...]) -> list[PipelineFile]:
			"""
			Nested function reading the files of a trigger job's child pipeline.

			:param job:                The trigger job.
			:param level:              How many levels of child pipelines are expanded above this one.
			:param callers:            The files expanded above this one, this one last.
			:returns:                  The files the resolver reads, if the depth allows expanding them.
			:raises PipelineFileError: If a child pipeline runs a file expanded above it.
			"""
			if resolver is None or job._trigger is None or (depth is not None and level >= depth):
				return []

			files = []
			for include in job._trigger._includes:
				if (child := resolver.Resolve(include)) is None:
					continue
				elif any(caller._path.resolve() == child._path.resolve() for caller in callers):
					ex = PipelineFileError(f"Child pipeline '{child._path.name}' runs itself.", callers[-1]._path, include._line)
					ex.add_note(f"Runs: {' -> '.join(caller._path.name for caller in (*callers, child))}.")
					raise ex

				files.append(child)

			return files

		def addElements(
			pipelineFile: PipelineFile,
			group:        CIWorkflow,
			level:        int,
			callers:      tuple[PipelineFile, ...]
		) -> None:
			"""
			Nested function for recursion, adding the elements of a file's jobs to a group.

			:param pipelineFile:       The file whose jobs become elements.
			:param group:              The group the elements are added to.
			:param level:              How many levels of child pipelines are expanded above this one.
			:param callers:            The files expanded above this one, this one last.
			:raises PipelineFileError: If a child pipeline runs a file expanded above it.
			"""
			elements: dict[str, DependencyMixin] = {}
			for job in pipelineFile._jobs.values():
				children = childFiles(job, level, callers)
				if job._parallel is not None:
					element = DefinedMatrix(job, parent=group)
					if job._parallel._count is not None:
						dimensions = [{"CI_NODE_INDEX": str(index)} for index in range(1, job._parallel._count + 1)]
					else:
						dimensions = job._parallel.Combinations

					for dimension in dimensions:
						if job._trigger is None:
							DefinedMatrixJob(job, dimension, parent=element)
						else:
							instance = DefinedMatrixWorkflow(job, dimension, childFiles=children, parent=element)
							for child in children:
								addElements(child, instance, level + 1, (*callers, child))
				elif job._trigger is not None:
					element = DefinedWorkflow(job, childFiles=children, parent=group)
					for child in children:
						addElements(child, element, level + 1, (*callers, child))
				else:
					element = DefinedJob(job, parent=group)

				elements[job._name] = element

			stages = pipelineFile.Stages
			byStage: dict[int, list[str]] = {}
			for job in pipelineFile._jobs.values():
				if job._stage in stages:
					byStage.setdefault(stages.index(job._stage), []).append(job._name)

			for job in pipelineFile._jobs.values():
				if job._needs is not None:
					for need in job._needs:
						if need._kind is NeedKind.Job and need._job in elements:
							elements[job._name].AddNeed(elements[need._job])
				elif job._stage in stages:
					earlier = [index for index in byStage if index < stages.index(job._stage)]
					for name in byStage[max(earlier)] if len(earlier) > 0 else ():
						elements[job._name].AddNeed(elements[name])

		pipeline = DefinedPipeline(self)
		addElements(self, pipeline, 0, (self, ))
		pipeline.Validate()

		return pipeline

	@classmethod
	def FromFile(cls, path: Path, resolver: Nullable[IncludeResolver] = None) -> Self:
		"""
		Read a configuration file.

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

		With a resolver, the local files the file includes are read too, so a job may extend their jobs and a
		``!reference`` tag refer to their keys. The included jobs aren't jobs of this file.

		:param path:               Path to the configuration file.
		:param resolver:           Optional, the resolver reading the local files the file includes. Default: ``None``.
		:returns:                  The configuration file, with its variables and jobs attached.
		:raises ValueError:        If parameter 'path' is ``None``.
		:raises TypeError:         If parameter 'path' is not of type :class:`~pathlib.Path`.
		:raises TypeError:         If parameter 'resolver' is not of type :class:`IncludeResolver`.
		:raises PipelineFileError: If the file doesn't exist.
		:raises PipelineFileError: If the file can't be read.
		:raises PipelineFileError: If the file is not a YAML document.
		:raises PipelineFileError: If the file holds more than two documents, or its first of two documents has no
		                           ``spec`` key.
		:raises PipelineFileError: If the configuration is not a mapping.
		:raises PipelineFileError: If a key holds a value of the wrong kind.
		:raises PipelineFileError: If an input is malformed, or its default doesn't match its type or options.
		:raises PipelineFileError: If a job is in a stage the pipeline doesn't have. |br|
		                           The note lists the stages.
		:raises PipelineFileError: If a job needs a job the file doesn't have, or the jobs need each other in a cycle. |br|
		                           For an unknown job, the note lists the file's jobs.
		"""
		if path is None:
			raise ValueError("Parameter 'path' is None.")
		elif not isinstance(path, Path):
			ex = TypeError("Parameter 'path' is not of type 'Path'.")
			ex.add_note(f"Got type '{getFullyQualifiedName(path)}'.")
			raise ex

		if resolver is not None and not isinstance(resolver, IncludeResolver):
			ex = TypeError("Parameter 'resolver' is not of type 'IncludeResolver'.")
			ex.add_note(f"Got type '{getFullyQualifiedName(resolver)}'.")
			raise ex

		header, document = cls._Load(path)
		included: dict[str, Any] = {}
		incomplete = "include" in document
		if resolver is not None:
			included, incomplete = resolver._Included(document, path, (path.resolve(), ))

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

		return pipelineFile

	@staticmethod
	def _Load(path: Path) -> tuple[Nullable[CommentedMap], CommentedMap]:
		"""
		Read the documents of a configuration file.

		:param path:               Path to the configuration file.
		:returns:                  The header document, or ``None``, and the configuration.
		:raises PipelineFileError: If the file doesn't exist, can't be read, or is not a YAML document.
		:raises PipelineFileError: If the file holds more than two documents, or its first of two documents has no
		                           ``spec`` key.
		:raises PipelineFileError: If the configuration is not a mapping.
		"""
		if not path.exists():
			raise PipelineFileError("Configuration file doesn't exist.", path) from FileNotFoundError(path)

		try:
			content = path.read_text(encoding="utf-8")
		except OSError as cause:
			raise PipelineFileError("Configuration file can't be read.", path) from cause

		try:
			documents = list(YAML(typ="rt").load_all(content))
		except YAMLError as cause:
			mark = getattr(cause, "problem_mark", None)
			line = None if mark is None else mark.line + 1
			raise PipelineFileError("Configuration file is not a YAML document.", path, line) from cause

		header = None
		if len(documents) > 2:
			raise PipelineFileError("Configuration file holds more than two documents.", path)
		elif len(documents) == 2:
			header = documents[0]
			if not isinstance(header, CommentedMap) or "spec" not in header:
				raise PipelineFileError("Header document of configuration file has no 'spec' key.", path, 1)

		document = documents[-1] if len(documents) > 0 else None
		if document is None:
			document = CommentedMap()
		elif not isinstance(document, CommentedMap):
			ex = PipelineFileError("Configuration is not a mapping.", path)
			ex.add_note(f"Got type '{getFullyQualifiedName(document)}'.")
			raise ex

		return header, document

	@classmethod
	def _Parse(
		cls,
		document:   CommentedMap,
		path:       Path,
		header:     Nullable[CommentedMap]      = None,
		included:   Nullable[Mapping[str, Any]] = None,
		incomplete: Nullable[bool]              = None
	) -> Self:
		"""
		Build a configuration file and the elements it contains from the documents read from it.

		:param document:           The configuration, a mapping.
		:param path:               Path to the configuration file.
		:param header:             Optional, the header document, a mapping with key ``spec``. Default: ``None``.
		:param included:           Optional, the top-level keys of the included files read. Default: ``None``.
		:param incomplete:         Optional, ``True``, if the file includes files that weren't read. Default: ``None``,
		                           for ``True`` if the file includes files.
		:returns:                  The configuration file, with its variables, jobs, workflow, includes and default
		                           attached.
		:raises PipelineFileError: If key ``spec`` or ``spec:inputs`` of the header is not a mapping, or an input is
		                           malformed.
		:raises PipelineFileError: If key ``stages`` is not a list.
		:raises PipelineFileError: If key ``variables``, ``workflow`` or a job is not a mapping.
		:raises PipelineFileError: If a job extends a job, or a ``!reference`` tag refers to a key, the file doesn't have,
		                           though it includes no files.
		:raises PipelineFileError: If jobs extend each other in a cycle, or ``extends`` or ``!reference`` tags nest too
		                           deep.
		:raises PipelineFileError: If a key of a variable, a job, the workflow or an include holds a value of the wrong
		                           kind.
		"""
		stages = None
		if (stageList := document.get("stages", None)) is not None:
			if not isinstance(stageList, CommentedSeq):
				ex = PipelineFileError("Key 'stages' is not a list.", path, Base._KeyLine(document, "stages"))
				ex.add_note(f"Got type '{getFullyQualifiedName(stageList)}'.")
				raise ex

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

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

		jobs = []
		for name, (mapping, unresolved) in cls._ResolveJobs(document, path, included, incomplete).items():
			jobs.append(Job._FromYAML(name, mapping, path, Base._KeyLine(document, name), unresolved))

		workflow = None
		if "workflow" in document:
			workflow = Workflow._FromYAML(document["workflow"], path, Base._KeyLine(document, "workflow"))

		includes = None
		if "include" in document:
			includes = Include._FromYAMLEntries(document["include"], path, Base._KeyLine(document, "include"))

		default = Default._FromYAML(document, path)

		inputs = None
		description = None
		if header is not None:
			spec = header["spec"]
			if not isinstance(spec, CommentedMap):
				ex = PipelineFileError("Key 'spec' of the header is not a mapping.", path, Base._KeyLine(header, "spec"))
				ex.add_note(f"Got type '{getFullyQualifiedName(spec)}'.")
				raise ex

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

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

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

	@classmethod
	def _ResolveJobs(
		cls,
		document:   CommentedMap,
		path:       Path,
		included:   Nullable[Mapping[str, Any]] = None,
		incomplete: Nullable[bool]              = None
	) -> dict[str, tuple[CommentedMap, list[str]]]:
		"""
		Resolve the ``!reference`` tags, the ``extends`` and the ``default`` of every job, as GitLab merges them.

		A ``!reference`` tag is replaced by the value it refers to; one in a list of a list's items is spliced into it.
		A job's mapping is the deep merge of the jobs it extends, in order, and of its own keys: mappings merge, other
		values - lists included - replace, and ``null`` removes a key. A job then gets every key of ``default``, and of
		the global keywords standing for it, which it doesn't set, unless ``inherit.default`` says otherwise.

		A job may extend the jobs, and a reference refer to the keys, of the included files read. Every key keeps the line
		it is written at; a key an included file contributes gets the line of the ``extends`` key or the reference
		bringing it in. What a job refers to, but neither the file nor an included file has, is an error - unless the file
		includes files that weren't read, which may have it: then it is skipped and reported in the job's ``unresolved``
		list.

		:param document:           The configuration.
		:param path:               Path to the configuration file.
		:param included:           Optional, the top-level keys of the included files read. Default: ``None``.
		:param incomplete:         Optional, ``True``, if the file includes files that weren't read. Default: ``None``,
		                           for ``True`` if the file includes files.
		:returns:                  Every job's merged mapping, and what it refers to but the file doesn't have, by name, in
		                           file order.
		:raises PipelineFileError: If a job is not a mapping.
		:raises PipelineFileError: If a job extends a job, or a ``!reference`` tag refers to a key, the file doesn't have,
		                           though it includes no files.
		:raises PipelineFileError: If jobs extend each other in a cycle, or ``extends`` or ``!reference`` tags nest too
		                           deep.
		"""
		included = {} if included is None else dict(included)
		hasIncludes = "include" in document if incomplete is None else incomplete
		scope = included | dict(document)
		foreign = {name for name in included if name not in document}
		unresolved: dict[str, list[str]] = {}

		def relocate(value: Any, line: int) -> Any:
			"""
			Nested function for recursion, copying a value of an included file with every line set to one of this file.

			:param value: The value.
			:param line:  The line, starting at 0.
			:returns:     The copy.
			"""
			if isinstance(value, CommentedMap):
				result = CommentedMap((key, relocate(item, line)) for key, item in value.items())
				for key in result:
					result.lc.add_kv_line_col(key, [line, 0, line, 0])
			elif isinstance(value, CommentedSeq):
				result = CommentedSeq(relocate(item, line) for item in value)
				for index in range(len(result)):
					result.lc.add_kv_line_col(index, [line, 0, line, 0])
			else:
				return value

			result.lc.line = line
			result.lc.col = 0
			return result

		def resolve(value: Any, owner: Nullable[str], depth: int) -> Any:
			"""
			Nested function for recursion, resolving the ``!reference`` tags in a value.

			:param value:              The value.
			:param owner:              Name of the job the value belongs to, or ``None`` for ``default``.
			:param depth:              How many references were followed to reach the value.
			:returns:                  The resolved value, or ``None`` for a reference of a job the file can't resolve.
			:raises PipelineFileError: If a reference can't be resolved, though the file includes no files, or it is in
			                           ``default``.
			:raises PipelineFileError: If references nest deeper than :data:`MAX_REFERENCE_DEPTH` levels.
			"""
			if isinstance(value, CommentedSeq) and value.tag.value == "!reference":
				segments = ", ".join(str(segment) for segment in value)
				where = "the default" if owner is None else f"job '{owner}'"
				if depth >= MAX_REFERENCE_DEPTH:
					raise PipelineFileError(
						f"Reference [{segments}] of {where} nests more than {MAX_REFERENCE_DEPTH} levels.", path, value.lc.line + 1
					)

				segmentList = [str(segment) for segment in value]
				target: Any = scope
				for segment in segmentList:
					if not isinstance(target, Mapping) or segment not in target:
						if not hasIncludes or owner is None:
							raise PipelineFileError(
								f"Reference [{segments}] of {where} refers to a key the file doesn't have.", path, value.lc.line + 1
							)

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

					target = target[segment]

				if segmentList[0] in foreign:
					target = relocate(target, value.lc.line)

				return resolve(target, owner, depth + 1)
			elif isinstance(value, CommentedSeq):
				items = CommentedSeq()
				items.lc.line = value.lc.line
				for index, item in enumerate(value):
					isReference = isinstance(item, CommentedSeq) and item.tag.value == "!reference"
					resolved = resolve(item, owner, depth)
					if isReference and resolved is None:
						continue
					elif isReference and isinstance(resolved, CommentedSeq):
						for position, element in enumerate(resolved):
							items.append(element)
							items.lc.add_kv_line_col(len(items) - 1, resolved.lc.data[position])
					else:
						items.append(resolved)
						items.lc.add_kv_line_col(len(items) - 1, value.lc.data[index])

				return items
			elif isinstance(value, CommentedMap):
				for key in list(value):
					isReference = isinstance(value[key], CommentedSeq) and value[key].tag.value == "!reference"
					resolved = resolve(value[key], owner, depth)
					if resolved is None and isReference:
						del value[key]
					else:
						value[key] = resolved

			return value

		def merge(target: CommentedMap, source: CommentedMap) -> None:
			"""
			Nested function for recursion, merging a mapping deeply into another, keeping each key's line.

			:param target: The mapping merged into.
			:param source: The mapping merged.
			"""
			for key, value in source.items():
				if value is None:
					target.pop(key, None)
					continue
				elif isinstance(value, CommentedMap) and isinstance(target.get(key, None), CommentedMap):
					merged = copy(target[key])
					merge(merged, value)
					value = merged

				target[key] = value
				if key in (source.lc.data or {}):
					target.lc.add_kv_line_col(key, source.lc.data[key])

		def copy(mapping: CommentedMap) -> CommentedMap:
			"""
			Nested function copying a mapping with the lines of its keys.

			:param mapping: The mapping.
			:returns:       The copy.
			"""
			result = CommentedMap(mapping)
			result.lc.line = mapping.lc.line
			result.lc.col = mapping.lc.col
			for key in mapping:
				if key in (mapping.lc.data or {}):
					result.lc.add_kv_line_col(key, mapping.lc.data[key])

			return result

		mappings: dict[str, CommentedMap] = {}
		for name in foreign:
			if name not in RESERVED_KEYS and isinstance(included[name], CommentedMap):
				mappings[name] = resolve(included[name], name, 0)

		for name, job in document.items():
			name = str(name)
			if name in RESERVED_KEYS:
				continue
			elif not isinstance(job, CommentedMap):
				ex = PipelineFileError(f"Job '{name}' is not a mapping.", path, Base._KeyLine(document, name))
				ex.add_note(f"Got type '{getFullyQualifiedName(job)}'.")
				raise ex

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

		defaults = CommentedMap()
		if isinstance(document.get("default", None), CommentedMap):
			defaults = copy(resolve(document["default"], None, 0))

		for key in Default._KEYS:
			if key in document and key not in defaults:
				defaults[key] = document[key]
				defaults.lc.add_kv_line_col(key, document.lc.data[key])

		def extended(name: str, chain: tuple[str, ...]) -> CommentedMap:
			"""
			Nested function for recursion, merging the jobs a job extends and its own keys.

			:param name:               Name of the job.
			:param chain:              Names of the jobs extending this one, outermost first.
			:returns:                  The merged mapping.
			:raises PipelineFileError: If a job extends a job the file doesn't have, though it includes no files.
			:raises PipelineFileError: If jobs extend each other in a cycle, or nest deeper than
			                           :data:`MAX_EXTENDS_DEPTH` levels.
			"""
			own = mappings[name]
			names = own.get("extends", ())
			names = [names] if isinstance(names, str) else list(names)
			result = CommentedMap()
			result.lc.line = own.lc.line
			result.lc.col = own.lc.col
			for base in (str(base) for base in names):
				if base in chain or base == name:
					cycle = " -> ".join((*chain, name, base))
					raise PipelineFileError(f"Jobs extend each other in a cycle: {cycle}.", path, Base._KeyLine(document, name))
				elif len(chain) >= MAX_EXTENDS_DEPTH:
					raise PipelineFileError(
						f"Job '{name}' extends more than {MAX_EXTENDS_DEPTH} levels.", path, Base._KeyLine(document, name)
					)
				elif base not in mappings:
					if not hasIncludes:
						raise PipelineFileError(
							f"Job '{name}' extends job '{base}', which the file doesn't have.", path, Base._KeyLine(own, "extends")
						)

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

				baseMapping = extended(base, (*chain, name))
				if base in foreign and name not in foreign:
					baseMapping = relocate(baseMapping, Base._KeyLine(own, "extends") - 1)

				merge(result, baseMapping)

			merge(result, own)
			return result

		resolved = {}
		for name in (name for name in mappings if name not in foreign):
			mapping = extended(name, ())
			inherit = mapping.get("inherit", None)
			inherited = inherit.get("default", True) if isinstance(inherit, CommentedMap) else True
			if not name.startswith(".") and inherited is not False:
				for key, value in defaults.items():
					if key not in mapping and (inherited is True or key in inherited):
						mapping[key] = value
						mapping.lc.add_kv_line_col(key, defaults.lc.data[key])

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

		return resolved

	def _Validate(self) -> None:
		"""
		Validate the configuration read from a file.

		:raises PipelineFileError: If a job is in a stage the pipeline doesn't have. |br|
		                           The note lists the stages.
		:raises PipelineFileError: If a job needs a job the file doesn't have. |br|
		                           The note lists the file's jobs.
		:raises PipelineFileError: If the jobs need each other in a cycle.
		"""
		self._ValidateStages()
		self._ValidateNeeds()
		self._ValidateAcyclic()

	def _ValidateStages(self) -> None:
		"""
		Validate that every job is in a stage of the pipeline.

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

		:raises PipelineFileError: If a job is in a stage the pipeline doesn't have. |br|
		                           The note lists the stages.
		"""
		stages = self.Stages
		for job in self._jobs.values():
			if job._stage not in stages and "$[[" not in job._stage:
				ex = PipelineFileError(
					f"Job '{job._name}' is in stage '{job._stage}', which isn't declared.", self._path, job._line
				)
				ex.add_note(f"Stages: {', '.join(stages)}.")
				raise ex

	def _ValidateNeeds(self) -> None:
		"""
		Validate that every job needs only jobs of the file, unless the need is optional or refers to another pipeline.

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

		:raises PipelineFileError: If a job needs a job the file doesn't have. |br|
		                           The note lists the file's jobs.
		"""
		for job in self._jobs.values():
			if job._needs is None:
				continue

			for need in job._needs:
				if need._kind is not NeedKind.Job or need._optional or need._job in self._jobs or "$[[" in need._job:
					continue

				ex = PipelineFileError(
					f"Job '{job._name}' needs job '{need._job}', which the file doesn't have.", self._path, need._line
				)
				ex.add_note(f"Jobs: {', '.join(self._jobs)}.")
				raise ex

	def _ValidateAcyclic(self) -> None:
		"""
		Validate that the jobs don't need each other in a cycle.

		:raises PipelineFileError: If the jobs need each other in a cycle.
		"""
		finished: set[str] = set()
		stack:    list[str] = []

		def visit(job: Job) -> None:
			"""
			Nested function for recursion.

			:param job:                The job whose needs are followed.
			:raises PipelineFileError: If the job is reached again while its needs are followed.
			"""
			if job._name in finished:
				return
			elif job._name in stack:
				cycle = stack[stack.index(job._name):] + [job._name]
				raise PipelineFileError(f"Jobs need each other in a cycle: {' -> '.join(cycle)}.", self._path, job._line)

			stack.append(job._name)
			for needed in job.NeededJobs:
				visit(needed)
			stack.pop()
			finished.add(job._name)

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


@export
class Job(Base[PipelineFile]):
	"""
	A job of a configuration file, or a hidden job.

	A job runs :attr:`Script` in :attr:`Stage`, after the jobs of the earlier stages - or, with a ``needs`` key, after
	the jobs in :attr:`Needs`. A hidden job, whose name starts with a dot, isn't run; other jobs extend it.
	"""

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

	_name:             str                    #: Name of the job, the key it is declared under.
	_stage:            str                    #: Stage the job runs in.
	_needs:            Nullable[list[Need]]   #: Entries of the job's ``needs``, or ``None`` without a ``needs`` key.
	_rules:            list[Rule]             #: Rules deciding whether the job is added to a pipeline.
	_when:             Nullable[RuleOutcome]  #: When the job runs.
	_allowFailure:     Nullable[bool]         #: ``True``, if the pipeline continues when the job fails.
	_allowedExitCodes: tuple[int, ...]        #: Exit codes, with which the job may fail.
	_script:           tuple[str, ...]        #: Lines of the job's ``script``.
	_beforeScript:     tuple[str, ...]        #: Lines of the job's ``before_script``.
	_afterScript:      tuple[str, ...]        #: Lines of the job's ``after_script``.
	_image:            Nullable[str]          #: Image of the container the job runs in.
	_services:         tuple[str, ...]        #: Images of the service containers.
	_tags:             tuple[str, ...]        #: Tags selecting the runner.
	_environment:      Nullable[str]          #: Name of the environment the job deploys to.
	_variables:        dict[str, Variable]    #: Variables of the job, by name, in file order.
	_inputs:           dict[str, Input]       #: Inputs of the job, by name, in file order.
	_parallel:         Nullable[Parallel]     #: The job's ``parallel``.
	_trigger:          Nullable[Trigger]      #: The pipeline the job starts.
	_extends:          tuple[str, ...]        #: Names of the jobs this job extends.
	_unresolved:       tuple[str, ...]        #: What the job refers to, but its file doesn't have.

	def __init__(
		self,
		name:             str,
		line:             int,
		stage:            str                          = "test",
		needs:            Nullable[Iterable[Need]]     = None,
		when:             Nullable[RuleOutcome]        = None,
		allowFailure:     Nullable[bool]               = None,
		allowedExitCodes: Nullable[Iterable[int]]      = None,
		script:           Nullable[Iterable[str]]      = None,
		beforeScript:     Nullable[Iterable[str]]      = None,
		afterScript:      Nullable[Iterable[str]]      = None,
		image:            Nullable[str]                = None,
		services:         Nullable[Iterable[str]]      = None,
		tags:             Nullable[Iterable[str]]      = None,
		environment:      Nullable[str]                = None,
		variables:        Nullable[Iterable[Variable]] = None,
		rules:            Nullable[Iterable[Rule]]     = None,
		inputs:           Nullable[Iterable[Input]]    = None,
		parallel:         Nullable[Parallel]           = None,
		trigger:          Nullable[Trigger]            = None,
		extends:          Nullable[Iterable[str]]      = None,
		unresolved:       Nullable[Iterable[str]]      = None,
		*,
		parent:           Nullable[PipelineFile]       = None
	) -> None:
		"""
		Initializes a job.

		A need, a variable, a rule, an input, a parallel or a trigger is attached by passing it, or by constructing it with
		the job as parent.

		:param name:             Name of the job, the key it is declared under.
		:param line:             Line the job's name is written at, starting at 1.
		:param stage:            Optional, stage the job runs in. Default: ``test``.
		:param needs:            Optional, entries of the job's ``needs``, which are attached to the job; an empty
		                         iterable for ``needs: []``. Default: ``None``, for a job without a ``needs`` key.
		:param when:             Optional, when the job runs. Default: ``None``, for a job that doesn't say.
		:param allowFailure:     Optional, ``True``, if the pipeline continues when the job fails. Default: ``None``.
		:param allowedExitCodes: Optional, exit codes, with which the job may fail. Default: ``None``.
		:param script:           Optional, lines of the job's ``script``. Default: ``None``.
		:param beforeScript:     Optional, lines of the job's ``before_script``. Default: ``None``.
		:param afterScript:      Optional, lines of the job's ``after_script``. Default: ``None``.
		:param image:            Optional, image of the container the job runs in. Default: ``None``.
		:param services:         Optional, images of the service containers. Default: ``None``.
		:param tags:             Optional, tags selecting the runner. Default: ``None``.
		:param environment:      Optional, name of the environment the job deploys to. Default: ``None``.
		:param variables:        Optional, variables of the job, which are attached to the job. Default: ``None``.
		:param rules:            Optional, rules deciding whether the job is added to a pipeline, which are attached to
		                         the job. Default: ``None``.
		:param inputs:           Optional, inputs of the job, which are attached to the job. Default: ``None``.
		:param parallel:         Optional, the job's ``parallel``, which is attached to the job. Default: ``None``.
		:param trigger:          Optional, the pipeline the job starts, which is attached to the job. Default: ``None``.
		:param extends:          Optional, names of the jobs this job extends. Default: ``None``.
		:param unresolved:       Optional, what the job refers to with ``extends`` or a ``!reference`` tag, but its file
		                         doesn't have. Default: ``None``.
		:param parent:           Optional, reference to the configuration file containing the job. Default: ``None``.
		:raises ValueError:      If parameter 'name' or 'stage' is ``None``.
		:raises TypeError:       If parameter 'name' or 'stage' is not of type :class:`str`.
		:raises ValueError:      If parameter 'name' or 'stage' is empty.
		:raises TypeError:       If parameter 'when' is not of type :class:`~pyTooling.CI.RuleOutcome`.
		:raises TypeError:       If parameter 'allowFailure' is not of type :class:`bool`.
		:raises TypeError:       If parameter 'image' or 'environment' is not of type :class:`str`.
		:raises TypeError:       If an element of parameter 'allowedExitCodes' is not of type :class:`int`.
		:raises TypeError:       If an element of parameter 'script', 'beforeScript', 'afterScript', 'services', 'tags',
		                         'extends' or 'unresolved' is not of type :class:`str`.
		:raises TypeError:       If an element of parameter 'needs' is not of type :class:`Need`.
		:raises TypeError:       If an element of parameter 'variables' is not of type :class:`Variable`.
		:raises TypeError:       If an element of parameter 'rules' is not of type :class:`Rule`.
		:raises TypeError:       If an element of parameter 'inputs' is not of type :class:`Input`.
		:raises TypeError:       If parameter 'parallel' is not of type :class:`Parallel`.
		:raises TypeError:       If parameter 'trigger' is not of type :class:`Trigger`.
		"""
		super().__init__(line, parent=parent)

		for parameterName, text in (
			("name",  name),
			("stage", stage)
		):
			if text is None:
				raise ValueError(f"Parameter '{parameterName}' is None.")
			elif not isinstance(text, str):
				ex = TypeError(f"Parameter '{parameterName}' is not of type 'str'.")
				ex.add_note(f"Got type '{getFullyQualifiedName(text)}'.")
				raise ex
			elif text == "":
				raise ValueError(f"Parameter '{parameterName}' is empty.")

		if when is not None and not isinstance(when, RuleOutcome):
			ex = TypeError("Parameter 'when' is not of type 'RuleOutcome'.")
			ex.add_note(f"Got type '{getFullyQualifiedName(when)}'.")
			raise ex

		if allowFailure is not None and not isinstance(allowFailure, bool):
			ex = TypeError("Parameter 'allowFailure' is not of type 'bool'.")
			ex.add_note(f"Got type '{getFullyQualifiedName(allowFailure)}'.")
			raise ex

		for parameterName, text in (
			("image",       image),
			("environment", environment)
		):
			if text is not None and not isinstance(text, str):
				ex = TypeError(f"Parameter '{parameterName}' is not of type 'str'.")
				ex.add_note(f"Got type '{getFullyQualifiedName(text)}'.")
				raise ex

		self._allowedExitCodes = () if allowedExitCodes is None else tuple(allowedExitCodes)
		for code in self._allowedExitCodes:
			if not isinstance(code, int) or isinstance(code, bool):
				ex = TypeError("An element of parameter 'allowedExitCodes' is not of type 'int'.")
				ex.add_note(f"Got type '{getFullyQualifiedName(code)}'.")
				raise ex

		self._script =       () if script is None else tuple(script)
		self._beforeScript = () if beforeScript is None else tuple(beforeScript)
		self._afterScript =  () if afterScript is None else tuple(afterScript)
		self._services =     () if services is None else tuple(services)
		self._tags =         () if tags is None else tuple(tags)
		self._extends =      () if extends is None else tuple(extends)
		self._unresolved =   () if unresolved is None else tuple(unresolved)
		for parameterName, texts in (
			("script",       self._script),
			("beforeScript", self._beforeScript),
			("afterScript",  self._afterScript),
			("services",     self._services),
			("tags",         self._tags),
			("extends",      self._extends),
			("unresolved",   self._unresolved)
		):
			for text in texts:
				if not isinstance(text, str):
					ex = TypeError(f"An element of parameter '{parameterName}' is not of type 'str'.")
					ex.add_note(f"Got type '{getFullyQualifiedName(text)}'.")
					raise ex

		self._name =         name
		self._stage =        stage
		self._needs =        None
		self._rules =        []
		self._inputs =       {}
		self._parallel =     None
		self._trigger =      None
		self._when =         when
		self._allowFailure = allowFailure
		self._image =        image
		self._environment =  environment
		self._variables =    {}

		if needs is not None:
			self._needs = []
			for need in needs:
				if not isinstance(need, Need):
					ex = TypeError("An element of parameter 'needs' is not of type 'Need'.")
					ex.add_note(f"Got type '{getFullyQualifiedName(need)}'.")
					raise ex

				self._needs.append(need)
				need.Parent = self

		if variables is not None:
			for variable in variables:
				if not isinstance(variable, Variable):
					ex = TypeError("An element of parameter 'variables' is not of type 'Variable'.")
					ex.add_note(f"Got type '{getFullyQualifiedName(variable)}'.")
					raise ex

				self._variables[variable._name] = variable
				variable.Parent = self

		if rules is not None:
			for rule in rules:
				if not isinstance(rule, Rule):
					ex = TypeError("An element of parameter 'rules' is not of type 'Rule'.")
					ex.add_note(f"Got type '{getFullyQualifiedName(rule)}'.")
					raise ex

				self._rules.append(rule)
				rule.Parent = self

		if inputs is not None:
			for parameter in inputs:
				if not isinstance(parameter, Input):
					ex = TypeError("An element of parameter 'inputs' is not of type 'Input'.")
					ex.add_note(f"Got type '{getFullyQualifiedName(parameter)}'.")
					raise ex

				self._inputs[parameter._name] = parameter
				parameter.Parent = self

		for parameterName, element, elementClass in (
			("parallel", parallel, Parallel),
			("trigger",  trigger,  Trigger)
		):
			if element is not None and not isinstance(element, elementClass):
				ex = TypeError(f"Parameter '{parameterName}' is not of type '{elementClass.__name__}'.")
				ex.add_note(f"Got type '{getFullyQualifiedName(element)}'.")
				raise ex

		if parallel is not None:
			self._parallel = parallel
			parallel.Parent = self

		if trigger is not None:
			self._trigger = trigger
			trigger.Parent = self

		if parent is not None:
			(parent._hiddenJobs if self.IsHidden else parent._jobs)[name] = self

	@Base.Parent.setter
	def Parent(self, value: PipelineFile) -> None:
		Base.Parent.fset(self, value)

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

		for variable in self._variables.values():
			variable.Parent = self

		for rule in self._rules:
			rule.Parent = self

		for parameter in self._inputs.values():
			parameter.Parent = self

		for element in (self._parallel, self._trigger):
			if element is not None:
				element.Parent = self

	@readonly
	def Name(self) -> str:
		"""
		Read-only property to access the job's name, the key it is declared under (:attr:`_name`).

		:returns: Name of the job.
		"""
		return self._name

	@readonly
	def IsHidden(self) -> bool:
		"""
		Read-only property to return whether the job is a hidden job, which GitLab doesn't run.

		:returns: ``True``, if the job's name starts with a dot.
		"""
		return self._name.startswith(".")

	@readonly
	def Extends(self) -> tuple[str, ...]:
		"""
		Read-only property to access the names of the jobs this job extends (:attr:`_extends`).

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

		:returns: The names, in the order ``extends`` lists them.
		"""
		return self._extends

	@readonly
	def Unresolved(self) -> tuple[str, ...]:
		"""
		Read-only property to access what the job refers to, but its file doesn't have (:attr:`_unresolved`).

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

		:returns: The jobs it extends and the ``!reference`` tags, as ``extends .base`` and ``!reference [.setup,
		          script]``, or an empty tuple if the job is complete.
		"""
		return self._unresolved

	@readonly
	def Stage(self) -> str:
		"""
		Read-only property to access the stage the job runs in (:attr:`_stage`).

		:returns: The stage, ``test`` for a job that doesn't name one.
		"""
		return self._stage

	@readonly
	def Needs(self) -> Nullable[tuple[Need, ...]]:
		"""
		Read-only property to return the entries of the job's ``needs`` (:attr:`_needs`).

		:returns: The entries, in file order; an empty tuple for ``needs: []``; or ``None`` for a job without a ``needs``
		          key, which runs after the jobs of the earlier stages.
		"""
		return None if self._needs is None else tuple(self._needs)

	@readonly
	def NeededJobs(self) -> tuple[Job, ...]:
		"""
		Read-only property to return the jobs of the same file this job needs, as its ``needs`` names them.

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

		:returns: The jobs, in the order the ``needs`` key lists them.
		"""
		if self._needs is None or self._pipelineFile is None:
			return ()

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

	@readonly
	def Rules(self) -> list[Rule]:
		"""
		Read-only property to access the rules deciding whether the job is added to a pipeline (:attr:`_rules`).

		:returns: The rules, in the order GitLab evaluates them.
		"""
		return self._rules

	@readonly
	def Inputs(self) -> dict[str, Input]:
		"""
		Read-only property to access the inputs of the job (:attr:`_inputs`).

		:returns: The inputs, by name, in file order.
		"""
		return self._inputs

	@readonly
	def Parallel(self) -> Nullable[Parallel]:
		"""
		Read-only property to access the job's ``parallel`` (:attr:`_parallel`).

		:returns: How often the job runs, or its matrix, or ``None`` for a job running once.
		"""
		return self._parallel

	@readonly
	def Trigger(self) -> Nullable[Trigger]:
		"""
		Read-only property to access the pipeline the job starts (:attr:`_trigger`).

		:returns: The trigger, or ``None`` for a job running a script.
		"""
		return self._trigger

	@readonly
	def When(self) -> Nullable[RuleOutcome]:
		"""
		Read-only property to access when the job runs (:attr:`_when`).

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

	@readonly
	def AllowFailure(self) -> Nullable[bool]:
		"""
		Read-only property to access whether the pipeline continues when the job fails (:attr:`_allowFailure`).

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

	@readonly
	def AllowedExitCodes(self) -> tuple[int, ...]:
		"""
		Read-only property to access the exit codes, with which the job may fail (:attr:`_allowedExitCodes`).

		:returns: The exit codes of ``allow_failure.exit_codes``, in file order.
		"""
		return self._allowedExitCodes

	@readonly
	def Script(self) -> tuple[str, ...]:
		"""
		Read-only property to access the lines of the job's ``script`` (:attr:`_script`).

		:returns: The lines, nested lists flattened.
		"""
		return self._script

	@readonly
	def BeforeScript(self) -> tuple[str, ...]:
		"""
		Read-only property to access the lines of the job's ``before_script`` (:attr:`_beforeScript`).

		:returns: The lines, nested lists flattened.
		"""
		return self._beforeScript

	@readonly
	def AfterScript(self) -> tuple[str, ...]:
		"""
		Read-only property to access the lines of the job's ``after_script`` (:attr:`_afterScript`).

		:returns: The lines, nested lists flattened.
		"""
		return self._afterScript

	@readonly
	def Image(self) -> Nullable[str]:
		"""
		Read-only property to access the image of the container the job runs in (:attr:`_image`).

		:returns: The image, as ``python:3.14``, or ``None`` if the job names none.
		"""
		return self._image

	@readonly
	def Services(self) -> tuple[str, ...]:
		"""
		Read-only property to access the images of the service containers (:attr:`_services`).

		:returns: The images, in file order.
		"""
		return self._services

	@readonly
	def Tags(self) -> tuple[str, ...]:
		"""
		Read-only property to access the tags selecting the runner (:attr:`_tags`).

		:returns: The tags, in file order.
		"""
		return self._tags

	@readonly
	def Environment(self) -> Nullable[str]:
		"""
		Read-only property to access the name of the environment the job deploys to (:attr:`_environment`).

		:returns: The environment's name, or ``None`` if the job deploys to none.
		"""
		return self._environment

	@readonly
	def Variables(self) -> dict[str, Variable]:
		"""
		Read-only property to access the variables of the job (:attr:`_variables`).

		:returns: The variables, by name, in file order.
		"""
		return self._variables

	def __str__(self) -> str:
		"""
		Return the job's name.

		:returns: Name of the job.
		"""
		return self._name

	@staticmethod
	def _Lines(value: Any, key: str, owner: str, mapping: CommentedMap, path: Path) -> list[str]:
		"""
		Read a script key: a line, or a list of lines and nested lists of lines.

		:param value:              The key's value.
		:param key:                The key, for a message.
		:param owner:              The element holding the key, for a message, as ``job 'build'``.
		:param mapping:            The job's mapping, for the key's line.
		:param path:               Path to the configuration file.
		:returns:                  The lines, nested lists flattened.
		:raises PipelineFileError: If the value is a mapping, or a list holds a mapping.
		"""
		if isinstance(value, CommentedSeq):
			lines = []
			for item in value:
				lines.extend(Job._Lines(item, key, owner, mapping, path))

			return lines
		elif isinstance(value, CommentedMap):
			ex = PipelineFileError(f"Key '{key}' of {owner} is not a script.", path, Base._KeyLine(mapping, key))
			ex.add_note(f"Got type '{getFullyQualifiedName(value)}'.")
			raise ex

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

	@staticmethod
	def _Name(value: Any) -> Nullable[str]:
		"""
		Read a key naming something by a string or by the ``name`` of a mapping, as ``image`` and ``environment`` do.

		:param value: The key's value.
		:returns:     The name, or ``None``.
		"""
		if isinstance(value, CommentedMap):
			value = value.get("name", None)

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

	@classmethod
	def _FromYAML(
		cls,
		name:       str,
		mapping:    CommentedMap,
		path:       Path,
		line:       int,
		unresolved: Nullable[Iterable[str]] = None
	) -> Self:
		"""
		Build a job and the elements it contains from its mapping in the configuration file.

		:param name:               Name of the job.
		:param mapping:            The job's mapping, merged with the jobs it extends and the default.
		:param path:               Path to the configuration file.
		:param line:               Line the job's name is written at, starting at 1.
		:param unresolved:         Optional, what the job refers to, but the file doesn't have. Default: ``None``.
		:returns:                  The job.
		:raises PipelineFileError: If key ``when`` is not a value GitLab knows. |br|
		                           The note lists the allowed values.
		:raises PipelineFileError: If a key of the job holds a value of the wrong kind.
		:raises PipelineFileError: If an entry of key ``needs`` is malformed.
		"""
		needs = None
		if "needs" in mapping:
			needs = Need._FromYAMLEntries(mapping["needs"], name, path, Base._KeyLine(mapping, "needs"))

		when = None
		if (whenValue := mapping.get("when", None)) is not None:
			try:
				when = RuleOutcome.Parse(Base._ToText(whenValue))
			except ValueError as cause:
				ex = PipelineFileError(
					f"Key 'when' of job '{name}' is not a known value.", path, Base._KeyLine(mapping, "when")
				)
				ex.add_note(f"Got '{whenValue}'.")
				ex.add_note(f"Allowed values: {', '.join(member.value for member in RuleOutcome)}.")
				raise ex from cause

		allowFailure = Base._ToPython(mapping.get("allow_failure", None))
		exitCodes = None
		if isinstance(allowFailure, dict):
			exitCodes = allowFailure.get("exit_codes", ())
			exitCodes = [exitCodes] if isinstance(exitCodes, int) else exitCodes
			allowFailure = True

		if allowFailure is not None and not isinstance(allowFailure, bool):
			ex = PipelineFileError(
				f"Key 'allow_failure' of job '{name}' is not a boolean.", path, Base._KeyLine(mapping, "allow_failure")
			)
			ex.add_note(f"Got '{allowFailure}'.")
			raise ex

		services = None
		if (serviceList := mapping.get("services", None)) is not None:
			if not isinstance(serviceList, CommentedSeq):
				ex = PipelineFileError(
					f"Key 'services' of job '{name}' is not a list.", path, Base._KeyLine(mapping, "services")
				)
				ex.add_note(f"Got type '{getFullyQualifiedName(serviceList)}'.")
				raise ex

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

		tags = None
		if (tagList := mapping.get("tags", None)) is not None:
			if not isinstance(tagList, CommentedSeq):
				ex = PipelineFileError(f"Key 'tags' of job '{name}' is not a list.", path, Base._KeyLine(mapping, "tags"))
				ex.add_note(f"Got type '{getFullyQualifiedName(tagList)}'.")
				raise ex

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

		variables = None
		if "variables" in mapping:
			keyLine = Base._KeyLine(mapping, "variables")
			variables = Variable._FromYAMLMapping(mapping["variables"], f"job '{name}'", path, keyLine)

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

		inputs = None
		if "inputs" in mapping:
			inputs = Input._FromYAMLMapping(mapping["inputs"], name, path, Base._KeyLine(mapping, "inputs"))

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

		trigger = None
		if "trigger" in mapping:
			trigger = Trigger._FromYAML(mapping["trigger"], name, path, Base._KeyLine(mapping, "trigger"))

		extends = mapping.get("extends", ())
		extends = [extends] if isinstance(extends, str) else extends
		stage = mapping.get("stage", None)

		return cls(
			name, line,
			stage="test" if stage is None else Base._ToText(stage),
			needs=needs,
			when=when,
			allowFailure=allowFailure,
			allowedExitCodes=exitCodes,
			script=cls._Lines(mapping.get("script", None), "script", f"job '{name}'", mapping, path),
			beforeScript=cls._Lines(mapping.get("before_script", None), "before_script", f"job '{name}'", mapping, path),
			afterScript=cls._Lines(mapping.get("after_script", None), "after_script", f"job '{name}'", mapping, path),
			image=cls._Name(mapping.get("image", None)),
			services=services,
			tags=tags,
			environment=cls._Name(mapping.get("environment", None)),
			variables=variables,
			rules=rules,
			inputs=inputs,
			parallel=parallel,
			trigger=trigger,
			extends=[Base._ToText(base) for base in extends],
			unresolved=unresolved
		)


@export
class Variable(Base[Union[PipelineFile, Job]]):
	"""
	A CI/CD variable, declared in a ``variables`` key.

	A default variable - declared in the top-level ``variables`` - may carry a :attr:`Description`, which makes GitLab
	prefill it in the form running a pipeline by hand, and :attr:`Options` to select its value from.
	"""

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

	_name:        str               #: Name of the variable.
	_value:       Nullable[str]     #: Value of the variable.
	_description: Nullable[str]     #: Description of the variable, shown when running a pipeline by hand.
	_options:     tuple[str, ...]   #: Values to select from, when running a pipeline by hand.
	_expand:      Nullable[bool]    #: ``False``, if variables in the value are not expanded.

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

	def __init__(
		self,
		name:        str,
		line:        int,
		value:       Nullable[str]                      = None,
		description: Nullable[str]                      = None,
		options:     Nullable[Iterable[str]]            = None,
		expand:      Nullable[bool]                     = None,
		*,
		parent:      Nullable[Union[PipelineFile, Job]] = None
	) -> None:
		"""
		Initializes a variable.

		:param name:        Name of the variable.
		:param line:        Line the variable's name is written at, starting at 1.
		:param value:       Optional, value of the variable. Default: ``None``.
		:param description: Optional, description of the variable. Default: ``None``.
		:param options:     Optional, values to select from when running a pipeline by hand. Default: ``None``.
		:param expand:      Optional, ``False``, if variables in the value are not expanded. Default: ``None``, for a
		                    variable that doesn't say.
		:param parent:      Optional, reference to the configuration file or the job declaring the variable. Default:
		                    ``None``.
		:raises ValueError: If parameter 'name' is ``None``.
		:raises TypeError:  If parameter 'name' is not of type :class:`str`.
		:raises ValueError: If parameter 'name' is empty.
		:raises TypeError:  If parameter 'value' is not of type :class:`str`.
		:raises TypeError:  If parameter 'description' is not of type :class:`str`.
		:raises TypeError:  If an element of parameter 'options' is not of type :class:`str`.
		:raises TypeError:  If parameter 'expand' is not of type :class:`bool`.
		"""
		super().__init__(line, parent=parent)

		if name is None:
			raise ValueError("Parameter 'name' is None.")
		elif not isinstance(name, str):
			ex = TypeError("Parameter 'name' is not of type 'str'.")
			ex.add_note(f"Got type '{getFullyQualifiedName(name)}'.")
			raise ex
		elif name == "":
			raise ValueError("Parameter 'name' is empty.")

		for parameterName, text in (
			("value",       value),
			("description", description)
		):
			if text is not None and not isinstance(text, str):
				ex = TypeError(f"Parameter '{parameterName}' is not of type 'str'.")
				ex.add_note(f"Got type '{getFullyQualifiedName(text)}'.")
				raise ex

		self._options = () if options is None else tuple(options)
		for option in self._options:
			if not isinstance(option, str):
				ex = TypeError("An element of parameter 'options' is not of type 'str'.")
				ex.add_note(f"Got type '{getFullyQualifiedName(option)}'.")
				raise ex

		if expand is not None and not isinstance(expand, bool):
			ex = TypeError("Parameter 'expand' is not of type 'bool'.")
			ex.add_note(f"Got type '{getFullyQualifiedName(expand)}'.")
			raise ex

		self._name =        name
		self._value =       value
		self._description = description
		self._expand =      expand

		if parent is not None:
			parent._variables[name] = self

	@readonly
	def Name(self) -> str:
		"""
		Read-only property to access the variable's name (:attr:`_name`).

		:returns: Name of the variable.
		"""
		return self._name

	@readonly
	def Value(self) -> Nullable[str]:
		"""
		Read-only property to access the variable's value (:attr:`_value`).

		A value written as a number or a boolean is its text, as ``3.14`` or ``true``.

		:returns: The value, or ``None`` if the declaration gives none.
		"""
		return self._value

	@readonly
	def Description(self) -> Nullable[str]:
		"""
		Read-only property to access the variable's description (:attr:`_description`).

		:returns: The description, or ``None`` if the declaration gives none.
		"""
		return self._description

	@readonly
	def Options(self) -> tuple[str, ...]:
		"""
		Read-only property to access the values to select from, when running a pipeline by hand (:attr:`_options`).

		:returns: The values, in the order the ``options`` key lists them.
		"""
		return self._options

	@readonly
	def Expand(self) -> Nullable[bool]:
		"""
		Read-only property to access whether variables in the value are expanded (:attr:`_expand`).

		:returns: The ``expand`` key, or ``None`` if the declaration gives none - GitLab expands then.
		"""
		return self._expand

	def __str__(self) -> str:
		"""
		Return the variable's name.

		:returns: Name of the variable.
		"""
		return self._name

	@classmethod
	def _FromYAML(cls, name: str, declaration: Any, path: Path, line: int) -> Self:
		"""
		Read a variable's declaration: a value, or a mapping of the keys in :attr:`_KEYS`.

		:param name:               Name of the variable.
		:param declaration:        The declaration.
		:param path:               Path to the configuration file.
		:param line:               Line the variable's name is written at, starting at 1.
		:returns:                  The variable.
		:raises PipelineFileError: If the declaration is neither a value nor a mapping.
		:raises PipelineFileError: If the mapping has a key GitLab doesn't know for a variable. |br|
		                           The note lists the allowed keys.
		:raises PipelineFileError: If key ``options`` is not a list of values, or key ``expand`` not a boolean.
		"""
		if declaration is None:
			return cls(name, line)
		elif isinstance(declaration, CommentedSeq):
			ex = PipelineFileError(f"Variable '{name}' is neither a value nor a mapping.", path, line)
			ex.add_note(f"Got type '{getFullyQualifiedName(declaration)}'.")
			raise ex
		elif not isinstance(declaration, CommentedMap):
			return cls(name, line, Base._ToText(declaration))

		for key in declaration:
			if key not in cls._KEYS:
				ex = PipelineFileError(f"Variable '{name}' has unknown key '{key}'.", path, Base._KeyLine(declaration, key))
				ex.add_note(f"Allowed keys: {', '.join(cls._KEYS)}.")
				raise ex

		options = None
		if (optionList := declaration.get("options", None)) is not None:
			isList = isinstance(optionList, CommentedSeq)
			if not isList or any(isinstance(item, (CommentedMap, CommentedSeq)) for item in optionList):
				ex = PipelineFileError(
					f"Key 'options' of variable '{name}' is not a list of values.", path, Base._KeyLine(declaration, "options")
				)
				ex.add_note(f"Got '{Base._ToPython(optionList)}'.")
				raise ex

			options = [Base._ToText(option) for option in optionList]

		expand = Base._ToPython(declaration.get("expand", None))
		if expand is not None and not isinstance(expand, bool):
			ex = PipelineFileError(
				f"Key 'expand' of variable '{name}' is not a boolean.", path, Base._KeyLine(declaration, "expand")
			)
			ex.add_note(f"Got '{expand}'.")
			raise ex

		value =       declaration.get("value", None)
		description = declaration.get("description", None)

		return cls(
			name, line,
			value=None if value is None else Base._ToText(value),
			description=None if description is None else str(description),
			options=options,
			expand=expand
		)

	@classmethod
	def _FromYAMLMapping(cls, mapping: Any, owner: Nullable[str], path: Path, line: int) -> list[Self]:
		"""
		Read the variables of a ``variables`` key.

		:param mapping:            The key's value.
		:param owner:              The element declaring the variables, for a message, as ``job 'build'``, or ``None``
		                           for the top-level ``variables``.
		:param path:               Path to the configuration file.
		:param line:               Line the ``variables`` key is written at, starting at 1.
		:returns:                  The variables, in file order.
		:raises PipelineFileError: If the value is not a mapping.
		:raises PipelineFileError: If a variable is malformed.
		"""
		if not isinstance(mapping, CommentedMap):
			ex = PipelineFileError(
				"Key 'variables' is not a mapping." if owner is None else f"Key 'variables' of {owner} is not a mapping.",
				path, line
			)
			ex.add_note(f"Got type '{getFullyQualifiedName(mapping)}'.")
			raise ex

		return [cls._FromYAML(str(name), value, path, Base._KeyLine(mapping, name)) for name, value in mapping.items()]


@export
class Need(Base[Job]):
	"""
	An entry of a job's ``needs``.

	An entry names a job of the same pipeline, as a string or as ``job`` of a mapping; a job of another pipeline of
	the parent-child hierarchy, with ``pipeline`` and ``job``; a job of another project's pipeline, with ``project``,
	``job`` and ``ref``; or, with ``pipeline`` only, another project's pipeline, whose status the job mirrors.
	:attr:`Kind` says which.
	"""

	_PARENT_TYPE: ClassVar[ParentTypes] = Job  #: A need is an entry of a job's ``needs``.

	_kind:      NeedKind            #: What the entry refers to.
	_job:       Nullable[str]       #: Name of the needed job.
	_artifacts: bool                #: ``True``, if the needed job's artifacts are downloaded.
	_optional:  bool                #: ``True``, if the needed job may be missing in the pipeline.
	_pipeline:  Nullable[str]       #: The other pipeline: its ID, or the project whose pipeline's status is mirrored.
	_project:   Nullable[str]       #: Path of the other project.
	_ref:       Nullable[str]       #: Reference of the other project, whose latest pipeline's artifacts are downloaded.
	_parallel:  Nullable[Parallel]  #: The matrix instances of the needed job, which are needed.

	_KEYS: ClassVar[tuple[str, ...]] = (
		"job", "artifacts", "optional", "pipeline", "project", "ref", "parallel"
	)  #: Keys of an entry as mapping.

	def __init__(
		self,
		job:       Nullable[str],
		line:      int,
		kind:      NeedKind           = NeedKind.Job,
		artifacts: bool               = True,
		optional:  bool               = False,
		pipeline:  Nullable[str]      = None,
		project:   Nullable[str]      = None,
		ref:       Nullable[str]      = None,
		parallel:  Nullable[Parallel] = None,
		*,
		parent:    Nullable[Job]      = None
	) -> None:
		"""
		Initializes an entry of a job's ``needs``.

		:param job:         Name of the needed job, or ``None`` for a need of kind :attr:`NeedKind.PipelineStatus`.
		:param line:        Line the entry is written at, starting at 1.
		:param kind:        Optional, what the entry refers to. Default: a job of the same pipeline.
		:param artifacts:   Optional, ``True``, if the needed job's artifacts are downloaded. Default: ``True``.
		:param optional:    Optional, ``True``, if the needed job may be missing in the pipeline. Default: ``False``.
		:param pipeline:    Optional, the other pipeline: its ID, or the project whose pipeline's status is mirrored.
		                    Default: ``None``.
		:param project:     Optional, path of the other project. Default: ``None``.
		:param ref:         Optional, reference of the other project. Default: ``None``.
		:param parallel:    Optional, the matrix instances of the needed job, which are needed, which is attached to
		                    the need. Default: ``None``, for every instance.
		:param parent:      Optional, reference to the job whose ``needs`` holds the entry. Default: ``None``.
		:raises ValueError: If parameter 'kind' is ``None``.
		:raises TypeError:  If parameter 'kind' is not of type :class:`NeedKind`.
		:raises TypeError:  If parameter 'job', 'pipeline', 'project' or 'ref' is not of type :class:`str`.
		:raises TypeError:  If parameter 'artifacts' or 'optional' is not of type :class:`bool`.
		:raises ValueError: If parameter 'job' is ``None``, but the kind names a job.
		:raises ValueError: If parameter 'pipeline' is ``None``, but the kind refers to another pipeline.
		:raises ValueError: If parameter 'project' or 'ref' is ``None``, but the kind refers to another project's job.
		:raises TypeError:  If parameter 'parallel' is not of type :class:`Parallel`.
		"""
		super().__init__(line, parent=parent)

		if kind is None:
			raise ValueError("Parameter 'kind' is None.")
		elif not isinstance(kind, NeedKind):
			ex = TypeError("Parameter 'kind' is not of type 'NeedKind'.")
			ex.add_note(f"Got type '{getFullyQualifiedName(kind)}'.")
			raise ex

		for parameterName, text in (
			("job",      job),
			("pipeline", pipeline),
			("project",  project),
			("ref",      ref)
		):
			if text is not None and not isinstance(text, str):
				ex = TypeError(f"Parameter '{parameterName}' is not of type 'str'.")
				ex.add_note(f"Got type '{getFullyQualifiedName(text)}'.")
				raise ex

		for parameterName, flag in (
			("artifacts", artifacts),
			("optional",  optional)
		):
			if not isinstance(flag, bool):
				ex = TypeError(f"Parameter '{parameterName}' is not of type 'bool'.")
				ex.add_note(f"Got type '{getFullyQualifiedName(flag)}'.")
				raise ex

		for parameterName, text, kinds in (
			("job",      job,      (NeedKind.Job, NeedKind.PipelineJob, NeedKind.ProjectJob)),
			("pipeline", pipeline, (NeedKind.PipelineJob, NeedKind.PipelineStatus)),
			("project",  project,  (NeedKind.ProjectJob, )),
			("ref",      ref,      (NeedKind.ProjectJob, ))
		):
			if text is None and kind in kinds:
				ex = ValueError(f"Parameter '{parameterName}' is None.")
				ex.add_note(f"A need of kind '{kind.value}' needs it.")
				raise ex

		self._kind =      kind
		self._job =       job
		self._artifacts = artifacts
		self._optional =  optional
		self._pipeline =  pipeline
		self._project =   project
		self._ref =       ref
		self._parallel =  None

		if parallel is not None:
			if not isinstance(parallel, Parallel):
				ex = TypeError("Parameter 'parallel' is not of type 'Parallel'.")
				ex.add_note(f"Got type '{getFullyQualifiedName(parallel)}'.")
				raise ex

			self._parallel = parallel
			parallel.Parent = self

		if parent is not None:
			if parent._needs is None:
				parent._needs = []

			parent._needs.append(self)

	@Base.Parent.setter
	def Parent(self, value: Job) -> None:
		Base.Parent.fset(self, value)

		if self._parallel is not None:
			self._parallel.Parent = self

	@readonly
	def Parallel(self) -> Nullable[Parallel]:
		"""
		Read-only property to access the matrix instances of the needed job, which are needed (:attr:`_parallel`).

		:returns: The instances' matrix, or ``None`` if every instance is needed.
		"""
		return self._parallel

	@readonly
	def Kind(self) -> NeedKind:
		"""
		Read-only property to access what the entry refers to (:attr:`_kind`).

		:returns: The kind of the need.
		"""
		return self._kind

	@readonly
	def JobName(self) -> Nullable[str]:
		"""
		Read-only property to access the name of the needed job (:attr:`_job`).

		:returns: Name of the job, or ``None`` for a need mirroring another pipeline's status.
		"""
		return self._job

	@readonly
	def NeededJob(self) -> Nullable[Job]:
		"""
		Read-only property to return the needed job of the same file.

		:returns: The job, or ``None`` for a need of another pipeline, or of a job the file doesn't have.
		"""
		if self._kind is not NeedKind.Job or self._pipelineFile is None:
			return None

		return self._pipelineFile._jobs.get(self._job, None)

	@readonly
	def Artifacts(self) -> bool:
		"""
		Read-only property to access whether the needed job's artifacts are downloaded (:attr:`_artifacts`).

		:returns: ``True``, if the artifacts are downloaded.
		"""
		return self._artifacts

	@readonly
	def IsOptional(self) -> bool:
		"""
		Read-only property to access whether the needed job may be missing in the pipeline (:attr:`_optional`).

		:returns: ``True``, if the need is optional.
		"""
		return self._optional

	@readonly
	def Pipeline(self) -> Nullable[str]:
		"""
		Read-only property to access the other pipeline (:attr:`_pipeline`).

		:returns: The pipeline's ID, as ``$PARENT_PIPELINE_ID``, or the project whose pipeline's status is mirrored, or
		          ``None`` for a need of the same pipeline or of another project's job.
		"""
		return self._pipeline

	@readonly
	def Project(self) -> Nullable[str]:
		"""
		Read-only property to access the path of the other project (:attr:`_project`).

		:returns: The project's path, or ``None`` for a need of a job of the same project.
		"""
		return self._project

	@readonly
	def Ref(self) -> Nullable[str]:
		"""
		Read-only property to access the reference of the other project (:attr:`_ref`).

		:returns: The reference, or ``None`` for a need of a job of the same project.
		"""
		return self._ref

	def __str__(self) -> str:
		"""
		Return the needed job's name, or the pipeline whose status is mirrored.

		:returns: The job's name, prefixed by the project for another project's job.
		"""
		if self._kind is NeedKind.PipelineStatus:
			return f"pipeline {self._pipeline}"
		elif self._kind is NeedKind.ProjectJob:
			return f"{self._project}: {self._job}"

		return self._job

	@classmethod
	def _FromYAML(cls, entry: Any, jobName: str, path: Path, line: int) -> Self:
		"""
		Read an entry of a job's ``needs``: a job's name, or a mapping of the keys in :attr:`_KEYS`.

		:param entry:              The entry.
		:param jobName:            Name of the job, whose ``needs`` holds the entry, for a message.
		:param path:               Path to the configuration file.
		:param line:               Line the entry is written at, starting at 1.
		:returns:                  The need.
		:raises PipelineFileError: If the entry is neither a job's name nor a mapping.
		:raises PipelineFileError: If the mapping has a key GitLab doesn't know for a need. |br|
		                           The note lists the allowed keys.
		:raises PipelineFileError: If key ``artifacts`` or ``optional`` is not a boolean.
		:raises PipelineFileError: If the mapping lacks a key its kind needs: ``job``, or ``ref`` with ``project``.
		"""
		if isinstance(entry, CommentedSeq) or entry is None:
			ex = PipelineFileError(f"Need of job '{jobName}' is neither a job's name nor a mapping.", path, line)
			ex.add_note(f"Got type '{getFullyQualifiedName(entry)}'.")
			raise ex
		elif not isinstance(entry, CommentedMap):
			return cls(Base._ToText(entry), line)

		for key in entry:
			if key not in cls._KEYS:
				ex = PipelineFileError(f"Need of job '{jobName}' has unknown key '{key}'.", path, Base._KeyLine(entry, key))
				ex.add_note(f"Allowed keys: {', '.join(cls._KEYS)}.")
				raise ex

		flags = {}
		for key, default in (
			("artifacts", True),
			("optional",  False)
		):
			flags[key] = Base._ToPython(entry.get(key, default))
			if not isinstance(flags[key], bool):
				ex = PipelineFileError(
					f"Key '{key}' of a need of job '{jobName}' is not a boolean.", path, Base._KeyLine(entry, key)
				)
				ex.add_note(f"Got '{flags[key]}'.")
				raise ex

		texts = {}
		for key in ("job", "pipeline", "project", "ref"):
			texts[key] = None if entry.get(key, None) is None else Base._ToText(entry[key])

		if texts["project"] is not None:
			kind = NeedKind.ProjectJob
		elif texts["pipeline"] is not None:
			kind = NeedKind.PipelineStatus if texts["job"] is None else NeedKind.PipelineJob
		else:
			kind = NeedKind.Job

		if texts["job"] is None and kind is not NeedKind.PipelineStatus:
			raise PipelineFileError(f"Need of job '{jobName}' has no 'job' key.", path, line)
		elif texts["ref"] is None and kind is NeedKind.ProjectJob:
			raise PipelineFileError(f"Need of job '{jobName}' with key 'project' has no 'ref' key.", path, line)

		parallel = None
		if "parallel" in entry:
			keyLine = Base._KeyLine(entry, "parallel")
			parallel = Parallel._FromYAML(entry["parallel"], f"a need of job '{jobName}'", path, keyLine)
			if parallel._count is not None:
				raise PipelineFileError(f"Key 'parallel' of a need of job '{jobName}' has no 'matrix' key.", path, line)

		return cls(
			texts["job"], line, kind, flags["artifacts"], flags["optional"],
			texts["pipeline"], texts["project"], texts["ref"], parallel
		)

	@classmethod
	def _FromYAMLEntries(cls, value: Any, jobName: str, path: Path, line: int) -> list[Self]:
		"""
		Read a job's ``needs``: a list of entries, or a single mapping, as ``pipeline: other/project``.

		:param value:              The key's value.
		:param jobName:            Name of the job, for a message.
		:param path:               Path to the configuration file.
		:param line:               Line the ``needs`` key is written at, starting at 1.
		:returns:                  The needs, in file order.
		:raises PipelineFileError: If the value is neither a list nor a mapping.
		:raises PipelineFileError: If an entry is malformed.
		"""
		if isinstance(value, CommentedMap):
			return [cls._FromYAML(value, jobName, path, line)]
		elif not isinstance(value, CommentedSeq):
			ex = PipelineFileError(f"Key 'needs' of job '{jobName}' is neither a list nor a mapping.", path, line)
			ex.add_note(f"Got type '{getFullyQualifiedName(value)}'.")
			raise ex

		return [cls._FromYAML(entry, jobName, path, Base._ItemLine(value, index)) for index, entry in enumerate(value)]


@export
class Workflow(Base[PipelineFile]):
	"""The ``workflow`` key of a configuration file: the pipeline's name and the rules deciding whether it is created."""

	_PARENT_TYPE: ClassVar[ParentTypes] = PipelineFile  #: A workflow belongs to a configuration file.

	_name:  Nullable[str]  #: Name of the pipeline.
	_rules: list[Rule]     #: Rules deciding whether a pipeline is created.

	def __init__(
		self,
		line:   int,
		name:   Nullable[str]            = None,
		rules:  Nullable[Iterable[Rule]] = None,
		*,
		parent: Nullable[PipelineFile]   = None
	) -> None:
		"""
		Initializes the ``workflow`` key.

		:param line:       Line the ``workflow`` key is written at, starting at 1.
		:param name:       Optional, name of the pipeline. Default: ``None``.
		:param rules:      Optional, rules deciding whether a pipeline is created, which are attached to the workflow.
		                   Default: ``None``.
		:param parent:     Optional, reference to the configuration file. Default: ``None``.
		:raises TypeError: If parameter 'name' is not of type :class:`str`.
		:raises TypeError: If an element of parameter 'rules' is not of type :class:`Rule`.
		"""
		super().__init__(line, parent=parent)

		if name is not None and not isinstance(name, str):
			ex = TypeError("Parameter 'name' is not of type 'str'.")
			ex.add_note(f"Got type '{getFullyQualifiedName(name)}'.")
			raise ex

		self._name =  name
		self._rules = []

		if rules is not None:
			for rule in rules:
				if not isinstance(rule, Rule):
					ex = TypeError("An element of parameter 'rules' is not of type 'Rule'.")
					ex.add_note(f"Got type '{getFullyQualifiedName(rule)}'.")
					raise ex

				self._rules.append(rule)
				rule.Parent = self

		if parent is not None:
			parent._workflow = self

	@Base.Parent.setter
	def Parent(self, value: PipelineFile) -> None:
		Base.Parent.fset(self, value)

		for rule in self._rules:
			rule.Parent = self

	@readonly
	def Name(self) -> Nullable[str]:
		"""
		Read-only property to access the pipeline's name (:attr:`_name`).

		:returns: The ``name`` key, as written, or ``None`` if the workflow gives none.
		"""
		return self._name

	@readonly
	def Rules(self) -> list[Rule]:
		"""
		Read-only property to access the rules deciding whether a pipeline is created (:attr:`_rules`).

		:returns: The rules, in the order GitLab evaluates them.
		"""
		return self._rules

	@classmethod
	def _FromYAML(cls, mapping: Any, path: Path, line: int) -> Self:
		"""
		Read the ``workflow`` key.

		:param mapping:            The key's value.
		:param path:               Path to the configuration file.
		:param line:               Line the ``workflow`` key is written at, starting at 1.
		:returns:                  The workflow.
		:raises PipelineFileError: If the value is not a mapping.
		:raises PipelineFileError: If a rule is malformed.
		"""
		if not isinstance(mapping, CommentedMap):
			ex = PipelineFileError("Key 'workflow' is not a mapping.", path, line)
			ex.add_note(f"Got type '{getFullyQualifiedName(mapping)}'.")
			raise ex

		rules = None
		if "rules" in mapping:
			rules = Rule._FromYAMLEntries(mapping["rules"], "the workflow", path, Base._KeyLine(mapping, "rules"))

		name = mapping.get("name", None)
		return cls(line, None if name is None else Base._ToText(name), rules)


@export
class Trigger(Base[Job]):
	"""
	A job's ``trigger``: the child pipeline, or the other project's pipeline, the job starts.

	A child pipeline runs the configuration of the files in :attr:`Includes`; another project's pipeline runs that
	project's configuration on :attr:`Branch`.
	"""

	_PARENT_TYPE: ClassVar[ParentTypes] = Job  #: A trigger belongs to a job.

	_project:  Nullable[str]              #: Path of the other project, whose pipeline is started.
	_branch:   Nullable[str]              #: Branch of the other project.
	_strategy: Nullable[TriggerStrategy]  #: How the job's status follows the started pipeline.
	_includes: list[Include]              #: Files of the child pipeline's configuration.

	def __init__(
		self,
		line:     int,
		project:  Nullable[str]               = None,
		branch:   Nullable[str]               = None,
		strategy: Nullable[TriggerStrategy]   = None,
		includes: Nullable[Iterable[Include]] = None,
		*,
		parent:   Nullable[Job]               = None
	) -> None:
		"""
		Initializes a job's ``trigger``.

		:param line:       Line the ``trigger`` key is written at, starting at 1.
		:param project:    Optional, path of the other project, whose pipeline is started. Default: ``None``.
		:param branch:     Optional, branch of the other project. Default: ``None``, for its default branch.
		:param strategy:   Optional, how the job's status follows the started pipeline. Default: ``None``, for a job
		                   succeeding as soon as the pipeline is created.
		:param includes:   Optional, files of the child pipeline's configuration, which are attached to the trigger.
		                   Default: ``None``.
		:param parent:     Optional, reference to the job. Default: ``None``.
		:raises TypeError: If parameter 'project' or 'branch' is not of type :class:`str`.
		:raises TypeError: If parameter 'strategy' is not of type :class:`TriggerStrategy`.
		:raises TypeError: If an element of parameter 'includes' is not of type :class:`Include`.
		"""
		super().__init__(line, parent=parent)

		for parameterName, text in (
			("project", project),
			("branch",  branch)
		):
			if text is not None and not isinstance(text, str):
				ex = TypeError(f"Parameter '{parameterName}' is not of type 'str'.")
				ex.add_note(f"Got type '{getFullyQualifiedName(text)}'.")
				raise ex

		if strategy is not None and not isinstance(strategy, TriggerStrategy):
			ex = TypeError("Parameter 'strategy' is not of type 'TriggerStrategy'.")
			ex.add_note(f"Got type '{getFullyQualifiedName(strategy)}'.")
			raise ex

		self._project =  project
		self._branch =   branch
		self._strategy = strategy
		self._includes = []

		if includes is not None:
			for include in includes:
				if not isinstance(include, Include):
					ex = TypeError("An element of parameter 'includes' is not of type 'Include'.")
					ex.add_note(f"Got type '{getFullyQualifiedName(include)}'.")
					raise ex

				self._includes.append(include)
				include.Parent = self

		if parent is not None:
			parent._trigger = self

	@Base.Parent.setter
	def Parent(self, value: Job) -> None:
		Base.Parent.fset(self, value)

		for include in self._includes:
			include.Parent = self

	@readonly
	def Project(self) -> Nullable[str]:
		"""
		Read-only property to access the path of the other project, whose pipeline is started (:attr:`_project`).

		:returns: The project's path, or ``None`` for a child pipeline.
		"""
		return self._project

	@readonly
	def Branch(self) -> Nullable[str]:
		"""
		Read-only property to access the branch of the other project (:attr:`_branch`).

		:returns: The branch, or ``None`` for the project's default branch.
		"""
		return self._branch

	@readonly
	def Strategy(self) -> Nullable[TriggerStrategy]:
		"""
		Read-only property to access how the job's status follows the started pipeline (:attr:`_strategy`).

		:returns: The strategy, or ``None`` if the trigger doesn't say.
		"""
		return self._strategy

	@readonly
	def Includes(self) -> list[Include]:
		"""
		Read-only property to access the files of the child pipeline's configuration (:attr:`_includes`).

		:returns: The files, in file order; empty for another project's pipeline.
		"""
		return self._includes

	@readonly
	def IsChildPipeline(self) -> bool:
		"""
		Read-only property to return whether the job starts a child pipeline.

		:returns: ``True``, if the trigger includes files; ``False`` for another project's pipeline.
		"""
		return len(self._includes) > 0

	@classmethod
	def _FromYAML(cls, value: Any, jobName: str, path: Path, line: int) -> Self:
		"""
		Read a job's ``trigger``: another project's path, or a mapping with ``include`` or ``project``.

		:param value:              The key's value.
		:param jobName:            Name of the job, for a message.
		:param path:               Path to the configuration file.
		:param line:               Line the ``trigger`` key is written at, starting at 1.
		:returns:                  The trigger.
		:raises PipelineFileError: If the value is neither a project's path nor a mapping with ``include`` or
		                           ``project``.
		:raises PipelineFileError: If key ``strategy`` is not a value GitLab knows. |br|
		                           The note lists the allowed values.
		:raises PipelineFileError: If an include is malformed.
		"""
		if isinstance(value, (str, ScalarString)):
			return cls(line, project=Base._ToText(value))
		elif not isinstance(value, CommentedMap) or ("include" not in value and "project" not in value):
			ex = PipelineFileError(
				f"Key 'trigger' of job '{jobName}' is neither a project nor a mapping with 'include' or 'project'.", path, line
			)
			ex.add_note(f"Got '{Base._ToPython(value)}'.")
			raise ex

		strategy = None
		if (strategyValue := value.get("strategy", None)) is not None:
			try:
				strategy = TriggerStrategy.Parse(Base._ToText(strategyValue))
			except ValueError as cause:
				ex = PipelineFileError(
					f"Key 'strategy' of the trigger of job '{jobName}' is not a known value.",
					path, Base._KeyLine(value, "strategy")
				)
				ex.add_note(f"Got '{strategyValue}'.")
				ex.add_note(f"Allowed values: {', '.join(member.value for member in TriggerStrategy)}.")
				raise ex from cause

		includes = None
		if "include" in value:
			includes = Include._FromYAMLEntries(value["include"], path, Base._KeyLine(value, "include"))

		project = value.get("project", None)
		branch =  value.get("branch", None)
		return cls(
			line,
			project=None if project is None else Base._ToText(project),
			branch=None if branch is None else Base._ToText(branch),
			strategy=strategy,
			includes=includes
		)


@export
class Include(Base[Union[PipelineFile, Trigger]]):
	"""
	An entry of ``include``, which adds the configuration of other files.

	:attr:`Kind` says where the files come from, :attr:`Location` names them: a path of the same repository, a URL, a
	template's name, a component's reference, the path of another project, whose files are in :attr:`Files`, or the
	artifact of the job :attr:`ArtifactJob`.
	"""

	_PARENT_TYPE: ClassVar[ParentTypes] = (PipelineFile, Trigger)  #: Included by a configuration file or a trigger.

	_kind:     IncludeKind        #: Where the included files come from.
	_location: str                #: Path, URL, template's name, component's reference, or project's path.
	_ref:      Nullable[str]      #: Reference of the project the files are read from.
	_files:    tuple[str, ...]    #: Paths of the files of another project.
	_job:      Nullable[str]      #: Name of the job, whose artifact is included.
	_inputs:   dict[str, ValueT]  #: Inputs passed to the included files, by name.
	_rules:    list[Rule]         #: Rules deciding whether the files are included.

	_KINDS: ClassVar[tuple[str, ...]] = tuple(member.value for member in IncludeKind)  #: Keys naming an include's kind.

	def __init__(
		self,
		kind:     IncludeKind,
		location: str,
		line:     int,
		files:    Nullable[Iterable[str]]                = None,
		ref:      Nullable[str]                          = None,
		inputs:   Nullable[Mapping[str, ValueT]]         = None,
		rules:    Nullable[Iterable[Rule]]               = None,
		job:      Nullable[str]                          = None,
		*,
		parent:   Nullable[Union[PipelineFile, Trigger]] = None
	) -> None:
		"""
		Initializes an entry of ``include``.

		:param kind:        Where the included files come from.
		:param location:    Path, URL, template's name, component's reference, or - for another project - its path.
		:param line:        Line the entry is written at, starting at 1.
		:param files:       Optional, paths of the files of another project. Default: ``None``.
		:param ref:         Optional, reference of the project the files are read from. Default: ``None``.
		:param inputs:      Optional, inputs passed to the included files, by name. Default: ``None``.
		:param rules:       Optional, rules deciding whether the files are included, which are attached to the entry.
		                    Default: ``None``.
		:param job:         Optional, name of the job, whose artifact is included. Default: ``None``.
		:param parent:      Optional, reference to the configuration file or the trigger. Default: ``None``.
		:raises ValueError: If parameter 'kind' or 'location' is ``None``.
		:raises TypeError:  If parameter 'kind' is not of type :class:`IncludeKind`.
		:raises TypeError:  If parameter 'location', 'ref' or 'job' is not of type :class:`str`.
		:raises ValueError: If parameter 'location' is empty.
		:raises TypeError:  If an element of parameter 'files' is not of type :class:`str`.
		:raises TypeError:  If an element of parameter 'rules' is not of type :class:`Rule`.
		"""
		super().__init__(line, parent=parent)

		if kind is None:
			raise ValueError("Parameter 'kind' is None.")
		elif not isinstance(kind, IncludeKind):
			ex = TypeError("Parameter 'kind' is not of type 'IncludeKind'.")
			ex.add_note(f"Got type '{getFullyQualifiedName(kind)}'.")
			raise ex

		if location is None:
			raise ValueError("Parameter 'location' is None.")
		elif not isinstance(location, str):
			ex = TypeError("Parameter 'location' is not of type 'str'.")
			ex.add_note(f"Got type '{getFullyQualifiedName(location)}'.")
			raise ex
		elif location == "":
			raise ValueError("Parameter 'location' is empty.")

		for parameterName, text in (
			("ref", ref),
			("job", job)
		):
			if text is not None and not isinstance(text, str):
				ex = TypeError(f"Parameter '{parameterName}' is not of type 'str'.")
				ex.add_note(f"Got type '{getFullyQualifiedName(text)}'.")
				raise ex

		self._files = () if files is None else tuple(files)
		for file in self._files:
			if not isinstance(file, str):
				ex = TypeError("An element of parameter 'files' is not of type 'str'.")
				ex.add_note(f"Got type '{getFullyQualifiedName(file)}'.")
				raise ex

		self._kind =     kind
		self._location = location
		self._ref =      ref
		self._job =      job
		self._inputs =   {} if inputs is None else dict(inputs)
		self._rules =    []

		if rules is not None:
			for rule in rules:
				if not isinstance(rule, Rule):
					ex = TypeError("An element of parameter 'rules' is not of type 'Rule'.")
					ex.add_note(f"Got type '{getFullyQualifiedName(rule)}'.")
					raise ex

				self._rules.append(rule)
				rule.Parent = self

		if parent is not None:
			parent._includes.append(self)

	@Base.Parent.setter
	def Parent(self, value: PipelineFile) -> None:
		Base.Parent.fset(self, value)

		for rule in self._rules:
			rule.Parent = self

	@readonly
	def Kind(self) -> IncludeKind:
		"""
		Read-only property to access where the included files come from (:attr:`_kind`).

		:returns: The kind of the include.
		"""
		return self._kind

	@readonly
	def Location(self) -> str:
		"""
		Read-only property to access what the entry includes (:attr:`_location`).

		:returns: A path, a URL, a template's name, a component's reference, or another project's path, as written.
		"""
		return self._location

	@readonly
	def Ref(self) -> Nullable[str]:
		"""
		Read-only property to access the reference of the project the files are read from (:attr:`_ref`).

		:returns: The ``ref`` key, or ``None`` - the project's default branch then.
		"""
		return self._ref

	@readonly
	def Files(self) -> tuple[str, ...]:
		"""
		Read-only property to access the paths of the files of another project (:attr:`_files`).

		:returns: The paths of ``file``, in file order.
		"""
		return self._files

	@readonly
	def ArtifactJob(self) -> Nullable[str]:
		"""
		Read-only property to access the name of the job, whose artifact is included (:attr:`_job`).

		:returns: The ``job`` key of an artifact's include, or ``None``.
		"""
		return self._job

	@readonly
	def Inputs(self) -> dict[str, ValueT]:
		"""
		Read-only property to access the inputs passed to the included files (:attr:`_inputs`).

		:returns: The inputs' values, by name, with the types they are written with.
		"""
		return self._inputs

	@readonly
	def Rules(self) -> list[Rule]:
		"""
		Read-only property to access the rules deciding whether the files are included (:attr:`_rules`).

		:returns: The rules, in the order GitLab evaluates them.
		"""
		return self._rules

	def __str__(self) -> str:
		"""
		Return the include's kind and location.

		:returns: The kind and the location, as ``local: /ci/build.yml``.
		"""
		return f"{self._kind.value}: {self._location}"

	@classmethod
	def _FromYAML(cls, entry: Any, path: Path, line: int) -> Self:
		"""
		Read an entry of ``include``: a path or a URL, or a mapping with one key of :attr:`_KINDS`.

		:param entry:              The entry.
		:param path:               Path to the configuration file.
		:param line:               Line the entry is written at, starting at 1.
		:returns:                  The include.
		:raises PipelineFileError: If the entry is neither a string nor a mapping.
		:raises PipelineFileError: If the mapping has none, or more than one, of the keys of :attr:`_KINDS`.
		:raises PipelineFileError: If key ``file`` of another project's include is missing, or not a path or a list.
		:raises PipelineFileError: If key ``inputs`` is not a mapping.
		:raises PipelineFileError: If a rule is malformed.
		"""
		if isinstance(entry, CommentedSeq) or entry is None:
			ex = PipelineFileError("Include is neither a path nor a mapping.", path, line)
			ex.add_note(f"Got type '{getFullyQualifiedName(entry)}'.")
			raise ex
		elif not isinstance(entry, CommentedMap):
			location = Base._ToText(entry)
			kind = IncludeKind.Remote if location.startswith(("https://", "http://")) else IncludeKind.Local
			return cls(kind, location, line)

		kinds = [key for key in cls._KINDS if key in entry]
		if len(kinds) != 1:
			count = "none" if len(kinds) == 0 else "more than one"
			ex = PipelineFileError(f"Include has {count} of its kinds' keys.", path, line)
			ex.add_note(f"Kinds: {', '.join(cls._KINDS)}.")
			raise ex

		kind = IncludeKind(kinds[0])
		files = None
		if kind is IncludeKind.Project:
			if (fileValue := entry.get("file", None)) is None:
				raise PipelineFileError("Include of another project has no 'file' key.", path, line)
			elif isinstance(fileValue, CommentedMap):
				ex = PipelineFileError("Key 'file' of an include is neither a path nor a list.", path, line)
				ex.add_note(f"Got type '{getFullyQualifiedName(fileValue)}'.")
				raise ex

			fileList = fileValue if isinstance(fileValue, CommentedSeq) else [fileValue]
			files = [Base._ToText(file) for file in fileList]

		inputs = entry.get("inputs", None)
		if inputs is not None and not isinstance(inputs, CommentedMap):
			ex = PipelineFileError("Key 'inputs' of an include is not a mapping.", path, Base._KeyLine(entry, "inputs"))
			ex.add_note(f"Got type '{getFullyQualifiedName(inputs)}'.")
			raise ex

		rules = None
		if "rules" in entry:
			rules = Rule._FromYAMLEntries(entry["rules"], "an include", path, Base._KeyLine(entry, "rules"))

		ref = entry.get("ref", None)
		job = entry.get("job", None)
		return cls(
			kind, Base._ToText(entry[kinds[0]]), line,
			files=files,
			ref=None if ref is None else Base._ToText(ref),
			inputs=None if inputs is None else Base._ToPython(inputs),
			rules=rules,
			job=None if job is None else Base._ToText(job)
		)

	@classmethod
	def _FromYAMLEntries(cls, value: Any, path: Path, line: int) -> list[Self]:
		"""
		Read the ``include`` key: an entry, or a list of entries.

		:param value:              The key's value.
		:param path:               Path to the configuration file.
		:param line:               Line the ``include`` key is written at, starting at 1.
		:returns:                  The includes, in file order.
		:raises PipelineFileError: If an entry is malformed.
		"""
		if not isinstance(value, CommentedSeq):
			return [cls._FromYAML(value, path, line)]

		return [cls._FromYAML(entry, path, Base._ItemLine(value, index)) for index, entry in enumerate(value)]


@export
class Rule(Base[Union[Job, Workflow, Include]]):
	"""
	A rule of ``rules``, deciding whether a job is added to a pipeline, a pipeline is created, or a file is included.

	GitLab evaluates the rules in order; the first one matching decides. A rule matches if its :attr:`Condition`, its
	:attr:`Changes` and its :attr:`Exists` match, as far as it has them.
	"""

	_PARENT_TYPE: ClassVar[ParentTypes] = (Job, Workflow, Include)  #: A rule belongs to a job, a workflow or an include.

	_condition:    Nullable[str]          #: Expression of the rule's ``if``.
	_changes:      tuple[str, ...]        #: Paths of the rule's ``changes``.
	_compareTo:    Nullable[str]          #: Reference ``changes`` is compared to.
	_exists:       tuple[str, ...]        #: Paths of the rule's ``exists``.
	_when:         Nullable[RuleOutcome]  #: When the job runs, if the rule matches.
	_allowFailure: Nullable[bool]         #: ``True``, if the pipeline continues when the job fails, if the rule matches.
	_variables:    dict[str, str]         #: Variables set, if the rule matches, by name.

	def __init__(
		self,
		line:         int,
		condition:    Nullable[str]               = None,
		changes:      Nullable[Iterable[str]]     = None,
		compareTo:    Nullable[str]               = None,
		exists:       Nullable[Iterable[str]]     = None,
		when:         Nullable[RuleOutcome]       = None,
		allowFailure: Nullable[bool]              = None,
		variables:    Nullable[Mapping[str, str]] = None,
		*,
		parent:       Nullable[Union[Job, Workflow, Include]] = None
	) -> None:
		"""
		Initializes a rule.

		:param line:         Line the rule is written at, starting at 1.
		:param condition:    Optional, expression of the rule's ``if``. Default: ``None``.
		:param changes:      Optional, paths of the rule's ``changes``. Default: ``None``.
		:param compareTo:    Optional, reference ``changes`` is compared to. Default: ``None``.
		:param exists:       Optional, paths of the rule's ``exists``. Default: ``None``.
		:param when:         Optional, when the job runs, if the rule matches. Default: ``None``.
		:param allowFailure: Optional, ``True``, if the pipeline continues when the job fails. Default: ``None``.
		:param variables:    Optional, variables set, if the rule matches, by name. Default: ``None``.
		:param parent:       Optional, reference to the job, workflow or include the rule belongs to. Default: ``None``.
		:raises TypeError:   If parameter 'condition' or 'compareTo' is not of type :class:`str`.
		:raises TypeError:   If an element of parameter 'changes' or 'exists' is not of type :class:`str`.
		:raises TypeError:   If parameter 'when' is not of type :class:`~pyTooling.CI.RuleOutcome`.
		:raises TypeError:   If parameter 'allowFailure' is not of type :class:`bool`.
		"""
		super().__init__(line, parent=parent)

		for parameterName, text in (
			("condition", condition),
			("compareTo", compareTo)
		):
			if text is not None and not isinstance(text, str):
				ex = TypeError(f"Parameter '{parameterName}' is not of type 'str'.")
				ex.add_note(f"Got type '{getFullyQualifiedName(text)}'.")
				raise ex

		self._changes = () if changes is None else tuple(changes)
		self._exists =  () if exists is None else tuple(exists)
		for parameterName, paths in (
			("changes", self._changes),
			("exists",  self._exists)
		):
			for path in paths:
				if not isinstance(path, str):
					ex = TypeError(f"An element of parameter '{parameterName}' is not of type 'str'.")
					ex.add_note(f"Got type '{getFullyQualifiedName(path)}'.")
					raise ex

		if when is not None and not isinstance(when, RuleOutcome):
			ex = TypeError("Parameter 'when' is not of type 'RuleOutcome'.")
			ex.add_note(f"Got type '{getFullyQualifiedName(when)}'.")
			raise ex

		if allowFailure is not None and not isinstance(allowFailure, bool):
			ex = TypeError("Parameter 'allowFailure' is not of type 'bool'.")
			ex.add_note(f"Got type '{getFullyQualifiedName(allowFailure)}'.")
			raise ex

		self._condition =    condition
		self._compareTo =    compareTo
		self._when =         when
		self._allowFailure = allowFailure
		self._variables =    {} if variables is None else dict(variables)

		if parent is not None:
			parent._rules.append(self)

	@readonly
	def Condition(self) -> Nullable[str]:
		"""
		Read-only property to access the expression of the rule's ``if`` (:attr:`_condition`).

		:returns: The expression, as written, or ``None`` if the rule has no ``if``.
		"""
		return self._condition

	@readonly
	def Changes(self) -> tuple[str, ...]:
		"""
		Read-only property to access the paths of the rule's ``changes`` (:attr:`_changes`).

		:returns: The paths, as written in ``changes`` or ``changes.paths``.
		"""
		return self._changes

	@readonly
	def CompareTo(self) -> Nullable[str]:
		"""
		Read-only property to access the reference ``changes`` is compared to (:attr:`_compareTo`).

		:returns: The reference of ``changes.compare_to``, or ``None``.
		"""
		return self._compareTo

	@readonly
	def Exists(self) -> tuple[str, ...]:
		"""
		Read-only property to access the paths of the rule's ``exists`` (:attr:`_exists`).

		:returns: The paths, as written in ``exists`` or ``exists.paths``.
		"""
		return self._exists

	@readonly
	def When(self) -> Nullable[RuleOutcome]:
		"""
		Read-only property to access when the job runs, if the rule matches (:attr:`_when`).

		:returns: The rule's ``when``, or ``None`` if the rule doesn't say.
		"""
		return self._when

	@readonly
	def AllowFailure(self) -> Nullable[bool]:
		"""
		Read-only property to access whether the pipeline continues when the job fails (:attr:`_allowFailure`).

		:returns: The rule's ``allow_failure``, or ``None`` if the rule doesn't say.
		"""
		return self._allowFailure

	@readonly
	def Variables(self) -> dict[str, str]:
		"""
		Read-only property to access the variables set, if the rule matches (:attr:`_variables`).

		:returns: The variables' values, by name.
		"""
		return self._variables

	@staticmethod
	def _Paths(value: Any, key: str, owner: str, entry: CommentedMap, path: Path) -> tuple[list[str], Nullable[str]]:
		"""
		Read the paths of ``changes`` or ``exists``: a list, or a mapping with ``paths``.

		:param value:              The key's value.
		:param key:                The key, for a message.
		:param owner:              The element the rule belongs to, for a message.
		:param entry:              The rule's mapping, for the key's line.
		:param path:               Path to the configuration file.
		:returns:                  The paths, and the reference of ``compare_to``.
		:raises PipelineFileError: If the value is neither a list nor a mapping with a list ``paths``.
		"""
		compareTo = None
		if isinstance(value, CommentedMap):
			compareTo = value.get("compare_to", None)
			value = value.get("paths", None)

		if not isinstance(value, CommentedSeq):
			ex = PipelineFileError(
				f"Key '{key}' of a rule of {owner} is not a list of paths.", path, Base._KeyLine(entry, key)
			)
			ex.add_note(f"Got type '{getFullyQualifiedName(value)}'.")
			raise ex

		return [Base._ToText(item) for item in value], None if compareTo is None else Base._ToText(compareTo)

	@classmethod
	def _FromYAMLEntries(cls, value: Any, owner: str, path: Path, line: int) -> list[Self]:
		"""
		Read a ``rules`` key: a list of rules, each a mapping.

		:param value:              The key's value.
		:param owner:              The element the rules belong to, for a message, as ``job 'build'``.
		:param path:               Path to the configuration file.
		:param line:               Line the ``rules`` key is written at, starting at 1.
		:returns:                  The rules, in file order.
		:raises PipelineFileError: If the value is not a list, or a rule is not a mapping.
		:raises PipelineFileError: If key ``when`` of a rule is not a value GitLab knows. |br|
		                           The note lists the allowed values.
		:raises PipelineFileError: If a key of a rule holds a value of the wrong kind.
		"""
		if not isinstance(value, CommentedSeq):
			ex = PipelineFileError(f"Key 'rules' of {owner} is not a list.", path, line)
			ex.add_note(f"Got type '{getFullyQualifiedName(value)}'.")
			raise ex

		rules = []
		for index, entry in enumerate(value):
			entryLine = Base._ItemLine(value, index)
			if not isinstance(entry, CommentedMap):
				ex = PipelineFileError(f"Rule of {owner} is not a mapping.", path, entryLine)
				ex.add_note(f"Got type '{getFullyQualifiedName(entry)}'.")
				raise ex

			changes = None
			compareTo = None
			if "changes" in entry:
				changes, compareTo = cls._Paths(entry["changes"], "changes", owner, entry, path)

			exists = None
			if "exists" in entry:
				exists, _ = cls._Paths(entry["exists"], "exists", owner, entry, path)

			when = None
			if (whenValue := entry.get("when", None)) is not None:
				try:
					when = RuleOutcome.Parse(Base._ToText(whenValue))
				except ValueError as cause:
					ex = PipelineFileError(f"Key 'when' of a rule of {owner} is not a known value.", path, entryLine)
					ex.add_note(f"Got '{whenValue}'.")
					ex.add_note(f"Allowed values: {', '.join(member.value for member in RuleOutcome)}.")
					raise ex from cause

			allowFailure = Base._ToPython(entry.get("allow_failure", None))
			if allowFailure is not None and not isinstance(allowFailure, bool):
				ex = PipelineFileError(f"Key 'allow_failure' of a rule of {owner} is not a boolean.", path, entryLine)
				ex.add_note(f"Got '{allowFailure}'.")
				raise ex

			variables = entry.get("variables", None)
			if variables is not None and not isinstance(variables, CommentedMap):
				ex = PipelineFileError(f"Key 'variables' of a rule of {owner} is not a mapping.", path, entryLine)
				ex.add_note(f"Got type '{getFullyQualifiedName(variables)}'.")
				raise ex

			condition = entry.get("if", None)
			rules.append(cls(
				entryLine,
				condition=None if condition is None else Base._ToText(condition),
				changes=changes,
				compareTo=compareTo,
				exists=exists,
				when=when,
				allowFailure=allowFailure,
				variables=None if variables is None else {str(k): Base._ToText(v) for k, v in variables.items()}
			))

		return rules


@export
class Default(Base[PipelineFile]):
	"""
	The ``default`` key of a configuration file: keys every job gets, unless it sets them itself.

	The global keywords ``image``, ``services``, ``before_script`` and ``after_script`` - deprecated forms of
	``default`` - are read into it too, unless ``default`` sets them.
	"""

	_PARENT_TYPE: ClassVar[ParentTypes] = PipelineFile  #: A default belongs to a configuration file.

	_image:        Nullable[str]    #: Image of the container a job runs in.
	_services:     tuple[str, ...]  #: Images of the service containers.
	_tags:         tuple[str, ...]  #: Tags selecting the runner.
	_beforeScript: tuple[str, ...]  #: Lines of ``before_script``.
	_afterScript:  tuple[str, ...]  #: Lines of ``after_script``.

	_KEYS: ClassVar[tuple[str, ...]] = ("image", "services", "before_script", "after_script")  #: The global keywords.

	def __init__(
		self,
		line:         int,
		image:        Nullable[str]           = None,
		services:     Nullable[Iterable[str]] = None,
		tags:         Nullable[Iterable[str]] = None,
		beforeScript: Nullable[Iterable[str]] = None,
		afterScript:  Nullable[Iterable[str]] = None,
		*,
		parent:       Nullable[PipelineFile]  = None
	) -> None:
		"""
		Initializes the ``default`` key.

		:param line:         Line the ``default`` key, or the first global keyword, is written at, starting at 1.
		:param image:        Optional, image of the container a job runs in. Default: ``None``.
		:param services:     Optional, images of the service containers. Default: ``None``.
		:param tags:         Optional, tags selecting the runner. Default: ``None``.
		:param beforeScript: Optional, lines of ``before_script``. Default: ``None``.
		:param afterScript:  Optional, lines of ``after_script``. Default: ``None``.
		:param parent:       Optional, reference to the configuration file. Default: ``None``.
		:raises TypeError:   If parameter 'image' is not of type :class:`str`.
		:raises TypeError:   If an element of parameter 'services', 'tags', 'beforeScript' or 'afterScript' is not of
		                     type :class:`str`.
		"""
		super().__init__(line, parent=parent)

		if image is not None and not isinstance(image, str):
			ex = TypeError("Parameter 'image' is not of type 'str'.")
			ex.add_note(f"Got type '{getFullyQualifiedName(image)}'.")
			raise ex

		self._services =     () if services is None else tuple(services)
		self._tags =         () if tags is None else tuple(tags)
		self._beforeScript = () if beforeScript is None else tuple(beforeScript)
		self._afterScript =  () if afterScript is None else tuple(afterScript)
		for parameterName, texts in (
			("services",     self._services),
			("tags",         self._tags),
			("beforeScript", self._beforeScript),
			("afterScript",  self._afterScript)
		):
			for text in texts:
				if not isinstance(text, str):
					ex = TypeError(f"An element of parameter '{parameterName}' is not of type 'str'.")
					ex.add_note(f"Got type '{getFullyQualifiedName(text)}'.")
					raise ex

		self._image = image

		if parent is not None:
			parent._default = self

	@readonly
	def Image(self) -> Nullable[str]:
		"""
		Read-only property to access the image of the container a job runs in (:attr:`_image`).

		:returns: The image, or ``None`` if the default names none.
		"""
		return self._image

	@readonly
	def Services(self) -> tuple[str, ...]:
		"""
		Read-only property to access the images of the service containers (:attr:`_services`).

		:returns: The images, in file order.
		"""
		return self._services

	@readonly
	def Tags(self) -> tuple[str, ...]:
		"""
		Read-only property to access the tags selecting the runner (:attr:`_tags`).

		:returns: The tags, in file order.
		"""
		return self._tags

	@readonly
	def BeforeScript(self) -> tuple[str, ...]:
		"""
		Read-only property to access the lines of ``before_script`` (:attr:`_beforeScript`).

		:returns: The lines, nested lists flattened.
		"""
		return self._beforeScript

	@readonly
	def AfterScript(self) -> tuple[str, ...]:
		"""
		Read-only property to access the lines of ``after_script`` (:attr:`_afterScript`).

		:returns: The lines, nested lists flattened.
		"""
		return self._afterScript

	@classmethod
	def _FromYAML(cls, document: CommentedMap, path: Path) -> Nullable[Self]:
		"""
		Read the ``default`` key and the global keywords standing for it.

		:param document:           The configuration.
		:param path:               Path to the configuration file.
		:returns:                  The default, or ``None`` if the configuration has neither.
		:raises PipelineFileError: If key ``default`` is not a mapping.
		:raises PipelineFileError: If a key holds a value of the wrong kind.
		"""
		mapping = CommentedMap()
		line = None
		if "default" in document:
			line = Base._KeyLine(document, "default")
			if not isinstance(document["default"], CommentedMap):
				ex = PipelineFileError("Key 'default' is not a mapping.", path, line)
				ex.add_note(f"Got type '{getFullyQualifiedName(document['default'])}'.")
				raise ex

			mapping = document["default"]

		globalKeys = {key: document[key] for key in cls._KEYS if key in document and key not in mapping}
		if line is None and len(globalKeys) == 0:
			return None
		elif line is None:
			line = min(Base._KeyLine(document, key) for key in globalKeys)

		def value(key: str) -> Any:
			"""
			Nested function returning a key of ``default``, or else the global keyword.

			:param key: The key.
			:returns:   The key's value, or ``None``.
			"""
			return mapping[key] if key in mapping else globalKeys.get(key, None)

		owner = mapping if "default" in document else document
		services = None
		if (serviceList := value("services")) is not None:
			if not isinstance(serviceList, CommentedSeq):
				ex = PipelineFileError("Key 'services' of the default is not a list.", path, line)
				ex.add_note(f"Got type '{getFullyQualifiedName(serviceList)}'.")
				raise ex

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

		tags = None
		if (tagList := value("tags")) is not None:
			if not isinstance(tagList, CommentedSeq):
				ex = PipelineFileError("Key 'tags' of the default is not a list.", path, line)
				ex.add_note(f"Got type '{getFullyQualifiedName(tagList)}'.")
				raise ex

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

		return cls(
			line,
			image=Job._Name(value("image")),
			services=services,
			tags=tags,
			beforeScript=Job._Lines(value("before_script"), "before_script", "the default", owner, path),
			afterScript=Job._Lines(value("after_script"), "after_script", "the default", owner, path)
		)


@export
class Parallel(Base[Union[Job, Need]]):
	"""
	A ``parallel`` key: how often a job runs, or the matrix of variables its instances run with.

	A job runs :attr:`Count` times, or once per combination of :attr:`Matrix`: an entry maps variables to values, and
	contributes the product of their lists. A need's ``parallel`` names the matrix instances it needs.
	"""

	_PARENT_TYPE: ClassVar[ParentTypes] = (Job, Need)  #: A parallel belongs to a job or a need.

	_count:  Nullable[int]                           #: How often the job runs.
	_matrix: tuple[dict[str, tuple[str, ...]], ...]  #: Entries of the matrix: variables to their values.

	def __init__(
		self,
		line:   int,
		count:  Nullable[int]                                   = None,
		matrix: Nullable[Iterable[Mapping[str, Iterable[str]]]] = None,
		*,
		parent: Nullable[Union[Job, Need]]                      = None
	) -> None:
		"""
		Initializes a ``parallel`` key.

		:param line:        Line the ``parallel`` key is written at, starting at 1.
		:param count:       Optional, how often the job runs. Default: ``None``, for a matrix.
		:param matrix:      Optional, entries of the matrix, each mapping variables to their values. Default: ``None``,
		                    for a count.
		:param parent:      Optional, reference to the job or the need. Default: ``None``.
		:raises ValueError: If both or neither of parameters 'count' and 'matrix' are given.
		:raises TypeError:  If parameter 'count' is not of type :class:`int`.
		:raises ValueError: If parameter 'count' is out of range 1..200.
		:raises TypeError:  If an entry of parameter 'matrix' is not a mapping, or a variable's values are not strings.
		"""
		super().__init__(line, parent=parent)

		if (count is None) == (matrix is None):
			raise ValueError("Parameters 'count' and 'matrix' are both given, or both None.")
		elif count is not None and (not isinstance(count, int) or isinstance(count, bool)):
			ex = TypeError("Parameter 'count' is not of type 'int'.")
			ex.add_note(f"Got type '{getFullyQualifiedName(count)}'.")
			raise ex
		elif count is not None and not (1 <= count <= 200):
			ex = ValueError("Parameter 'count' is out of range 1..200.")
			ex.add_note(f"Got value '{count}'.")
			raise ex

		entries = []
		for entry in () if matrix is None else matrix:
			if not isinstance(entry, Mapping):
				ex = TypeError("An entry of parameter 'matrix' is not a mapping.")
				ex.add_note(f"Got type '{getFullyQualifiedName(entry)}'.")
				raise ex

			variables = {}
			for variable, values in entry.items():
				variables[variable] = tuple(values)
				if not isinstance(variable, str) or any(not isinstance(value, str) for value in variables[variable]):
					ex = TypeError(f"Variable '{variable}' of parameter 'matrix' has values not of type 'str'.")
					ex.add_note(f"Got '{variables[variable]}'.")
					raise ex

			entries.append(variables)

		self._count =  count
		self._matrix = tuple(entries)

		if parent is not None:
			parent._parallel = self

	@readonly
	def Count(self) -> Nullable[int]:
		"""
		Read-only property to access how often the job runs (:attr:`_count`).

		:returns: The count of ``parallel: N``, or ``None`` for a matrix.
		"""
		return self._count

	@readonly
	def Matrix(self) -> tuple[dict[str, tuple[str, ...]], ...]:
		"""
		Read-only property to access the entries of the matrix (:attr:`_matrix`).

		:returns: The entries, each mapping variables to their values, in file order; empty for a count.
		"""
		return self._matrix

	@readonly
	def IsMatrix(self) -> bool:
		"""
		Read-only property to return whether the key is a matrix.

		:returns: ``True`` for ``parallel: matrix``, ``False`` for ``parallel: N``.
		"""
		return self._count is None

	@readonly
	def Combinations(self) -> list[dict[str, str]]:
		"""
		Read-only property to return the combinations of the matrix, one per instance.

		:returns: The combinations, each mapping the variables to a value, in the order GitLab creates the instances.
		"""
		combinations = []
		for entry in self._matrix:
			for values in product(*entry.values()):
				combinations.append(dict(zip(entry, values)))

		return combinations

	@readonly
	def InstanceNames(self) -> list[str]:
		"""
		Read-only property to return the names GitLab gives the instances.

		:returns: The names, as ``test 1/3`` for a count, or ``deploy: [aws, app1]`` for a matrix.
		"""
		if isinstance(self._parent, Need):
			name = self._parent._job
		else:
			name = "" if self._parent is None else self._parent._name

		if self._count is not None:
			return [self._InstanceName(name, self._count, {"CI_NODE_INDEX": index}) for index in range(1, self._count + 1)]

		return [self._InstanceName(name, None, combination) for combination in self.Combinations]

	@staticmethod
	def _InstanceName(name: str, count: Nullable[int], dimensions: Mapping[str, Any]) -> str:
		"""
		Return the name GitLab gives an instance.

		:param name:       Name of the job.
		:param count:      The count of ``parallel: N``, or ``None`` for a matrix.
		:param dimensions: The instance's variables, ``CI_NODE_INDEX`` for ``parallel: N``.
		:returns:          The name, as ``test 1/3`` for a count, or ``deploy: [aws, app1]`` for a matrix.
		"""
		if count is not None:
			return f"{name} {dimensions['CI_NODE_INDEX']}/{count}"

		return f"{name}: [{', '.join(str(value) for value in dimensions.values())}]"

	@classmethod
	def _FromYAML(cls, value: Any, owner: str, path: Path, line: int) -> Self:
		"""
		Read a ``parallel`` key: a count, or a mapping with key ``matrix``.

		:param value:              The key's value.
		:param owner:              The element holding the key, for a message, as ``job 'test'``.
		:param path:               Path to the configuration file.
		:param line:               Line the ``parallel`` key is written at, starting at 1.
		:returns:                  The parallel.
		:raises PipelineFileError: If the value is neither a count nor a mapping with key ``matrix``.
		:raises PipelineFileError: If the count is out of range 1..200.
		:raises PipelineFileError: If the matrix is not a list of mappings of variables to a value or a list of values.
		"""
		count = Base._ToPython(value)
		if isinstance(count, int) and not isinstance(count, bool):
			if not (1 <= count <= 200):
				ex = PipelineFileError(f"Key 'parallel' of {owner} is out of range 1..200.", path, line)
				ex.add_note(f"Got '{count}'.")
				raise ex

			return cls(line, count)
		elif not isinstance(value, CommentedMap) or "matrix" not in value:
			ex = PipelineFileError(f"Key 'parallel' of {owner} is neither a count nor a mapping with 'matrix'.", path, line)
			ex.add_note(f"Got '{count}'.")
			raise ex

		entries = value["matrix"]
		if not isinstance(entries, CommentedSeq) or any(not isinstance(entry, CommentedMap) for entry in entries):
			ex = PipelineFileError(f"Key 'parallel.matrix' of {owner} is not a list of mappings.", path, line)
			ex.add_note(f"Got '{Base._ToPython(entries)}'.")
			raise ex

		matrix = []
		for entry in entries:
			variables = {}
			for variable, values in entry.items():
				values = values if isinstance(values, CommentedSeq) else [values]
				if any(isinstance(item, (CommentedMap, CommentedSeq)) for item in values):
					ex = PipelineFileError(
						f"Variable '{variable}' of the matrix of {owner} is neither a value nor a list of values.",
						path, Base._KeyLine(entry, variable)
					)
					ex.add_note(f"Got '{Base._ToPython(values)}'.")
					raise ex

				variables[str(variable)] = [Base._ToText(item) for item in values]

			matrix.append(variables)

		return cls(line, matrix=matrix)


@export
class Input(Base[Union[PipelineFile, Job]]):
	"""
	An input of the header's ``spec:inputs``, or of a job's ``inputs``.

	An input of a file is a parameter of its configuration, which ``include:inputs`` or ``trigger:include:inputs`` set, or
	the form running a pipeline by hand; it is mandatory without a default. An input of a job is set when the job is
	run or retried by hand, and always has a default.
	"""

	_PARENT_TYPE: ClassVar[ParentTypes] = (PipelineFile, Job)  #: An input belongs to a configuration file or a job.

	_name:        str                            #: Name of the input.
	_type:        InputType                      #: Type of the input.
	_required:    bool                           #: ``True``, if the input has no default.
	_default:     ValueT                         #: Value of the input, if it isn't set.
	_description: Nullable[str]                  #: Description of the input.
	_options:     tuple[ValueT, ...]             #: Values the input may have.
	_regex:       Nullable[str]                  #: Regular expression the input's value must match.
	_rules:       tuple[dict[str, ValueT], ...]  #: Conditional options and defaults of ``rules``.

	_KEYS: ClassVar[tuple[str, ...]] = (
		"default", "type", "description", "options", "regex", "rules"
	)  #: Keys of an input as mapping.

	def __init__(
		self,
		name:        str,
		line:        int,
		inputType:   InputType                                = InputType.String,
		required:    bool                                     = True,
		default:     ValueT                                   = None,
		description: Nullable[str]                            = None,
		options:     Nullable[Iterable[ValueT]]               = None,
		regex:       Nullable[str]                            = None,
		rules:       Nullable[Iterable[Mapping[str, ValueT]]] = None,
		*,
		parent:      Nullable[Union[PipelineFile, Job]]       = None
	) -> None:
		"""
		Initializes an input.

		:param name:        Name of the input.
		:param line:        Line the input's name is written at, starting at 1.
		:param inputType:   Optional, type of the input. Default: :attr:`InputType.String`.
		:param required:    Optional, ``True``, if the input has no default. Default: ``True``.
		:param default:     Optional, value of the input, if it isn't set. Default: ``None``.
		:param description: Optional, description of the input. Default: ``None``.
		:param options:     Optional, values the input may have. Default: ``None``.
		:param regex:       Optional, regular expression the input's value must match. Default: ``None``.
		:param rules:       Optional, conditional options and defaults, each a mapping of ``if``, ``options`` and
		                    ``default``. Default: ``None``.
		:param parent:      Optional, reference to the configuration file or the job. Default: ``None``.
		:raises ValueError: If parameter 'name' is ``None``.
		:raises TypeError:  If parameter 'name' is not of type :class:`str`.
		:raises ValueError: If parameter 'name' is empty.
		:raises TypeError:  If parameter 'inputType' is not of type :class:`InputType`.
		:raises TypeError:  If parameter 'required' is not of type :class:`bool`.
		:raises TypeError:  If parameter 'description' or 'regex' is not of type :class:`str`.
		"""
		super().__init__(line, parent=parent)

		if name is None:
			raise ValueError("Parameter 'name' is None.")
		elif not isinstance(name, str):
			ex = TypeError("Parameter 'name' is not of type 'str'.")
			ex.add_note(f"Got type '{getFullyQualifiedName(name)}'.")
			raise ex
		elif name == "":
			raise ValueError("Parameter 'name' is empty.")

		if not isinstance(inputType, InputType):
			ex = TypeError("Parameter 'inputType' is not of type 'InputType'.")
			ex.add_note(f"Got type '{getFullyQualifiedName(inputType)}'.")
			raise ex

		if not isinstance(required, bool):
			ex = TypeError("Parameter 'required' is not of type 'bool'.")
			ex.add_note(f"Got type '{getFullyQualifiedName(required)}'.")
			raise ex

		for parameterName, text in (
			("description", description),
			("regex",       regex)
		):
			if text is not None and not isinstance(text, str):
				ex = TypeError(f"Parameter '{parameterName}' is not of type 'str'.")
				ex.add_note(f"Got type '{getFullyQualifiedName(text)}'.")
				raise ex

		self._name =        name
		self._type =        inputType
		self._required =    required
		self._default =     default
		self._description = description
		self._options =     () if options is None else tuple(options)
		self._regex =       regex
		self._rules =       () if rules is None else tuple(dict(rule) for rule in rules)

		if parent is not None:
			parent._inputs[name] = self

	@readonly
	def Name(self) -> str:
		"""
		Read-only property to access the input's name (:attr:`_name`).

		:returns: Name of the input.
		"""
		return self._name

	@readonly
	def Type(self) -> InputType:
		"""
		Read-only property to access the input's type (:attr:`_type`).

		:returns: The ``type`` key, :attr:`InputType.String` if the input doesn't say.
		"""
		return self._type

	@readonly
	def Required(self) -> bool:
		"""
		Read-only property to access whether the input has to be set (:attr:`_required`).

		:returns: ``True``, if the input has no ``default`` key.
		"""
		return self._required

	@readonly
	def Default(self) -> ValueT:
		"""
		Read-only property to access the input's value, if it isn't set (:attr:`_default`).

		:returns: The default, with the type it is written with, or ``None`` if the input has none.
		"""
		return self._default

	@readonly
	def Description(self) -> Nullable[str]:
		"""
		Read-only property to access the input's description (:attr:`_description`).

		:returns: The description, or ``None`` if the input gives none.
		"""
		return self._description

	@readonly
	def Options(self) -> tuple[ValueT, ...]:
		"""
		Read-only property to access the values the input may have (:attr:`_options`).

		:returns: The options, in file order; empty if the input may have any value.
		"""
		return self._options

	@readonly
	def Regex(self) -> Nullable[str]:
		"""
		Read-only property to access the regular expression the input's value must match (:attr:`_regex`).

		:returns: The expression, as written, or ``None``.
		"""
		return self._regex

	@readonly
	def Rules(self) -> tuple[dict[str, ValueT], ...]:
		"""
		Read-only property to access the input's conditional options and defaults (:attr:`_rules`).

		:returns: The rules, each mapping ``if``, ``options`` and ``default``, in the order GitLab evaluates them.
		"""
		return self._rules

	def __str__(self) -> str:
		"""
		Return the input's name.

		:returns: Name of the input.
		"""
		return self._name

	@classmethod
	def _FromYAML(cls, name: str, declaration: Any, jobName: Nullable[str], path: Path, line: int) -> Self:
		"""
		Read an input's declaration: empty, or a mapping of the keys in :attr:`_KEYS`.

		:param name:               Name of the input.
		:param declaration:        The declaration.
		:param jobName:            Name of the job declaring the input, or ``None`` for ``spec:inputs``.
		:param path:               Path to the configuration file.
		:param line:               Line the input's name is written at, starting at 1.
		:returns:                  The input.
		:raises PipelineFileError: If the declaration is neither empty nor a mapping.
		:raises PipelineFileError: If the mapping has a key GitLab doesn't know for an input. |br|
		                           The note lists the allowed keys.
		:raises PipelineFileError: If key ``type`` is not an input type. |br|
		                           The note lists the allowed values.
		:raises PipelineFileError: If an input of a job has no default.
		:raises PipelineFileError: If the default doesn't match the type, or isn't one of the options.
		:raises PipelineFileError: If key ``options`` or ``rules`` is not a list, or ``regex`` is used with a type other
		                           than ``string``.
		"""
		subject = f"input '{name}'" if jobName is None else f"input '{name}' of job '{jobName}'"
		if declaration is None:
			declaration = CommentedMap()
		elif not isinstance(declaration, CommentedMap):
			ex = PipelineFileError(f"I{subject[1:]} is not a mapping.", path, line)
			ex.add_note(f"Got type '{getFullyQualifiedName(declaration)}'.")
			raise ex

		for key in declaration:
			if key not in cls._KEYS:
				ex = PipelineFileError(f"I{subject[1:]} has unknown key '{key}'.", path, Base._KeyLine(declaration, key))
				ex.add_note(f"Allowed keys: {', '.join(cls._KEYS)}.")
				raise ex

		try:
			inputType = InputType.Parse(Base._ToText(declaration.get("type", "string")))
		except ValueError as cause:
			ex = PipelineFileError(f"Key 'type' of {subject} is not an input type.", path, line)
			ex.add_note(f"Got '{declaration['type']}'.")
			ex.add_note(f"Allowed values: {', '.join(member.value for member in InputType)}.")
			raise ex from cause

		required = "default" not in declaration
		if required and jobName is not None:
			raise PipelineFileError(f"I{subject[1:]} has no default.", path, line)

		for key in ("options", "rules"):
			if key in declaration and not isinstance(declaration[key], CommentedSeq):
				ex = PipelineFileError(
					f"Key '{key}' of {subject} is not a list.", path, Base._KeyLine(declaration, key)
				)
				ex.add_note(f"Got type '{getFullyQualifiedName(declaration[key])}'.")
				raise ex

		default = Base._ToPython(declaration.get("default", None))
		options = Base._ToPython(declaration.get("options", []))
		types = {
			InputType.String:  (str, ),
			InputType.Number:  (int, float),
			InputType.Boolean: (bool, ),
			InputType.Array:   (list, )
		}[inputType]
		if default is not None and (not isinstance(default, types) or (isinstance(default, bool) and bool not in types)):
			ex = PipelineFileError(f"Default of {subject} is not of type '{inputType.value}'.", path, line)
			ex.add_note(f"Got '{default}'.")
			raise ex
		elif default is not None and len(options) > 0 and default not in options:
			ex = PipelineFileError(f"Default of {subject} is not one of its options.", path, line)
			ex.add_note(f"Options: {', '.join(str(option) for option in options)}.")
			raise ex
		elif "regex" in declaration and inputType is not InputType.String:
			raise PipelineFileError(f"Key 'regex' of {subject} needs type 'string'.", path, line)

		description = declaration.get("description", None)
		regex = declaration.get("regex", None)
		return cls(
			name, line, inputType, required, default,
			description=None if description is None else Base._ToText(description),
			options=options,
			regex=None if regex is None else Base._ToText(regex),
			rules=Base._ToPython(declaration.get("rules", []))
		)

	@classmethod
	def _FromYAMLMapping(cls, mapping: Any, jobName: Nullable[str], path: Path, line: int) -> list[Self]:
		"""
		Read the inputs of ``spec:inputs`` or of a job's ``inputs``.

		:param mapping:            The key's value.
		:param jobName:            Name of the job declaring the inputs, or ``None`` for ``spec:inputs``.
		:param path:               Path to the configuration file.
		:param line:               Line the key is written at, starting at 1.
		:returns:                  The inputs, in file order.
		:raises PipelineFileError: If the value is not a mapping.
		:raises PipelineFileError: If an input is malformed.
		"""
		if not isinstance(mapping, CommentedMap):
			message = "Key 'spec:inputs'" if jobName is None else f"Key 'inputs' of job '{jobName}'"
			ex = PipelineFileError(f"{message} is not a mapping.", path, line)
			ex.add_note(f"Got type '{getFullyQualifiedName(mapping)}'.")
			raise ex

		return [
			cls._FromYAML(str(name), value, jobName, path, Base._KeyLine(mapping, name)) for name, value in mapping.items()
		]


@export
class IncludeResolver(metaclass=ExtendedType, slots=True):
	"""
	Reads the local files a configuration includes, or a trigger job's child pipeline runs, from a repository's directory.

	A local include's path, as ``/ci/build.yml`` or ``ci/build.yml``, is relative to the repository's root. Includes of
	another kind - another project's files, a URL, a template, a component, an artifact - aren't read.

	Every file is read once; asking for it again returns the same :class:`PipelineFile`. A file read is read with this
	resolver, so its own local includes are read too.
	"""

	_root:      Path                      #: The repository's root directory.
	_files:     dict[Path, PipelineFile]  #: Files already read, by resolved path.
	_documents: dict[Path, CommentedMap]  #: Configurations of included files already read, by resolved path.

	def __init__(self, root: Path) -> None:
		"""
		Initializes a resolver.

		:param root:        The repository's root directory.
		:raises ValueError: If parameter 'root' is ``None``.
		:raises TypeError:  If parameter 'root' is not of type :class:`~pathlib.Path`.
		"""
		if root is None:
			raise ValueError("Parameter 'root' is None.")
		elif not isinstance(root, Path):
			ex = TypeError("Parameter 'root' is not of type 'Path'.")
			ex.add_note(f"Got type '{getFullyQualifiedName(root)}'.")
			raise ex

		self._root =      root
		self._files =     {}
		self._documents = {}

	@readonly
	def Root(self) -> Path:
		"""
		Read-only property to access the repository's root directory (:attr:`_root`).

		:returns: The directory.
		"""
		return self._root

	def Resolve(self, include: Include) -> Nullable[PipelineFile]:
		"""
		Read the file a local include names.

		:param include:            The include.
		:returns:                  The file, or ``None`` for an include of another kind, or of a file that doesn't exist.
		:raises ValueError:        If parameter 'include' is ``None``.
		:raises TypeError:         If parameter 'include' is not of type :class:`Include`.
		:raises PipelineFileError: If the file is not a well-formed configuration.
		"""
		if include is None:
			raise ValueError("Parameter 'include' is None.")
		elif not isinstance(include, Include):
			ex = TypeError("Parameter 'include' is not of type 'Include'.")
			ex.add_note(f"Got type '{getFullyQualifiedName(include)}'.")
			raise ex

		if include._kind is not IncludeKind.Local:
			return None

		path = (self._root / include._location.lstrip("/")).resolve()
		if (known := self._files.get(path, None)) is not None:
			return known
		elif not path.exists():
			return None

		self._files[path] = PipelineFile.FromFile(path, self)
		return self._files[path]

	def _Included(
		self,
		document: CommentedMap,
		path:     Path,
		visited:  tuple[Path, ...]
	) -> tuple[dict[str, Any], bool]:
		"""
		Read the local files a configuration includes, and those they include in turn.

		A file included again, by itself or another, is read once.

		:param document:           The configuration.
		:param path:               Path to the configuration file.
		:param visited:            Resolved paths of the files read on the way to this one, this one last.
		:returns:                  The top-level keys of the included files, a later file's key replacing an earlier one's;
		                           and ``True``, if an include couldn't be read.
		:raises PipelineFileError: If an include is malformed, or an included file is not a well-formed configuration.
		"""
		keys: dict[str, Any] = {}
		incomplete = False
		if "include" not in document:
			return keys, incomplete

		for include in Include._FromYAMLEntries(document["include"], path, Base._KeyLine(document, "include")):
			if include._kind is not IncludeKind.Local:
				incomplete = True
				continue

			includedPath = (self._root / include._location.lstrip("/")).resolve()
			if includedPath in visited:
				continue
			elif not includedPath.exists():
				incomplete = True
				continue
			elif includedPath not in self._documents:
				self._documents[includedPath] = PipelineFile._Load(includedPath)[1]

			nested, nestedIncomplete = self._Included(self._documents[includedPath], includedPath, (*visited, includedPath))
			incomplete = incomplete or nestedIncomplete
			keys.update(nested)
			keys.update((str(key), value) for key, value in self._documents[includedPath].items())

		return keys, incomplete


@export
class DefinitionMixin(Generic[DefinitionType], metaclass=ExtendedType, mixin=True, expects=("_DEFINITION_TYPE",)):
	"""
	Mixin-class for an element of :mod:`pyTooling.CI` built from a configuration file, linking it to its definition.

	:meth:`PipelineFile.ToPipeline` builds the elements, so a consumer of the generic model still reaches the facts only
	the file has: the line an element is written at, its stage, its trigger.
	"""

	_definition: DefinitionType  #: The element of the configuration file this element was built from.

	@classmethod
	def _CheckDefinition(cls, definition: DefinitionType) -> None:
		"""
		Check a definition before the element is built from it.

		The host class names the element by its definition, so it checks the definition before calling
		``super().__init__()``.

		:param definition:  The element of the configuration file the element is built from.
		:raises ValueError: If parameter 'definition' is ``None``.
		:raises TypeError:  If parameter 'definition' is not of the type the host class declares in
		                    :attr:`_DEFINITION_TYPE`.
		"""
		if definition is None:
			raise ValueError("Parameter 'definition' is None.")
		elif not isinstance(definition, cls._DEFINITION_TYPE):
			ex = TypeError(f"Parameter 'definition' is not of type '{cls._DEFINITION_TYPE.__name__}'.")
			ex.add_note(f"Got type '{getFullyQualifiedName(definition)}'.")
			raise ex

	@staticmethod
	def _Rules(rules: Sequence[Rule], when: Nullable[RuleOutcome], default: RuleOutcome) -> list[CIRule]:
		"""
		Return the :mod:`pyTooling.CI` rules of an element built from a configuration file.

		Each of the file's rules becomes a rule deciding the rule's ``when``, else the element's, else ``default``. Its
		``changes``, ``compare_to``, ``exists``, ``allow_failure`` and ``variables`` are the rule's key-value-pairs, as
		far as it has them. An element with ``when``, but without rules, gets one rule without condition. The rules are
		built anew for every element, as the instances of a matrix share one definition.

		:param rules:   The rules of the file's element, in the order GitLab evaluates them.
		:param when:    The ``when`` of the file's element, or ``None``.
		:param default: What a rule decides, if neither the rule nor the element say.
		:returns:       The rules, empty for an element with neither rules nor ``when``.
		"""
		if len(rules) == 0:
			return [] if when is None else [CIRule(None, when)]

		ciRules = []
		for rule in rules:
			keyValuePairs: dict[Hashable, Any] = {}
			if len(rule._changes) > 0:
				keyValuePairs["changes"] = rule._changes

			if rule._compareTo is not None:
				keyValuePairs["compare_to"] = rule._compareTo

			if len(rule._exists) > 0:
				keyValuePairs["exists"] = rule._exists

			if rule._allowFailure is not None:
				keyValuePairs["allow_failure"] = rule._allowFailure

			if len(rule._variables) > 0:
				keyValuePairs["variables"] = dict(rule._variables)

			if rule._when is not None:
				outcome = rule._when
			elif when is not None:
				outcome = when
			else:
				outcome = default

			ciRules.append(CIRule(rule._condition, outcome, keyValuePairs=keyValuePairs))

		return ciRules

	def __init__(self, definition: DefinitionType) -> None:
		"""
		Initializes the link of an element to its definition, which :meth:`_CheckDefinition` checked.

		:param definition: The element of the configuration file this element is built from.
		"""
		self._definition = definition

	@readonly
	def Definition(self) -> DefinitionType:
		"""
		Read-only property to access the file's element this element was built from (:attr:`_definition`).

		:returns: The :class:`PipelineFile` of a pipeline, or the :class:`Job` of any other element.
		"""
		return self._definition


@export
class ChildPipelineMixin(metaclass=ExtendedType, mixin=True):
	"""Mixin-class for a trigger job built from a configuration file, holding the files its child pipeline runs."""

	_childFiles: tuple[PipelineFile, ...]  #: The files the child pipeline's elements were built from.

	def __init__(self, childFiles: Nullable[Iterable[PipelineFile]] = None) -> None:
		"""
		Initializes the child pipeline's files.

		:param childFiles: Optional, the files the child pipeline's elements are built from. Default: ``None``.
		:raises TypeError: If an element of parameter 'childFiles' is not of type :class:`PipelineFile`.
		"""
		self._childFiles = () if childFiles is None else tuple(childFiles)
		for childFile in self._childFiles:
			if not isinstance(childFile, PipelineFile):
				ex = TypeError("An element of parameter 'childFiles' is not of type 'PipelineFile'.")
				ex.add_note(f"Got type '{getFullyQualifiedName(childFile)}'.")
				raise ex

	@readonly
	def ChildFiles(self) -> tuple[PipelineFile, ...]:
		"""
		Read-only property to access the files the child pipeline was expanded from (:attr:`_childFiles`).

		:returns: The files, empty if the child pipeline wasn't expanded - its files aren't at hand, the depth was used
		          up, or the job starts another project's pipeline.
		"""
		return self._childFiles


@export
class DefinedPipeline(CIPipeline, DefinitionMixin[PipelineFile]):
	"""The pipeline a configuration file defines, as :meth:`PipelineFile.ToPipeline` builds it."""

	_DEFINITION_TYPE: ClassVar[type] = PipelineFile  #: A pipeline is built from a configuration file.

	def __init__(self, definition: PipelineFile, *, keyValuePairs: Nullable[Mapping[Hashable, Any]] = None) -> None:
		"""
		Initializes a pipeline built from a configuration file, named by ``workflow:name``, or else by the file's name.

		:param definition:    The configuration file.
		:param keyValuePairs: Optional, mapping (dictionary) of key-value-pairs. Default: ``None``.
		"""
		self._CheckDefinition(definition)

		workflow = definition._workflow
		name =     definition._path.name if workflow is None or workflow._name is None else workflow._name
		rules =    [] if workflow is None else self._Rules(workflow._rules, None, RuleOutcome.Always)
		super().__init__(name, rules=rules, keyValuePairs=keyValuePairs)
		DefinitionMixin.__init__(self, definition)


@export
class DefinedWorkflow(CIWorkflow, ChildPipelineMixin, DefinitionMixin[Job]):
	"""A trigger job, as :meth:`PipelineFile.ToPipeline` builds it: the pipeline it starts, as a workflow."""

	_DEFINITION_TYPE: ClassVar[type] = Job  #: A workflow is built from a trigger job.

	def __init__(
		self,
		definition:    Job,
		*,
		childFiles:    Nullable[Iterable[PipelineFile]] = None,
		keyValuePairs: Nullable[Mapping[Hashable, Any]] = None,
		parent:        Nullable[CIWorkflow]             = None
	) -> None:
		"""
		Initializes a workflow built from a trigger job, named by the job's key.

		The other project, or the child pipeline's files, are the workflow's :attr:`~pyTooling.CI.Workflow.Reference`,
		the job's rules the workflow's :attr:`~pyTooling.CI.RulesMixin.Rules`.

		:param definition:    The trigger job.
		:param childFiles:    Optional, the files the child pipeline's elements are built from. Default: ``None``.
		:param keyValuePairs: Optional, mapping (dictionary) of key-value-pairs. Default: ``None``.
		:param parent:        Optional, reference to the workflow containing the trigger job. Default: ``None``.
		:raises ValueError:   If parameter 'definition' starts no pipeline.
		"""
		self._CheckDefinition(definition)

		if definition._trigger is None:
			ex = ValueError("Parameter 'definition' starts no pipeline.")
			ex.add_note(f"Got job '{definition._name}'.")
			raise ex

		super().__init__(
			definition._name, reference=DefinedWorkflow._Reference(definition),
			rules=self._Rules(definition._rules, definition._when, RuleOutcome.DEFAULT), keyValuePairs=keyValuePairs,
			parent=parent
		)
		ChildPipelineMixin.__init__(self, childFiles)
		DefinitionMixin.__init__(self, definition)

	@staticmethod
	def _Reference(definition: Job) -> str:
		"""
		Return what a trigger job starts, for :attr:`~pyTooling.CI.Workflow.Reference`.

		:param definition: The trigger job.
		:returns:          The other project's path, or the child pipeline's files, as ``local: /ci/child.yml``.
		"""
		trigger = definition._trigger
		if trigger._project is not None:
			return trigger._project

		return ", ".join(str(include) for include in trigger._includes)


@export
class DefinedMatrix(CIMatrix, DefinitionMixin[Job]):
	"""A job with ``parallel``, as :meth:`PipelineFile.ToPipeline` builds it: a matrix of its instances."""

	_DEFINITION_TYPE: ClassVar[type] = Job  #: A matrix is built from a job with ``parallel``.

	def __init__(
		self,
		definition:    Job,
		*,
		keyValuePairs: Nullable[Mapping[Hashable, Any]] = None,
		parent:        Nullable[CIWorkflow]             = None
	) -> None:
		"""
		Initializes a matrix built from a job with ``parallel``, named by the job's key.

		:param definition:    The job.
		:param keyValuePairs: Optional, mapping (dictionary) of key-value-pairs. Default: ``None``.
		:param parent:        Optional, reference to the workflow containing the matrix. Default: ``None``.
		:raises ValueError:   If parameter 'definition' has no ``parallel``.
		"""
		self._CheckDefinition(definition)

		if definition._parallel is None:
			ex = ValueError("Parameter 'definition' has no 'parallel'.")
			ex.add_note(f"Got job '{definition._name}'.")
			raise ex

		super().__init__(
			definition._name, rules=self._Rules(definition._rules, definition._when, RuleOutcome.DEFAULT),
			keyValuePairs=keyValuePairs, parent=parent
		)
		DefinitionMixin.__init__(self, definition)


@export
class DefinedMatrixWorkflow(CIMatrixWorkflow, ChildPipelineMixin, DefinitionMixin[Job]):
	"""One instance of a trigger job with ``parallel``, as :meth:`PipelineFile.ToPipeline` builds it."""

	_DEFINITION_TYPE: ClassVar[type] = Job  #: A matrix instance is built from the job with ``parallel``.

	def __init__(
		self,
		definition:    Job,
		dimensions:    Mapping[str, Any],
		*,
		childFiles:    Nullable[Iterable[PipelineFile]] = None,
		keyValuePairs: Nullable[Mapping[Hashable, Any]] = None,
		parent:        Nullable[CIMatrix]               = None
	) -> None:
		"""
		Initializes one instance of a trigger job with ``parallel``, named by the job's key.

		:param definition:    The trigger job.
		:param dimensions:    The variables this instance runs with, as ``{"PROVIDER": "aws"}``, or
		                      ``{"CI_NODE_INDEX": "2"}`` for ``parallel: N``.
		:param childFiles:    Optional, the files the child pipeline's elements are built from. Default: ``None``.
		:param keyValuePairs: Optional, mapping (dictionary) of key-value-pairs. Default: ``None``.
		:param parent:        Optional, reference to the matrix containing the instance. Default: ``None``.
		:raises ValueError:   If parameter 'definition' starts no pipeline.
		:raises ValueError:   If parameter 'dimensions' is ``None``.
		"""
		self._CheckDefinition(definition)

		if definition._trigger is None:
			ex = ValueError("Parameter 'definition' starts no pipeline.")
			ex.add_note(f"Got job '{definition._name}'.")
			raise ex
		elif dimensions is None:
			raise ValueError("Parameter 'dimensions' is None.")

		super().__init__(
			definition._name, dimensions, reference=DefinedWorkflow._Reference(definition),
			rules=self._Rules(definition._rules, definition._when, RuleOutcome.DEFAULT), keyValuePairs=keyValuePairs,
			parent=parent
		)
		ChildPipelineMixin.__init__(self, childFiles)
		DefinitionMixin.__init__(self, definition)

	def __str__(self) -> str:
		"""
		Return the name GitLab gives the instance.

		:returns: The name, as ``test 1/3`` for ``parallel: N``, or ``test: [3.14, linux]`` for a matrix.
		"""
		return Parallel._InstanceName(self._name, self._definition._parallel._count, self._dimensions)


@export
class DefinedJob(CIJob, DefinitionMixin[Job]):
	"""A job running a script, as :meth:`PipelineFile.ToPipeline` builds it."""

	_DEFINITION_TYPE: ClassVar[type] = Job  #: A job is built from its job in the configuration file.

	def __init__(
		self,
		definition:    Job,
		*,
		keyValuePairs: Nullable[Mapping[Hashable, Any]] = None,
		parent:        Nullable[JobGroup]               = None
	) -> None:
		"""
		Initializes a job built from its job in the configuration file, named by the job's key.

		:param definition:    The job.
		:param keyValuePairs: Optional, mapping (dictionary) of key-value-pairs. Default: ``None``.
		:param parent:        Optional, reference to the group containing the job. Default: ``None``.
		"""
		self._CheckDefinition(definition)

		super().__init__(
			definition._name, rules=self._Rules(definition._rules, definition._when, RuleOutcome.DEFAULT),
			keyValuePairs=keyValuePairs, parent=parent
		)
		DefinitionMixin.__init__(self, definition)


@export
class DefinedMatrixJob(CIMatrixJob, DefinitionMixin[Job]):
	"""One instance of a job with ``parallel``, as :meth:`PipelineFile.ToPipeline` builds it."""

	_DEFINITION_TYPE: ClassVar[type] = Job  #: A matrix instance is built from the job with ``parallel``.

	def __init__(
		self,
		definition:    Job,
		dimensions:    Mapping[str, Any],
		*,
		keyValuePairs: Nullable[Mapping[Hashable, Any]] = None,
		parent:        Nullable[CIMatrix]               = None
	) -> None:
		"""
		Initializes one instance of a job with ``parallel``, named by the job's key.

		:param definition:    The job.
		:param dimensions:    The variables this instance runs with, as ``{"PROVIDER": "aws"}``, or
		                      ``{"CI_NODE_INDEX": "2"}`` for ``parallel: N``.
		:param keyValuePairs: Optional, mapping (dictionary) of key-value-pairs. Default: ``None``.
		:param parent:        Optional, reference to the matrix containing the instance. Default: ``None``.
		:raises ValueError:   If parameter 'dimensions' is ``None``.
		"""
		self._CheckDefinition(definition)

		if dimensions is None:
			raise ValueError("Parameter 'dimensions' is None.")

		super().__init__(
			definition._name, dimensions, rules=self._Rules(definition._rules, definition._when, RuleOutcome.DEFAULT),
			keyValuePairs=keyValuePairs, parent=parent
		)
		DefinitionMixin.__init__(self, definition)

	def __str__(self) -> str:
		"""
		Return the name GitLab gives the instance.

		:returns: The name, as ``test 1/3`` for ``parallel: N``, or ``test: [3.14, linux]`` for a matrix.
		"""
		return Parallel._InstanceName(self._name, self._definition._parallel._count, self._dimensions)