pyTooling.GitHub.WorkflowFile

pyTooling/GitHub/WorkflowFile.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
# ==================================================================================================================== #
#             _____           _ _               ____ _ _   _   _       _                                               #
#  _ __  _   |_   _|__   ___ | (_)_ __   __ _  / ___(_) |_| | | |_   _| |__                                            #
# | '_ \| | | || |/ _ \ / _ \| | | '_ \ / _` || |  _| | __| |_| | | | | '_ \                                           #
# | |_) | |_| || | (_) | (_) | | | | | | (_| || |_| | | |_|  _  | |_| | |_) |                                          #
# | .__/ \__, ||_|\___/ \___/|_|_|_| |_|\__, (_)____|_|\__|_| |_|\__,_|_.__/                                           #
# |_|    |___/                          |___/                                                                          #
# ==================================================================================================================== #
# 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 GitHub Actions workflow file.

A workflow file is read once into objects:

.. code-block:: text

   Workflow                 a workflow file, e.g. '.github/workflows/CompletePipeline.yml'
   +-- Input                an input of 'on.workflow_call'
   +-- Output               an output of 'on.workflow_call'
   +-- Secret               a secret of 'on.workflow_call'
   +-- Permission           a permission the workflow declares
   +-- Job                  a job, in file order
       +-- UsesReference    the reusable workflow the job calls
       +-- Permission       a permission the job declares
       +-- Matrix           the job's 'strategy.matrix'
       +-- Step             a step of the job
           +-- UsesReference    the action the step runs

   Action                   an action's file, e.g. '.github/actions/ComputeRequirements/action.yml'
   +-- Step                 a step of a composite action
       +-- UsesReference    the action the step runs

Every element knows its parent, the workflow it belongs to, the file it was read from - a workflow's or an action's -
and the line it starts at, so a consumer can name the place a finding comes from, as ``CompletePipeline.yml:552``.

:class:`WorkflowResolver` reads the reusable workflows a job calls and the actions a step runs, as far as they are in a
local directory.

The model is independent of :mod:`pyTooling.GitHub`, which models a workflow *run* as the REST API reports it.
:meth:`Workflow.ToPipeline` builds the pipeline a workflow defines as a :mod:`pyTooling.CI` model, whose
elements link back to the jobs they were built from, and :meth:`Workflow.ApplyNeeds` gives a run the dependencies
its workflow file declares.
"""
from __future__               import annotations

from functools                import cached_property
from itertools                import product
from json                     import dumps as json_dumps
from pathlib                  import Path, PurePosixPath
from typing                   import Any, ClassVar, Generic, Hashable, Iterable, Iterator, Mapping, Optional as Nullable
from typing                   import Self, TypeVar, Union

from pyTooling.CI             import CIError, DependencyMixin, JobGroup, Matrix as CIMatrix, MatrixInstanceMixin
from pyTooling.CI             import MatrixJob as CIMatrixJob, MatrixWorkflow as CIMatrixWorkflow
from pyTooling.CI             import Job as CIJob, Pipeline as CIPipeline, Step as CIStep, Workflow as CIWorkflow
from pyTooling.Common         import getFullyQualifiedName, StringEnum
from pyTooling.Decorators     import export, readonly
from pyTooling.MetaClasses    import ExtendedType, abstractclass

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

ValueT = Union[str, bool, int, float, None, list["ValueT"], dict[str, "ValueT"]]
"""A value read from a workflow 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 workflow file's element an element of :mod:`pyTooling.CI` is built from."""


@export
class WorkflowError(CIError):
	"""
	Base-exception of all exceptions raised by :mod:`pyTooling.GitHub.WorkflowFile`.

	The exception is raised for a workflow file that is not a well-formed workflow. 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 workflow file.
	_line: Nullable[int]   #: Line in the workflow file, starting at 1.

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

		:param message: The exception's message.
		:param path:    Optional, path to the workflow file. Default: ``None``.
		:param line:    Optional, line in the workflow 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 workflow 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 AccessLevel(StringEnum):
	"""
	The access a permission grants to the ``GITHUB_TOKEN``.

	The members are declared from the least to the most access, so :meth:`Rank` orders them.
	"""

	NoAccess = "none"   #: No access.
	Read =     "read"   #: Read access.
	Write =    "write"  #: Read and write access.

	@cached_property
	def Rank(self) -> int:
		"""
		Read-only property to return the member's position in the order of access, so levels can be compared.

		It is computed once per member.

		:returns: ``0`` for :attr:`NoAccess`, ``1`` for :attr:`Read`, ``2`` for :attr:`Write`.
		"""
		return list(AccessLevel).index(self)


@export
class PermissionScope(StringEnum):
	"""
	The scope a permission grants the ``GITHUB_TOKEN`` access to, as a key of ``permissions``.

	:attr:`All` stands for every scope at once, as ``read-all`` and ``write-all`` grant it.
	"""

	All =                 "*"                     #: Every scope, from ``read-all`` or ``write-all``.
	Actions =             "actions"               #: Workflows, runs and artifacts.
	ArtifactMetadata =    "artifact-metadata"     #: Storage records of artifacts.
	Attestations =        "attestations"          #: Artifact attestations.
	Checks =              "checks"                #: Check runs and check suites.
	CodeQuality =         "code-quality"          #: Code quality findings.
	Contents =            "contents"              #: Repository contents, commits, branches, tags and releases.
	Deployments =         "deployments"           #: Deployments.
	Discussions =         "discussions"           #: GitHub Discussions.
	IDToken =             "id-token"              #: An OpenID Connect token.
	Issues =              "issues"                #: Issues and their comments.
	Packages =            "packages"              #: GitHub Packages.
	Pages =               "pages"                 #: GitHub Pages builds.
	PullRequests =        "pull-requests"         #: Pull requests.
	SecurityEvents =      "security-events"       #: Code scanning alerts.
	Statuses =            "statuses"              #: Commit statuses.
	VulnerabilityAlerts = "vulnerability-alerts"  #: Dependabot alerts.


@export
class InputType(StringEnum):
	"""The type of an input of a reusable workflow."""

	String =  "string"   #: A string.
	Boolean = "boolean"  #: A boolean.
	Number =  "number"   #: A number.


@export
@abstractclass
class Base(Generic[ParentType], metaclass=ExtendedType, slots=True):
	"""
	Common behaviour of every element of a workflow file or an action's file.

	Every element knows the element containing it, the workflow it belongs to, the file it was read from, 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.
	_workflow: Nullable[Workflow]    #: Reference to the workflow this element belongs to.
	_file:     Nullable[Path]        #: Path to the file the element was read from: a workflow's or an action's file.
	_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 workflow file.

		:param line:        Line the element starts at in the workflow 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._workflow = None if parent is None else parent._workflow
		self._file =     None if parent is None else parent._file
		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 workflow and file,
		and so do the elements it contains.

		:returns:           The containing element, or ``None`` for a :class:`Workflow`.
		:raises ValueError: If ``None`` is assigned.
		:raises TypeError:  If a parent is assigned to a :class:`Workflow` or an :class:`Action`, which have 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._workflow = value._workflow
		self._file =     value._file

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

		:returns: The workflow, or ``None`` for an element outside one.
		"""
		return self._workflow

	@readonly
	def File(self) -> Nullable[Path]:
		"""
		Read-only property to access the file the element was read from (:attr:`_file`).

		:returns: Path to the workflow's or the action's file, or ``None`` for an element outside both.
		"""
		return self._file

	@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 ``CompletePipeline.yml:552`` or ``action.yml:12``, or ``line 552`` for
		          an element outside a file.
		"""
		if self._file is None:
			return f"line {self._line}"

		return f"{self._file.name}:{self._line}"

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

		:param mapping: The mapping read from the file.
		:param key:     The key.
		:returns:       The line, starting at 1.
		"""
		return mapping.lc.key(key)[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 - an anchored boolean even prints as ``0`` or ``1``. 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


@export
class Workflow(Base[None]):
	"""
	A GitHub Actions workflow file.

	The workflow is named by its file's stem - ``CompletePipeline`` for ``CompletePipeline.yml`` - because that is how
	a caller names it in ``uses``; the ``name`` key is kept as :attr:`DisplayName`.
	"""

	_path:        Path                                         #: Path to the workflow file.
	_name:        str                                          #: Name of the workflow, the file's stem.
	_displayName: Nullable[str]                                #: Name of the workflow, as GitHub displays it.
	_triggers:    tuple[str, ...]                              #: Events triggering the workflow.
	_inputs:      dict[str, Input]                             #: Inputs of ``on.workflow_call``, by name.
	_outputs:     dict[str, Output]                            #: Outputs of ``on.workflow_call``, by name.
	_secrets:     dict[str, Secret]                            #: Secrets of ``on.workflow_call``, by name.
	_permissions: Nullable[dict[PermissionScope, Permission]]  #: Permissions the workflow declares, by scope.
	_jobs:        dict[str, Job]                               #: Jobs of the workflow, by name, in file order.

	def __init__(
		self,
		path:        Path,
		displayName: Nullable[str]                  = None,
		triggers:    Nullable[Iterable[str]]        = None,
		inputs:      Nullable[Iterable[Input]]      = None,
		outputs:     Nullable[Iterable[Output]]     = None,
		secrets:     Nullable[Iterable[Secret]]     = None,
		permissions: Nullable[Iterable[Permission]] = None,
		jobs:        Nullable[Iterable[Job]]        = None
	) -> None:
		"""
		Initializes a workflow.

		An input, output, secret, permission or job is attached by passing it, or by constructing it with the workflow as
		parent. Use :meth:`FromFile` to read a workflow file.

		:param path:        Path to the workflow file.
		:param displayName: Optional, name of the workflow, as GitHub displays it. Default: ``None``.
		:param triggers:    Optional, events triggering the workflow, as ``workflow_call``. Default: ``None``.
		:param inputs:      Optional, inputs of ``on.workflow_call``, which are attached to the workflow. Default: ``None``.
		:param outputs:     Optional, outputs of ``on.workflow_call``, which are attached to the workflow. Default:
		                    ``None``.
		:param secrets:     Optional, secrets of ``on.workflow_call``, which are attached to the workflow. Default:
		                    ``None``.
		:param permissions: Optional, permissions the workflow declares for all its jobs, which are attached to the
		                    workflow. Default: ``None``, for a workflow without a ``permissions`` key.
		:param jobs:        Optional, jobs, which are attached to the workflow. Default: ``None``.
		:raises ValueError: If parameter 'path' is ``None``.
		:raises TypeError:  If parameter 'path' is not of type :class:`~pathlib.Path`.
		:raises TypeError:  If parameter 'displayName' is not of type :class:`str`.
		:raises TypeError:  If an element of parameter 'triggers' is not of type :class:`str`.
		:raises TypeError:  If an element of parameter 'inputs' is not of type :class:`Input`.
		:raises TypeError:  If an element of parameter 'outputs' is not of type :class:`Output`.
		:raises TypeError:  If an element of parameter 'secrets' is not of type :class:`Secret`.
		:raises TypeError:  If an element of parameter 'permissions' is not of type :class:`Permission`.
		:raises TypeError:  If an element of parameter 'jobs' is not of type :class:`Job`.
		"""
		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 displayName is not None and not isinstance(displayName, str):
			ex = TypeError("Parameter 'displayName' is not of type 'str'.")
			ex.add_note(f"Got type '{getFullyQualifiedName(displayName)}'.")
			raise ex

		self._workflow =    self
		self._file =        path
		self._path =        path
		self._name =        path.stem
		self._displayName = displayName
		self._triggers =    ()
		self._inputs =      {}
		self._outputs =     {}
		self._secrets =     {}
		self._permissions = None
		self._jobs =        {}

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

		for parameterName, elements, elementClass, container in (
			("inputs",  inputs,  Input,  self._inputs),
			("outputs", outputs, Output, self._outputs),
			("secrets", secrets, Secret, self._secrets),
			("jobs",    jobs,    Job,    self._jobs)
		):
			if elements is None:
				continue

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

				container[element._name] = element
				element.Parent = self

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

				self._permissions[permission._scope] = permission
				permission.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 workflow file (:attr:`_path`).

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

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

		:returns: Name of the workflow, as ``CompletePipeline``.
		"""
		return self._name

	@readonly
	def DisplayName(self) -> Nullable[str]:
		"""
		Read-only property to access the workflow's name, as GitHub displays it (:attr:`_displayName`).

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

	@readonly
	def Triggers(self) -> tuple[str, ...]:
		"""
		Read-only property to access the events triggering the workflow (:attr:`_triggers`).

		:returns: The events, as ``workflow_call`` or ``push``, in the order the ``on`` key lists them.
		"""
		return self._triggers

	@readonly
	def IsCallable(self) -> bool:
		"""
		Read-only property to return whether the workflow is a reusable workflow.

		:returns: ``True``, if the workflow is triggered by ``workflow_call``.
		"""
		return "workflow_call" in self._triggers

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

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

	@readonly
	def Outputs(self) -> dict[str, Output]:
		"""
		Read-only property to access the outputs of ``on.workflow_call`` (:attr:`_outputs`).

		:returns: The outputs, by name, in file order.
		"""
		return self._outputs

	@readonly
	def Secrets(self) -> dict[str, Secret]:
		"""
		Read-only property to access the secrets of ``on.workflow_call`` (:attr:`_secrets`).

		:returns: The secrets, by name, in file order.
		"""
		return self._secrets

	@readonly
	def Permissions(self) -> Nullable[dict[PermissionScope, Permission]]:
		"""
		Read-only property to access the permissions the workflow declares for all its jobs (:attr:`_permissions`).

		:returns: The permissions, by scope, or ``None`` if the workflow has no ``permissions`` key.
		"""
		return self._permissions

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

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

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

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

		* a job running steps becomes a :class:`DefinedJob`, its steps :class:`DefinedStep`\\ s;
		* a job calling a reusable workflow becomes a :class:`DefinedWorkflow`, holding the elements of the called
		  workflow, if the resolver reads it and the depth allows it;
		* a job with a ``strategy.matrix`` becomes a :class:`DefinedMatrix`, holding a :class:`DefinedMatrixJob` or a
		  :class:`DefinedMatrixWorkflow` per combination of :attr:`Matrix.Combinations`. A dynamic matrix holds no
		  instances, because its combinations are known at run time only.

		The ``needs`` of the jobs become the elements' :attr:`~pyTooling.CI.DependencyMixin.Needs`, so
		:meth:`~pyTooling.CI.Workflow.ToGraph` converts the result into a graph.

		:param resolver:       Optional, the resolver reading the workflows the jobs call. Without it, called workflows
		                       are not expanded. Default: ``None``.
		:param depth:          Optional, how many levels of called workflows to expand; ``0`` expands none, ``None``
		                       every level. Default: ``None``.
		:returns:              The pipeline.
		:raises TypeError:     If parameter 'resolver' is not of type :class:`WorkflowResolver`.
		:raises TypeError:     If parameter 'depth' is not of type :class:`int`.
		:raises ValueError:    If parameter 'depth' is negative.
		:raises WorkflowError: If a workflow to expand doesn't exist, or is not a well-formed workflow.
		:raises WorkflowError: If a workflow to expand calls itself, directly or through others.
		:raises WorkflowError: If ``include`` or ``exclude`` of a matrix is not a list of mappings.
		"""
		if resolver is not None and not isinstance(resolver, WorkflowResolver):
			ex = TypeError("Parameter 'resolver' is not of type 'WorkflowResolver'.")
			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 addElements(workflow: Workflow, group: CIWorkflow, level: int, callers: tuple[Workflow, ...]) -> None:
			"""
			Nested function for recursion.

			:param workflow:       The workflow whose jobs become elements.
			:param group:          The group the elements are added to.
			:param level:          How many levels of called workflows are expanded above this one.
			:param callers:        The workflows expanded above this one, this one last.
			:raises WorkflowError: If a workflow to expand calls itself, directly or through others.
			"""
			elements: dict[str, DependencyMixin] = {}
			for job in workflow._jobs.values():
				called = None
				if job._uses is not None and resolver is not None and (depth is None or level < depth):
					called = resolver.Resolve(job._uses)
					if called is not None and any(caller._path.resolve() == called._path.resolve() for caller in callers):
						ex = WorkflowError(f"Workflow '{called._name}' calls itself.", workflow._path, job._uses._line)
						ex.add_note(f"Calls: {' -> '.join(caller._name for caller in (*callers, called))}.")
						raise ex

				if job._matrix is not None:
					element = DefinedMatrix(job, parent=group)
					if not job._matrix.IsDynamic:
						for combination in job._matrix.Combinations:
							dimensions = Matrix._FormatCombination(combination)
							if job._uses is None:
								instance = DefinedMatrixJob(job, dimensions, parent=element)
								for step in job._steps:
									DefinedStep(step, parent=instance)
							else:
								instance = DefinedMatrixWorkflow(job, dimensions, calledWorkflow=called, parent=element)
								if called is not None:
									addElements(called, instance, level + 1, (*callers, called))
				elif job._uses is not None:
					element = DefinedWorkflow(job, calledWorkflow=called, parent=group)
					if called is not None:
						addElements(called, element, level + 1, (*callers, called))
				else:
					element = DefinedJob(job, parent=group)
					for step in job._steps:
						DefinedStep(step, parent=element)

				elements[job._name] = element

			for job in workflow._jobs.values():
				for need in job.Needs:
					elements[job._name].AddNeed(elements[need._name])

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

		return pipeline

	def ApplyNeeds(self, pipeline: CIWorkflow, resolver: Nullable[WorkflowResolver] = None) -> list[str]:
		"""
		Give a run of this workflow the dependencies its jobs declare with ``needs``.

		A run read from a service's API, as :class:`pyTooling.GitHub.Pipeline`, knows no ``needs``. Each job of this
		workflow is looked up in the run by its display name, or else by its key, and gets as
		:attr:`~pyTooling.CI.DependencyMixin.Needs` the elements the jobs it needs were found as. A job calling
		a reusable workflow is followed into the called workflow of the run - into each instance, if it is a matrix -,
		as far as the resolver reads the called file. A dependency the run's element has already is kept once.

		A job whose display name is an expression, as ``${{ matrix.os }} Tests``, can't be looked up, and is skipped. A
		job with a condition may have been skipped in the run, so it isn't reported when it is missing.

		A run names a matrix instance's dimensions by position, as ``{"0": "ubuntu-26.04", "1": "3.14"}``. If the job
		declares a static matrix, an instance whose values are those of one of :attr:`Matrix.Combinations` gets that
		combination's names, ``{"os": "ubuntu-26.04", "python": "3.14"}``. The instances of a dynamic matrix, and an
		instance matching no combination, keep the positions.

		:param pipeline:                  The run, or a called workflow of a run.
		:param resolver:                  Optional, the resolver reading the workflows the jobs call. Without it, called
		                                  workflows are not followed. Default: ``None``.
		:returns:                         The qualified names of the jobs of this workflow, and of the workflows followed,
		                                  missing in the run - as the run would name them -, in the order they were looked
		                                  up.
		:raises ValueError:               If parameter 'pipeline' is ``None``.
		:raises TypeError:                If parameter 'pipeline' is not of type :class:`pyTooling.CI.Workflow`.
		:raises TypeError:                If parameter 'resolver' is not of type :class:`WorkflowResolver`.
		:raises WorkflowError:            If a workflow to follow doesn't exist, or is not a well-formed workflow.
		:raises WorkflowError:            If ``include`` or ``exclude`` of a matrix is not a list of mappings.
		:raises NeedDependencyCycleError: If the needs of the run, with the needs added, form a cycle.
		"""
		if pipeline is None:
			raise ValueError("Parameter 'pipeline' is None.")
		elif not isinstance(pipeline, CIWorkflow):
			ex = TypeError("Parameter 'pipeline' is not of type 'Workflow'.")
			ex.add_note(f"Got type '{getFullyQualifiedName(pipeline)}'.")
			raise ex

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

		missing: list[str] = []

		def apply(workflow: Workflow, group: CIWorkflow) -> None:
			"""
			Nested function for recursion.

			:param workflow: The workflow whose jobs are looked up.
			:param group:    The group of the run the jobs are looked up in.
			"""
			elements: dict[str, DependencyMixin] = {}
			for job in workflow._jobs.values():
				if job._displayName is None:
					names = (job._name, )
				elif "${{" in job._displayName:
					continue
				else:
					names = (job._displayName, job._name)

				if (name := next((name for name in names if group.ContainsElement(name)), None)) is None:
					if job._condition is None:
						missing.append(names[0] if isinstance(group, CIPipeline) else f"{group.QualifiedName} / {names[0]}")
					continue

				element = group.GetElement(name)
				elements[job._name] = element
				if job._matrix is not None and not job._matrix.IsDynamic and isinstance(element, CIMatrix):
					combinations = [Matrix._FormatCombination(combination) for combination in job._matrix.Combinations]
					for instance in element.Instances:
						if not isinstance(instance, MatrixInstanceMixin):
							continue

						values = [str(value) for value in instance._dimensions.values()]
						if (names := next((c for c in combinations if list(c.values()) == values), None)) is not None:
							instance._dimensions = dict(zip(names, instance._dimensions.values()))

				if job._uses is None or resolver is None or (called := resolver.Resolve(job._uses)) is None:
					continue
				elif isinstance(element, CIWorkflow):
					apply(called, element)
				elif isinstance(element, CIMatrix):
					for instance in element.Instances:
						if isinstance(instance, CIWorkflow):
							apply(called, instance)

			for job in workflow._jobs.values():
				if (element := elements.get(job._name, None)) is None:
					continue

				for need in job.Needs:
					if (needed := elements.get(need._name, None)) is not None and needed not in element._needs:
						element.AddNeed(needed)

		apply(self, pipeline)
		pipeline.Validate()

		return missing

	def IterateActions(self) -> Iterator[UsesReference]:
		"""
		Iterate the actions the workflow's steps run.

		An action is yielded as often as a step runs it. The reusable workflows the jobs call are in :attr:`Job.Uses`.

		:returns: An iterator over the actions, in file order.
		"""
		for job in self._jobs.values():
			for step in job._steps:
				if step._uses is not None:
					yield step._uses

	def CollectPermissions(self, resolver: Nullable[WorkflowResolver] = None) -> dict[PermissionScope, Permission]:
		"""
		Collect the permissions the workflow and its jobs declare, and those of the workflows its jobs call.

		A called workflow can keep or reduce the permissions of the ``GITHUB_TOKEN``, never raise them, so what a
		workflow's jobs declare is what a caller has to grant. When several elements declare a scope, the permission
		granting the most access is returned, so its :attr:`~Base.Location` names where that access is asked for.

		:param resolver:   Optional, the resolver reading the workflows the jobs call. Without it, called workflows are
		                   not followed. Default: ``None``.
		:returns:          The permissions, by scope, in the order they are first declared.
		:raises TypeError: If parameter 'resolver' is not of type :class:`WorkflowResolver`.
		"""
		if resolver is not None and not isinstance(resolver, WorkflowResolver):
			ex = TypeError("Parameter 'resolver' is not of type 'WorkflowResolver'.")
			ex.add_note(f"Got type '{getFullyQualifiedName(resolver)}'.")
			raise ex

		collected: dict[PermissionScope, Permission] = {}
		visited:   set[int] = set()

		def collect(workflow: Workflow) -> None:
			"""
			Nested function for recursion.

			:param workflow: The workflow whose permissions are collected.
			"""
			visited.add(id(workflow))

			declarations = [] if workflow._permissions is None else [workflow._permissions]
			for job in workflow._jobs.values():
				if job._permissions is not None:
					declarations.append(job._permissions)

			for permissions in declarations:
				for scope, permission in permissions.items():
					if (known := collected.get(scope, None)) is None or permission._level.Rank > known._level.Rank:
						collected[scope] = permission

			if resolver is not None:
				for job in workflow._jobs.values():
					if job._uses is None or (called := resolver.Resolve(job._uses)) is None:
						continue
					elif id(called) not in visited:
						collect(called)

		collect(self)

		return collected

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

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

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

		:param name: Name of the job, the key it is declared under.
		:returns:    ``True``, if the workflow has a job of that name.
		"""
		return name in self._jobs

	def IterateJobs(self) -> Iterator[Job]:
		"""
		Iterate the workflow's jobs.

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

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

		:returns: Name of the workflow, the file's stem.
		"""
		return self._name

	@classmethod
	def FromFile(cls, path: Path) -> Self:
		"""
		Read a workflow file.

		:param path:           Path to the workflow file.
		:returns:              The workflow, with its parameters, permissions and jobs attached.
		:raises ValueError:    If parameter 'path' is ``None``.
		:raises TypeError:     If parameter 'path' is not of type :class:`~pathlib.Path`.
		:raises WorkflowError: If the file doesn't exist.
		:raises WorkflowError: If the file can't be read.
		:raises WorkflowError: If the file is not a YAML document.
		:raises WorkflowError: If the document is not a mapping, or has no ``on`` or ``jobs`` key.
		:raises WorkflowError: If a parameter of ``on.workflow_call`` lacks a key GitHub requires, or has a value of the
		                       wrong kind. |br|
		                       For an unknown input type, the note lists the allowed values.
		:raises WorkflowError: If a job is malformed, needs a job the workflow doesn't have, or the jobs need each other in
		                       a cycle. |br|
		                       For an unknown job, the note lists the workflow'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
		elif not path.exists():
			raise WorkflowError("Workflow file doesn't exist.", path) from FileNotFoundError(path)

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

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

		if document is None:
			raise WorkflowError("Workflow file is empty.", path)
		elif not isinstance(document, CommentedMap):
			ex = WorkflowError("Workflow file is not a mapping.", path, 1)
			ex.add_note(f"Got type '{getFullyQualifiedName(document)}'.")
			raise ex
		elif "on" not in document:
			raise WorkflowError("Workflow file has no 'on' key.", path)
		elif "jobs" not in document:
			raise WorkflowError("Workflow file has no 'jobs' key.", path)

		workflow = cls._Parse(document, path)
		workflow._Validate()

		return workflow

	@classmethod
	def _Parse(cls, document: CommentedMap, path: Path) -> Self:
		"""
		Build a workflow and the elements it contains from the document read from its file.

		:param document:       The document, a mapping with an ``on`` and a ``jobs`` key.
		:param path:           Path to the workflow file.
		:returns:              The workflow, with its parameters, permissions and jobs attached.
		:raises WorkflowError: If key ``on`` is neither an event, a list nor a mapping.
		:raises WorkflowError: If a parameter of ``on.workflow_call`` lacks a key GitHub requires, or has a value of the
		                       wrong kind. |br|
		                       For an unknown input type, the note lists the allowed values.
		:raises WorkflowError: If key ``jobs`` or a job is not a mapping, or a job is malformed.
		"""
		on = document["on"]
		if isinstance(on, str):
			triggers = (on, )
		elif isinstance(on, (CommentedSeq, CommentedMap)):
			triggers = tuple(str(trigger) for trigger in on)
		else:
			ex = WorkflowError("Key 'on' is neither an event, a list nor a mapping.", path, Base._KeyLine(document, "on"))
			ex.add_note(f"Got type '{getFullyQualifiedName(on)}'.")
			raise ex

		parameters: dict[str, list[Parameter]] = {"inputs": [], "outputs": [], "secrets": []}
		if isinstance(on, CommentedMap) and (call := on.get("workflow_call", None)) is not None:
			if not isinstance(call, CommentedMap):
				ex = WorkflowError("Key 'on.workflow_call' is not a mapping.", path, Base._KeyLine(on, "workflow_call"))
				ex.add_note(f"Got type '{getFullyQualifiedName(call)}'.")
				raise ex

			for section, parameterClass in (("inputs", Input), ("outputs", Output), ("secrets", Secret)):
				if (declarations := call.get(section, None)) is None:
					continue
				elif not isinstance(declarations, CommentedMap):
					ex = WorkflowError(f"Key 'on.workflow_call.{section}' is not a mapping.", path, Base._KeyLine(call, section))
					ex.add_note(f"Got type '{getFullyQualifiedName(declarations)}'.")
					raise ex

				parameters[section] = [
					parameterClass._FromYAML(str(name), declaration, path, Base._KeyLine(declarations, name))
					for name, declaration in declarations.items()
				]

		jobs = document["jobs"]
		if not isinstance(jobs, CommentedMap):
			ex = WorkflowError("Key 'jobs' is not a mapping.", path, Base._KeyLine(document, "jobs"))
			ex.add_note(f"Got type '{getFullyQualifiedName(jobs)}'.")
			raise ex

		jobList = []
		for name, job in jobs.items():
			line = Base._KeyLine(jobs, name)
			if not isinstance(job, CommentedMap):
				ex = WorkflowError(f"Job '{name}' is not a mapping.", path, line)
				ex.add_note(f"Got type '{getFullyQualifiedName(job)}'.")
				raise ex

			jobList.append(Job._FromYAML(str(name), job, path, line))

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

		displayName = document.get("name", None)
		return cls(
			path,
			None if displayName is None else str(displayName),
			triggers,
			parameters["inputs"],
			parameters["outputs"],
			parameters["secrets"],
			permissions,
			jobList
		)

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

		:raises WorkflowError: If a job needs a job the workflow doesn't have. |br|
		                       The note lists the workflow's jobs.
		:raises WorkflowError: If the jobs need each other in a cycle.
		"""
		self._ValidateNeeds()
		self._ValidateAcyclic()

	def _ValidateNeeds(self) -> None:
		"""
		Validate that every job names only jobs of the workflow in its ``needs`` key.

		:raises WorkflowError: If a job needs a job the workflow doesn't have. |br|
		                       The note lists the workflow's jobs.
		"""
		for job in self._jobs.values():
			for need in job._needNames:
				if need not in self._jobs:
					ex = WorkflowError(
						f"Job '{job._name}' needs job '{need}', which the workflow doesn't have.", self._path, job._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 WorkflowError: If the jobs need each other in a cycle.
		"""
		# Depth-first search: a job still on the stack when it is reached again closes 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 WorkflowError: 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 WorkflowError(f"Jobs need each other in a cycle: {' -> '.join(cycle)}.", self._path, job._line)

			stack.append(job._name)
			for need in job.Needs:
				visit(need)
			stack.pop()
			finished.add(job._name)

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


@export
class Job(Base[Workflow]):
	"""
	A job of a workflow.

	A job either runs :attr:`Steps` on a runner selected by :attr:`RunsOn`, or calls the reusable workflow named by
	:attr:`Uses`.
	"""

	_PARENT_TYPE: ClassVar[ParentTypes] = Workflow  #: A job is contained in a workflow.

	_name:            str                                          #: Name of the job, the key it is declared under.
	_displayName:     Nullable[str]                                #: Name of the job, as GitHub displays it.
	_needNames:       tuple[str, ...]                              #: Names of the jobs this job needs.
	_condition:       Nullable[str]                                #: Condition under which the job runs.
	_permissions:     Nullable[dict[PermissionScope, Permission]]  #: Permissions the job declares, by scope.
	_runsOn:          tuple[str, ...]                              #: Labels selecting the runner.
	_uses:            Nullable[UsesReference]                      #: The reusable workflow the job calls.
	_with:            dict[str, ValueT]                            #: Inputs passed to the called workflow, by name.
	_secrets:         dict[str, str]                               #: Secrets passed to the called workflow, by name.
	_inheritsSecrets: bool                                         #: ``True``, if secrets are inherited.
	_matrix:          Nullable[Matrix]                             #: The job's matrix.
	_steps:           list[Step]                                   #: Steps of the job.
	_outputs:         dict[str, str]                               #: Outputs of the job, by name.
	_container:       Nullable[str]                                #: Image of the container the job's steps run in.
	_services:        dict[str, str]                               #: Images of the service containers, by service name.

	def __init__(
		self,
		name:            str,
		line:            int,
		displayName:     Nullable[str]                  = None,
		needs:           Nullable[Iterable[str]]        = None,
		condition:       Nullable[str]                  = None,
		runsOn:          Nullable[Iterable[str]]        = None,
		container:       Nullable[str]                  = None,
		services:        Nullable[Mapping[str, str]]    = None,
		uses:            Nullable[UsesReference]        = None,
		withInputs:      Nullable[Mapping[str, ValueT]] = None,
		secrets:         Nullable[Mapping[str, str]]    = None,
		inheritsSecrets: bool                           = False,
		outputs:         Nullable[Mapping[str, str]]    = None,
		permissions:     Nullable[Iterable[Permission]] = None,
		matrix:          Nullable[Matrix]               = None,
		steps:           Nullable[Iterable[Step]]       = None,
		*,
		parent:          Nullable[Workflow]             = None
	) -> None:
		"""
		Initializes a job of a workflow.

		The reusable workflow a job calls, its permissions, its matrix and its steps are attached by passing them, or by
		constructing a :class:`UsesReference`, :class:`Permission`, :class:`Matrix` or :class:`Step` 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 displayName:     Optional, name of the job, as GitHub displays it. Default: ``None``.
		:param needs:           Optional, names of the jobs this job needs. Default: ``None``.
		:param condition:       Optional, condition under which the job runs. Default: ``None``.
		:param runsOn:          Optional, labels selecting the runner. Default: ``None``.
		:param container:       Optional, image of the container the job's steps run in. Default: ``None``.
		:param services:        Optional, images of the service containers, by service name. Default: ``None``.
		:param uses:            Optional, the reusable workflow the job calls, which is attached to the job. Default:
		                        ``None``.
		:param withInputs:      Optional, inputs passed to the called workflow, by name. Default: ``None``.
		:param secrets:         Optional, secrets passed to the called workflow, by name. Default: ``None``.
		:param inheritsSecrets: Optional, ``True``, if the called workflow inherits every secret. Default: ``False``.
		:param outputs:         Optional, outputs of the job, by name. Default: ``None``.
		:param permissions:     Optional, permissions the job declares, which are attached to the job. Default: ``None``,
		                        for a job without a ``permissions`` key.
		:param matrix:          Optional, the job's matrix, which is attached to the job. Default: ``None``.
		:param steps:           Optional, the job's steps, which are attached to the job. Default: ``None``.
		:param parent:          Optional, reference to the workflow containing 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 'displayName' is not of type :class:`str`.
		:raises TypeError:      If parameter 'condition' is not of type :class:`str`.
		:raises TypeError:      If parameter 'container' is not of type :class:`str`.
		:raises TypeError:      If an element of parameter 'needs' is not of type :class:`str`.
		:raises TypeError:      If an element of parameter 'runsOn' is not of type :class:`str`.
		:raises TypeError:      If parameter 'uses' is not of type :class:`UsesReference`.
		:raises TypeError:      If parameter 'inheritsSecrets' is not of type :class:`bool`.
		:raises TypeError:      If an element of parameter 'permissions' is not of type :class:`Permission`.
		:raises TypeError:      If parameter 'matrix' is not of type :class:`Matrix`.
		:raises TypeError:      If an element of parameter 'steps' is not of type :class:`Step`.
		"""
		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, value in (
			("displayName", displayName),
			("condition",   condition),
			("container",   container)
		):
			if value is not None and not isinstance(value, str):
				ex = TypeError(f"Parameter '{parameterName}' is not of type 'str'.")
				ex.add_note(f"Got type '{getFullyQualifiedName(value)}'.")
				raise ex

		self._needNames = () if needs is None else tuple(needs)
		self._runsOn =    () if runsOn is None else tuple(runsOn)
		for parameterName, values in (("needs", self._needNames), ("runsOn", self._runsOn)):
			for value in values:
				if not isinstance(value, str):
					ex = TypeError(f"An element of parameter '{parameterName}' is not of type 'str'.")
					ex.add_note(f"Got type '{getFullyQualifiedName(value)}'.")
					raise ex

		for parameterName, value, valueClass in (
			("uses",   uses,   UsesReference),
			("matrix", matrix, Matrix)
		):
			if value is not None and not isinstance(value, valueClass):
				ex = TypeError(f"Parameter '{parameterName}' is not of type '{valueClass.__name__}'.")
				ex.add_note(f"Got type '{getFullyQualifiedName(value)}'.")
				raise ex

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

		self._name =            name
		self._displayName =     displayName
		self._condition =       condition
		self._permissions =     None
		self._uses =            uses
		self._with =            {} if withInputs is None else dict(withInputs)
		self._secrets =         {} if secrets is None else dict(secrets)
		self._inheritsSecrets = inheritsSecrets
		self._matrix =          matrix
		self._steps =           []
		self._outputs =         {} if outputs is None else dict(outputs)
		self._container =       container
		self._services =        {} if services is None else dict(services)

		if uses is not None:
			uses.Parent = self

		if matrix is not None:
			matrix.Parent = self

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

				self._permissions[permission._scope] = permission
				permission.Parent = self

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

				self._steps.append(step)
				step.Parent = self

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

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

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

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

		for step in self._steps:
			step.Parent = self

		if self._permissions is not None:
			for permission in self._permissions.values():
				permission.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 DisplayName(self) -> Nullable[str]:
		"""
		Read-only property to access the job's name, as GitHub displays it (:attr:`_displayName`).

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

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

		:returns: The names, in the order the ``needs`` key lists them.
		"""
		return self._needNames

	@readonly
	def Needs(self) -> tuple[Job, ...]:
		"""
		Read-only property to return the jobs this job needs.

		The names in :attr:`NeedNames` are looked up in the workflow containing the job. :meth:`Workflow.FromFile`
		rejects a name naming no job, so for a workflow read from a file every name is resolved.

		:returns: The jobs, in the order the ``needs`` key lists them, skipping names naming no job of the workflow.
		"""
		if self._workflow is None:
			return ()

		jobs = self._workflow._jobs
		return tuple(jobs[name] for name in self._needNames if name in jobs)

	@readonly
	def Condition(self) -> Nullable[str]:
		"""
		Read-only property to access the condition under which the job runs (:attr:`_condition`).

		The expression is not evaluated.

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

	@readonly
	def Permissions(self) -> Nullable[dict[PermissionScope, Permission]]:
		"""
		Read-only property to access the permissions the job declares (:attr:`_permissions`).

		:returns: The permissions, by scope, or ``None`` if the job has no ``permissions`` key and inherits them.
		"""
		return self._permissions

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

		:returns: The labels, as written - an expression is not evaluated -, or ``()`` for a job calling a workflow.
		"""
		return self._runsOn

	@readonly
	def Uses(self) -> Nullable[UsesReference]:
		"""
		Read-only property to access the reusable workflow the job calls (:attr:`_uses`).

		:returns: The reference, or ``None`` for a job running steps.
		"""
		return self._uses

	@readonly
	def With(self) -> dict[str, ValueT]:
		"""
		Read-only property to access the inputs passed to the called workflow (:attr:`_with`).

		:returns: The inputs, by name.
		"""
		return self._with

	@readonly
	def Secrets(self) -> dict[str, str]:
		"""
		Read-only property to access the secrets passed to the called workflow (:attr:`_secrets`).

		:returns: The secrets, by name, or an empty dictionary if the job passes none or :attr:`InheritsSecrets`.
		"""
		return self._secrets

	@readonly
	def InheritsSecrets(self) -> bool:
		"""
		Read-only property to access whether the called workflow inherits every secret (:attr:`_inheritsSecrets`).

		:returns: ``True``, if the job says ``secrets: inherit``.
		"""
		return self._inheritsSecrets

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

		:returns: The matrix, or ``None`` if the job has no ``strategy.matrix``.
		"""
		return self._matrix

	@readonly
	def Steps(self) -> list[Step]:
		"""
		Read-only property to access the job's steps (:attr:`_steps`).

		:returns: The steps, in file order, or an empty list for a job calling a workflow.
		"""
		return self._steps

	@readonly
	def Outputs(self) -> dict[str, str]:
		"""
		Read-only property to access the job's outputs (:attr:`_outputs`).

		:returns: The expressions the outputs are taken from, by name.
		"""
		return self._outputs

	@readonly
	def Container(self) -> Nullable[str]:
		"""
		Read-only property to access the image of the container the job's steps run in (:attr:`_container`).

		:returns: The image, as written - e.g. ``pytooling/miktex:sphinx`` or an expression -, or ``None`` if the job has no
		          ``container``.
		"""
		return self._container

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

		:returns: The images, as written, by service name.
		"""
		return self._services

	@readonly
	def StepCount(self) -> int:
		"""
		Read-only property to return the number of steps of the job.

		:returns: Number of steps.
		"""
		return len(self._steps)

	def IterateSteps(self) -> Iterator[Step]:
		"""
		Iterate the job's steps.

		:returns: An iterator over the steps, in file order.
		"""
		return iter(self._steps)

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

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

	@classmethod
	def _FromYAML(cls, name: str, mapping: CommentedMap, path: Path, line: int) -> Self:
		"""
		Build a job and the elements it contains from its mapping in the workflow file.

		:param name:           Name of the job.
		:param mapping:        The job's mapping.
		:param path:           Path to the workflow file.
		:param line:           Line the job's name is written at, starting at 1.
		:returns:              The job.
		:raises WorkflowError: If the job has neither ``runs-on`` nor ``uses``, or both.
		:raises WorkflowError: If a key of the job holds a value of the wrong kind.
		"""
		if ("runs-on" in mapping) == ("uses" in mapping):
			raise WorkflowError(f"Job '{name}' needs either 'runs-on' or 'uses'.", path, line)

		needs = mapping.get("needs", ())
		if isinstance(needs, str):
			needs = (needs, )
		elif not isinstance(needs, (list, tuple)):
			ex = WorkflowError(
				f"Key 'needs' of job '{name}' is neither a job name nor a list.", path, Base._KeyLine(mapping, "needs")
			)
			ex.add_note(f"Got type '{getFullyQualifiedName(needs)}'.")
			raise ex

		runsOn = mapping.get("runs-on", ())
		if isinstance(runsOn, dict):
			runsOn = runsOn.get("labels", ())

		if isinstance(runsOn, str):
			runsOn = (runsOn, )

		condition = mapping.get("if", None)

		secrets = mapping.get("secrets", None)
		inheritsSecrets = secrets == "inherit"
		if inheritsSecrets:
			secrets = None
		elif secrets is not None:
			if not isinstance(secrets, CommentedMap):
				ex = WorkflowError(f"Key 'secrets' of job '{name}' is not a mapping.", path, Base._KeyLine(mapping, "secrets"))
				ex.add_note(f"Got type '{getFullyQualifiedName(secrets)}'.")
				raise ex

			secrets = {str(key): str(value) for key, value in secrets.items()}

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

			outputs = {str(key): str(value) for key, value in outputs.items()}

		if (withValues := mapping.get("with", None)) is not None:
			if not isinstance(withValues, CommentedMap):
				ex = WorkflowError(f"Key 'with' of job '{name}' is not a mapping.", path, Base._KeyLine(mapping, "with"))
				ex.add_note(f"Got type '{getFullyQualifiedName(withValues)}'.")
				raise ex

			withValues = Base._ToPython(withValues)

		uses = None
		if "uses" in mapping:
			uses = UsesReference._FromYAML(mapping, f"job '{name}'", path)

		permissions = None
		if "permissions" in mapping:
			permissions = Permission._FromYAML(mapping["permissions"], path, Base._KeyLine(mapping, "permissions"))

		matrix = None
		if (strategy := mapping.get("strategy", None)) is not None:
			if not isinstance(strategy, CommentedMap):
				ex = WorkflowError(
					f"Key 'strategy' of job '{name}' is not a mapping.", path, Base._KeyLine(mapping, "strategy")
				)
				ex.add_note(f"Got type '{getFullyQualifiedName(strategy)}'.")
				raise ex

			if "matrix" in strategy:
				matrix = Matrix._FromYAML(strategy["matrix"], path, Base._KeyLine(strategy, "matrix"))

		container = mapping.get("container", None)
		if isinstance(container, CommentedMap):
			container = container.get("image", None)

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

			services = {}
			for serviceName, service in serviceMap.items():
				if isinstance(service, CommentedMap):
					service = service.get("image", None)

				if service is not None:
					services[str(serviceName)] = str(service)

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

			steps = [
				Step._FromYAML(step, position, f"job '{name}'", path, stepList.lc.item(position)[0] + 1)
				for position, step in enumerate(stepList)
			]

		displayName = mapping.get("name", None)

		return cls(
			name, line,
			displayName=None if displayName is None else str(displayName),
			needs=(str(need) for need in needs),
			condition=None if condition is None else str(condition),
			runsOn=(str(label) for label in runsOn),
			container=None if container is None else str(container),
			services=services,
			uses=uses,
			withInputs=withValues,
			secrets=secrets,
			inheritsSecrets=inheritsSecrets,
			outputs=outputs,
			permissions=permissions,
			matrix=matrix,
			steps=steps
		)


@export
class Action(Base[None]):
	"""
	An action's file, ``action.yml``.

	The action is named by its directory - ``ComputeRequirements`` for ``.github/actions/ComputeRequirements/action.yml``
	- because that is how a step names it in ``uses``; the ``name`` key is kept as :attr:`DisplayName`. Of a composite
	action, the steps are read, so the actions it runs in turn are known.
	"""

	_path:        Path           #: Path to the action's file.
	_name:        str            #: Name of the action, its directory's name.
	_displayName: Nullable[str]  #: Name of the action, as GitHub displays it.
	_using:       str            #: How the action runs, as ``composite``, ``docker`` or ``node24``.
	_image:       Nullable[str]  #: The image a Docker action runs, as ``Dockerfile`` or ``docker://alpine:3.22``.
	_steps:       list[Step]     #: Steps of a composite action.

	def __init__(
		self,
		path:        Path,
		using:       str,
		displayName: Nullable[str]            = None,
		image:       Nullable[str]            = None,
		steps:       Nullable[Iterable[Step]] = None
	) -> None:
		"""
		Initializes an action.

		The steps of a composite action are attached by passing them, or by constructing them with the action as parent.
		Use :meth:`FromFile` to read an action's file.

		:param path:        Path to the action's file.
		:param using:       How the action runs, as ``composite``.
		:param displayName: Optional, name of the action, as GitHub displays it. Default: ``None``.
		:param image:       Optional, the image a Docker action runs. Default: ``None``.
		:param steps:       Optional, the steps of a composite action, which are attached to the action. Default:
		                    ``None``.
		:raises ValueError: If parameter 'path' is ``None``.
		:raises TypeError:  If parameter 'path' is not of type :class:`~pathlib.Path`.
		:raises ValueError: If parameter 'using' is ``None``.
		:raises TypeError:  If parameter 'using' is not of type :class:`str`.
		:raises TypeError:  If parameter 'displayName' is not of type :class:`str`.
		:raises TypeError:  If parameter 'image' is not of type :class:`str`.
		:raises TypeError:  If an element of parameter 'steps' is not of type :class:`Step`.
		"""
		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 using is None:
			raise ValueError("Parameter 'using' is None.")

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

		self._file =        path
		self._path =        path
		self._name =        path.parent.name
		self._displayName = displayName
		self._using =       using
		self._image =       image
		self._steps =       []

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

				self._steps.append(step)
				step.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 action's file (:attr:`_path`).

		:returns: Path to the action's file.
		"""
		return self._path

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

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

	@readonly
	def DisplayName(self) -> Nullable[str]:
		"""
		Read-only property to access the action's name, as GitHub displays it (:attr:`_displayName`).

		:returns: The ``name`` key, or ``None`` if the file has none.
		"""
		return self._displayName

	@readonly
	def Using(self) -> str:
		"""
		Read-only property to access how the action runs (:attr:`_using`).

		:returns: The ``runs.using`` key, as ``composite``, ``docker`` or ``node24``.
		"""
		return self._using

	@readonly
	def IsComposite(self) -> bool:
		"""
		Read-only property to return whether the action is a composite action, running steps.

		:returns: ``True``, if ``runs.using`` is ``composite``.
		"""
		return self._using == "composite"

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

		:returns: The ``runs.image`` key, as ``Dockerfile`` or ``docker://alpine:3.22``, or ``None`` for another action.
		"""
		return self._image

	@readonly
	def Steps(self) -> list[Step]:
		"""
		Read-only property to access the steps of a composite action (:attr:`_steps`).

		:returns: The steps, in file order, or an empty list for another action.
		"""
		return self._steps

	def IterateActions(self) -> Iterator[UsesReference]:
		"""
		Iterate the actions the steps of a composite action run.

		:returns: An iterator over the actions, in file order.
		"""
		for step in self._steps:
			if step._uses is not None:
				yield step._uses

	@readonly
	def StepCount(self) -> int:
		"""
		Read-only property to return the number of steps of the action.

		:returns: Number of steps.
		"""
		return len(self._steps)

	def IterateSteps(self) -> Iterator[Step]:
		"""
		Iterate the action's steps.

		:returns: An iterator over the steps, in file order.
		"""
		return iter(self._steps)

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

		:returns: Name of the action, its directory's name.
		"""
		return self._name

	@classmethod
	def FromFile(cls, path: Path) -> Self:
		"""
		Read an action's file.

		:param path:           Path to the action's file.
		:returns:              The action, with the steps of a composite action attached.
		:raises ValueError:    If parameter 'path' is ``None``.
		:raises TypeError:     If parameter 'path' is not of type :class:`~pathlib.Path`.
		:raises WorkflowError: If the file doesn't exist.
		:raises WorkflowError: If the file can't be read.
		:raises WorkflowError: If the file is not a YAML document.
		:raises WorkflowError: If the document is not a mapping, or has no ``runs`` key.
		:raises WorkflowError: If ``runs`` is not a mapping or has no ``using`` key, or a step is malformed.
		"""
		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
		elif not path.exists():
			raise WorkflowError("Action file doesn't exist.", path) from FileNotFoundError(path)

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

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

		if document is None:
			raise WorkflowError("Action file is empty.", path)
		elif not isinstance(document, CommentedMap):
			ex = WorkflowError("Action file is not a mapping.", path, 1)
			ex.add_note(f"Got type '{getFullyQualifiedName(document)}'.")
			raise ex
		elif "runs" not in document:
			raise WorkflowError("Action file has no 'runs' key.", path)

		return cls._Parse(document, path)

	@classmethod
	def _Parse(cls, document: CommentedMap, path: Path) -> Self:
		"""
		Build an action and the steps it contains from the document read from its file.

		:param document:       The document, a mapping with a ``runs`` key.
		:param path:           Path to the action's file.
		:returns:              The action, with the steps of a composite action attached.
		:raises WorkflowError: If key ``runs`` is not a mapping, or has no ``using`` key.
		:raises WorkflowError: If key ``runs.steps`` is not a list, or a step is malformed.
		"""
		runs = document["runs"]
		if not isinstance(runs, CommentedMap):
			ex = WorkflowError("Key 'runs' is not a mapping.", path, Base._KeyLine(document, "runs"))
			ex.add_note(f"Got type '{getFullyQualifiedName(runs)}'.")
			raise ex
		elif "using" not in runs:
			raise WorkflowError("Key 'runs' has no 'using' key.", path, Base._KeyLine(document, "runs"))

		steps = None
		if (stepList := runs.get("steps", None)) is not None:
			if not isinstance(stepList, CommentedSeq):
				ex = WorkflowError("Key 'runs.steps' is not a list.", path, Base._KeyLine(runs, "steps"))
				ex.add_note(f"Got type '{getFullyQualifiedName(stepList)}'.")
				raise ex

			steps = [
				Step._FromYAML(step, position, f"action '{path.parent.name}'", path, stepList.lc.item(position)[0] + 1)
				for position, step in enumerate(stepList)
			]

		displayName = document.get("name", None)
		image = runs.get("image", None)
		return cls(
			path,
			str(runs["using"]),
			displayName=None if displayName is None else str(displayName),
			image=None if image is None else str(image),
			steps=steps
		)


@export
class Step(Base[Union[Job, Action]]):
	"""A step of a job or of a composite action."""

	_PARENT_TYPE: ClassVar[ParentTypes] = (Job, Action)  #: A step is contained in a job or an action.

	_name:       Nullable[str]            #: Name of the step.
	_identifier: Nullable[str]            #: Identifier of the step, as referenced by ``steps.<id>``.
	_condition:  Nullable[str]            #: Condition under which the step runs.
	_uses:       Nullable[UsesReference]  #: The action the step runs.
	_run:        Nullable[str]            #: The script the step runs.

	def __init__(
		self,
		line:       int,
		name:       Nullable[str]                = None,
		identifier: Nullable[str]                = None,
		condition:  Nullable[str]                = None,
		run:        Nullable[str]                = None,
		uses:       Nullable[UsesReference]      = None,
		*,
		parent:     Nullable[Union[Job, Action]] = None
	) -> None:
		"""
		Initializes a step of a job or of a composite action.

		The action a step runs is attached by passing it, or by constructing a :class:`UsesReference` with the step as
		parent.

		:param line:       Line the step starts at, starting at 1.
		:param name:       Optional, name of the step. Default: ``None``.
		:param identifier: Optional, identifier of the step. Default: ``None``.
		:param condition:  Optional, condition under which the step runs. Default: ``None``.
		:param run:        Optional, the script the step runs. Default: ``None``.
		:param uses:       Optional, the action the step runs, which is attached to the step. Default: ``None``.
		:param parent:     Optional, reference to the job or the composite action containing the step, which the step is
		                   attached to. Default: ``None``.
		:raises TypeError: If parameter 'name' is not of type :class:`str`.
		:raises TypeError: If parameter 'identifier' is not of type :class:`str`.
		:raises TypeError: If parameter 'condition' is not of type :class:`str`.
		:raises TypeError: If parameter 'run' is not of type :class:`str`.
		:raises TypeError: If parameter 'uses' is not of type :class:`UsesReference`.
		"""
		super().__init__(line, parent=parent)

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

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

		self._name =       name
		self._identifier = identifier
		self._condition =  condition
		self._uses =       uses
		self._run =        run

		if uses is not None:
			uses.Parent = self

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

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

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

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

		:returns: Name of the step, or ``None`` if the workflow gives none.
		"""
		return self._name

	@readonly
	def ID(self) -> Nullable[str]:
		"""
		Read-only property to access the step's identifier (:attr:`_identifier`).

		:returns: Identifier of the step, or ``None`` if the workflow gives none.
		"""
		return self._identifier

	@readonly
	def Condition(self) -> Nullable[str]:
		"""
		Read-only property to access the condition under which the step runs (:attr:`_condition`).

		:returns: The ``if`` expression, as written, or ``None`` if the step always runs.
		"""
		return self._condition

	@readonly
	def Uses(self) -> Nullable[UsesReference]:
		"""
		Read-only property to access the action the step runs (:attr:`_uses`).

		:returns: The action, or ``None`` for a step running a script.
		"""
		return self._uses

	@readonly
	def Run(self) -> Nullable[str]:
		"""
		Read-only property to access the script the step runs (:attr:`_run`).

		:returns: The script, or ``None`` for a step running an action.
		"""
		return self._run

	@classmethod
	def _FromYAML(cls, mapping: Any, position: int, what: str, path: Path, line: int) -> Self:
		"""
		Read a step from the ``steps`` list of a job or of a composite action.

		:param mapping:        The step's mapping.
		:param position:       Position of the step in its list, starting at 0.
		:param what:           The job or action containing the step, for the exception's message, as ``job 'Build'`` or
		                       ``action 'Setup'``.
		:param path:           Path to the file, for a message.
		:param line:           Line the step starts at, starting at 1.
		:returns:              The step.
		:raises WorkflowError: If the step is not a mapping.
		:raises WorkflowError: If the step's ``uses`` is not a reference.
		"""
		if not isinstance(mapping, CommentedMap):
			ex = WorkflowError(f"Step {position + 1} of {what} is not a mapping.", path, line)
			ex.add_note(f"Got type '{getFullyQualifiedName(mapping)}'.")
			raise ex

		name =       mapping.get("name", None)
		identifier = mapping.get("id", None)
		condition =  mapping.get("if", None)
		run =        mapping.get("run", None)
		uses =       None
		if "uses" in mapping:
			uses = UsesReference._FromYAML(mapping, f"step {position + 1} of {what}", path)

		return cls(
			line,
			name=None if name is None else str(name),
			identifier=None if identifier is None else str(identifier),
			condition=None if condition is None else str(condition),
			run=None if run is None else str(run),
			uses=uses
		)


@export
class Matrix(Base[Job]):
	"""
	The ``strategy.matrix`` of a job.

	A matrix is *dynamic*, if a part of it is an expression - as ``include: ${{ fromJson(inputs.jobs) }}`` - because
	its instances are then known at run time only.
	"""

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

	_dimensions: dict[str, ValueT]  #: The dimensions, by name.
	_include:    ValueT             #: The combinations added, or an expression producing them.
	_exclude:    ValueT             #: The combinations removed, or an expression producing them.
	_expression: Nullable[str]      #: The expression the whole matrix is taken from.

	def __init__(
		self,
		line:       int,
		dimensions: Nullable[Mapping[str, ValueT]] = None,
		include:    ValueT                         = None,
		exclude:    ValueT                         = None,
		expression: Nullable[str]                  = None,
		*,
		parent:     Nullable[Job]                  = None
	) -> None:
		"""
		Initializes a job's matrix.

		:param line:       Line the ``matrix`` key is written at, starting at 1.
		:param dimensions: Optional, the dimensions, by name; a dimension's value is a list or an expression.
		                   Default: ``None``.
		:param include:    Optional, the combinations added, or an expression producing them. Default: ``None``.
		:param exclude:    Optional, the combinations removed, or an expression producing them. Default: ``None``.
		:param expression: Optional, the expression the whole matrix is taken from. Default: ``None``.
		:param parent:     Optional, reference to the job the matrix belongs to, which the matrix is attached to.
		                   Default: ``None``.
		:raises TypeError: If parameter 'dimensions' is not a mapping.
		:raises TypeError: If parameter 'expression' is not of type :class:`str`.
		"""
		super().__init__(line, parent=parent)

		if dimensions is not None and not isinstance(dimensions, Mapping):
			ex = TypeError("Parameter 'dimensions' is not a mapping.")
			ex.add_note(f"Got type '{getFullyQualifiedName(dimensions)}'.")
			raise ex

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

		self._dimensions = {} if dimensions is None else dict(dimensions)
		self._include =    include
		self._exclude =    exclude
		self._expression = expression

		if parent is not None:
			parent._matrix = self

	@readonly
	def Dimensions(self) -> dict[str, ValueT]:
		"""
		Read-only property to access the matrix' dimensions (:attr:`_dimensions`).

		:returns: The dimensions, by name; a dimension's value is a list, or an expression producing one.
		"""
		return self._dimensions

	@readonly
	def Include(self) -> ValueT:
		"""
		Read-only property to access the combinations added to the matrix (:attr:`_include`).

		:returns: A list of combinations, an expression producing them, or ``None`` if the matrix has no ``include``.
		"""
		return self._include

	@readonly
	def Exclude(self) -> ValueT:
		"""
		Read-only property to access the combinations removed from the matrix (:attr:`_exclude`).

		:returns: A list of combinations, an expression producing them, or ``None`` if the matrix has no ``exclude``.
		"""
		return self._exclude

	@readonly
	def Expression(self) -> Nullable[str]:
		"""
		Read-only property to access the expression the whole matrix is taken from (:attr:`_expression`).

		:returns: The expression, as ``${{ fromJson(needs.Params.outputs.matrix) }}``, or ``None`` if the matrix is a
		          mapping.
		"""
		return self._expression

	@readonly
	def IsDynamic(self) -> bool:
		"""
		Read-only property to return whether the matrix' instances are known at run time only.

		:returns: ``True``, if the matrix, its ``include``, its ``exclude`` or one of its dimensions is an expression.
		"""
		return (
			self._expression is not None or isinstance(self._include, str) or isinstance(self._exclude, str) or
			any(isinstance(value, str) for value in self._dimensions.values())
		)

	@readonly
	def Combinations(self) -> list[dict[str, ValueT]]:
		"""
		Read-only property to return the combinations the matrix produces, as GitHub computes them.

		The dimensions are combined in the order they are written, the last one varying fastest. Then ``exclude``
		removes every combination matching all key-value pairs of an entry, and ``include`` extends every remaining
		combination whose dimension values the entry doesn't change - its other keys, and those an earlier entry
		added, it may change. An entry extending no combination is a combination of its own.

		:returns:              The combinations, each a mapping of the dimensions' and included keys' names to values.
		:raises WorkflowError: If the matrix is dynamic, so its combinations are known at run time only.
		:raises WorkflowError: If ``include`` or ``exclude`` is not a list of mappings.
		"""
		path = self._file
		if self.IsDynamic:
			raise WorkflowError("Matrix is dynamic; its combinations are known at run time only.", path, self._line)

		for key, entries in (
			("include", self._include),
			("exclude", self._exclude)
		):
			if entries is not None and (
				not isinstance(entries, list) or not all(isinstance(entry, dict) for entry in entries)
			):
				raise WorkflowError(f"Key '{key}' of the matrix is not a list of mappings.", path, self._line)

		combinations = []
		if len(self._dimensions) > 0:
			dimensions = {name: value if isinstance(value, list) else [value] for name, value in self._dimensions.items()}
			combinations = [dict(zip(dimensions, values)) for values in product(*dimensions.values())]

		if self._exclude is not None:
			for entry in self._exclude:
				combinations = [
					combination for combination in combinations
					if not all(combination.get(key, None) == value for key, value in entry.items())
				]

		if self._include is None:
			return combinations

		originals = [dict(combination) for combination in combinations]
		for entry in self._include:
			extended = False
			for combination, original in zip(combinations, originals):
				if all(original[key] == value for key, value in entry.items() if key in original):
					combination.update(entry)
					extended = True

			if not extended:
				combinations.append(dict(entry))

		return combinations

	@staticmethod
	def _FormatCombination(combination: Mapping[str, ValueT]) -> dict[str, str]:
		"""
		Format the values of a matrix' combination as GitHub prints them in the name of a matrix instance.

		A string is printed as it is, any other value as JSON: ``true``, ``3``, ``{"os": "ubuntu"}``.

		:param combination: The combination, as :attr:`Matrix.Combinations` returns it.
		:returns:           The combination's names and formatted values, in the combination's order.
		"""
		return {
			name: value if isinstance(value, str) else json_dumps(value, separators=(", ", ": "))
			for name, value in combination.items()
		}

	@classmethod
	def _FromYAML(cls, value: Any, path: Path, line: int) -> Self:
		"""
		Read the value of a job's ``strategy.matrix`` key.

		:param value:          The value of the ``matrix`` key: a mapping, or an expression.
		:param path:           Path to the workflow file.
		:param line:           Line the key is written at, starting at 1.
		:returns:              The matrix.
		:raises WorkflowError: If the value is neither a mapping nor an expression.
		"""
		if isinstance(value, str):
			return cls(line, expression=str(value))
		elif not isinstance(value, CommentedMap):
			ex = WorkflowError("Key 'strategy.matrix' is not a mapping.", path, line)
			ex.add_note(f"Got type '{getFullyQualifiedName(value)}'.")
			raise ex

		return cls(
			line,
			dimensions={key: Base._ToPython(item) for key, item in value.items() if key not in ("include", "exclude")},
			include=Base._ToPython(value.get("include", None)),
			exclude=Base._ToPython(value.get("exclude", None))
		)


@export
class UsesReference(Base[Union[Job, Step]]):
	"""
	The value of a ``uses`` key: a reusable workflow called by a job, or an action run by a step.

	The forms GitHub accepts are read into their parts:

	.. code-block:: text

	   pyTooling/Actions/.github/workflows/Package.yml@r8   repository, path and ref
	   actions/checkout@v6                                   an action in a repository's root
	   ./.github/workflows/Package.yml                       a file of the same repository and commit
	   docker://alpine:3.22                                  a Docker image
	"""

	_PARENT_TYPE: ClassVar[ParentTypes] = (Job, Step)  #: A reference is contained in a job or a step.

	_rawReference: str            #: The reference, as written.
	_repository:   Nullable[str]  #: The repository, as ``owner/repo``.
	_path:         str            #: The path within the repository.
	_reference:    Nullable[str]  #: The branch, tag or commit.
	_isLocal:      bool           #: ``True``, if the reference names a file of the same repository.
	_isDocker:     bool           #: ``True``, if the reference names a Docker image.

	def __init__(self, rawReference: str, line: int, *, parent: Nullable[Union[Job, Step]] = None) -> None:
		"""
		Initializes a ``uses`` reference by reading it into its parts.

		:param rawReference: The reference, as written.
		:param line:         Line the reference is written at, starting at 1.
		:param parent:       Optional, reference to the job or step containing it, which the reference is attached to.
		                     Default: ``None``.
		:raises ValueError:  If parameter 'rawReference' is ``None``.
		:raises TypeError:   If parameter 'rawReference' is not of type :class:`str`.
		:raises ValueError:  If parameter 'rawReference' is empty.
		:raises ValueError:  If parameter 'rawReference' names a repository without a ref.
		:raises ValueError:  If parameter 'rawReference' names no repository as ``owner/repo``.
		"""
		super().__init__(line, parent=parent)

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

		self._rawReference = rawReference
		self._isLocal =      False
		self._isDocker =     False
		self._repository =   None
		self._reference =    None

		if rawReference.startswith("docker://"):
			self._isDocker = True
			self._path =     rawReference[len("docker://"):]
		elif rawReference.startswith("./"):
			self._isLocal = True
			self._path =    rawReference[len("./"):]
		else:
			location, separator, reference = rawReference.partition("@")
			if separator == "" or reference == "":
				ex = ValueError("Parameter 'rawReference' names a repository without a ref.")
				ex.add_note(f"Got '{rawReference}'.")
				raise ex

			owner, _, remainder = location.partition("/")
			repository, _, path = remainder.partition("/")
			if owner == "" or repository == "":
				ex = ValueError("Parameter 'rawReference' names no repository as 'owner/repo'.")
				ex.add_note(f"Got '{rawReference}'.")
				raise ex

			self._repository = f"{owner}/{repository}"
			self._path =       path
			self._reference =  reference

		if parent is not None:
			parent._uses = self

	@readonly
	def Repository(self) -> Nullable[str]:
		"""
		Read-only property to access the repository (:attr:`_repository`).

		:returns: The repository, as ``owner/repo``, or ``None`` for a local reference and a Docker image.
		"""
		return self._repository

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

		:returns: The path, as ``.github/workflows/Package.yml``, without the leading ``./`` of a local reference. It
		          is empty for an action in a repository's root, and the image for a Docker image.
		"""
		return self._path

	@readonly
	def Reference(self) -> Nullable[str]:
		"""
		Read-only property to access the branch, tag or commit (:attr:`_reference`).

		:returns: The branch, tag or commit, as ``r8``, or ``None`` for a local reference and a Docker image.
		"""
		return self._reference

	@readonly
	def IsLocal(self) -> bool:
		"""
		Read-only property to access whether the reference names a file of the same repository (:attr:`_isLocal`).

		:returns: ``True``, if the reference starts with ``./``.
		"""
		return self._isLocal

	@readonly
	def IsDocker(self) -> bool:
		"""
		Read-only property to access whether the reference names a Docker image (:attr:`_isDocker`).

		:returns: ``True``, if the reference starts with ``docker://``.
		"""
		return self._isDocker

	@readonly
	def IsWorkflow(self) -> bool:
		"""
		Read-only property to return whether the reference names a reusable workflow rather than an action.

		:returns: ``True``, if the path names a ``.yml`` or ``.yaml`` file in ``.github/workflows``.
		"""
		path = PurePosixPath(self._path)
		return (
			not self._isDocker and path.parent == PurePosixPath(".github/workflows") and path.suffix in (".yml", ".yaml")
		)

	@readonly
	def FileName(self) -> str:
		"""
		Read-only property to return the last element of the path.

		:returns: The file name, as ``Package.yml`` for a reusable workflow, or ``""`` for an action in a repository's
		          root.
		"""
		return PurePosixPath(self._path).name if not self._isDocker else ""

	@readonly
	def Stem(self) -> str:
		"""
		Read-only property to return the file name without its extension.

		For a reusable workflow, it is the name :class:`Workflow` gives the file it reads, e.g. ``Package``.

		:returns: The file name without its extension, or ``""`` for an action in a repository's root.
		"""
		return PurePosixPath(self._path).stem if not self._isDocker else ""

	def __str__(self) -> str:
		"""
		Return the reference, as written.

		:returns: The reference.
		"""
		return self._rawReference

	@classmethod
	def _FromYAML(cls, mapping: CommentedMap, what: str, path: Path) -> Self:
		"""
		Read the ``uses`` key of a job or step.

		:param mapping:        The mapping of the job or step, which has a ``uses`` key.
		:param what:           The job or step, for the exception's message, as ``job 'Build'``.
		:param path:           Path to the workflow file.
		:returns:              The reference.
		:raises WorkflowError: If the value is not a reference.
		"""
		line = Base._KeyLine(mapping, "uses")
		try:
			return cls(str(mapping["uses"]), line)
		except ValueError as cause:
			raise WorkflowError(f"Key 'uses' of {what} is not a reference.", path, line) from cause


@export
class Permission(Base[Union[Workflow, Job]]):
	"""
	A permission a workflow or job declares for the ``GITHUB_TOKEN``, as ``contents: write``.

	The short forms ``read-all`` and ``write-all`` are read as one permission of scope :attr:`PermissionScope.All`.
	"""

	_PARENT_TYPE: ClassVar[ParentTypes] = (Workflow, Job)  #: A permission is declared by a workflow or a job.

	_scope: PermissionScope  #: The scope, as ``contents``.
	_level: AccessLevel      #: The access granted.

	def __init__(
		self,
		scope:  PermissionScope,
		level:  AccessLevel,
		line:   int,
		*,
		parent: Nullable[Union[Workflow, Job]] = None
	) -> None:
		"""
		Initializes a permission.

		:param scope:       The scope, as ``contents``.
		:param level:       The access granted.
		:param line:        Line the permission is written at, starting at 1.
		:param parent:      Optional, reference to the workflow or job declaring it, which the permission is attached to.
		                    Default: ``None``.
		:raises ValueError: If parameter 'scope' is ``None``.
		:raises TypeError:  If parameter 'scope' is not of type :class:`PermissionScope`.
		:raises ValueError: If parameter 'level' is ``None``.
		:raises TypeError:  If parameter 'level' is not of type :class:`AccessLevel`.
		"""
		super().__init__(line, parent=parent)

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

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

		self._scope = scope
		self._level = level

		if parent is not None:
			if parent._permissions is None:
				parent._permissions = {}

			parent._permissions[scope] = self

	@readonly
	def Scope(self) -> PermissionScope:
		"""
		Read-only property to access the scope (:attr:`_scope`).

		:returns: The scope, as :attr:`PermissionScope.Contents`, or :attr:`PermissionScope.All` for ``read-all`` and
		          ``write-all``.
		"""
		return self._scope

	@readonly
	def Level(self) -> AccessLevel:
		"""
		Read-only property to access the access granted (:attr:`_level`).

		:returns: The access level.
		"""
		return self._level

	def __str__(self) -> str:
		"""
		Return the permission, as written in a workflow file.

		:returns: The permission, as ``contents: write``, or ``read-all`` for scope :attr:`PermissionScope.All`.
		"""
		if self._scope is PermissionScope.All:
			return f"{self._level.value}-all"

		return f"{self._scope}: {self._level.value}"

	@classmethod
	def _FromYAML(cls, value: Any, path: Path, line: int) -> list[Self]:
		"""
		Read the value of a ``permissions`` key into the permissions a workflow or job declares.

		:param value:          The value of the ``permissions`` key.
		:param path:           Path to the workflow file.
		:param line:           Line the key is written at, starting at 1.
		:returns:              The permissions, in file order.
		:raises WorkflowError: If the value is neither ``read-all``, ``write-all`` nor a mapping.
		:raises WorkflowError: If a key is not a permission scope. |br|
		                       The note lists the allowed values.
		:raises WorkflowError: If a scope's value is not an access level. |br|
		                       The note lists the allowed values.
		"""
		if value == "read-all":
			return [cls(PermissionScope.All, AccessLevel.Read, line)]
		elif value == "write-all":
			return [cls(PermissionScope.All, AccessLevel.Write, line)]
		elif not isinstance(value, CommentedMap):
			ex = WorkflowError("Key 'permissions' is neither 'read-all', 'write-all' nor a mapping.", path, line)
			ex.add_note(f"Got '{value}'." if isinstance(value, str) else f"Got type '{getFullyQualifiedName(value)}'.")
			raise ex

		permissions = []
		for scope, level in value.items():
			scopeLine = Base._KeyLine(value, scope)
			try:
				permissionScope = PermissionScope(scope)
			except ValueError as cause:
				ex = WorkflowError(f"Key '{scope}' of 'permissions' is not a permission scope.", path, scopeLine)
				scopes = (member.value for member in PermissionScope if member is not PermissionScope.All)
				ex.add_note(f"Allowed values: {', '.join(scopes)}.")
				raise ex from cause

			try:
				accessLevel = AccessLevel(level)
			except ValueError as cause:
				ex = WorkflowError(f"Permission '{scope}' is not an access level.", path, scopeLine)
				ex.add_note(f"Got '{level}'.")
				ex.add_note(f"Allowed values: {', '.join(member.value for member in AccessLevel)}.")
				raise ex from cause

			permissions.append(cls(permissionScope, accessLevel, scopeLine))

		return permissions


@export
@abstractclass
class Parameter(Base[Workflow]):
	"""
	Common behaviour of the inputs, outputs and secrets of a reusable workflow.

	Every parameter has a name and an optional description, and belongs to a :class:`Workflow`.
	"""

	_PARENT_TYPE: ClassVar[ParentTypes] = Workflow  #: A parameter is declared by a workflow.

	_name:        str            #: Name of the parameter.
	_description: Nullable[str]  #: Description of the parameter.

	def __init__(
		self,
		name:        str,
		line:        int,
		description: Nullable[str]      = None,
		*,
		parent:      Nullable[Workflow] = None
	) -> None:
		"""
		Initializes a parameter of a reusable workflow.

		:param name:        Name of the parameter.
		:param line:        Line the parameter's name is written at, starting at 1.
		:param description: Optional, description of the parameter. Default: ``None``.
		:param parent:      Optional, reference to the workflow declaring it. 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 'description' 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 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._name =        name
		self._description = description

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

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

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

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

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

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


@export
class Input(Parameter):
	"""An input of a reusable workflow, declared in ``on.workflow_call.inputs``."""

	_type:     InputType  #: Type of the input.
	_required: bool       #: ``True``, if a caller has to pass the input.
	_default:  ValueT     #: Value of the input, if a caller doesn't pass it.

	def __init__(
		self,
		name:        str,
		line:        int,
		inputType:   InputType,
		required:    bool               = False,
		default:     ValueT             = None,
		description: Nullable[str]      = None,
		*,
		parent:      Nullable[Workflow] = None
	) -> None:
		"""
		Initializes an input of a reusable workflow.

		:param name:        Name of the input.
		:param line:        Line the input's name is written at, starting at 1.
		:param inputType:   Type of the input.
		:param required:    Optional, ``True``, if a caller has to pass the input. Default: ``False``.
		:param default:     Optional, value of the input, if a caller doesn't pass it. Default: ``None``.
		:param description: Optional, description of the input. Default: ``None``.
		:param parent:      Optional, reference to the workflow declaring it. Default: ``None``.
		:raises ValueError: If parameter 'inputType' is ``None``.
		:raises TypeError:  If parameter 'inputType' is not of type :class:`InputType`.
		:raises TypeError:  If parameter 'required' is not of type :class:`bool`.
		"""
		super().__init__(name, line, description, parent=parent)

		if inputType is None:
			raise ValueError("Parameter 'inputType' is None.")
		elif 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

		self._type =     inputType
		self._required = required
		self._default =  default

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

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

		:returns: Type of the input.
		"""
		return self._type

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

		:returns: ``True``, if the input is required.
		"""
		return self._required

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

		The value keeps the type it is written with, as ``'3.14'`` or ``false``, and a multi-line value keeps its line
		breaks.

		:returns: The default value, or ``None`` if the workflow gives none.
		"""
		return self._default

	@classmethod
	def _FromYAML(cls, name: str, declaration: Any, path: Path, line: int) -> Self:
		"""
		Read an input's declaration below ``on.workflow_call.inputs``.


		:param name:           Name of the input.
		:param declaration:    The declaration.
		:param path:           Path to the workflow file.
		:param line:           Line the input's name is written at, starting at 1.
		:returns:              The input.
		:raises WorkflowError: If the declaration is not a mapping.
		:raises WorkflowError: If key ``required`` is not a boolean.
		:raises WorkflowError: If the declaration has no ``type`` key.
		:raises WorkflowError: If key ``type`` is not an input type. |br|
		                       The note lists the allowed values.
		"""
		if declaration is None:
			raise WorkflowError(f"Input '{name}' has no 'type' key.", path, line)
		elif not isinstance(declaration, CommentedMap):
			ex = WorkflowError(f"Declaration of '{name}' is not a mapping.", path, line)
			ex.add_note(f"Got type '{getFullyQualifiedName(declaration)}'.")
			raise ex

		description = declaration.get("description", None)
		required = Base._ToPython(declaration.get("required", False))
		if not isinstance(required, bool):
			ex = WorkflowError(f"Key 'required' of '{name}' is not a boolean.", path, line)
			ex.add_note(f"Got '{required}'.")
			raise ex

		if (inputType := declaration.get("type", None)) is None:
			raise WorkflowError(f"Input '{name}' has no 'type' key.", path, line)

		try:
			inputType = InputType.Parse(str(inputType))
		except ValueError as cause:
			ex = WorkflowError(f"Key 'type' of input '{name}' is not an input type.", path, line)
			ex.add_note(f"Got '{inputType}'.")
			ex.add_note(f"Allowed values: {', '.join(member.value for member in InputType)}.")
			raise ex from cause

		default = Base._ToPython(declaration.get("default", None))

		return cls(name, line, inputType, required, default, None if description is None else str(description))


@export
class Output(Parameter):
	"""An output of a reusable workflow, declared in ``on.workflow_call.outputs``."""

	_value: str  #: Expression the output's value is taken from.

	def __init__(
		self,
		name:        str,
		line:        int,
		value:       str,
		description: Nullable[str]      = None,
		*,
		parent:      Nullable[Workflow] = None
	) -> None:
		"""
		Initializes an output of a reusable workflow.

		:param name:        Name of the output.
		:param line:        Line the output's name is written at, starting at 1.
		:param value:       Expression the output's value is taken from, as ``${{ jobs.Build.outputs.version }}``.
		:param description: Optional, description of the output. Default: ``None``.
		:param parent:      Optional, reference to the workflow declaring it. Default: ``None``.
		:raises ValueError: If parameter 'value' is ``None``.
		:raises TypeError:  If parameter 'value' is not of type :class:`str`.
		"""
		super().__init__(name, line, description, parent=parent)

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

		self._value = value

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

	@readonly
	def Value(self) -> str:
		"""
		Read-only property to access the expression the output's value is taken from (:attr:`_value`).

		:returns: The expression, as ``${{ jobs.Build.outputs.version }}``.
		"""
		return self._value

	@classmethod
	def _FromYAML(cls, name: str, declaration: Any, path: Path, line: int) -> Self:
		"""
		Read an output's declaration below ``on.workflow_call.outputs``.


		:param name:           Name of the output.
		:param declaration:    The declaration.
		:param path:           Path to the workflow file.
		:param line:           Line the output's name is written at, starting at 1.
		:returns:              The output.
		:raises WorkflowError: If the declaration is not a mapping.
		:raises WorkflowError: If the declaration has no ``value`` key.
		"""
		if declaration is None:
			raise WorkflowError(f"Output '{name}' has no 'value' key.", path, line)
		elif not isinstance(declaration, CommentedMap):
			ex = WorkflowError(f"Declaration of '{name}' is not a mapping.", path, line)
			ex.add_note(f"Got type '{getFullyQualifiedName(declaration)}'.")
			raise ex

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

		if (value := declaration.get("value", None)) is None:
			raise WorkflowError(f"Output '{name}' has no 'value' key.", path, line)

		return cls(name, line, str(value), None if description is None else str(description))


@export
class Secret(Parameter):
	"""A secret of a reusable workflow, declared in ``on.workflow_call.secrets``."""

	_required: bool  #: ``True``, if a caller has to pass the secret.

	def __init__(
		self,
		name:        str,
		line:        int,
		required:    bool               = False,
		description: Nullable[str]      = None,
		*,
		parent:      Nullable[Workflow] = None
	) -> None:
		"""
		Initializes a secret of a reusable workflow.

		:param name:        Name of the secret.
		:param line:        Line the secret's name is written at, starting at 1.
		:param required:    Optional, ``True``, if a caller has to pass the secret. Default: ``False``.
		:param description: Optional, description of the secret. Default: ``None``.
		:param parent:      Optional, reference to the workflow declaring it. Default: ``None``.
		:raises TypeError:  If parameter 'required' is not of type :class:`bool`.
		"""
		super().__init__(name, line, description, parent=parent)

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

		self._required = required

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

	@readonly
	def Required(self) -> bool:
		"""
		Read-only property to access whether a caller has to pass the secret (:attr:`_required`).

		:returns: ``True``, if the secret is required.
		"""
		return self._required

	@classmethod
	def _FromYAML(cls, name: str, declaration: Any, path: Path, line: int) -> Self:
		"""
		Read a secret's declaration below ``on.workflow_call.secrets``.


		:param name:           Name of the secret.
		:param declaration:    The declaration.
		:param path:           Path to the workflow file.
		:param line:           Line the secret's name is written at, starting at 1.
		:returns:              The secret.
		:raises WorkflowError: If the declaration is not a mapping.
		:raises WorkflowError: If key ``required`` is not a boolean.
		"""
		if declaration is None:
			return cls(name, line)
		elif not isinstance(declaration, CommentedMap):
			ex = WorkflowError(f"Declaration of '{name}' is not a mapping.", path, line)
			ex.add_note(f"Got type '{getFullyQualifiedName(declaration)}'.")
			raise ex

		description = declaration.get("description", None)
		required = Base._ToPython(declaration.get("required", False))
		if not isinstance(required, bool):
			ex = WorkflowError(f"Key 'required' of '{name}' is not a boolean.", path, line)
			ex.add_note(f"Got '{required}'.")
			raise ex

		return cls(name, line, required, None if description is None else str(description))


@export
class WorkflowResolver(metaclass=ExtendedType, slots=True):
	"""
	Reads the reusable workflows jobs call, and the actions steps run, as far as they are in a local directory.

	A repository is mapped to the directory holding its workflow files, so a reference like
	``pyTooling/Actions/.github/workflows/Package.yml@r8`` reads ``Package.yml`` from that directory, whatever its ref.
	A local reference like ``./.github/workflows/Package.yml`` reads the file next to the calling workflow's file.

	An action of a mapped repository, like ``pyTooling/Actions/.github/actions/ComputeRequirements@r8``, is read from
	the repository's root - the directory holding the ``.github`` directory the mapped directory is in. A local action,
	like ``./.github/actions/ComputeRequirements``, is read from the root of the calling workflow's or action's
	repository.

	Every file is read once; asking for it again returns the same :class:`Workflow` or :class:`Action`.
	"""

	_repositories: dict[str, Path]       #: Directories holding the workflow files, by repository in lower case.
	_workflows:    dict[Path, Workflow]  #: Workflows already read, by resolved path.
	_actions:      dict[Path, Action]    #: Actions already read, by resolved path.

	def __init__(self, repositories: Nullable[Mapping[str, Path]] = None) -> None:
		"""
		Initializes a resolver.

		:param repositories: Optional, directories holding the workflow files, by repository, as
		                     ``{"pyTooling/Actions": Path(".github/workflows")}``. Default: ``None``.
		:raises TypeError:   If parameter 'repositories' is not a mapping.
		:raises TypeError:   If a key of parameter 'repositories' is not of type :class:`str`.
		:raises ValueError:  If a key of parameter 'repositories' is not of the form ``owner/repo``.
		:raises TypeError:   If a value of parameter 'repositories' is not of type :class:`~pathlib.Path`.
		"""
		self._repositories = {}
		self._workflows =    {}
		self._actions =      {}

		if repositories is None:
			return
		elif not isinstance(repositories, Mapping):
			ex = TypeError("Parameter 'repositories' is not a mapping.")
			ex.add_note(f"Got type '{getFullyQualifiedName(repositories)}'.")
			raise ex

		for repository, directory in repositories.items():
			if not isinstance(repository, str):
				ex = TypeError("Key of parameter 'repositories' is not of type 'str'.")
				ex.add_note(f"Got type '{getFullyQualifiedName(repository)}'.")
				raise ex
			elif repository.count("/") != 1 or repository.startswith("/") or repository.endswith("/"):
				ex = ValueError("Key of parameter 'repositories' is not of the form 'owner/repo'.")
				ex.add_note(f"Got '{repository}'.")
				raise ex
			elif not isinstance(directory, Path):
				ex = TypeError(f"Value of parameter 'repositories' for '{repository}' is not of type 'Path'.")
				ex.add_note(f"Got type '{getFullyQualifiedName(directory)}'.")
				raise ex

			self._repositories[repository.lower()] = directory

	@readonly
	def Repositories(self) -> dict[str, Path]:
		"""
		Read-only property to access the directories holding the workflow files (:attr:`_repositories`).

		:returns: The directories, by repository in lower case.
		"""
		return self._repositories

	def CanResolve(self, uses: UsesReference) -> bool:
		"""
		Return whether a reference names a file the resolver reads: a local one, or one of a mapped repository.

		:param uses:        The reference, as :attr:`Job.Uses`.
		:returns:           ``True``, if the reference is local, or its repository is in :attr:`Repositories`.
		:raises ValueError: If parameter 'uses' is ``None``.
		:raises TypeError:  If parameter 'uses' is not of type :class:`UsesReference`.
		"""
		if uses is None:
			raise ValueError("Parameter 'uses' is None.")
		elif not isinstance(uses, UsesReference):
			ex = TypeError("Parameter 'uses' is not of type 'UsesReference'.")
			ex.add_note(f"Got type '{getFullyQualifiedName(uses)}'.")
			raise ex

		return uses._isLocal or (uses._repository is not None and uses._repository.lower() in self._repositories)

	def Load(self, path: Path) -> Workflow:
		"""
		Read a workflow file, or return it if it was read before.

		:param path:           Path to the workflow file.
		:returns:              The workflow.
		:raises ValueError:    If parameter 'path' is ``None``.
		:raises TypeError:     If parameter 'path' is not of type :class:`~pathlib.Path`.
		:raises WorkflowError: If the file doesn't exist, can't be read, or is not a well-formed workflow.
		"""
		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

		key = path.resolve()
		if (workflow := self._workflows.get(key, None)) is None:
			workflow = Workflow.FromFile(path)
			self._workflows[key] = workflow

		return workflow

	def Resolve(self, uses: UsesReference) -> Nullable[Workflow]:
		"""
		Return the reusable workflow a reference names, if its file is in a local directory.

		:param uses:           The reference, as :attr:`Job.Uses`.
		:returns:              The workflow, or ``None`` if the reference names an action, or a repository without a
		                       directory.
		:raises ValueError:    If parameter 'uses' is ``None``.
		:raises TypeError:     If parameter 'uses' is not of type :class:`UsesReference`.
		:raises ValueError:    If parameter 'uses' is a local reference outside a workflow.
		:raises WorkflowError: If the workflow file doesn't exist in the directory. |br|
		                       The note names the reference's location.
		:raises WorkflowError: If the file is not a well-formed workflow.
		"""
		if uses is None:
			raise ValueError("Parameter 'uses' is None.")
		elif not isinstance(uses, UsesReference):
			ex = TypeError("Parameter 'uses' is not of type 'UsesReference'.")
			ex.add_note(f"Got type '{getFullyQualifiedName(uses)}'.")
			raise ex

		if not uses.IsWorkflow:
			return None
		elif uses._isLocal:
			if uses._workflow is None:
				ex = ValueError("Parameter 'uses' is a local reference outside a workflow.")
				ex.add_note(f"Got '{uses}'.")
				raise ex

			directory = uses._workflow._path.parent
		elif (directory := self._repositories.get(uses._repository.lower(), None)) is None:
			return None

		path = directory / uses.FileName
		if not path.exists():
			ex = WorkflowError(
				f"Workflow '{uses.FileName}' doesn't exist in '{directory}'.",
				uses._file,
				uses._line
			)
			ex.add_note(f"Called as '{uses}'.")
			raise ex

		return self.Load(path)

	def LoadAction(self, path: Path) -> Action:
		"""
		Read an action's file, or return it if it was read before.

		:param path:           Path to the action's file.
		:returns:              The action.
		:raises ValueError:    If parameter 'path' is ``None``.
		:raises TypeError:     If parameter 'path' is not of type :class:`~pathlib.Path`.
		:raises WorkflowError: If the file doesn't exist, can't be read, or is not a well-formed action.
		"""
		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

		key = path.resolve()
		if (action := self._actions.get(key, None)) is None:
			action = Action.FromFile(path)
			self._actions[key] = action

		return action

	def ResolveAction(self, uses: UsesReference) -> Nullable[Action]:
		"""
		Return the action a step's reference names, if its file is in a local directory.

		:param uses:           The reference, as :attr:`Step.Uses`.
		:returns:              The action, or ``None`` if the reference names a reusable workflow, a Docker image, a
		                       repository without a directory, or a local action outside a repository's ``.github``
		                       directory.
		:raises ValueError:    If parameter 'uses' is ``None``.
		:raises TypeError:     If parameter 'uses' is not of type :class:`UsesReference`.
		:raises WorkflowError: If the directory has neither an ``action.yml`` nor an ``action.yaml``. |br|
		                       The note names the reference's location.
		:raises WorkflowError: If the file is not a well-formed action.
		"""
		if uses is None:
			raise ValueError("Parameter 'uses' is None.")
		elif not isinstance(uses, UsesReference):
			ex = TypeError("Parameter 'uses' is not of type 'UsesReference'.")
			ex.add_note(f"Got type '{getFullyQualifiedName(uses)}'.")
			raise ex

		if uses.IsWorkflow or uses._isDocker:
			return None

		if uses._isLocal:
			if uses._file is None:
				return None

			base = uses._file.parent
		elif (base := self._repositories.get(uses._repository.lower(), None)) is None:
			return None

		root = next((directory.parent for directory in (base, *base.parents) if directory.name == ".github"), None)
		if root is None:
			return None

		directory = root / uses._path
		for fileName in ("action.yml", "action.yaml"):
			if (path := directory / fileName).exists():
				return self.LoadAction(path)

		ex = WorkflowError(f"Action '{uses._path}' has no 'action.yml' in '{directory}'.", uses._file, uses._line)
		ex.add_note(f"Called as '{uses}'.")
		raise ex


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

	:meth:`Workflow.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, the reference a job calls, its permissions.
	"""

	_definition: DefinitionType  #: The element of the workflow 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 workflow 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

	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 workflow file this element is built from.
		"""
		self._definition = definition

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

		:returns: The :class:`Workflow` of a pipeline, the :class:`Job` of a called workflow, a matrix, a matrix instance
		          and a job, or the :class:`Step` of a step.
		"""
		return self._definition


@export
class CallMixin(metaclass=ExtendedType, mixin=True):
	"""Mixin-class for a called workflow built from a workflow file, holding the workflow file it was expanded from."""

	_calledWorkflow: Nullable[Workflow]  #: The workflow file the called workflow's elements were built from.

	def __init__(self, calledWorkflow: Nullable[Workflow] = None) -> None:
		"""
		Initializes the called workflow file.

		:param calledWorkflow: Optional, the workflow file the called workflow's elements are built from. Default:
		                       ``None``.
		:raises TypeError:     If parameter 'calledWorkflow' is not of type :class:`Workflow`.
		"""
		if calledWorkflow is not None and not isinstance(calledWorkflow, Workflow):
			ex = TypeError("Parameter 'calledWorkflow' is not of type 'Workflow'.")
			ex.add_note(f"Got type '{getFullyQualifiedName(calledWorkflow)}'.")
			raise ex

		self._calledWorkflow = calledWorkflow

	@readonly
	def CalledWorkflow(self) -> Nullable[Workflow]:
		"""
		Read-only property to access the workflow file the called workflow was expanded from (:attr:`_calledWorkflow`).

		:returns: The workflow, or ``None`` if the call wasn't expanded - its file isn't at hand, or the depth was used
		          up.
		"""
		return self._calledWorkflow


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

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

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

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

		super().__init__(definition._name, keyValuePairs=keyValuePairs)
		DefinitionMixin.__init__(self, definition)


@export
class DefinedWorkflow(CIWorkflow, CallMixin, DefinitionMixin[Job]):
	"""A called workflow built from the job calling it, as :meth:`Workflow.ToPipeline` builds it."""

	_DEFINITION_TYPE: ClassVar[type] = Job  #: A called workflow is built from the job calling it.

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

		The job's ``uses`` is the workflow's :attr:`~pyTooling.CI.Workflow.Reference`, its ``if`` the
		workflow's :attr:`~pyTooling.CI.ConditionMixin.Condition`.

		:param definition:     The job calling the workflow.
		:param calledWorkflow: Optional, the workflow file the called workflow'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 call. Default: ``None``.
		:raises ValueError:    If parameter 'definition' calls no workflow.
		"""
		self._CheckDefinition(definition)

		if definition._uses is None:
			ex = ValueError("Parameter 'definition' calls no workflow.")
			ex.add_note(f"Got job '{definition._name}'.")
			raise ex

		super().__init__(
			definition._name, reference=str(definition._uses), condition=definition._condition, keyValuePairs=keyValuePairs,
			parent=parent
		)
		DefinitionMixin.__init__(self, definition)
		CallMixin.__init__(self, calledWorkflow)


@export
class DefinedMatrix(CIMatrix, DefinitionMixin[Job]):
	"""
	A matrix built from the job declaring it, as :meth:`Workflow.ToPipeline` builds it.

	A dynamic matrix - see :attr:`Matrix.IsDynamic` - holds no instances, since its combinations are known at run time
	only.
	"""

	_DEFINITION_TYPE: ClassVar[type] = Job  #: A matrix is built from the job declaring it.

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

		:param definition:    The job declaring the matrix.
		: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' declares no matrix.
		"""
		self._CheckDefinition(definition)

		if definition._matrix is None:
			ex = ValueError("Parameter 'definition' declares no matrix.")
			ex.add_note(f"Got job '{definition._name}'.")
			raise ex

		super().__init__(definition._name, condition=definition._condition, keyValuePairs=keyValuePairs, parent=parent)
		DefinitionMixin.__init__(self, definition)


@export
class DefinedMatrixWorkflow(CIMatrixWorkflow, CallMixin, DefinitionMixin[Job]):
	"""One instance of a matrix calling a reusable workflow, as :meth:`Workflow.ToPipeline` builds it."""

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

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

		:param definition:     The job declaring the matrix.
		:param dimensions:     The matrix' combination this instance is called with, the values as GitHub prints them.
		:param calledWorkflow: Optional, the workflow file the called workflow'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' calls no workflow.
		:raises ValueError:    If parameter 'dimensions' is ``None``.
		"""
		self._CheckDefinition(definition)

		if definition._uses is None:
			ex = ValueError("Parameter 'definition' calls no workflow.")
			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=str(definition._uses), condition=definition._condition,
			keyValuePairs=keyValuePairs, parent=parent
		)
		DefinitionMixin.__init__(self, definition)
		CallMixin.__init__(self, calledWorkflow)


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

	_DEFINITION_TYPE: ClassVar[type] = Job  #: A job is built from its job in the workflow 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 workflow 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, condition=definition._condition, keyValuePairs=keyValuePairs, parent=parent)
		DefinitionMixin.__init__(self, definition)


@export
class DefinedMatrixJob(CIMatrixJob, DefinitionMixin[Job]):
	"""One instance of a matrix running steps, as :meth:`Workflow.ToPipeline` builds it."""

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

	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 matrix running steps, named by the job's key.

		:param definition:    The job declaring the matrix.
		:param dimensions:    The matrix' combination this instance runs with, the values as GitHub prints them.
		: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, condition=definition._condition, keyValuePairs=keyValuePairs, parent=parent
		)
		DefinitionMixin.__init__(self, definition)


@export
class DefinedStep(CIStep, DefinitionMixin[Step]):
	"""A step of a job, as :meth:`Workflow.ToPipeline` builds it."""

	_DEFINITION_TYPE: ClassVar[type] = Step  #: A step is built from its step in the workflow file.

	def __init__(
		self,
		definition:    Step,
		*,
		keyValuePairs: Nullable[Mapping[Hashable, Any]] = None,
		parent:        Nullable[CIJob]                  = None
	) -> None:
		"""
		Initializes a step built from its step in the workflow file.

		The step is named as GitHub displays it: by its ``name``, or else ``Run`` followed by the action it runs or the
		first line of its script.

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

		if definition._name is not None:
			name = definition._name
		elif definition._uses is not None:
			name = f"Run {definition._uses}"
		elif definition._run is not None:
			firstLine = definition._run.strip().partition("\n")[0]
			name = f"Run {firstLine}"
		else:
			name = f"Step at line {definition._line}"

		super().__init__(name, condition=definition._condition, keyValuePairs=keyValuePairs, parent=parent)
		DefinitionMixin.__init__(self, definition)