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