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