anodizer-core 0.2.0

Core configuration, context, and template engine for the anodizer release tool
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
use crate::artifact::ArtifactRegistry;
use crate::config::Config;
use crate::git::GitInfo;
use crate::log::{StageLogger, Verbosity};
use crate::partial::PartialTarget;
use crate::scm::ScmTokenType;
use crate::template::TemplateVars;
use anyhow::Context as _;
use chrono::Utc;
use std::collections::HashMap;
use std::path::PathBuf;

/// Valid --skip values for the `release` command (matches GoReleaser).
///
/// Publisher skip names use the short canonical form (matching the CLI binary
/// name and GoReleaser convention): `brew`, `choco`, `krew`, `cargo`, etc.
/// Long aliases (e.g. `homebrew`, `chocolatey`) are NOT accepted — DEC-5 forbids
/// aliases; use the short name everywhere (FOLL-1).
pub const VALID_RELEASE_SKIPS: &[&str] = &[
    "publish",
    "announce",
    "sign",
    "validate",
    "sbom",
    "docker",
    "winget",
    "choco",
    "snapcraft",
    "snapcraft-publish",
    "scoop",
    "brew",
    "nix",
    "aur",
    "cargo",
    "krew",
    "nfpm",
    "makeself",
    "flatpak",
    "srpm",
    "before",
    "notarize",
    "archive",
    "source",
    "build",
    "changelog",
    "release",
    "checksum",
    "upx",
    "blob",
    "templatefiles",
    "dmg",
    "msi",
    "nsis",
    "pkg",
    "appbundle",
];

/// Valid --skip values for the `build` command.
pub const VALID_BUILD_SKIPS: &[&str] = &["pre-hooks", "post-hooks", "validate", "before"];

/// Validate that all skip values are in the allowed set.
///
/// Returns `Ok(())` if all values are valid, or `Err` with a descriptive
/// message listing the invalid value(s) and the full set of valid options.
pub fn validate_skip_values(skip: &[String], valid: &[&str]) -> Result<(), String> {
    let invalid: Vec<&str> = skip
        .iter()
        .map(|s| s.as_str())
        .filter(|s| !valid.contains(s))
        .collect();
    if invalid.is_empty() {
        Ok(())
    } else {
        Err(format!(
            "invalid --skip value(s): {}. Valid options: {}",
            invalid.join(", "),
            valid.join(", "),
        ))
    }
}

pub struct ContextOptions {
    pub snapshot: bool,
    pub nightly: bool,
    pub dry_run: bool,
    pub quiet: bool,
    pub verbose: bool,
    pub debug: bool,
    pub skip_stages: Vec<String>,
    pub selected_crates: Vec<String>,
    pub token: Option<String>,
    /// Maximum number of parallel build jobs (minimum 1).
    pub parallelism: usize,
    /// When set, build only for this single host target triple.
    pub single_target: Option<String>,
    /// Path to a custom release notes file (overrides changelog).
    pub release_notes_path: Option<PathBuf>,
    /// When true, abort immediately on first error during publishing.
    pub fail_fast: bool,
    /// Partial build target for split/merge mode. When set, the build stage
    /// filters targets to only those matching this partial target.
    pub partial_target: Option<PartialTarget>,
    /// When true, running with `--merge` flag (merging artifacts from split builds).
    pub merge: bool,
    /// Explicit project root directory. When set, stages use this instead of
    /// discovering the repo root via `git rev-parse --show-toplevel`.
    pub project_root: Option<PathBuf>,
    /// Strict mode: configured features that would silently skip become errors.
    pub strict: bool,
}

impl Default for ContextOptions {
    fn default() -> Self {
        Self {
            snapshot: false,
            nightly: false,
            dry_run: false,
            quiet: false,
            verbose: false,
            debug: false,
            skip_stages: Vec::new(),
            selected_crates: Vec::new(),
            token: None,
            parallelism: 4,
            single_target: None,
            release_notes_path: None,
            fail_fast: false,
            partial_target: None,
            merge: false,
            project_root: None,
            strict: false,
        }
    }
}

/// Stage→stage handoff state produced by stages and consumed by later
/// stages (as opposed to `config` / `options` which are pipeline inputs,
/// or `artifacts` which has its own registry). Closes the F·3 deferral
/// (see `.claude/plans/archive/...`): the changelog stage writes here,
/// the release stage reads here.
#[derive(Debug, Default)]
pub struct StageOutputs {
    /// Set by the changelog stage when `use: github-native` is configured.
    /// The release stage reads this to set `generate_release_notes(true)`
    /// on the GitHub API.
    pub github_native_changelog: bool,
    /// Per-crate rendered changelog body, keyed by crate name.
    pub changelogs: HashMap<String, String>,
    /// Rendered `changelog.header` value, populated by the changelog stage.
    /// The release stage uses it as a fallback when `release.header` is
    /// unset so YAML-configured changelog headers reach the GitHub release
    /// body (matching GoReleaser's `loadContent(ReleaseHeader…)` behaviour).
    pub changelog_header: Option<String>,
    /// Rendered `changelog.footer` value, populated by the changelog stage.
    /// Same fallback semantics as `changelog_header`.
    pub changelog_footer: Option<String>,
}

pub struct Context {
    pub config: Config,
    pub artifacts: ArtifactRegistry,
    pub options: ContextOptions,
    /// Stage→stage handoff outputs (changelog text, header/footer, etc.).
    pub stage_outputs: StageOutputs,
    template_vars: TemplateVars,
    pub git_info: Option<GitInfo>,
    /// The resolved SCM token type (GitHub, GitLab, or Gitea).
    pub token_type: ScmTokenType,
    /// Aggregated skips from per-sub-config loops (signs, docker_signs,
    /// publishers, …). Drained by the pipeline runner at end-of-pipeline so
    /// the summary shows what was intentionally skipped — mirroring
    /// GoReleaser's `pipe.SkipMemento` pattern. The inner `Arc<Mutex<…>>`
    /// lets parallel stage workers contribute without extra plumbing.
    pub skip_memento: crate::pipe_skip::SkipMemento,
}

impl Context {
    pub fn new(config: Config, options: ContextOptions) -> Self {
        let mut vars = TemplateVars::new();
        vars.set("ProjectName", &config.project_name);
        Self {
            config,
            artifacts: ArtifactRegistry::new(),
            options,
            stage_outputs: StageOutputs::default(),
            template_vars: vars,
            git_info: None,
            token_type: ScmTokenType::GitHub,
            skip_memento: crate::pipe_skip::SkipMemento::new(),
        }
    }

    /// Record an intentional skip from a per-sub-config loop
    /// (`signs`, `docker_signs`, `publishers`, …). `stage` identifies the
    /// owning stage, `label` identifies the sub-config (id / name / index),
    /// `reason` is short user-facing text. Duplicate (stage, label, reason)
    /// tuples are dropped on insert so a per-artifact inner loop cannot emit
    /// N copies of the same skip message.
    pub fn remember_skip(&self, stage: &str, label: &str, reason: &str) {
        self.skip_memento.remember(stage, label, reason);
    }

    pub fn template_vars(&self) -> &TemplateVars {
        &self.template_vars
    }

    pub fn template_vars_mut(&mut self) -> &mut TemplateVars {
        &mut self.template_vars
    }

    pub fn render_template(&self, template: &str) -> anyhow::Result<String> {
        crate::template::render(template, &self.template_vars)
    }

    /// Render a template if present, returning `None` for `None` input.
    pub fn render_template_opt(&self, template: Option<&str>) -> anyhow::Result<Option<String>> {
        template.map(|t| self.render_template(t)).transpose()
    }

    /// Evaluate a `skip` field, logging at INFO level when it resolves to true.
    ///
    /// Returns `Ok(false)` when `skip` is `None` or evaluates falsy. On
    /// truthy, writes `"{label} skipped"` via `log.status` and returns
    /// `Ok(true)`. A malformed `skip:` template propagates as `Err` so the
    /// caller fails fast — silently treating a render error as "not skipped"
    /// (the prior behavior) shipped configs that the user thought would
    /// suppress a stage but actually ran it.
    pub fn skip_with_log(
        &self,
        skip: &Option<crate::config::StringOrBool>,
        log: &StageLogger,
        label: &str,
    ) -> anyhow::Result<bool> {
        let Some(d) = skip else {
            return Ok(false);
        };
        let should_skip = d
            .try_evaluates_to_true(|s| self.render_template(s))
            .with_context(|| format!("evaluate skip expression for {label}"))?;
        if should_skip {
            log.status(&format!("{} skipped", label));
        }
        Ok(should_skip)
    }

    pub fn should_skip(&self, stage_name: &str) -> bool {
        self.options.skip_stages.iter().any(|s| s == stage_name)
    }

    /// Check whether "validate" is in the skip list.
    pub fn skip_validate(&self) -> bool {
        self.should_skip("validate")
    }

    pub fn is_dry_run(&self) -> bool {
        self.options.dry_run
    }

    pub fn is_snapshot(&self) -> bool {
        self.options.snapshot
    }

    pub fn is_strict(&self) -> bool {
        self.options.strict
    }

    /// In strict mode, return an error. In normal mode, log a warning and continue.
    /// Use this for any situation where a configured feature silently skips.
    pub fn strict_guard(&self, log: &crate::log::StageLogger, msg: &str) -> anyhow::Result<()> {
        if self.options.strict {
            anyhow::bail!("{} (strict mode)", msg);
        }
        log.warn(msg);
        Ok(())
    }

    /// Defense-in-depth helper for upload-style stages.
    ///
    /// Returns `true` (after logging the skip) when the context is in snapshot
    /// mode. Stages that perform external uploads (registries, package indexes,
    /// object storage, snap store, …) call this at entry so they no-op even
    /// when invoked directly without the orchestration layer's auto-skip.
    /// Centralising the check keeps every publish stage consistent and avoids
    /// per-stage copy-paste.
    pub fn skip_in_snapshot(&self, log: &crate::log::StageLogger, stage: &str) -> bool {
        if self.is_snapshot() {
            log.status(&format!("{}: skipped (snapshot mode)", stage));
            true
        } else {
            false
        }
    }

    /// Render a template, failing in strict mode on error, or falling back to the raw string.
    pub fn render_template_strict(
        &self,
        template: &str,
        label: &str,
        log: &crate::log::StageLogger,
    ) -> anyhow::Result<String> {
        match self.render_template(template) {
            Ok(rendered) => Ok(rendered),
            Err(e) => {
                if self.options.strict {
                    anyhow::bail!("{}: failed to render template: {} (strict mode)", label, e);
                }
                log.warn(&format!("{}: failed to render template: {}", label, e));
                Ok(template.to_string())
            }
        }
    }

    pub fn is_nightly(&self) -> bool {
        self.options.nightly
    }

    /// Set the `ReleaseURL` template variable.
    ///
    /// Should be called after a GitHub release is created, with the URL of
    /// the created release (e.g. `https://github.com/owner/repo/releases/tag/v1.0.0`).
    pub fn set_release_url(&mut self, url: &str) {
        self.template_vars.set("ReleaseURL", url);
    }

    /// Return the current `Version` template variable, or an empty string if
    /// not yet populated.
    pub fn version(&self) -> String {
        self.template_vars
            .get("Version")
            .cloned()
            .unwrap_or_default()
    }

    /// Derive the verbosity level from context options.
    pub fn verbosity(&self) -> Verbosity {
        Verbosity::from_flags(self.options.quiet, self.options.verbose, self.options.debug)
    }

    /// Resolve the user's `retry:` block into a concrete [`RetryPolicy`],
    /// applying defaults when `retry:` is unset. Equivalent to
    /// `ctx.config.retry.unwrap_or_default().to_policy()` but centralizes
    /// the lookup so a future refactor can hang validation / clamping off
    /// a single seam.
    pub fn retry_policy(&self) -> crate::retry::RetryPolicy {
        self.config.retry.unwrap_or_default().to_policy()
    }

    /// Create a [`StageLogger`] for the given stage name, pre-attached to
    /// the context's env-pairs list so that subprocess stderr / stdout
    /// flowing through [`StageLogger::check_output`] is automatically
    /// redacted. The env list combines the template-engine env
    /// (process + config + `.env` files) and the current `std::env::vars`
    /// snapshot, so any secret value reachable to a hook or subprocess is
    /// available for scrubbing.
    pub fn logger(&self, stage: &'static str) -> StageLogger {
        StageLogger::new(stage, self.verbosity()).with_env(self.env_for_redact())
    }

    /// Build the env-pairs list used to seed every [`StageLogger`] created
    /// via [`Context::logger`]. Combines the template-engine env map
    /// (process env + config env + `.env` file values) with the current
    /// `std::env::vars` snapshot, deduplicating by key (template-engine
    /// values win because they reflect any user overrides).
    fn env_for_redact(&self) -> Vec<(String, String)> {
        use std::collections::HashMap;
        let mut map: HashMap<String, String> = std::env::vars().collect();
        for (k, v) in self.template_vars.all_env() {
            map.insert(k.clone(), v.clone());
        }
        map.into_iter().collect()
    }

    /// Populate template variables from `self.git_info`.
    ///
    /// Must be called after `self.git_info` is set. Sets the following vars:
    /// - `Tag`, `Version`, `RawVersion` — tag and version strings
    /// - `Major`, `Minor`, `Patch` — semver components
    /// - `Prerelease` — prerelease suffix (or empty)
    /// - `BuildMetadata` — build metadata from semver tag (or empty)
    /// - `FullCommit`, `Commit` — full commit SHA (`Commit` is alias for `FullCommit`)
    /// - `ShortCommit` — abbreviated commit SHA
    /// - `Branch` — current git branch
    /// - `CommitDate` — ISO 8601 author date of HEAD commit
    /// - `CommitTimestamp` — unix timestamp of HEAD commit
    /// - `IsGitDirty` — "true"/"false"
    /// - `IsGitClean` — "true"/"false" (inverse of `IsGitDirty`)
    /// - `GitTreeState` — "clean"/"dirty"
    /// - `GitURL` — git remote URL
    /// - `Summary` — git describe summary
    /// - `TagSubject` — annotated tag subject or commit subject
    /// - `TagContents` — full annotated tag message or commit message
    /// - `TagBody` — tag message body or commit message body
    /// - `IsSnapshot` — from context options
    /// - `IsNightly` — from context options
    /// - `IsDraft` — "false" (stages may override to "true")
    /// - `IsSingleTarget` — "true"/"false" based on single_target option
    /// - `PreviousTag` — previous matching tag, stripped in monorepo mode (or empty)
    /// - `PrefixedTag` — full tag with monorepo prefix, or tag_prefix-prepended (Pro addition)
    /// - `PrefixedPreviousTag` — full previous tag with prefix (Pro addition)
    /// - `PrefixedSummary` — full summary with prefix (Pro addition)
    /// - `IsRelease` — "true" if not snapshot and not nightly (Pro addition)
    /// - `IsMerging` — "true" if running with --merge flag (Pro addition)
    ///
    /// **Stage-scoped variables** (NOT set here; set per-artifact during stage execution):
    /// - `Binary` — binary name, set by build stage per binary and archive stage per archive
    /// - `ArtifactName` — output artifact filename, set by archive stage after creating each archive
    /// - `ArtifactPath` — absolute path to artifact, set by archive stage after creating each archive
    /// - `ArtifactExt` — artifact file extension (e.g. `.tar.gz`, `.exe`), set alongside ArtifactName
    /// - `ArtifactID` — build config `id` field, set by build stage per build config
    /// - `Os` — target OS, set by archive/nfpm stages per target
    /// - `Arch` — target architecture, set by archive/nfpm stages per target
    /// - `Target` — full target triple (e.g. `x86_64-unknown-linux-gnu`), set alongside Os/Arch
    /// - `Checksums` — combined checksum file contents, set by checksum stage
    pub fn populate_git_vars(&mut self) {
        if let Some(ref info) = self.git_info {
            // RawVersion: just major.minor.patch, no prerelease or build metadata.
            let raw_version = format!(
                "{}.{}.{}",
                info.semver.major, info.semver.minor, info.semver.patch
            );

            // Version: clean semver derived from the parsed SemVer struct, not
            // from the tag string.  The old `tag.strip_prefix('v')` approach
            // broke for monorepo workspace tags like `core-v0.3.2` because it
            // only stripped a leading 'v', leaving `core-v0.3.2` intact.
            // Deriving from the struct handles all tag_template prefixes.
            let mut version = raw_version.clone();
            if let Some(ref pre) = info.semver.prerelease {
                version.push('-');
                version.push_str(pre);
            }
            if let Some(ref meta) = info.semver.build_metadata {
                version.push('+');
                version.push_str(meta);
            }

            self.template_vars.set("Tag", &info.tag);
            self.template_vars.set("Version", &version);
            self.template_vars.set("RawVersion", &raw_version);
            self.template_vars
                .set("Major", &info.semver.major.to_string());
            self.template_vars
                .set("Minor", &info.semver.minor.to_string());
            self.template_vars
                .set("Patch", &info.semver.patch.to_string());
            self.template_vars.set(
                "Prerelease",
                info.semver.prerelease.as_deref().unwrap_or(""),
            );
            self.template_vars.set(
                "BuildMetadata",
                info.semver.build_metadata.as_deref().unwrap_or(""),
            );
            self.template_vars.set("FullCommit", &info.commit);
            self.template_vars.set("Commit", &info.commit);
            self.template_vars.set("ShortCommit", &info.short_commit);
            self.template_vars.set("Branch", &info.branch);
            self.template_vars.set("CommitDate", &info.commit_date);
            self.template_vars
                .set("CommitTimestamp", &info.commit_timestamp);
            self.template_vars
                .set("IsGitDirty", if info.dirty { "true" } else { "false" });
            self.template_vars
                .set("IsGitClean", if info.dirty { "false" } else { "true" });
            self.template_vars
                .set("GitTreeState", if info.dirty { "dirty" } else { "clean" });
            self.template_vars.set("GitURL", &info.remote_url);
            self.template_vars.set("Summary", &info.summary);
            self.template_vars.set("TagSubject", &info.tag_subject);
            self.template_vars.set("TagContents", &info.tag_contents);
            self.template_vars.set("TagBody", &info.tag_body);
            self.template_vars
                .set("PreviousTag", info.previous_tag.as_deref().unwrap_or(""));
            self.template_vars
                .set("FirstCommit", info.first_commit.as_deref().unwrap_or(""));

            // Pro additions: PrefixedTag, PrefixedPreviousTag, PrefixedSummary
            //
            // When monorepo.tag_prefix is configured, the git tag already
            // contains the prefix (e.g. "subproject1/v1.2.3"). In this case:
            //   - Tag = prefix stripped (e.g. "v1.2.3")
            //   - PrefixedTag = full tag (e.g. "subproject1/v1.2.3")
            //   - PrefixedPreviousTag = full previous tag
            //
            // When monorepo is NOT configured, fall back to the original
            // behavior: prepend tag.tag_prefix to construct PrefixedTag.
            let monorepo_prefix = self.config.monorepo_tag_prefix();

            // monorepo.tag_prefix takes precedence over tag.tag_prefix for
            // PrefixedTag / PrefixedPreviousTag / PrefixedSummary behavior.
            // When monorepo is configured, info.tag and info.summary already
            // contain the prefix from git, so we strip for the base vars and
            // use the raw values for the Prefixed variants.
            if let Some(prefix) = monorepo_prefix {
                // Monorepo mode: the tag in git_info is the FULL prefixed tag.
                // PrefixedTag = full tag (already has prefix).
                self.template_vars.set("PrefixedTag", &info.tag);

                // Tag = prefix stripped. Override the Tag we set above.
                let stripped_tag = crate::git::strip_monorepo_prefix(&info.tag, prefix);
                self.template_vars.set("Tag", stripped_tag);

                // Version: derive from the stripped tag (overrides the initial
                // value set above from info.tag, which in monorepo mode still
                // contains the prefix).
                let version = stripped_tag
                    .strip_prefix('v')
                    .unwrap_or(stripped_tag)
                    .to_string();
                self.template_vars.set("Version", &version);

                // PrefixedPreviousTag = full previous tag (already has prefix).
                let prev_tag = info.previous_tag.as_deref().unwrap_or("");
                self.template_vars.set("PrefixedPreviousTag", prev_tag);

                // PreviousTag = prefix stripped, consistent with Tag being stripped.
                let stripped_prev = crate::git::strip_monorepo_prefix(prev_tag, prefix);
                self.template_vars.set("PreviousTag", stripped_prev);

                // PrefixedSummary: info.summary from `git describe` already
                // includes the monorepo prefix (e.g. "subproject1/v1.2.3-0-gabc123d"),
                // so use it as-is for the prefixed variant.
                self.template_vars.set("PrefixedSummary", &info.summary);
                // Summary: strip the monorepo prefix for the base variant.
                let stripped_summary = crate::git::strip_monorepo_prefix(&info.summary, prefix);
                self.template_vars.set("Summary", stripped_summary);
            } else {
                // Non-monorepo: prepend tag.tag_prefix to construct PrefixedTag.
                let tag_prefix = self
                    .config
                    .tag
                    .as_ref()
                    .and_then(|t| t.tag_prefix.as_deref())
                    .unwrap_or("");
                self.template_vars
                    .set("PrefixedTag", &format!("{}{}", tag_prefix, info.tag));
                let prev_tag = info.previous_tag.as_deref().unwrap_or("");
                let prefixed_prev = if prev_tag.is_empty() {
                    String::new()
                } else {
                    format!("{}{}", tag_prefix, prev_tag)
                };
                self.template_vars
                    .set("PrefixedPreviousTag", &prefixed_prev);
                self.template_vars.set(
                    "PrefixedSummary",
                    &format!("{}{}", tag_prefix, info.summary),
                );
            }
        }

        self.template_vars.set(
            "IsSnapshot",
            if self.options.snapshot {
                "true"
            } else {
                "false"
            },
        );
        self.template_vars.set(
            "IsNightly",
            if self.options.nightly {
                "true"
            } else {
                "false"
            },
        );
        // Wire IsDraft from config (GoReleaser reads ctx.Config.Release.Draft).
        let is_draft = self
            .config
            .release
            .as_ref()
            .and_then(|r| r.draft)
            .unwrap_or(false);
        self.template_vars
            .set("IsDraft", if is_draft { "true" } else { "false" });
        self.template_vars.set(
            "IsSingleTarget",
            if self.options.single_target.is_some() {
                "true"
            } else {
                "false"
            },
        );

        // Pro addition: IsRelease — true if this is a regular release (not snapshot, not nightly).
        let is_release = !self.options.snapshot && !self.options.nightly;
        self.template_vars
            .set("IsRelease", if is_release { "true" } else { "false" });

        // Pro addition: IsMerging — true if running with --merge flag.
        self.template_vars.set(
            "IsMerging",
            if self.options.merge { "true" } else { "false" },
        );
    }

    /// Populate time-related template variables using the current UTC time.
    ///
    /// Sets:
    /// - `Date` — current UTC time as RFC 3339
    /// - `Timestamp` — current unix timestamp as string
    /// - `Now` — current UTC time as RFC 3339
    /// - `Year` — four-digit year (e.g. "2026")
    /// - `Month` — zero-padded month (e.g. "03")
    /// - `Day` — zero-padded day (e.g. "30")
    /// - `Hour` — zero-padded hour (e.g. "14")
    /// - `Minute` — zero-padded minute (e.g. "05")
    pub fn populate_time_vars(&mut self) {
        let now = Utc::now();
        self.template_vars.set("Date", &now.to_rfc3339());
        self.template_vars
            .set("Timestamp", &now.timestamp().to_string());
        self.template_vars.set("Now", &now.to_rfc3339());
        self.template_vars
            .set("Year", &now.format("%Y").to_string());
        self.template_vars
            .set("Month", &now.format("%m").to_string());
        self.template_vars.set("Day", &now.format("%d").to_string());
        self.template_vars
            .set("Hour", &now.format("%H").to_string());
        self.template_vars
            .set("Minute", &now.format("%M").to_string());
    }

    /// Populate runtime environment variables.
    ///
    /// Sets:
    /// - `RuntimeGoos` — host OS in Go-compatible naming (e.g. "linux", "darwin", "windows")
    /// - `RuntimeGoarch` — host architecture in Go-compatible naming (e.g. "amd64", "arm64")
    /// - `Runtime_Goos` / `Runtime_Goarch` — GoReleaser-compatible nested aliases
    pub fn populate_runtime_vars(&mut self) {
        let goos = map_os_to_goos(std::env::consts::OS);
        let goarch = map_arch_to_goarch(std::env::consts::ARCH);
        self.template_vars.set("RuntimeGoos", goos);
        self.template_vars.set("RuntimeGoarch", goarch);
        // GoReleaser uses Runtime.Goos / Runtime.Goarch — after preprocessing
        // the dot becomes an underscore-separated flat key. We expose both forms.
        self.template_vars.set("Runtime_Goos", goos);
        self.template_vars.set("Runtime_Goarch", goarch);
    }

    /// Populate the `ReleaseNotes` template variable from stored changelogs.
    ///
    /// Should be called after the changelog stage has run and populated
    /// `self.stage_outputs.changelogs`. Uses the first crate (by config
    /// order) whose changelog is present, or an empty string if no
    /// changelogs exist. Config order is deterministic, unlike HashMap
    /// iteration order.
    pub fn populate_release_notes_var(&mut self) {
        // Look up changelogs in config-defined crate order for determinism.
        let notes = self
            .config
            .crates
            .iter()
            .find_map(|c| self.stage_outputs.changelogs.get(&c.name))
            .cloned()
            .unwrap_or_default();
        self.template_vars.set("ReleaseNotes", &notes);
    }

    /// Refresh the `Artifacts` structured template variable from the current
    /// artifact registry. Should be called before rendering release body and
    /// announce templates so they can iterate over all artifacts.
    ///
    /// Each artifact is serialized as a map with keys: `name`, `path`, `target`,
    /// `kind`, `crate_name`, and `metadata`.
    ///
    /// **Known metadata keys** (populated by individual stages):
    /// - `format` — archive format (e.g. `"tar.gz"`, `"zip"`), set by archive stage
    /// - `extra_file` — `"true"` when artifact is an extra file, set by checksum stage
    /// - `extra_name_template` — name template override for extra files, set by checksum stage
    /// - `digest` — docker image digest (e.g. `sha256:abc123...`), set by docker stage
    /// - `id` — artifact ID from config, set by docker and build stages
    /// - `binary` — binary name, set by build stage
    pub fn refresh_artifacts_var(&mut self) {
        // CSV metadata keys we expose as JSON arrays for template iteration.
        // Storage remains HashMap<String,String> (flat); only the
        // template-exposed view is expanded. Matches GoReleaser's
        // ExtraBinaries / ExtraFiles list semantics.
        const CSV_LIST_KEYS: &[&str] = &["extra_binaries", "extra_files"];

        let artifacts_value: Vec<serde_json::Value> = self
            .artifacts
            .all()
            .iter()
            .map(|a| {
                // Rebuild metadata map converting known CSV keys into arrays.
                let mut metadata_map = serde_json::Map::with_capacity(a.metadata.len());
                for (k, v) in &a.metadata {
                    if CSV_LIST_KEYS.contains(&k.as_str()) {
                        let items: Vec<serde_json::Value> = if v.is_empty() {
                            Vec::new()
                        } else {
                            v.split(',')
                                .map(|s| serde_json::Value::String(s.to_string()))
                                .collect()
                        };
                        metadata_map.insert(k.clone(), serde_json::Value::Array(items));
                    } else {
                        metadata_map.insert(k.clone(), serde_json::Value::String(v.clone()));
                    }
                }
                serde_json::json!({
                    "name": a.name,
                    "path": a.path.to_string_lossy(),
                    "target": a.target.as_deref().unwrap_or(""),
                    "kind": a.kind.as_str(),
                    "crate_name": a.crate_name,
                    "metadata": serde_json::Value::Object(metadata_map),
                })
            })
            .collect();
        // serde_json::Value and tera::Value are the same type under the hood,
        // so no conversion is needed — pass values directly.
        let tera_value = tera::Value::Array(artifacts_value);
        self.template_vars.set_structured("Artifacts", tera_value);
    }

    /// Populate the `Metadata` structured template variable from config.metadata.
    ///
    /// Exposes the project metadata block as a nested map with PascalCase keys
    /// matching GoReleaser's `.Metadata.*` namespace:
    /// `Description`, `Homepage`, `License`, `Maintainers`, `ModTimestamp`,
    /// `FullDescription` (resolved), `CommitAuthor.{Name,Email}`.
    /// Missing fields default to empty strings / empty arrays.
    ///
    /// `full_description` with `from_url` is NOT resolved here (avoids a
    /// reqwest dep in core); the FromUrl case returns an error and the caller
    /// should surface it. Inline and FromFile are resolved synchronously.
    pub fn populate_metadata_var(&mut self) -> anyhow::Result<()> {
        use crate::config::ContentSource;

        // Clone the small scalar fields so we don't hold a borrow on self.config
        // across the render_template calls below.
        let (
            description,
            homepage,
            license,
            maintainers,
            mod_timestamp,
            full_desc_src,
            commit_author,
        ) = {
            let meta = self.config.metadata.as_ref();
            let description = meta
                .and_then(|m| m.description.as_deref())
                .unwrap_or("")
                .to_string();
            let homepage = meta
                .and_then(|m| m.homepage.as_deref())
                .unwrap_or("")
                .to_string();
            let license = meta
                .and_then(|m| m.license.as_deref())
                .unwrap_or("")
                .to_string();
            let maintainers: Vec<String> = meta
                .and_then(|m| m.maintainers.as_ref())
                .cloned()
                .unwrap_or_default();
            let mod_timestamp = meta
                .and_then(|m| m.mod_timestamp.as_deref())
                .unwrap_or("")
                .to_string();
            let full_desc_src = meta.and_then(|m| m.full_description.clone());
            let commit_author = meta.and_then(|m| m.commit_author.clone());
            (
                description,
                homepage,
                license,
                maintainers,
                mod_timestamp,
                full_desc_src,
                commit_author,
            )
        };

        // Resolve full_description (Inline + FromFile in-core; FromUrl errors here).
        let full_description = match full_desc_src {
            None => String::new(),
            Some(ContentSource::Inline(s)) => s,
            Some(ContentSource::FromFile { from_file }) => {
                let rendered_path = self.render_template(&from_file).with_context(|| {
                    format!("metadata.full_description: render path '{}'", from_file)
                })?;
                std::fs::read_to_string(&rendered_path).with_context(|| {
                    format!(
                        "metadata.full_description: read from_file '{}'",
                        rendered_path
                    )
                })?
            }
            Some(ContentSource::FromUrl { .. }) => {
                anyhow::bail!(
                    "metadata.full_description: `from_url` is not yet supported at metadata \
                     population time (core has no HTTP client). Use `from_file` with a \
                     pre-fetched file, or inline the content. Tracked for future: move \
                     URL resolution into a late-pipeline stage or add reqwest to core."
                );
            }
        };

        let commit_author_map = serde_json::json!({
            "Name": commit_author.as_ref().and_then(|c| c.name.clone()).unwrap_or_default(),
            "Email": commit_author.as_ref().and_then(|c| c.email.clone()).unwrap_or_default(),
        });

        let meta_map = serde_json::json!({
            "Description": description,
            "Homepage": homepage,
            "License": license,
            "Maintainers": maintainers,
            "ModTimestamp": mod_timestamp,
            "FullDescription": full_description,
            "CommitAuthor": commit_author_map,
        });
        // serde_json::Value and tera::Value are the same type, so pass directly.
        self.template_vars.set_structured("Metadata", meta_map);
        Ok(())
    }
}

/// Map Rust's `std::env::consts::OS` to Go-compatible GOOS naming.
/// GoReleaser templates expect Go runtime names (e.g. "darwin" not "macos").
pub fn map_os_to_goos(os: &str) -> &str {
    match os {
        "macos" => "darwin",
        other => other, // linux, windows, freebsd, etc. already match
    }
}

/// Map Rust's `std::env::consts::ARCH` to Go-compatible GOARCH naming.
/// GoReleaser templates expect Go runtime names (e.g. "amd64" not "x86_64").
pub fn map_arch_to_goarch(arch: &str) -> &str {
    match arch {
        "x86_64" => "amd64",
        "x86" => "386",
        "aarch64" => "arm64",
        "powerpc64" => "ppc64",
        "s390x" => "s390x",
        "mips" => "mips",
        "mips64" => "mips64",
        "riscv64" => "riscv64",
        other => other,
    }
}

#[cfg(test)]
#[allow(clippy::field_reassign_with_default)]
mod tests {
    use super::*;
    use crate::config::Config;
    use crate::git::{GitInfo, SemVer};

    fn make_git_info(dirty: bool, prerelease: Option<&str>) -> GitInfo {
        let tag = match prerelease {
            Some(pre) => format!("v1.2.3-{pre}"),
            None => "v1.2.3".to_string(),
        };
        GitInfo {
            tag,
            commit: "abc123def456abc123def456abc123def456abc1".to_string(),
            short_commit: "abc123d".to_string(),
            branch: "main".to_string(),
            dirty,
            semver: SemVer {
                major: 1,
                minor: 2,
                patch: 3,
                prerelease: prerelease.map(|s| s.to_string()),
                build_metadata: None,
            },
            commit_date: "2026-03-25T10:30:00+00:00".to_string(),
            commit_timestamp: "1774463400".to_string(),
            previous_tag: Some("v1.2.2".to_string()),
            remote_url: "https://github.com/test/repo.git".to_string(),
            summary: "v1.2.3-0-gabc123d".to_string(),
            tag_subject: "Release v1.2.3".to_string(),
            tag_contents: "Release v1.2.3\n\nFull release notes here.".to_string(),
            tag_body: "Full release notes here.".to_string(),
            first_commit: None,
        }
    }

    #[test]
    fn test_context_template_vars() {
        let mut config = Config::default();
        config.project_name = "test-project".to_string();
        let ctx = Context::new(config, ContextOptions::default());
        assert_eq!(
            ctx.template_vars().get("ProjectName"),
            Some(&"test-project".to_string())
        );
    }

    #[test]
    fn test_context_should_skip() {
        let config = Config::default();
        let opts = ContextOptions {
            skip_stages: vec!["publish".to_string(), "announce".to_string()],
            ..Default::default()
        };
        let ctx = Context::new(config, opts);
        assert!(ctx.should_skip("publish"));
        assert!(ctx.should_skip("announce"));
        assert!(!ctx.should_skip("build"));
    }

    #[test]
    fn test_context_render_template() {
        let mut config = Config::default();
        config.project_name = "myapp".to_string();
        let ctx = Context::new(config, ContextOptions::default());
        let result = ctx.render_template("{{ .ProjectName }}-release").unwrap();
        assert_eq!(result, "myapp-release");
    }

    #[test]
    fn test_populate_git_vars_sets_all_expected_vars() {
        let config = Config::default();
        let mut ctx = Context::new(config, ContextOptions::default());
        ctx.git_info = Some(make_git_info(false, None));
        ctx.populate_git_vars();

        let v = ctx.template_vars();
        assert_eq!(v.get("Tag"), Some(&"v1.2.3".to_string()));
        assert_eq!(v.get("Version"), Some(&"1.2.3".to_string()));
        assert_eq!(v.get("RawVersion"), Some(&"1.2.3".to_string()));
        assert_eq!(v.get("Major"), Some(&"1".to_string()));
        assert_eq!(v.get("Minor"), Some(&"2".to_string()));
        assert_eq!(v.get("Patch"), Some(&"3".to_string()));
        assert_eq!(v.get("Prerelease"), Some(&"".to_string()));
        assert_eq!(
            v.get("FullCommit"),
            Some(&"abc123def456abc123def456abc123def456abc1".to_string())
        );
        assert_eq!(v.get("ShortCommit"), Some(&"abc123d".to_string()));
        assert_eq!(v.get("Branch"), Some(&"main".to_string()));
        assert_eq!(
            v.get("CommitDate"),
            Some(&"2026-03-25T10:30:00+00:00".to_string())
        );
        assert_eq!(v.get("CommitTimestamp"), Some(&"1774463400".to_string()));
        assert_eq!(v.get("PreviousTag"), Some(&"v1.2.2".to_string()));
    }

    #[test]
    fn test_commit_is_alias_for_full_commit() {
        let config = Config::default();
        let mut ctx = Context::new(config, ContextOptions::default());
        ctx.git_info = Some(make_git_info(false, None));
        ctx.populate_git_vars();

        let v = ctx.template_vars();
        assert_eq!(v.get("Commit"), v.get("FullCommit"));
    }

    #[test]
    fn test_populate_git_vars_prerelease() {
        let config = Config::default();
        let mut ctx = Context::new(config, ContextOptions::default());
        ctx.git_info = Some(make_git_info(false, Some("rc.1")));
        ctx.populate_git_vars();

        let v = ctx.template_vars();
        assert_eq!(v.get("Version"), Some(&"1.2.3-rc.1".to_string()));
        assert_eq!(v.get("RawVersion"), Some(&"1.2.3".to_string()));
        assert_eq!(v.get("Prerelease"), Some(&"rc.1".to_string()));
    }

    #[test]
    fn test_build_metadata_template_var() {
        let config = Config::default();
        let mut ctx = Context::new(config, ContextOptions::default());
        let mut info = make_git_info(false, None);
        info.tag = "v1.2.3+build.42".to_string();
        info.semver.build_metadata = Some("build.42".to_string());
        ctx.git_info = Some(info);
        ctx.populate_git_vars();

        let v = ctx.template_vars();
        assert_eq!(v.get("BuildMetadata"), Some(&"build.42".to_string()));
        // Version should include build metadata (strip v prefix only)
        assert_eq!(v.get("Version"), Some(&"1.2.3+build.42".to_string()));
    }

    #[test]
    fn test_build_metadata_empty_when_none() {
        let config = Config::default();
        let mut ctx = Context::new(config, ContextOptions::default());
        ctx.git_info = Some(make_git_info(false, None));
        ctx.populate_git_vars();

        assert_eq!(
            ctx.template_vars().get("BuildMetadata"),
            Some(&"".to_string())
        );
    }

    #[test]
    fn test_populate_git_vars_monorepo_prefixed_tag() {
        // Workspace tags like "core-v0.3.2" should produce Version="0.3.2",
        // not "core-v0.3.2" (which breaks RPM Version fields and templates).
        let config = Config::default();
        let mut ctx = Context::new(config, ContextOptions::default());
        let mut info = make_git_info(false, None);
        info.tag = "core-v0.3.2".to_string();
        info.semver = SemVer {
            major: 0,
            minor: 3,
            patch: 2,
            prerelease: None,
            build_metadata: None,
        };
        ctx.git_info = Some(info);
        ctx.populate_git_vars();

        let v = ctx.template_vars();
        assert_eq!(v.get("Tag"), Some(&"core-v0.3.2".to_string()));
        assert_eq!(v.get("Version"), Some(&"0.3.2".to_string()));
        assert_eq!(v.get("RawVersion"), Some(&"0.3.2".to_string()));
        assert_eq!(v.get("Major"), Some(&"0".to_string()));
        assert_eq!(v.get("Minor"), Some(&"3".to_string()));
        assert_eq!(v.get("Patch"), Some(&"2".to_string()));
    }

    #[test]
    fn test_populate_git_vars_monorepo_prefixed_tag_with_prerelease() {
        let config = Config::default();
        let mut ctx = Context::new(config, ContextOptions::default());
        let mut info = make_git_info(false, None);
        info.tag = "operator-v1.0.0-rc.1".to_string();
        info.semver = SemVer {
            major: 1,
            minor: 0,
            patch: 0,
            prerelease: Some("rc.1".to_string()),
            build_metadata: None,
        };
        ctx.git_info = Some(info);
        ctx.populate_git_vars();

        let v = ctx.template_vars();
        assert_eq!(v.get("Tag"), Some(&"operator-v1.0.0-rc.1".to_string()));
        assert_eq!(v.get("Version"), Some(&"1.0.0-rc.1".to_string()));
        assert_eq!(v.get("RawVersion"), Some(&"1.0.0".to_string()));
    }

    #[test]
    fn test_git_tree_state_clean() {
        let config = Config::default();
        let mut ctx = Context::new(config, ContextOptions::default());
        ctx.git_info = Some(make_git_info(false, None));
        ctx.populate_git_vars();

        let v = ctx.template_vars();
        assert_eq!(v.get("IsGitDirty"), Some(&"false".to_string()));
        assert_eq!(v.get("GitTreeState"), Some(&"clean".to_string()));
    }

    #[test]
    fn test_git_tree_state_dirty() {
        let config = Config::default();
        let mut ctx = Context::new(config, ContextOptions::default());
        ctx.git_info = Some(make_git_info(true, None));
        ctx.populate_git_vars();

        let v = ctx.template_vars();
        assert_eq!(v.get("IsGitDirty"), Some(&"true".to_string()));
        assert_eq!(v.get("GitTreeState"), Some(&"dirty".to_string()));
    }

    #[test]
    fn test_is_snapshot_reflects_context_options() {
        let config = Config::default();
        let opts = ContextOptions {
            snapshot: true,
            ..Default::default()
        };
        let mut ctx = Context::new(config, opts);
        ctx.git_info = Some(make_git_info(false, None));
        ctx.populate_git_vars();

        assert_eq!(
            ctx.template_vars().get("IsSnapshot"),
            Some(&"true".to_string())
        );

        // Non-snapshot
        let config2 = Config::default();
        let opts2 = ContextOptions {
            snapshot: false,
            ..Default::default()
        };
        let mut ctx2 = Context::new(config2, opts2);
        ctx2.git_info = Some(make_git_info(false, None));
        ctx2.populate_git_vars();

        assert_eq!(
            ctx2.template_vars().get("IsSnapshot"),
            Some(&"false".to_string())
        );
    }

    #[test]
    fn test_is_draft_defaults_to_false() {
        let config = Config::default();
        let mut ctx = Context::new(config, ContextOptions::default());
        ctx.git_info = Some(make_git_info(false, None));
        ctx.populate_git_vars();

        assert_eq!(
            ctx.template_vars().get("IsDraft"),
            Some(&"false".to_string())
        );
    }

    #[test]
    fn test_previous_tag_empty_when_none() {
        let config = Config::default();
        let mut ctx = Context::new(config, ContextOptions::default());
        let mut info = make_git_info(false, None);
        info.previous_tag = None;
        ctx.git_info = Some(info);
        ctx.populate_git_vars();

        assert_eq!(
            ctx.template_vars().get("PreviousTag"),
            Some(&"".to_string())
        );
    }

    #[test]
    fn test_populate_time_vars() {
        let config = Config::default();
        let mut ctx = Context::new(config, ContextOptions::default());
        ctx.populate_time_vars();

        let v = ctx.template_vars();

        // Date should be RFC 3339 format (e.g. 2026-03-30T12:00:00+00:00)
        let date = v
            .get("Date")
            .unwrap_or_else(|| panic!("Date should be set"));
        assert!(
            date.contains('T') && date.len() > 10,
            "Date should be RFC 3339, got: {date}"
        );

        // Timestamp should be numeric
        let ts = v
            .get("Timestamp")
            .unwrap_or_else(|| panic!("Timestamp should be set"));
        assert!(
            ts.parse::<i64>().is_ok(),
            "Timestamp should be a numeric string, got: {ts}"
        );

        // Now should be ISO 8601
        let now = v.get("Now").unwrap_or_else(|| panic!("Now should be set"));
        assert!(now.contains('T'), "Now should be ISO 8601, got: {now}");
    }

    #[test]
    fn test_env_vars_accessible_in_templates() {
        let mut config = Config::default();
        config.project_name = "myapp".to_string();
        let mut ctx = Context::new(config, ContextOptions::default());
        ctx.template_vars_mut().set_env("MY_VAR", "hello-world");
        ctx.template_vars_mut().set_env("DEPLOY_ENV", "staging");

        let result = ctx
            .render_template("{{ .Env.MY_VAR }}-{{ .Env.DEPLOY_ENV }}")
            .unwrap();
        assert_eq!(result, "hello-world-staging");
    }

    #[test]
    fn test_populate_git_vars_without_git_info_still_sets_snapshot() {
        let config = Config::default();
        let opts = ContextOptions {
            snapshot: true,
            ..Default::default()
        };
        let mut ctx = Context::new(config, opts);
        // Don't set git_info — populate_git_vars should still set IsSnapshot/IsDraft
        ctx.populate_git_vars();

        assert_eq!(
            ctx.template_vars().get("IsSnapshot"),
            Some(&"true".to_string())
        );
        assert_eq!(
            ctx.template_vars().get("IsDraft"),
            Some(&"false".to_string())
        );
        // Git-specific vars should NOT be set
        assert_eq!(ctx.template_vars().get("Tag"), None);
    }

    #[test]
    fn test_is_nightly_set_when_nightly_mode_active() {
        let config = Config::default();
        let opts = ContextOptions {
            nightly: true,
            ..Default::default()
        };
        let mut ctx = Context::new(config, opts);
        ctx.git_info = Some(make_git_info(false, None));
        ctx.populate_git_vars();

        assert_eq!(
            ctx.template_vars().get("IsNightly"),
            Some(&"true".to_string()),
            "IsNightly should be 'true' when nightly mode is active"
        );
        assert!(ctx.is_nightly(), "is_nightly() should return true");
    }

    #[test]
    fn test_is_nightly_false_by_default() {
        let config = Config::default();
        let mut ctx = Context::new(config, ContextOptions::default());
        ctx.git_info = Some(make_git_info(false, None));
        ctx.populate_git_vars();

        assert_eq!(
            ctx.template_vars().get("IsNightly"),
            Some(&"false".to_string()),
            "IsNightly should default to 'false'"
        );
        assert!(
            !ctx.is_nightly(),
            "is_nightly() should return false by default"
        );
    }

    #[test]
    fn test_version_returns_populated_value() {
        let config = Config::default();
        let mut ctx = Context::new(config, ContextOptions::default());
        ctx.git_info = Some(make_git_info(false, None));
        ctx.populate_git_vars();

        assert_eq!(ctx.version(), "1.2.3");
    }

    #[test]
    fn test_version_returns_empty_when_not_set() {
        let config = Config::default();
        let ctx = Context::new(config, ContextOptions::default());
        assert_eq!(ctx.version(), "");
    }

    #[test]
    fn test_is_nightly_without_git_info() {
        let config = Config::default();
        let opts = ContextOptions {
            nightly: true,
            ..Default::default()
        };
        let mut ctx = Context::new(config, opts);
        // No git_info set — populate_git_vars still sets IsNightly
        ctx.populate_git_vars();

        assert_eq!(
            ctx.template_vars().get("IsNightly"),
            Some(&"true".to_string()),
            "IsNightly should be set even without git info"
        );
    }

    #[test]
    fn test_is_git_clean_when_not_dirty() {
        let config = Config::default();
        let mut ctx = Context::new(config, ContextOptions::default());
        ctx.git_info = Some(make_git_info(false, None));
        ctx.populate_git_vars();

        assert_eq!(
            ctx.template_vars().get("IsGitClean"),
            Some(&"true".to_string())
        );
    }

    #[test]
    fn test_is_git_clean_when_dirty() {
        let config = Config::default();
        let mut ctx = Context::new(config, ContextOptions::default());
        ctx.git_info = Some(make_git_info(true, None));
        ctx.populate_git_vars();

        assert_eq!(
            ctx.template_vars().get("IsGitClean"),
            Some(&"false".to_string())
        );
    }

    #[test]
    fn test_git_url_set_from_git_info() {
        let config = Config::default();
        let mut ctx = Context::new(config, ContextOptions::default());
        ctx.git_info = Some(make_git_info(false, None));
        ctx.populate_git_vars();

        assert_eq!(
            ctx.template_vars().get("GitURL"),
            Some(&"https://github.com/test/repo.git".to_string())
        );
    }

    #[test]
    fn test_summary_set_from_git_info() {
        let config = Config::default();
        let mut ctx = Context::new(config, ContextOptions::default());
        ctx.git_info = Some(make_git_info(false, None));
        ctx.populate_git_vars();

        assert_eq!(
            ctx.template_vars().get("Summary"),
            Some(&"v1.2.3-0-gabc123d".to_string())
        );
    }

    #[test]
    fn test_tag_subject_set_from_git_info() {
        let config = Config::default();
        let mut ctx = Context::new(config, ContextOptions::default());
        ctx.git_info = Some(make_git_info(false, None));
        ctx.populate_git_vars();

        assert_eq!(
            ctx.template_vars().get("TagSubject"),
            Some(&"Release v1.2.3".to_string())
        );
    }

    #[test]
    fn test_tag_contents_set_from_git_info() {
        let config = Config::default();
        let mut ctx = Context::new(config, ContextOptions::default());
        ctx.git_info = Some(make_git_info(false, None));
        ctx.populate_git_vars();

        assert_eq!(
            ctx.template_vars().get("TagContents"),
            Some(&"Release v1.2.3\n\nFull release notes here.".to_string())
        );
    }

    #[test]
    fn test_tag_body_set_from_git_info() {
        let config = Config::default();
        let mut ctx = Context::new(config, ContextOptions::default());
        ctx.git_info = Some(make_git_info(false, None));
        ctx.populate_git_vars();

        assert_eq!(
            ctx.template_vars().get("TagBody"),
            Some(&"Full release notes here.".to_string())
        );
    }

    #[test]
    fn test_is_single_target_false_by_default() {
        let config = Config::default();
        let mut ctx = Context::new(config, ContextOptions::default());
        ctx.git_info = Some(make_git_info(false, None));
        ctx.populate_git_vars();

        assert_eq!(
            ctx.template_vars().get("IsSingleTarget"),
            Some(&"false".to_string())
        );
    }

    #[test]
    fn test_is_single_target_true_when_set() {
        let config = Config::default();
        let opts = ContextOptions {
            single_target: Some("x86_64-unknown-linux-gnu".to_string()),
            ..Default::default()
        };
        let mut ctx = Context::new(config, opts);
        ctx.git_info = Some(make_git_info(false, None));
        ctx.populate_git_vars();

        assert_eq!(
            ctx.template_vars().get("IsSingleTarget"),
            Some(&"true".to_string())
        );
    }

    #[test]
    fn test_populate_runtime_vars() {
        let config = Config::default();
        let mut ctx = Context::new(config, ContextOptions::default());
        ctx.populate_runtime_vars();

        let v = ctx.template_vars();

        let goos = v
            .get("RuntimeGoos")
            .unwrap_or_else(|| panic!("RuntimeGoos should be set"));
        assert!(
            !goos.is_empty(),
            "RuntimeGoos should not be empty, got: {goos}"
        );
        // RuntimeGoos uses Go naming (e.g. "darwin" not "macos")
        assert_eq!(goos, map_os_to_goos(std::env::consts::OS));

        let goarch = v
            .get("RuntimeGoarch")
            .unwrap_or_else(|| panic!("RuntimeGoarch should be set"));
        assert!(
            !goarch.is_empty(),
            "RuntimeGoarch should not be empty, got: {goarch}"
        );
        // RuntimeGoarch uses Go naming (e.g. "amd64" not "x86_64")
        assert_eq!(goarch, map_arch_to_goarch(std::env::consts::ARCH));
    }

    #[test]
    fn test_populate_release_notes_var_with_changelogs() {
        let mut config = Config::default();
        config.crates.push(crate::config::CrateConfig {
            name: "my-crate".to_string(),
            ..Default::default()
        });
        let mut ctx = Context::new(config, ContextOptions::default());
        ctx.stage_outputs
            .changelogs
            .insert("my-crate".to_string(), "## Changes\n- fix bug".to_string());
        ctx.populate_release_notes_var();

        assert_eq!(
            ctx.template_vars().get("ReleaseNotes"),
            Some(&"## Changes\n- fix bug".to_string())
        );
    }

    #[test]
    fn test_populate_release_notes_var_empty_when_no_changelogs() {
        let config = Config::default();
        let mut ctx = Context::new(config, ContextOptions::default());
        ctx.populate_release_notes_var();

        assert_eq!(
            ctx.template_vars().get("ReleaseNotes"),
            Some(&"".to_string())
        );
    }

    #[test]
    fn test_populate_release_notes_var_deterministic_with_multiple_crates() {
        let mut config = Config::default();
        config.crates.push(crate::config::CrateConfig {
            name: "crate-a".to_string(),
            ..Default::default()
        });
        config.crates.push(crate::config::CrateConfig {
            name: "crate-b".to_string(),
            ..Default::default()
        });
        let mut ctx = Context::new(config, ContextOptions::default());
        ctx.stage_outputs
            .changelogs
            .insert("crate-a".to_string(), "notes-a".to_string());
        ctx.stage_outputs
            .changelogs
            .insert("crate-b".to_string(), "notes-b".to_string());
        ctx.populate_release_notes_var();

        // Should always pick the first crate in config order, not arbitrary HashMap order
        assert_eq!(
            ctx.template_vars().get("ReleaseNotes"),
            Some(&"notes-a".to_string())
        );
    }

    #[test]
    fn test_outputs_accessible_in_templates() {
        let mut config = Config::default();
        config.project_name = "myapp".to_string();
        let mut ctx = Context::new(config, ContextOptions::default());
        ctx.template_vars_mut().set_output("build_id", "abc123");
        ctx.template_vars_mut()
            .set_output("deploy_url", "https://example.com");

        let result = ctx
            .render_template("{{ .Outputs.build_id }}-{{ .Outputs.deploy_url }}")
            .unwrap();
        assert_eq!(result, "abc123-https://example.com");
    }

    #[test]
    fn test_artifact_ext_and_target_template_vars() {
        let mut config = Config::default();
        config.project_name = "myapp".to_string();
        let mut ctx = Context::new(config, ContextOptions::default());
        ctx.template_vars_mut().set("ArtifactName", "myapp.tar.gz");
        ctx.template_vars_mut().set("ArtifactExt", ".tar.gz");
        ctx.template_vars_mut()
            .set("Target", "x86_64-unknown-linux-gnu");

        let result = ctx
            .render_template("{{ .ArtifactExt }}_{{ .Target }}")
            .unwrap();
        assert_eq!(result, ".tar.gz_x86_64-unknown-linux-gnu");
    }

    #[test]
    fn test_checksums_template_var() {
        let mut config = Config::default();
        config.project_name = "myapp".to_string();
        let mut ctx = Context::new(config, ContextOptions::default());
        let checksum_text = "abc123  myapp.tar.gz\ndef456  myapp.zip\n";
        ctx.template_vars_mut().set("Checksums", checksum_text);

        let result = ctx.render_template("{{ .Checksums }}").unwrap();
        assert_eq!(result, checksum_text);
    }

    // --- Pro template variable tests ---

    #[test]
    fn test_prefixed_tag_with_tag_prefix() {
        let mut config = Config::default();
        config.tag = Some(crate::config::TagConfig {
            tag_prefix: Some("api/".to_string()),
            ..Default::default()
        });
        let mut ctx = Context::new(config, ContextOptions::default());
        ctx.git_info = Some(make_git_info(false, None));
        ctx.populate_git_vars();

        assert_eq!(
            ctx.template_vars().get("PrefixedTag"),
            Some(&"api/v1.2.3".to_string())
        );
    }

    #[test]
    fn test_prefixed_tag_without_tag_prefix() {
        let config = Config::default();
        let mut ctx = Context::new(config, ContextOptions::default());
        ctx.git_info = Some(make_git_info(false, None));
        ctx.populate_git_vars();

        // No tag_prefix configured — PrefixedTag should equal Tag
        assert_eq!(
            ctx.template_vars().get("PrefixedTag"),
            Some(&"v1.2.3".to_string())
        );
    }

    #[test]
    fn test_prefixed_previous_tag_with_tag_prefix() {
        let mut config = Config::default();
        config.tag = Some(crate::config::TagConfig {
            tag_prefix: Some("api/".to_string()),
            ..Default::default()
        });
        let mut ctx = Context::new(config, ContextOptions::default());
        ctx.git_info = Some(make_git_info(false, None));
        ctx.populate_git_vars();

        assert_eq!(
            ctx.template_vars().get("PrefixedPreviousTag"),
            Some(&"api/v1.2.2".to_string())
        );
    }

    #[test]
    fn test_prefixed_previous_tag_empty_when_no_previous() {
        let mut config = Config::default();
        config.tag = Some(crate::config::TagConfig {
            tag_prefix: Some("api/".to_string()),
            ..Default::default()
        });
        let mut ctx = Context::new(config, ContextOptions::default());
        let mut info = make_git_info(false, None);
        info.previous_tag = None;
        ctx.git_info = Some(info);
        ctx.populate_git_vars();

        // When there is no previous tag, PrefixedPreviousTag should be empty
        // (not just the prefix), matching GoReleaser behavior.
        assert_eq!(
            ctx.template_vars().get("PrefixedPreviousTag"),
            Some(&"".to_string())
        );
    }

    #[test]
    fn test_prefixed_summary_with_tag_prefix() {
        let mut config = Config::default();
        config.tag = Some(crate::config::TagConfig {
            tag_prefix: Some("api/".to_string()),
            ..Default::default()
        });
        let mut ctx = Context::new(config, ContextOptions::default());
        ctx.git_info = Some(make_git_info(false, None));
        ctx.populate_git_vars();

        assert_eq!(
            ctx.template_vars().get("PrefixedSummary"),
            Some(&"api/v1.2.3-0-gabc123d".to_string())
        );
    }

    #[test]
    fn test_is_release_true_for_normal_release() {
        let config = Config::default();
        let opts = ContextOptions {
            snapshot: false,
            nightly: false,
            ..Default::default()
        };
        let mut ctx = Context::new(config, opts);
        ctx.git_info = Some(make_git_info(false, None));
        ctx.populate_git_vars();

        assert_eq!(
            ctx.template_vars().get("IsRelease"),
            Some(&"true".to_string())
        );
    }

    #[test]
    fn test_is_release_false_for_snapshot() {
        let config = Config::default();
        let opts = ContextOptions {
            snapshot: true,
            ..Default::default()
        };
        let mut ctx = Context::new(config, opts);
        ctx.git_info = Some(make_git_info(false, None));
        ctx.populate_git_vars();

        assert_eq!(
            ctx.template_vars().get("IsRelease"),
            Some(&"false".to_string())
        );
    }

    #[test]
    fn test_is_release_false_for_nightly() {
        let config = Config::default();
        let opts = ContextOptions {
            nightly: true,
            ..Default::default()
        };
        let mut ctx = Context::new(config, opts);
        ctx.git_info = Some(make_git_info(false, None));
        ctx.populate_git_vars();

        assert_eq!(
            ctx.template_vars().get("IsRelease"),
            Some(&"false".to_string())
        );
    }

    #[test]
    fn test_is_merging_true_when_merge_flag_set() {
        let config = Config::default();
        let opts = ContextOptions {
            merge: true,
            ..Default::default()
        };
        let mut ctx = Context::new(config, opts);
        ctx.git_info = Some(make_git_info(false, None));
        ctx.populate_git_vars();

        assert_eq!(
            ctx.template_vars().get("IsMerging"),
            Some(&"true".to_string())
        );
    }

    #[test]
    fn test_is_merging_false_by_default() {
        let config = Config::default();
        let mut ctx = Context::new(config, ContextOptions::default());
        ctx.git_info = Some(make_git_info(false, None));
        ctx.populate_git_vars();

        assert_eq!(
            ctx.template_vars().get("IsMerging"),
            Some(&"false".to_string())
        );
    }

    #[test]
    fn test_refresh_artifacts_var_empty() {
        let config = Config::default();
        let mut ctx = Context::new(config, ContextOptions::default());
        ctx.refresh_artifacts_var();

        // Should render as an empty array
        let result = ctx
            .render_template("{% for a in Artifacts %}{{ a.name }}{% endfor %}")
            .unwrap();
        assert_eq!(result, "");
    }

    #[test]
    fn test_refresh_artifacts_var_with_artifacts() {
        use crate::artifact::{Artifact, ArtifactKind};
        use std::collections::HashMap;
        use std::path::PathBuf;

        let config = Config::default();
        let mut ctx = Context::new(config, ContextOptions::default());
        // Artifacts are created with empty `name` — ArtifactRegistry::add()
        // auto-derives the name from the path's filename component when name
        // is empty (see artifact.rs add() implementation).
        ctx.artifacts.add(Artifact {
            kind: ArtifactKind::Archive,
            name: String::new(),
            path: PathBuf::from("dist/myapp-1.0.0-linux-amd64.tar.gz"),
            target: Some("x86_64-unknown-linux-gnu".to_string()),
            crate_name: "myapp".to_string(),
            metadata: HashMap::from([("format".to_string(), "tar.gz".to_string())]),
            size: None,
        });
        ctx.artifacts.add(Artifact {
            kind: ArtifactKind::Binary,
            name: String::new(),
            path: PathBuf::from("dist/myapp"),
            target: Some("x86_64-unknown-linux-gnu".to_string()),
            crate_name: "myapp".to_string(),
            metadata: HashMap::new(),
            size: None,
        });
        ctx.refresh_artifacts_var();

        // Iterate over artifacts and collect names
        let result = ctx
            .render_template("{% for a in Artifacts %}{{ a.name }},{% endfor %}")
            .unwrap();
        assert!(result.contains("myapp-1.0.0-linux-amd64.tar.gz"));
        assert!(result.contains("myapp"));

        // Check kind field
        let result_kinds = ctx
            .render_template("{% for a in Artifacts %}{{ a.kind }},{% endfor %}")
            .unwrap();
        assert!(result_kinds.contains("archive"));
        assert!(result_kinds.contains("binary"));
    }

    #[test]
    fn test_populate_metadata_var_with_mod_timestamp() {
        let mut config = Config::default();
        config.metadata = Some(crate::config::MetadataConfig {
            mod_timestamp: Some("{{ .CommitTimestamp }}".to_string()),
            ..Default::default()
        });
        let mut ctx = Context::new(config, ContextOptions::default());
        ctx.populate_metadata_var().unwrap();

        // Metadata should be accessible as a nested map with PascalCase keys
        let result = ctx.render_template("{{ Metadata.ModTimestamp }}").unwrap();
        assert_eq!(result, "{{ .CommitTimestamp }}");
    }

    #[test]
    fn test_populate_metadata_var_empty_when_no_config() {
        let config = Config::default();
        let mut ctx = Context::new(config, ContextOptions::default());
        ctx.populate_metadata_var().unwrap();

        // Should render empty strings for missing fields (PascalCase keys)
        let result = ctx.render_template("{{ Metadata.Description }}").unwrap();
        assert_eq!(result, "");
    }

    #[test]
    fn test_populate_metadata_var_reads_from_config() {
        let mut config = Config::default();
        config.metadata = Some(crate::config::MetadataConfig {
            description: Some("A test project".to_string()),
            homepage: Some("https://example.com".to_string()),
            license: Some("MIT".to_string()),
            maintainers: Some(vec!["Alice".to_string(), "Bob".to_string()]),
            mod_timestamp: Some("1234567890".to_string()),
            ..Default::default()
        });
        let mut ctx = Context::new(config, ContextOptions::default());
        ctx.populate_metadata_var().unwrap();

        let desc = ctx.render_template("{{ Metadata.Description }}").unwrap();
        assert_eq!(desc, "A test project");

        let home = ctx.render_template("{{ Metadata.Homepage }}").unwrap();
        assert_eq!(home, "https://example.com");

        let lic = ctx.render_template("{{ Metadata.License }}").unwrap();
        assert_eq!(lic, "MIT");

        let ts = ctx.render_template("{{ Metadata.ModTimestamp }}").unwrap();
        assert_eq!(ts, "1234567890");
    }

    #[test]
    fn test_populate_metadata_var_full_description_inline() {
        use crate::config::ContentSource;
        let mut config = Config::default();
        config.metadata = Some(crate::config::MetadataConfig {
            full_description: Some(ContentSource::Inline(
                "A long-form description of the project.".to_string(),
            )),
            ..Default::default()
        });
        let mut ctx = Context::new(config, ContextOptions::default());
        ctx.populate_metadata_var().unwrap();
        let rendered = ctx
            .render_template("{{ Metadata.FullDescription }}")
            .unwrap();
        assert_eq!(rendered, "A long-form description of the project.");
    }

    #[test]
    fn test_populate_metadata_var_full_description_from_file() {
        use crate::config::ContentSource;
        let tmp = tempfile::tempdir().unwrap();
        let desc_path = tmp.path().join("DESCRIPTION.md");
        std::fs::write(&desc_path, "read from disk").unwrap();
        let mut config = Config::default();
        config.metadata = Some(crate::config::MetadataConfig {
            full_description: Some(ContentSource::FromFile {
                from_file: desc_path.to_string_lossy().into_owned(),
            }),
            ..Default::default()
        });
        let mut ctx = Context::new(config, ContextOptions::default());
        ctx.populate_metadata_var().unwrap();
        let rendered = ctx
            .render_template("{{ Metadata.FullDescription }}")
            .unwrap();
        assert_eq!(rendered, "read from disk");
    }

    #[test]
    fn test_populate_metadata_var_full_description_from_url_errors() {
        // Avoids silent-skip footgun (see W1 in pro-features-audit.md). If the user
        // configures from_url for metadata.full_description, emit a clear, actionable
        // error at context-populate time rather than quietly shipping an empty string.
        use crate::config::ContentSource;
        let mut config = Config::default();
        config.metadata = Some(crate::config::MetadataConfig {
            full_description: Some(ContentSource::FromUrl {
                from_url: "https://example.com/description.md".to_string(),
                headers: None,
            }),
            ..Default::default()
        });
        let mut ctx = Context::new(config, ContextOptions::default());
        let err = ctx
            .populate_metadata_var()
            .expect_err("from_url must error");
        let msg = format!("{:#}", err);
        assert!(
            msg.contains("metadata.full_description") && msg.contains("from_url"),
            "error should mention the feature + limitation, got: {msg}"
        );
    }

    #[test]
    fn test_populate_metadata_var_commit_author() {
        use crate::config::CommitAuthorConfig;
        let mut config = Config::default();
        config.metadata = Some(crate::config::MetadataConfig {
            commit_author: Some(CommitAuthorConfig {
                name: Some("Alice Developer".to_string()),
                email: Some("alice@example.com".to_string()),
                signing: None,
                use_github_app_token: false,
            }),
            ..Default::default()
        });
        let mut ctx = Context::new(config, ContextOptions::default());
        ctx.populate_metadata_var().unwrap();
        let name = ctx
            .render_template("{{ Metadata.CommitAuthor.Name }}")
            .unwrap();
        assert_eq!(name, "Alice Developer");
        let email = ctx
            .render_template("{{ Metadata.CommitAuthor.Email }}")
            .unwrap();
        assert_eq!(email, "alice@example.com");
    }

    #[test]
    fn test_artifact_id_template_var() {
        let mut config = Config::default();
        config.project_name = "myapp".to_string();
        let mut ctx = Context::new(config, ContextOptions::default());
        ctx.template_vars_mut().set("ArtifactID", "default");

        let result = ctx.render_template("{{ .ArtifactID }}").unwrap();
        assert_eq!(result, "default");
    }

    #[test]
    fn test_artifact_id_empty_when_not_set() {
        let mut config = Config::default();
        config.project_name = "myapp".to_string();
        let mut ctx = Context::new(config, ContextOptions::default());
        ctx.template_vars_mut().set("ArtifactID", "");

        let result = ctx.render_template("{{ .ArtifactID }}").unwrap();
        assert_eq!(result, "");
    }

    #[test]
    fn test_pro_vars_rendered_in_templates() {
        // Test that all Pro vars can be used in templates together
        let mut config = Config::default();
        config.tag = Some(crate::config::TagConfig {
            tag_prefix: Some("api/".to_string()),
            ..Default::default()
        });
        let opts = ContextOptions {
            snapshot: false,
            nightly: false,
            merge: true,
            ..Default::default()
        };
        let mut ctx = Context::new(config, opts);
        ctx.git_info = Some(make_git_info(false, None));
        ctx.populate_git_vars();

        let result = ctx
            .render_template(
                "{% if IsRelease %}release{% endif %}-{% if IsMerging %}merge{% endif %}-{{ .PrefixedTag }}",
            )
            .unwrap();
        assert_eq!(result, "release-merge-api/v1.2.3");
    }

    #[test]
    fn test_is_release_without_git_info() {
        // IsRelease should still be set even without git info
        let config = Config::default();
        let opts = ContextOptions {
            snapshot: false,
            nightly: false,
            ..Default::default()
        };
        let mut ctx = Context::new(config, opts);
        ctx.populate_git_vars();

        assert_eq!(
            ctx.template_vars().get("IsRelease"),
            Some(&"true".to_string())
        );
    }

    #[test]
    fn test_is_merging_without_git_info() {
        // IsMerging should still be set even without git info
        let config = Config::default();
        let opts = ContextOptions {
            merge: true,
            ..Default::default()
        };
        let mut ctx = Context::new(config, opts);
        ctx.populate_git_vars();

        assert_eq!(
            ctx.template_vars().get("IsMerging"),
            Some(&"true".to_string())
        );
    }

    // -----------------------------------------------------------------------
    // Monorepo template variable tests
    // -----------------------------------------------------------------------

    #[test]
    fn test_monorepo_tag_prefix_strips_tag_for_template_var() {
        let mut config = Config::default();
        config.monorepo = Some(crate::config::MonorepoConfig {
            tag_prefix: Some("subproject1/".to_string()),
            dir: None,
        });
        let mut ctx = Context::new(config, ContextOptions::default());

        // Simulate a monorepo tag: the full prefixed tag is stored in git_info.
        let mut info = make_git_info(false, None);
        info.tag = "subproject1/v1.2.3".to_string();
        info.previous_tag = Some("subproject1/v1.2.2".to_string());
        info.summary = "subproject1/v1.2.3-0-gabc123d".to_string();
        ctx.git_info = Some(info);
        ctx.populate_git_vars();

        let v = ctx.template_vars();
        // Tag should have the prefix stripped.
        assert_eq!(v.get("Tag"), Some(&"v1.2.3".to_string()));
        // Version should derive from stripped tag.
        assert_eq!(v.get("Version"), Some(&"1.2.3".to_string()));
        // PrefixedTag should retain the full tag.
        assert_eq!(
            v.get("PrefixedTag"),
            Some(&"subproject1/v1.2.3".to_string())
        );
        // PreviousTag should be stripped (consistent with Tag).
        assert_eq!(v.get("PreviousTag"), Some(&"v1.2.2".to_string()));
        // PrefixedPreviousTag should retain the full tag.
        assert_eq!(
            v.get("PrefixedPreviousTag"),
            Some(&"subproject1/v1.2.2".to_string())
        );
        // Summary should be stripped.
        assert_eq!(v.get("Summary"), Some(&"v1.2.3-0-gabc123d".to_string()));
        // PrefixedSummary should retain the full summary.
        assert_eq!(
            v.get("PrefixedSummary"),
            Some(&"subproject1/v1.2.3-0-gabc123d".to_string())
        );
    }

    #[test]
    fn test_monorepo_prefixed_previous_tag() {
        let mut config = Config::default();
        config.monorepo = Some(crate::config::MonorepoConfig {
            tag_prefix: Some("svc/".to_string()),
            dir: None,
        });
        let mut ctx = Context::new(config, ContextOptions::default());

        let mut info = make_git_info(false, None);
        info.tag = "svc/v2.0.0".to_string();
        info.previous_tag = Some("svc/v1.9.0".to_string());
        ctx.git_info = Some(info);
        ctx.populate_git_vars();

        let v = ctx.template_vars();
        // PrefixedPreviousTag should be the full previous tag.
        assert_eq!(
            v.get("PrefixedPreviousTag"),
            Some(&"svc/v1.9.0".to_string())
        );
        // PreviousTag should be stripped (prefix removed), consistent with Tag.
        assert_eq!(v.get("PreviousTag"), Some(&"v1.9.0".to_string()));
    }

    #[test]
    fn test_no_monorepo_falls_back_to_tag_prefix() {
        // When monorepo is not set, PrefixedTag should use tag.tag_prefix.
        let mut config = Config::default();
        config.tag = Some(crate::config::TagConfig {
            tag_prefix: Some("release/".to_string()),
            ..Default::default()
        });
        let mut ctx = Context::new(config, ContextOptions::default());
        ctx.git_info = Some(make_git_info(false, None));
        ctx.populate_git_vars();

        let v = ctx.template_vars();
        // Tag is plain "v1.2.3" (not stripped because no monorepo).
        assert_eq!(v.get("Tag"), Some(&"v1.2.3".to_string()));
        // PrefixedTag should prepend tag_prefix.
        assert_eq!(v.get("PrefixedTag"), Some(&"release/v1.2.3".to_string()));
        assert_eq!(
            v.get("PrefixedPreviousTag"),
            Some(&"release/v1.2.2".to_string())
        );
    }

    #[test]
    fn test_monorepo_overrides_tag_prefix_for_prefixed_vars() {
        // When both monorepo.tag_prefix and tag.tag_prefix are set,
        // monorepo should take precedence for PrefixedTag.
        let mut config = Config::default();
        config.tag = Some(crate::config::TagConfig {
            tag_prefix: Some("release/".to_string()),
            ..Default::default()
        });
        config.monorepo = Some(crate::config::MonorepoConfig {
            tag_prefix: Some("svc/".to_string()),
            dir: None,
        });
        let mut ctx = Context::new(config, ContextOptions::default());

        let mut info = make_git_info(false, None);
        info.tag = "svc/v1.2.3".to_string();
        info.previous_tag = Some("svc/v1.2.2".to_string());
        ctx.git_info = Some(info);
        ctx.populate_git_vars();

        let v = ctx.template_vars();
        // Monorepo takes precedence: Tag is stripped.
        assert_eq!(v.get("Tag"), Some(&"v1.2.3".to_string()));
        // PrefixedTag is the full monorepo tag, NOT tag_prefix-prepended.
        assert_eq!(v.get("PrefixedTag"), Some(&"svc/v1.2.3".to_string()));
    }

    #[test]
    fn test_monorepo_prefixed_summary() {
        let mut config = Config::default();
        config.monorepo = Some(crate::config::MonorepoConfig {
            tag_prefix: Some("pkg/".to_string()),
            dir: None,
        });
        let mut ctx = Context::new(config, ContextOptions::default());

        let mut info = make_git_info(false, None);
        info.tag = "pkg/v1.2.3".to_string();
        // In a real monorepo, `git describe` already includes the prefix in the summary.
        info.summary = "pkg/v1.2.3-0-gabc123d".to_string();
        ctx.git_info = Some(info);
        ctx.populate_git_vars();

        // PrefixedSummary is info.summary as-is (already contains prefix).
        assert_eq!(
            ctx.template_vars().get("PrefixedSummary"),
            Some(&"pkg/v1.2.3-0-gabc123d".to_string())
        );
        // Summary should have the prefix stripped.
        assert_eq!(
            ctx.template_vars().get("Summary"),
            Some(&"v1.2.3-0-gabc123d".to_string())
        );
    }

    #[test]
    fn test_monorepo_no_previous_tag() {
        let mut config = Config::default();
        config.monorepo = Some(crate::config::MonorepoConfig {
            tag_prefix: Some("svc/".to_string()),
            dir: None,
        });
        let mut ctx = Context::new(config, ContextOptions::default());

        let mut info = make_git_info(false, None);
        info.tag = "svc/v1.0.0".to_string();
        info.previous_tag = None;
        ctx.git_info = Some(info);
        ctx.populate_git_vars();

        let v = ctx.template_vars();
        assert_eq!(v.get("PrefixedPreviousTag"), Some(&"".to_string()));
        // PreviousTag should also be empty when no previous tag exists.
        assert_eq!(v.get("PreviousTag"), Some(&"".to_string()));
    }

    // -----------------------------------------------------------------------
    // Integration test: full monorepo flow
    // -----------------------------------------------------------------------

    #[test]
    fn test_monorepo_full_flow_all_vars() {
        // End-to-end test: config with monorepo.tag_prefix + dir
        // → context creation → populate_git_vars → verify ALL template vars.
        let mut config = Config::default();
        config.project_name = "mymonorepo".to_string();
        config.monorepo = Some(crate::config::MonorepoConfig {
            tag_prefix: Some("services/api/".to_string()),
            dir: Some("services/api".to_string()),
        });

        // Verify Config helper methods work
        assert_eq!(config.monorepo_tag_prefix(), Some("services/api/"));
        assert_eq!(config.monorepo_dir(), Some("services/api"));

        let mut ctx = Context::new(config, ContextOptions::default());

        // Simulate git info as it would appear in a monorepo:
        // tag and summary already contain the prefix from git.
        let mut info = make_git_info(false, None);
        info.tag = "services/api/v2.1.0".to_string();
        info.previous_tag = Some("services/api/v2.0.5".to_string());
        info.summary = "services/api/v2.1.0-0-gabc123d".to_string();
        info.semver = crate::git::SemVer {
            major: 2,
            minor: 1,
            patch: 0,
            prerelease: None,
            build_metadata: None,
        };
        ctx.git_info = Some(info);
        ctx.populate_git_vars();

        let v = ctx.template_vars();

        // Base vars should have the prefix STRIPPED.
        assert_eq!(v.get("Tag"), Some(&"v2.1.0".to_string()));
        assert_eq!(v.get("Version"), Some(&"2.1.0".to_string()));
        assert_eq!(v.get("RawVersion"), Some(&"2.1.0".to_string()));
        assert_eq!(v.get("Major"), Some(&"2".to_string()));
        assert_eq!(v.get("Minor"), Some(&"1".to_string()));
        assert_eq!(v.get("Patch"), Some(&"0".to_string()));
        assert_eq!(v.get("PreviousTag"), Some(&"v2.0.5".to_string()));
        assert_eq!(v.get("Summary"), Some(&"v2.1.0-0-gabc123d".to_string()));

        // Prefixed vars should retain the FULL prefix.
        assert_eq!(
            v.get("PrefixedTag"),
            Some(&"services/api/v2.1.0".to_string())
        );
        assert_eq!(
            v.get("PrefixedPreviousTag"),
            Some(&"services/api/v2.0.5".to_string())
        );
        assert_eq!(
            v.get("PrefixedSummary"),
            Some(&"services/api/v2.1.0-0-gabc123d".to_string())
        );

        // Project name should be available.
        assert_eq!(v.get("ProjectName"), Some(&"mymonorepo".to_string()));
    }
}