Skip to main content

anodizer_core/
context.rs

1use crate::artifact::ArtifactRegistry;
2use crate::config::Config;
3use crate::env_source::{EnvSource, ProcessEnvSource};
4use crate::git::GitInfo;
5use crate::log::{StageLogger, Verbosity};
6use crate::partial::PartialTarget;
7use crate::publish_report::PublishReport;
8use crate::scm::ScmTokenType;
9use crate::template::TemplateVars;
10use crate::verify_release_summary::VerifyReleaseSummary;
11use anyhow::Context as _;
12use serde::{Deserialize, Serialize};
13use std::collections::HashMap;
14use std::path::PathBuf;
15use std::sync::Arc;
16
17/// Rollback policy after the publish stage. `BestEffort` is the default when
18/// pre-flight ran clean; `None` is the implicit default otherwise (callers
19/// should warn that rollback is disabled). The CLI flag `--rollback=<v>`
20/// sets `ContextOptions::rollback_mode` to `Some(v)` to override the
21/// default-resolution at the dispatch site.
22#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Serialize, Deserialize)]
23#[serde(rename_all = "kebab-case")]
24pub enum RollbackMode {
25    /// Do not attempt rollback. Useful when the operator wants to inspect
26    /// half-published state before deciding.
27    None,
28    /// Run best-effort rollback for every reversible publisher whose
29    /// evidence is present in the report. Most irreversible publishers
30    /// (chocolatey moderation, winget PRs, AUR) are never rolled back —
31    /// the Submitter gate is their only protection. The exception is
32    /// cargo: a partial multi-crate publish that left live crates records
33    /// them and gets those crates yanked even on a failed run.
34    #[default]
35    BestEffort,
36}
37
38/// Valid --skip values for the `release` command.
39///
40/// Skip tokens are stage names plus publisher names. Every publisher's skip
41/// token is its canonical [`crate::Publisher::name`] (the same token
42/// `--publishers` keys on and the same one GoReleaser's `--skip` uses), so
43/// homebrew is `homebrew` and chocolatey is `chocolatey` — there are no short
44/// aliases (`brew`/`choco`). This keeps one denylist vocabulary across the
45/// `--skip` and `--publishers` selectors and matches GoReleaser's `--skip`
46/// keys, so a single name works on both tools.
47pub const VALID_RELEASE_SKIPS: &[&str] = &[
48    "publish",
49    "announce",
50    "sign",
51    "validate",
52    "sbom",
53    "attest",
54    "docker",
55    "docker-sign",
56    "winget",
57    "chocolatey",
58    "snapcraft",
59    "snapcraft-publish",
60    "scoop",
61    "homebrew",
62    "nix",
63    "aur",
64    "cargo",
65    "krew",
66    "nfpm",
67    "makeself",
68    "appimage",
69    "flatpak",
70    "srpm",
71    "before",
72    "before-publish",
73    "notarize",
74    "archive",
75    "source",
76    "build",
77    "changelog",
78    "release",
79    "checksum",
80    "upx",
81    "blob",
82    "templatefiles",
83    "dmg",
84    "msi",
85    "nsis",
86    "pkg",
87    "appbundle",
88    "verify-release",
89];
90
91/// Valid --skip values for the `build` command.
92pub const VALID_BUILD_SKIPS: &[&str] = &["pre-hooks", "post-hooks", "validate", "before"];
93
94/// Validate that all skip values are in the allowed set.
95///
96/// Returns `Ok(())` if all values are valid, or `Err` with a descriptive
97/// message listing the invalid value(s) and the full set of valid options.
98pub fn validate_skip_values(skip: &[String], valid: &[&str]) -> Result<(), String> {
99    let invalid: Vec<&str> = skip
100        .iter()
101        .map(|s| s.as_str())
102        .filter(|s| !valid.contains(s))
103        .collect();
104    if invalid.is_empty() {
105        Ok(())
106    } else {
107        Err(format!(
108            "invalid --skip value(s): {}. Valid options: {}",
109            invalid.join(", "),
110            valid.join(", "),
111        ))
112    }
113}
114
115pub struct ContextOptions {
116    pub snapshot: bool,
117    pub nightly: bool,
118    pub dry_run: bool,
119    pub quiet: bool,
120    pub verbose: bool,
121    pub debug: bool,
122    pub skip_stages: Vec<String>,
123    /// `--publishers`: per-publisher allowlist. Empty means "no allowlist" —
124    /// every publisher runs (subject to `skip_stages`). Non-empty restricts
125    /// the publish stage to exactly the named publishers. Entries are
126    /// canonical publisher names (`Publisher::name()`, e.g. `npm`, `cargo`).
127    /// Orthogonal to `selected_crates` (which scopes crates, not publishers)
128    /// and to `skip_stages` (the unified denylist, which always wins — see
129    /// [`Context::publisher_deselected`]).
130    pub publisher_allowlist: Vec<String>,
131    pub selected_crates: Vec<String>,
132    pub token: Option<String>,
133    /// Maximum number of parallel build jobs (minimum 1).
134    pub parallelism: usize,
135    /// When set, build only for this single host target triple.
136    pub single_target: Option<String>,
137    /// Path to a custom release notes file (overrides changelog).
138    pub release_notes_path: Option<PathBuf>,
139    /// When true, abort immediately on first error during publishing.
140    pub fail_fast: bool,
141    /// Partial build target for split/merge mode. When set, the build stage
142    /// filters targets to only those matching this partial target.
143    pub partial_target: Option<PartialTarget>,
144    /// When true, running with `--merge` flag (merging artifacts from split builds).
145    pub merge: bool,
146    /// `--publish-only`: load artifacts from a preserved dist (written
147    /// by `anodize check determinism --preserve-dist=...`) and run
148    /// only the sign + publish pipeline. The CLI dispatcher uses this
149    /// flag in `setup_env` to defer the GitHub-token check to the
150    /// config-derived environment preflight (the github-release
151    /// publisher's token ladder plus the sign stage's `KeyEnv`
152    /// requirements), which validates token and sign-key material in
153    /// one collect-all pass and bails fail-closed on missing values.
154    /// Without this deferral, `setup_env`'s token check would fire FIRST
155    /// and pre-empt that richer, per-publisher preflight.
156    pub publish_only: bool,
157    /// `--preflight-secrets`: a check-only secrets gate. Like
158    /// [`Self::publish_only`], it defers `setup_env`'s GitHub-token hard
159    /// error to the config-derived environment preflight (run in
160    /// `SecretsOnly` scope), which validates the token ladder alongside
161    /// every other runner-agnostic credential and then exits with zero
162    /// mutations. Without this deferral, `setup_env` would bail on the
163    /// missing token before the secrets gate could report the full set.
164    pub preflight_secrets: bool,
165    /// Explicit project root directory. When set, stages use this instead of
166    /// discovering the repo root via `git rev-parse --show-toplevel`.
167    pub project_root: Option<PathBuf>,
168    /// Strict mode: configured features that would silently skip become errors.
169    pub strict: bool,
170    /// `--resume-release`: opt-in to continue into a release left over from
171    /// a prior failed attempt. Bypasses the leftover-assets pre-check that
172    /// bails when an existing release already has assets and
173    /// `replace_existing_artifacts` is false.
174    pub resume_release: bool,
175    /// `--replace-existing`: CLI override that forces
176    /// `release.replace_existing_artifacts: true` regardless of config.
177    /// The release stage ORs this with the config value.
178    pub replace_existing_artifacts: bool,
179    /// `--no-post-publish-poll`: skip post-publish polling for the
180    /// chocolatey moderation queue and the winget PR validation pipeline.
181    /// When `true`, the polling runner emits `PostPublishStatus::NotPolled`
182    /// (pending immediately) for every publisher rather than waiting on a
183    /// terminal state. Lets CI users with no patience for long-running
184    /// waits opt out without scattering `post_publish_poll.enabled: false`
185    /// across every publisher block.
186    pub skip_post_publish_poll: bool,
187    /// Whether the publisher dispatcher gates irreversible Submitter
188    /// publishers (chocolatey, winget, AUR-source, krew, snapcraft) on
189    /// the success of every required Assets/Manager publisher that ran
190    /// before them. `None` defaults to `Some(true)` (gate on). The CLI
191    /// flag `--no-gate-submitter` flips this to `Some(false)`. See
192    /// `stage-publish::dispatch::DispatchOptions::gate_submitter` for
193    /// the gating mechanics.
194    pub gate_submitter: Option<bool>,
195    /// `--rollback=<none|best-effort>`: post-publish rollback policy.
196    /// `None` means "resolve from preflight state at dispatch time"
197    /// (best-effort when preflight ran clean, none otherwise with a
198    /// warn). Consumed by the rollback-dispatch task.
199    pub rollback_mode: Option<RollbackMode>,
200    /// `--simulate-failure=<publisher>` (repeatable, hidden, env-gated
201    /// behind `ANODIZE_TEST_HARNESS=1`): names of publishers whose
202    /// `run()` should be skipped and a synthetic `Failed("simulated
203    /// failure: <name>")` recorded in the report instead. Lets the
204    /// failure-mode test harness exercise gate / rollback / report
205    /// paths deterministically without monkey-patching production
206    /// publisher code.
207    pub simulate_failure_publishers: Vec<String>,
208    /// `--rollback-only`: skip publish; re-attempt rollback from a
209    /// prior run report. Requires `from_run` to identify which prior
210    /// run's `report.json` to load. The actual replay logic lands in
211    /// a follow-up task; this field is plumbed so the flag is visible
212    /// in `--help` today.
213    pub rollback_only: bool,
214    /// `--allow-rerun`: force `PublishStage::run` to proceed even
215    /// when a prior `report.json` exists for the current `run_id`.
216    /// The default (false) refuses re-runs to prevent PR-based
217    /// publishers (homebrew / scoop / nix / krew / MCP) from
218    /// duplicating their pull requests against the same tag.
219    ///
220    /// Operators recovering from a partial failure should prefer
221    /// `--rollback-only --from-run=<id>` (which has its own
222    /// idempotency guard via `dist/run-<id>/rollback.json`). The
223    /// rerun flag is an escape hatch for advanced cases where the
224    /// operator has manually verified no duplicate-publish risk
225    /// exists.
226    ///
227    /// Audit ref: 2026-05-15 release-resilience-review finding I4.
228    pub allow_rerun: bool,
229    /// `--show-skipped`: surface the per-crate "no `<publisher>` config
230    /// block" skip lines at default verbosity. In workspace mode every
231    /// PR-based publisher (homebrew / nix / scoop / aur / winget / krew /
232    /// chocolatey) visits every selected crate and skips the ones whose
233    /// config lacks its block; at default verbosity those no-op skips are
234    /// routed to debug (invisible unless `--debug`) so they do not bury the
235    /// real output. Setting this flag forces them back to status — the
236    /// diagnostic escape hatch for "why didn't publisher X run for crate Y?".
237    pub show_skipped: bool,
238    /// `--from-run=<id>`: prior run id whose `report.json` to load
239    /// when running in `--rollback-only` mode. clap enforces the
240    /// `requires = "rollback_only"` relationship at parse time.
241    pub from_run: Option<String>,
242    /// `--allow-nondeterministic <name>=<reason>` (repeatable):
243    /// runtime non-determinism opt-outs for specific artifacts. The
244    /// determinism stage suppresses its non-determinism error for
245    /// any matching artifact name, recording the supplied reason in
246    /// the report. Mutually exclusive with `--strict` at the clap
247    /// layer.
248    pub runtime_nondeterministic_allowlist: Vec<(String, String)>,
249    /// `--summary-json=<path>`: when set, the per-publisher run
250    /// summary is written to this path. Consumed by the run-summary
251    /// task.
252    pub summary_json_path: Option<PathBuf>,
253    /// `--allow-ai-failure`: when true, a failure inside the
254    /// `changelog.ai` enhancement step (transport, non-2xx, parse) is
255    /// logged as a warning and the pre-AI release notes are kept
256    /// verbatim. Default `false` (fail-closed) follows the conventional
257    /// "any hook failure aborts" pattern: a silent fall-back to the
258    /// raw notes ships the wrong body without the operator noticing.
259    pub allow_ai_failure: bool,
260    /// `changelog --from <ref>`: explicit lower bound (range start) for
261    /// changelog commit collection. When set, the changelog stage uses this
262    /// ref as the previous tag instead of auto-discovering the latest matching
263    /// tag. A dedicated option (rather than the always-auto-populated
264    /// `PreviousTag` template var) so a full release run's per-crate
265    /// auto-discovery is never overridden — only an explicit `--from` is.
266    pub changelog_from: Option<String>,
267    /// `changelog ..` / `changelog ..<ref>`: an explicit empty lower bound,
268    /// meaning "from the beginning of history" with no auto-discovered
269    /// previous tag. When `true`, the changelog stage skips tag
270    /// auto-discovery entirely so the range covers all reachable commits up
271    /// to the upper bound — distinguishing the explicit empty-from form from
272    /// an omitted range (which still resolves to the last release tag).
273    pub changelog_full_history: bool,
274    /// `changelog <from>..<to>` / `changelog <tag>`: an explicit UPPER bound
275    /// (range end) for changelog commit collection. When set, the changelog
276    /// stage walks `<from>..<to>` instead of `<from>..HEAD`, so commits AFTER
277    /// `<to>` are excluded. A dedicated option (rather than the always-populated
278    /// `Tag` template var) so the pending / snapshot window — where `Tag`
279    /// resolves to the latest EXISTING tag yet the range must still run to
280    /// HEAD — is never silently bounded to that tag. `None` keeps the upper
281    /// bound at `HEAD` (the pending window since the last release).
282    pub changelog_to: Option<String>,
283    /// Marks the run as the standalone `changelog --format release-notes`
284    /// LOCAL preview, NOT the `release`/`tag` pipeline. The standalone command
285    /// is an inspection tool: it must render the pending window from local git
286    /// with no release-time preconditions, so this flag relaxes three guards
287    /// that are correct for a real release but wrong for a preview:
288    ///   - the tag-must-point-at-HEAD + dirty-tree bails in
289    ///     `resolve_git_context` (a preview must not require a checkout or a
290    ///     clean tree),
291    ///   - the snapshot-skip config gate in the changelog stage (a preview
292    ///     must render without `changelog.snapshot: true`),
293    ///   - the `use: github-native` branch (a preview renders from local git
294    ///     instead of requiring a token / emitting empty bodies).
295    ///
296    /// ONLY the standalone changelog command sets this; the release/tag
297    /// pipelines leave it `false` so their guards stay fully intact.
298    pub changelog_preview: bool,
299    /// `--allow-snapshot-publish`: downgrade the publish stage's non-release
300    /// version guard from a hard bail to a warning.
301    ///
302    /// By default the publish, blob, and announce stages REFUSE to ship a
303    /// non-release version (snapshot / dirty / `0.0.0`-sentinel — see
304    /// [`crate::version::guard_release_version`] /
305    /// [`crate::version::is_release_version`]) to an external, often
306    /// irreversible, channel. The canonical accident this prevents: a CI run
307    /// that resolved `0.0.0~SNAPSHOT-<sha>` and pushed it to a package
308    /// registry. This flag is the deliberate opt-in for the legitimate
309    /// "publish a snapshot to a private channel" case; it is the ONLY thing
310    /// required to opt in (the version is not re-stated). Default `false`
311    /// (fail-closed).
312    pub allow_snapshot_publish: bool,
313}
314
315impl Default for ContextOptions {
316    fn default() -> Self {
317        Self {
318            snapshot: false,
319            nightly: false,
320            dry_run: false,
321            quiet: false,
322            verbose: false,
323            debug: false,
324            skip_stages: Vec::new(),
325            publisher_allowlist: Vec::new(),
326            selected_crates: Vec::new(),
327            token: None,
328            parallelism: 4,
329            single_target: None,
330            release_notes_path: None,
331            fail_fast: false,
332            partial_target: None,
333            merge: false,
334            publish_only: false,
335            preflight_secrets: false,
336            project_root: None,
337            strict: false,
338            resume_release: false,
339            replace_existing_artifacts: false,
340            skip_post_publish_poll: false,
341            gate_submitter: None,
342            rollback_mode: None,
343            simulate_failure_publishers: Vec::new(),
344            rollback_only: false,
345            allow_rerun: false,
346            show_skipped: false,
347            from_run: None,
348            runtime_nondeterministic_allowlist: Vec::new(),
349            summary_json_path: None,
350            allow_ai_failure: false,
351            changelog_from: None,
352            changelog_full_history: false,
353            changelog_to: None,
354            changelog_preview: false,
355            allow_snapshot_publish: false,
356        }
357    }
358}
359
360/// Stage→stage handoff state produced by stages and consumed by later
361/// stages (as opposed to `config` / `options` which are pipeline inputs,
362/// or `artifacts` which has its own registry). The changelog stage
363/// writes here, the release stage reads here.
364#[derive(Debug, Default)]
365pub struct StageOutputs {
366    /// Set by the changelog stage when `use: github-native` is configured.
367    /// The release stage reads this to set `generate_release_notes(true)`
368    /// on the GitHub API.
369    pub github_native_changelog: bool,
370    /// Per-crate rendered changelog body, keyed by crate name.
371    pub changelogs: HashMap<String, String>,
372    /// Rendered `changelog.header` value, populated by the changelog stage.
373    /// The release stage uses it as a fallback when `release.header` is
374    /// unset so YAML-configured changelog headers reach the GitHub release
375    /// body (the release-header content-loading behaviour).
376    pub changelog_header: Option<String>,
377    /// Rendered `changelog.footer` value, populated by the changelog stage.
378    /// Same fallback semantics as `changelog_header`.
379    pub changelog_footer: Option<String>,
380    /// Per-publisher post-publish polling results, written by the publish
381    /// stage's chocolatey / winget polling fan-out and consumed by the
382    /// release-summary renderer. Stored as opaque JSON to keep core free
383    /// of stage-publish types (the `PostPublishResult` type lives in
384    /// `anodizer-stage-publish::post_publish::status` and serializes
385    /// stably). Empty when polling was disabled or no eligible
386    /// publishers ran.
387    pub post_publish_results: Vec<serde_json::Value>,
388}
389
390pub struct Context {
391    pub config: Config,
392    pub artifacts: ArtifactRegistry,
393    pub options: ContextOptions,
394    /// Stage→stage handoff outputs (changelog text, header/footer, etc.).
395    pub stage_outputs: StageOutputs,
396    template_vars: TemplateVars,
397    pub git_info: Option<GitInfo>,
398    /// The resolved SCM token type (GitHub, GitLab, or Gitea).
399    pub token_type: ScmTokenType,
400    /// Aggregated skips from per-sub-config loops (signs, docker_signs,
401    /// publishers, …). Drained by the pipeline runner at end-of-pipeline so
402    /// the summary shows what was intentionally skipped — mirroring
403    /// the skip-memento pattern. The inner `Arc<Mutex<…>>`
404    /// lets parallel stage workers contribute without extra plumbing.
405    pub skip_memento: crate::pipe_skip::SkipMemento,
406    /// Trait-based publisher dispatch report, set by `PublishStage::run`
407    /// when the per-publisher dispatcher finishes. `None` until the
408    /// publish stage executes (or when publishing is skipped entirely
409    /// via snapshot mode / `--skip=publish`). Downstream stages
410    /// (SnapcraftPublishStage, AnnounceStage, future Submitter-group
411    /// stages) consult this to apply the submitter-gate / announce-gate
412    /// rules — see `PublishReport::any_failed`.
413    pub publish_report: Option<PublishReport>,
414    /// Whether `PublishStage::run` entered its body this run. Set before
415    /// the pre-dispatch guards (rerun refusal, runtime allowlist), so a
416    /// guard abort leaves this `true` with `publish_report` still `None`
417    /// — the summary placeholder row uses the pair to distinguish
418    /// "publish skipped" from "publish aborted before dispatch".
419    pub publish_attempted: bool,
420    /// Verify-release verdict, set by `VerifyReleaseStage::run` immediately
421    /// before it returns (clean pass OR `bail!`). `None` until the gate runs
422    /// its checks — it stays `None` on the disabled / skipped / dry-run /
423    /// snapshot early-returns, where no published release exists to verify.
424    ///
425    /// Read by the run-summary builder so the end-of-pipeline Summary states
426    /// the verify-release outcome on a SEPARATE axis from the publisher rows:
427    /// the gate runs after the irreversible publish, so the publishes still
428    /// read `succeeded` while this slot records whether the published release
429    /// has unverified defects to investigate.
430    pub verify_release: Option<VerifyReleaseSummary>,
431    /// SOURCE_DATE_EPOCH seed + non-determinism allow-list state for the
432    /// run. `None` until a stage (typically `BuildStage`) seeds it from
433    /// `resolve_reproducible_epoch(commit_timestamp)`; downstream stages
434    /// (`stage-sbom`, `stage-archive`, `stage-sign`) read `sde` to derive
435    /// deterministic timestamps. Lazy-init by design: tests and snapshot
436    /// runs without a clean commit can still proceed.
437    pub determinism: Option<crate::DeterminismState>,
438    /// Per-publisher outcome override published by `Publisher::run` when
439    /// the artifact reached a non-`Succeeded` terminal state but `run`
440    /// still returned `Ok` (e.g. chocolatey moderation skip,
441    /// winget/krew/homebrew PR-already-exists skip). Dispatch consumes
442    /// this slot via `take_pending_outcome()` immediately after `run`
443    /// returns Ok so the per-publisher row in the summary table reads
444    /// `pending-moderation` / `pending-validation` instead of
445    /// `succeeded`. The slot is single-shot: any unread value is
446    /// cleared at the start of every `run` call.
447    pub pending_outcome: Option<crate::PublisherOutcome>,
448    /// Partial [`PublishEvidence`] published by `Publisher::run` BEFORE it
449    /// returned `Err`, so a publisher that did irreversible work for the
450    /// first N items and then failed on item N+1 can still hand the
451    /// rollback path the authoritative record of what actually went live.
452    ///
453    /// The cargo publisher is the motivating case: a multi-crate publish
454    /// that succeeds on crate A then fails on crate B must yank A. On the
455    /// `Ok` path `run` returns its evidence directly; on the `Err` path
456    /// dispatch consumes this slot via [`Context::take_pending_evidence`]
457    /// and records it on the failed publisher's report row so rollback has
458    /// something to act on. Single-shot — drained at the start of every
459    /// `run` and cleared on the `Ok` path.
460    pub pending_evidence: Option<crate::PublishEvidence>,
461    /// Distinct set of crate names the build stage actually built — i.e.
462    /// those that had at least one in-scope build (or `copy_from`) job after
463    /// target resolution. `None` until [`BuildStage`] runs (e.g. merge mode,
464    /// which pre-loads artifacts and never invokes the build stage).
465    ///
466    /// Read by the binary-artifact guard to distinguish "configured a
467    /// binary-requiring surface but legitimately had no in-scope target in
468    /// this shard" (skip) from "was built yet produced no binary" (a real
469    /// mis-scope to fail on). Populated via [`Context::set_built_crate_names`]
470    /// and read via [`Context::built_crate_names`].
471    built_crate_names: Option<std::collections::HashSet<String>>,
472    /// Injectable environment-variable source. Defaults to
473    /// [`ProcessEnvSource`] (reads `std::env::var`). Tests inject a
474    /// [`MapEnvSource`](crate::MapEnvSource) via
475    /// [`TestContextBuilder::env`](crate::test_helpers::TestContextBuilder::env)
476    /// so deterministic branches can be exercised without mutating the
477    /// process env. Read through [`Context::env_var`]; replace via
478    /// [`Context::set_env_source`].
479    env_source: Arc<dyn EnvSource>,
480    /// Optional in-memory log-capture handle. When `Some`, every logger
481    /// produced by [`Context::logger`] attaches it so the test can read
482    /// back aggregated counts of `status` / `warn` / etc. calls without
483    /// having to intercept stderr.
484    ///
485    /// Gated behind the `test-helpers` Cargo feature — production
486    /// binaries do not carry the field at all.
487    #[cfg(feature = "test-helpers")]
488    pub log_capture: Option<crate::log::LogCapture>,
489    /// Runtime-togglable strict-render flag, distinct from the user's global
490    /// `--strict` (`options.strict`). The pre-publish guard flips this on for
491    /// the duration of its in-memory render pass (via [`Context::set_render_strict`])
492    /// so EVERY publisher/announce template it renders propagates its error
493    /// instead of falling back to the raw string — turning a swallowed
494    /// broken-template warning into a release-blocking abort BEFORE any
495    /// irreversible publisher fires. Production publish leaves it `false`, so
496    /// dry-run / snapshot / nightly stay lenient (warn + raw fallback).
497    ///
498    /// A `Cell` (not a plain `bool`) because the render path holds only a
499    /// shared `&Context`: the guard sets it through its `&mut Context`, then
500    /// the deep render helpers toggle-read it through `&Context`.
501    /// [`Context::render_is_strict`] ORs this with `is_strict()`, so the user's
502    /// global `--strict` also makes every render strict everywhere.
503    render_strict: std::cell::Cell<bool>,
504    /// When true, announce message BODIES are treated as already-final text and
505    /// are NOT run through Tera at send time. Set by `anodizer notify` so an
506    /// operator-supplied (possibly untrusted) message — e.g. an on_error error
507    /// string — cannot expand an `Env`-reference into a secret when the
508    /// provider sends it. Only message bodies are affected; titles and other
509    /// templated fields still render normally.
510    pub literal_message: bool,
511    /// When true (the default), outbound announce message BODIES have
512    /// known-secret env values masked before send (same policy as log
513    /// redaction). `anodizer notify --allow-secrets` sets this false to send a
514    /// secret deliberately over a trusted channel. Only the outbound body is
515    /// affected; anodizer's own logs are redacted unconditionally regardless of
516    /// this flag.
517    pub redact_body: bool,
518    /// Memoized `std::env::vars()` snapshot — the immutable half of the
519    /// redaction env. `env_for_redact` is called once per provider per
520    /// dispatch (and per `StageLogger`), and the process env never changes
521    /// for the lifetime of a run, so collecting it once and merging only the
522    /// cheap, dynamic template-var portion fresh on each call avoids
523    /// re-walking the whole process environment every time. Lazily filled on
524    /// first use via [`std::cell::OnceCell`] (Context is already `!Sync` via
525    /// `render_strict`, so the single-threaded cell weakens no auto-trait).
526    process_env_cache: std::cell::OnceCell<std::collections::HashMap<String, String>>,
527}
528
529impl Context {
530    pub fn new(config: Config, options: ContextOptions) -> Self {
531        let mut vars = TemplateVars::new();
532        vars.set("ProjectName", &config.project_name);
533        Self {
534            config,
535            artifacts: ArtifactRegistry::new(),
536            options,
537            stage_outputs: StageOutputs::default(),
538            template_vars: vars,
539            git_info: None,
540            token_type: ScmTokenType::GitHub,
541            skip_memento: crate::pipe_skip::SkipMemento::new(),
542            publish_report: None,
543            publish_attempted: false,
544            verify_release: None,
545            determinism: None,
546            pending_outcome: None,
547            pending_evidence: None,
548            built_crate_names: None,
549            env_source: Arc::new(ProcessEnvSource),
550            #[cfg(feature = "test-helpers")]
551            log_capture: None,
552            render_strict: std::cell::Cell::new(false),
553            literal_message: false,
554            redact_body: true,
555            process_env_cache: std::cell::OnceCell::new(),
556        }
557    }
558
559    /// Redact known-secret env values from outbound announce text, using the
560    /// same combined env (template engine env + process env) and the same
561    /// policy as log redaction. Always redacts; gating on `redact_body` is the
562    /// caller's responsibility (see `render_message_with_default`).
563    pub fn redact(&self, s: &str) -> String {
564        crate::redact::with_env(s, &self.env_for_redact())
565    }
566
567    /// Read an environment variable through the injected source.
568    ///
569    /// Production reads `std::env::var(name).ok()`. Tests inject a
570    /// [`MapEnvSource`](crate::MapEnvSource) via
571    /// [`TestContextBuilder::env`](crate::test_helpers::TestContextBuilder::env)
572    /// so deterministic branches can be exercised without mutating the
573    /// process env.
574    pub fn env_var(&self, name: &str) -> Option<String> {
575        self.env_source.var(name)
576    }
577
578    /// Replace the injected environment-variable source.
579    ///
580    /// Production migration code uses this when wrapping an
581    /// already-constructed context; tests reach this indirectly through
582    /// [`TestContextBuilder::env`](crate::test_helpers::TestContextBuilder::env).
583    pub fn set_env_source<S: EnvSource + 'static>(&mut self, src: S) {
584        self.env_source = Arc::new(src);
585    }
586
587    /// Borrow the injected environment-variable source as a trait
588    /// object so callers can pass it into helpers that take
589    /// `&dyn EnvSource` / `&E: EnvSource + ?Sized` without re-binding
590    /// each var through [`Context::env_var`].
591    pub fn env_source(&self) -> &dyn EnvSource {
592        self.env_source.as_ref()
593    }
594
595    /// Clone the injected environment-variable source as an `Arc` so
596    /// callers can move it into a `tokio::spawn` future or any other
597    /// `'static` closure. Production-default value is
598    /// [`ProcessEnvSource`]; tests may replace it via
599    /// [`Context::set_env_source`].
600    pub fn env_source_arc(&self) -> Arc<dyn EnvSource> {
601        Arc::clone(&self.env_source)
602    }
603
604    /// Attach an in-memory log-capture sink so every logger derived from
605    /// this context via [`Context::logger`] records to it. Intended for
606    /// tests; production callers leave this `None`.
607    ///
608    /// Gated behind the `test-helpers` Cargo feature.
609    #[cfg(feature = "test-helpers")]
610    pub fn with_log_capture(&mut self, capture: crate::log::LogCapture) {
611        self.log_capture = Some(capture);
612    }
613
614    /// Publisher-facing override: when `Publisher::run` returns `Ok`
615    /// but the terminal outcome is something other than `Succeeded`
616    /// (chocolatey moderation skip, winget/krew/homebrew
617    /// PR-already-exists skip, …) call this before returning so
618    /// dispatch records the correct `PublisherOutcome` on the report.
619    /// Without this, dispatch defaults to `Succeeded` on any Ok and
620    /// the summary table silently misreports the skip as success.
621    pub fn record_publisher_outcome(&mut self, outcome: crate::PublisherOutcome) {
622        self.pending_outcome = Some(outcome);
623    }
624
625    /// Dispatch-side consumer: take the pending outcome override (if
626    /// any) recorded by the publisher's `run`. Single-shot — the slot
627    /// is empty after this call.
628    pub fn take_pending_outcome(&mut self) -> Option<crate::PublisherOutcome> {
629        self.pending_outcome.take()
630    }
631
632    /// Publisher-side recorder: stash the partial evidence accumulated
633    /// before a failing `run` returns `Err`, so dispatch can attach it to
634    /// the failed report row and rollback has the authoritative record of
635    /// what went live. See [`Context::pending_evidence`].
636    pub fn record_pending_evidence(&mut self, evidence: crate::PublishEvidence) {
637        self.pending_evidence = Some(evidence);
638    }
639
640    /// Dispatch-side consumer: take the partial evidence (if any) a
641    /// publisher recorded before failing. Single-shot — empty after this
642    /// call.
643    pub fn take_pending_evidence(&mut self) -> Option<crate::PublishEvidence> {
644        self.pending_evidence.take()
645    }
646
647    /// Borrow the publisher dispatch report set by `PublishStage::run`,
648    /// or `None` if the publish stage hasn't run yet (or was skipped).
649    pub fn publish_report(&self) -> Option<&PublishReport> {
650        self.publish_report.as_ref()
651    }
652
653    /// Whether the publish stage entered its body this run (even if it
654    /// aborted before dispatching any publisher).
655    pub fn publish_attempted(&self) -> bool {
656        self.publish_attempted
657    }
658
659    /// Record that the publish stage entered its body. Called by
660    /// `PublishStage::run` ahead of its pre-dispatch guards so guard
661    /// aborts are distinguishable from a skipped stage.
662    pub fn set_publish_attempted(&mut self) {
663        self.publish_attempted = true;
664    }
665
666    /// Store the publisher dispatch report. Overwrites any prior value.
667    ///
668    /// Written by the publish stage during a normal release run; rehydrated by
669    /// `--announce-only` from the on-disk `<dist>/run-<id>/report.json` so the
670    /// announce stage sees an equivalent context without re-publishing.
671    pub fn set_publish_report(&mut self, r: PublishReport) {
672        self.publish_report = Some(r);
673    }
674
675    /// Borrow the set of crate names the build stage actually built, or
676    /// `None` if the build stage has not run in this pipeline (merge mode).
677    pub fn built_crate_names(&self) -> Option<&std::collections::HashSet<String>> {
678        self.built_crate_names.as_ref()
679    }
680
681    /// Record the distinct crate names that received at least one in-scope
682    /// build job. Called once by the build stage after job planning.
683    pub fn set_built_crate_names(&mut self, names: std::collections::HashSet<String>) {
684        self.built_crate_names = Some(names);
685    }
686
687    /// Record an intentional skip from a per-sub-config loop
688    /// (`signs`, `docker_signs`, `publishers`, …). `stage` identifies the
689    /// owning stage, `label` identifies the sub-config (id / name / index),
690    /// `reason` is short user-facing text. Duplicate (stage, label, reason)
691    /// tuples are dropped on insert so a per-artifact inner loop cannot emit
692    /// N copies of the same skip message.
693    pub fn remember_skip(&self, stage: &str, label: &str, reason: &str) {
694        self.skip_memento.remember(stage, label, reason);
695    }
696
697    pub fn template_vars(&self) -> &TemplateVars {
698        &self.template_vars
699    }
700
701    pub fn template_vars_mut(&mut self) -> &mut TemplateVars {
702        &mut self.template_vars
703    }
704
705    pub fn render_template(&self, template: &str) -> anyhow::Result<String> {
706        crate::template::render(template, &self.template_vars)
707    }
708
709    /// Render a template if present, returning `None` for `None` input.
710    pub fn render_template_opt(&self, template: Option<&str>) -> anyhow::Result<Option<String>> {
711        template.map(|t| self.render_template(t)).transpose()
712    }
713
714    /// Evaluate a `skip` field, logging at INFO level when it resolves to true.
715    ///
716    /// Returns `Ok(false)` when `skip` is `None` or evaluates falsy. On
717    /// truthy, writes `"{label} skipped"` via `log.status` and returns
718    /// `Ok(true)`. A malformed `skip:` template propagates as `Err` so the
719    /// caller fails fast — silently treating a render error as "not skipped"
720    /// (the prior behavior) shipped configs that the user thought would
721    /// suppress a stage but actually ran it.
722    pub fn skip_with_log(
723        &self,
724        skip: &Option<crate::config::StringOrBool>,
725        log: &StageLogger,
726        label: &str,
727    ) -> anyhow::Result<bool> {
728        let Some(d) = skip else {
729            return Ok(false);
730        };
731        let should_skip = d
732            .try_evaluates_to_true(|s| self.render_template(s))
733            .with_context(|| format!("evaluate skip expression for {label}"))?;
734        if should_skip {
735            log.status(&format!("{} skipped", label));
736        }
737        Ok(should_skip)
738    }
739
740    /// Whether `stage_name` (or a publisher name — the skip list is unified) is
741    /// in the operator's `--skip` denylist.
742    pub fn should_skip(&self, stage_name: &str) -> bool {
743        self.options.skip_stages.iter().any(|s| s == stage_name)
744    }
745
746    /// Whether the named publisher is excluded from this run by operator
747    /// selection. Combines the two selectors the publish dispatch consults
748    /// before running any publisher:
749    ///
750    /// - `--skip` (`skip_stages`, the UNIFIED denylist holding stage names
751    ///   AND publisher names) ALWAYS wins: a publisher named there is
752    ///   deselected regardless of any allowlist.
753    /// - `--publishers` (`publisher_allowlist`): an EMPTY allowlist deselects
754    ///   nothing (every publisher runs); a NON-EMPTY allowlist deselects every
755    ///   publisher not listed in it.
756    ///
757    /// Returns `true` when the publisher should be reported
758    /// [`crate::publish_report::SkipReason::Deselected`] instead of dispatched.
759    pub fn publisher_deselected(&self, name: &str) -> bool {
760        self.should_skip(name)
761            || (!self.options.publisher_allowlist.is_empty()
762                && !self.options.publisher_allowlist.iter().any(|s| s == name))
763    }
764
765    /// A distinguished, operator-facing summary line for a deselected
766    /// publisher, naming WHICH selector excluded it so the operator can fix
767    /// their command. `--skip` always wins, so it is tested first: a publisher
768    /// named in both selectors reports the denylist cause.
769    ///
770    /// Shared by the dispatch chokepoint and the out-of-dispatch publish
771    /// stages (blob / snapcraft-publish / docker / docker-sign / announce) so the
772    /// "skipped X — excluded via --skip" / "… — not in --publishers allowlist"
773    /// wording is identical everywhere a publisher is deselected. Call only
774    /// when [`Self::publisher_deselected`] is `true`.
775    pub fn deselected_reason(&self, name: &str) -> String {
776        let reason = if self.should_skip(name) {
777            "excluded via --skip"
778        } else {
779            "not in --publishers allowlist"
780        };
781        format!("skipped {name} — {reason}")
782    }
783
784    /// Check whether "validate" is in the skip list.
785    pub fn skip_validate(&self) -> bool {
786        self.should_skip("validate")
787    }
788
789    pub fn is_dry_run(&self) -> bool {
790        self.options.dry_run
791    }
792
793    pub fn is_snapshot(&self) -> bool {
794        self.options.snapshot
795    }
796
797    /// Whether this run is `anodizer release --publish-only` (publishing a
798    /// preserved dist rather than building from source).
799    ///
800    /// Build-time concerns (notably the `binary_signs:` per-binary signing
801    /// loop, whose output is embedded into archives at build time and has no
802    /// publish-time consumer) are gated off this in publish-only mode, where
803    /// the runner carries only publish-time credentials.
804    pub fn is_publish_only(&self) -> bool {
805        self.options.publish_only
806    }
807
808    pub fn is_strict(&self) -> bool {
809        self.options.strict
810    }
811
812    /// Toggle the runtime strict-render flag (see the `render_strict` field).
813    ///
814    /// The pre-publish guard calls this with `true` before its render pass and
815    /// restores the prior value after, so render-error swallowing is suppressed
816    /// only for that in-memory validation — production publish renders stay
817    /// lenient unless the user passed the global `--strict`. Returns the prior
818    /// value so the caller can restore it.
819    pub fn set_render_strict(&self, on: bool) -> bool {
820        self.render_strict.replace(on)
821    }
822
823    /// Whether template renders should propagate errors (strict) rather than
824    /// warn-and-fall-back-to-raw (lenient).
825    ///
826    /// True when EITHER the guard's transient `render_strict` flag is set OR the
827    /// user passed the global `--strict`, so a malformed publisher/announce
828    /// template fails loud under the guard and under `--strict` everywhere.
829    pub fn render_is_strict(&self) -> bool {
830        self.render_strict.get() || self.is_strict()
831    }
832
833    /// In strict mode, return an error. In normal mode, log a warning and continue.
834    /// Use this for any situation where a configured feature silently skips.
835    pub fn strict_guard(&self, log: &crate::log::StageLogger, msg: &str) -> anyhow::Result<()> {
836        if self.options.strict {
837            anyhow::bail!("{} (strict mode)", msg);
838        }
839        log.warn(msg);
840        Ok(())
841    }
842
843    /// Defense-in-depth helper for upload-style stages.
844    ///
845    /// Returns `true` (after logging the skip) when the context is in snapshot
846    /// mode. Stages that perform external uploads (registries, package indexes,
847    /// object storage, snap store, …) call this at entry so they no-op even
848    /// when invoked directly without the orchestration layer's auto-skip.
849    /// Centralising the check keeps every publish stage consistent and avoids
850    /// per-stage copy-paste.
851    pub fn skip_in_snapshot(&self, log: &crate::log::StageLogger, stage: &str) -> bool {
852        if self.is_snapshot() {
853            // The stage name stays in the line: this guard fires on direct
854            // stage invocation, where no pipeline section header has named
855            // the stage yet.
856            log.status(&format!("skipped {stage} — snapshot mode"));
857            true
858        } else {
859            false
860        }
861    }
862
863    /// Render a template, failing in strict mode on error, or falling back to the raw string.
864    pub fn render_template_strict(
865        &self,
866        template: &str,
867        label: &str,
868        log: &crate::log::StageLogger,
869    ) -> anyhow::Result<String> {
870        match self.render_template(template) {
871            Ok(rendered) => Ok(rendered),
872            Err(e) => {
873                if self.options.strict {
874                    anyhow::bail!("{}: failed to render template: {} (strict mode)", label, e);
875                }
876                log.warn(&format!("failed to render template for {}: {}", label, e));
877                Ok(template.to_string())
878            }
879        }
880    }
881
882    pub fn is_nightly(&self) -> bool {
883        self.options.nightly
884    }
885
886    /// Set the `ReleaseURL` template variable.
887    ///
888    /// Should be called after a GitHub release is created, with the URL of
889    /// the created release (e.g. `https://github.com/owner/repo/releases/tag/v1.0.0`).
890    pub fn set_release_url(&mut self, url: &str) {
891        self.template_vars.set("ReleaseURL", url);
892    }
893
894    /// Return the current `Version` template variable, or an empty string if
895    /// not yet populated.
896    pub fn version(&self) -> String {
897        self.template_vars
898            .get("Version")
899            .cloned()
900            .unwrap_or_default()
901    }
902
903    /// Derive the verbosity level from context options.
904    pub fn verbosity(&self) -> Verbosity {
905        Verbosity::from_flags(self.options.quiet, self.options.verbose, self.options.debug)
906    }
907
908    /// Resolve the user's `retry:` block into a concrete [`RetryPolicy`],
909    /// applying defaults when `retry:` is unset. Equivalent to
910    /// `ctx.config.retry.unwrap_or_default().to_policy()` but centralizes
911    /// the lookup so a future refactor can hang validation / clamping off
912    /// a single seam.
913    pub fn retry_policy(&self) -> crate::retry::RetryPolicy {
914        self.config.retry.unwrap_or_default().to_policy()
915    }
916
917    /// Create a [`StageLogger`] for the given stage name, pre-attached to
918    /// the context's env-pairs list so that subprocess stderr / stdout
919    /// flowing through [`StageLogger::check_output`] is automatically
920    /// redacted. The env list combines the template-engine env
921    /// (process + config + `.env` files) and the current `std::env::vars`
922    /// snapshot, so any secret value reachable to a hook or subprocess is
923    /// available for scrubbing.
924    pub fn logger(&self, stage: &'static str) -> StageLogger {
925        #[allow(unused_mut)]
926        let mut log = StageLogger::new(stage, self.verbosity()).with_env(self.env_for_redact());
927        #[cfg(feature = "test-helpers")]
928        if let Some(cap) = &self.log_capture {
929            log = log.with_capture_handle(cap.clone());
930        }
931        log
932    }
933
934    /// Build the env-pairs list used to seed every [`StageLogger`] created
935    /// via [`Context::logger`]. Combines the template-engine env map
936    /// (process env + config env + `.env` file values) with the current
937    /// `std::env::vars` snapshot, deduplicating by key (template-engine
938    /// values win because they reflect any user overrides).
939    ///
940    /// The `std::env::vars` half is memoized in `process_env_cache` (it is
941    /// immutable for the process lifetime); only the cheap template-var
942    /// overlay is rebuilt per call. The merged output is identical to
943    /// collecting both fresh each time.
944    fn env_for_redact(&self) -> Vec<(String, String)> {
945        use std::collections::HashMap;
946        let mut map: HashMap<String, String> = self
947            .process_env_cache
948            .get_or_init(|| std::env::vars().collect())
949            .clone();
950        for (k, v) in self.template_vars.all_env() {
951            map.insert(k.clone(), v.clone());
952        }
953        map.into_iter().collect()
954    }
955
956    /// Populate template variables from `self.git_info`.
957    ///
958    /// Must be called after `self.git_info` is set. Sets the following vars:
959    /// - `Tag`, `Version`, `RawVersion` — tag and version strings
960    /// - `Major`, `Minor`, `Patch` — semver components
961    /// - `Prerelease` — prerelease suffix (or empty)
962    /// - `BuildMetadata` — build metadata from semver tag (or empty)
963    /// - `FullCommit`, `Commit` — full commit SHA (`Commit` is alias for `FullCommit`)
964    /// - `ShortCommit` — abbreviated commit SHA
965    /// - `Branch` — current git branch
966    /// - `CommitDate` — ISO 8601 author date of HEAD commit
967    /// - `CommitTimestamp` — unix timestamp of HEAD commit
968    /// - `IsGitDirty` — "true"/"false"
969    /// - `IsGitClean` — "true"/"false" (inverse of `IsGitDirty`)
970    /// - `GitTreeState` — "clean"/"dirty"
971    /// - `GitURL` — git remote URL
972    /// - `Summary` — git describe summary
973    /// - `TagSubject` — annotated tag subject or commit subject
974    /// - `TagContents` — full annotated tag message or commit message
975    /// - `TagBody` — tag message body or commit message body
976    /// - `IsSnapshot` — from context options
977    /// - `IsNightly` — from context options
978    /// - `IsDraft` — "false" (stages may override to "true")
979    /// - `IsSingleTarget` — "true"/"false" based on single_target option
980    /// - `PreviousTag` — previous matching tag, stripped in monorepo mode (or empty)
981    /// - `PrefixedTag` — full tag with monorepo prefix, or tag_prefix-prepended (Pro addition)
982    /// - `PrefixedPreviousTag` — full previous tag with prefix (Pro addition)
983    /// - `PrefixedSummary` — full summary with prefix (Pro addition)
984    /// - `IsRelease` — "true" if not snapshot and not nightly (Pro addition)
985    /// - `IsMerging` — "true" if running with --merge flag (Pro addition)
986    ///
987    /// **Stage-scoped variables** (NOT set here; set per-artifact during stage execution):
988    /// - `Binary` — binary name, set by build stage per binary and archive stage per archive
989    /// - `ArtifactName` — output artifact filename, set by archive stage after creating each archive
990    /// - `ArtifactPath` — absolute path to artifact, set by archive stage after creating each archive
991    /// - `ArtifactExt` — artifact file extension (e.g. `.tar.gz`, `.exe`), set alongside ArtifactName
992    /// - `ArtifactID` — build config `id` field, set by build stage per build config
993    /// - `Os` — target OS, set by archive/nfpm stages per target
994    /// - `Arch` — target architecture, set by archive/nfpm stages per target
995    /// - `Target` — full target triple (e.g. `x86_64-unknown-linux-gnu`), set alongside Os/Arch
996    /// - `Checksums` — combined checksum file contents, set by checksum stage
997    pub fn populate_git_vars(&mut self) {
998        if let Some(ref info) = self.git_info {
999            // RawVersion: just major.minor.patch, no prerelease or build metadata.
1000            let raw_version = info.semver.raw_version_string();
1001
1002            // Version: clean semver derived from the parsed SemVer struct, not
1003            // from the tag string.  The old `tag.strip_prefix('v')` approach
1004            // broke for monorepo workspace tags like `core-v0.3.2` because it
1005            // only stripped a leading 'v', leaving `core-v0.3.2` intact.
1006            // Deriving from the struct handles all tag_template prefixes.
1007            let version = info.semver.version_string();
1008
1009            self.template_vars.set("Tag", &info.tag);
1010            self.template_vars.set("Version", &version);
1011            self.template_vars.set("RawVersion", &raw_version);
1012            // `Base`: the numeric base semver (no prerelease / build metadata),
1013            // captured before snapshot/nightly version templating overwrites
1014            // `Version`. Lets a nightly `version_template` reference the stable
1015            // base for schemes like `"{{ .Base }}-nightly.{{ .NightlyBuild }}+{{ .ShortCommit }}"`.
1016            self.template_vars.set("Base", &raw_version);
1017            self.template_vars
1018                .set("Major", &info.semver.major.to_string());
1019            self.template_vars
1020                .set("Minor", &info.semver.minor.to_string());
1021            self.template_vars
1022                .set("Patch", &info.semver.patch.to_string());
1023            self.template_vars.set(
1024                "Prerelease",
1025                info.semver.prerelease.as_deref().unwrap_or(""),
1026            );
1027            self.template_vars.set(
1028                "BuildMetadata",
1029                info.semver.build_metadata.as_deref().unwrap_or(""),
1030            );
1031            self.template_vars.set("FullCommit", &info.commit);
1032            self.template_vars.set("Commit", &info.commit);
1033            self.template_vars.set("ShortCommit", &info.short_commit);
1034            self.template_vars.set("Branch", &info.branch);
1035            self.template_vars.set("CommitDate", &info.commit_date);
1036            self.template_vars
1037                .set("CommitTimestamp", &info.commit_timestamp);
1038            self.template_vars.set_bool("IsGitDirty", info.dirty);
1039            self.template_vars.set_bool("IsGitClean", !info.dirty);
1040            self.template_vars
1041                .set("GitTreeState", if info.dirty { "dirty" } else { "clean" });
1042            self.template_vars.set("GitURL", &info.remote_url);
1043            self.template_vars.set("Summary", &info.summary);
1044            self.template_vars.set("TagSubject", &info.tag_subject);
1045            self.template_vars.set("TagContents", &info.tag_contents);
1046            self.template_vars.set("TagBody", &info.tag_body);
1047            self.template_vars
1048                .set("PreviousTag", info.previous_tag.as_deref().unwrap_or(""));
1049            self.template_vars
1050                .set("FirstCommit", info.first_commit.as_deref().unwrap_or(""));
1051
1052            // Pro additions: PrefixedTag, PrefixedPreviousTag, PrefixedSummary
1053            //
1054            // When monorepo.tag_prefix is configured, the git tag already
1055            // contains the prefix (e.g. "subproject1/v1.2.3"). In this case:
1056            //   - Tag = prefix stripped (e.g. "v1.2.3")
1057            //   - PrefixedTag = full tag (e.g. "subproject1/v1.2.3")
1058            //   - PrefixedPreviousTag = full previous tag
1059            //
1060            // When monorepo is NOT configured, fall back to the original
1061            // behavior: prepend tag.tag_prefix to construct PrefixedTag.
1062            let monorepo_prefix = self.config.monorepo_tag_prefix();
1063
1064            // monorepo.tag_prefix takes precedence over tag.tag_prefix for
1065            // PrefixedTag / PrefixedPreviousTag / PrefixedSummary behavior.
1066            // When monorepo is configured, info.tag and info.summary already
1067            // contain the prefix from git, so we strip for the base vars and
1068            // use the raw values for the Prefixed variants.
1069            if let Some(prefix) = monorepo_prefix {
1070                // Monorepo mode: the tag in git_info is the FULL prefixed tag.
1071                // PrefixedTag = full tag (already has prefix).
1072                self.template_vars.set("PrefixedTag", &info.tag);
1073
1074                // Tag = prefix stripped. Override the Tag we set above.
1075                let stripped_tag = crate::git::strip_monorepo_prefix(&info.tag, prefix);
1076                self.template_vars.set("Tag", stripped_tag);
1077
1078                // Version: derived from the parsed SemVer struct (same source as
1079                // the non-monorepo path and the build stage's per-crate
1080                // re-scoping) so all three stay byte-identical. `info.semver`
1081                // was parsed from the full prefixed tag, so it already excludes
1082                // the monorepo prefix — no separate string-strip needed.
1083                //
1084                // For a non-semver tag under `--skip=validate`, info.semver is
1085                // the skip-validate fallback, so this yields "0.0.0" rather than
1086                // the old raw prefix-stripped string.
1087                let version = info.semver.version_string();
1088                self.template_vars.set("Version", &version);
1089
1090                // PrefixedPreviousTag = full previous tag (already has prefix).
1091                let prev_tag = info.previous_tag.as_deref().unwrap_or("");
1092                self.template_vars.set("PrefixedPreviousTag", prev_tag);
1093
1094                // PreviousTag = prefix stripped, consistent with Tag being stripped.
1095                let stripped_prev = crate::git::strip_monorepo_prefix(prev_tag, prefix);
1096                self.template_vars.set("PreviousTag", stripped_prev);
1097
1098                // PrefixedSummary: info.summary from `git describe` already
1099                // includes the monorepo prefix (e.g. "subproject1/v1.2.3-0-gabc123d"),
1100                // so use it as-is for the prefixed variant.
1101                self.template_vars.set("PrefixedSummary", &info.summary);
1102                // Summary: strip the monorepo prefix for the base variant.
1103                let stripped_summary = crate::git::strip_monorepo_prefix(&info.summary, prefix);
1104                self.template_vars.set("Summary", stripped_summary);
1105            } else {
1106                // Non-monorepo: prepend tag.tag_prefix to construct PrefixedTag.
1107                let tag_prefix = self
1108                    .config
1109                    .tag
1110                    .as_ref()
1111                    .and_then(|t| t.tag_prefix.as_deref())
1112                    .unwrap_or("");
1113                self.template_vars
1114                    .set("PrefixedTag", &format!("{}{}", tag_prefix, info.tag));
1115                let prev_tag = info.previous_tag.as_deref().unwrap_or("");
1116                let prefixed_prev = if prev_tag.is_empty() {
1117                    String::new()
1118                } else {
1119                    format!("{}{}", tag_prefix, prev_tag)
1120                };
1121                self.template_vars
1122                    .set("PrefixedPreviousTag", &prefixed_prev);
1123                self.template_vars.set(
1124                    "PrefixedSummary",
1125                    &format!("{}{}", tag_prefix, info.summary),
1126                );
1127            }
1128        }
1129
1130        // `NightlyBuild`: stateless per-base-version build counter derived
1131        // from `git rev-list --count <last-tag>..HEAD`. Resets automatically
1132        // when a new version tag lands (no state anodizer persists). Set
1133        // unconditionally (it is just a count), but intended for nightly /
1134        // snapshot `version_template`s such as
1135        // `"{{ .Base }}-nightly.{{ .NightlyBuild }}+{{ .ShortCommit }}"`.
1136        // Defaults to "0" outside a git repo (synthetic snapshot/scratch
1137        // builds) and on any git error so templates never fail to render.
1138        //
1139        // The monorepo prefix constrains the last-tag lookup to the active
1140        // crate's tags so per-crate workspace runs count since the right
1141        // tag (not the nearest tag from another subproject).
1142        let nightly_build = if self.git_info.is_some() {
1143            let root = self
1144                .options
1145                .project_root
1146                .clone()
1147                .unwrap_or_else(|| PathBuf::from("."));
1148            let monorepo_prefix = self.config.monorepo_tag_prefix();
1149            crate::git::count_commits_since_last_tag_in(&root, monorepo_prefix).unwrap_or(0)
1150        } else {
1151            0
1152        };
1153        self.template_vars
1154            .set_structured("NightlyBuild", tera::Value::from(nightly_build));
1155
1156        // Mode flags are injected as real bools (not "true"/"false" strings)
1157        // so `not IsSnapshot` / `IsSnapshot == false` / bare `{% if … %}`
1158        // forms all evaluate correctly; `{{ IsSnapshot }}` interpolation
1159        // still renders "true"/"false".
1160        self.template_vars
1161            .set_bool("IsSnapshot", self.options.snapshot);
1162        self.template_vars
1163            .set_bool("IsNightly", self.options.nightly);
1164        // Surfaced to user `if_condition:` templates so stages can
1165        // selectively run inside the determinism harness even when
1166        // `not IsSnapshot` would otherwise skip them.
1167        self.template_vars.set_bool(
1168            "IsHarness",
1169            self.env_var("ANODIZER_IN_DETERMINISM_HARNESS").is_some(),
1170        );
1171        // Wire IsDraft from `release.draft`.
1172        let is_draft = self
1173            .config
1174            .release
1175            .as_ref()
1176            .and_then(|r| r.draft)
1177            .unwrap_or(false);
1178        self.template_vars.set_bool("IsDraft", is_draft);
1179        self.template_vars
1180            .set_bool("IsSingleTarget", self.options.single_target.is_some());
1181
1182        // Pro addition: IsRelease — true if this is a regular release (not snapshot, not nightly).
1183        let is_release = !self.options.snapshot && !self.options.nightly;
1184        self.template_vars.set_bool("IsRelease", is_release);
1185
1186        // Pro addition: IsMerging — true if running with --merge flag.
1187        self.template_vars.set_bool("IsMerging", self.options.merge);
1188    }
1189
1190    /// Populate time-related template variables.
1191    ///
1192    /// Sets:
1193    /// - `Date` — UTC time as RFC 3339
1194    /// - `Timestamp` — unix timestamp as string
1195    /// - `Now` — UTC time as RFC 3339
1196    /// - `Year` — four-digit year (e.g. "2026")
1197    /// - `Month` — zero-padded month (e.g. "03")
1198    /// - `Day` — zero-padded day (e.g. "30")
1199    /// - `Hour` — zero-padded hour (e.g. "14")
1200    /// - `Minute` — zero-padded minute (e.g. "05")
1201    ///
1202    /// Time source resolution (first match wins):
1203    ///
1204    /// 1. `SOURCE_DATE_EPOCH` env var — the standard reproducibility contract
1205    ///    (set by the determinism harness on every child release subprocess,
1206    ///    and the conventional way external CI / packagers signal a fixed
1207    ///    epoch). This is load-bearing for byte-stability of `metadata.json`
1208    ///    (which embeds `Date`) and any user template that consumes `Date` /
1209    ///    `Timestamp` / `Now`. Without this branch, two from-clean runs of
1210    ///    the same commit emit metadata.json files that differ in the `date`
1211    ///    field, defeating release-asset idempotency.
1212    /// 2. `chrono::Utc::now()` — wall-clock fallback. The
1213    ///    legacy semantics for runs without SDE wired in. Note that the
1214    ///    template docs explicitly call `.Now` "not deterministic"
1215    ///    — under SDE-aware reproducible builds we deviate from that
1216    ///    behavior intentionally.
1217    pub fn populate_time_vars(&mut self) {
1218        // Resolution order (SDE first, else wall-clock) is centralized in
1219        // `crate::sde::resolve_now_with_env` so any caller —
1220        // `populate_time_vars`, Tera built-ins, stage-srpm's `%changelog`
1221        // date, nightly `date_str` — sees identical "now" semantics.
1222        // Routes through the injected `env_source` so tests can inject
1223        // SOURCE_DATE_EPOCH via TestContextBuilder::env() without
1224        // mutating the process env.
1225        let now = crate::sde::resolve_now_with_env(self.env_source());
1226        self.template_vars.set("Date", &now.to_rfc3339());
1227        self.template_vars
1228            .set("Timestamp", &now.timestamp().to_string());
1229        self.template_vars.set("Now", &now.to_rfc3339());
1230        self.template_vars
1231            .set("Year", &now.format("%Y").to_string());
1232        self.template_vars
1233            .set("Month", &now.format("%m").to_string());
1234        self.template_vars.set("Day", &now.format("%d").to_string());
1235        self.template_vars
1236            .set("Hour", &now.format("%H").to_string());
1237        self.template_vars
1238            .set("Minute", &now.format("%M").to_string());
1239    }
1240
1241    /// Populate runtime environment variables.
1242    ///
1243    /// Sets:
1244    /// - `RuntimeGoos` — host OS in Go-compatible naming (e.g. "linux", "darwin", "windows")
1245    /// - `RuntimeGoarch` — host architecture in Go-compatible naming (e.g. "amd64", "arm64")
1246    /// - `Runtime_Goos` / `Runtime_Goarch` — nested aliases
1247    /// - `RustcVersion` — host rustc release version (e.g. "1.96.0"), or "" when
1248    ///   rustc is unavailable
1249    pub fn populate_runtime_vars(&mut self) {
1250        let goos = map_os_to_goos(std::env::consts::OS);
1251        let goarch = map_arch_to_goarch(std::env::consts::ARCH);
1252        self.template_vars.set("RuntimeGoos", goos);
1253        self.template_vars.set("RuntimeGoarch", goarch);
1254        // Runtime.Goos / Runtime.Goarch — after preprocessing
1255        // the dot becomes an underscore-separated flat key. We expose both forms.
1256        self.template_vars.set("Runtime_Goos", goos);
1257        self.template_vars.set("Runtime_Goarch", goarch);
1258        // RustcVersion is a host-environment fact like OS/arch, so it is set in
1259        // the same call — keeping it a separate populate step risks a call-site
1260        // forgetting to invoke the sibling.
1261        self.populate_rustc_vars();
1262    }
1263
1264    /// Populate the `RustcVersion` built-in template variable.
1265    ///
1266    /// Probes `rustc -vV` and extracts the `release:` line (e.g. `"1.96.0"`).
1267    /// Sets `RustcVersion` to the extracted string, or to `""` when rustc is
1268    /// unavailable or the line is absent — templates that reference
1269    /// `{{ .RustcVersion }}` degrade to an empty value rather than erroring.
1270    fn populate_rustc_vars(&mut self) {
1271        let ver = crate::partial::detect_rustc_version().unwrap_or_default();
1272        self.template_vars.set("RustcVersion", &ver);
1273    }
1274
1275    /// Populate the `ReleaseNotes` template variable from stored changelogs.
1276    ///
1277    /// Should be called after the changelog stage has run and populated
1278    /// `self.stage_outputs.changelogs`. Uses the first crate (by config
1279    /// order) whose changelog is present, or an empty string if no
1280    /// changelogs exist. Config order is deterministic, unlike HashMap
1281    /// iteration order.
1282    pub fn populate_release_notes_var(&mut self) {
1283        // Look up changelogs in config-defined crate order for determinism.
1284        let notes = self
1285            .config
1286            .crates
1287            .iter()
1288            .find_map(|c| self.stage_outputs.changelogs.get(&c.name))
1289            .cloned()
1290            .unwrap_or_default();
1291        self.template_vars.set("ReleaseNotes", &notes);
1292    }
1293
1294    /// Refresh the `Artifacts` structured template variable from the current
1295    /// artifact registry. Should be called before rendering release body and
1296    /// announce templates so they can iterate over all artifacts.
1297    ///
1298    /// Each artifact is serialized as a map with keys: `name`, `path`, `target`,
1299    /// `kind`, `crate_name`, and `metadata`.
1300    ///
1301    /// **Known metadata keys** (populated by individual stages):
1302    /// - `format` — archive format (e.g. `"tar.gz"`, `"zip"`), set by archive stage
1303    /// - `extra_file` — `"true"` when artifact is an extra file, set by checksum stage
1304    /// - `extra_name_template` — name template override for extra files, set by checksum stage
1305    /// - `digest` — docker image digest (e.g. `sha256:abc123...`), set by docker stage
1306    /// - `id` — artifact ID from config, set by docker and build stages
1307    /// - `binary` — binary name, set by build stage
1308    pub fn refresh_artifacts_var(&mut self) {
1309        // CSV metadata keys we expose as JSON arrays for template iteration.
1310        // Storage remains HashMap<String,String> (flat); only the
1311        // template-exposed view is expanded. The
1312        // ExtraBinaries / ExtraFiles list semantics.
1313        const CSV_LIST_KEYS: &[&str] = &["extra_binaries", "extra_files"];
1314        // JSON-encoded list metadata keys: stored as a JSON-array string in
1315        // `HashMap<String,String>`, exposed as a real array on the template
1316        // side so `{% for p in .Artifacts[0].metadata.Platforms %}` works.
1317        // `Platforms` is the platform-list slice on
1318        // `DockerImageV2` artifacts.
1319        const JSON_LIST_KEYS: &[&str] = &["Platforms"];
1320
1321        let artifacts_value: Vec<serde_json::Value> = self
1322            .artifacts
1323            .all()
1324            .iter()
1325            .map(|a| {
1326                // Rebuild metadata map converting known CSV keys into arrays.
1327                let mut metadata_map = serde_json::Map::with_capacity(a.metadata.len());
1328                for (k, v) in &a.metadata {
1329                    if CSV_LIST_KEYS.contains(&k.as_str()) {
1330                        let items: Vec<serde_json::Value> = if v.is_empty() {
1331                            Vec::new()
1332                        } else {
1333                            v.split(',')
1334                                .map(|s| serde_json::Value::String(s.to_string()))
1335                                .collect()
1336                        };
1337                        metadata_map.insert(k.clone(), serde_json::Value::Array(items));
1338                    } else if JSON_LIST_KEYS.contains(&k.as_str()) {
1339                        // Decode JSON-array string into a real Value::Array;
1340                        // a malformed value falls back to the raw string so
1341                        // custom publishers can still inspect it.
1342                        let parsed = serde_json::from_str::<serde_json::Value>(v)
1343                            .unwrap_or_else(|_| serde_json::Value::String(v.clone()));
1344                        metadata_map.insert(k.clone(), parsed);
1345                    } else {
1346                        metadata_map.insert(k.clone(), serde_json::Value::String(v.clone()));
1347                    }
1348                }
1349                serde_json::json!({
1350                    "name": a.name,
1351                    "path": a.path.to_string_lossy(),
1352                    "target": a.target.as_deref().unwrap_or(""),
1353                    "kind": a.kind.as_str(),
1354                    "crate_name": a.crate_name,
1355                    "metadata": serde_json::Value::Object(metadata_map),
1356                })
1357            })
1358            .collect();
1359        // serde_json::Value and tera::Value are the same type under the hood,
1360        // so no conversion is needed — pass values directly.
1361        let tera_value = tera::Value::Array(artifacts_value);
1362        self.template_vars.set_structured("Artifacts", tera_value);
1363    }
1364
1365    /// Populate the `Metadata` structured template variable from config.metadata.
1366    ///
1367    /// Exposes the project metadata block as a nested map with PascalCase keys
1368    /// the `.Metadata.*` namespace:
1369    /// `Description`, `Homepage`, `Documentation`, `License`, `Repository`,
1370    /// `Maintainers`, `ModTimestamp`, `FullDescription` (resolved),
1371    /// `CommitAuthor.{Name,Email}`.
1372    /// Missing fields default to empty strings / empty arrays.
1373    ///
1374    /// `full_description` supports `Inline`, `FromFile` (template-rendered
1375    /// path, read from disk), and `FromUrl` (template-rendered URL +
1376    /// headers, fetched through [`crate::content_source::resolve`] which
1377    /// applies retries, body caps, and CR/LF header-injection guards).
1378    pub fn populate_metadata_var(&mut self) -> anyhow::Result<()> {
1379        // Clone the small scalar fields so we don't hold a borrow on self.config
1380        // across the render_template calls below.
1381        let (
1382            description,
1383            homepage,
1384            documentation,
1385            license,
1386            repository,
1387            maintainers,
1388            mod_timestamp,
1389            full_desc_src,
1390            commit_author,
1391        ) = {
1392            let meta = self.config.metadata.as_ref();
1393            // Description / homepage / documentation / license resolve through
1394            // the project-level fallback: top-level `metadata.*` wins, else the
1395            // primary crate's `Cargo.toml`-derived value. This keeps
1396            // `{{ Metadata.* }}` single-sourced with the per-publisher
1397            // `meta_*_for` resolvers, so dropping a redundant `metadata.license`
1398            // (derivable from Cargo.toml) does not silently empty the var.
1399            let description = self
1400                .config
1401                .meta_description_project()
1402                .unwrap_or("")
1403                .to_string();
1404            let homepage = self
1405                .config
1406                .meta_homepage_project()
1407                .unwrap_or("")
1408                .to_string();
1409            let documentation = self
1410                .config
1411                .meta_documentation_project()
1412                .unwrap_or("")
1413                .to_string();
1414            let license = self.config.meta_license_project().unwrap_or("").to_string();
1415            let repository = self
1416                .config
1417                .meta_repository_project()
1418                .unwrap_or("")
1419                .to_string();
1420            let maintainers: Vec<String> = meta
1421                .and_then(|m| m.maintainers.as_ref())
1422                .cloned()
1423                .unwrap_or_default();
1424            let mod_timestamp = meta
1425                .and_then(|m| m.mod_timestamp.as_deref())
1426                .unwrap_or("")
1427                .to_string();
1428            let full_desc_src = meta.and_then(|m| m.full_description.clone());
1429            let commit_author = meta.and_then(|m| m.commit_author.clone());
1430            (
1431                description,
1432                homepage,
1433                documentation,
1434                license,
1435                repository,
1436                maintainers,
1437                mod_timestamp,
1438                full_desc_src,
1439                commit_author,
1440            )
1441        };
1442
1443        // Resolve full_description through the shared ContentSource resolver
1444        // so Inline, FromFile (template-rendered path), and FromUrl
1445        // (template-rendered URL + headers, retried HTTP fetch with
1446        // body cap and CR/LF guard) all behave the same as the release
1447        // header/footer fields.
1448        let full_description = match full_desc_src {
1449            None => String::new(),
1450            Some(src) => crate::content_source::resolve(&src, "metadata.full_description", self)?,
1451        };
1452
1453        let commit_author_map = serde_json::json!({
1454            "Name": commit_author.as_ref().and_then(|c| c.name.clone()).unwrap_or_default(),
1455            "Email": commit_author.as_ref().and_then(|c| c.email.clone()).unwrap_or_default(),
1456        });
1457
1458        let meta_map = serde_json::json!({
1459            "Description": description,
1460            "Homepage": homepage,
1461            "Documentation": documentation,
1462            "License": license,
1463            "Repository": repository,
1464            "Maintainers": maintainers,
1465            "ModTimestamp": mod_timestamp,
1466            "FullDescription": full_description,
1467            "CommitAuthor": commit_author_map,
1468        });
1469        // serde_json::Value and tera::Value are the same type, so pass directly.
1470        self.template_vars.set_structured("Metadata", meta_map);
1471        Ok(())
1472    }
1473}
1474
1475/// Map Rust's `std::env::consts::OS` to Go-compatible GOOS naming.
1476/// Templates expect Go runtime names (e.g. "darwin" not "macos").
1477pub fn map_os_to_goos(os: &str) -> &str {
1478    match os {
1479        "macos" => "darwin",
1480        other => other, // linux, windows, freebsd, etc. already match
1481    }
1482}
1483
1484/// Map Rust's `std::env::consts::ARCH` to Go-compatible GOARCH naming.
1485/// Templates expect Go runtime names (e.g. "amd64" not "x86_64").
1486pub fn map_arch_to_goarch(arch: &str) -> &str {
1487    match arch {
1488        "x86_64" => "amd64",
1489        "x86" => "386",
1490        "aarch64" => "arm64",
1491        "powerpc64" => "ppc64",
1492        "s390x" => "s390x",
1493        "mips" => "mips",
1494        "mips64" => "mips64",
1495        "riscv64" => "riscv64",
1496        other => other,
1497    }
1498}
1499
1500#[cfg(test)]
1501#[allow(clippy::field_reassign_with_default)]
1502mod tests {
1503    use super::*;
1504    use crate::config::Config;
1505    use crate::git::{GitInfo, SemVer};
1506
1507    fn make_git_info(dirty: bool, prerelease: Option<&str>) -> GitInfo {
1508        let tag = match prerelease {
1509            Some(pre) => format!("v1.2.3-{pre}"),
1510            None => "v1.2.3".to_string(),
1511        };
1512        GitInfo {
1513            tag,
1514            commit: "abc123def456abc123def456abc123def456abc1".to_string(),
1515            short_commit: "abc123d".to_string(),
1516            branch: "main".to_string(),
1517            dirty,
1518            semver: SemVer {
1519                major: 1,
1520                minor: 2,
1521                patch: 3,
1522                prerelease: prerelease.map(|s| s.to_string()),
1523                build_metadata: None,
1524            },
1525            commit_date: "2026-03-25T10:30:00+00:00".to_string(),
1526            commit_timestamp: "1774463400".to_string(),
1527            previous_tag: Some("v1.2.2".to_string()),
1528            remote_url: "https://github.com/test/repo.git".to_string(),
1529            summary: "v1.2.3-0-gabc123d".to_string(),
1530            tag_subject: "Release v1.2.3".to_string(),
1531            tag_contents: "Release v1.2.3\n\nFull release notes here.".to_string(),
1532            tag_body: "Full release notes here.".to_string(),
1533            first_commit: None,
1534        }
1535    }
1536
1537    #[test]
1538    fn test_context_template_vars() {
1539        let mut config = Config::default();
1540        config.project_name = "test-project".to_string();
1541        let ctx = Context::new(config, ContextOptions::default());
1542        assert_eq!(
1543            ctx.template_vars().get("ProjectName"),
1544            Some(&"test-project".to_string())
1545        );
1546    }
1547
1548    #[test]
1549    fn test_context_should_skip() {
1550        let config = Config::default();
1551        let opts = ContextOptions {
1552            skip_stages: vec!["publish".to_string(), "announce".to_string()],
1553            ..Default::default()
1554        };
1555        let ctx = Context::new(config, opts);
1556        assert!(ctx.should_skip("publish"));
1557        assert!(ctx.should_skip("announce"));
1558        assert!(!ctx.should_skip("build"));
1559    }
1560
1561    #[test]
1562    fn publisher_deselected_empty_selectors_runs_everything() {
1563        let ctx = Context::new(Config::default(), ContextOptions::default());
1564        assert!(!ctx.publisher_deselected("npm"));
1565        assert!(!ctx.publisher_deselected("cargo"));
1566        assert!(!ctx.publisher_deselected("anything"));
1567    }
1568
1569    #[test]
1570    fn publisher_deselected_skip_denylists() {
1571        let opts = ContextOptions {
1572            skip_stages: vec!["npm".to_string()],
1573            ..Default::default()
1574        };
1575        let ctx = Context::new(Config::default(), opts);
1576        assert!(ctx.publisher_deselected("npm"));
1577        assert!(!ctx.publisher_deselected("cargo"));
1578    }
1579
1580    #[test]
1581    fn publisher_deselected_allowlist_excludes_unlisted() {
1582        let opts = ContextOptions {
1583            publisher_allowlist: vec!["cargo".to_string()],
1584            ..Default::default()
1585        };
1586        let ctx = Context::new(Config::default(), opts);
1587        assert!(!ctx.publisher_deselected("cargo"));
1588        assert!(ctx.publisher_deselected("npm"));
1589    }
1590
1591    #[test]
1592    fn publisher_deselected_skip_wins_over_allowlist() {
1593        let opts = ContextOptions {
1594            skip_stages: vec!["cargo".to_string()],
1595            publisher_allowlist: vec!["cargo".to_string()],
1596            ..Default::default()
1597        };
1598        let ctx = Context::new(Config::default(), opts);
1599        assert!(ctx.publisher_deselected("cargo"));
1600    }
1601
1602    #[test]
1603    fn test_context_render_template() {
1604        let mut config = Config::default();
1605        config.project_name = "myapp".to_string();
1606        let ctx = Context::new(config, ContextOptions::default());
1607        let result = ctx.render_template("{{ .ProjectName }}-release").unwrap();
1608        assert_eq!(result, "myapp-release");
1609    }
1610
1611    #[test]
1612    fn test_populate_git_vars_sets_all_expected_vars() {
1613        let config = Config::default();
1614        let mut ctx = Context::new(config, ContextOptions::default());
1615        ctx.git_info = Some(make_git_info(false, None));
1616        ctx.populate_git_vars();
1617
1618        let v = ctx.template_vars();
1619        assert_eq!(v.get("Tag"), Some(&"v1.2.3".to_string()));
1620        assert_eq!(v.get("Version"), Some(&"1.2.3".to_string()));
1621        assert_eq!(v.get("RawVersion"), Some(&"1.2.3".to_string()));
1622        assert_eq!(v.get("Major"), Some(&"1".to_string()));
1623        assert_eq!(v.get("Minor"), Some(&"2".to_string()));
1624        assert_eq!(v.get("Patch"), Some(&"3".to_string()));
1625        assert_eq!(v.get("Prerelease"), Some(&"".to_string()));
1626        assert_eq!(
1627            v.get("FullCommit"),
1628            Some(&"abc123def456abc123def456abc123def456abc1".to_string())
1629        );
1630        assert_eq!(v.get("ShortCommit"), Some(&"abc123d".to_string()));
1631        assert_eq!(v.get("Branch"), Some(&"main".to_string()));
1632        assert_eq!(
1633            v.get("CommitDate"),
1634            Some(&"2026-03-25T10:30:00+00:00".to_string())
1635        );
1636        assert_eq!(v.get("CommitTimestamp"), Some(&"1774463400".to_string()));
1637        assert_eq!(v.get("PreviousTag"), Some(&"v1.2.2".to_string()));
1638        // Base mirrors the numeric base semver, set before any
1639        // snapshot/nightly version templating overwrites Version.
1640        assert_eq!(v.get("Base"), Some(&"1.2.3".to_string()));
1641    }
1642
1643    #[test]
1644    fn test_nightly_build_defaults_to_zero_without_git_info() {
1645        // No git_info (synthetic snapshot/scratch build): NightlyBuild must
1646        // render as "0" so version_templates referencing it never fail.
1647        let config = Config::default();
1648        let mut ctx = Context::new(config, ContextOptions::default());
1649        ctx.git_info = None;
1650        ctx.populate_git_vars();
1651        assert_eq!(
1652            ctx.template_vars().get_structured("NightlyBuild"),
1653            Some(&tera::Value::from(0u64))
1654        );
1655    }
1656
1657    #[test]
1658    fn test_commit_is_alias_for_full_commit() {
1659        let config = Config::default();
1660        let mut ctx = Context::new(config, ContextOptions::default());
1661        ctx.git_info = Some(make_git_info(false, None));
1662        ctx.populate_git_vars();
1663
1664        let v = ctx.template_vars();
1665        assert_eq!(v.get("Commit"), v.get("FullCommit"));
1666    }
1667
1668    #[test]
1669    fn test_populate_git_vars_prerelease() {
1670        let config = Config::default();
1671        let mut ctx = Context::new(config, ContextOptions::default());
1672        ctx.git_info = Some(make_git_info(false, Some("rc.1")));
1673        ctx.populate_git_vars();
1674
1675        let v = ctx.template_vars();
1676        assert_eq!(v.get("Version"), Some(&"1.2.3-rc.1".to_string()));
1677        assert_eq!(v.get("RawVersion"), Some(&"1.2.3".to_string()));
1678        assert_eq!(v.get("Prerelease"), Some(&"rc.1".to_string()));
1679    }
1680
1681    #[test]
1682    fn test_build_metadata_template_var() {
1683        let config = Config::default();
1684        let mut ctx = Context::new(config, ContextOptions::default());
1685        let mut info = make_git_info(false, None);
1686        info.tag = "v1.2.3+build.42".to_string();
1687        info.semver.build_metadata = Some("build.42".to_string());
1688        ctx.git_info = Some(info);
1689        ctx.populate_git_vars();
1690
1691        let v = ctx.template_vars();
1692        assert_eq!(v.get("BuildMetadata"), Some(&"build.42".to_string()));
1693        // Version should include build metadata (strip v prefix only)
1694        assert_eq!(v.get("Version"), Some(&"1.2.3+build.42".to_string()));
1695    }
1696
1697    #[test]
1698    fn test_build_metadata_empty_when_none() {
1699        let config = Config::default();
1700        let mut ctx = Context::new(config, ContextOptions::default());
1701        ctx.git_info = Some(make_git_info(false, None));
1702        ctx.populate_git_vars();
1703
1704        assert_eq!(
1705            ctx.template_vars().get("BuildMetadata"),
1706            Some(&"".to_string())
1707        );
1708    }
1709
1710    #[test]
1711    fn test_populate_git_vars_monorepo_prefixed_tag() {
1712        // Workspace tags like "core-v0.3.2" should produce Version="0.3.2",
1713        // not "core-v0.3.2" (which breaks RPM Version fields and templates).
1714        let config = Config::default();
1715        let mut ctx = Context::new(config, ContextOptions::default());
1716        let mut info = make_git_info(false, None);
1717        info.tag = "core-v0.3.2".to_string();
1718        info.semver = SemVer {
1719            major: 0,
1720            minor: 3,
1721            patch: 2,
1722            prerelease: None,
1723            build_metadata: None,
1724        };
1725        ctx.git_info = Some(info);
1726        ctx.populate_git_vars();
1727
1728        let v = ctx.template_vars();
1729        assert_eq!(v.get("Tag"), Some(&"core-v0.3.2".to_string()));
1730        assert_eq!(v.get("Version"), Some(&"0.3.2".to_string()));
1731        assert_eq!(v.get("RawVersion"), Some(&"0.3.2".to_string()));
1732        assert_eq!(v.get("Major"), Some(&"0".to_string()));
1733        assert_eq!(v.get("Minor"), Some(&"3".to_string()));
1734        assert_eq!(v.get("Patch"), Some(&"2".to_string()));
1735    }
1736
1737    #[test]
1738    fn test_populate_git_vars_monorepo_prefixed_tag_with_prerelease() {
1739        let config = Config::default();
1740        let mut ctx = Context::new(config, ContextOptions::default());
1741        let mut info = make_git_info(false, None);
1742        info.tag = "operator-v1.0.0-rc.1".to_string();
1743        info.semver = SemVer {
1744            major: 1,
1745            minor: 0,
1746            patch: 0,
1747            prerelease: Some("rc.1".to_string()),
1748            build_metadata: None,
1749        };
1750        ctx.git_info = Some(info);
1751        ctx.populate_git_vars();
1752
1753        let v = ctx.template_vars();
1754        assert_eq!(v.get("Tag"), Some(&"operator-v1.0.0-rc.1".to_string()));
1755        assert_eq!(v.get("Version"), Some(&"1.0.0-rc.1".to_string()));
1756        assert_eq!(v.get("RawVersion"), Some(&"1.0.0".to_string()));
1757    }
1758
1759    #[test]
1760    fn test_git_tree_state_clean() {
1761        let config = Config::default();
1762        let mut ctx = Context::new(config, ContextOptions::default());
1763        ctx.git_info = Some(make_git_info(false, None));
1764        ctx.populate_git_vars();
1765
1766        let v = ctx.template_vars();
1767        assert_eq!(
1768            v.get_structured("IsGitDirty"),
1769            Some(&tera::Value::Bool(false))
1770        );
1771        assert_eq!(v.get("GitTreeState"), Some(&"clean".to_string()));
1772    }
1773
1774    #[test]
1775    fn test_git_tree_state_dirty() {
1776        let config = Config::default();
1777        let mut ctx = Context::new(config, ContextOptions::default());
1778        ctx.git_info = Some(make_git_info(true, None));
1779        ctx.populate_git_vars();
1780
1781        let v = ctx.template_vars();
1782        assert_eq!(
1783            v.get_structured("IsGitDirty"),
1784            Some(&tera::Value::Bool(true))
1785        );
1786        assert_eq!(v.get("GitTreeState"), Some(&"dirty".to_string()));
1787    }
1788
1789    #[test]
1790    fn test_is_snapshot_reflects_context_options() {
1791        let config = Config::default();
1792        let opts = ContextOptions {
1793            snapshot: true,
1794            ..Default::default()
1795        };
1796        let mut ctx = Context::new(config, opts);
1797        ctx.git_info = Some(make_git_info(false, None));
1798        ctx.populate_git_vars();
1799
1800        assert_eq!(
1801            ctx.template_vars().get_structured("IsSnapshot"),
1802            Some(&tera::Value::Bool(true))
1803        );
1804
1805        // Non-snapshot
1806        let config2 = Config::default();
1807        let opts2 = ContextOptions {
1808            snapshot: false,
1809            ..Default::default()
1810        };
1811        let mut ctx2 = Context::new(config2, opts2);
1812        ctx2.git_info = Some(make_git_info(false, None));
1813        ctx2.populate_git_vars();
1814
1815        assert_eq!(
1816            ctx2.template_vars().get_structured("IsSnapshot"),
1817            Some(&tera::Value::Bool(false))
1818        );
1819    }
1820
1821    #[test]
1822    fn test_is_draft_defaults_to_false() {
1823        let config = Config::default();
1824        let mut ctx = Context::new(config, ContextOptions::default());
1825        ctx.git_info = Some(make_git_info(false, None));
1826        ctx.populate_git_vars();
1827
1828        assert_eq!(
1829            ctx.template_vars().get_structured("IsDraft"),
1830            Some(&tera::Value::Bool(false))
1831        );
1832    }
1833
1834    #[test]
1835    fn test_previous_tag_empty_when_none() {
1836        let config = Config::default();
1837        let mut ctx = Context::new(config, ContextOptions::default());
1838        let mut info = make_git_info(false, None);
1839        info.previous_tag = None;
1840        ctx.git_info = Some(info);
1841        ctx.populate_git_vars();
1842
1843        assert_eq!(
1844            ctx.template_vars().get("PreviousTag"),
1845            Some(&"".to_string())
1846        );
1847    }
1848
1849    /// Regression: `populate_time_vars` MUST derive `Date` / `Timestamp` /
1850    /// `Now` (and the calendar fields) from `SOURCE_DATE_EPOCH` when the
1851    /// env var is set — the standard reproducible-build contract the
1852    /// determinism harness depends on. Two from-clean runs of the same
1853    /// commit otherwise emit `dist/metadata.json` files that differ in
1854    /// the embedded `date` field, drifting `metadata.json` AND its
1855    /// `.sha256` sidecar across runs. CI run 25975073213 surfaced this
1856    /// drift on every platform shard before the fix landed.
1857    #[test]
1858    fn populate_time_vars_uses_source_date_epoch_when_set() {
1859        // 1_715_000_000 = 2024-05-06T12:53:20+00:00 — picked to be safely
1860        // earlier than wall-clock so a wall-clock-derived assertion would
1861        // visibly fail.
1862        let env = crate::MapEnvSource::new().with("SOURCE_DATE_EPOCH", "1715000000");
1863        let config = Config::default();
1864        let mut ctx = Context::new(config, ContextOptions::default());
1865        ctx.set_env_source(env);
1866        ctx.populate_time_vars();
1867
1868        let v = ctx.template_vars();
1869        assert_eq!(
1870            v.get("Timestamp"),
1871            Some(&"1715000000".to_string()),
1872            "Timestamp must equal SOURCE_DATE_EPOCH seconds"
1873        );
1874        assert_eq!(
1875            v.get("Date"),
1876            Some(&"2024-05-06T12:53:20+00:00".to_string()),
1877            "Date must be RFC 3339 derived from SDE"
1878        );
1879        assert_eq!(v.get("Year"), Some(&"2024".to_string()));
1880        assert_eq!(v.get("Month"), Some(&"05".to_string()));
1881        assert_eq!(v.get("Day"), Some(&"06".to_string()));
1882    }
1883
1884    #[test]
1885    fn test_populate_time_vars() {
1886        // Wall-clock fallback path: empty MapEnvSource has no
1887        // SOURCE_DATE_EPOCH, so we exercise the chrono::Utc::now() branch.
1888        let env = crate::MapEnvSource::new();
1889        let config = Config::default();
1890        let mut ctx = Context::new(config, ContextOptions::default());
1891        ctx.set_env_source(env);
1892        ctx.populate_time_vars();
1893
1894        let v = ctx.template_vars();
1895
1896        // Date should be RFC 3339 format (e.g. 2026-03-30T12:00:00+00:00)
1897        let date = v
1898            .get("Date")
1899            .unwrap_or_else(|| panic!("Date should be set"));
1900        assert!(
1901            date.contains('T') && date.len() > 10,
1902            "Date should be RFC 3339, got: {date}"
1903        );
1904
1905        // Timestamp should be numeric
1906        let ts = v
1907            .get("Timestamp")
1908            .unwrap_or_else(|| panic!("Timestamp should be set"));
1909        assert!(
1910            ts.parse::<i64>().is_ok(),
1911            "Timestamp should be a numeric string, got: {ts}"
1912        );
1913
1914        // Now should be ISO 8601
1915        let now = v.get("Now").unwrap_or_else(|| panic!("Now should be set"));
1916        assert!(now.contains('T'), "Now should be ISO 8601, got: {now}");
1917    }
1918
1919    #[test]
1920    fn test_env_vars_accessible_in_templates() {
1921        let mut config = Config::default();
1922        config.project_name = "myapp".to_string();
1923        let mut ctx = Context::new(config, ContextOptions::default());
1924        ctx.template_vars_mut().set_env("MY_VAR", "hello-world");
1925        ctx.template_vars_mut().set_env("DEPLOY_ENV", "staging");
1926
1927        let result = ctx
1928            .render_template("{{ .Env.MY_VAR }}-{{ .Env.DEPLOY_ENV }}")
1929            .unwrap();
1930        assert_eq!(result, "hello-world-staging");
1931    }
1932
1933    #[test]
1934    fn test_populate_git_vars_without_git_info_still_sets_snapshot() {
1935        let config = Config::default();
1936        let opts = ContextOptions {
1937            snapshot: true,
1938            ..Default::default()
1939        };
1940        let mut ctx = Context::new(config, opts);
1941        // Don't set git_info — populate_git_vars should still set IsSnapshot/IsDraft
1942        ctx.populate_git_vars();
1943
1944        assert_eq!(
1945            ctx.template_vars().get_structured("IsSnapshot"),
1946            Some(&tera::Value::Bool(true))
1947        );
1948        assert_eq!(
1949            ctx.template_vars().get_structured("IsDraft"),
1950            Some(&tera::Value::Bool(false))
1951        );
1952        // Git-specific vars should NOT be set
1953        assert_eq!(ctx.template_vars().get("Tag"), None);
1954    }
1955
1956    #[test]
1957    fn test_is_nightly_set_when_nightly_mode_active() {
1958        let config = Config::default();
1959        let opts = ContextOptions {
1960            nightly: true,
1961            ..Default::default()
1962        };
1963        let mut ctx = Context::new(config, opts);
1964        ctx.git_info = Some(make_git_info(false, None));
1965        ctx.populate_git_vars();
1966
1967        assert_eq!(
1968            ctx.template_vars().get_structured("IsNightly"),
1969            Some(&tera::Value::Bool(true)),
1970            "IsNightly should be 'true' when nightly mode is active"
1971        );
1972        assert!(ctx.is_nightly(), "is_nightly() should return true");
1973    }
1974
1975    #[test]
1976    fn test_is_nightly_false_by_default() {
1977        let config = Config::default();
1978        let mut ctx = Context::new(config, ContextOptions::default());
1979        ctx.git_info = Some(make_git_info(false, None));
1980        ctx.populate_git_vars();
1981
1982        assert_eq!(
1983            ctx.template_vars().get_structured("IsNightly"),
1984            Some(&tera::Value::Bool(false)),
1985            "IsNightly should default to 'false'"
1986        );
1987        assert!(
1988            !ctx.is_nightly(),
1989            "is_nightly() should return false by default"
1990        );
1991    }
1992
1993    #[test]
1994    fn test_version_returns_populated_value() {
1995        let config = Config::default();
1996        let mut ctx = Context::new(config, ContextOptions::default());
1997        ctx.git_info = Some(make_git_info(false, None));
1998        ctx.populate_git_vars();
1999
2000        assert_eq!(ctx.version(), "1.2.3");
2001    }
2002
2003    #[test]
2004    fn test_version_returns_empty_when_not_set() {
2005        let config = Config::default();
2006        let ctx = Context::new(config, ContextOptions::default());
2007        assert_eq!(ctx.version(), "");
2008    }
2009
2010    #[test]
2011    fn test_is_nightly_without_git_info() {
2012        let config = Config::default();
2013        let opts = ContextOptions {
2014            nightly: true,
2015            ..Default::default()
2016        };
2017        let mut ctx = Context::new(config, opts);
2018        // No git_info set — populate_git_vars still sets IsNightly
2019        ctx.populate_git_vars();
2020
2021        assert_eq!(
2022            ctx.template_vars().get_structured("IsNightly"),
2023            Some(&tera::Value::Bool(true)),
2024            "IsNightly should be set even without git info"
2025        );
2026    }
2027
2028    #[test]
2029    fn test_is_git_clean_when_not_dirty() {
2030        let config = Config::default();
2031        let mut ctx = Context::new(config, ContextOptions::default());
2032        ctx.git_info = Some(make_git_info(false, None));
2033        ctx.populate_git_vars();
2034
2035        assert_eq!(
2036            ctx.template_vars().get_structured("IsGitClean"),
2037            Some(&tera::Value::Bool(true))
2038        );
2039    }
2040
2041    #[test]
2042    fn test_is_git_clean_when_dirty() {
2043        let config = Config::default();
2044        let mut ctx = Context::new(config, ContextOptions::default());
2045        ctx.git_info = Some(make_git_info(true, None));
2046        ctx.populate_git_vars();
2047
2048        assert_eq!(
2049            ctx.template_vars().get_structured("IsGitClean"),
2050            Some(&tera::Value::Bool(false))
2051        );
2052    }
2053
2054    #[test]
2055    fn test_git_url_set_from_git_info() {
2056        let config = Config::default();
2057        let mut ctx = Context::new(config, ContextOptions::default());
2058        ctx.git_info = Some(make_git_info(false, None));
2059        ctx.populate_git_vars();
2060
2061        assert_eq!(
2062            ctx.template_vars().get("GitURL"),
2063            Some(&"https://github.com/test/repo.git".to_string())
2064        );
2065    }
2066
2067    #[test]
2068    fn test_summary_set_from_git_info() {
2069        let config = Config::default();
2070        let mut ctx = Context::new(config, ContextOptions::default());
2071        ctx.git_info = Some(make_git_info(false, None));
2072        ctx.populate_git_vars();
2073
2074        assert_eq!(
2075            ctx.template_vars().get("Summary"),
2076            Some(&"v1.2.3-0-gabc123d".to_string())
2077        );
2078    }
2079
2080    #[test]
2081    fn test_tag_subject_set_from_git_info() {
2082        let config = Config::default();
2083        let mut ctx = Context::new(config, ContextOptions::default());
2084        ctx.git_info = Some(make_git_info(false, None));
2085        ctx.populate_git_vars();
2086
2087        assert_eq!(
2088            ctx.template_vars().get("TagSubject"),
2089            Some(&"Release v1.2.3".to_string())
2090        );
2091    }
2092
2093    #[test]
2094    fn test_tag_contents_set_from_git_info() {
2095        let config = Config::default();
2096        let mut ctx = Context::new(config, ContextOptions::default());
2097        ctx.git_info = Some(make_git_info(false, None));
2098        ctx.populate_git_vars();
2099
2100        assert_eq!(
2101            ctx.template_vars().get("TagContents"),
2102            Some(&"Release v1.2.3\n\nFull release notes here.".to_string())
2103        );
2104    }
2105
2106    #[test]
2107    fn test_tag_body_set_from_git_info() {
2108        let config = Config::default();
2109        let mut ctx = Context::new(config, ContextOptions::default());
2110        ctx.git_info = Some(make_git_info(false, None));
2111        ctx.populate_git_vars();
2112
2113        assert_eq!(
2114            ctx.template_vars().get("TagBody"),
2115            Some(&"Full release notes here.".to_string())
2116        );
2117    }
2118
2119    #[test]
2120    fn test_is_single_target_false_by_default() {
2121        let config = Config::default();
2122        let mut ctx = Context::new(config, ContextOptions::default());
2123        ctx.git_info = Some(make_git_info(false, None));
2124        ctx.populate_git_vars();
2125
2126        assert_eq!(
2127            ctx.template_vars().get_structured("IsSingleTarget"),
2128            Some(&tera::Value::Bool(false))
2129        );
2130    }
2131
2132    #[test]
2133    fn test_is_single_target_true_when_set() {
2134        let config = Config::default();
2135        let opts = ContextOptions {
2136            single_target: Some("x86_64-unknown-linux-gnu".to_string()),
2137            ..Default::default()
2138        };
2139        let mut ctx = Context::new(config, opts);
2140        ctx.git_info = Some(make_git_info(false, None));
2141        ctx.populate_git_vars();
2142
2143        assert_eq!(
2144            ctx.template_vars().get_structured("IsSingleTarget"),
2145            Some(&tera::Value::Bool(true))
2146        );
2147    }
2148
2149    #[test]
2150    #[serial_test::serial]
2151    fn test_populate_runtime_vars() {
2152        let config = Config::default();
2153        let mut ctx = Context::new(config, ContextOptions::default());
2154        ctx.populate_runtime_vars();
2155
2156        let v = ctx.template_vars();
2157
2158        let goos = v
2159            .get("RuntimeGoos")
2160            .unwrap_or_else(|| panic!("RuntimeGoos should be set"));
2161        assert!(
2162            !goos.is_empty(),
2163            "RuntimeGoos should not be empty, got: {goos}"
2164        );
2165        // RuntimeGoos uses Go naming (e.g. "darwin" not "macos")
2166        assert_eq!(goos, map_os_to_goos(std::env::consts::OS));
2167
2168        let goarch = v
2169            .get("RuntimeGoarch")
2170            .unwrap_or_else(|| panic!("RuntimeGoarch should be set"));
2171        assert!(
2172            !goarch.is_empty(),
2173            "RuntimeGoarch should not be empty, got: {goarch}"
2174        );
2175        // RuntimeGoarch uses Go naming (e.g. "amd64" not "x86_64")
2176        assert_eq!(goarch, map_arch_to_goarch(std::env::consts::ARCH));
2177    }
2178
2179    #[test]
2180    fn test_populate_release_notes_var_with_changelogs() {
2181        let mut config = Config::default();
2182        config.crates.push(crate::config::CrateConfig {
2183            name: "my-crate".to_string(),
2184            ..Default::default()
2185        });
2186        let mut ctx = Context::new(config, ContextOptions::default());
2187        ctx.stage_outputs
2188            .changelogs
2189            .insert("my-crate".to_string(), "## Changes\n- fix bug".to_string());
2190        ctx.populate_release_notes_var();
2191
2192        assert_eq!(
2193            ctx.template_vars().get("ReleaseNotes"),
2194            Some(&"## Changes\n- fix bug".to_string())
2195        );
2196    }
2197
2198    #[test]
2199    fn test_populate_release_notes_var_empty_when_no_changelogs() {
2200        let config = Config::default();
2201        let mut ctx = Context::new(config, ContextOptions::default());
2202        ctx.populate_release_notes_var();
2203
2204        assert_eq!(
2205            ctx.template_vars().get("ReleaseNotes"),
2206            Some(&"".to_string())
2207        );
2208    }
2209
2210    #[test]
2211    fn test_populate_release_notes_var_deterministic_with_multiple_crates() {
2212        let mut config = Config::default();
2213        config.crates.push(crate::config::CrateConfig {
2214            name: "crate-a".to_string(),
2215            ..Default::default()
2216        });
2217        config.crates.push(crate::config::CrateConfig {
2218            name: "crate-b".to_string(),
2219            ..Default::default()
2220        });
2221        let mut ctx = Context::new(config, ContextOptions::default());
2222        ctx.stage_outputs
2223            .changelogs
2224            .insert("crate-a".to_string(), "notes-a".to_string());
2225        ctx.stage_outputs
2226            .changelogs
2227            .insert("crate-b".to_string(), "notes-b".to_string());
2228        ctx.populate_release_notes_var();
2229
2230        // Should always pick the first crate in config order, not arbitrary HashMap order
2231        assert_eq!(
2232            ctx.template_vars().get("ReleaseNotes"),
2233            Some(&"notes-a".to_string())
2234        );
2235    }
2236
2237    #[test]
2238    fn test_outputs_accessible_in_templates() {
2239        let mut config = Config::default();
2240        config.project_name = "myapp".to_string();
2241        let mut ctx = Context::new(config, ContextOptions::default());
2242        ctx.template_vars_mut().set_output("build_id", "abc123");
2243        ctx.template_vars_mut()
2244            .set_output("deploy_url", "https://example.com");
2245
2246        let result = ctx
2247            .render_template("{{ .Outputs.build_id }}-{{ .Outputs.deploy_url }}")
2248            .unwrap();
2249        assert_eq!(result, "abc123-https://example.com");
2250    }
2251
2252    #[test]
2253    fn test_artifact_ext_and_target_template_vars() {
2254        let mut config = Config::default();
2255        config.project_name = "myapp".to_string();
2256        let mut ctx = Context::new(config, ContextOptions::default());
2257        ctx.template_vars_mut().set("ArtifactName", "myapp.tar.gz");
2258        ctx.template_vars_mut().set("ArtifactExt", ".tar.gz");
2259        ctx.template_vars_mut()
2260            .set("Target", "x86_64-unknown-linux-gnu");
2261
2262        let result = ctx
2263            .render_template("{{ .ArtifactExt }}_{{ .Target }}")
2264            .unwrap();
2265        assert_eq!(result, ".tar.gz_x86_64-unknown-linux-gnu");
2266    }
2267
2268    #[test]
2269    fn test_checksums_template_var() {
2270        let mut config = Config::default();
2271        config.project_name = "myapp".to_string();
2272        let mut ctx = Context::new(config, ContextOptions::default());
2273        let checksum_text = "abc123  myapp.tar.gz\ndef456  myapp.zip\n";
2274        ctx.template_vars_mut().set("Checksums", checksum_text);
2275
2276        let result = ctx.render_template("{{ .Checksums }}").unwrap();
2277        assert_eq!(result, checksum_text);
2278    }
2279
2280    // --- Pro template variable tests ---
2281
2282    #[test]
2283    fn test_prefixed_tag_with_tag_prefix() {
2284        let mut config = Config::default();
2285        config.tag = Some(crate::config::TagConfig {
2286            tag_prefix: Some("api/".to_string()),
2287            ..Default::default()
2288        });
2289        let mut ctx = Context::new(config, ContextOptions::default());
2290        ctx.git_info = Some(make_git_info(false, None));
2291        ctx.populate_git_vars();
2292
2293        assert_eq!(
2294            ctx.template_vars().get("PrefixedTag"),
2295            Some(&"api/v1.2.3".to_string())
2296        );
2297    }
2298
2299    #[test]
2300    fn test_prefixed_tag_without_tag_prefix() {
2301        let config = Config::default();
2302        let mut ctx = Context::new(config, ContextOptions::default());
2303        ctx.git_info = Some(make_git_info(false, None));
2304        ctx.populate_git_vars();
2305
2306        // No tag_prefix configured — PrefixedTag should equal Tag
2307        assert_eq!(
2308            ctx.template_vars().get("PrefixedTag"),
2309            Some(&"v1.2.3".to_string())
2310        );
2311    }
2312
2313    #[test]
2314    fn test_prefixed_previous_tag_with_tag_prefix() {
2315        let mut config = Config::default();
2316        config.tag = Some(crate::config::TagConfig {
2317            tag_prefix: Some("api/".to_string()),
2318            ..Default::default()
2319        });
2320        let mut ctx = Context::new(config, ContextOptions::default());
2321        ctx.git_info = Some(make_git_info(false, None));
2322        ctx.populate_git_vars();
2323
2324        assert_eq!(
2325            ctx.template_vars().get("PrefixedPreviousTag"),
2326            Some(&"api/v1.2.2".to_string())
2327        );
2328    }
2329
2330    #[test]
2331    fn test_prefixed_previous_tag_empty_when_no_previous() {
2332        let mut config = Config::default();
2333        config.tag = Some(crate::config::TagConfig {
2334            tag_prefix: Some("api/".to_string()),
2335            ..Default::default()
2336        });
2337        let mut ctx = Context::new(config, ContextOptions::default());
2338        let mut info = make_git_info(false, None);
2339        info.previous_tag = None;
2340        ctx.git_info = Some(info);
2341        ctx.populate_git_vars();
2342
2343        // When there is no previous tag, PrefixedPreviousTag should be empty
2344        // (not just the prefix).
2345        assert_eq!(
2346            ctx.template_vars().get("PrefixedPreviousTag"),
2347            Some(&"".to_string())
2348        );
2349    }
2350
2351    #[test]
2352    fn test_prefixed_summary_with_tag_prefix() {
2353        let mut config = Config::default();
2354        config.tag = Some(crate::config::TagConfig {
2355            tag_prefix: Some("api/".to_string()),
2356            ..Default::default()
2357        });
2358        let mut ctx = Context::new(config, ContextOptions::default());
2359        ctx.git_info = Some(make_git_info(false, None));
2360        ctx.populate_git_vars();
2361
2362        assert_eq!(
2363            ctx.template_vars().get("PrefixedSummary"),
2364            Some(&"api/v1.2.3-0-gabc123d".to_string())
2365        );
2366    }
2367
2368    #[test]
2369    fn test_is_release_true_for_normal_release() {
2370        let config = Config::default();
2371        let opts = ContextOptions {
2372            snapshot: false,
2373            nightly: false,
2374            ..Default::default()
2375        };
2376        let mut ctx = Context::new(config, opts);
2377        ctx.git_info = Some(make_git_info(false, None));
2378        ctx.populate_git_vars();
2379
2380        assert_eq!(
2381            ctx.template_vars().get_structured("IsRelease"),
2382            Some(&tera::Value::Bool(true))
2383        );
2384    }
2385
2386    #[test]
2387    fn test_is_release_false_for_snapshot() {
2388        let config = Config::default();
2389        let opts = ContextOptions {
2390            snapshot: true,
2391            ..Default::default()
2392        };
2393        let mut ctx = Context::new(config, opts);
2394        ctx.git_info = Some(make_git_info(false, None));
2395        ctx.populate_git_vars();
2396
2397        assert_eq!(
2398            ctx.template_vars().get_structured("IsRelease"),
2399            Some(&tera::Value::Bool(false))
2400        );
2401    }
2402
2403    #[test]
2404    fn test_is_release_false_for_nightly() {
2405        let config = Config::default();
2406        let opts = ContextOptions {
2407            nightly: true,
2408            ..Default::default()
2409        };
2410        let mut ctx = Context::new(config, opts);
2411        ctx.git_info = Some(make_git_info(false, None));
2412        ctx.populate_git_vars();
2413
2414        assert_eq!(
2415            ctx.template_vars().get_structured("IsRelease"),
2416            Some(&tera::Value::Bool(false))
2417        );
2418    }
2419
2420    #[test]
2421    fn test_is_merging_true_when_merge_flag_set() {
2422        let config = Config::default();
2423        let opts = ContextOptions {
2424            merge: true,
2425            ..Default::default()
2426        };
2427        let mut ctx = Context::new(config, opts);
2428        ctx.git_info = Some(make_git_info(false, None));
2429        ctx.populate_git_vars();
2430
2431        assert_eq!(
2432            ctx.template_vars().get_structured("IsMerging"),
2433            Some(&tera::Value::Bool(true))
2434        );
2435    }
2436
2437    #[test]
2438    fn test_is_merging_false_by_default() {
2439        let config = Config::default();
2440        let mut ctx = Context::new(config, ContextOptions::default());
2441        ctx.git_info = Some(make_git_info(false, None));
2442        ctx.populate_git_vars();
2443
2444        assert_eq!(
2445            ctx.template_vars().get_structured("IsMerging"),
2446            Some(&tera::Value::Bool(false))
2447        );
2448    }
2449
2450    #[test]
2451    fn test_refresh_artifacts_var_empty() {
2452        let config = Config::default();
2453        let mut ctx = Context::new(config, ContextOptions::default());
2454        ctx.refresh_artifacts_var();
2455
2456        // Should render as an empty array
2457        let result = ctx
2458            .render_template("{% for a in Artifacts %}{{ a.name }}{% endfor %}")
2459            .unwrap();
2460        assert_eq!(result, "");
2461    }
2462
2463    #[test]
2464    fn test_refresh_artifacts_var_with_artifacts() {
2465        use crate::artifact::{Artifact, ArtifactKind};
2466        use std::collections::HashMap;
2467        use std::path::PathBuf;
2468
2469        let config = Config::default();
2470        let mut ctx = Context::new(config, ContextOptions::default());
2471        // Artifacts are created with empty `name` — ArtifactRegistry::add()
2472        // auto-derives the name from the path's filename component when name
2473        // is empty (see artifact.rs add() implementation).
2474        ctx.artifacts.add(Artifact {
2475            kind: ArtifactKind::Archive,
2476            name: String::new(),
2477            path: PathBuf::from("dist/myapp-1.0.0-linux-amd64.tar.gz"),
2478            target: Some("x86_64-unknown-linux-gnu".to_string()),
2479            crate_name: "myapp".to_string(),
2480            metadata: HashMap::from([("format".to_string(), "tar.gz".to_string())]),
2481            size: None,
2482        });
2483        ctx.artifacts.add(Artifact {
2484            kind: ArtifactKind::Binary,
2485            name: String::new(),
2486            path: PathBuf::from("dist/myapp"),
2487            target: Some("x86_64-unknown-linux-gnu".to_string()),
2488            crate_name: "myapp".to_string(),
2489            metadata: HashMap::new(),
2490            size: None,
2491        });
2492        ctx.refresh_artifacts_var();
2493
2494        // Iterate over artifacts and collect names
2495        let result = ctx
2496            .render_template("{% for a in Artifacts %}{{ a.name }},{% endfor %}")
2497            .unwrap();
2498        assert!(result.contains("myapp-1.0.0-linux-amd64.tar.gz"));
2499        assert!(result.contains("myapp"));
2500
2501        // Check kind field
2502        let result_kinds = ctx
2503            .render_template("{% for a in Artifacts %}{{ a.kind }},{% endfor %}")
2504            .unwrap();
2505        assert!(result_kinds.contains("archive"));
2506        assert!(result_kinds.contains("binary"));
2507    }
2508
2509    #[test]
2510    fn test_populate_metadata_var_with_mod_timestamp() {
2511        let mut config = Config::default();
2512        config.metadata = Some(crate::config::MetadataConfig {
2513            mod_timestamp: Some("{{ .CommitTimestamp }}".to_string()),
2514            ..Default::default()
2515        });
2516        let mut ctx = Context::new(config, ContextOptions::default());
2517        ctx.populate_metadata_var().unwrap();
2518
2519        // Metadata should be accessible as a nested map with PascalCase keys
2520        let result = ctx.render_template("{{ Metadata.ModTimestamp }}").unwrap();
2521        assert_eq!(result, "{{ .CommitTimestamp }}");
2522    }
2523
2524    #[test]
2525    fn test_populate_metadata_var_empty_when_no_config() {
2526        let config = Config::default();
2527        let mut ctx = Context::new(config, ContextOptions::default());
2528        ctx.populate_metadata_var().unwrap();
2529
2530        // Should render empty strings for missing fields (PascalCase keys)
2531        let result = ctx.render_template("{{ Metadata.Description }}").unwrap();
2532        assert_eq!(result, "");
2533    }
2534
2535    #[test]
2536    fn test_populate_metadata_var_reads_from_config() {
2537        let mut config = Config::default();
2538        config.metadata = Some(crate::config::MetadataConfig {
2539            description: Some("A test project".to_string()),
2540            homepage: Some("https://example.com".to_string()),
2541            documentation: Some("https://docs.example.com".to_string()),
2542            license: Some("MIT".to_string()),
2543            repository: Some("https://github.com/example/test".to_string()),
2544            maintainers: Some(vec!["Alice".to_string(), "Bob".to_string()]),
2545            mod_timestamp: Some("1234567890".to_string()),
2546            ..Default::default()
2547        });
2548        let mut ctx = Context::new(config, ContextOptions::default());
2549        ctx.populate_metadata_var().unwrap();
2550
2551        let desc = ctx.render_template("{{ Metadata.Description }}").unwrap();
2552        assert_eq!(desc, "A test project");
2553
2554        let home = ctx.render_template("{{ Metadata.Homepage }}").unwrap();
2555        assert_eq!(home, "https://example.com");
2556
2557        let repo = ctx.render_template("{{ Metadata.Repository }}").unwrap();
2558        assert_eq!(repo, "https://github.com/example/test");
2559
2560        let docs = ctx.render_template("{{ Metadata.Documentation }}").unwrap();
2561        assert_eq!(docs, "https://docs.example.com");
2562
2563        let lic = ctx.render_template("{{ Metadata.License }}").unwrap();
2564        assert_eq!(lic, "MIT");
2565
2566        let ts = ctx.render_template("{{ Metadata.ModTimestamp }}").unwrap();
2567        assert_eq!(ts, "1234567890");
2568    }
2569
2570    #[test]
2571    fn test_populate_metadata_var_license_falls_back_to_derived() {
2572        // No top-level `metadata.license`: the var must derive from the
2573        // primary crate's Cargo.toml-derived license (here, a dual SPDX
2574        // expression), not render empty.
2575        let mut config = Config::default();
2576        config.crates = vec![crate::config::CrateConfig {
2577            name: "anodizer".to_string(),
2578            ..Default::default()
2579        }];
2580        config.derived_metadata.insert(
2581            "anodizer".to_string(),
2582            crate::config::MetadataConfig {
2583                description: Some("Derived desc".to_string()),
2584                homepage: Some("https://derived.example".to_string()),
2585                documentation: Some("https://derived.docs".to_string()),
2586                license: Some("MIT OR Apache-2.0".to_string()),
2587                ..Default::default()
2588            },
2589        );
2590        let mut ctx = Context::new(config, ContextOptions::default());
2591        ctx.populate_metadata_var().unwrap();
2592
2593        assert_eq!(
2594            ctx.render_template("{{ Metadata.License }}").unwrap(),
2595            "MIT OR Apache-2.0"
2596        );
2597        assert_eq!(
2598            ctx.render_template("{{ Metadata.Description }}").unwrap(),
2599            "Derived desc"
2600        );
2601        assert_eq!(
2602            ctx.render_template("{{ Metadata.Homepage }}").unwrap(),
2603            "https://derived.example"
2604        );
2605        assert_eq!(
2606            ctx.render_template("{{ Metadata.Documentation }}").unwrap(),
2607            "https://derived.docs"
2608        );
2609    }
2610
2611    #[test]
2612    fn test_populate_metadata_var_top_level_license_wins_over_derived() {
2613        // Explicit top-level `metadata.license` still wins over the derived
2614        // Cargo.toml value.
2615        let mut config = Config::default();
2616        config.crates = vec![crate::config::CrateConfig {
2617            name: "anodizer".to_string(),
2618            ..Default::default()
2619        }];
2620        config.derived_metadata.insert(
2621            "anodizer".to_string(),
2622            crate::config::MetadataConfig {
2623                license: Some("MIT OR Apache-2.0".to_string()),
2624                ..Default::default()
2625            },
2626        );
2627        config.metadata = Some(crate::config::MetadataConfig {
2628            license: Some("GPL-3.0".to_string()),
2629            ..Default::default()
2630        });
2631        let mut ctx = Context::new(config, ContextOptions::default());
2632        ctx.populate_metadata_var().unwrap();
2633
2634        assert_eq!(
2635            ctx.render_template("{{ Metadata.License }}").unwrap(),
2636            "GPL-3.0"
2637        );
2638    }
2639
2640    #[test]
2641    fn test_populate_metadata_var_documentation_renders() {
2642        let mut config = Config::default();
2643        config.metadata = Some(crate::config::MetadataConfig {
2644            documentation: Some("https://docs.rs/anodizer".to_string()),
2645            ..Default::default()
2646        });
2647        let mut ctx = Context::new(config, ContextOptions::default());
2648        ctx.populate_metadata_var().unwrap();
2649
2650        let docs = ctx.render_template("{{ Metadata.Documentation }}").unwrap();
2651        assert_eq!(docs, "https://docs.rs/anodizer");
2652    }
2653
2654    #[test]
2655    fn test_populate_metadata_var_documentation_empty_when_unset() {
2656        let mut ctx = Context::new(Config::default(), ContextOptions::default());
2657        ctx.populate_metadata_var().unwrap();
2658
2659        let docs = ctx.render_template("{{ Metadata.Documentation }}").unwrap();
2660        assert_eq!(docs, "");
2661    }
2662
2663    #[test]
2664    fn test_populate_metadata_var_full_description_inline() {
2665        use crate::config::ContentSource;
2666        let mut config = Config::default();
2667        config.metadata = Some(crate::config::MetadataConfig {
2668            full_description: Some(ContentSource::Inline(
2669                "A long-form description of the project.".to_string(),
2670            )),
2671            ..Default::default()
2672        });
2673        let mut ctx = Context::new(config, ContextOptions::default());
2674        ctx.populate_metadata_var().unwrap();
2675        let rendered = ctx
2676            .render_template("{{ Metadata.FullDescription }}")
2677            .unwrap();
2678        assert_eq!(rendered, "A long-form description of the project.");
2679    }
2680
2681    #[test]
2682    fn test_populate_metadata_var_full_description_from_file() {
2683        use crate::config::ContentSource;
2684        let tmp = tempfile::tempdir().unwrap();
2685        let desc_path = tmp.path().join("DESCRIPTION.md");
2686        std::fs::write(&desc_path, "read from disk").unwrap();
2687        let mut config = Config::default();
2688        config.metadata = Some(crate::config::MetadataConfig {
2689            full_description: Some(ContentSource::FromFile {
2690                from_file: desc_path.to_string_lossy().into_owned(),
2691            }),
2692            ..Default::default()
2693        });
2694        let mut ctx = Context::new(config, ContextOptions::default());
2695        ctx.populate_metadata_var().unwrap();
2696        let rendered = ctx
2697            .render_template("{{ Metadata.FullDescription }}")
2698            .unwrap();
2699        assert_eq!(rendered, "read from disk");
2700    }
2701
2702    #[test]
2703    fn test_populate_metadata_var_full_description_from_url_resolves() {
2704        // `from_url` routes through the shared `content_source::resolve`
2705        // helper. We stand up a oneshot HTTP responder so the test is
2706        // hermetic (no real network) and verify the body lands in the
2707        // rendered Metadata.FullDescription variable.
2708        use crate::config::ContentSource;
2709        use crate::test_helpers::responder::spawn_oneshot_http_responder;
2710
2711        let body = "long form description body";
2712        let body_len = body.len();
2713        let response: &'static str = Box::leak(
2714            format!("HTTP/1.1 200 OK\r\nContent-Length: {body_len}\r\n\r\n{body}").into_boxed_str(),
2715        );
2716        let (addr, _calls) = spawn_oneshot_http_responder(vec![response]);
2717
2718        let mut config = Config::default();
2719        config.metadata = Some(crate::config::MetadataConfig {
2720            full_description: Some(ContentSource::FromUrl {
2721                from_url: format!("http://{addr}/description.md"),
2722                headers: None,
2723            }),
2724            ..Default::default()
2725        });
2726        let mut ctx = Context::new(config, ContextOptions::default());
2727        ctx.populate_metadata_var()
2728            .expect("from_url should resolve through content_source");
2729        let rendered = ctx
2730            .render_template("{{ Metadata.FullDescription }}")
2731            .unwrap();
2732        assert_eq!(rendered, body);
2733    }
2734
2735    #[test]
2736    fn test_populate_metadata_var_commit_author() {
2737        use crate::config::CommitAuthorConfig;
2738        let mut config = Config::default();
2739        config.metadata = Some(crate::config::MetadataConfig {
2740            commit_author: Some(CommitAuthorConfig {
2741                name: Some("Alice Developer".to_string()),
2742                email: Some("alice@example.com".to_string()),
2743                signing: None,
2744                use_github_app_token: false,
2745            }),
2746            ..Default::default()
2747        });
2748        let mut ctx = Context::new(config, ContextOptions::default());
2749        ctx.populate_metadata_var().unwrap();
2750        let name = ctx
2751            .render_template("{{ Metadata.CommitAuthor.Name }}")
2752            .unwrap();
2753        assert_eq!(name, "Alice Developer");
2754        let email = ctx
2755            .render_template("{{ Metadata.CommitAuthor.Email }}")
2756            .unwrap();
2757        assert_eq!(email, "alice@example.com");
2758    }
2759
2760    #[test]
2761    fn test_artifact_id_template_var() {
2762        let mut config = Config::default();
2763        config.project_name = "myapp".to_string();
2764        let mut ctx = Context::new(config, ContextOptions::default());
2765        ctx.template_vars_mut().set("ArtifactID", "default");
2766
2767        let result = ctx.render_template("{{ .ArtifactID }}").unwrap();
2768        assert_eq!(result, "default");
2769    }
2770
2771    #[test]
2772    fn test_artifact_id_empty_when_not_set() {
2773        let mut config = Config::default();
2774        config.project_name = "myapp".to_string();
2775        let mut ctx = Context::new(config, ContextOptions::default());
2776        ctx.template_vars_mut().set("ArtifactID", "");
2777
2778        let result = ctx.render_template("{{ .ArtifactID }}").unwrap();
2779        assert_eq!(result, "");
2780    }
2781
2782    #[test]
2783    fn test_pro_vars_rendered_in_templates() {
2784        // Test that all Pro vars can be used in templates together
2785        let mut config = Config::default();
2786        config.tag = Some(crate::config::TagConfig {
2787            tag_prefix: Some("api/".to_string()),
2788            ..Default::default()
2789        });
2790        let opts = ContextOptions {
2791            snapshot: false,
2792            nightly: false,
2793            merge: true,
2794            ..Default::default()
2795        };
2796        let mut ctx = Context::new(config, opts);
2797        ctx.git_info = Some(make_git_info(false, None));
2798        ctx.populate_git_vars();
2799
2800        let result = ctx
2801            .render_template(
2802                "{% if IsRelease %}release{% endif %}-{% if IsMerging %}merge{% endif %}-{{ .PrefixedTag }}",
2803            )
2804            .unwrap();
2805        assert_eq!(result, "release-merge-api/v1.2.3");
2806    }
2807
2808    #[test]
2809    fn test_is_release_without_git_info() {
2810        // IsRelease should still be set even without git info
2811        let config = Config::default();
2812        let opts = ContextOptions {
2813            snapshot: false,
2814            nightly: false,
2815            ..Default::default()
2816        };
2817        let mut ctx = Context::new(config, opts);
2818        ctx.populate_git_vars();
2819
2820        assert_eq!(
2821            ctx.template_vars().get_structured("IsRelease"),
2822            Some(&tera::Value::Bool(true))
2823        );
2824    }
2825
2826    #[test]
2827    fn test_is_merging_without_git_info() {
2828        // IsMerging should still be set even without git info
2829        let config = Config::default();
2830        let opts = ContextOptions {
2831            merge: true,
2832            ..Default::default()
2833        };
2834        let mut ctx = Context::new(config, opts);
2835        ctx.populate_git_vars();
2836
2837        assert_eq!(
2838            ctx.template_vars().get_structured("IsMerging"),
2839            Some(&tera::Value::Bool(true))
2840        );
2841    }
2842
2843    // -----------------------------------------------------------------------
2844    // Monorepo template variable tests
2845    // -----------------------------------------------------------------------
2846
2847    /// Parity proof: in monorepo mode `populate_git_vars` derives `Version`
2848    /// from the shared `SemVer::version_string()` helper — the SAME source the
2849    /// build stage's per-crate `crate_template_overrides` uses — so the two
2850    /// can't drift. Exercised with a prerelease + build-metadata tag, the case
2851    /// where the old raw string-strip and the struct derivation could diverge.
2852    #[test]
2853    fn test_monorepo_version_matches_shared_semver_helper() {
2854        let mut config = Config::default();
2855        config.monorepo = Some(crate::config::MonorepoConfig {
2856            tag_prefix: Some("core/".to_string()),
2857            dir: None,
2858        });
2859        let mut ctx = Context::new(config, ContextOptions::default());
2860
2861        let semver = SemVer {
2862            major: 2,
2863            minor: 1,
2864            patch: 0,
2865            prerelease: Some("rc.1".to_string()),
2866            build_metadata: Some("build.7".to_string()),
2867        };
2868        let mut info = make_git_info(false, None);
2869        info.tag = "core/v2.1.0-rc.1+build.7".to_string();
2870        info.semver = semver.clone();
2871        ctx.git_info = Some(info);
2872        ctx.populate_git_vars();
2873
2874        let v = ctx.template_vars();
2875        // populate_git_vars (monorepo path) and the build stage's per-crate
2876        // derivation both route through SemVer::version_string().
2877        assert_eq!(v.get("Version"), Some(&semver.version_string()));
2878        assert_eq!(v.get("Version"), Some(&"2.1.0-rc.1+build.7".to_string()));
2879        assert_eq!(v.get("RawVersion"), Some(&semver.raw_version_string()));
2880        assert_eq!(v.get("RawVersion"), Some(&"2.1.0".to_string()));
2881        // Tag is still the monorepo-stripped value.
2882        assert_eq!(v.get("Tag"), Some(&"v2.1.0-rc.1+build.7".to_string()));
2883    }
2884
2885    #[test]
2886    fn test_monorepo_tag_prefix_strips_tag_for_template_var() {
2887        let mut config = Config::default();
2888        config.monorepo = Some(crate::config::MonorepoConfig {
2889            tag_prefix: Some("subproject1/".to_string()),
2890            dir: None,
2891        });
2892        let mut ctx = Context::new(config, ContextOptions::default());
2893
2894        // Simulate a monorepo tag: the full prefixed tag is stored in git_info.
2895        let mut info = make_git_info(false, None);
2896        info.tag = "subproject1/v1.2.3".to_string();
2897        info.previous_tag = Some("subproject1/v1.2.2".to_string());
2898        info.summary = "subproject1/v1.2.3-0-gabc123d".to_string();
2899        ctx.git_info = Some(info);
2900        ctx.populate_git_vars();
2901
2902        let v = ctx.template_vars();
2903        // Tag should have the prefix stripped.
2904        assert_eq!(v.get("Tag"), Some(&"v1.2.3".to_string()));
2905        // Version should derive from stripped tag.
2906        assert_eq!(v.get("Version"), Some(&"1.2.3".to_string()));
2907        // PrefixedTag should retain the full tag.
2908        assert_eq!(
2909            v.get("PrefixedTag"),
2910            Some(&"subproject1/v1.2.3".to_string())
2911        );
2912        // PreviousTag should be stripped (consistent with Tag).
2913        assert_eq!(v.get("PreviousTag"), Some(&"v1.2.2".to_string()));
2914        // PrefixedPreviousTag should retain the full tag.
2915        assert_eq!(
2916            v.get("PrefixedPreviousTag"),
2917            Some(&"subproject1/v1.2.2".to_string())
2918        );
2919        // Summary should be stripped.
2920        assert_eq!(v.get("Summary"), Some(&"v1.2.3-0-gabc123d".to_string()));
2921        // PrefixedSummary should retain the full summary.
2922        assert_eq!(
2923            v.get("PrefixedSummary"),
2924            Some(&"subproject1/v1.2.3-0-gabc123d".to_string())
2925        );
2926    }
2927
2928    #[test]
2929    fn test_monorepo_prefixed_previous_tag() {
2930        let mut config = Config::default();
2931        config.monorepo = Some(crate::config::MonorepoConfig {
2932            tag_prefix: Some("svc/".to_string()),
2933            dir: None,
2934        });
2935        let mut ctx = Context::new(config, ContextOptions::default());
2936
2937        let mut info = make_git_info(false, None);
2938        info.tag = "svc/v2.0.0".to_string();
2939        info.previous_tag = Some("svc/v1.9.0".to_string());
2940        ctx.git_info = Some(info);
2941        ctx.populate_git_vars();
2942
2943        let v = ctx.template_vars();
2944        // PrefixedPreviousTag should be the full previous tag.
2945        assert_eq!(
2946            v.get("PrefixedPreviousTag"),
2947            Some(&"svc/v1.9.0".to_string())
2948        );
2949        // PreviousTag should be stripped (prefix removed), consistent with Tag.
2950        assert_eq!(v.get("PreviousTag"), Some(&"v1.9.0".to_string()));
2951    }
2952
2953    #[test]
2954    fn test_no_monorepo_falls_back_to_tag_prefix() {
2955        // When monorepo is not set, PrefixedTag should use tag.tag_prefix.
2956        let mut config = Config::default();
2957        config.tag = Some(crate::config::TagConfig {
2958            tag_prefix: Some("release/".to_string()),
2959            ..Default::default()
2960        });
2961        let mut ctx = Context::new(config, ContextOptions::default());
2962        ctx.git_info = Some(make_git_info(false, None));
2963        ctx.populate_git_vars();
2964
2965        let v = ctx.template_vars();
2966        // Tag is plain "v1.2.3" (not stripped because no monorepo).
2967        assert_eq!(v.get("Tag"), Some(&"v1.2.3".to_string()));
2968        // PrefixedTag should prepend tag_prefix.
2969        assert_eq!(v.get("PrefixedTag"), Some(&"release/v1.2.3".to_string()));
2970        assert_eq!(
2971            v.get("PrefixedPreviousTag"),
2972            Some(&"release/v1.2.2".to_string())
2973        );
2974    }
2975
2976    #[test]
2977    fn test_monorepo_overrides_tag_prefix_for_prefixed_vars() {
2978        // When both monorepo.tag_prefix and tag.tag_prefix are set,
2979        // monorepo should take precedence for PrefixedTag.
2980        let mut config = Config::default();
2981        config.tag = Some(crate::config::TagConfig {
2982            tag_prefix: Some("release/".to_string()),
2983            ..Default::default()
2984        });
2985        config.monorepo = Some(crate::config::MonorepoConfig {
2986            tag_prefix: Some("svc/".to_string()),
2987            dir: None,
2988        });
2989        let mut ctx = Context::new(config, ContextOptions::default());
2990
2991        let mut info = make_git_info(false, None);
2992        info.tag = "svc/v1.2.3".to_string();
2993        info.previous_tag = Some("svc/v1.2.2".to_string());
2994        ctx.git_info = Some(info);
2995        ctx.populate_git_vars();
2996
2997        let v = ctx.template_vars();
2998        // Monorepo takes precedence: Tag is stripped.
2999        assert_eq!(v.get("Tag"), Some(&"v1.2.3".to_string()));
3000        // PrefixedTag is the full monorepo tag, NOT tag_prefix-prepended.
3001        assert_eq!(v.get("PrefixedTag"), Some(&"svc/v1.2.3".to_string()));
3002    }
3003
3004    #[test]
3005    fn test_monorepo_prefixed_summary() {
3006        let mut config = Config::default();
3007        config.monorepo = Some(crate::config::MonorepoConfig {
3008            tag_prefix: Some("pkg/".to_string()),
3009            dir: None,
3010        });
3011        let mut ctx = Context::new(config, ContextOptions::default());
3012
3013        let mut info = make_git_info(false, None);
3014        info.tag = "pkg/v1.2.3".to_string();
3015        // In a real monorepo, `git describe` already includes the prefix in the summary.
3016        info.summary = "pkg/v1.2.3-0-gabc123d".to_string();
3017        ctx.git_info = Some(info);
3018        ctx.populate_git_vars();
3019
3020        // PrefixedSummary is info.summary as-is (already contains prefix).
3021        assert_eq!(
3022            ctx.template_vars().get("PrefixedSummary"),
3023            Some(&"pkg/v1.2.3-0-gabc123d".to_string())
3024        );
3025        // Summary should have the prefix stripped.
3026        assert_eq!(
3027            ctx.template_vars().get("Summary"),
3028            Some(&"v1.2.3-0-gabc123d".to_string())
3029        );
3030    }
3031
3032    #[test]
3033    fn test_monorepo_no_previous_tag() {
3034        let mut config = Config::default();
3035        config.monorepo = Some(crate::config::MonorepoConfig {
3036            tag_prefix: Some("svc/".to_string()),
3037            dir: None,
3038        });
3039        let mut ctx = Context::new(config, ContextOptions::default());
3040
3041        let mut info = make_git_info(false, None);
3042        info.tag = "svc/v1.0.0".to_string();
3043        info.previous_tag = None;
3044        ctx.git_info = Some(info);
3045        ctx.populate_git_vars();
3046
3047        let v = ctx.template_vars();
3048        assert_eq!(v.get("PrefixedPreviousTag"), Some(&"".to_string()));
3049        // PreviousTag should also be empty when no previous tag exists.
3050        assert_eq!(v.get("PreviousTag"), Some(&"".to_string()));
3051    }
3052
3053    // -----------------------------------------------------------------------
3054    // Integration test: full monorepo flow
3055    // -----------------------------------------------------------------------
3056
3057    #[test]
3058    fn test_monorepo_full_flow_all_vars() {
3059        // End-to-end test: config with monorepo.tag_prefix + dir
3060        // → context creation → populate_git_vars → verify ALL template vars.
3061        let mut config = Config::default();
3062        config.project_name = "mymonorepo".to_string();
3063        config.monorepo = Some(crate::config::MonorepoConfig {
3064            tag_prefix: Some("services/api/".to_string()),
3065            dir: Some("services/api".to_string()),
3066        });
3067
3068        // Verify Config helper methods work
3069        assert_eq!(config.monorepo_tag_prefix(), Some("services/api/"));
3070        assert_eq!(config.monorepo_dir(), Some("services/api"));
3071
3072        let mut ctx = Context::new(config, ContextOptions::default());
3073
3074        // Simulate git info as it would appear in a monorepo:
3075        // tag and summary already contain the prefix from git.
3076        let mut info = make_git_info(false, None);
3077        info.tag = "services/api/v2.1.0".to_string();
3078        info.previous_tag = Some("services/api/v2.0.5".to_string());
3079        info.summary = "services/api/v2.1.0-0-gabc123d".to_string();
3080        info.semver = crate::git::SemVer {
3081            major: 2,
3082            minor: 1,
3083            patch: 0,
3084            prerelease: None,
3085            build_metadata: None,
3086        };
3087        ctx.git_info = Some(info);
3088        ctx.populate_git_vars();
3089
3090        let v = ctx.template_vars();
3091
3092        // Base vars should have the prefix STRIPPED.
3093        assert_eq!(v.get("Tag"), Some(&"v2.1.0".to_string()));
3094        assert_eq!(v.get("Version"), Some(&"2.1.0".to_string()));
3095        assert_eq!(v.get("RawVersion"), Some(&"2.1.0".to_string()));
3096        assert_eq!(v.get("Major"), Some(&"2".to_string()));
3097        assert_eq!(v.get("Minor"), Some(&"1".to_string()));
3098        assert_eq!(v.get("Patch"), Some(&"0".to_string()));
3099        assert_eq!(v.get("PreviousTag"), Some(&"v2.0.5".to_string()));
3100        assert_eq!(v.get("Summary"), Some(&"v2.1.0-0-gabc123d".to_string()));
3101
3102        // Prefixed vars should retain the FULL prefix.
3103        assert_eq!(
3104            v.get("PrefixedTag"),
3105            Some(&"services/api/v2.1.0".to_string())
3106        );
3107        assert_eq!(
3108            v.get("PrefixedPreviousTag"),
3109            Some(&"services/api/v2.0.5".to_string())
3110        );
3111        assert_eq!(
3112            v.get("PrefixedSummary"),
3113            Some(&"services/api/v2.1.0-0-gabc123d".to_string())
3114        );
3115
3116        // Project name should be available.
3117        assert_eq!(v.get("ProjectName"), Some(&"mymonorepo".to_string()));
3118    }
3119
3120    #[test]
3121    fn context_env_var_defaults_to_process_env_source() {
3122        let ctx = Context::new(Config::default(), ContextOptions::default());
3123        // A deliberately weird name no real shell will ever export.
3124        assert_eq!(ctx.env_var("ANODIZER_T3_UNSET_VAR"), None);
3125    }
3126
3127    #[test]
3128    fn context_env_var_routes_to_injected_source() {
3129        let mut ctx = Context::new(Config::default(), ContextOptions::default());
3130        ctx.set_env_source(crate::MapEnvSource::new().with("INJECTED", "yes"));
3131        assert_eq!(ctx.env_var("INJECTED"), Some("yes".to_string()));
3132        // The injected source REPLACES the process source — `PATH` is set
3133        // in every realistic execution environment, but the map does not
3134        // know about it, so the read must return `None`.
3135        assert_eq!(ctx.env_var("PATH"), None);
3136    }
3137
3138    #[test]
3139    #[serial_test::serial]
3140    fn populate_runtime_vars_sets_rustc_version() {
3141        let config = Config::default();
3142        let mut ctx = Context::new(config, ContextOptions::default());
3143        // RustcVersion is folded into populate_runtime_vars — exercising the
3144        // public entry point proves the delegation wires the var through.
3145        ctx.populate_runtime_vars();
3146
3147        let ver = ctx
3148            .template_vars()
3149            .get("RustcVersion")
3150            .expect("RustcVersion should be set after populate_runtime_vars");
3151        // On a host with rustc on PATH the var must be non-empty and start
3152        // with a digit (e.g. "1.96.0").  On a host without rustc the var is
3153        // empty but must still be present (no missing-key footgun).
3154        if !ver.is_empty() {
3155            assert!(
3156                ver.chars().next().is_some_and(|c| c.is_ascii_digit()),
3157                "RustcVersion should start with a digit: {ver}"
3158            );
3159        }
3160    }
3161}