anodizer 0.4.0

A Rust-native release automation tool inspired by GoReleaser
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
use anodizer_core::artifact::{Artifact, ArtifactKind};
use anodizer_core::config::{Config, ForceTokenKind, GitHubConfig, WorkspaceConfig};
use anodizer_core::context::Context;
use anodizer_core::git;
use anodizer_core::log::StageLogger;
use anodizer_core::scm::{self, ScmTokenType};
use anyhow::{Context as _, Result};
use std::collections::HashMap;
use std::path::{Path, PathBuf};

/// Parse a comma-separated list (e.g. `--targets=a,b,c` or `--stages=x,y`)
/// into the canonical `Option<Vec<String>>` form.
///
/// - `None`           → `None` (no filter).
/// - `Some("a,b")`    → `Some(["a", "b"])`.
/// - Empty / whitespace-only tokens (trailing comma, double comma,
///   surrounding spaces) are dropped — they're noise, not intent.
/// - `Some("")` or `Some(" , ")` (all-empty after trimming) → `Err`. The
///   operator clearly meant to pass *something*; surfacing the typo
///   beats silently degrading into a no-op filter.
///
/// `flag_help` is the `--flag=<example>` snippet appended to the error so
/// each call site gets a copy-pasteable hint specific to its CSV shape.
pub(crate) fn parse_csv_list(
    raw: Option<&str>,
    flag_help: &str,
) -> Result<Option<Vec<String>>, String> {
    match raw {
        None => Ok(None),
        Some(list) => {
            let parsed: Vec<String> = list
                .split(',')
                .map(str::trim)
                .filter(|s| !s.is_empty())
                .map(str::to_string)
                .collect();
            if parsed.is_empty() {
                return Err(format!(
                    "{flag_help} must list at least one entry (got empty / whitespace-only input)"
                ));
            }
            Ok(Some(parsed))
        }
    }
}

/// Walk an artifact path iterator and fail if any path appears more than
/// once. Used by post-load manifest validators (publish-only's per-shard
/// merge, `release --merge`'s split-worker merge) to surface accidental
/// shard overlap as a hard error rather than a silent double-publish
/// downstream.
pub(crate) fn detect_duplicate_paths<'a, I>(paths: I) -> Result<()>
where
    I: IntoIterator<Item = &'a Path>,
{
    use std::collections::BTreeMap;
    let mut counts: BTreeMap<PathBuf, usize> = BTreeMap::new();
    for p in paths {
        *counts.entry(p.to_path_buf()).or_insert(0) += 1;
    }
    let duplicates: Vec<(PathBuf, usize)> = counts.into_iter().filter(|(_, n)| *n > 1).collect();
    if duplicates.is_empty() {
        return Ok(());
    }
    let summary = duplicates
        .iter()
        .map(|(p, n)| format!("{} ({}×)", p.display(), n))
        .collect::<Vec<_>>()
        .join(", ");
    anyhow::bail!(
        "duplicate artifact path(s) after merging per-shard manifests: {summary}. \
         Hypothesis: two shards overlapped on the same target, so both \
         emitted an artifact for the same path. Inspect the matrix in \
         `.github/workflows/release.yml` (or the equivalent dispatcher) \
         to confirm the shards partition the target set."
    );
}

/// Walk an artifact path iterator and verify each file exists on disk
/// under `dist/`. Tries the literal path first (absolute or relative),
/// then `dist.join(<path>)`. Missing files are fatal so SignStage /
/// ChecksumStage emit an operator-friendly manifest-shaped diagnostic
/// rather than cosign / gpg's less actionable "file not found".
///
/// Files in `dist/` that are *absent* from the manifest are not flagged
/// — dist trees carry metadata.json, harness logs, etc. that aren't
/// part of the artifact registry.
pub(crate) fn detect_missing_files<'a, I>(paths: I, dist: &Path) -> Result<()>
where
    I: IntoIterator<Item = &'a Path>,
{
    let mut missing: Vec<PathBuf> = Vec::new();
    for p in paths {
        if p.is_absolute() {
            if !p.is_file() {
                missing.push(p.to_path_buf());
            }
        } else if !p.is_file() && !dist.join(p).is_file() {
            missing.push(p.to_path_buf());
        }
    }
    if missing.is_empty() {
        return Ok(());
    }
    missing.sort();
    let summary = missing
        .iter()
        .map(|p| p.display().to_string())
        .collect::<Vec<_>>()
        .join(", ");
    anyhow::bail!(
        "artifacts manifest references file(s) not present under {}: {summary}. \
         The preserved dist is incomplete; re-run \
         `anodize check determinism --preserve-dist=<dist>` to repopulate, or \
         remove the stale manifest entries before retrying.",
        dist.display(),
    );
}

/// Set a process-level environment variable.
///
/// # Safety contract
///
/// `std::env::set_var` is unsafe because it mutates global process state that
/// other threads may be reading concurrently.  This function must ONLY be
/// called during single-threaded pipeline setup (i.e., inside `setup_env`)
/// before any worker threads are spawned.  All later stages that need env
/// values should read from the `Context` template vars or pass them
/// explicitly via `Command::envs()`.
fn set_env_var_single_threaded(key: &str, value: &str) {
    // SAFETY: Caller guarantees no other threads exist yet.
    unsafe { std::env::set_var(key, value) };
}

/// Resolve the effective `force_token` kind — config field first, then the
/// `ANODIZER_FORCE_TOKEN` env var, then the `GORELEASER_FORCE_TOKEN` compat
/// fallback. Returns `None` if nothing is set (or the value isn't a recognised
/// backend).
///
/// Extracted so `setup_env` and `resolve_scm_token_type` can't drift — adding
/// a new backend only needs to be wired in this one place.
fn resolve_force_token(config: &Config) -> Option<ForceTokenKind> {
    config.force_token.as_ref().cloned().or_else(|| {
        let env_val = std::env::var("ANODIZER_FORCE_TOKEN")
            .ok()
            .or_else(|| std::env::var("GORELEASER_FORCE_TOKEN").ok())?;
        match env_val.to_lowercase().as_str() {
            "github" => Some(ForceTokenKind::GitHub),
            "gitlab" => Some(ForceTokenKind::GitLab),
            "gitea" => Some(ForceTokenKind::Gitea),
            _ => None,
        }
    })
}

/// Collect all configured build targets from a config, in declaration order.
///
/// Iterates `config.crates` plus every `config.workspaces[].crates` so monorepos
/// with multi-root workspaces are covered. Per-crate `builds[].targets` entries
/// REPLACE `defaults.targets` for that build (override semantics — matching
/// the `BuildConfig.targets` rustdoc and the stage-build runtime). Builds
/// whose `targets` field is `None` fall back to `defaults.targets`.
/// Duplicates are filtered across all builds, and `defaults.builds.ignore`
/// (os/arch pairs) removes matching targets.
///
/// `selected_crates` filters the iteration: when empty, all crates are used;
/// otherwise only crates whose `name` is in the slice contribute.
pub fn collect_build_targets(config: &Config, selected_crates: &[String]) -> Vec<String> {
    let mut targets: Vec<String> = Vec::new();
    let default_targets = config
        .defaults
        .as_ref()
        .and_then(|d| d.targets.as_deref())
        .unwrap_or(&[]);

    let all_crates = config.crates.iter().chain(
        config
            .workspaces
            .as_deref()
            .unwrap_or_default()
            .iter()
            .flat_map(|w| w.crates.iter()),
    );

    let mut have_any_build = false;
    for krate in all_crates {
        if !selected_crates.is_empty() && !selected_crates.contains(&krate.name) {
            continue;
        }

        if let Some(ref builds) = krate.builds {
            for build in builds {
                have_any_build = true;
                // Override semantics: when a per-build `targets` is set,
                // it REPLACES `defaults.targets` for that build. Only when
                // it is None does the build fall through to the defaults.
                let chosen = match build.targets.as_deref() {
                    Some(ts) => ts,
                    None => default_targets,
                };
                for t in chosen {
                    if !targets.contains(t) {
                        targets.push(t.clone());
                    }
                }
            }
        }
    }

    // No builds at all (e.g. lib-only crates inheriting nothing); the
    // defaults.targets list is the canonical fallback set so callers like
    // `anodizer release --single-target` still see something to filter
    // against.
    if !have_any_build {
        for t in default_targets {
            if !targets.contains(t) {
                targets.push(t.clone());
            }
        }
    }

    if let Some(ignores) = config
        .defaults
        .as_ref()
        .and_then(|d| d.builds.as_ref())
        .and_then(|b| b.ignore.as_ref())
    {
        targets.retain(|t| {
            let (os, arch) = anodizer_core::target::map_target(t);
            !ignores.iter().any(|ig| ig.os == os && ig.arch == arch)
        });
    }

    targets
}

/// Apply a workspace's configuration overlay onto the top-level config.
///
/// - `crates` is always replaced.
/// - `changelog`, `signs`, `before`, and `after` replace when present.
/// - `env` is merged additively (workspace values override same-key top-level values).
pub fn apply_workspace_overlay(config: &mut Config, ws: &WorkspaceConfig) {
    config.crates = ws.crates.clone();
    if ws.changelog.is_some() {
        config.changelog = ws.changelog.clone();
    }
    if !ws.signs.is_empty() {
        config.signs = ws.signs.clone();
    }
    if !ws.binary_signs.is_empty() {
        config.binary_signs = ws.binary_signs.clone();
    }
    if ws.before.is_some() {
        config.before = ws.before.clone();
    }
    if ws.after.is_some() {
        config.after = ws.after.clone();
    }
    if let Some(ref env_list) = ws.env {
        let merged = config.env.get_or_insert_with(Vec::new);
        merged.extend(env_list.iter().cloned());
    }
}

/// Resolve tag and populate git variables on the context.
///
/// Finds the first selected crate (or the first crate in config), looks up
/// the latest tag matching its `tag_template`, detects git info, and
/// populates the context's template variables.
pub fn resolve_git_context(
    ctx: &mut Context,
    config: &Config,
    log: &StageLogger,
) -> anyhow::Result<()> {
    // Warn on shallow clones where tag discovery may be incomplete.
    if git::is_shallow_clone() {
        eprintln!(
            "WARNING: shallow clone detected; tag discovery may be incomplete. Use `git fetch --unshallow` in CI."
        );
    }

    // Allow env var overrides for tag discovery. Anodizer-native var wins;
    // the GoReleaser compat alias is checked as a fallback so CI jobs migrating
    // from GoReleaser pick up their existing env vars without rewiring.
    let tag_override = std::env::var("ANODIZER_CURRENT_TAG")
        .ok()
        .filter(|s| !s.is_empty())
        .or_else(|| {
            std::env::var("GORELEASER_CURRENT_TAG")
                .ok()
                .filter(|s| !s.is_empty())
        });

    // Resolve a crate to derive the tag from. Selection order:
    //   1. The first explicitly selected crate (--crate or --all selection)
    //   2. The first top-level crate in config
    //   3. The first crate of the first workspace (workspace-only configs)
    //
    // The workspace fallback is critical for snapshot/dry-run mode in
    // workspace-only configs (e.g. cfgd) — without it, `Version` is never
    // populated in the template context, breaking any template that
    // references it.
    let first_crate = ctx
        .options
        .selected_crates
        .first()
        .and_then(|name| {
            config.crates.iter().find(|c| &c.name == name).or_else(|| {
                config.workspaces.as_ref().and_then(|ws_list| {
                    ws_list
                        .iter()
                        .flat_map(|w| w.crates.iter())
                        .find(|c| &c.name == name)
                })
            })
        })
        .or_else(|| config.crates.first())
        .or_else(|| {
            config
                .workspaces
                .as_ref()
                .and_then(|ws_list| ws_list.iter().flat_map(|w| w.crates.iter()).next())
        });

    if let Some(crate_cfg) = first_crate {
        let tag = if let Some(ref override_tag) = tag_override {
            log.verbose(&format!(
                "using ANODIZER_CURRENT_TAG override: {}",
                override_tag
            ));
            override_tag.clone()
        } else {
            let monorepo_prefix = config.monorepo_tag_prefix();
            let latest_tag = match git::find_latest_tag_matching_with_prefix(
                &crate_cfg.tag_template,
                config.git.as_ref(),
                Some(ctx.template_vars()),
                monorepo_prefix,
            ) {
                Ok(found) => found,
                Err(e) => {
                    log.warn(&format!("error finding tags matching template: {e}"));
                    None
                }
            };
            match latest_tag {
                Some(t) => t,
                None => {
                    if ctx.options.snapshot {
                        log.warn("no git tags found, defaulting to v0.0.0 (snapshot mode).");
                        "v0.0.0".to_string()
                    } else if ctx.options.dry_run {
                        log.warn("no git tags found, defaulting to v0.0.0 (dry-run mode).");
                        "v0.0.0".to_string()
                    } else {
                        anyhow::bail!("no git tag found; create a tag or use --snapshot");
                    }
                }
            }
        };

        // Validate HEAD points at the tag (like GoReleaser's ErrWrongRef).
        // Skip this check for the synthetic v0.0.0 tag since it doesn't exist in git.
        let is_synthetic_tag = tag == "v0.0.0" && tag_override.is_none();
        if !is_synthetic_tag
            && let Ok(false) = git::tag_points_at_head(&tag)
            && !ctx.options.snapshot
        {
            let head = git::get_short_commit().unwrap_or_else(|_| "unknown".to_string());
            anyhow::bail!(
                "tag {} does not point at HEAD ({}). Check out the tag or use --snapshot to skip this check.",
                tag,
                head
            );
        }

        match git::detect_git_info(&tag, ctx.skip_validate()) {
            Ok(mut git_info) => {
                // Validate dirty working tree: error in non-snapshot/non-dry-run mode,
                // matching GoReleaser's CheckDirty behavior.
                if git_info.dirty && !ctx.options.snapshot {
                    if ctx.options.dry_run {
                        log.warn("git is in a dirty state; run `git status` to see what changed.");
                    } else {
                        anyhow::bail!(
                            "git is in a dirty state; run `git status` to see what changed. \
                             Use --snapshot to force."
                        );
                    }
                }

                // Allow ANODIZER_PREVIOUS_TAG (or GoReleaser compat
                // GORELEASER_PREVIOUS_TAG) env override for the previous tag.
                let prev_override = std::env::var("ANODIZER_PREVIOUS_TAG")
                    .ok()
                    .filter(|s| !s.is_empty())
                    .or_else(|| {
                        std::env::var("GORELEASER_PREVIOUS_TAG")
                            .ok()
                            .filter(|s| !s.is_empty())
                    });
                if let Some(prev_override) = prev_override {
                    log.verbose(&format!(
                        "using ANODIZER_PREVIOUS_TAG override: {}",
                        prev_override
                    ));
                    git_info.previous_tag = Some(prev_override);
                } else {
                    // Derive the tag-prefix filter from the current crate's
                    // tag_template (e.g. `v` for cfgd, `csi-v` for cfgd-csi)
                    // so monorepo-style workspaces don't bleed prior tags
                    // across crates. Without this, `git describe --tags`
                    // returns the most recent tag of ANY crate — e.g.
                    // `cfgd: csi-v0.3.4 -> 0.3.5` ends up in the nix/
                    // homebrew commit message because csi was the most
                    // recently tagged sibling. Falls back to the global
                    // monorepo prefix when the template has no extractable
                    // prefix.
                    let crate_prefix = git::extract_tag_prefix(&crate_cfg.tag_template);
                    let prefix = crate_prefix
                        .as_deref()
                        .or_else(|| config.monorepo_tag_prefix());
                    git_info.previous_tag = git::find_previous_tag_with_prefix(
                        &tag,
                        config.git.as_ref(),
                        Some(ctx.template_vars()),
                        prefix,
                    )
                    .ok()
                    .flatten();
                }
                ctx.git_info = Some(git_info);
                ctx.populate_git_vars();
            }
            Err(e) => {
                if ctx.options.snapshot {
                    log.warn(&format!(
                        "could not detect git info in snapshot mode, using defaults: {e}"
                    ));
                    ctx.git_info = Some(git::GitInfo {
                        tag: tag.clone(),
                        commit: "none".to_string(),
                        short_commit: "none".to_string(),
                        branch: "none".to_string(),
                        dirty: true,
                        semver: git::SemVer {
                            major: 0,
                            minor: 0,
                            patch: 0,
                            prerelease: None,
                            build_metadata: None,
                        },
                        commit_date: String::new(),
                        commit_timestamp: String::new(),
                        previous_tag: None,
                        remote_url: String::new(),
                        summary: "snapshot".to_string(),
                        tag_subject: String::new(),
                        tag_contents: String::new(),
                        tag_body: String::new(),
                        first_commit: None,
                    });
                    ctx.populate_git_vars();
                } else {
                    return Err(anyhow::anyhow!("could not detect git info: {e}"));
                }
            }
        }
    } else {
        ctx.populate_git_vars();
    }
    Ok(())
}

/// Combine `defaults.env` and top-level `config.env` into a single list with
/// deterministic precedence: defaults entries come first so any same-keyed
/// entry in `config.env` clobbers the defaults version on the
/// last-one-wins-per-key application path inside `setup_env`.
///
/// Returns `None` when both inputs are `None`. Returns the cloned non-None
/// input when only one side is set.
fn merge_env_with_defaults(
    defaults_env: Option<&Vec<String>>,
    config_env: Option<&Vec<String>>,
) -> Option<Vec<String>> {
    match (defaults_env, config_env) {
        (None, None) => None,
        (Some(d), None) => Some(d.clone()),
        (None, Some(c)) => Some(c.clone()),
        (Some(d), Some(c)) => {
            let mut v = Vec::with_capacity(d.len() + c.len());
            v.extend(d.iter().cloned());
            v.extend(c.iter().cloned());
            Some(v)
        }
    }
}

/// Load process environment variables, `.env` files, and user-defined env vars
/// into the context's template variables.
///
/// Loading order (later wins):
/// 1. All process environment variables (`std::env::vars()`)
/// 2. Variables from `.env` files specified in config
/// 3. Explicit `env:` map entries — `defaults.env` first, then `config.env`
///    (so per-config entries override defaults on duplicate keys)
///
/// This ensures config-defined env vars always take precedence over process
/// environment, matching GoReleaser's behavior where all process env vars are
/// accessible in templates via `{{ .Env.VAR }}`.
pub fn setup_env(
    ctx: &mut Context,
    config: &Config,
    log: &anodizer_core::log::StageLogger,
) -> anyhow::Result<()> {
    // Load ALL process environment variables first (lowest priority)
    for (key, value) in std::env::vars() {
        ctx.template_vars_mut().set_env(&key, &value);
    }

    // Load env files into template context (overrides process env).
    // Supports both list form (array of .env files) and struct form (token file paths).
    // These are user-configured, so use set_config_env (safe for cross-platform
    // serialization and subprocess injection).
    if let Some(ref env_files_config) = config.env_files {
        match env_files_config {
            anodizer_core::config::EnvFilesConfig::List(files) => {
                let env_vars = anodizer_core::config::load_env_files(files, log, ctx.is_strict())
                    .map_err(anyhow::Error::msg)?;
                for (key, value) in &env_vars {
                    ctx.template_vars_mut().set_config_env(key, value);
                }
            }
            anodizer_core::config::EnvFilesConfig::TokenFiles(token_config) => {
                let token_vars = anodizer_core::config::load_token_files(token_config, log)
                    .map_err(anyhow::Error::msg)?;
                for (key, value) in &token_vars {
                    ctx.template_vars_mut().set_config_env(key, value);
                    set_env_var_single_threaded(key, value);
                }
            }
        }
    } else {
        // always check default
        // token file paths even when env_files is not configured.
        let default_config = anodizer_core::config::EnvFilesTokenConfig::default();
        let token_vars = anodizer_core::config::load_token_files(&default_config, log)
            .map_err(anyhow::Error::msg)?;
        for (key, value) in &token_vars {
            ctx.template_vars_mut().set_config_env(key, value);
            set_env_var_single_threaded(key, value);
        }
    }

    // Populate user-defined env vars into template context (highest priority).
    // GoReleaser renders env values through the template engine.
    let merged_env = merge_env_with_defaults(
        config.defaults.as_ref().and_then(|d| d.env.as_ref()),
        config.env.as_ref(),
    );
    if let Some(ref env_list) = merged_env {
        let rendered_pairs =
            anodizer_core::config::render_env_entries(env_list, |v| ctx.render_template(v))
                .with_context(|| "config.env: parse and render entries")?;
        for (key, rendered) in rendered_pairs {
            ctx.template_vars_mut().set_config_env(&key, &rendered);
            // Also set in the process environment so that child processes which
            // inherit env (docker, lipo, rustup, git, hook scripts) see these
            // values. Some commands use explicit `.envs()`, but many rely on
            // process-level inheritance.
            //
            // SAFETY: This is called during single-threaded pipeline setup in
            // `setup_env`, before any worker threads are spawned. No concurrent
            // readers of the process environment exist at this point.
            set_env_var_single_threaded(&key, &rendered);
        }
    }

    // Populate user-defined custom variables into template context.
    if let Some(ref vars_map) = config.variables {
        for (key, value) in vars_map {
            // Render variable values through templates (they may reference env vars or other template vars)
            let rendered = ctx.render_template(value).unwrap_or_else(|_| value.clone());
            ctx.template_vars_mut().set_custom_var(key, &rendered);
        }
    }

    // GoReleaser env.go:75-86: when force_token is active, clear non-forced
    // token env vars BEFORE the multi-token check so it cannot fire.
    let resolved_force = resolve_force_token(config);
    if let Some(ref forced) = resolved_force {
        // Remove env vars for non-forced token types so downstream code
        // only sees the forced provider's token.
        let keep_github = matches!(forced, ForceTokenKind::GitHub);
        let keep_gitlab = matches!(forced, ForceTokenKind::GitLab);
        let keep_gitea = matches!(forced, ForceTokenKind::Gitea);
        if !keep_github {
            // SAFETY: single-threaded pipeline setup, see set_env_var_single_threaded.
            unsafe {
                std::env::remove_var("GITHUB_TOKEN");
                std::env::remove_var("ANODIZER_GITHUB_TOKEN");
            }
        }
        if !keep_gitlab {
            // SAFETY: single-threaded pipeline setup, see set_env_var_single_threaded.
            unsafe { std::env::remove_var("GITLAB_TOKEN") };
        }
        if !keep_gitea {
            // SAFETY: single-threaded pipeline setup, see set_env_var_single_threaded.
            unsafe { std::env::remove_var("GITEA_TOKEN") };
        }
    }

    // Multiple-token detection (GoReleaser env.go:88-101 ErrMultipleTokens).
    // When multiple SCM tokens are set without force_token, error early.
    if resolved_force.is_none() {
        let has_github =
            std::env::var("GITHUB_TOKEN").is_ok() || std::env::var("ANODIZER_GITHUB_TOKEN").is_ok();
        let has_gitlab = std::env::var("GITLAB_TOKEN").is_ok();
        let has_gitea = std::env::var("GITEA_TOKEN").is_ok();
        let count = [has_github, has_gitlab, has_gitea]
            .iter()
            .filter(|&&b| b)
            .count();
        if count > 1 {
            anyhow::bail!(
                "multiple SCM tokens set simultaneously ({}). Set force_token in config \
                 or ANODIZER_FORCE_TOKEN env var to specify which to use.",
                [
                    if has_github {
                        Some("GITHUB_TOKEN")
                    } else {
                        None
                    },
                    if has_gitlab {
                        Some("GITLAB_TOKEN")
                    } else {
                        None
                    },
                    if has_gitea { Some("GITEA_TOKEN") } else { None },
                ]
                .into_iter()
                .flatten()
                .collect::<Vec<_>>()
                .join(", ")
            );
        }
    }

    // Missing token hard error (GoReleaser env.go:138-142 ErrMissingToken).
    // Error early if no SCM token and the pipeline needs one.
    // Snapshot mode, dry-run, and release.skip can proceed without a token.
    //
    // `--publish-only` defers the token check to
    // `publish_only::preflight_credentials`, which combines the token
    // check with the production sign-key check (the spec wants both
    // validated together at the top of the publish-only branch). If
    // setup_env bailed here first, publish-only would never get a
    // chance to emit its combined preflight error or honor
    // `--no-preflight`. The publish-only branch enforces the same
    // gate downstream so dropping it here doesn't widen the hole.
    if ctx.options.token.is_none()
        && !ctx.is_snapshot()
        && !ctx.is_dry_run()
        && !ctx.options.publish_only
    {
        let release_skipped = match config
            .crates
            .first()
            .and_then(|c| c.release.as_ref()?.skip.as_ref())
        {
            Some(d) => d
                .try_evaluates_to_true(|t| ctx.render_template(t))
                .with_context(|| "release: render skip template")?,
            None => false,
        };
        let needs_token = config.crates.iter().any(|c| c.release.is_some())
            && !ctx.should_skip("release")
            && !release_skipped;
        if needs_token {
            let hint = match ctx.token_type {
                anodizer_core::scm::ScmTokenType::GitLab => {
                    "no GitLab token found. Set GITLAB_TOKEN."
                }
                anodizer_core::scm::ScmTokenType::Gitea => "no Gitea token found. Set GITEA_TOKEN.",
                anodizer_core::scm::ScmTokenType::GitHub => {
                    "no GitHub token found. Set GITHUB_TOKEN or ANODIZER_GITHUB_TOKEN."
                }
            };
            anyhow::bail!("{}", hint);
        }
    }

    Ok(())
}

/// Write `dist/config.yaml` with the fully-resolved (effective) config.
///
/// GoReleaser always writes this, including in dry-run mode (effectiveconfig.go).
/// Shared by `release` and `build` pipelines so both surface the same artifact.
///
/// Two runs of the determinism harness must emit a byte-identical
/// `config.yaml`. The `Config` type carries many `HashMap<String, _>` fields
/// (`docker.labels`, `docker.build_args`, `variables`, `nfpm.dependencies`,
/// announcer `extra`, custom headers, …) whose iteration order is randomized
/// per process. We serialize to a `serde_yaml_ng::Value` first, then
/// recursively sort every mapping's keys alphabetically, then emit the
/// canonical form. Centralised here so adding a new HashMap field anywhere
/// in `Config` is automatically covered without a per-field `serialize_with`
/// attribute.
pub fn write_effective_config(config: &Config, log: &StageLogger) -> Result<()> {
    let dist = &config.dist;
    std::fs::create_dir_all(dist)
        .with_context(|| format!("failed to create dist directory: {}", dist.display()))?;
    let effective_path = dist.join("config.yaml");
    let mut value: serde_yaml_ng::Value =
        serde_yaml_ng::to_value(config).context("failed to serialize effective config")?;
    sort_yaml_mapping(&mut value);
    let yaml = serde_yaml_ng::to_string(&value).context("failed to serialize effective config")?;
    std::fs::write(&effective_path, &yaml)
        .with_context(|| format!("failed to write {}", effective_path.display()))?;
    log.verbose(&format!(
        "wrote effective config to {}",
        effective_path.display()
    ));
    Ok(())
}

/// Recursively sort every `Value::Mapping` entry by key.
///
/// `serde_yaml_ng::Mapping` is an `IndexMap` (insertion-ordered), so the
/// emit order is whatever order serde visited the source. For
/// `HashMap<String, _>` fields that order is randomized per process — fatal
/// for the determinism harness, which fingerprints `dist/config.yaml`. This
/// helper rebuilds each mapping in sort order (lexicographically by the
/// `Display` form of `Value`, which for `String` keys is the underlying
/// string — the only mapping-key shape the `Config` type produces).
fn sort_yaml_mapping(value: &mut serde_yaml_ng::Value) {
    use serde_yaml_ng::{Mapping, Value};
    match value {
        Value::Mapping(map) => {
            let mut entries: Vec<(Value, Value)> = std::mem::take(map).into_iter().collect();
            entries.sort_by_key(|(a, _)| yaml_key_sort_key(a));
            let mut sorted = Mapping::with_capacity(entries.len());
            for (k, mut v) in entries {
                sort_yaml_mapping(&mut v);
                sorted.insert(k, v);
            }
            *map = sorted;
        }
        Value::Sequence(seq) => {
            for v in seq.iter_mut() {
                sort_yaml_mapping(v);
            }
        }
        Value::Tagged(tagged) => sort_yaml_mapping(&mut tagged.value),
        _ => {}
    }
}

/// Stable string-keyed sort for YAML mapping entries. Strings compare on
/// their UTF-8 bytes (the common case); every other `Value` flavour falls
/// back to its `Debug` rendering so the order is at least deterministic.
fn yaml_key_sort_key(v: &serde_yaml_ng::Value) -> String {
    match v {
        serde_yaml_ng::Value::String(s) => s.clone(),
        other => format!("{:?}", other),
    }
}

/// Print the artifact size report if `report_sizes` is enabled in config.
pub fn run_report_sizes(ctx: &mut Context, config: &Config, log: &StageLogger) {
    if config.report_sizes.unwrap_or(false) {
        anodizer_core::artifact::print_size_report(&mut ctx.artifacts, log);
    }
}

/// Write `dist/metadata.json` and `dist/artifacts.json` and apply the
/// configured `metadata.mod_timestamp` to both files.
///
/// Mirrors GoReleaser's metadata.Pipe + artifacts.Pipe. Registers
/// `metadata.json` as an artifact so downstream stages can pick it up.
pub fn write_metadata_and_artifacts(
    ctx: &mut Context,
    config: &Config,
    log: &StageLogger,
) -> Result<()> {
    let dist = &config.dist;
    std::fs::create_dir_all(dist)
        .with_context(|| format!("failed to create dist directory: {}", dist.display()))?;

    let metadata_path = dist.join("metadata.json");
    let goos = anodizer_core::context::map_os_to_goos(std::env::consts::OS);
    let goarch = anodizer_core::context::map_arch_to_goarch(std::env::consts::ARCH);

    let tag = ctx.template_vars().get("Tag").cloned().unwrap_or_default();
    let previous_tag = ctx
        .template_vars()
        .get("PreviousTag")
        .cloned()
        .unwrap_or_default();
    let version = ctx.version();
    let commit = ctx
        .template_vars()
        .get("FullCommit")
        .cloned()
        .unwrap_or_default();
    let date = ctx.template_vars().get("Date").cloned().unwrap_or_default();

    let project_metadata = serde_json::json!({
        "project_name": config.project_name,
        "tag": tag,
        "previous_tag": previous_tag,
        "version": version,
        "commit": commit,
        "date": date,
        "runtime": {
            "goos": goos,
            "goarch": goarch,
        }
    });

    let json_str = serde_json::to_string_pretty(&project_metadata)
        .context("failed to serialize project metadata JSON")?;
    std::fs::write(&metadata_path, &json_str)
        .with_context(|| format!("failed to write {}", metadata_path.display()))?;
    log.status(&format!("wrote {}", metadata_path.display()));

    ctx.artifacts.add(anodizer_core::artifact::Artifact {
        kind: ArtifactKind::Metadata,
        name: "metadata.json".to_string(),
        path: metadata_path.clone(),
        target: None,
        crate_name: config.project_name.clone(),
        metadata: Default::default(),
        size: None,
    });

    let artifacts_path = dist.join("artifacts.json");
    let artifacts_json = ctx
        .artifacts
        .to_artifacts_json()
        .context("failed to serialize artifact list")?;
    let json_str = serde_json::to_string_pretty(&artifacts_json)
        .context("failed to serialize artifacts JSON")?;
    std::fs::write(&artifacts_path, &json_str)
        .with_context(|| format!("failed to write {}", artifacts_path.display()))?;
    log.status(&format!("wrote {}", artifacts_path.display()));

    if let Some(ref meta) = config.metadata
        && let Some(ref ts_tmpl) = meta.mod_timestamp
    {
        let rendered = ctx
            .render_template(ts_tmpl)
            .context("failed to render metadata.mod_timestamp template")?;
        if !rendered.is_empty() {
            let mtime = anodizer_core::util::parse_mod_timestamp(&rendered)
                .with_context(|| format!("invalid metadata.mod_timestamp value: {:?}", rendered))?;
            anodizer_core::util::set_file_mtime(&metadata_path, mtime)?;
            anodizer_core::util::set_file_mtime(&artifacts_path, mtime)?;
            log.status(&format!(
                "set mtime on metadata.json and artifacts.json to {}",
                rendered
            ));
        }
    }

    Ok(())
}

/// Auto-infer `project_name` from Cargo.toml when not set in config.
///
/// GoReleaser's project.go:22-43 infers the project name from Cargo.toml,
/// go.mod, or the git remote. We mirror the Cargo.toml branch here so
/// every pipeline command (release, build, check, continue) resolves the
/// project name consistently.
pub fn infer_project_name(config: &mut Config, log: &StageLogger) {
    if !config.project_name.is_empty() {
        return;
    }
    if let Ok(cargo_toml) = std::fs::read_to_string("Cargo.toml")
        && let Ok(doc) = cargo_toml.parse::<toml_edit::DocumentMut>()
        && let Some(name) = doc
            .get("package")
            .and_then(|p| p.get("name"))
            .and_then(|n| n.as_str())
    {
        config.project_name = name.to_string();
        log.verbose(&format!("inferred project_name '{}' from Cargo.toml", name));
    }
}

/// Auto-detect the GitHub owner/name from the git remote and fill in any crate
/// release configs that are missing the `github` section.
pub fn auto_detect_github(config: &mut Config, log: &StageLogger) {
    let detected_github = git::detect_github_repo().ok();
    for crate_cfg in &mut config.crates {
        if let Some(ref mut release) = crate_cfg.release
            && release.github.is_none()
        {
            if let Some((ref owner, ref name)) = detected_github {
                release.github = Some(GitHubConfig {
                    owner: owner.clone(),
                    name: name.clone(),
                });
            } else {
                log.warn("could not auto-detect GitHub repo from git remote");
            }
        }
    }
}

/// Perform the standard context setup sequence shared by all pipeline commands.
///
/// This encapsulates the boilerplate that every pipeline entry point
/// (release, publish, announce, continue) must run after constructing a
/// `Context`:
///   1. Resolve SCM token type from config/environment
///   2. Populate time template variables
///   3. Populate runtime template variables
///   4. Load environment variables and `.env` files
///   5. Resolve git context (tag discovery, git info)
pub fn setup_context(ctx: &mut Context, config: &Config, log: &StageLogger) -> Result<()> {
    resolve_scm_token_type(ctx, config);
    ctx.populate_time_vars();
    ctx.populate_runtime_vars();
    // Default the GR-Pro `IsPrepare` template var to `"false"` for every
    // command that flows through `setup_context`. The release command
    // overrides this when `--prepare` is passed (see
    // `commands/release/mod.rs`). Setting it unconditionally avoids a
    // "missing key" footgun in user templates that branch on
    // `{{ if IsPrepare }}`.
    ctx.template_vars_mut().set("IsPrepare", "false");
    setup_env(ctx, config, log)?;
    resolve_git_context(ctx, config, log)?;
    Ok(())
}

/// Resolve the SCM token type and token value from config and environment.
///
/// This sets `ctx.token_type` based on priority (highest first):
/// 1. `config.force_token` — explicit user config (`force_token: gitlab`)
/// 2. `ANODIZER_FORCE_TOKEN` env var — e.g. `github`, `gitlab`, `gitea`
/// 3. `GORELEASER_FORCE_TOKEN` env var — GoReleaser compat fallback
/// 4. Environment variable presence — `GITLAB_TOKEN` → GitLab, `GITEA_TOKEN` → Gitea
/// 5. Default — GitHub
///
/// It also resolves the token value into `ctx.options.token` (if not already
/// set by a CLI flag) from the appropriate environment variable:
/// - GitLab: `GITLAB_TOKEN`
/// - Gitea: `GITEA_TOKEN`
/// - GitHub: `ANODIZER_GITHUB_TOKEN` or `GITHUB_TOKEN`
pub fn resolve_scm_token_type(ctx: &mut Context, config: &Config) {
    // Detect which SCM backend to use from environment variables.
    let env_hint = if std::env::var("GITLAB_TOKEN").is_ok() {
        Some("gitlab")
    } else if std::env::var("GITEA_TOKEN").is_ok() {
        Some("gitea")
    } else {
        None
    };

    let force_token = resolve_force_token(config);

    ctx.token_type = scm::resolve_token_type(force_token.as_ref(), env_hint);

    // Resolve the token value if not already provided via CLI flag.
    if ctx.options.token.is_none() {
        ctx.options.token = match ctx.token_type {
            ScmTokenType::GitLab => std::env::var("GITLAB_TOKEN").ok(),
            ScmTokenType::Gitea => std::env::var("GITEA_TOKEN").ok(),
            ScmTokenType::GitHub => std::env::var("ANODIZER_GITHUB_TOKEN")
                .ok()
                .or_else(|| std::env::var("GITHUB_TOKEN").ok()),
        };
    }
}

/// Load config, auto-detect GitHub, build a `Context`, and rehydrate
/// artifacts from `dist/` — the shared prelude for the `publish`,
/// `announce`, and (no-`--merge` branch of) `continue` commands.
///
/// Returns `(config, ctx, dist)` so the caller can drive the publish /
/// announce pipeline. `ctx_opts` is assembled by the caller so each
/// command supplies its own `skip_stages` / `merge` / `token` overlay.
///
/// Side effect: emits a `log.status("loaded N artifact(s) from <dist>")`
/// line after rehydration so the operator sees the artifact count at
/// the same point in every "resume from dist" command.
pub fn init_publish_stage_ctx(
    config_override: Option<&Path>,
    ctx_opts: anodizer_core::context::ContextOptions,
    dist_override: Option<&Path>,
    infer_project: bool,
    log: &StageLogger,
) -> Result<(Config, Context, std::path::PathBuf)> {
    let config_path = crate::pipeline::find_config_with_logger(config_override, Some(log))?;
    let mut config = crate::pipeline::load_config(&config_path)?;
    if infer_project {
        infer_project_name(&mut config, log);
    }
    auto_detect_github(&mut config, log);

    let mut ctx = Context::new(config.clone(), ctx_opts);
    setup_context(&mut ctx, &config, log)?;

    let dist = dist_override.unwrap_or(&config.dist).to_path_buf();
    load_artifacts_from_dist(&mut ctx, &dist)?;
    log.status(&format!(
        "loaded {} artifact(s) from {}",
        ctx.artifacts.all().len(),
        dist.display()
    ));

    Ok((config, ctx, dist))
}

/// Load artifacts from dist/artifacts.json into the context's artifact registry.
/// Used by `publish` and `announce` commands that run from a completed dist/.
pub fn load_artifacts_from_dist(ctx: &mut Context, dist: &Path) -> Result<()> {
    let artifacts_path = dist.join("artifacts.json");
    load_artifacts_from_manifest(ctx, dist, &artifacts_path)
}

/// Load artifacts from an explicitly-named manifest path under `dist/`.
/// Split from [`load_artifacts_from_dist`] so a sharded matrix can fold
/// in `artifacts-<shard>.json` files one at a time. `dist` is carried
/// only for the error message (caller-meaningful location).
pub fn load_artifacts_from_manifest(
    ctx: &mut Context,
    dist: &Path,
    manifest_path: &Path,
) -> Result<()> {
    if !manifest_path.exists() {
        anyhow::bail!(
            "no artifacts manifest found at {} (under {}). Run a full release or merge first.",
            manifest_path.display(),
            dist.display()
        );
    }

    let content = std::fs::read_to_string(manifest_path)
        .with_context(|| format!("read {}", manifest_path.display()))?;

    #[derive(serde::Deserialize)]
    struct MetadataArtifact {
        kind: String,
        #[serde(default)]
        name: Option<String>,
        path: String,
        target: Option<String>,
        crate_name: String,
        #[serde(default)]
        metadata: HashMap<String, String>,
        #[serde(default)]
        size: Option<u64>,
    }

    let artifacts: Vec<MetadataArtifact> = serde_json::from_str(&content)
        .with_context(|| format!("parse {}", manifest_path.display()))?;

    for a in artifacts {
        let kind = ArtifactKind::parse(&a.kind)
            .ok_or_else(|| anyhow::anyhow!("unknown artifact kind: {}", a.kind))?;
        ctx.artifacts.add(Artifact {
            kind,
            name: a.name.unwrap_or_default(),
            path: std::path::PathBuf::from(&a.path),
            target: a.target,
            crate_name: a.crate_name,
            metadata: a.metadata,
            size: a.size,
        });
    }

    Ok(())
}

#[cfg(test)]
mod tests {
    use super::*;
    use anodizer_core::config::{ChangelogConfig, CrateConfig, SignConfig};
    use anodizer_core::context::ContextOptions;
    use anodizer_core::scm::ScmTokenType;

    /// `Config.variables` is a `HashMap<String, String>` whose iteration order
    /// is randomized per process. The determinism harness fingerprints
    /// `dist/config.yaml`, so two runs in the same workspace must emit
    /// byte-identical YAML. `write_effective_config` is expected to route
    /// the serialized config through `sort_yaml_mapping`, alphabetising the
    /// keys of every mapping (top-level AND nested). Without that, the
    /// `variables:` block's emit order tracks HashMap randomness and drifts.
    #[test]
    fn write_effective_config_emits_sorted_keys() {
        let tmp = tempfile::tempdir().unwrap();
        let mut variables = HashMap::new();
        // Insert in deliberately non-alphabetical order so the test would
        // pass on raw HashMap iteration only by luck (1 / N!).
        variables.insert("zeta".to_string(), "1".to_string());
        variables.insert("alpha".to_string(), "2".to_string());
        variables.insert("mu".to_string(), "3".to_string());
        variables.insert("beta".to_string(), "4".to_string());
        variables.insert("nu".to_string(), "5".to_string());
        let config = Config {
            project_name: "anodize".to_string(),
            dist: tmp.path().to_path_buf(),
            variables: Some(variables),
            ..Default::default()
        };
        let log = StageLogger::new("test", anodizer_core::log::Verbosity::Quiet);

        // Build a second config with the same contents inserted in REVERSE
        // order. Two HashMaps containing the same keys may still iterate
        // differently depending on insertion history; the sort step must
        // collapse both to the same byte stream.
        let mut variables_reversed = HashMap::new();
        for key in ["nu", "beta", "mu", "alpha", "zeta"] {
            let v = match key {
                "zeta" => "1",
                "alpha" => "2",
                "mu" => "3",
                "beta" => "4",
                "nu" => "5",
                _ => unreachable!(),
            };
            variables_reversed.insert(key.to_string(), v.to_string());
        }
        let config_reversed = Config {
            variables: Some(variables_reversed),
            ..config.clone()
        };

        write_effective_config(&config, &log).expect("first write");
        let yaml1 = std::fs::read_to_string(tmp.path().join("config.yaml")).unwrap();
        // Second write into the same dist with reversed-insertion variables.
        write_effective_config(&config_reversed, &log).expect("second write");
        let yaml2 = std::fs::read_to_string(tmp.path().join("config.yaml")).unwrap();
        assert_eq!(
            yaml1, yaml2,
            "two write_effective_config calls with identical input keys \
             must produce byte-identical YAML regardless of HashMap \
             insertion order (HashMap-iteration drift would fail this)"
        );

        // And the variables block keys must be alphabetical.
        let var_block_lines: Vec<&str> = yaml1
            .lines()
            .skip_while(|l| !l.starts_with("variables:"))
            .skip(1)
            .take_while(|l| l.starts_with("  ") || l.starts_with('\t'))
            .collect();
        let keys: Vec<&str> = var_block_lines
            .iter()
            .filter_map(|l| l.trim().split(':').next())
            .collect();
        assert_eq!(
            keys,
            vec!["alpha", "beta", "mu", "nu", "zeta"],
            "variables: keys must be emitted in alphabetical order; got {:?} \
             from yaml:\n{}",
            keys,
            yaml1,
        );
    }

    /// Recursive guard: the harness's drift channel is most often a *nested*
    /// HashMap (e.g. `docker.labels`, `nfpm.dependencies`,
    /// `announce.<flavour>.headers`). `sort_yaml_mapping` must walk into
    /// sub-mappings AND into sequences-of-mappings. Hand-crafted
    /// `serde_yaml_ng::Value` to exercise both axes.
    #[test]
    fn sort_yaml_mapping_recurses_into_nested_maps_and_sequences() {
        let yaml = "\
top:
  z: 1
  a: 2
list:
  - inner_z: 1
    inner_a: 2
  - solo: 3
";
        let mut value: serde_yaml_ng::Value = serde_yaml_ng::from_str(yaml).unwrap();
        sort_yaml_mapping(&mut value);
        let out = serde_yaml_ng::to_string(&value).unwrap();
        // Top-level keys: list comes before top alphabetically.
        let first_line = out.lines().next().unwrap();
        assert!(
            first_line.starts_with("list:"),
            "top-level keys must be sorted alphabetically; got {out:?}"
        );
        // Sub-mapping under `top:` must be sorted (a before z).
        let top_pos = out.find("top:").unwrap();
        let top_block = &out[top_pos..];
        let a_pos = top_block.find("a:").expect("a: present");
        let z_pos = top_block.find("z:").expect("z: present");
        assert!(
            a_pos < z_pos,
            "nested mapping under `top:` must be sorted; got {out:?}"
        );
        // Sub-mapping inside the first list element must also be sorted.
        let list_pos = out.find("list:").unwrap();
        let list_block = &out[list_pos..];
        let inner_a = list_block.find("inner_a:").expect("inner_a: present");
        let inner_z = list_block.find("inner_z:").expect("inner_z: present");
        assert!(
            inner_a < inner_z,
            "nested mapping inside a sequence element must be sorted; got {out:?}"
        );
    }

    fn make_crate(name: &str) -> CrateConfig {
        CrateConfig {
            name: name.to_string(),
            path: ".".to_string(),
            tag_template: format!("{}-v{{{{ .Version }}}}", name),
            ..Default::default()
        }
    }

    #[test]
    fn test_apply_workspace_overlay_replaces_crates() {
        let mut config = Config {
            project_name: "test".to_string(),
            crates: vec![make_crate("original")],
            ..Default::default()
        };
        let ws = WorkspaceConfig {
            name: "ws".to_string(),
            crates: vec![make_crate("ws-crate")],
            ..Default::default()
        };

        apply_workspace_overlay(&mut config, &ws);
        assert_eq!(config.crates.len(), 1);
        assert_eq!(config.crates[0].name, "ws-crate");
    }

    #[test]
    fn test_apply_workspace_overlay_merges_env() {
        let mut config = Config {
            project_name: "test".to_string(),
            env: Some(vec![
                "SHARED=from-top".to_string(),
                "TOP_ONLY=top-value".to_string(),
            ]),
            ..Default::default()
        };
        let ws = WorkspaceConfig {
            name: "ws".to_string(),
            crates: vec![],
            env: Some(vec![
                "SHARED=from-ws".to_string(),
                "WS_ONLY=ws-value".to_string(),
            ]),
            ..Default::default()
        };

        apply_workspace_overlay(&mut config, &ws);
        let env = config.env.as_ref().unwrap();
        assert!(env.contains(&"TOP_ONLY=top-value".to_string()));
        assert!(env.contains(&"SHARED=from-ws".to_string()));
        assert!(env.contains(&"WS_ONLY=ws-value".to_string()));
    }

    #[test]
    fn test_apply_workspace_overlay_replaces_signs() {
        let mut config = Config {
            project_name: "test".to_string(),
            signs: vec![SignConfig {
                cmd: Some("gpg".to_string()),
                ..Default::default()
            }],
            ..Default::default()
        };
        let ws = WorkspaceConfig {
            name: "ws".to_string(),
            crates: vec![],
            signs: vec![SignConfig {
                cmd: Some("cosign".to_string()),
                ..Default::default()
            }],
            ..Default::default()
        };

        apply_workspace_overlay(&mut config, &ws);
        assert_eq!(config.signs.len(), 1);
        assert_eq!(config.signs[0].cmd.as_deref(), Some("cosign"));
    }

    #[test]
    fn test_apply_workspace_overlay_replaces_changelog() {
        let mut config = Config {
            project_name: "test".to_string(),
            changelog: Some(ChangelogConfig {
                sort: Some("asc".to_string()),
                ..Default::default()
            }),
            ..Default::default()
        };
        let ws = WorkspaceConfig {
            name: "ws".to_string(),
            crates: vec![],
            changelog: Some(ChangelogConfig {
                sort: Some("desc".to_string()),
                ..Default::default()
            }),
            ..Default::default()
        };

        apply_workspace_overlay(&mut config, &ws);
        assert_eq!(
            config.changelog.as_ref().unwrap().sort.as_deref(),
            Some("desc")
        );
    }

    #[test]
    fn test_apply_workspace_overlay_skips_none_fields() {
        let mut config = Config {
            project_name: "test".to_string(),
            changelog: Some(ChangelogConfig {
                sort: Some("asc".to_string()),
                ..Default::default()
            }),
            ..Default::default()
        };
        let ws = WorkspaceConfig {
            name: "ws".to_string(),
            crates: vec![],
            // changelog is None, should not overwrite
            ..Default::default()
        };

        apply_workspace_overlay(&mut config, &ws);
        // Original changelog preserved
        assert_eq!(
            config.changelog.as_ref().unwrap().sort.as_deref(),
            Some("asc")
        );
    }

    // -----------------------------------------------------------------------
    // load_artifacts_from_dist tests
    // -----------------------------------------------------------------------

    #[test]
    fn test_load_artifacts_from_dist_valid() {
        use anodizer_core::artifact::ArtifactKind;
        use anodizer_core::context::{Context, ContextOptions};

        let dir = tempfile::TempDir::new().unwrap();
        let artifacts_json = serde_json::json!([
            {
                "kind": "binary",
                "name": "myapp",
                "path": "dist/myapp",
                "target": "x86_64-unknown-linux-gnu",
                "crate_name": "myapp",
                "metadata": {},
                "size": 4096
            },
            {
                "kind": "archive",
                "name": "myapp.tar.gz",
                "path": "dist/myapp.tar.gz",
                "target": null,
                "crate_name": "myapp",
                "metadata": {"format": "tar.gz"}
            }
        ]);
        std::fs::write(
            dir.path().join("artifacts.json"),
            serde_json::to_string_pretty(&artifacts_json).unwrap(),
        )
        .unwrap();

        let config = Config::default();
        let mut ctx = Context::new(config, ContextOptions::default());
        load_artifacts_from_dist(&mut ctx, dir.path()).unwrap();

        let all = ctx.artifacts.all();
        assert_eq!(all.len(), 2);

        assert_eq!(all[0].kind, ArtifactKind::Binary);
        assert_eq!(all[0].name, "myapp");
        assert_eq!(
            all[0].size,
            Some(4096),
            "size should be preserved from JSON"
        );

        assert_eq!(all[1].kind, ArtifactKind::Archive);
        assert_eq!(all[1].name, "myapp.tar.gz");
        assert_eq!(
            all[1].metadata.get("format").map(|s| s.as_str()),
            Some("tar.gz")
        );
        assert_eq!(
            all[1].size, None,
            "size should be None when absent from JSON"
        );
    }

    #[test]
    fn test_load_artifacts_from_dist_missing_file() {
        use anodizer_core::context::{Context, ContextOptions};

        let dir = tempfile::TempDir::new().unwrap();
        let config = Config::default();
        let mut ctx = Context::new(config, ContextOptions::default());
        let result = load_artifacts_from_dist(&mut ctx, dir.path());
        assert!(result.is_err());
        let msg = result.unwrap_err().to_string();
        assert!(
            msg.contains("no artifacts manifest found"),
            "error should mention missing file: {msg}"
        );
    }

    #[test]
    fn test_load_artifacts_from_dist_invalid_json() {
        use anodizer_core::context::{Context, ContextOptions};

        let dir = tempfile::TempDir::new().unwrap();
        std::fs::write(dir.path().join("artifacts.json"), "not valid json").unwrap();

        let config = Config::default();
        let mut ctx = Context::new(config, ContextOptions::default());
        let result = load_artifacts_from_dist(&mut ctx, dir.path());
        assert!(result.is_err());
    }

    #[test]
    fn test_load_artifacts_from_dist_unknown_kind() {
        use anodizer_core::context::{Context, ContextOptions};

        let dir = tempfile::TempDir::new().unwrap();
        let artifacts_json = serde_json::json!([
            {
                "kind": "unknown_kind",
                "name": "thing",
                "path": "dist/thing",
                "target": null,
                "crate_name": "myapp",
                "metadata": {}
            }
        ]);
        std::fs::write(
            dir.path().join("artifacts.json"),
            serde_json::to_string_pretty(&artifacts_json).unwrap(),
        )
        .unwrap();

        let config = Config::default();
        let mut ctx = Context::new(config, ContextOptions::default());
        let result = load_artifacts_from_dist(&mut ctx, dir.path());
        assert!(result.is_err());
        let msg = result.unwrap_err().to_string();
        assert!(
            msg.contains("unknown artifact kind"),
            "error should mention unknown kind: {msg}"
        );
    }

    #[test]
    fn test_load_artifacts_from_dist_roundtrip() {
        use anodizer_core::artifact::{Artifact, ArtifactKind, ArtifactRegistry};
        use anodizer_core::context::{Context, ContextOptions};

        // Build an artifact registry, serialize, write, then load back
        let mut registry = ArtifactRegistry::new();
        registry.add(Artifact {
            kind: ArtifactKind::Checksum,
            name: String::new(),
            path: std::path::PathBuf::from("dist/checksums.txt"),
            target: None,
            crate_name: "myapp".to_string(),
            metadata: Default::default(),
            size: Some(256),
        });
        registry.add(Artifact {
            kind: ArtifactKind::Binary,
            name: String::new(),
            path: std::path::PathBuf::from("dist/myapp"),
            target: Some("aarch64-apple-darwin".to_string()),
            crate_name: "myapp".to_string(),
            metadata: Default::default(),
            size: None,
        });

        let json_val = registry.to_artifacts_json().unwrap();
        let json_str = serde_json::to_string_pretty(&json_val).unwrap();

        let dir = tempfile::TempDir::new().unwrap();
        std::fs::write(dir.path().join("artifacts.json"), &json_str).unwrap();

        let config = Config::default();
        let mut ctx = Context::new(config, ContextOptions::default());
        load_artifacts_from_dist(&mut ctx, dir.path()).unwrap();

        let loaded = ctx.artifacts.all();
        assert_eq!(loaded.len(), 2);

        // `to_artifacts_json` emits a stable sort on (kind, target,
        // crate_name, name, path) to keep `dist/artifacts.json` byte-
        // identical across runs regardless of registration order, so the
        // round-tripped order is Binary (kind="binary") before Checksum
        // (kind="checksum"), not the insertion order.
        assert_eq!(loaded[0].kind, ArtifactKind::Binary);
        assert_eq!(loaded[0].name, "myapp");
        assert_eq!(loaded[0].target.as_deref(), Some("aarch64-apple-darwin"));
        assert_eq!(loaded[0].size, None);

        assert_eq!(loaded[1].kind, ArtifactKind::Checksum);
        assert_eq!(loaded[1].name, "checksums.txt");
        assert_eq!(loaded[1].size, Some(256));
    }

    // -----------------------------------------------------------------------
    // resolve_scm_token_type tests
    // -----------------------------------------------------------------------

    /// Mutex to serialize tests that mutate process environment variables.
    /// cargo test runs tests in parallel within a single process, so
    /// concurrent env mutations cause flaky failures without serialization.
    static ENV_MUTEX: std::sync::Mutex<()> = std::sync::Mutex::new(());

    /// Helper to run resolve_scm_token_type tests with controlled env state.
    /// Acquires ENV_MUTEX, removes all SCM token env vars, runs the closure,
    /// then restores original state.
    fn with_clean_token_env<F: FnOnce()>(f: F) {
        let _lock = ENV_MUTEX.lock().unwrap_or_else(|e| e.into_inner());

        // Save and remove all token env vars to isolate the test.
        let saved: Vec<(&str, Option<String>)> = [
            "GITLAB_TOKEN",
            "GITEA_TOKEN",
            "ANODIZER_GITHUB_TOKEN",
            "GITHUB_TOKEN",
            "ANODIZER_FORCE_TOKEN",
            "GORELEASER_FORCE_TOKEN",
        ]
        .iter()
        .map(|&k| (k, std::env::var(k).ok()))
        .collect();

        for &(k, _) in &saved {
            // SAFETY: ENV_MUTEX ensures no concurrent env access from our tests.
            unsafe { std::env::remove_var(k) };
        }

        f();

        // Restore original env state.
        for (k, v) in saved {
            match v {
                Some(val) => unsafe { std::env::set_var(k, val) },
                None => unsafe { std::env::remove_var(k) },
            }
        }
    }

    #[test]
    fn test_resolve_scm_token_type_default_is_github() {
        with_clean_token_env(|| {
            let config = Config::default();
            let mut ctx = Context::new(config.clone(), ContextOptions::default());
            resolve_scm_token_type(&mut ctx, &config);

            assert_eq!(ctx.token_type, ScmTokenType::GitHub);
            // No token env vars set, token should remain None.
            assert!(ctx.options.token.is_none());
        });
    }

    #[test]
    fn test_resolve_scm_token_type_force_gitlab() {
        with_clean_token_env(|| {
            let config = Config {
                force_token: Some(ForceTokenKind::GitLab),
                ..Default::default()
            };
            let mut ctx = Context::new(config.clone(), ContextOptions::default());

            // Set GITLAB_TOKEN so token value resolution picks it up.
            unsafe { std::env::set_var("GITLAB_TOKEN", "glpat-test123") };
            resolve_scm_token_type(&mut ctx, &config);

            assert_eq!(ctx.token_type, ScmTokenType::GitLab);
            assert_eq!(ctx.options.token.as_deref(), Some("glpat-test123"));
        });
    }

    #[test]
    fn test_resolve_scm_token_type_force_gitea() {
        with_clean_token_env(|| {
            let config = Config {
                force_token: Some(ForceTokenKind::Gitea),
                ..Default::default()
            };
            let mut ctx = Context::new(config.clone(), ContextOptions::default());

            unsafe { std::env::set_var("GITEA_TOKEN", "gitea-tok") };
            resolve_scm_token_type(&mut ctx, &config);

            assert_eq!(ctx.token_type, ScmTokenType::Gitea);
            assert_eq!(ctx.options.token.as_deref(), Some("gitea-tok"));
        });
    }

    #[test]
    fn test_resolve_scm_token_type_env_gitlab_detected() {
        with_clean_token_env(|| {
            unsafe { std::env::set_var("GITLAB_TOKEN", "glpat-env") };

            let config = Config::default();
            let mut ctx = Context::new(config.clone(), ContextOptions::default());
            resolve_scm_token_type(&mut ctx, &config);

            assert_eq!(ctx.token_type, ScmTokenType::GitLab);
            assert_eq!(ctx.options.token.as_deref(), Some("glpat-env"));
        });
    }

    #[test]
    fn test_resolve_scm_token_type_env_gitea_detected() {
        with_clean_token_env(|| {
            unsafe { std::env::set_var("GITEA_TOKEN", "gitea-env") };

            let config = Config::default();
            let mut ctx = Context::new(config.clone(), ContextOptions::default());
            resolve_scm_token_type(&mut ctx, &config);

            assert_eq!(ctx.token_type, ScmTokenType::Gitea);
            assert_eq!(ctx.options.token.as_deref(), Some("gitea-env"));
        });
    }

    #[test]
    fn test_resolve_scm_token_type_github_token_from_env() {
        with_clean_token_env(|| {
            unsafe { std::env::set_var("GITHUB_TOKEN", "ghp-from-env") };

            let config = Config::default();
            let mut ctx = Context::new(config.clone(), ContextOptions::default());
            resolve_scm_token_type(&mut ctx, &config);

            assert_eq!(ctx.token_type, ScmTokenType::GitHub);
            assert_eq!(ctx.options.token.as_deref(), Some("ghp-from-env"));
        });
    }

    #[test]
    fn test_resolve_scm_token_type_anodizer_github_token_takes_precedence() {
        with_clean_token_env(|| {
            unsafe { std::env::set_var("ANODIZER_GITHUB_TOKEN", "anodizer-tok") };
            unsafe { std::env::set_var("GITHUB_TOKEN", "gh-tok") };

            let config = Config::default();
            let mut ctx = Context::new(config.clone(), ContextOptions::default());
            resolve_scm_token_type(&mut ctx, &config);

            assert_eq!(ctx.token_type, ScmTokenType::GitHub);
            assert_eq!(
                ctx.options.token.as_deref(),
                Some("anodizer-tok"),
                "ANODIZER_GITHUB_TOKEN should take precedence over GITHUB_TOKEN"
            );
        });
    }

    #[test]
    fn test_resolve_scm_token_type_cli_token_preserved() {
        with_clean_token_env(|| {
            unsafe { std::env::set_var("GITHUB_TOKEN", "from-env") };

            let config = Config::default();
            let opts = ContextOptions {
                token: Some("from-cli".to_string()),
                ..Default::default()
            };
            let mut ctx = Context::new(config.clone(), opts);
            resolve_scm_token_type(&mut ctx, &config);

            assert_eq!(ctx.token_type, ScmTokenType::GitHub);
            assert_eq!(
                ctx.options.token.as_deref(),
                Some("from-cli"),
                "CLI --token flag should not be overwritten by env var"
            );
        });
    }

    #[test]
    fn test_resolve_scm_token_type_force_overrides_env_detection() {
        with_clean_token_env(|| {
            // GITLAB_TOKEN is set, but force_token says GitHub.
            unsafe { std::env::set_var("GITLAB_TOKEN", "glpat-ignored") };

            let config = Config {
                force_token: Some(ForceTokenKind::GitHub),
                ..Default::default()
            };
            let mut ctx = Context::new(config.clone(), ContextOptions::default());
            resolve_scm_token_type(&mut ctx, &config);

            assert_eq!(
                ctx.token_type,
                ScmTokenType::GitHub,
                "force_token should override env-based detection"
            );
            // Token value should be None since no GitHub token env var is set.
            assert!(
                ctx.options.token.is_none(),
                "no GitHub token env var set, so token should remain None"
            );
        });
    }

    #[test]
    fn test_resolve_scm_token_type_gitlab_priority_over_gitea() {
        with_clean_token_env(|| {
            // Both GITLAB_TOKEN and GITEA_TOKEN are set; GITLAB should win.
            unsafe { std::env::set_var("GITLAB_TOKEN", "gl-tok") };
            unsafe { std::env::set_var("GITEA_TOKEN", "gt-tok") };

            let config = Config::default();
            let mut ctx = Context::new(config.clone(), ContextOptions::default());
            resolve_scm_token_type(&mut ctx, &config);

            assert_eq!(
                ctx.token_type,
                ScmTokenType::GitLab,
                "GITLAB_TOKEN should be checked before GITEA_TOKEN"
            );
            assert_eq!(ctx.options.token.as_deref(), Some("gl-tok"));
        });
    }

    #[test]
    fn test_resolve_scm_token_type_anodizer_force_token_env_gitlab() {
        with_clean_token_env(|| {
            // ANODIZER_FORCE_TOKEN env var should override env-based detection.
            unsafe { std::env::set_var("ANODIZER_FORCE_TOKEN", "gitlab") };
            unsafe { std::env::set_var("GITLAB_TOKEN", "glpat-env") };

            let config = Config::default();
            let mut ctx = Context::new(config.clone(), ContextOptions::default());
            resolve_scm_token_type(&mut ctx, &config);

            assert_eq!(
                ctx.token_type,
                ScmTokenType::GitLab,
                "ANODIZER_FORCE_TOKEN=gitlab should force GitLab"
            );
            assert_eq!(ctx.options.token.as_deref(), Some("glpat-env"));
        });
    }

    #[test]
    fn test_resolve_scm_token_type_anodizer_force_token_env_github() {
        with_clean_token_env(|| {
            // Force GitHub even though GITLAB_TOKEN is present.
            unsafe { std::env::set_var("ANODIZER_FORCE_TOKEN", "github") };
            unsafe { std::env::set_var("GITLAB_TOKEN", "glpat-ignored") };
            unsafe { std::env::set_var("GITHUB_TOKEN", "ghp-forced") };

            let config = Config::default();
            let mut ctx = Context::new(config.clone(), ContextOptions::default());
            resolve_scm_token_type(&mut ctx, &config);

            assert_eq!(
                ctx.token_type,
                ScmTokenType::GitHub,
                "ANODIZER_FORCE_TOKEN=github should override GITLAB_TOKEN detection"
            );
            assert_eq!(ctx.options.token.as_deref(), Some("ghp-forced"));
        });
    }

    #[test]
    fn test_resolve_scm_token_type_goreleaser_force_token_compat() {
        with_clean_token_env(|| {
            // GORELEASER_FORCE_TOKEN is the compat fallback when ANODIZER_ is not set.
            unsafe { std::env::set_var("GORELEASER_FORCE_TOKEN", "gitea") };
            unsafe { std::env::set_var("GITEA_TOKEN", "gitea-compat") };

            let config = Config::default();
            let mut ctx = Context::new(config.clone(), ContextOptions::default());
            resolve_scm_token_type(&mut ctx, &config);

            assert_eq!(
                ctx.token_type,
                ScmTokenType::Gitea,
                "GORELEASER_FORCE_TOKEN should work as compat fallback"
            );
            assert_eq!(ctx.options.token.as_deref(), Some("gitea-compat"));
        });
    }

    #[test]
    fn test_resolve_scm_token_type_anodizer_force_token_overrides_goreleaser() {
        with_clean_token_env(|| {
            // When both env vars are set, ANODIZER_FORCE_TOKEN takes precedence.
            unsafe { std::env::set_var("ANODIZER_FORCE_TOKEN", "github") };
            unsafe { std::env::set_var("GORELEASER_FORCE_TOKEN", "gitlab") };
            unsafe { std::env::set_var("GITHUB_TOKEN", "ghp-wins") };
            unsafe { std::env::set_var("GITLAB_TOKEN", "glpat-loses") };

            let config = Config::default();
            let mut ctx = Context::new(config.clone(), ContextOptions::default());
            resolve_scm_token_type(&mut ctx, &config);

            assert_eq!(
                ctx.token_type,
                ScmTokenType::GitHub,
                "ANODIZER_FORCE_TOKEN should take precedence over GORELEASER_FORCE_TOKEN"
            );
            assert_eq!(ctx.options.token.as_deref(), Some("ghp-wins"));
        });
    }

    #[test]
    fn test_resolve_scm_token_type_config_force_token_overrides_env() {
        with_clean_token_env(|| {
            // Config-level force_token should override env var.
            unsafe { std::env::set_var("ANODIZER_FORCE_TOKEN", "gitlab") };
            unsafe { std::env::set_var("GITHUB_TOKEN", "ghp-config") };

            let config = Config {
                force_token: Some(ForceTokenKind::GitHub),
                ..Default::default()
            };
            let mut ctx = Context::new(config.clone(), ContextOptions::default());
            resolve_scm_token_type(&mut ctx, &config);

            assert_eq!(
                ctx.token_type,
                ScmTokenType::GitHub,
                "config.force_token should override ANODIZER_FORCE_TOKEN env var"
            );
            assert_eq!(ctx.options.token.as_deref(), Some("ghp-config"));
        });
    }

    #[test]
    fn test_resolve_scm_token_type_invalid_force_token_env_ignored() {
        with_clean_token_env(|| {
            // Invalid value should be ignored, falling back to env-based detection.
            unsafe { std::env::set_var("ANODIZER_FORCE_TOKEN", "invalid") };
            unsafe { std::env::set_var("GITLAB_TOKEN", "glpat-detected") };

            let config = Config::default();
            let mut ctx = Context::new(config.clone(), ContextOptions::default());
            resolve_scm_token_type(&mut ctx, &config);

            assert_eq!(
                ctx.token_type,
                ScmTokenType::GitLab,
                "invalid ANODIZER_FORCE_TOKEN should fall back to env detection"
            );
            assert_eq!(ctx.options.token.as_deref(), Some("glpat-detected"));
        });
    }

    // ---- collect_build_targets override semantics ---------------------

    #[test]
    fn test_collect_build_targets_per_build_overrides_defaults() {
        use anodizer_core::config::{BuildConfig, Defaults};

        let config = Config {
            project_name: "test".to_string(),
            defaults: Some(Defaults {
                targets: Some(vec!["a".to_string(), "b".to_string()]),
                ..Default::default()
            }),
            crates: vec![CrateConfig {
                name: "k1".to_string(),
                path: ".".to_string(),
                tag_template: "v{{ Version }}".to_string(),
                builds: Some(vec![BuildConfig {
                    targets: Some(vec!["c".to_string()]),
                    ..Default::default()
                }]),
                ..Default::default()
            }],
            ..Default::default()
        };
        let result = collect_build_targets(&config, &[]);
        assert_eq!(
            result,
            vec!["c".to_string()],
            "per-build targets should REPLACE defaults.targets, not concat",
        );
    }

    #[test]
    fn test_collect_build_targets_per_build_none_falls_back_to_defaults() {
        use anodizer_core::config::{BuildConfig, Defaults};

        let config = Config {
            project_name: "test".to_string(),
            defaults: Some(Defaults {
                targets: Some(vec!["a".to_string(), "b".to_string()]),
                ..Default::default()
            }),
            crates: vec![CrateConfig {
                name: "k1".to_string(),
                path: ".".to_string(),
                tag_template: "v{{ Version }}".to_string(),
                builds: Some(vec![BuildConfig {
                    targets: None, // not set; should inherit defaults
                    ..Default::default()
                }]),
                ..Default::default()
            }],
            ..Default::default()
        };
        let result = collect_build_targets(&config, &[]);
        assert_eq!(
            result,
            vec!["a".to_string(), "b".to_string()],
            "build with targets=None should inherit defaults.targets",
        );
    }

    // ---- merge_env_with_defaults --------------------------------------

    #[test]
    fn test_merge_env_with_defaults_both_none_yields_none() {
        assert!(merge_env_with_defaults(None, None).is_none());
    }

    #[test]
    fn test_merge_env_with_defaults_only_defaults_yields_defaults() {
        let d = vec!["FOO=defaults".to_string()];
        let merged = merge_env_with_defaults(Some(&d), None).unwrap();
        assert_eq!(merged, vec!["FOO=defaults".to_string()]);
    }

    #[test]
    fn test_merge_env_with_defaults_only_config_yields_config() {
        let c = vec!["BAR=top".to_string()];
        let merged = merge_env_with_defaults(None, Some(&c)).unwrap();
        assert_eq!(merged, vec!["BAR=top".to_string()]);
    }

    #[test]
    fn test_merge_env_with_defaults_disjoint_keys_concat() {
        // defaults.env contributes when no per-config entry shadows it.
        let d = vec!["FOO=defaults".to_string()];
        let c = vec!["BAR=top".to_string()];
        let merged = merge_env_with_defaults(Some(&d), Some(&c)).unwrap();
        assert_eq!(
            merged,
            vec!["FOO=defaults".to_string(), "BAR=top".to_string()]
        );
    }

    #[test]
    fn test_merge_env_with_defaults_top_level_wins_on_collision() {
        // Defaults provide FOO=a, top-level overrides with FOO=b.
        // Order is defaults-first so the per-key last-write-wins inside
        // setup_env produces FOO=b.
        let d = vec!["FOO=a".to_string()];
        let c = vec!["FOO=b".to_string()];
        let merged = merge_env_with_defaults(Some(&d), Some(&c)).unwrap();
        // Both entries appear; the consumer (setup_env) iterates in order
        // and the last write to a key wins.
        assert_eq!(merged.len(), 2);
        assert_eq!(merged[0], "FOO=a");
        assert_eq!(merged[1], "FOO=b");
    }

    // ---- defaults.env wired into setup_env ------------------------------

    use anodizer_core::config::Defaults;
    use serial_test::serial;

    #[test]
    #[serial]
    fn test_setup_env_inherits_defaults_env_when_crate_unset() {
        with_clean_token_env(|| {
            unsafe { std::env::remove_var("DEFAULTS_ENV_INHERITED") };
            let config = Config {
                defaults: Some(Defaults {
                    env: Some(vec!["DEFAULTS_ENV_INHERITED=defaults".to_string()]),
                    ..Default::default()
                }),
                ..Default::default()
            };
            let mut ctx = Context::new(config.clone(), ContextOptions::default());
            let log =
                anodizer_core::log::StageLogger::new("test", anodizer_core::log::Verbosity::Quiet);
            setup_env(&mut ctx, &config, &log).expect("setup_env should succeed");
            assert_eq!(
                ctx.template_vars()
                    .all_config_env()
                    .get("DEFAULTS_ENV_INHERITED")
                    .map(|s| s.as_str()),
                Some("defaults"),
                "defaults.env entry should populate the template context",
            );
            unsafe { std::env::remove_var("DEFAULTS_ENV_INHERITED") };
        });
    }

    #[test]
    #[serial]
    fn test_setup_env_top_level_env_wins_over_defaults_env() {
        with_clean_token_env(|| {
            unsafe { std::env::remove_var("DEFAULTS_ENV_OVERRIDE") };
            let config = Config {
                defaults: Some(Defaults {
                    env: Some(vec!["DEFAULTS_ENV_OVERRIDE=a".to_string()]),
                    ..Default::default()
                }),
                env: Some(vec!["DEFAULTS_ENV_OVERRIDE=b".to_string()]),
                ..Default::default()
            };
            let mut ctx = Context::new(config.clone(), ContextOptions::default());
            let log =
                anodizer_core::log::StageLogger::new("test", anodizer_core::log::Verbosity::Quiet);
            setup_env(&mut ctx, &config, &log).expect("setup_env should succeed");
            assert_eq!(
                ctx.template_vars()
                    .all_config_env()
                    .get("DEFAULTS_ENV_OVERRIDE")
                    .map(|s| s.as_str()),
                Some("b"),
                "top-level config.env should override defaults.env on duplicate key",
            );
            unsafe { std::env::remove_var("DEFAULTS_ENV_OVERRIDE") };
        });
    }
}