anodizer 0.28.1

A Rust-native release automation tool inspired by GoReleaser
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
use super::*;

/// Decide whether the pre-flight publisher-state check should run.
///
/// Encodes the gating rules so they can be unit-tested without dragging
/// the entire pipeline up. The rules are:
///
/// - `--snapshot` / `--dry-run` / `--split` skip → no upstream side effects.
/// - `publish` in `skip` → caller opted out of one-way doors.
/// - otherwise → true. `--publish-only` runs it like a regular release: it
///   is the one mode that actually crosses the one-way doors, and the
///   probes (whoami / duplicate-version / moderation-queue / open-PR /
///   endpoint reachability) are read-only and cost seconds — the
///   config-derived env preflight has already validated the credentials
///   they use by the time this fires.
///
/// `--announce-only` and `--publish-only` are not parameters: both run the
/// engine, under a narrower scope.
pub(crate) fn should_run_preflight(
    snapshot: bool,
    dry_run: bool,
    split: bool,
    preflight_skipped: bool,
) -> bool {
    !snapshot && !dry_run && !split && !preflight_skipped
}

/// `--prepare`: runs local build/archive/sign/checksum/sbom stages but skips
/// everything that reaches upstream — the shared
/// [`anodizer_core::stages::UPSTREAM_STAGES`] classification (release,
/// docker build/push + signature push, blob, publish, snapcraft upload,
/// announce, post-publish verification), so the publish-nothing contract
/// cannot drift from the set the determinism harness also derives from.
/// Idempotent — won't duplicate stages already present in `skip`.
///
/// Composition with `--snapshot`: well-defined — `--prepare --snapshot` emits
/// snapshot-prefixed artifacts (`Version`/`Tag` derived from
/// `<version>-SNAPSHOT-<shortcommit>`, no tag required) without publishing.
/// Useful for generating pre-release archives in PR CI without needing a real
/// tag or release. `--prepare` without `--snapshot` requires a real tag.
pub(crate) fn apply_prepare_mode_to_skip(skip: &mut Vec<String>) {
    for &stage in anodizer_core::stages::UPSTREAM_STAGES {
        if !skip.iter().any(|s| s == stage) {
            skip.push(stage.to_string());
        }
    }
}

/// Installs the pre-submitter verify-release gate onto `ctx.verify_gate`.
/// Extracted to a named function (rather than an inline closure at the call
/// site) so wiring — not just [`anodizer_stage_verify_release::run_asset_gate`]'s
/// own behavior, which is unit-tested directly in that crate — has its own
/// falsifiable test: deleting the call to this function, or swapping it for
/// a decoy, must fail a test rather than silently pass the whole tree.
pub(crate) fn install_verify_gate(ctx: &mut Context) {
    ctx.verify_gate = Some(std::sync::Arc::new(|ctx: &mut Context| {
        anodizer_stage_verify_release::run_asset_gate(ctx)
    }));
}

/// `--strict` and `--allow-nondeterministic` are mutually exclusive: strict
/// mode forbids the determinism stage from suppressing findings, the
/// allowlist's whole purpose is to suppress one. clap can't express this
/// directly (--strict lives on the top-level Cli struct and the allowlist on
/// the Release variant), so the check runs here.
pub(crate) fn validate_strict_vs_allowlist(opts: &ReleaseOpts) -> Result<()> {
    if opts.strict && !opts.allow_nondeterministic.is_empty() {
        anyhow::bail!(
            "--strict and --allow-nondeterministic are mutually exclusive (drop --strict if a runtime exemption is required)"
        );
    }
    Ok(())
}

/// Apply the workspace overlay (explicit `--workspace`, or inferred from the
/// `--crate` selection when it resolves into a single workspace). Returns the
/// list of workspace-level skip stages to merge later. Delegates to the
/// shared [`helpers::apply_workspace_scope`] so `release`, `build`, and every
/// other crate-selecting command scope and validate identically.
pub(crate) fn apply_workspace_overlay_for_opts(
    config: &mut Config,
    opts: &ReleaseOpts,
    log: &StageLogger,
) -> Result<Vec<String>> {
    helpers::apply_workspace_scope(config, opts.workspace.as_deref(), &opts.crate_names, log)
}

/// Apply CLI overrides that mutate `config.release` (draft / header / footer
/// and their `_tmpl` variants). `*_tmpl` flags override their plain
/// counterparts; the template stage renders the content later.
pub(crate) fn apply_release_meta_overrides(config: &mut Config, opts: &ReleaseOpts) -> Result<()> {
    if opts.draft {
        let release = config.release.get_or_insert_with(Default::default);
        release.draft = Some(true);
    }
    if let Some(ref header_path) = opts.release_header {
        let header_content = std::fs::read_to_string(header_path).with_context(|| {
            format!(
                "failed to read release header file: {}",
                header_path.display()
            )
        })?;
        let release = config.release.get_or_insert_with(Default::default);
        release.header = Some(anodizer_core::config::ContentSource::Inline(header_content));
    }
    if let Some(ref header_tmpl_path) = opts.release_header_tmpl {
        let raw = std::fs::read_to_string(header_tmpl_path).with_context(|| {
            format!(
                "failed to read release header template file: {}",
                header_tmpl_path.display()
            )
        })?;
        let release = config.release.get_or_insert_with(Default::default);
        release.header = Some(anodizer_core::config::ContentSource::Inline(raw));
    }
    if let Some(ref footer_path) = opts.release_footer {
        let footer_content = std::fs::read_to_string(footer_path).with_context(|| {
            format!(
                "failed to read release footer file: {}",
                footer_path.display()
            )
        })?;
        let release = config.release.get_or_insert_with(Default::default);
        release.footer = Some(anodizer_core::config::ContentSource::Inline(footer_content));
    }
    if let Some(ref footer_tmpl_path) = opts.release_footer_tmpl {
        let raw = std::fs::read_to_string(footer_tmpl_path).with_context(|| {
            format!(
                "failed to read release footer template file: {}",
                footer_tmpl_path.display()
            )
        })?;
        let release = config.release.get_or_insert_with(Default::default);
        release.footer = Some(anodizer_core::config::ContentSource::Inline(raw));
    }
    Ok(())
}

/// The files a run writes into `dist/` before any stage produces an
/// artifact: the effective config (`config.yaml`, every run), the rendered
/// `--release-notes-tmpl` (`release-notes.md`, only with that flag) and the
/// `--split` worker matrix (`matrix.json`, only with `--split`). A failed run
/// leaves exactly these behind, so their presence is not the population the
/// dist gate refuses to build over. Because only the first is unconditional,
/// the gate deletes all three once it passes rather than trusting the next run
/// to overwrite them — otherwise a `matrix.json` from an earlier `--split`
/// outlives the split that wrote it and a later `--merge` reconciles against a
/// worker set that no longer exists.
pub(crate) const RUN_BOOKKEEPING_FILES: &[&str] = &[
    anodizer_core::dist::CONFIG_YAML,
    anodizer_core::dist::RELEASE_NOTES_MD,
    anodizer_core::dist::MATRIX_JSON,
];

/// Enforce the dist directory state: `--clean` removes it (logs in dry-run);
/// otherwise a dist holding anything beyond the run's own bookkeeping
/// ([`RUN_BOOKKEEPING_FILES`]) is a hard error, and the bookkeeping a previous
/// run left is removed so this run starts from only what it writes itself.
/// `--merge` / `--publish-only` skip the non-empty check because each of
/// those modes requires preserved dist content.
pub(crate) fn enforce_dist_state(
    config: &Config,
    opts: &ReleaseOpts,
    log: &StageLogger,
) -> Result<()> {
    if opts.clean && !opts.dry_run {
        let dist = &config.dist;
        if dist.exists() {
            std::fs::remove_dir_all(dist)?;
        }
    } else if opts.clean && opts.dry_run {
        log.status("(dry-run) would clean dist directory");
    }

    if !opts.clean && !opts.merge && !opts.publish_only && !opts.announce_only {
        let dist = &config.dist;
        if let Some(populated) = dist_population(dist) {
            return Err(anodizer_core::error_class::deterministic_msg(format!(
                "dist directory '{}' is not empty (holds '{populated}'); use --clean to remove it first",
                dist.display()
            )));
        }
        clear_stale_bookkeeping(dist, opts.dry_run, log)?;
    }
    Ok(())
}

/// Drop the [`RUN_BOOKKEEPING_FILES`] a previous run left in `dist`, so the
/// only ones present afterwards are the ones this run writes.
fn clear_stale_bookkeeping(dist: &Path, dry_run: bool, log: &StageLogger) -> Result<()> {
    for name in RUN_BOOKKEEPING_FILES {
        let path = dist.join(name);
        if !path.is_file() {
            continue;
        }
        if dry_run {
            log.status(&format!("(dry-run) would remove stale {name}"));
        } else {
            std::fs::remove_file(&path)
                .with_context(|| format!("remove stale {}", path.display()))?;
        }
    }
    Ok(())
}

/// The first FILE under `dist` that is neither one of the run's own
/// [`RUN_BOOKKEEPING_FILES`] nor a split shard's own `context.json`, as a
/// `dist`-relative path; `None` when nothing else is there.
///
/// Both exemptions are anchored to the depth the run writes them at: the
/// bookkeeping files at the root of `dist`, a shard's `context.json`
/// directly inside its own `dist/<shard>/`. A stage artifact that happens
/// to share one of those names deeper in the tree — `dist/<shard>/config.yaml`
/// — is population like any other file, and a gate that excused it would
/// silently build over it.
///
/// Directories are never population in themselves. A `--split` run creates
/// `dist/<shard>/` before any stage produces an artifact, so a run refused
/// after that point would otherwise be unable to retry without `--clean`; the
/// shard directory only counts once it holds something the retry would
/// overwrite.
fn dist_population(dist: &Path) -> Option<String> {
    fn walk(dir: &Path, prefix: &Path, depth: usize, found: &mut Vec<String>) {
        let Ok(entries) = dir.read_dir() else {
            return;
        };
        for entry in entries.flatten() {
            let name = entry.file_name().to_string_lossy().into_owned();
            let rel = prefix.join(&name);
            if entry.path().is_dir() {
                walk(&entry.path(), &rel, depth + 1, found);
                continue;
            }
            let run_bookkeeping = depth == 0 && RUN_BOOKKEEPING_FILES.contains(&name.as_str());
            let shard_context = depth == 1 && name == anodizer_core::dist::CONTEXT_JSON;
            if !run_bookkeeping && !shard_context {
                found.push(rel.to_string_lossy().replace('\\', "/"));
            }
        }
    }

    let mut found = Vec::new();
    walk(dist, Path::new(""), 0, &mut found);
    // Sorted so the named entry is stable across runs rather than whatever
    // the filesystem returned first.
    found.sort();
    found.into_iter().next()
}
/// Read the `--release-notes-tmpl` file (when set) so its content can be
/// rendered post-`populate_*_vars`. `--release-notes-tmpl` overrides
/// `--release-notes`.
pub(crate) fn read_release_notes_template(opts: &ReleaseOpts) -> Result<Option<(PathBuf, String)>> {
    if let Some(ref tmpl_path) = opts.release_notes_tmpl {
        let content = std::fs::read_to_string(tmpl_path).with_context(|| {
            format!(
                "failed to read release notes template: {}",
                tmpl_path.display()
            )
        })?;
        Ok(Some((tmpl_path.clone(), content)))
    } else {
        Ok(None)
    }
}

/// Resolve the `--simulate-failure` list. The flag is test-only and gated by
/// `ANODIZE_TEST_HARNESS=1`; production releases that accidentally set the
/// flag get a hard error rather than silent pass-through so the surface
/// cannot be weaponized.
pub(crate) fn resolve_simulate_failure(simulate: &mut Vec<String>) -> Result<Vec<String>> {
    if std::env::var("ANODIZE_TEST_HARNESS").as_deref() == Ok("1") {
        Ok(std::mem::take(simulate))
    } else if !simulate.is_empty() {
        anyhow::bail!(
            "--simulate-failure requires ANODIZE_TEST_HARNESS=1 (test-harness gated flag)"
        );
    } else {
        Ok(Vec::new())
    }
}

/// Translate `--allow-nondeterministic name=reason` (repeatable) into
/// `(name, reason)` tuples. Empty reasons are rejected so the run summary
/// always carries a human-readable justification.
pub(crate) fn parse_allow_nondeterministic(entries: &[String]) -> Result<Vec<(String, String)>> {
    entries
        .iter()
        .map(|s| {
            let (name, reason) = s.split_once('=').ok_or_else(|| {
                anyhow::anyhow!("--allow-nondeterministic must be NAME=REASON, got: {}", s)
            })?;
            if reason.trim().is_empty() {
                anyhow::bail!("--allow-nondeterministic reason cannot be empty for: {}", s);
            }
            Ok::<_, anyhow::Error>((name.to_string(), reason.to_string()))
        })
        .collect()
}

/// Resolve `project_root` for [`ContextOptions::project_root`].
///
/// Precedence:
///   1. The parent directory of the resolved config file (authoritative
///      — the operator may have invoked anodizer from a subdirectory
///      with `--config=../anodizer.yaml`).
///   2. Process CWD (`current_dir`), as a fallback when the config path
///      lacks a parent component (e.g. a bare filename in `/`).
///
/// Both branches canonicalize when possible so downstream consumers that
/// join repo-relative paths (snapcraft icons, extra-file globs, ...) hit
/// the real tree even when called from a symlinked checkout.
///
/// When the CWD fallback fires (bare-filename `--config=anodizer.yaml`)
/// and `log` is `Some`, a warn surfaces because the resulting CWD
/// anchor is almost certainly NOT what the operator meant when they
/// passed a bare filename: repo-relative file lookups (snapcraft icon
/// resolution, extra-file globs, etc.) will all hit the process CWD
/// rather than the repo root. A warn rather than a bail, because
/// legitimate workflows do invoke anodizer with CWD == project root and
/// a bare filename; the warn lets a misconfiguration become visible
/// without breaking the working case.
pub(crate) fn resolve_project_root(
    config_path: &std::path::Path,
    log: Option<&StageLogger>,
) -> Option<PathBuf> {
    let from_parent = config_path
        .parent()
        .filter(|p| !p.as_os_str().is_empty())
        .map(std::path::Path::to_path_buf);
    let candidate = match from_parent {
        Some(p) => p,
        None => {
            let cwd = std::env::current_dir().ok()?;
            if let Some(log) = log {
                log.warn(&format!(
                    "project_root falling back to CWD `{}` because --config=`{}` is a bare filename",
                    cwd.display(),
                    config_path.display()
                ));
                log.warn(
                    "repo-relative file lookups (snapcraft icons, extra-file globs, ...) \
                     will resolve against the process CWD — pass --config with a parent \
                     directory (e.g. `--config=./anodizer.yaml`) if this is incorrect",
                );
            }
            cwd
        }
    };
    Some(std::fs::canonicalize(&candidate).unwrap_or(candidate))
}

/// Resolve `--host-targets` into `opts.targets` against the detected host
/// triple. Thin wrapper over [`apply_host_targets_filter`] that supplies the
/// real host via `rustc -vV`; the filter itself is host-injectable so its
/// per-config-mode behaviour can be unit-tested deterministically.
pub(crate) fn resolve_host_targets(
    opts: &mut ReleaseOpts,
    config: &Config,
    selected_crates: &[String],
    log: &StageLogger,
) -> Result<()> {
    let host = anodizer_core::partial::resolve_host_target()
        .context("--host-targets: failed to detect the host target triple")?;
    apply_host_targets_filter(opts, config, selected_crates, &host, log)
}

/// Partition the configured target union for `selected_crates` into the
/// host-buildable subset and write it to `opts.targets`.
///
/// Collects the union (honoring per-build `targets`, `defaults.targets`, and
/// `builds.ignore` exactly as the build stage does — so every config mode,
/// single-crate / workspace-lockstep / workspace-per-crate, resolves the same
/// list the builds will), partitions it via
/// [`anodizer_core::partial::host_buildable_targets`] against `host`, logs the
/// skipped set once, and feeds the kept set through the existing
/// `PartialTarget::Targets` intersection filter.
///
/// Hard-errors when the host can build NONE of the configured targets
/// (e.g. an apple-darwin-only config on a Linux host): proceeding would
/// emit an empty snapshot that breaks the downstream archive / checksum
/// stages, so the operator is told which native host each skipped group
/// requires (a macOS host for apple targets, a Windows host for
/// windows-msvc) rather than a hardcoded single remedy.
pub(crate) fn apply_host_targets_filter(
    opts: &mut ReleaseOpts,
    config: &Config,
    selected_crates: &[String],
    host: &str,
    log: &StageLogger,
) -> Result<()> {
    let configured = helpers::collect_build_targets(config, selected_crates);

    // A config with no build targets at all has nothing to filter; leave
    // `opts.targets` untouched so downstream stages handle the no-build case
    // (e.g. lib-only crates) exactly as they would without --host-targets.
    if configured.is_empty() {
        return Ok(());
    }

    let (kept, skipped) = anodizer_core::partial::host_buildable_targets(host, &configured);

    if let Some(msg) = anodizer_core::partial::host_targets_skip_message(host, &skipped) {
        log.warn(&msg);
    }

    if kept.is_empty() {
        // Every configured target was skipped — name the native host each
        // group needs (reusing the grouped skip clauses) rather than a
        // hardcoded macOS remedy, which would mislead a windows-msvc-only
        // config skipped purely for lack of a Windows host.
        let reasons = anodizer_core::partial::host_targets_skip_reasons(host, &skipped);
        anyhow::bail!(
            "--host-targets: none of the {} configured target(s) can be built on this host \
             ({}); all require a different native host: {}. Adjust build.targets, or run on \
             a host that satisfies the constraint above.",
            configured.len(),
            host,
            reasons,
        );
    }

    opts.targets = Some(kept);
    Ok(())
}

/// Assemble the [`ContextOptions`] from parsed flags + derived state.
/// `resume_release` auto-enables under `--publish-only` so the publish
/// pipeline's `ReleaseStage` and `github-release` publisher target the same
/// tag without tripping the leftover-asset bail.
///
/// `project_root` resolves from the parent directory of the resolved
/// config file when available, falling back to the process CWD. The
/// resolved config path is authoritative because the operator may have
/// invoked anodizer from a subdirectory with `--config=../anodizer.yaml`;
/// CWD alone would point repo-relative consumers at the wrong tree.
/// Stage modules that need to read repo-relative files (snapcraft
/// icons, extra-file globs, the cargo publisher's `target/`
/// resolution, ...) consume this via `ctx.options.project_root`.
pub(crate) fn build_context_options(
    opts: &ReleaseOpts,
    skip_stages: Vec<String>,
    selected_sorted: Vec<String>,
    simulate_failure_publishers: Vec<String>,
    runtime_nondeterministic_allowlist: Vec<(String, String)>,
    project_root: Option<PathBuf>,
    changelog_aggregate_set: Option<Vec<anodizer_core::config::CrateConfig>>,
) -> ContextOptions {
    ContextOptions {
        snapshot: opts.snapshot,
        nightly: opts.nightly,
        dry_run: opts.dry_run,
        quiet: opts.quiet,
        verbose: opts.verbose,
        debug: opts.debug,
        skip_stages,
        selected_crates: selected_sorted,
        token: opts.token.clone(),
        parallelism: opts.parallelism,
        single_target: opts.single_target.clone(),
        release_notes_path: opts.release_notes.clone(),
        fail_fast: opts.fail_fast,
        partial_target: opts
            .targets
            .clone()
            .map(anodizer_core::partial::PartialTarget::Targets),
        merge: opts.merge,
        publish_only: opts.publish_only,
        project_root,
        strict: opts.strict,
        resume_release: opts.resume_release || opts.publish_only,
        replace_existing_artifacts: opts.replace_existing,
        skip_post_publish_poll: opts.no_post_publish_poll,
        gate_submitter: if opts.no_gate_submitter {
            Some(false)
        } else {
            None
        },
        simulate_failure_publishers,
        show_skipped: opts.show_skipped,
        runtime_nondeterministic_allowlist,
        summary_json_path: opts.summary_json.clone(),
        allow_ai_failure: opts.allow_ai_failure,
        // The full release pipeline has no `--from`; changelog range starts
        // are auto-discovered per crate. Only `anodizer changelog --from`
        // sets this.
        changelog_from: None,
        // The full release pipeline never spans full history; each crate's
        // notes bound at its previous tag. Only `anodizer changelog ..` opts in.
        changelog_full_history: false,
        // The full release pipeline bounds each crate's notes at its previous
        // tag, walking to HEAD; only the standalone `changelog <from>..<to>`
        // command pins an explicit upper bound.
        changelog_to: None,
        // The release pipeline is NOT a local preview: its tag-at-HEAD,
        // dirty-tree, snapshot-gate, and github-native guards must all stay
        // intact. Only the standalone `changelog --format release-notes`
        // command sets this true.
        changelog_preview: false,
        observe: false,
        notify: false,
        allow_snapshot_publish: opts.allow_snapshot_publish,
        publisher_allowlist: opts.publishers.clone(),
        changelog_aggregate_set,
    }
}