verctl-github 0.8.6-rc.19

GitHub REST client for verctl releases, pull requests, tags, and branch rules
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
//! GitHub REST client for `verctl` pull requests, Releases, drafts, tags,
//! branch rules, and workflow runs.

use std::cell::OnceCell;
use std::path::{Path, PathBuf};
use std::time::Duration;
use std::{env, fmt, fs, io};

use anyhow::{Context, Result, bail, ensure};
use octocrab::Octocrab;
use octocrab::models::repos::Object;
use octocrab::params::State;
use octocrab::params::repos::Reference;
use octocrab::repos::releases::MakeLatest;
use reqwest::header::HeaderValue;
use reqwest::redirect::Policy;
use tokio::runtime::Builder;
use tokio::time;
pub use verctl_core::env::{
    default_branch_of, event_default_branch, event_is_merge_group, is_merge_group,
    pull_request_number, write_github_output as write_output,
};
pub use verctl_core::repo::{Repo, parse_remote, parse_slug};
use verctl_core::{env as release_env, lookup, stop};

/// Actions sets `GITHUB_REPOSITORY`. Locally, `origin` is the contract.
///
/// # Errors
///
/// Returns an error when `GITHUB_REPOSITORY` is set but is not `owner/name`,
/// or, without it, when the `origin` URL cannot be read or is not a GitHub
/// remote. Without `GITHUB_REPOSITORY`, the error is a
/// [`lookup::Unavailable`]: the repository names no GitHub repository to ask.
/// A malformed `GITHUB_REPOSITORY` is a setting to fix, so it stays unmarked.
pub fn repo_with(origin_url: impl FnOnce() -> Result<String>) -> Result<Repo> {
    if let Ok(slug) = env::var("GITHUB_REPOSITORY")
        && !slug.is_empty()
    {
        return parse_slug(&slug);
    }
    origin_url()
        .and_then(|url| parse_remote(url.trim()))
        .map_err(lookup::unavailable)
}

/// The branch a Version PR targets: `GITHUB_REF_NAME`, else
/// `VERCTL_DEFAULT_BRANCH`, else the branch `origin/HEAD` names.
///
/// If none of them is set, the call fails instead of guessing.
/// A repository whose default is not `main` would otherwise get a Version PR
/// against a branch it does not release from.
///
/// # Errors
///
/// Returns an error when none of those three sources names a branch.
pub fn base_branch_with(
    configured: Option<String>,
    upstream: impl FnOnce() -> Option<String>,
) -> Result<String> {
    if let Ok(name) = env::var("GITHUB_REF_NAME")
        && !name.is_empty()
    {
        return Ok(name);
    }
    configured
        .or_else(upstream)
        .context(
            "cannot tell which branch the Version PR targets: set VERCTL_DEFAULT_BRANCH, or run `git remote set-head origin --auto`",
        )
}

/// An open pull request.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ExistingPr {
    /// Link to the pull request.
    pub url: String,
    /// The pull request number.
    pub number: u64,
    /// Full hex SHA of the pull request's base branch tip as GitHub reports it.
    pub base_sha: String,
}

/// The open pull request from `head` in this repository, if one exists.
///
/// # Errors
///
/// Returns an error when the GitHub client cannot be built or the call that
/// lists pull requests fails.
pub fn existing_pr(token: &str, repo: &Repo, head: &str) -> Result<Option<ExistingPr>> {
    block(async {
        let crab = client(token)?;
        let page = crab
            .pulls(&repo.owner, &repo.name)
            .list()
            .state(State::Open)
            .head(format!("{}:{head}", repo.owner))
            .per_page(1)
            .send()
            .await
            .context("list pull requests")?;
        Ok(page.items.into_iter().next().and_then(|pr| {
            let url = pr.html_url?.to_string();
            Some(ExistingPr {
                url,
                number: pr.number,
                base_sha: pr.base.sha,
            })
        }))
    })
}

/// Sets the title and body of pull request `number` and returns its URL.
///
/// # Errors
///
/// Returns an error when the GitHub client cannot be built, the update
/// request fails, or the response carries no URL.
pub fn update_pr(token: &str, repo: &Repo, number: u64, title: &str, body: &str) -> Result<String> {
    block(async {
        let crab = client(token)?;
        let pr = crab
            .pulls(&repo.owner, &repo.name)
            .update(number)
            .title(title)
            .body(body)
            .send()
            .await
            .context("update pull request")?;
        pr.html_url
            .map(|url| url.to_string())
            .context("updated PR has no html_url")
    })
}

/// Opens a pull request from `head` into `base`.
///
/// # Errors
///
/// Returns an error when the GitHub client cannot be built or the create
/// request fails, for example when `head` does not exist.
/// It also returns one when the response carries no URL.
pub fn create_pr(
    token: &str,
    repo: &Repo,
    title: &str,
    head: &str,
    base: &str,
    body: &str,
) -> Result<ExistingPr> {
    block(async {
        let crab = client(token)?;
        let pr = crab
            .pulls(&repo.owner, &repo.name)
            .create(title, head, base)
            .body(body)
            .send()
            .await
            .context("create pull request")?;
        let url = pr
            .html_url
            .map(|url| url.to_string())
            .context("created PR has no html_url")?;
        Ok(ExistingPr {
            url,
            number: pr.number,
            base_sha: pr.base.sha,
        })
    })
}

/// Posts `comment` on pull request `number`, closes it, and returns its URL.
///
/// # Errors
///
/// Returns an error when the GitHub client cannot be built, the comment or
/// close request fails, or the closed pull request response carries no URL.
pub fn close_pr(token: &str, repo: &Repo, number: u64, comment: &str) -> Result<String> {
    block(async {
        let crab = client(token)?;
        close_pr_with(&crab, repo, number, comment).await
    })
}

async fn close_pr_with(crab: &Octocrab, repo: &Repo, number: u64, comment: &str) -> Result<String> {
    #[derive(serde::Serialize)]
    struct CommentBody<'a> {
        body: &'a str,
    }
    #[derive(serde::Serialize)]
    struct CloseState {
        state: &'static str,
    }
    #[derive(serde::Deserialize)]
    struct ClosedPull {
        html_url: Option<String>,
    }
    let comment_route = format!(
        "/repos/{owner}/{name}/issues/{number}/comments",
        owner = repo.owner,
        name = repo.name,
    );
    let _: serde_json::Value = crab
        .post(comment_route, Some(&CommentBody { body: comment }))
        .await
        .with_context(|| format!("comment on pull request #{number}"))?;
    let pull_route = format!(
        "/repos/{owner}/{name}/pulls/{number}",
        owner = repo.owner,
        name = repo.name,
    );
    let closed: ClosedPull = crab
        .patch(pull_route, Some(&CloseState { state: "closed" }))
        .await
        .with_context(|| format!("close pull request #{number}"))?;
    closed.html_url.context("closed PR has no html_url")
}

/// Whether the pull request of this `pull_request` event is a Version PR by
/// the identity of the `version-pr-identity` design §1.
/// Its head repository is this repository, and its head branch is
/// `verctl/release/<base>` for the base it targets now.
///
/// The check reads all three through the API when it runs.
/// It never reads the event payload, because a base can change after the
/// event and a label applied after opening is missing from the `opened`
/// payload.
/// It never reads the title, body, or labels, and it ignores
/// `GITHUB_HEAD_REF`.
///
/// Without an event, or for an event that is not a pull request's, it is
/// `false`.
///
/// # Errors
///
/// Returns an error when the event names a pull request but no token is set.
/// It also returns one when `GITHUB_REPOSITORY` is not `owner/name` or GitHub
/// cannot read the pull request.
pub fn pull_request_is_version_pr() -> Result<bool> {
    let Ok(path) = env::var("GITHUB_EVENT_PATH") else {
        return Ok(false);
    };
    let Ok(raw) = fs::read_to_string(path) else {
        return Ok(false);
    };
    let Some(number) = pull_request_number(&raw) else {
        return Ok(false);
    };
    let token = release_env::env_token().context(
        "the version check reads the pull request and needs GITHUB_TOKEN with pull-requests: read",
    )?;
    let slug = env::var("GITHUB_REPOSITORY").unwrap_or_default();
    let repo = parse_slug(&slug)?;
    block(async move {
        let crab = client(&token)?;
        let pr = crab
            .pulls(&repo.owner, &repo.name)
            .get(number)
            .await
            .with_context(|| format!("read pull request #{number}"))?;
        let same_repo = pr
            .head
            .repo
            .as_ref()
            .and_then(|head| head.full_name.as_deref())
            .is_some_and(|name| name.eq_ignore_ascii_case(&slug));
        Ok(same_repo && pr.head.ref_field == release_env::version_branch(&pr.base.ref_field))
    })
}

/// Where a Release stands: the stable one, or a candidate before it.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Stage {
    /// A stable version: GitHub's defaults apply, so the Release becomes the
    /// repository's latest.
    Stable,
    /// A candidate: a prerelease that never becomes the latest Release, so
    /// the repository's latest stays the stable one ([create a release]).
    ///
    /// [create a release]: https://docs.github.com/en/rest/releases/releases#create-a-release
    Candidate,
}

/// The Release a run creates for a tag: a draft for `release`, or a Release
/// published at once for [`ensure_release`].
///
/// Not `#[non_exhaustive]`: `verctl-release` constructs it directly.
#[derive(Debug, Clone, Copy)]
pub struct NewRelease<'a> {
    /// The tag the Release is for.
    pub tag: &'a str,
    /// The Release title.
    pub name: &'a str,
    /// The Release notes.
    pub body: &'a str,
    /// The commit the tag is created at, and the one an existing tag must name.
    pub sha: &'a str,
    /// Whether the Release is the stable one or a candidate.
    pub stage: Stage,
    /// The asset names the draft must contain before it is published, because
    /// an immutable Release takes no asset once published ([immutable
    /// releases]). Empty, the draft is published with none.
    ///
    /// [immutable releases]: https://docs.github.com/en/code-security/supply-chain-security/understanding-your-software-supply-chain/immutable-releases
    pub assets: &'a [String],
}

/// Whether a release run uploaded a package under a tag.
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
pub enum PackageUpload {
    /// This run published a package under the tag, so an existing release's
    /// tag must match `sha`.
    #[default]
    Shipped,
    /// Nothing under the tag shipped in this run; an existing published
    /// release may stay at its earlier commit.
    Skipped,
}

/// Create `tag` at `sha` if it is missing. Returns the release HTML URL.
///
/// A new Release is a [`Stage::Stable`] one, with GitHub's defaults, and is
/// published at once. An existing release is used as it is, and a draft found
/// is published.
///
/// An existing release is not trusted: GitHub's `target_commitish` on the
/// Release object is a branch name more often than a SHA. The git ref is
/// re-read either way, and a tag that names another commit fails.
///
/// # Errors
///
/// Returns an error when:
///
/// - The GitHub client cannot be built.
/// - A release or tag lookup fails.
/// - The release cannot be created, or a draft found cannot be published.
/// - The tag does not point at `sha`.
///
/// The tag is checked against an existing release only when `upload` is
/// [`PackageUpload::Shipped`].
pub fn ensure_release(
    token: &str,
    repo: &Repo,
    tag: &str,
    name: &str,
    body: &str,
    sha: &str,
    upload: PackageUpload,
) -> Result<String> {
    let release = NewRelease {
        tag,
        name,
        body,
        sha,
        stage: Stage::Stable,
        assets: &[],
    };
    block(async {
        let crab = client(token)?;
        ensure_release_with(&crab, repo, &release, upload).await
    })
}

/// [`PackageUpload::Shipped`] means this run published a package under the
/// tag. With [`PackageUpload::Skipped`], an existing published release belongs
/// to the run that did, and its tag may name that earlier commit. A draft's
/// tag is always checked.
async fn ensure_release_with(
    crab: &Octocrab,
    repo: &Repo,
    release: &NewRelease<'_>,
    upload: PackageUpload,
) -> Result<String> {
    let NewRelease {
        tag,
        name,
        body,
        sha,
        stage,
        assets: _,
    } = *release;
    let existing = if read_tag(crab, repo, tag).await?.is_some() {
        find_release(crab, repo, tag, &ReleaseList::default()).await?
    } else {
        None
    };
    match existing {
        Some(found) if !found.draft => {
            if matches!(upload, PackageUpload::Shipped) {
                require_tag_at(crab, repo, tag, sha).await?;
            }
            return Ok(found.html_url);
        }
        Some(draft) => {
            require_tag_at(crab, repo, tag, sha).await?;
            return finalize(crab, repo, release, &draft).await;
        }
        None => {}
    }
    let repos = crab.repos(&repo.owner, &repo.name);
    let releases = repos.releases();
    let create = releases.create(tag).name(name).body(body);
    let create = match stage {
        Stage::Stable => create,
        Stage::Candidate => create.prerelease(true).make_latest(MakeLatest::False),
    };
    let created = create
        .target_commitish(sha)
        .send()
        .await
        .map_err(|error| release_error(error, tag, sha))?;
    require_tag_at(crab, repo, tag, sha).await?;
    Ok(created.html_url.to_string())
}

/// How long the tag proof waits before each read after the first, while
/// GitHub answers 404 for a tag that publishing the draft created.
/// Five reads over 15 seconds, inside the 30 seconds the release-tag-order
/// spec allows: GitHub can serve a new tag a moment after the Release that
/// created it, as in rawr run 43414046487.
pub const TAG_PROOF_DELAYS: [Duration; 4] = [
    Duration::from_secs(1),
    Duration::from_secs(2),
    Duration::from_secs(4),
    Duration::from_secs(8),
];

/// What a run finds on GitHub for one release tag, before it writes
/// anything.
#[derive(Debug)]
pub enum ExistingRelease {
    /// A Release published at HEAD. The run opens no draft for it and proves
    /// its tag. A mutable one takes the declared tarballs it lacks, so an
    /// older release missing a target can still be finished.
    Published(ReleaseRecord),
    /// No published Release: the run opens a draft for the tag.
    DraftState(DraftState),
}

impl ExistingRelease {
    /// The asset names already on the Release the run uploads to, or `None`
    /// for a published immutable Release, which takes no asset ([immutable
    /// releases]). Its shortfall is reported, and nothing is uploaded.
    ///
    /// [immutable releases]: https://docs.github.com/en/code-security/supply-chain-security/understanding-your-software-supply-chain/immutable-releases
    #[must_use]
    pub fn uploaded(&self) -> Option<Vec<&str>> {
        match self {
            Self::Published(release) if release.immutable => None,
            Self::Published(release) => Some(release.uploaded()),
            Self::DraftState(draft) => Some(draft.uploaded()),
        }
    }
}

/// A tag with no published Release, and the draft a run finds for it.
#[derive(Debug)]
pub enum DraftState {
    /// No Release exists for the tag.
    Missing,
    /// A draft at HEAD, which the run uploads to and publishes.
    AtHead(ReleaseRecord),
    /// A draft at another commit or at a branch name. Its tarballs were built
    /// from other code, so the run deletes it and creates a draft at HEAD.
    Stale(ReleaseRecord),
}

impl DraftState {
    /// The asset names uploaded on the draft the run keeps. A stale draft is
    /// deleted, so nothing on it counts.
    #[must_use]
    pub fn uploaded(&self) -> Vec<&str> {
        match self {
            Self::AtHead(draft) => draft.uploaded(),
            Self::Missing | Self::Stale(_) => Vec::new(),
        }
    }
}

/// Read what GitHub has for `tag`: the tag and its Release, draft or
/// published, so a run reads what to create before it writes anything.
///
/// A tag that exists must name `head`, whatever the Release's state: GitHub
/// uses an existing tag when a draft is published, so a tag on another commit
/// would fail the tag proof after the uploads.
/// A published Release counts as at HEAD when its tag names `head`, or when
/// GitHub serves no tag yet and the Release's `target_commitish` is `head`.
/// A draft counts as at HEAD when its `target_commitish` is `head`, or when
/// its tag names `head`.
///
/// The Releases list comes from `list`, which the run shares with its plan.
///
/// # Errors
///
/// Returns an error when the GitHub client cannot be built, when a lookup
/// fails, when the tag names a commit other than `head`, or when a Release is
/// published at another commit.
pub fn read_release(
    token: &str,
    repo: &Repo,
    tag: &str,
    head: &str,
    list: &ReleaseList,
) -> Result<ExistingRelease> {
    block(async {
        let crab = client(token)?;
        read_release_with(&crab, repo, tag, head, list).await
    })
}

async fn read_release_with(
    crab: &Octocrab,
    repo: &Repo,
    tag: &str,
    head: &str,
    list: &ReleaseList,
) -> Result<ExistingRelease> {
    let named = read_tag(crab, repo, tag).await?;
    if let Some(named) = &named {
        ensure!(
            named.eq_ignore_ascii_case(head),
            "tag {tag} names {named}, not HEAD {head}"
        );
    }
    let Some(release) = find_release(crab, repo, tag, list).await? else {
        return Ok(ExistingRelease::DraftState(DraftState::Missing));
    };
    let at_head = named.is_some() || release.target_commitish.eq_ignore_ascii_case(head);
    if release.draft {
        return Ok(ExistingRelease::DraftState(if at_head {
            DraftState::AtHead(release)
        } else {
            DraftState::Stale(release)
        }));
    }
    ensure!(
        at_head,
        "release {tag} is published at {target}, not HEAD {head}, and GitHub serves no tag {tag}",
        target = release.target_commitish
    );
    Ok(ExistingRelease::Published(release))
}

/// The id of the draft for `release`: the one `found` names at HEAD, or a new
/// draft with `target_commitish` set to `release.sha`.
/// A stale draft is deleted first.
///
/// The draft creates no tag: GitHub creates it at `target_commitish` when the
/// draft is published ([create a release]).
/// Until then the draft can still be changed or deleted, so a failed upload
/// leaves no tag behind.
///
/// # Errors
///
/// Returns an error when the GitHub client cannot be built, a stale draft
/// cannot be deleted, or the draft cannot be created.
/// A 403 on the create names the missing permission.
///
/// [create a release]: https://docs.github.com/en/rest/releases/releases#create-a-release
pub fn open_draft(
    token: &str,
    repo: &Repo,
    release: &NewRelease<'_>,
    found: &DraftState,
) -> Result<u64> {
    block(async {
        let crab = client(token)?;
        open_draft_with(&crab, repo, release, found).await
    })
}

async fn open_draft_with(
    crab: &Octocrab,
    repo: &Repo,
    release: &NewRelease<'_>,
    found: &DraftState,
) -> Result<u64> {
    let NewRelease {
        tag,
        name,
        body,
        sha,
        stage,
        assets: _,
    } = *release;
    let repos = crab.repos(&repo.owner, &repo.name);
    let releases = repos.releases();
    match found {
        DraftState::AtHead(draft) => return Ok(draft.id),
        DraftState::Stale(draft) => releases.delete(draft.id).await.with_context(|| {
            format!(
                "delete the draft release {tag} at {target}",
                target = draft.target_commitish
            )
        })?,
        DraftState::Missing => {}
    }
    let create = releases
        .create(tag)
        .name(name)
        .body(body)
        .draft(true)
        .target_commitish(sha);
    let create = match stage {
        Stage::Stable => create,
        Stage::Candidate => create.prerelease(true).make_latest(MakeLatest::False),
    };
    let created = create
        .send()
        .await
        .map_err(|error| release_error(error, tag, sha))?;
    Ok(created.id.into_inner())
}

/// The HTML URL of the Release `id`, draft or published, which the report of
/// a run that leaves the draft names.
///
/// # Errors
///
/// Returns an error when the GitHub client cannot be built or the Release
/// cannot be read.
pub fn release_url(token: &str, repo: &Repo, id: u64) -> Result<String> {
    block(async {
        let crab = client(token)?;
        let release: ReleaseRecord = crab
            .get(
                format!(
                    "/repos/{owner}/{name}/releases/{id}",
                    owner = repo.owner,
                    name = repo.name
                ),
                None::<&()>,
            )
            .await
            .with_context(|| format!("read the release {id}"))?;
        Ok(release.url().to_owned())
    })
}

/// Publish the draft `id` for `release`, which creates its tag at
/// `release.sha`, and return the Release URL.
///
/// The draft is read again first, so the check sees what GitHub has: a
/// draft that lacks a declared asset is never published.
///
/// # Errors
///
/// Returns an error when the GitHub client cannot be built, the draft cannot
/// be read or published, or it lacks a declared asset.
pub fn publish_draft(
    token: &str,
    repo: &Repo,
    release: &NewRelease<'_>,
    id: u64,
) -> Result<String> {
    block(async {
        let crab = client(token)?;
        publish_draft_with(&crab, repo, release, id).await
    })
}

async fn publish_draft_with(
    crab: &Octocrab,
    repo: &Repo,
    release: &NewRelease<'_>,
    id: u64,
) -> Result<String> {
    let draft: ReleaseRecord = crab
        .get(
            format!(
                "/repos/{owner}/{name}/releases/{id}",
                owner = repo.owner,
                name = repo.name
            ),
            None::<&()>,
        )
        .await
        .with_context(|| format!("read the draft release {}", release.tag))?;
    finalize(crab, repo, release, &draft).await
}

/// Write `body` as the notes of draft `id` of `tag`, and nothing else, so
/// the draft keeps its state: a failed run records why it stopped there.
///
/// # Errors
///
/// Returns an error when the GitHub client cannot be built or the update
/// fails.
pub fn write_draft_body(token: &str, repo: &Repo, tag: &str, id: u64, body: &str) -> Result<()> {
    block(async {
        let crab = client(token)?;
        crab.repos(&repo.owner, &repo.name)
            .releases()
            .update(id)
            .body(body)
            .send()
            .await
            .with_context(|| format!("write the stop record into the draft release {tag}"))?;
        Ok(())
    })
}

/// Publish `draft` once every asset `release` declares is `uploaded` on it,
/// and return its URL.
///
/// The update sends the title and notes this run has, `target_commitish`,
/// and the settings its stage sets, so a draft someone edited reads as this
/// run would have written it.
/// A candidate stays a prerelease and never becomes the latest.
/// A stable one sends `make_latest: legacy`, so GitHub decides by date and
/// version, and an older version published late does not take the latest from
/// a newer one ([update a release]).
///
/// [update a release]: https://docs.github.com/en/rest/releases/releases#update-a-release
async fn finalize(
    crab: &Octocrab,
    repo: &Repo,
    release: &NewRelease<'_>,
    draft: &ReleaseRecord,
) -> Result<String> {
    let uploaded = draft.uploaded();
    let missing: Vec<&str> = release
        .assets
        .iter()
        .map(String::as_str)
        .filter(|name| !uploaded.contains(name))
        .collect();
    ensure!(
        missing.is_empty(),
        "the draft release {tag} lacks {missing}, so it stays a draft; rerun release with them in --assets-dir, or with --skip-assets to publish it without them",
        tag = draft.tag_name,
        missing = missing.join(", ")
    );
    let repos = crab.repos(&repo.owner, &repo.name);
    let releases = repos.releases();
    let update = releases
        .update(draft.id)
        .name(release.name)
        .body(release.body)
        .target_commitish(release.sha)
        .draft(false);
    let update = match release.stage {
        Stage::Stable => update.make_latest(MakeLatest::Legacy),
        Stage::Candidate => update.prerelease(true).make_latest(MakeLatest::False),
    };
    let published = update
        .send()
        .await
        .with_context(|| format!("publish the draft release {}", draft.tag_name))?;
    Ok(published.html_url.to_string())
}

/// Prove that `tag` names `head`, reading it again after each of `delays`
/// while GitHub answers 404.
///
/// Publishing a draft creates its tag, and GitHub can serve the tag a moment
/// after the Release. Only a 404 is read again: any other error, and a tag
/// that names another commit, fail at once.
///
/// # Errors
///
/// Returns an error when the GitHub client cannot be built, a read fails with
/// anything but 404, the tag names a commit other than `head`, or every read
/// answers 404. The last names the tag and the number of reads.
pub fn prove_tag(
    token: &str,
    repo: &Repo,
    tag: &str,
    head: &str,
    delays: &[Duration],
) -> Result<()> {
    block(async {
        let crab = client(token)?;
        prove_tag_with(&crab, repo, tag, head, delays).await
    })
}

async fn prove_tag_with(
    crab: &Octocrab,
    repo: &Repo,
    tag: &str,
    head: &str,
    delays: &[Duration],
) -> Result<()> {
    let mut waits = delays.iter();
    let mut reads = 0_usize;
    loop {
        reads += 1;
        if let Some(named) = read_tag(crab, repo, tag).await? {
            ensure!(
                named.eq_ignore_ascii_case(head),
                "tag {tag} names {named}, not HEAD {head}"
            );
            return Ok(());
        }
        let Some(wait) = waits.next() else {
            bail!(
                "GitHub serves no tag {tag} after {reads} reads, though its Release is published; rerun release to read the tag again"
            );
        };
        time::sleep(*wait).await;
    }
}

/// The Release for a vendored set's `tag`, created at `sha` when the tag has
/// none. Returns its HTML URL.
///
/// An existing Release is used as it is.
/// Its tag records which commit built the first asset, and that commit is
/// not a version commit, so the tag target is not checked.
///
/// A new Release is created with `make_latest: false`.
/// GitHub otherwise makes every new published Release the latest of the
/// repository ([create a release]).
/// A vendored library must not displace the Release of the repository itself.
///
/// # Errors
///
/// Returns an error when the GitHub client cannot be built or when reading the
/// Release fails with anything but 404.
/// It also returns one when creating the Release fails for any reason other
/// than another job having created it first.
///
/// [create a release]: https://docs.github.com/en/rest/releases/releases#create-a-release
pub fn ensure_vendored_release(
    token: &str,
    repo: &Repo,
    tag: &str,
    body: &str,
    sha: &str,
) -> Result<String> {
    block(async {
        let crab = client(token)?;
        ensure_vendored_release_with(&crab, repo, tag, body, sha).await
    })
}

/// Every target's job runs this, so two can find the Release missing at once.
/// GitHub refuses one of them with `already_exists`, and that job reads the
/// Release the other created.
async fn ensure_vendored_release_with(
    crab: &Octocrab,
    repo: &Repo,
    tag: &str,
    body: &str,
    sha: &str,
) -> Result<String> {
    let repos = crab.repos(&repo.owner, &repo.name);
    let releases = repos.releases();
    match releases.get_by_tag(tag).await {
        Ok(release) => return Ok(release.html_url.to_string()),
        Err(error) if is_not_found(&error) => {}
        Err(error) => return Err(error).with_context(|| format!("read release {tag}")),
    }
    let created = releases
        .create(tag)
        .name(tag)
        .body(body)
        .target_commitish(sha)
        .make_latest(MakeLatest::False)
        .send()
        .await;
    match created {
        Ok(release) => Ok(release.html_url.to_string()),
        Err(error) if is_already_exists(&error) => {
            let release = releases
                .get_by_tag(tag)
                .await
                .with_context(|| format!("read release {tag}, which another job created"))?;
            Ok(release.html_url.to_string())
        }
        Err(error) => Err(release_error(error, tag, sha)),
    }
}

/// The hex SHA-256 that GitHub stores for asset `name` in the `tag` Release.
/// It comes from the `digest` of the asset (`sha256:<hex>`, see
/// [release assets]).
/// Reading the digest from GitHub, instead of hashing a local file, keeps the
/// checksum matching the stored asset.
/// A rerun's build can differ in bytes from the one GitHub kept.
///
/// # Errors
///
/// Returns an error when the GitHub client cannot be built or the Release
/// cannot be read.
/// It also returns one when the Release does not list `name` or the asset has
/// no SHA-256 digest.
///
/// [release assets]: https://docs.github.com/en/rest/releases/assets
pub fn asset_sha256(token: &str, repo: &Repo, tag: &str, name: &str) -> Result<String> {
    block(async {
        let crab = client(token)?;
        asset_sha256_with(&crab, repo, tag, name).await
    })
}

async fn asset_sha256_with(crab: &Octocrab, repo: &Repo, tag: &str, name: &str) -> Result<String> {
    let release = upload_target(crab, repo, Target::Tag(tag)).await?;
    let asset = release
        .assets
        .iter()
        .find(|asset| asset.name == name)
        .with_context(|| format!("release {tag} does not list asset {name}"))?;
    asset
        .digest
        .as_deref()
        .and_then(|digest| digest.strip_prefix("sha256:"))
        .map(str::to_owned)
        .with_context(|| format!("GitHub reports no SHA-256 digest for asset {name} of {tag}"))
}

/// The names of the assets of the Release of `tag`, draft or published,
/// whose upload completed.
///
/// # Errors
///
/// Returns an error when the GitHub client cannot be built, or when no
/// Release exists for `tag`.
pub fn uploaded_assets(token: &str, repo: &Repo, tag: &str) -> Result<Vec<String>> {
    block(async {
        let crab = client(token)?;
        let release = upload_target(&crab, repo, Target::Tag(tag)).await?;
        Ok(release.uploaded().into_iter().map(str::to_owned).collect())
    })
}

/// A Release asset [`download_release_assets`] saved.
#[derive(Debug)]
#[non_exhaustive]
pub struct AssetFile {
    /// The asset's name, which is the file name it was saved under.
    pub name: String,
    /// Where it was saved.
    pub path: PathBuf,
    /// The SHA-256 GitHub reports for the stored file, in lowercase hex.
    pub sha256: String,
}

/// How long one asset download may take.
const DOWNLOAD_TIMEOUT: Duration = Duration::from_mins(5);

/// Save each of `names` from the Release of `tag`, draft or published, into
/// `dir` under its own name.
///
/// GitHub answers the asset API with a redirect to its storage. The token goes
/// to GitHub only: the client follows no redirect itself, and fetches the
/// storage URL without it ([release assets]).
///
/// # Errors
///
/// Returns an error when the GitHub client cannot be built, the Release does
/// not exist or does not list one of `names`, or GitHub reports no SHA-256
/// digest for one. It also returns one when a download fails or a file cannot
/// be written.
///
/// [release assets]: https://docs.github.com/en/rest/releases/assets#get-a-release-asset
pub fn download_release_assets(
    token: &str,
    repo: &Repo,
    tag: &str,
    names: &[&str],
    dir: &Path,
) -> Result<Vec<AssetFile>> {
    block(async {
        let crab = client(token)?;
        download_release_assets_with(&crab, token, repo, tag, names, dir).await
    })
}

async fn download_release_assets_with(
    crab: &Octocrab,
    token: &str,
    repo: &Repo,
    tag: &str,
    names: &[&str],
    dir: &Path,
) -> Result<Vec<AssetFile>> {
    let release = upload_target(crab, repo, Target::Tag(tag)).await?;
    let http = reqwest::Client::builder()
        .redirect(Policy::none())
        .user_agent(format!("verctl/{}", env!("CARGO_PKG_VERSION")))
        .timeout(DOWNLOAD_TIMEOUT)
        .build()
        .context("HTTP client")?;
    let mut saved = Vec::new();
    for name in names {
        let asset = release
            .assets
            .iter()
            .find(|asset| asset.name == *name)
            .with_context(|| format!("release {tag} does not list asset {name}"))?;
        ensure!(
            !asset.url.is_empty(),
            "GitHub reports no API URL for asset {name} of {tag}"
        );
        let sha256 = asset
            .digest
            .as_deref()
            .and_then(|digest| digest.strip_prefix("sha256:"))
            .map(str::to_owned)
            .with_context(|| {
                format!("GitHub reports no SHA-256 digest for asset {name} of {tag}")
            })?;
        let body = download_asset(&http, token, &asset.url)
            .await
            .with_context(|| format!("download {name} from release {tag}"))?;
        let path = dir.join(name);
        fs::write(&path, &body).with_context(|| path.display().to_string())?;
        saved.push(AssetFile {
            name: (*name).to_owned(),
            path,
            sha256,
        });
    }
    Ok(saved)
}

/// The bytes of the asset at `url`: its API URL with the token, then the
/// storage URL GitHub redirects to, without it. An error names `url` and
/// never the storage URL, whose query string signs the download.
async fn download_asset(http: &reqwest::Client, token: &str, url: &str) -> Result<bytes::Bytes> {
    use reqwest::header::{ACCEPT, LOCATION};
    let response = http
        .get(url)
        .bearer_auth(token)
        .header(ACCEPT, "application/octet-stream")
        .send()
        .await
        .with_context(|| format!("GET {url}"))?;
    let response = if response.status().is_redirection() {
        let location = response
            .headers()
            .get(LOCATION)
            .and_then(|value| value.to_str().ok())
            .with_context(|| format!("GET {url}: a redirect with no Location"))?
            .to_owned();
        http.get(location)
            .send()
            .await
            .map_err(reqwest::Error::without_url)
            .with_context(|| format!("GET the storage URL {url} redirects to"))?
    } else {
        response
    };
    let response = response
        .error_for_status()
        .map_err(reqwest::Error::without_url)
        .with_context(|| format!("GET {url}"))?;
    ensure!(
        response.status().is_success(),
        "GET {url}: unexpected status {}",
        response.status()
    );
    response
        .bytes()
        .await
        .map_err(reqwest::Error::without_url)
        .with_context(|| format!("read {url}"))
}

/// Names the cause of GitHub's 403 for a new Release.
/// Creating a Release takes `contents: write`, plus `workflows: write` when
/// the commit the tag would point at has a `.github/workflows` tree that
/// differs from the default branch.
/// The `X-Accepted-GitHub-Permissions` header of the refusal lists both sets.
///
/// An Actions `GITHUB_TOKEN` can never carry `workflows`, so releasing an
/// older version commit fails once a later commit changes a workflow.
fn release_error(error: octocrab::Error, tag: &str, sha: &str) -> anyhow::Error {
    let forbidden = matches!(
        &error,
        octocrab::Error::GitHub { source, backtrace: _ } if source.status_code.as_u16() == 403
    );
    let error = anyhow::Error::new(error).context("create GitHub release");
    if forbidden {
        error.context(ReleaseRefused {
            tag: tag.to_owned(),
            sha: sha.to_owned(),
        })
    } else {
        error
    }
}

/// GitHub's 403 on creating a Release.
/// The token lacks a permission the commit needs.
/// A rerun with a token that has the permission can still create the Release.
#[derive(Debug)]
struct ReleaseRefused {
    tag: String,
    sha: String,
}

impl fmt::Display for ReleaseRefused {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(
            f,
            "GitHub refused to create {tag} at {sha}. When that commit's .github/workflows differ from the default branch, the Releases API also needs workflows: write, which GITHUB_TOKEN lacks; rerun verctl release at that commit with a token that has it",
            tag = self.tag,
            sha = self.sha
        )
    }
}

async fn require_tag_at(crab: &Octocrab, repo: &Repo, tag: &str, sha: &str) -> Result<()> {
    let named = read_tag(crab, repo, tag)
        .await?
        .with_context(|| format!("tag {tag} does not exist"))?;
    ensure!(
        named.eq_ignore_ascii_case(sha),
        "tag {tag} names {named}, not the published commit {sha}"
    );
    Ok(())
}

/// The commit `tag` names, peeled through an annotated tag, or `None` when
/// GitHub answers 404 for it.
#[expect(
    clippy::wildcard_enum_match_arm,
    reason = "octocrab's ref Object is non_exhaustive, so a catch-all arm is required"
)]
async fn read_tag(crab: &Octocrab, repo: &Repo, tag: &str) -> Result<Option<String>> {
    let git_ref = match crab
        .repos(&repo.owner, &repo.name)
        .get_ref(&Reference::Tag(tag.to_owned()))
        .await
    {
        Ok(git_ref) => git_ref,
        Err(error) if is_not_found(&error) => return Ok(None),
        Err(error) => return Err(lookup_failed(error, format!("read tag {tag}"))),
    };
    match git_ref.object {
        Object::Commit { sha, url: _ } => Ok(Some(sha)),
        Object::Tag {
            sha: tag_sha,
            url: _,
        } => peel_tag(crab, repo, tag, &tag_sha).await.map(Some),
        other => bail!("tag {tag} names {other:?}, not a commit"),
    }
}

#[derive(serde::Deserialize)]
struct TagTarget {
    object: PeeledTarget,
}

#[derive(serde::Deserialize)]
struct PeeledTarget {
    sha: String,
}

async fn peel_tag(crab: &Octocrab, repo: &Repo, tag: &str, tag_sha: &str) -> Result<String> {
    let peeled: TagTarget = crab
        .get(
            format!(
                "/repos/{owner}/{name}/git/tags/{tag_sha}",
                owner = repo.owner,
                name = repo.name
            ),
            None::<&()>,
        )
        .await
        .map_err(|error| lookup_failed(error, format!("peel tag {tag}")))?;
    Ok(peeled.object.sha)
}

/// What GitHub has for one release tag.
///
/// Not `#[non_exhaustive]`: `verctl-release` constructs fixtures directly.
#[derive(Debug, Clone, Default, PartialEq, Eq)]
pub struct ReleaseState {
    /// The commit the tag names, peeled through an annotated tag. `None` when
    /// the tag does not exist.
    pub tag: Option<String>,
    /// Whether a Release exists for the tag, draft or published.
    pub release: bool,
    /// Whether that Release is a draft, which `release` publishes after its
    /// uploads.
    pub draft: bool,
    /// Whether GitHub keeps that Release immutable: once published, its
    /// assets and tag cannot change ([immutable releases]).
    ///
    /// [immutable releases]: https://docs.github.com/en/code-security/supply-chain-security/understanding-your-software-supply-chain/immutable-releases
    pub immutable: bool,
    /// The file names of the Release's assets whose upload completed.
    pub assets: Vec<String>,
    /// The stop record of a draft's body, which the last `release` run that
    /// failed an upload wrote. Display only; a published Release has none.
    pub stop: stop::Record,
}

/// Read the tag and the Release for `tag`, so a plan can tell which parts of a
/// release still need doing.
/// The Release is read even when the tag is missing: a draft has no tag
/// until it is published, so a tagless draft is an incomplete release.
///
/// # Errors
///
/// Returns an error when the GitHub client cannot be built or when GitHub
/// answers a tag or Release lookup with an error other than 404.
/// It also returns one when the tag points at a tree or a blob.
///
/// Only a lookup that GitHub gave no answer to, meaning a transport failure
/// or a 5xx, is a [`lookup::Unavailable`].
/// A 401 from a bad token, a tag on a tree, and a malformed `GITHUB_API_URL`
/// stay unmarked.
///
/// The Releases list comes from `list`, so the lookups of one plan read it
/// once however many tags are missing.
pub fn release_state(
    token: &str,
    repo: &Repo,
    tag: &str,
    list: &ReleaseList,
) -> Result<ReleaseState> {
    block(async {
        let crab = client(token)?;
        release_state_with(&crab, repo, tag, list).await
    })
}

async fn release_state_with(
    crab: &Octocrab,
    repo: &Repo,
    tag: &str,
    list: &ReleaseList,
) -> Result<ReleaseState> {
    let tag_sha = read_tag(crab, repo, tag).await?;
    let release = find_release(crab, repo, tag, list).await?;
    Ok(ReleaseState {
        tag: tag_sha,
        release: release.is_some(),
        draft: release.as_ref().is_some_and(|release| release.draft),
        immutable: release.as_ref().is_some_and(|release| release.immutable),
        assets: release
            .as_ref()
            .map_or_default(|release| release.uploaded().into_iter().map(str::to_owned).collect()),
        stop: release
            .as_ref()
            .filter(|release| release.draft)
            .map_or_default(|release| stop::read(release.body.as_deref().unwrap_or_default())),
    })
}

/// `error` under `context`, marked as a [`lookup::Unavailable`] when GitHub
/// gave no answer.
/// That covers two cases.
/// The request failed in transport (DNS, connect, a timeout, a connection
/// dropped while the body was read).
/// Or GitHub answered with a 5xx or a rate limit after the retries of
/// octocrab.
/// [`lookup::no_answer`] separates those statuses from the rest.
///
/// Any other answer, such as a 401 or a plain 403, stays an error.
///
/// octocrab 0.54.5 turns every non-2xx answer into `GitHub` with its status
/// and headers, whatever the body contains.
/// Its `map_github_error` falls back to the body text when the body is not
/// GitHub JSON.
/// An HTML 502 from a proxy therefore keeps its status.
///
/// A transport failure reaches octocrab as `Service` from the HTTP client.
/// It also arrives as `Hyper` while octocrab reads a body, alone or inside
/// `Service`.
/// `Service` also carries a request that the client blocks before sending.
/// It counts only when an I/O or body error caused it.
fn lookup_failed(error: octocrab::Error, context: String) -> anyhow::Error {
    let refused = matches!(&error, octocrab::Error::GitHub { source, backtrace: _ }
    if lookup::no_answer(
        source.status_code.as_u16(),
        source
            .headers
            .as_ref()
            .and_then(|headers| headers.get("x-ratelimit-remaining"))
            .map(HeaderValue::as_bytes),
    ));
    let body = matches!(
        &error,
        octocrab::Error::Hyper {
            source: _,
            backtrace: _
        }
    );
    let service = matches!(
        &error,
        octocrab::Error::Service {
            source: _,
            backtrace: _
        }
    );
    let error = anyhow::Error::new(error);
    let transport = service
        && error.chain().any(|cause| {
            cause.is::<io::Error>()
                || matches!(
                    cause.downcast_ref::<octocrab::Error>(),
                    Some(octocrab::Error::Hyper {
                        source: _,
                        backtrace: _
                    })
                )
        });
    let error = error.context(context);
    if refused || body || transport {
        lookup::unavailable(error)
    } else {
        error
    }
}

fn is_not_found(error: &octocrab::Error) -> bool {
    matches!(error, octocrab::Error::GitHub { source, backtrace: _ } if source.status_code.as_u16() == 404)
}

/// The part of a Release verctl reads, draft or published.
#[derive(Debug, Clone, serde::Deserialize)]
pub struct ReleaseRecord {
    id: u64,
    html_url: String,
    tag_name: String,
    /// The commit or branch the tag is created at when the Release is
    /// published. GitHub reports it for every Release. A server that does not
    /// report it names no commit, so a draft without it is stale.
    #[serde(default)]
    target_commitish: String,
    draft: bool,
    /// Reported by GitHub for every Release. A server that does not report
    /// it keeps the Release mutable.
    #[serde(default)]
    immutable: bool,
    /// The notes. GitHub reports `null` for a Release with none.
    #[serde(default)]
    body: Option<String>,
    assets: Vec<ForgeAsset>,
}

impl ReleaseRecord {
    /// The Release's id.
    #[must_use]
    pub const fn id(&self) -> u64 {
        self.id
    }

    /// The Release's HTML URL.
    #[must_use]
    pub fn url(&self) -> &str {
        &self.html_url
    }

    /// The names of the assets whose upload completed.
    #[must_use]
    pub fn uploaded(&self) -> Vec<&str> {
        self.assets
            .iter()
            .filter(|asset| asset.state == "uploaded")
            .map(|asset| asset.name.as_str())
            .collect()
    }
}

#[derive(Debug, Clone, serde::Deserialize)]
struct ForgeAsset {
    name: String,
    /// The asset's API URL, which serves the file to a token that can read
    /// the Release, a draft's included. GitHub reports it for every asset.
    #[serde(default)]
    url: String,
    /// `uploaded` once GitHub has the whole file; an upload that broke off
    /// leaves the asset in another state.
    state: String,
    /// `sha256:<hex>` of the stored file. GitHub reports `null` for an asset
    /// it contains no digest for.
    #[serde(default)]
    digest: Option<String>,
}

/// Releases read per page; GitHub's maximum.
const RELEASES_PER_PAGE: usize = 100;

/// Pages of Releases a lookup reads before it stops, so a repository with
/// thousands of Releases costs ten requests instead of one per page.
/// A draft verctl creates is the newest Release, so it is on the first page.
const MAX_RELEASE_PAGES: u32 = 10;

/// The Releases of a repository as `GET /releases` lists them, drafts
/// included, read at most once.
///
/// A run looks up several tags, and a draft has no tag until it is
/// published, so each missing tag would otherwise read the list again, up to
/// ten pages each. The caller has one for the lookups
/// of a run, before it writes anything: a Release the run creates afterwards
/// is not in it.
#[derive(Debug, Default)]
pub struct ReleaseList {
    listed: OnceCell<Vec<ReleaseRecord>>,
}

impl ReleaseList {
    /// The newest Release the list contains for `tag`, reading the list first
    /// when no lookup has yet.
    async fn find(&self, crab: &Octocrab, repo: &Repo, tag: &str) -> Result<Option<ReleaseRecord>> {
        let listed = if let Some(listed) = self.listed.get() {
            listed
        } else {
            let read = list_releases(crab, repo).await?;
            self.listed.get_or_init(|| read)
        };
        Ok(listed
            .iter()
            .find(|release| release.tag_name == tag)
            .cloned())
    }
}

/// Every Release `GET /releases` lists, newest first, which shows drafts to
/// a token with push access ([list releases]), up to [`MAX_RELEASE_PAGES`]
/// pages.
/// A draft verctl creates is the newest Release, so it is on the first page;
/// a draft older than the newest 1000 Releases is not found.
///
/// [list releases]: https://docs.github.com/en/rest/releases/releases#list-releases
async fn list_releases(crab: &Octocrab, repo: &Repo) -> Result<Vec<ReleaseRecord>> {
    let mut listed = Vec::new();
    for page in 1..=MAX_RELEASE_PAGES {
        let releases: Vec<ReleaseRecord> = crab
            .get(
                format!(
                    "/repos/{owner}/{name}/releases?per_page={RELEASES_PER_PAGE}&page={page}",
                    owner = repo.owner,
                    name = repo.name
                ),
                None::<&()>,
            )
            .await
            .map_err(|error| lookup_failed(error, "list releases".to_owned()))?;
        let last = releases.len() < RELEASES_PER_PAGE;
        listed.extend(releases);
        if last {
            break;
        }
    }
    Ok(listed)
}

/// The Release for `tag`, draft or published, or `None`.
///
/// `GET /releases/tags/{tag}` answers for a published Release in one
/// request, even when GitHub serves its new tag a moment later. It returns
/// 404 for a draft ([get a release by tag name]), and only then is the tag
/// looked up in `list`, which a draft is in: a draft has no tag until it is
/// published.
///
/// [get a release by tag name]: https://docs.github.com/en/rest/releases/releases#get-a-release-by-tag-name
async fn find_release(
    crab: &Octocrab,
    repo: &Repo,
    tag: &str,
    list: &ReleaseList,
) -> Result<Option<ReleaseRecord>> {
    let published: Result<ReleaseRecord, _> = crab
        .get(
            format!(
                "/repos/{owner}/{name}/releases/tags/{tag}",
                owner = repo.owner,
                name = repo.name
            ),
            None::<&()>,
        )
        .await;
    match published {
        Ok(found) => return Ok(Some(found)),
        Err(error) if is_not_found(&error) => {}
        Err(error) => return Err(lookup_failed(error, format!("get release {tag}"))),
    }
    list.find(crab, repo, tag).await
}

/// Attach `tarball` to the release for `tag`.
///
/// Returns the download URL, or `already <name>` when GitHub refuses the
/// upload because the release already has a complete asset of that name.
/// The run that got there first, or an earlier attempt of this one, uploaded
/// it.
///
/// # Errors
///
/// Returns an error when:
///
/// - `tarball` has no UTF-8 file name or cannot be read.
/// - The GitHub client cannot be built.
/// - The release for `tag` does not exist.
/// - The asset of that name exists but its upload does not complete within a
///   minute.
/// - The upload fails for a reason other than a duplicate asset.
pub fn upload_release_asset(token: &str, repo: &Repo, tag: &str, tarball: &Path) -> Result<String> {
    upload(token, repo, Target::Tag(tag), tarball)
}

/// [`upload_release_asset`] to the Release `id` of `tag`, which this run
/// opened or found, so the upload never looks the Release up by its tag
/// again: two drafts can share a tag name.
///
/// # Errors
///
/// Returns the errors of [`upload_release_asset`], with the Release read by
/// its id.
pub fn upload_to_release(
    token: &str,
    repo: &Repo,
    id: u64,
    tag: &str,
    tarball: &Path,
) -> Result<String> {
    upload(token, repo, Target::Id { id, tag }, tarball)
}

fn upload(token: &str, repo: &Repo, target: Target<'_>, tarball: &Path) -> Result<String> {
    let name = tarball
        .file_name()
        .and_then(|name| name.to_str())
        .context("asset name")?
        .to_owned();
    let body =
        bytes::Bytes::from(fs::read(tarball).with_context(|| tarball.display().to_string())?);
    block(async {
        let crab = client(token)?;
        upload_release_asset_with(&crab, repo, target, &name, body, &UPLOAD_SETTLE_DELAYS).await
    })
}

/// How long an upload refused as a duplicate waits for the other upload to
/// finish. GitHub lists an asset as soon as its upload starts, in a state
/// other than `uploaded`. A tarball of a few megabytes uploads in seconds, so a
/// minute covers a run that lost the race while the winner was still sending.
const UPLOAD_SETTLE_DELAYS: [Duration; 12] = [Duration::from_secs(5); 12];

/// The Release an upload or a checksum reads.
#[derive(Debug, Clone, Copy)]
enum Target<'a> {
    /// The Release found by its tag, draft or published.
    Tag(&'a str),
    /// The Release `id` of `tag`, which the run uses.
    Id {
        /// The Release id.
        id: u64,
        /// Its tag, for the messages.
        tag: &'a str,
    },
}

/// The Release `target` names.
async fn upload_target(crab: &Octocrab, repo: &Repo, target: Target<'_>) -> Result<ReleaseRecord> {
    match target {
        Target::Tag(tag) => find_release(crab, repo, tag, &ReleaseList::default())
            .await?
            .with_context(|| format!("release {tag} does not exist")),
        Target::Id { id, tag } => crab
            .get(
                format!(
                    "/repos/{owner}/{name}/releases/{id}",
                    owner = repo.owner,
                    name = repo.name
                ),
                None::<&()>,
            )
            .await
            .with_context(|| format!("read release {tag} (id {id})")),
    }
}

async fn upload_release_asset_with(
    crab: &Octocrab,
    repo: &Repo,
    target: Target<'_>,
    name: &str,
    body: bytes::Bytes,
    settle: &[Duration],
) -> Result<String> {
    let tag = match target {
        Target::Tag(tag) | Target::Id { tag, id: _ } => tag,
    };
    let release = upload_target(crab, repo, target).await?;
    if release.uploaded().contains(&name) {
        return Ok(format!("already {name}"));
    }
    let uploaded = crab
        .repos(&repo.owner, &repo.name)
        .releases()
        .upload_asset(release.id, name, body)
        .send()
        .await;
    match uploaded {
        Ok(asset) => Ok(asset.browser_download_url.to_string()),
        // Two runs can release the same commit, and both build every asset.
        // The tarballs differ in bytes (tar records file times), so a digest
        // cannot separate a duplicate from a mismatch. The name carries the
        // version and the target, and the tag fixes the commit, so a complete
        // asset of that name is this asset.
        Err(error) if is_already_exists(&error) => {
            let mut delays = settle.iter();
            loop {
                let release = upload_target(crab, repo, target).await?;
                let asset = release
                    .assets
                    .iter()
                    .find(|asset| asset.name == name)
                    .with_context(|| {
                        format!(
                            "GitHub reports asset {name} exists, but release {tag} does not list it"
                        )
                    })?;
                if asset.state == "uploaded" {
                    return Ok(format!("already {name}"));
                }
                let Some(delay) = delays.next() else {
                    bail!(
                        "release {tag} has asset {name} in state {:?}, not uploaded, after waiting for another upload to finish; delete the asset and rerun",
                        asset.state
                    );
                };
                time::sleep(*delay).await;
            }
        }
        Err(error) => Err(error).context("upload release asset"),
    }
}

/// GitHub's 422 for an upload whose name the release already has, from
/// [upload a release asset].
/// The code is only in the error's body: octocrab displays a GitHub error as
/// "GitHub", so its text never names it.
///
/// [upload a release asset]: https://docs.github.com/en/rest/releases/assets#upload-a-release-asset
fn is_already_exists(error: &octocrab::Error) -> bool {
    matches!(error, octocrab::Error::GitHub { source, backtrace: _ }
    if source.status_code.as_u16() == 422
        && source.errors.iter().flatten().any(|detail| {
            detail.get("code").and_then(serde_json::Value::as_str) == Some("already_exists")
        }))
}

/// Who opened a pull request, and where its head branch lives.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct PullAuthor {
    /// The author's login.
    pub login: String,
    /// GitHub's user `type`: `User` for a person, `Bot` for an app.
    pub kind: String,
    /// The head branch lives outside the repository: a fork, or a branch that
    /// GitHub has dropped. Maintainers push branches to the repository itself.
    pub from_fork: bool,
}

/// The author of pull request `number`, from
/// `GET /repos/{owner}/{repo}/pulls/{number}` ([get a pull request]).
///
/// # Errors
///
/// Returns an error when the GitHub client cannot be built or the request or
/// its decoding fails, for example when pull request `number` does not exist.
///
/// [get a pull request]: https://docs.github.com/en/rest/pulls/pulls#get-a-pull-request
pub fn pull_author(token: &str, repo: &Repo, number: u64) -> Result<PullAuthor> {
    block(async {
        let crab = client(token)?;
        pull_author_with(&crab, repo, number).await
    })
}

async fn pull_author_with(crab: &Octocrab, repo: &Repo, number: u64) -> Result<PullAuthor> {
    #[derive(serde::Deserialize)]
    struct User {
        login: String,
        #[serde(rename = "type")]
        kind: String,
    }
    #[derive(serde::Deserialize)]
    struct HeadRepo {
        full_name: String,
    }
    #[derive(serde::Deserialize)]
    struct Head {
        repo: Option<HeadRepo>,
    }
    #[derive(serde::Deserialize)]
    struct Pull {
        user: User,
        head: Head,
    }
    let route = format!("/repos/{}/{}/pulls/{number}", repo.owner, repo.name);
    let pull: Pull = crab
        .get(route, None::<&()>)
        .await
        .with_context(|| format!("read pull request #{number}"))?;
    let own = format!("{}/{}", repo.owner, repo.name);
    Ok(PullAuthor {
        login: pull.user.login,
        kind: pull.user.kind,
        from_fork: pull
            .head
            .repo
            .is_none_or(|head| !head.full_name.eq_ignore_ascii_case(&own)),
    })
}

/// A workflow run that has not ended.
#[derive(Debug, Clone, PartialEq, Eq)]
#[non_exhaustive]
pub struct ActiveRun {
    /// The run's page on GitHub.
    pub url: String,
}

/// The first run of the workflow file `workflow` at commit `sha` that has not
/// ended, from `GET /repos/{owner}/{repo}/actions/workflows/{workflow}/runs`
/// with `head_sha` ([list workflow runs]). The first 100 runs of that commit
/// are read, and the commit is checked again on each, so a server that
/// ignores the filter finds no run for another commit.
///
/// A run has not ended unless its `status` is `completed`, so a status GitHub
/// adds later, or none at all, counts as running.
///
/// # Errors
///
/// Returns an error when the GitHub client cannot be built or the request or
/// its decoding fails, for example when no workflow file has that name. Only
/// a lookup that GitHub gave no answer to is a [`lookup::Unavailable`].
///
/// [list workflow runs]: https://docs.github.com/en/rest/actions/workflow-runs#list-workflow-runs-for-a-workflow
pub fn active_run(
    token: &str,
    repo: &Repo,
    workflow: &str,
    sha: &str,
) -> Result<Option<ActiveRun>> {
    #[derive(serde::Deserialize)]
    struct Run {
        html_url: String,
        head_sha: String,
        status: Option<String>,
    }
    #[derive(serde::Deserialize)]
    struct Runs {
        workflow_runs: Vec<Run>,
    }
    block(async {
        let crab = client(token)?;
        let runs: Runs = crab
            .get(
                format!(
                    "/repos/{owner}/{name}/actions/workflows/{workflow}/runs?head_sha={sha}&per_page=100",
                    owner = repo.owner,
                    name = repo.name
                ),
                None::<&()>,
            )
            .await
            .map_err(|error| lookup_failed(error, format!("list the runs of {workflow}")))?;
        Ok(runs
            .workflow_runs
            .into_iter()
            .find(|run| {
                run.head_sha.eq_ignore_ascii_case(sha) && run.status.as_deref() != Some("completed")
            })
            .map(|run| ActiveRun { url: run.html_url }))
    })
}

/// The labels of pull request `number`, from
/// `GET /repos/{owner}/{repo}/pulls/{number}` ([get a pull request]).
///
/// # Errors
///
/// Returns an error when the GitHub client cannot be built or the request or
/// its decoding fails, for example when pull request `number` does not exist.
///
/// [get a pull request]: https://docs.github.com/en/rest/pulls/pulls#get-a-pull-request
pub fn pull_labels(token: &str, repo: &Repo, number: u64) -> Result<Vec<String>> {
    #[derive(serde::Deserialize)]
    struct Label {
        name: String,
    }
    #[derive(serde::Deserialize)]
    struct Pull {
        labels: Vec<Label>,
    }
    block(async {
        let crab = client(token)?;
        let pull: Pull = crab
            .get(
                format!(
                    "/repos/{owner}/{name}/pulls/{number}",
                    owner = repo.owner,
                    name = repo.name
                ),
                None::<&()>,
            )
            .await
            .with_context(|| format!("read pull request #{number}"))?;
        Ok(pull.labels.into_iter().map(|label| label.name).collect())
    })
}

/// The `type` of each rule that applies to `branch`, from
/// `GET /repos/{owner}/{repo}/rules/branches/{branch}` ([get rules for a
/// branch]). The list is empty when no rule applies.
///
/// # Errors
///
/// Returns an error when the GitHub client cannot be built or the request or
/// its decoding fails, including the 403 and 404 answers of a token that
/// cannot read the rules.
///
/// [get rules for a branch]: https://docs.github.com/en/rest/repos/rules#get-rules-for-a-branch
pub fn branch_rule_types(token: &str, repo: &Repo, branch: &str) -> Result<Vec<String>> {
    #[derive(serde::Deserialize)]
    struct Rule {
        #[serde(rename = "type")]
        kind: String,
    }
    block(async {
        let crab = client(token)?;
        let rules: Vec<Rule> = crab
            .get(
                format!(
                    "/repos/{owner}/{name}/rules/branches/{branch}",
                    owner = repo.owner,
                    name = repo.name
                ),
                None::<&()>,
            )
            .await
            .with_context(|| format!("read the rules of {branch}"))?;
        Ok(rules.into_iter().map(|rule| rule.kind).collect())
    })
}

/// A GitHub client for `token`.
/// It uses the API from `GITHUB_API_URL` when that is set, as on a GitHub
/// Enterprise Server or a test's mock server.
/// Otherwise it uses api.github.com.
fn client(token: &str) -> Result<Octocrab> {
    let mut builder = Octocrab::builder().personal_token(token.to_owned());
    if let Ok(base) = env::var("GITHUB_API_URL")
        && !base.is_empty()
    {
        builder = builder.base_uri(base).context("GITHUB_API_URL")?;
    }
    builder.build().context("GitHub client")
}

/// Run one future to completion on a fresh current-thread runtime, so the
/// blocking command handlers can call async clients.
/// Request a GitHub Actions OIDC JWT from `request_url` for `audience`, using
/// bearer `request_token`, without exposing the token or URL query string in
/// any error message.
///
/// # Errors
///
/// Returns an error when the HTTP client cannot be built, the request fails,
/// or the JSON body contains no `value` token field.
pub fn fetch_oidc_token(
    request_url: &str,
    request_token: &str,
    audience: &str,
    url_env_name: &str,
    timeout: Duration,
) -> Result<String> {
    #[derive(serde::Deserialize)]
    struct Issued {
        value: String,
    }
    block(async {
        let http = reqwest::Client::builder()
            .user_agent(format!("verctl/{}", env!("CARGO_PKG_VERSION")))
            .timeout(timeout)
            .build()
            .context("HTTP client")?;
        let separator = if request_url.contains('?') { '&' } else { '?' };
        let response = http
            .get(format!("{request_url}{separator}audience={audience}"))
            .bearer_auth(request_token)
            .send()
            .await
            .and_then(reqwest::Response::error_for_status)
            .map_err(reqwest::Error::without_url)
            .with_context(|| format!("request the OIDC token from {url_env_name}"))?;
        let body = response
            .bytes()
            .await
            .map_err(reqwest::Error::without_url)
            .with_context(|| format!("read the OIDC token from {url_env_name}"))?;
        let issued: Issued = serde_json::from_slice(&body)
            .ok()
            .with_context(|| format!("the answer of {url_env_name} has no OIDC token"))?;
        Ok(issued.value)
    })
}

fn block<F, T>(fut: F) -> Result<T>
where
    F: Future<Output = Result<T>>,
{
    Builder::new_current_thread()
        .enable_all()
        .build()
        .context("tokio")?
        .block_on(fut)
}

#[cfg(test)]
mod tests {
    use std::fs;
    use std::time::Duration;

    use indoc::indoc;
    use octocrab::service::middleware::retry::RetryConfig;
    use verctl_core::stop::{Record, Stop};
    use wiremock::matchers::{body_partial_json, header, method, path, path_regex, query_param};
    use wiremock::{Mock, MockServer, ResponseTemplate};

    use super::{Octocrab, ReleaseList, parse_remote, parse_slug};

    #[test]
    fn slug_and_remotes() {
        let expected = super::Repo {
            owner: "victor-software-house".into(),
            name: "verctl".into(),
        };
        assert_eq!(
            parse_slug("victor-software-house/verctl").unwrap(),
            expected
        );
        assert_eq!(
            parse_remote("https://github.com/victor-software-house/verctl.git").unwrap(),
            expected
        );
        assert_eq!(
            parse_remote("git@github.com:victor-software-house/verctl.git").unwrap(),
            expected
        );
        assert_eq!(
            parse_remote("ssh://git@github.com/victor-software-house/verctl.git").unwrap(),
            expected
        );
    }

    #[test]
    fn pull_request_number_reads_only_a_pull_request_event() {
        assert_eq!(
            super::pull_request_number(r#"{"pull_request":{"number":187,"labels":[]}}"#),
            Some(187)
        );
        assert_eq!(super::pull_request_number("{}"), None);
        assert_eq!(super::pull_request_number("not json"), None);
        assert_eq!(
            super::pull_request_number(r#"{"issue":{"number":187}}"#),
            None
        );
    }

    #[test]
    fn is_merge_group_reads_only_a_merge_group_event() {
        assert!(super::is_merge_group(
            r#"{"action":"checks_requested","merge_group":{"head_ref":"refs/heads/gh-readonly-queue/main/pr-7-0000000000000000000000000000000000000001"}}"#
        ));
        assert!(!super::is_merge_group(r#"{"pull_request":{"number":7}}"#));
        assert!(!super::is_merge_group(r#"{"merge_group":null}"#));
        assert!(!super::is_merge_group("not json"));
    }

    #[test]
    fn default_branch_of_reads_the_event_repository() {
        assert_eq!(
            super::default_branch_of(
                r#"{"pull_request":{"number":1},"repository":{"default_branch":"main"}}"#
            ),
            Some("main".to_owned())
        );
        assert_eq!(
            super::default_branch_of(r#"{"repository":{"default_branch":""}}"#),
            None
        );
        assert_eq!(super::default_branch_of("{}"), None);
        assert_eq!(super::default_branch_of("not json"), None);
    }

    async fn pull_author_from(head: serde_json::Value) -> super::PullAuthor {
        let server = MockServer::start().await;
        Mock::given(method("GET"))
            .and(path(format!("/repos/{OWNER}/{NAME}/pulls/12")))
            .respond_with(ResponseTemplate::new(200).set_body_json(serde_json::json!({
                "number": 12,
                "user": { "login": "octo", "type": "User" },
                "head": head
            })))
            .mount(&server)
            .await;
        super::pull_author_with(&crab(&server.uri()), &repo(), 12)
            .await
            .unwrap()
    }

    #[tokio::test]
    async fn a_fork_head_is_a_fork() {
        let author =
            pull_author_from(serde_json::json!({ "repo": { "full_name": "octo/app" } })).await;
        assert_eq!(author.login, "octo");
        assert_eq!(author.kind, "User");
        assert!(author.from_fork);
    }

    #[tokio::test]
    async fn a_head_in_the_repository_is_not_a_fork() {
        let author = pull_author_from(serde_json::json!({
            "repo": { "full_name": format!("{OWNER}/{NAME}") }
        }))
        .await;
        assert!(!author.from_fork);
    }

    #[tokio::test]
    async fn a_deleted_fork_is_a_fork() {
        let author = pull_author_from(serde_json::json!({ "repo": null })).await;
        assert!(author.from_fork);
    }

    #[test]
    fn rejects_non_github() {
        parse_remote("https://gitlab.com/acme/app.git").unwrap_err();
    }

    const OWNER: &str = "acme";
    const NAME: &str = "app";
    const TAG: &str = "v1.0.0";
    const PUBLISHED: &str = "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa";
    const OTHER: &str = "bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb";
    const TAG_OBJECT: &str = "cccccccccccccccccccccccccccccccccccccccc";

    fn repo() -> super::Repo {
        super::Repo {
            owner: OWNER.into(),
            name: NAME.into(),
        }
    }

    fn crab(uri: &str) -> Octocrab {
        Octocrab::builder()
            .personal_token("token".to_owned())
            .base_uri(uri)
            .unwrap()
            .build()
            .unwrap()
    }

    fn missing_release() -> Mock {
        Mock::given(method("GET"))
            .and(path(format!("/repos/{OWNER}/{NAME}/releases/tags/{TAG}")))
            .respond_with(ResponseTemplate::new(404).set_body_json(serde_json::json!({
                "message": "Not Found",
                "documentation_url": "https://docs.github.com"
            })))
    }

    /// `GET /releases`, the only listing that shows drafts. The lookup reads
    /// it when `GET /releases/tags/{tag}` answers 404.
    fn listed_releases(listed: serde_json::Value) -> Mock {
        Mock::given(method("GET"))
            .and(path(format!("/repos/{OWNER}/{NAME}/releases")))
            .respond_with(ResponseTemplate::new(200).set_body_json(listed))
    }

    fn no_releases_listed() -> Mock {
        listed_releases(serde_json::json!([]))
    }

    fn existing_release() -> Mock {
        Mock::given(method("GET"))
            .and(path(format!("/repos/{OWNER}/{NAME}/releases/tags/{TAG}")))
            .respond_with(ResponseTemplate::new(200).set_body_json(release_json("main")))
    }

    /// A draft that contains `assets`, each a name and the state GitHub
    /// reports.
    fn draft_json(assets: &[(&str, &str)]) -> serde_json::Value {
        let mut json = release_json(PUBLISHED);
        json["draft"] = true.into();
        json["html_url"] =
            format!("https://github.com/{OWNER}/{NAME}/releases/tag/untagged-1").into();
        json["assets"] = assets
            .iter()
            .map(|(name, state)| serde_json::json!({ "name": name, "state": state }))
            .collect();
        json
    }

    fn declared() -> Vec<String> {
        vec![
            "app.pkg".to_owned(),
            "app_1.0.0_linux_x64.tar.gz".to_owned(),
        ]
    }

    /// `stable()` with the assets `declared()` names.
    fn with_assets(declared: &[String]) -> super::NewRelease<'_> {
        super::NewRelease {
            assets: declared,
            ..stable()
        }
    }

    fn create_tag_ref() -> Mock {
        Mock::given(method("POST"))
            .and(path(format!("/repos/{OWNER}/{NAME}/git/refs")))
            .and(body_partial_json(serde_json::json!({
                "ref": format!("refs/tags/{TAG}"),
                "sha": PUBLISHED
            })))
            .respond_with(ResponseTemplate::new(201).set_body_json(serde_json::json!({
                "ref": format!("refs/tags/{TAG}"),
                "node_id": "R",
                "url": format!("https://api.github.com/repos/{OWNER}/{NAME}/git/refs/tags/{TAG}"),
                "object": {
                    "type": "commit",
                    "sha": PUBLISHED,
                    "url": format!("https://api.github.com/repos/{OWNER}/{NAME}/git/commits/{PUBLISHED}")
                }
            })))
    }

    fn create_draft() -> Mock {
        Mock::given(method("POST"))
            .and(path(format!("/repos/{OWNER}/{NAME}/releases")))
            .and(body_partial_json(serde_json::json!({
                "tag_name": TAG,
                "draft": true,
                "target_commitish": PUBLISHED
            })))
            .respond_with(ResponseTemplate::new(201).set_body_json(draft_json(&[])))
    }

    fn publish_draft() -> wiremock::MockBuilder {
        Mock::given(method("PATCH"))
            .and(path(format!("/repos/{OWNER}/{NAME}/releases/1")))
            .and(body_partial_json(serde_json::json!({ "draft": false })))
    }

    fn create_at_published_sha() -> Mock {
        Mock::given(method("POST"))
            .and(path(format!("/repos/{OWNER}/{NAME}/releases")))
            .and(body_partial_json(serde_json::json!({
                "tag_name": TAG,
                "target_commitish": PUBLISHED
            })))
            .respond_with(ResponseTemplate::new(201).set_body_json(release_json("main")))
    }

    fn stable() -> super::NewRelease<'static> {
        super::NewRelease {
            tag: TAG,
            name: TAG,
            body: "notes",
            sha: PUBLISHED,
            stage: super::Stage::Stable,
            assets: &[],
        }
    }

    fn lightweight_tag(sha: &str) -> Mock {
        Mock::given(method("GET"))
            .and(path(format!("/repos/{OWNER}/{NAME}/git/ref/tags/{TAG}")))
            .respond_with(ResponseTemplate::new(200).set_body_json(serde_json::json!({
                "ref": format!("refs/tags/{TAG}"),
                "node_id": "R",
                "url": format!("https://api.github.com/repos/{OWNER}/{NAME}/git/refs/tags/{TAG}"),
                "object": {
                    "type": "commit",
                    "sha": sha,
                    "url": format!("https://api.github.com/repos/{OWNER}/{NAME}/git/commits/{sha}")
                }
            })))
    }

    fn annotated_tag() -> Mock {
        Mock::given(method("GET"))
            .and(path(format!("/repos/{OWNER}/{NAME}/git/ref/tags/{TAG}")))
            .respond_with(ResponseTemplate::new(200).set_body_json(serde_json::json!({
                "ref": format!("refs/tags/{TAG}"),
                "node_id": "R",
                "url": format!("https://api.github.com/repos/{OWNER}/{NAME}/git/refs/tags/{TAG}"),
                "object": {
                    "type": "tag",
                    "sha": TAG_OBJECT,
                    "url": format!("https://api.github.com/repos/{OWNER}/{NAME}/git/tags/{TAG_OBJECT}")
                }
            })))
    }

    fn peeled_tag_object(sha: &str) -> Mock {
        Mock::given(method("GET"))
            .and(path(format!("/repos/{OWNER}/{NAME}/git/tags/{TAG_OBJECT}")))
            .respond_with(ResponseTemplate::new(200).set_body_json(serde_json::json!({
                "node_id": "T",
                "tag": TAG,
                "sha": TAG_OBJECT,
                "url": format!("https://api.github.com/repos/{OWNER}/{NAME}/git/tags/{TAG_OBJECT}"),
                "message": TAG,
                "object": {
                    "type": "commit",
                    "sha": sha,
                    "url": format!("https://api.github.com/repos/{OWNER}/{NAME}/git/commits/{sha}")
                }
            })))
    }

    fn release_json(target_commitish: &str) -> serde_json::Value {
        serde_json::json!({
            "url": format!("https://api.github.com/repos/{OWNER}/{NAME}/releases/1"),
            "html_url": format!("https://github.com/{OWNER}/{NAME}/releases/tag/{TAG}"),
            "assets_url": format!("https://api.github.com/repos/{OWNER}/{NAME}/releases/1/assets"),
            "upload_url": format!("https://uploads.github.com/repos/{OWNER}/{NAME}/releases/1/assets{{?name,label}}"),
            "tarball_url": format!("https://api.github.com/repos/{OWNER}/{NAME}/tarball/{TAG}"),
            "zipball_url": format!("https://api.github.com/repos/{OWNER}/{NAME}/zipball/{TAG}"),
            "id": 1,
            "node_id": "R",
            "tag_name": TAG,
            "target_commitish": target_commitish,
            "name": TAG,
            "body": "notes",
            "draft": false,
            "prerelease": false,
            "created_at": "2026-08-22T00:00:00Z",
            "published_at": "2026-08-22T00:00:00Z",
            "assets": []
        })
    }

    fn release_with_assets(assets: &[(&str, &str)]) -> Mock {
        let mut json = release_json("main");
        json["assets"] = assets
            .iter()
            .map(|(name, state)| serde_json::json!({ "name": name, "state": state }))
            .collect();
        Mock::given(method("GET"))
            .and(path(format!("/repos/{OWNER}/{NAME}/releases/tags/{TAG}")))
            .respond_with(ResponseTemplate::new(200).set_body_json(json))
    }

    fn missing_tag() -> Mock {
        Mock::given(method("GET"))
            .and(path(format!("/repos/{OWNER}/{NAME}/git/ref/tags/{TAG}")))
            .respond_with(ResponseTemplate::new(404).set_body_json(serde_json::json!({
                "message": "Not Found",
                "documentation_url": "https://docs.github.com"
            })))
    }

    #[tokio::test]
    async fn a_release_never_made_has_no_tag_and_no_release() {
        let server = MockServer::start().await;
        missing_tag().mount(&server).await;
        missing_release().expect(1).mount(&server).await;
        no_releases_listed().expect(1).mount(&server).await;
        let state =
            super::release_state_with(&crab(&server.uri()), &repo(), TAG, &ReleaseList::default())
                .await
                .unwrap();
        assert_eq!(state, super::ReleaseState::default());
    }

    #[tokio::test]
    async fn a_finished_release_names_its_commit_and_assets() {
        let server = MockServer::start().await;
        lightweight_tag(PUBLISHED).mount(&server).await;
        release_with_assets(&[
            ("app-darwin-arm64.tar.gz", "uploaded"),
            ("app-linux-x64.tar.gz", "uploaded"),
            ("app.pkg", "starter"),
        ])
        .mount(&server)
        .await;
        let state =
            super::release_state_with(&crab(&server.uri()), &repo(), TAG, &ReleaseList::default())
                .await
                .unwrap();
        assert_eq!(state.tag.as_deref(), Some(PUBLISHED));
        assert!(state.release);
        assert!(!state.draft);
        assert_eq!(
            state.assets,
            ["app-darwin-arm64.tar.gz", "app-linux-x64.tar.gz"]
        );
    }

    #[tokio::test]
    async fn an_immutable_release_is_read_as_immutable() {
        let server = MockServer::start().await;
        lightweight_tag(PUBLISHED).mount(&server).await;
        let mut json = release_json("main");
        json["immutable"] = true.into();
        Mock::given(method("GET"))
            .and(path(format!("/repos/{OWNER}/{NAME}/releases/tags/{TAG}")))
            .respond_with(ResponseTemplate::new(200).set_body_json(json))
            .mount(&server)
            .await;
        let state =
            super::release_state_with(&crab(&server.uri()), &repo(), TAG, &ReleaseList::default())
                .await
                .unwrap();
        assert!(
            state.release && !state.draft && state.immutable,
            "{state:?}"
        );
    }

    /// `GET /releases/tags/{tag}` answers 404 for a draft, so the lookup reads
    /// the list, and only an asset in state `uploaded` counts.
    #[tokio::test]
    async fn a_draft_is_found_through_the_release_list() {
        let server = MockServer::start().await;
        lightweight_tag(PUBLISHED).mount(&server).await;
        missing_release().mount(&server).await;
        let mut other = release_json("main");
        other["tag_name"] = "v0.9.0".into();
        listed_releases(serde_json::json!([
            other,
            draft_json(&[
                ("app.pkg", "uploaded"),
                ("app_1.0.0_linux_x64.tar.gz", "starter")
            ])
        ]))
        .mount(&server)
        .await;
        let state =
            super::release_state_with(&crab(&server.uri()), &repo(), TAG, &ReleaseList::default())
                .await
                .unwrap();
        assert!(
            state.release && state.draft && !state.immutable,
            "{state:?}"
        );
        assert_eq!(state.assets, ["app.pkg"]);
    }

    /// A tag with no Release opens a draft at HEAD, and no tag is created:
    /// GitHub creates it when the draft is published.
    #[tokio::test]
    async fn a_missing_release_opens_a_draft_at_head_with_no_tag() {
        let server = MockServer::start().await;
        create_tag_ref().expect(0).mount(&server).await;
        create_draft().expect(1).mount(&server).await;
        let declared = declared();
        let id = super::open_draft_with(
            &crab(&server.uri()),
            &repo(),
            &with_assets(&declared),
            &super::DraftState::Missing,
        )
        .await
        .unwrap();
        assert_eq!(id, 1);
    }

    #[tokio::test]
    async fn a_release_with_no_assets_is_published_at_once() {
        let server = MockServer::start().await;
        missing_release().mount(&server).await;
        no_releases_listed().mount(&server).await;
        lightweight_tag(PUBLISHED).mount(&server).await;
        Mock::given(method("POST"))
            .and(path(format!("/repos/{OWNER}/{NAME}/releases")))
            .and(body_partial_json(serde_json::json!({
                "tag_name": TAG,
                "target_commitish": PUBLISHED
            })))
            .and(|request: &wiremock::Request| {
                let body: serde_json::Value = serde_json::from_slice(&request.body).unwrap();
                body.get("draft").is_none()
            })
            .respond_with(ResponseTemplate::new(201).set_body_json(release_json("main")))
            .expect(1)
            .mount(&server)
            .await;
        create_tag_ref().expect(0).mount(&server).await;
        let url = super::ensure_release_with(
            &crab(&server.uri()),
            &repo(),
            &stable(),
            super::PackageUpload::Shipped,
        )
        .await
        .unwrap();
        assert!(url.contains(TAG), "{url}");
    }

    /// The draft as `GET /releases/{id}` returns it, containing `assets`.
    fn draft_by_id(assets: &[(&str, &str)]) -> Mock {
        Mock::given(method("GET"))
            .and(path(format!("/repos/{OWNER}/{NAME}/releases/1")))
            .respond_with(ResponseTemplate::new(200).set_body_json(draft_json(assets)))
    }

    /// The update sends this run's title, notes and commit, so a draft
    /// someone edited reads as this run would have written it.
    #[tokio::test]
    async fn a_draft_with_every_asset_uploaded_is_published() {
        let server = MockServer::start().await;
        draft_by_id(&[
            ("app.pkg", "uploaded"),
            ("app_1.0.0_linux_x64.tar.gz", "uploaded"),
        ])
        .mount(&server)
        .await;
        publish_draft()
            .and(body_partial_json(serde_json::json!({
                "name": TAG,
                "body": "notes",
                "target_commitish": PUBLISHED,
                "make_latest": "legacy"
            })))
            .respond_with(ResponseTemplate::new(200).set_body_json(release_json(PUBLISHED)))
            .expect(1)
            .mount(&server)
            .await;
        let declared = declared();
        let url =
            super::publish_draft_with(&crab(&server.uri()), &repo(), &with_assets(&declared), 1)
                .await
                .unwrap();
        assert_eq!(
            url,
            format!("https://github.com/{OWNER}/{NAME}/releases/tag/{TAG}")
        );
    }

    #[tokio::test]
    async fn a_candidate_draft_is_published_as_a_prerelease_that_is_never_the_latest() {
        let server = MockServer::start().await;
        draft_by_id(&[("app.pkg", "uploaded")]).mount(&server).await;
        Mock::given(method("PATCH"))
            .and(path(format!("/repos/{OWNER}/{NAME}/releases/1")))
            .and(body_partial_json(serde_json::json!({
                "draft": false,
                "prerelease": true,
                "make_latest": "false"
            })))
            .respond_with(ResponseTemplate::new(200).set_body_json(release_json(PUBLISHED)))
            .expect(1)
            .mount(&server)
            .await;
        let declared = ["app.pkg".to_owned()];
        let candidate = super::NewRelease {
            stage: super::Stage::Candidate,
            ..with_assets(&declared)
        };
        super::publish_draft_with(&crab(&server.uri()), &repo(), &candidate, 1)
            .await
            .unwrap();
    }

    /// Only an asset in state `uploaded` counts, and a draft that lacks one is
    /// never published.
    #[tokio::test]
    async fn a_draft_missing_an_asset_is_not_published_and_names_what_it_lacks() {
        let server = MockServer::start().await;
        draft_by_id(&[
            ("app.pkg", "uploaded"),
            ("app_1.0.0_linux_x64.tar.gz", "starter"),
        ])
        .mount(&server)
        .await;
        publish_draft()
            .respond_with(ResponseTemplate::new(500))
            .expect(0)
            .mount(&server)
            .await;
        let declared = declared();
        let error =
            super::publish_draft_with(&crab(&server.uri()), &repo(), &with_assets(&declared), 1)
                .await
                .unwrap_err();
        let message = format!("{error:#}");
        assert!(
            message.contains(&format!("{TAG} lacks app_1.0.0_linux_x64.tar.gz")),
            "{message}"
        );
    }

    async fn found(server: &MockServer) -> anyhow::Result<super::ExistingRelease> {
        super::read_release_with(
            &crab(&server.uri()),
            &repo(),
            TAG,
            PUBLISHED,
            &ReleaseList::default(),
        )
        .await
    }

    /// A tag on another commit fails before any write, whatever its Release:
    /// publishing a draft keeps an existing tag where it is.
    #[tokio::test]
    async fn a_tag_on_another_commit_fails_before_any_write() {
        let server = MockServer::start().await;
        missing_release().mount(&server).await;
        lightweight_tag(OTHER).mount(&server).await;
        listed_releases(serde_json::json!([draft_json(&[])]))
            .mount(&server)
            .await;
        let message = format!("{:#}", found(&server).await.unwrap_err());
        assert!(message.contains(OTHER), "{message}");
        assert!(message.contains(PUBLISHED), "{message}");
    }

    #[tokio::test]
    async fn a_draft_at_head_is_kept() {
        let server = MockServer::start().await;
        missing_tag().mount(&server).await;
        missing_release().mount(&server).await;
        listed_releases(serde_json::json!([draft_json(&[("app.pkg", "uploaded")])]))
            .mount(&server)
            .await;
        let super::ExistingRelease::DraftState(draft @ super::DraftState::AtHead(_)) =
            found(&server).await.unwrap()
        else {
            panic!("a draft at HEAD");
        };
        assert_eq!(draft.uploaded(), ["app.pkg"]);
    }

    /// A draft at a branch name, as one created with GitHub's default target,
    /// is stale, and none of its assets count.
    #[tokio::test]
    async fn a_draft_at_another_commit_is_stale() {
        let server = MockServer::start().await;
        missing_tag().mount(&server).await;
        missing_release().mount(&server).await;
        let mut stale = draft_json(&[("app.pkg", "uploaded")]);
        stale["target_commitish"] = "main".into();
        listed_releases(serde_json::json!([stale]))
            .mount(&server)
            .await;
        let super::ExistingRelease::DraftState(draft @ super::DraftState::Stale(_)) =
            found(&server).await.unwrap()
        else {
            panic!("a stale draft");
        };
        assert_eq!(draft.uploaded(), Vec::<&str>::new());
    }

    /// GitHub can answer 404 for a tag a moment after the Release that created
    /// it is published. A Release published at HEAD then counts as at HEAD.
    #[tokio::test]
    async fn a_release_published_at_head_before_its_tag_is_served_counts_as_published() {
        let server = MockServer::start().await;
        missing_tag().mount(&server).await;
        Mock::given(method("GET"))
            .and(path(format!("/repos/{OWNER}/{NAME}/releases/tags/{TAG}")))
            .respond_with(ResponseTemplate::new(200).set_body_json(release_json(PUBLISHED)))
            .mount(&server)
            .await;
        assert!(
            matches!(
                found(&server).await.unwrap(),
                super::ExistingRelease::Published(_)
            ),
            "published at HEAD"
        );
    }

    #[tokio::test]
    async fn a_release_published_elsewhere_with_no_tag_fails() {
        let server = MockServer::start().await;
        missing_tag().mount(&server).await;
        Mock::given(method("GET"))
            .and(path(format!("/repos/{OWNER}/{NAME}/releases/tags/{TAG}")))
            .respond_with(ResponseTemplate::new(200).set_body_json(release_json(OTHER)))
            .mount(&server)
            .await;
        let message = format!("{:#}", found(&server).await.unwrap_err());
        assert!(message.contains(OTHER), "{message}");
        assert!(message.contains(PUBLISHED), "{message}");
    }

    /// A stale draft is deleted before the draft at HEAD is created.
    #[tokio::test]
    async fn a_stale_draft_is_deleted_and_created_again_at_head() {
        let server = MockServer::start().await;
        Mock::given(method("DELETE"))
            .and(path(format!("/repos/{OWNER}/{NAME}/releases/7")))
            .respond_with(ResponseTemplate::new(204))
            .expect(1)
            .mount(&server)
            .await;
        create_draft().expect(1).mount(&server).await;
        let mut stale = draft_json(&[]);
        stale["id"] = 7.into();
        stale["target_commitish"] = OTHER.into();
        let stale = serde_json::from_value(stale).unwrap();
        let id = super::open_draft_with(
            &crab(&server.uri()),
            &repo(),
            &stable(),
            &super::DraftState::Stale(stale),
        )
        .await
        .unwrap();
        assert_eq!(id, 1);
        let methods: Vec<String> = server
            .received_requests()
            .await
            .unwrap()
            .iter()
            .map(|request| request.method.to_string())
            .collect();
        assert_eq!(methods, ["DELETE", "POST"]);
    }

    /// A 403 on the draft names the permission, and the run stops there,
    /// before any upload.
    #[tokio::test]
    async fn a_forbidden_draft_names_the_workflows_permission() {
        let server = MockServer::start().await;
        Mock::given(method("POST"))
            .and(path(format!("/repos/{OWNER}/{NAME}/releases")))
            .respond_with(ResponseTemplate::new(403).set_body_json(serde_json::json!({
                "message": "Resource not accessible by integration",
                "documentation_url": "https://docs.github.com/rest/releases/releases#create-a-release"
            })))
            .mount(&server)
            .await;
        let error = super::open_draft_with(
            &crab(&server.uri()),
            &repo(),
            &stable(),
            &super::DraftState::Missing,
        )
        .await
        .unwrap_err();
        let message = format!("{error:#}");
        assert!(message.contains("workflows: write"), "{message}");
        assert!(
            error.downcast_ref::<super::ReleaseRefused>().is_some(),
            "{message}"
        );
    }

    #[tokio::test]
    async fn a_draft_at_head_is_used_as_it_is() {
        let server = MockServer::start().await;
        let draft = serde_json::from_value(draft_json(&[])).unwrap();
        let id = super::open_draft_with(
            &crab(&server.uri()),
            &repo(),
            &stable(),
            &super::DraftState::AtHead(draft),
        )
        .await
        .unwrap();
        assert_eq!(id, 1);
        assert_eq!(server.received_requests().await.unwrap().len(), 0);
    }

    const NO_WAIT: [Duration; 4] = [Duration::ZERO; 4];

    async fn reads_of_the_tag(server: &MockServer) -> usize {
        server.received_requests().await.unwrap().len()
    }

    #[tokio::test]
    async fn the_tag_proof_reads_again_after_a_404() {
        let server = MockServer::start().await;
        missing_tag().up_to_n_times(1).mount(&server).await;
        lightweight_tag(PUBLISHED).mount(&server).await;
        super::prove_tag_with(&crab(&server.uri()), &repo(), TAG, PUBLISHED, &NO_WAIT)
            .await
            .unwrap();
        assert_eq!(reads_of_the_tag(&server).await, 2);
    }

    #[tokio::test]
    async fn the_tag_proof_fails_after_five_404s() {
        let server = MockServer::start().await;
        missing_tag().mount(&server).await;
        let error = super::prove_tag_with(&crab(&server.uri()), &repo(), TAG, PUBLISHED, &NO_WAIT)
            .await
            .unwrap_err();
        let message = format!("{error:#}");
        assert!(message.contains(&format!("no tag {TAG}")), "{message}");
        assert!(message.contains("after 5 reads"), "{message}");
        assert_eq!(reads_of_the_tag(&server).await, 5);
    }

    /// Any error but a 404 fails at once. octocrab retries a 5xx itself, so
    /// the client here makes one request per read.
    #[tokio::test]
    async fn the_tag_proof_fails_at_once_on_any_other_error() {
        let server = MockServer::start().await;
        Mock::given(method("GET"))
            .and(path(format!("/repos/{OWNER}/{NAME}/git/ref/tags/{TAG}")))
            .respond_with(ResponseTemplate::new(500))
            .mount(&server)
            .await;
        let once = Octocrab::builder()
            .personal_token("token".to_owned())
            .base_uri(server.uri())
            .unwrap()
            .add_retry_config(RetryConfig::None)
            .build()
            .unwrap();
        let error = super::prove_tag_with(&once, &repo(), TAG, PUBLISHED, &NO_WAIT)
            .await
            .unwrap_err();
        assert!(
            format!("{error:#}").contains(&format!("read tag {TAG}")),
            "{error:#}"
        );
        assert_eq!(reads_of_the_tag(&server).await, 1);
    }

    #[tokio::test]
    async fn the_tag_proof_fails_on_a_tag_at_another_commit() {
        let server = MockServer::start().await;
        lightweight_tag(OTHER).mount(&server).await;
        let error = super::prove_tag_with(&crab(&server.uri()), &repo(), TAG, PUBLISHED, &NO_WAIT)
            .await
            .unwrap_err();
        let message = format!("{error:#}");
        assert!(message.contains(OTHER), "{message}");
        assert!(message.contains(PUBLISHED), "{message}");
    }

    fn other_releases(count: usize) -> Vec<serde_json::Value> {
        (0..count)
            .map(|n| {
                let mut json = release_json("main");
                json["tag_name"] = format!("v0.0.{n}").into();
                json
            })
            .collect()
    }

    /// The list is read a page at a time, 100 to a page, until a Release has
    /// the tag. Each mock answers only its own page.
    #[tokio::test]
    async fn the_release_list_is_read_page_by_page_until_the_tag_is_found() {
        let server = MockServer::start().await;
        missing_release().mount(&server).await;
        Mock::given(method("GET"))
            .and(path(format!("/repos/{OWNER}/{NAME}/releases")))
            .and(query_param("per_page", "100"))
            .and(query_param("page", "1"))
            .respond_with(ResponseTemplate::new(200).set_body_json(other_releases(100)))
            .expect(1)
            .mount(&server)
            .await;
        Mock::given(method("GET"))
            .and(path(format!("/repos/{OWNER}/{NAME}/releases")))
            .and(query_param("per_page", "100"))
            .and(query_param("page", "2"))
            .respond_with(
                ResponseTemplate::new(200).set_body_json(serde_json::json!([draft_json(&[])])),
            )
            .expect(1)
            .mount(&server)
            .await;
        let found =
            super::find_release(&crab(&server.uri()), &repo(), TAG, &ReleaseList::default())
                .await
                .unwrap()
                .expect("the draft on page 2");
        assert!(found.draft);
    }

    /// A draft has no tag until it is published, so a missing tag still reads
    /// the Releases, and a tagless draft is an incomplete release.
    #[tokio::test]
    async fn a_tagless_draft_is_an_incomplete_release() {
        let server = MockServer::start().await;
        missing_tag().mount(&server).await;
        missing_release().mount(&server).await;
        listed_releases(serde_json::json!([draft_json(&[("app.pkg", "uploaded")])]))
            .mount(&server)
            .await;
        let state =
            super::release_state_with(&crab(&server.uri()), &repo(), TAG, &ReleaseList::default())
                .await
                .unwrap();
        assert_eq!(state.tag, None);
        assert!(state.release && state.draft, "{state:?}");
        assert_eq!(state.assets, ["app.pkg"]);
    }

    /// A draft's stop record is read from its body, for `status` to show.
    #[tokio::test]
    async fn a_drafts_stop_record_is_read() {
        let server = MockServer::start().await;
        missing_tag().mount(&server).await;
        missing_release().mount(&server).await;
        let mut draft = draft_json(&[]);
        draft["body"] = indoc! {r#"
            notes

            <!-- verctl:stop {"package":"app","version":"1.0.0","cause":"429 Too Many Requests"} -->
        "#}
        .into();
        listed_releases(serde_json::json!([draft]))
            .mount(&server)
            .await;
        let state =
            super::release_state_with(&crab(&server.uri()), &repo(), TAG, &ReleaseList::default())
                .await
                .unwrap();
        assert_eq!(
            state.stop,
            Record::Read(Stop::new("app", "1.0.0", "429 Too Many Requests", None))
        );
    }

    /// A tag with no Release in a repository with many reads ten pages, then
    /// counts as having none, instead of one request per page forever.
    #[tokio::test]
    async fn the_release_list_is_read_for_ten_pages_at_most() {
        let server = MockServer::start().await;
        missing_release().mount(&server).await;
        Mock::given(method("GET"))
            .and(path(format!("/repos/{OWNER}/{NAME}/releases")))
            .respond_with(ResponseTemplate::new(200).set_body_json(other_releases(100)))
            .expect(10)
            .mount(&server)
            .await;
        let found =
            super::find_release(&crab(&server.uri()), &repo(), TAG, &ReleaseList::default())
                .await
                .unwrap();
        assert!(found.is_none(), "{found:?}");
    }

    #[tokio::test]
    async fn create_tags_the_published_commit_not_the_default_branch() {
        let server = MockServer::start().await;
        missing_release().mount(&server).await;
        no_releases_listed().mount(&server).await;
        create_at_published_sha().mount(&server).await;
        lightweight_tag(PUBLISHED).mount(&server).await;
        let url = super::ensure_release_with(
            &crab(&server.uri()),
            &repo(),
            &stable(),
            super::PackageUpload::Shipped,
        )
        .await
        .unwrap();
        assert!(url.contains(TAG), "{url}");
    }

    #[tokio::test]
    async fn a_candidate_release_is_a_prerelease_that_is_never_the_latest() {
        let server = MockServer::start().await;
        missing_release().mount(&server).await;
        no_releases_listed().mount(&server).await;
        Mock::given(method("POST"))
            .and(path(format!("/repos/{OWNER}/{NAME}/releases")))
            .and(body_partial_json(serde_json::json!({
                "tag_name": TAG,
                "prerelease": true,
                "make_latest": "false"
            })))
            .respond_with(ResponseTemplate::new(201).set_body_json(release_json("main")))
            .mount(&server)
            .await;
        lightweight_tag(PUBLISHED).mount(&server).await;
        let candidate = super::NewRelease {
            stage: super::Stage::Candidate,
            ..stable()
        };
        let url = super::ensure_release_with(
            &crab(&server.uri()),
            &repo(),
            &candidate,
            super::PackageUpload::Shipped,
        )
        .await
        .unwrap();
        assert!(url.contains(TAG), "{url}");
    }

    #[tokio::test]
    async fn a_stable_release_sets_neither_prerelease_nor_latest() {
        let server = MockServer::start().await;
        missing_release().mount(&server).await;
        no_releases_listed().mount(&server).await;
        Mock::given(method("POST"))
            .and(path(format!("/repos/{OWNER}/{NAME}/releases")))
            .and(|request: &wiremock::Request| {
                let body: serde_json::Value = serde_json::from_slice(&request.body).unwrap();
                body.get("prerelease").is_none() && body.get("make_latest").is_none()
            })
            .respond_with(ResponseTemplate::new(201).set_body_json(release_json("main")))
            .mount(&server)
            .await;
        lightweight_tag(PUBLISHED).mount(&server).await;
        let url = super::ensure_release_with(
            &crab(&server.uri()),
            &repo(),
            &stable(),
            super::PackageUpload::Shipped,
        )
        .await
        .unwrap();
        assert!(url.contains(TAG), "{url}");
    }

    #[tokio::test]
    async fn a_forbidden_release_names_the_workflows_permission() {
        let server = MockServer::start().await;
        missing_release().mount(&server).await;
        no_releases_listed().mount(&server).await;
        Mock::given(method("POST"))
            .and(path(format!("/repos/{OWNER}/{NAME}/releases")))
            .respond_with(ResponseTemplate::new(403).set_body_json(serde_json::json!({
                "message": "Resource not accessible by integration",
                "documentation_url": "https://docs.github.com/rest/releases/releases#create-a-release"
            })))
            .mount(&server)
            .await;
        let error = super::ensure_release_with(
            &crab(&server.uri()),
            &repo(),
            &stable(),
            super::PackageUpload::Shipped,
        )
        .await
        .unwrap_err();
        let message = format!("{error:#}");
        assert!(message.contains("workflows: write"), "{message}");
        assert!(message.contains(PUBLISHED), "{message}");
        assert!(
            error.downcast_ref::<super::ReleaseRefused>().is_some(),
            "{message}"
        );
    }

    #[tokio::test]
    async fn create_fails_when_the_tag_lands_elsewhere() {
        let server = MockServer::start().await;
        missing_release().mount(&server).await;
        no_releases_listed().mount(&server).await;
        create_at_published_sha().mount(&server).await;
        lightweight_tag(OTHER).mount(&server).await;
        let error = super::ensure_release_with(
            &crab(&server.uri()),
            &repo(),
            &stable(),
            super::PackageUpload::Shipped,
        )
        .await
        .unwrap_err();
        let message = format!("{error:#}");
        assert!(message.contains(OTHER), "{message}");
        assert!(message.contains(PUBLISHED), "{message}");
    }

    #[tokio::test]
    async fn existing_release_at_the_published_commit_is_ok() {
        let server = MockServer::start().await;
        existing_release().mount(&server).await;
        lightweight_tag(PUBLISHED).mount(&server).await;
        let url = super::ensure_release_with(
            &crab(&server.uri()),
            &repo(),
            &stable(),
            super::PackageUpload::Shipped,
        )
        .await
        .unwrap();
        assert!(url.contains(TAG), "{url}");
    }

    #[tokio::test]
    async fn existing_release_at_another_commit_fails() {
        let server = MockServer::start().await;
        existing_release().mount(&server).await;
        lightweight_tag(OTHER).mount(&server).await;
        let error = super::ensure_release_with(
            &crab(&server.uri()),
            &repo(),
            &stable(),
            super::PackageUpload::Shipped,
        )
        .await
        .unwrap_err();
        let message = format!("{error:#}");
        assert!(message.contains(OTHER), "{message}");
        assert!(message.contains(PUBLISHED), "{message}");
    }

    #[tokio::test]
    async fn existing_release_is_kept_when_nothing_under_it_shipped() {
        let server = MockServer::start().await;
        existing_release().mount(&server).await;
        lightweight_tag(OTHER).mount(&server).await;
        let url = super::ensure_release_with(
            &crab(&server.uri()),
            &repo(),
            &stable(),
            super::PackageUpload::Skipped,
        )
        .await
        .unwrap();
        assert!(url.contains(TAG), "{url}");
    }

    #[tokio::test]
    async fn annotated_tag_peels_to_the_commit() {
        let server = MockServer::start().await;
        existing_release().mount(&server).await;
        annotated_tag().mount(&server).await;
        peeled_tag_object(PUBLISHED).mount(&server).await;
        let url = super::ensure_release_with(
            &crab(&server.uri()),
            &repo(),
            &stable(),
            super::PackageUpload::Shipped,
        )
        .await
        .unwrap();
        assert!(url.contains(TAG), "{url}");
    }

    /// The lookups of one plan share the Releases list: two missing tags
    /// read it once.
    #[tokio::test]
    async fn two_missing_tags_read_the_release_list_once() {
        let server = MockServer::start().await;
        Mock::given(method("GET"))
            .and(path_regex(format!(
                "^/repos/{OWNER}/{NAME}/git/ref/tags/.+$"
            )))
            .respond_with(ResponseTemplate::new(404).set_body_json(serde_json::json!({
                "message": "Not Found",
                "documentation_url": "https://docs.github.com"
            })))
            .mount(&server)
            .await;
        Mock::given(method("GET"))
            .and(path_regex(format!(
                "^/repos/{OWNER}/{NAME}/releases/tags/.+$"
            )))
            .respond_with(ResponseTemplate::new(404).set_body_json(serde_json::json!({
                "message": "Not Found",
                "documentation_url": "https://docs.github.com"
            })))
            .expect(2)
            .mount(&server)
            .await;
        no_releases_listed().expect(1).mount(&server).await;
        let list = ReleaseList::default();
        let crab = crab(&server.uri());
        for tag in ["v1.0.0", "v2.0.0"] {
            let state = super::release_state_with(&crab, &repo(), tag, &list)
                .await
                .unwrap();
            assert_eq!(state, super::ReleaseState::default());
        }
    }

    /// An upload goes to the Release id the run has, and never looks the
    /// tag up again, so a second draft with the same tag name is left alone.
    #[tokio::test]
    async fn an_upload_goes_to_the_drafts_id_when_two_drafts_share_the_tag() {
        let server = MockServer::start().await;
        let uri = server.uri();
        let mut first = draft_json(&[]);
        first["id"] = 1.into();
        let mut second = draft_json(&[]);
        second["id"] = 2.into();
        listed_releases(serde_json::json!([first, second]))
            .expect(0)
            .mount(&server)
            .await;
        let mut draft = release_json(PUBLISHED);
        draft["id"] = 2.into();
        draft["draft"] = true.into();
        draft["upload_url"] =
            format!("{uri}/upload/repos/{OWNER}/{NAME}/releases/2/assets{{?name,label}}").into();
        Mock::given(method("GET"))
            .and(path(format!("/repos/{OWNER}/{NAME}/releases/2")))
            .respond_with(ResponseTemplate::new(200).set_body_json(draft))
            .mount(&server)
            .await;
        Mock::given(method("POST"))
            .and(path(format!(
                "/upload/repos/{OWNER}/{NAME}/releases/2/assets"
            )))
            .respond_with(ResponseTemplate::new(201).set_body_json(serde_json::json!({
                "url": format!("{uri}/repos/{OWNER}/{NAME}/releases/assets/9"),
                "browser_download_url": format!("https://github.com/{OWNER}/{NAME}/releases/download/{TAG}/app.tar.gz"),
                "id": 9,
                "node_id": "A",
                "name": "app.tar.gz",
                "label": null,
                "state": "uploaded",
                "content_type": "application/gzip",
                "size": 7,
                "digest": null,
                "download_count": 0,
                "created_at": "2026-11-13T00:00:00Z",
                "updated_at": "2026-11-13T00:00:00Z",
                "uploader": null
            })))
            .expect(1)
            .mount(&server)
            .await;
        let url = super::upload_release_asset_with(
            &crab(&uri),
            &repo(),
            super::Target::Id { id: 2, tag: TAG },
            "app.tar.gz",
            bytes::Bytes::from_static(b"tarball"),
            &[Duration::ZERO; 2],
        )
        .await
        .unwrap();
        assert!(url.ends_with("/app.tar.gz"), "{url}");
    }

    fn upload_target_json(assets: &serde_json::Value) -> Mock {
        let mut json = release_json("main");
        json["assets"] = assets.clone();
        Mock::given(method("GET"))
            .and(path(format!("/repos/{OWNER}/{NAME}/releases/tags/{TAG}")))
            .respond_with(ResponseTemplate::new(200).set_body_json(json))
    }

    /// The release octocrab reads before an upload, pointing uploads at `uri`.
    fn release_by_id(uri: &str) -> Mock {
        let mut json = release_json("main");
        json["upload_url"] =
            format!("{uri}/upload/repos/{OWNER}/{NAME}/releases/1/assets{{?name,label}}").into();
        Mock::given(method("GET"))
            .and(path(format!("/repos/{OWNER}/{NAME}/releases/1")))
            .respond_with(ResponseTemplate::new(200).set_body_json(json))
    }

    fn upload_refused(status: u16, body: serde_json::Value) -> Mock {
        Mock::given(method("POST"))
            .and(path(format!(
                "/upload/repos/{OWNER}/{NAME}/releases/1/assets"
            )))
            .respond_with(ResponseTemplate::new(status).set_body_json(body))
    }

    fn already_exists() -> serde_json::Value {
        serde_json::json!({
            "message": "Validation Failed",
            "errors": [{ "resource": "ReleaseAsset", "code": "already_exists", "field": "name" }],
            "documentation_url": "https://docs.github.com/rest/releases/assets#upload-a-release-asset"
        })
    }

    async fn upload(server: &MockServer) -> anyhow::Result<String> {
        super::upload_release_asset_with(
            &crab(&server.uri()),
            &repo(),
            super::Target::Tag(TAG),
            "app_1.0.0_linux_x64.tar.gz",
            bytes::Bytes::from_static(b"tarball"),
            &[Duration::ZERO; 2],
        )
        .await
    }

    #[tokio::test]
    async fn an_asset_another_run_uploaded_is_already_done() {
        let server = MockServer::start().await;
        upload_target_json(&serde_json::json!([
            { "name": "app_1.0.0_linux_x64.tar.gz", "state": "uploaded" }
        ]))
        .mount(&server)
        .await;
        release_by_id(&server.uri()).mount(&server).await;
        upload_refused(422, already_exists())
            .expect(0)
            .mount(&server)
            .await;
        assert_eq!(
            upload(&server).await.unwrap(),
            "already app_1.0.0_linux_x64.tar.gz"
        );
    }

    #[tokio::test]
    async fn a_duplicate_waits_for_the_other_upload_to_finish() {
        let server = MockServer::start().await;
        // The read before the upload and the first read after the refusal see
        // the other run still sending.
        upload_target_json(&serde_json::json!([
            { "name": "app_1.0.0_linux_x64.tar.gz", "state": "starter" }
        ]))
        .up_to_n_times(2)
        .mount(&server)
        .await;
        upload_target_json(&serde_json::json!([
            { "name": "app_1.0.0_linux_x64.tar.gz", "state": "uploaded" }
        ]))
        .mount(&server)
        .await;
        release_by_id(&server.uri()).mount(&server).await;
        upload_refused(422, already_exists()).mount(&server).await;
        assert_eq!(
            upload(&server).await.unwrap(),
            "already app_1.0.0_linux_x64.tar.gz"
        );
    }

    #[tokio::test]
    async fn an_asset_whose_upload_broke_off_fails() {
        let server = MockServer::start().await;
        upload_target_json(&serde_json::json!([
            { "name": "app_1.0.0_linux_x64.tar.gz", "state": "starter" }
        ]))
        .mount(&server)
        .await;
        release_by_id(&server.uri()).mount(&server).await;
        upload_refused(422, already_exists()).mount(&server).await;
        let error = upload(&server).await.unwrap_err();
        assert!(format!("{error:#}").contains("\"starter\""), "{error:#}");
    }

    #[tokio::test]
    async fn another_validation_failure_fails_the_upload() {
        let server = MockServer::start().await;
        upload_target_json(&serde_json::json!([]))
            .mount(&server)
            .await;
        release_by_id(&server.uri()).mount(&server).await;
        upload_refused(
            422,
            serde_json::json!({
                "message": "Validation Failed",
                "errors": [{ "resource": "ReleaseAsset", "code": "invalid", "field": "name" }]
            }),
        )
        .mount(&server)
        .await;
        let error = upload(&server).await.unwrap_err();
        assert!(
            format!("{error:#}").contains("upload release asset"),
            "{error:#}"
        );
    }

    fn create_vendored_release() -> wiremock::MockBuilder {
        Mock::given(method("POST"))
            .and(path(format!("/repos/{OWNER}/{NAME}/releases")))
            .and(body_partial_json(serde_json::json!({
                "tag_name": TAG,
                "name": TAG,
                "body": "Built from upstream.",
                "target_commitish": PUBLISHED,
                "make_latest": "false"
            })))
    }

    async fn vendored_release(server: &MockServer) -> anyhow::Result<String> {
        super::ensure_vendored_release_with(
            &crab(&server.uri()),
            &repo(),
            TAG,
            "Built from upstream.",
            PUBLISHED,
        )
        .await
    }

    #[tokio::test]
    async fn a_missing_vendored_release_is_created_and_not_made_latest() {
        let server = MockServer::start().await;
        missing_release().mount(&server).await;
        create_vendored_release()
            .respond_with(ResponseTemplate::new(201).set_body_json(release_json(PUBLISHED)))
            .expect(1)
            .mount(&server)
            .await;
        let url = vendored_release(&server).await.unwrap();
        assert!(url.ends_with(&format!("/releases/tag/{TAG}")), "{url}");
    }

    #[tokio::test]
    async fn an_existing_vendored_release_is_used_wherever_its_tag_points() {
        let server = MockServer::start().await;
        existing_release().mount(&server).await;
        Mock::given(method("POST"))
            .respond_with(ResponseTemplate::new(500))
            .expect(0)
            .mount(&server)
            .await;
        let url = vendored_release(&server).await.unwrap();
        assert!(url.contains(TAG), "{url}");
    }

    #[tokio::test]
    async fn a_vendored_release_another_job_created_first_is_used() {
        let server = MockServer::start().await;
        missing_release().up_to_n_times(1).mount(&server).await;
        existing_release().mount(&server).await;
        create_vendored_release()
            .respond_with(ResponseTemplate::new(422).set_body_json(serde_json::json!({
                "message": "Validation Failed",
                "errors": [{ "resource": "Release", "code": "already_exists", "field": "tag_name" }]
            })))
            .expect(1)
            .mount(&server)
            .await;
        let url = vendored_release(&server).await.unwrap();
        assert!(url.contains(TAG), "{url}");
    }

    async fn sha256_of(server: &MockServer, name: &str) -> anyhow::Result<String> {
        super::asset_sha256_with(&crab(&server.uri()), &repo(), TAG, name).await
    }

    #[tokio::test]
    async fn the_checksum_is_the_digest_github_holds() {
        let server = MockServer::start().await;
        upload_target_json(&serde_json::json!([
            { "name": "lib-1.0.0-linux-x64.tar.gz", "state": "uploaded", "digest": "sha256:abc123" }
        ]))
        .mount(&server)
        .await;
        assert_eq!(
            sha256_of(&server, "lib-1.0.0-linux-x64.tar.gz")
                .await
                .unwrap(),
            "abc123"
        );
    }

    #[tokio::test]
    async fn an_asset_without_a_digest_has_no_checksum() {
        let server = MockServer::start().await;
        upload_target_json(&serde_json::json!([
            { "name": "lib-1.0.0-linux-x64.tar.gz", "state": "uploaded", "digest": null }
        ]))
        .mount(&server)
        .await;
        let error = sha256_of(&server, "lib-1.0.0-linux-x64.tar.gz")
            .await
            .unwrap_err();
        assert!(
            format!("{error:#}").contains("no SHA-256 digest"),
            "{error:#}"
        );
    }

    /// A request that carries no `Authorization` header.
    struct Anonymous;

    impl wiremock::Match for Anonymous {
        fn matches(&self, request: &wiremock::Request) -> bool {
            !request.headers.contains_key("authorization")
        }
    }

    /// The asset API redirects to storage, and the token stays with GitHub.
    #[tokio::test]
    async fn a_draft_asset_downloads_through_the_redirect_without_the_token() {
        let server = MockServer::start().await;
        let uri = server.uri();
        upload_target_json(&serde_json::json!([{
            "name": "app.tar.gz",
            "state": "uploaded",
            "url": format!("{uri}/repos/{OWNER}/{NAME}/releases/assets/9"),
            "digest": "sha256:abc123"
        }]))
        .mount(&server)
        .await;
        Mock::given(method("GET"))
            .and(path(format!("/repos/{OWNER}/{NAME}/releases/assets/9")))
            .and(header("accept", "application/octet-stream"))
            .and(header("authorization", "Bearer token"))
            .respond_with(
                ResponseTemplate::new(302)
                    .insert_header("location", format!("{uri}/storage/app.tar.gz")),
            )
            .expect(1)
            .mount(&server)
            .await;
        Mock::given(method("GET"))
            .and(path("/storage/app.tar.gz"))
            .and(Anonymous)
            .respond_with(ResponseTemplate::new(200).set_body_bytes(b"tarball".to_vec()))
            .expect(1)
            .mount(&server)
            .await;
        let dir = tempfile::TempDir::new().unwrap();
        let saved = super::download_release_assets_with(
            &crab(&uri),
            "token",
            &repo(),
            TAG,
            &["app.tar.gz"],
            dir.path(),
        )
        .await
        .unwrap();
        assert_eq!(saved.len(), 1);
        assert_eq!(saved[0].name, "app.tar.gz");
        assert_eq!(saved[0].sha256, "abc123");
        assert_eq!(fs::read(dir.path().join("app.tar.gz")).unwrap(), b"tarball");
    }

    /// Storage that redirects again is refused: the client follows no
    /// redirect, so a second 3xx body never becomes the asset.
    #[tokio::test]
    async fn a_second_redirect_fails_the_download() {
        let server = MockServer::start().await;
        let uri = server.uri();
        upload_target_json(&serde_json::json!([{
            "name": "app.tar.gz",
            "state": "uploaded",
            "url": format!("{uri}/repos/{OWNER}/{NAME}/releases/assets/9"),
            "digest": "sha256:abc123"
        }]))
        .mount(&server)
        .await;
        Mock::given(method("GET"))
            .and(path(format!("/repos/{OWNER}/{NAME}/releases/assets/9")))
            .respond_with(
                ResponseTemplate::new(302)
                    .insert_header("location", format!("{uri}/storage/app.tar.gz")),
            )
            .mount(&server)
            .await;
        Mock::given(method("GET"))
            .and(path("/storage/app.tar.gz"))
            .respond_with(
                ResponseTemplate::new(302).insert_header("location", format!("{uri}/elsewhere")),
            )
            .mount(&server)
            .await;
        let dir = tempfile::TempDir::new().unwrap();
        let error = super::download_release_assets_with(
            &crab(&uri),
            "token",
            &repo(),
            TAG,
            &["app.tar.gz"],
            dir.path(),
        )
        .await
        .unwrap_err();
        assert!(
            format!("{error:#}").contains("unexpected status 302"),
            "{error:#}"
        );
        assert!(!dir.path().join("app.tar.gz").exists());
    }

    #[tokio::test]
    async fn close_pr_comments_and_closes_pull_request() {
        let server = MockServer::start().await;
        let expected_url = format!("https://github.com/{OWNER}/{NAME}/pull/42");
        Mock::given(method("POST"))
            .and(path(format!("/repos/{OWNER}/{NAME}/issues/42/comments")))
            .and(body_partial_json(serde_json::json!({
                "body": "Closing this Version PR: no pending fragments remain on `main` at abc123."
            })))
            .respond_with(ResponseTemplate::new(201).set_body_json(serde_json::json!({
                "id": 99
            })))
            .expect(1)
            .mount(&server)
            .await;
        Mock::given(method("PATCH"))
            .and(path(format!("/repos/{OWNER}/{NAME}/pulls/42")))
            .and(body_partial_json(serde_json::json!({
                "state": "closed"
            })))
            .respond_with(ResponseTemplate::new(200).set_body_json(serde_json::json!({
                "number": 42,
                "state": "closed",
                "html_url": expected_url,
            })))
            .expect(1)
            .mount(&server)
            .await;
        let url = super::close_pr_with(
            &crab(&server.uri()),
            &repo(),
            42,
            "Closing this Version PR: no pending fragments remain on `main` at abc123.",
        )
        .await
        .unwrap();
        assert_eq!(url, expected_url);
    }
}