anodizer 0.7.0

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
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
use super::helpers;
use crate::commands::bump::cargo_edit::{WorkspaceInfo, load_workspace};
use crate::commands::bump::inference::find_last_tag_for_prefix;
use crate::commands::changelog_sync::{
    ChangelogRouting, RefreshTarget, extract_unreleased_section, refresh_changelogs,
};
use crate::commands::tag::{RepoShape, detect_repo_shape};
use crate::pipeline;
use anodizer_cli::ChangelogFormat;
use anodizer_core::config::Config;
use anodizer_core::context::{Context, ContextOptions};
use anodizer_core::git;
use anodizer_core::log::{StageLogger, Verbosity};
use anodizer_core::stage::Stage;
use anyhow::{Context as _, Result, bail};
use std::io::Write as _;
use std::path::{Path, PathBuf};

/// Options for `anodizer changelog`.
///
/// Bundled struct rather than positional args so adding a flag at the CLI
/// layer doesn't ripple through every test. Mirrors the shape of
/// `release::ReleaseOpts` / `tag::TagOpts`.
pub struct ChangelogOpts {
    /// A specific crate in a workspace, or `None` for every selected crate.
    pub crate_name: Option<String>,
    /// Positional `[<tag>|<range>]`: a `from..to` range, a single `<tag>`
    /// (predecessor-resolved against the crate it belongs to), or `None` to
    /// refresh each crate's pending section against its last tag.
    pub range: Option<String>,
    /// Output format; defaults to keep-a-changelog.
    pub format: ChangelogFormat,
    /// Apply the regenerated `[Unreleased]` to the configured `CHANGELOG.md`
    /// file(s). Valid only with `--format keep-a-changelog`.
    pub write: bool,
    /// Preview as a snapshot release (forwarded to the release-notes path).
    pub snapshot: bool,
    pub config_override: Option<PathBuf>,
    pub verbose: bool,
    pub debug: bool,
    pub quiet: bool,
}

/// The lower bound of a changelog range.
///
/// Three states because an omitted arg and an explicit empty lower bound must
/// mean different things: omitting the positional refreshes each target's
/// pending window (since its last release), while writing `..` (an explicit
/// empty left side) asks for full history. Collapsing both to "no lower
/// bound" would make `..` indistinguishable from omission — the trap this
/// enum exists to remove.
enum RangeStart {
    /// Arg omitted: each target resolves its own last release tag (the pending
    /// `[Unreleased]` window).
    Pending,
    /// Explicit empty lower bound (`..`, `..<ref>`): no lower bound — full history.
    FullHistory,
    /// Explicit ref (`<ref>..`, `<ref>..<ref>`, or a single tag's predecessor).
    Ref(String),
}

/// The resolved commit range driving a changelog render.
struct ResolvedRange {
    start: RangeStart,
    to: Option<String>,
    /// When set, the positional was a single tag that resolved to exactly one
    /// crate; narrows the selection to that crate regardless of `--crate`.
    pinned_crate: Option<String>,
}

pub fn run(opts: ChangelogOpts) -> Result<()> {
    let ChangelogOpts {
        crate_name,
        range,
        format,
        write,
        snapshot,
        config_override,
        verbose,
        debug,
        quiet,
    } = opts;
    let log = StageLogger::new("changelog", Verbosity::from_flags(quiet, verbose, debug));

    // `--write` only makes sense for the in-place keep-a-changelog refresh;
    // release-notes / json stream to stdout for the user to redirect.
    if write && format != ChangelogFormat::KeepAChangelog {
        bail!(
            "--write is only valid with --format keep-a-changelog; \
             redirect stdout to capture release-notes/json output"
        );
    }

    let path = pipeline::find_config_with_logger(config_override.as_deref(), Some(&log))?;
    let config = pipeline::load_config(&path)?;

    let workspace_root =
        crate::commands::helpers::discover_workspace_root(config_override.as_deref())?;

    // Reject an incoherent flat-aggregate config (members sharing one tag prefix
    // but disagreeing on `[package].version`) before any work, identically to
    // `tag` and `bump`.
    let workspace = load_workspace(&workspace_root).ok();
    crate::commands::tag::guard_flat_aggregate_coherence(
        Some(&config),
        workspace.as_ref(),
        &workspace_root,
    )?;

    match format {
        ChangelogFormat::KeepAChangelog => run_refresh(
            &workspace_root,
            &config,
            crate_name.as_deref(),
            range.as_deref(),
            write,
            &log,
        ),
        ChangelogFormat::ReleaseNotes => run_release_notes(
            &workspace_root,
            config,
            crate_name,
            range.as_deref(),
            snapshot,
            verbose,
            debug,
            &log,
        ),
        ChangelogFormat::Json => run_json(
            &workspace_root,
            &config,
            crate_name.as_deref(),
            range.as_deref(),
            &log,
        ),
    }
}

/// Resolve the positional `[<tag>|<range>]` into a [`RangeStart`] + upper
/// bound plus an optional crate pin.
///
/// - `None` → `start: Pending`; each target resolves its own last tag (the
///   pending window since its last release).
/// - `..` / `..<ref>` → empty left side ⇒ `start: FullHistory` (no lower
///   bound); `<ref>..` / `<ref>..<ref>` ⇒ `start: Ref(<ref>)`. No pin (applies
///   to all targets).
/// - `<tag>` → resolve the owning crate from its tag prefix, pin to it, and set
///   `start` to `Ref(predecessor)` (the tag immediately below `<tag>` in that
///   crate's semver-sorted list) or `FullHistory` when `<tag>` is the earliest
///   (full history up to it), with `to = <tag>`.
fn resolve_range(
    workspace_root: &Path,
    config: &Config,
    range: Option<&str>,
) -> Result<ResolvedRange> {
    let Some(spec) = range else {
        return Ok(ResolvedRange {
            start: RangeStart::Pending,
            to: None,
            pinned_crate: None,
        });
    };
    if let Some((from, to)) = spec.split_once("..") {
        let start = if from.is_empty() {
            RangeStart::FullHistory
        } else {
            RangeStart::Ref(from.to_string())
        };
        return Ok(ResolvedRange {
            start,
            to: (!to.is_empty()).then(|| to.to_string()),
            pinned_crate: None,
        });
    }
    // Single tag: resolve the owning crate + predecessor. No predecessor means
    // `<tag>` is the earliest tag, so the range is full history up to it.
    let (owning_crate, prefix) = resolve_tag_owner(config, spec)?;
    let predecessor = predecessor_tag(workspace_root, &prefix, spec)?;
    Ok(ResolvedRange {
        start: predecessor.map_or(RangeStart::FullHistory, RangeStart::Ref),
        to: Some(spec.to_string()),
        pinned_crate: Some(owning_crate),
    })
}

/// Map a [`RangeStart`] to the concrete lower-bound ref the engine-backed
/// formats (`keep-a-changelog`, `json`) pass to the changelog engine.
///
/// - `Pending` → the last tag matching `prefix` (`None` when no tags exist yet,
///   which is naturally full history).
/// - `FullHistory` → `None` (no lower bound).
/// - `Ref(r)` → `Some(r)`.
fn resolve_start_bound(
    start: &RangeStart,
    workspace_root: &Path,
    prefix: &str,
) -> Result<Option<String>> {
    match start {
        RangeStart::Pending => find_last_tag_for_prefix(workspace_root, prefix),
        RangeStart::FullHistory => Ok(None),
        RangeStart::Ref(r) => Ok(Some(r.clone())),
    }
}

/// Resolve which crate a single tag belongs to from its tag-template prefix,
/// returning `(crate_name, prefix)`. Mirrors the `resolve-tag` command:
/// longest-matching prefix wins, and the remainder must look like a version.
fn resolve_tag_owner(config: &Config, tag: &str) -> Result<(String, String)> {
    let all_crates = config.crates.iter().chain(
        config
            .workspaces
            .as_deref()
            .unwrap_or_default()
            .iter()
            .flat_map(|w| &w.crates),
    );
    let mut best: Option<(&str, String)> = None;
    for c in all_crates {
        let prefix =
            git::extract_tag_prefix(&c.tag_template).unwrap_or_else(|| format!("{}-v", c.name));
        if let Some(remainder) = tag.strip_prefix(&prefix) {
            let is_version = remainder
                .split('.')
                .next()
                .is_some_and(|s| !s.is_empty() && s.chars().all(|ch| ch.is_ascii_digit()));
            if is_version && best.as_ref().is_none_or(|(_, p)| prefix.len() > p.len()) {
                best = Some((c.name.as_str(), prefix));
            }
        }
    }
    match best {
        Some((name, prefix)) => Ok((name.to_string(), prefix)),
        None => bail!("no crate in the config matches tag '{}'", tag),
    }
}

/// The tag immediately preceding `tag` in the prefix's semver-sorted list, or
/// `None` when `tag` is the earliest (or absent from the list).
///
/// `get_all_semver_tags_in` returns matches descending by version, so the
/// predecessor is the first entry strictly below `tag`.
fn predecessor_tag(workspace_root: &Path, prefix: &str, tag: &str) -> Result<Option<String>> {
    let tags = git::get_all_semver_tags_in(workspace_root, prefix, None, None)
        .with_context(|| format!("list tags with prefix '{}'", prefix))?;
    let target = git::parse_semver_tag(tag).ok();
    let Some(target) = target else {
        return Ok(None);
    };
    for candidate in &tags {
        if let Ok(v) = git::parse_semver_tag(candidate)
            && v < target
        {
            return Ok(Some(candidate.clone()));
        }
    }
    Ok(None)
}

/// The global tag prefix that `tag`/`bump` apply to the lockstep / single
/// unit: the configured `tag.tag_prefix`, defaulting to `v`.
///
/// Shared by [`select_crates`] (lockstep range bounding) and the
/// `run_release_notes` bare-lockstep synthesis so the default-`v` lives in one
/// place; a hardcoded `v` at either site would miss a custom prefix (e.g.
/// `release-v`) and silently degrade the range to full history.
fn global_tag_prefix(config: &Config) -> String {
    config
        .tag
        .as_ref()
        .and_then(|t| t.tag_prefix.clone())
        .unwrap_or_else(|| "v".to_string())
}

/// Enumerate the crates selected for rendering across all three config modes,
/// honoring `--crate` and a single-tag crate pin.
///
/// Each entry is `(crate_name, crate_dir, tag_prefix)`. For lockstep the sole
/// entry is the workspace root aggregate, prefixed by the resolved
/// `tag.tag_prefix` (default `v`) — identical to how `tag`/`bump` bound the
/// lockstep range.
fn select_crates(
    workspace_root: &Path,
    config: &Config,
    workspace: Option<&WorkspaceInfo>,
    crate_filter: Option<&str>,
) -> Vec<(String, PathBuf, String)> {
    let prefix_for = |c: &anodizer_core::config::CrateConfig| -> String {
        git::extract_tag_prefix(&c.tag_template).unwrap_or_else(|| format!("{}-v", c.name))
    };
    let global_prefix = global_tag_prefix(config);
    let entries: Vec<(String, PathBuf, String)> =
        match detect_repo_shape(workspace_root, Some(config), workspace) {
            RepoShape::Single => {
                // The sole crate (or a config-less single crate): one
                // global-prefixed target at its directory (workspace root when no
                // crate is defined). A crate's own `tag_template` still wins when
                // it sets one; otherwise it inherits the global prefix.
                let c = config.crates.first().or_else(|| {
                    config
                        .workspaces
                        .as_deref()
                        .unwrap_or_default()
                        .iter()
                        .flat_map(|w| &w.crates)
                        .next()
                });
                match c {
                    Some(c) => vec![(
                        c.name.clone(),
                        workspace_root.join(&c.path),
                        git::extract_tag_prefix(&c.tag_template)
                            .unwrap_or_else(|| global_prefix.clone()),
                    )],
                    None => vec![(
                        config.project_name.clone(),
                        workspace_root.to_path_buf(),
                        global_prefix.clone(),
                    )],
                }
            }
            RepoShape::Lockstep | RepoShape::FlatAggregate(_) => {
                // One aggregate target at the workspace root, using the resolved
                // global `tag.tag_prefix`. Genuine lockstep and a flat-aggregate
                // (shared-prefix flat `crates:` list) both render one flat
                // whole-release section, so both collapse to a single entry here.
                vec![(
                    config.project_name.clone(),
                    workspace_root.to_path_buf(),
                    global_prefix.clone(),
                )]
            }
            RepoShape::PerCrate(groups) => groups
                .iter()
                .flatten()
                .map(|c| (c.name.clone(), workspace_root.join(&c.path), prefix_for(c)))
                .collect(),
        };

    match crate_filter {
        Some(name) => entries.into_iter().filter(|(n, _, _)| n == name).collect(),
        None => entries,
    }
}

/// Whether the selected crates render as ONE flat whole-release changelog
/// section (the `single_track` rendering flag).
///
/// [`select_crates`] already collapses every shared-root shape — `Single`,
/// genuine `Lockstep`, and the same-prefix flat-aggregate (`FlatAggregate`) — to
/// exactly ONE workspace-root entry; only a distinct-prefix `PerCrate` yields N.
/// So the flat-aggregate vs multi-track decision is fully made by the shape, and
/// this helper only marks the rendering flag:
/// - `crate_filtered` (an explicit `--crate`/single-tag pin): `false`, so a
///   genuine multi-track repo refreshes only THAT crate's `### <crate>`
///   subsection.
/// - A multi-entry selection (only a distinct-prefix `PerCrate`): `false`,
///   keeping per-crate / multi-track behaviour.
/// - Otherwise a single shared-root entry on shared-root-only routing
///   (`root_enabled && !per_crate`): `true`, forcing the flat roll.
fn resolve_single_track(
    selected: &[(String, PathBuf, String)],
    root_enabled: bool,
    per_crate: bool,
    crate_filtered: bool,
) -> bool {
    if crate_filtered || selected.len() != 1 {
        return false;
    }
    root_enabled && !per_crate
}

/// keep-a-changelog: refresh each selected crate's pending `[Unreleased]`
/// section. Previews to stdout unless `write` writes the file(s) in place.
fn run_refresh(
    workspace_root: &Path,
    config: &Config,
    crate_filter: Option<&str>,
    range: Option<&str>,
    write: bool,
    log: &StageLogger,
) -> Result<()> {
    let resolved = resolve_range(workspace_root, config, range)?;
    let effective_filter = resolved.pinned_crate.as_deref().or(crate_filter);
    let workspace = load_workspace(workspace_root).ok();
    let selected = select_crates(workspace_root, config, workspace.as_ref(), effective_filter);
    if selected.is_empty() {
        log.warn("no crates selected for changelog refresh");
        return Ok(());
    }

    let empty = anodizer_core::config::ChangelogConfig::default();
    let mut routing = ChangelogRouting::from_config(config.changelog.as_ref().unwrap_or(&empty));
    routing.single_track = resolve_single_track(
        &selected,
        routing.root_enabled,
        routing.per_crate,
        effective_filter.is_some(),
    );
    // Derive the root multitrack signal + the full root-routed crate-name set
    // from TOPOLOGY (every configured crate ∩ the root crates filter), so a
    // `--crate`-filtered run still classifies subsections by crate name and a
    // fresh root bootstraps every crate's subsection. One shared full-set source
    // (`config_root_crate_names`) across the refresh / bump / tag callers.
    let root_crate_names =
        crate::commands::changelog_sync::config_root_crate_names(config, routing.root_crates);
    routing.multitrack =
        routing.root_enabled && !routing.single_track && root_crate_names.len() > 1;
    routing.root_crate_names = root_crate_names;

    let targets: Vec<RefreshTarget> = selected
        .into_iter()
        .map(|(name, dir, prefix)| {
            let from_tag = resolve_start_bound(&resolved.start, workspace_root, &prefix)?;
            Ok(RefreshTarget {
                crate_name: name,
                crate_dir: dir,
                from_tag,
                to_ref: resolved.to.clone(),
            })
        })
        .collect::<Result<_>>()?;

    let outputs = refresh_changelogs(workspace_root, &targets, &routing, write, log)?;

    if outputs.is_empty() {
        log.warn("no changelog sections to refresh");
        return Ok(());
    }

    if write {
        // Files written + logged by refresh_changelogs; nothing to print.
        return Ok(());
    }

    // Preview: print only the regenerated `[Unreleased]` section of each file,
    // attributing multi-file output with a `--- <path> ---` header.
    let multi = outputs.len() > 1;
    let mut stdout = std::io::stdout();
    for out in &outputs {
        let section = extract_unreleased_section(&out.rendered_text);
        if multi {
            writeln!(stdout, "--- {} ---", out.rel_path)
                .context("changelog: write preview separator")?;
        }
        writeln!(stdout, "{}", section).context("changelog: write preview section")?;
        if multi {
            writeln!(stdout).context("changelog: write preview spacer")?;
        }
    }
    Ok(())
}

/// release-notes: the historical grouped-bullet GitHub-body markdown to stdout,
/// driven by the resolved range. Honors `--crate` and `--snapshot`.
#[allow(clippy::too_many_arguments)]
fn run_release_notes(
    workspace_root: &Path,
    mut config: Config,
    crate_filter: Option<String>,
    range: Option<&str>,
    snapshot: bool,
    verbose: bool,
    debug: bool,
    log: &StageLogger,
) -> Result<()> {
    let resolved = resolve_range(workspace_root, &config, range)?;
    let effective_filter = resolved.pinned_crate.clone().or(crate_filter);

    log.status("generating release notes");

    // Collapse a flat-aggregate to ONE whole-workspace body (mirroring kac/json):
    // without an explicit `--crate`, a flat `crates:` list sharing one tag track
    // and one root file is a single lockstep aggregate, so the stage renders one
    // whole-repo body instead of N path-filtered duplicates joined by `---`
    // separators. The DECISION lives in `select_crates`/`detect_repo_shape` (a
    // flat-aggregate collapses to ONE shared-root entry) consumed via
    // `resolve_single_track`, so the predicate can't drift; release-notes only
    // differs in how it APPLIES the result — the changelog stage iterates
    // `config.crates` (not a tuple list), so the aggregate is realized by
    // retaining one path-cleared crate whose body then spans the workspace.
    if effective_filter.is_none() && config.crates.len() > 1 {
        let empty = anodizer_core::config::ChangelogConfig::default();
        let routing = ChangelogRouting::from_config(config.changelog.as_ref().unwrap_or(&empty));
        let workspace = load_workspace(workspace_root).ok();
        let selected = select_crates(workspace_root, &config, workspace.as_ref(), None);
        let single_track =
            resolve_single_track(&selected, routing.root_enabled, routing.per_crate, false);
        if single_track && let Some(mut first) = config.crates.first().cloned() {
            first.path = String::new();
            config.crates = vec![first];
        }
    }

    // Both bare-lockstep and `workspaces:`-multi-track configs leave
    // `config.crates` empty, so the changelog stage (which iterates
    // `config.crates`) would render nothing. kac/json avoid this because
    // `select_crates`/`detect_repo_shape` materialize the render set for these
    // shapes; mirror that here. Skipped when an explicit `--crate` filter
    // targets a member (handled by the overlay below) so a synthetic/flattened
    // entry never shadows the real per-crate context.
    if effective_filter.is_none() && config.crates.is_empty() {
        let workspace_crates: Vec<anodizer_core::config::CrateConfig> = config
            .workspaces
            .as_deref()
            .unwrap_or_default()
            .iter()
            .flat_map(|w| w.crates.iter().cloned())
            .collect();
        if workspace_crates.is_empty() {
            // No `workspaces:` either: bare-lockstep / config-less single crate
            // (version from `[workspace.package]`). Synthesize ONE project-name
            // aggregate at the workspace root, matching `select_crates`'s
            // lockstep/single arm.
            let global_prefix = global_tag_prefix(&config);
            config.crates = vec![anodizer_core::config::CrateConfig {
                name: config.project_name.clone(),
                path: String::new(),
                tag_template: format!("{}{{{{ Version }}}}", global_prefix),
                ..Default::default()
            }];
        } else {
            // `workspaces:`-multi-track: flatten every workspace's crates into
            // the render set so each track's release-notes body is generated and
            // joined by the multi-crate separator below — matching the kac/json
            // `detect_repo_shape::PerCrate` output for this shape.
            config.crates = workspace_crates;
        }
    }

    let selected_crates: Vec<String> = match effective_filter.as_ref() {
        Some(name) => vec![name.clone()],
        None => Vec::new(),
    };

    // Apply the workspace overlay when the filter resolves to a workspace crate
    // so monorepo configs (top-level `workspaces:` rather than `crates:`) hand
    // the changelog stage the right per-crate context.
    if let Some(ref target) = effective_filter
        && config.crates.is_empty()
    {
        let ws_for_target = config
            .workspaces
            .as_ref()
            .and_then(|ws_list| {
                ws_list
                    .iter()
                    .find(|ws| ws.crates.iter().any(|c| &c.name == target))
            })
            .cloned();
        if let Some(ws) = ws_for_target {
            log.verbose(&format!(
                "--crate {} lives in workspace '{}'; applying workspace overlay",
                target, ws.name
            ));
            helpers::apply_workspace_overlay(&mut config, &ws);
        }
    }

    // Map the resolved start onto the stage's two signals so release-notes
    // covers the SAME commits the engine-backed formats do for an identical
    // range arg:
    //   - `Ref(r)` → explicit lower bound (`changelog_from`).
    //   - `Pending` → no signal; the stage auto-discovers the last release tag.
    //     `resolve_prev_tag` keeps that tag in snapshot mode (where the current
    //     `Tag` resolves to the latest existing tag and would otherwise be
    //     dropped as "equal to current"), so the pending window stays
    //     "since last release" — matching kac/json's `find_last_tag`.
    //   - `FullHistory` → `changelog_full_history` short-circuits the stage's
    //     auto-discovery so the range spans all history.
    let explicit_from = match &resolved.start {
        RangeStart::Ref(r) => Some(r.clone()),
        RangeStart::Pending | RangeStart::FullHistory => None,
    };
    let ctx_opts = ContextOptions {
        verbose,
        debug,
        selected_crates,
        snapshot,
        // The range start, carried as a dedicated option so the changelog stage
        // overrides its auto-discovered previous tag only when the user supplied
        // an explicit lower bound (the always-auto-populated `PreviousTag`
        // template var cannot signal "user asked for this").
        changelog_from: explicit_from.clone(),
        changelog_full_history: matches!(resolved.start, RangeStart::FullHistory),
        // The explicit upper bound (`<from>..<to>` or a single tag's `to`),
        // threaded into the stage's git-log range so commits AFTER `<to>` are
        // excluded — mirroring how the json format passes `resolved.to` into
        // `render_changelog_json`. `None` (omitted / open `<from>..`) keeps the
        // upper bound at HEAD, preserving the pending window. Setting only the
        // `Tag` template var (below) is insufficient: it drives header/footer
        // text, not the commit-collection range.
        changelog_to: resolved.to.clone(),
        // Standalone-command marker: render the pending window from local git
        // with no release-time preconditions (no checkout, no clean tree, no
        // `changelog.snapshot: true`, no token for github-native). The
        // release/tag pipelines never construct options this way, so their
        // guards stay intact.
        changelog_preview: true,
        ..Default::default()
    };
    let mut ctx = Context::new(config.clone(), ctx_opts);
    helpers::resolve_scm_token_type(&mut ctx, &config);
    ctx.populate_time_vars();
    ctx.populate_runtime_vars();
    helpers::resolve_git_context(&mut ctx, &config, log)?;

    // Apply range overrides AFTER `resolve_git_context` has filled the default
    // `Tag` / `PreviousTag` so the user override wins. `to` becomes `Tag` (the
    // upper bound the stage reads directly); `from` sets `PreviousTag` so
    // header/footer templates see it (the range-start driving commit collection
    // flows via `ctx_opts.changelog_from`).
    if let Some(ref t) = resolved.to {
        ctx.template_vars_mut().set("Tag", t);
    }
    if let Some(ref f) = explicit_from {
        ctx.template_vars_mut().set("PreviousTag", f);
    }

    let stage = anodizer_stage_changelog::ChangelogStage;
    stage.run(&mut ctx)?;

    // Stable iteration order (HashMap iteration is non-deterministic, which
    // makes stdout flicker across runs and breaks test pinning).
    let mut entries: Vec<(&String, &String)> = ctx.stage_outputs.changelogs.iter().collect();
    entries.sort_by(|a, b| a.0.cmp(b.0));

    let mut aggregated = String::new();
    for (name, body) in &entries {
        if entries.len() > 1 {
            // Multi-crate separator keeps each crate's body attributable.
            aggregated.push_str(&format!("\n---\n{}\n---\n\n", name));
        }
        aggregated.push_str(body);
        if !body.ends_with('\n') {
            aggregated.push('\n');
        }
    }

    print!("{}", aggregated);

    if ctx.stage_outputs.changelogs.is_empty() {
        log.warn("no changelogs generated");
    }
    Ok(())
}

/// json: a stable JSON array of `{ crate, from, to, groups }` objects, one per
/// selected crate, sorted by crate name. Respects the resolved range.
fn run_json(
    workspace_root: &Path,
    config: &Config,
    crate_filter: Option<&str>,
    range: Option<&str>,
    log: &StageLogger,
) -> Result<()> {
    let resolved = resolve_range(workspace_root, config, range)?;
    let effective_filter = resolved.pinned_crate.as_deref().or(crate_filter);
    let workspace = load_workspace(workspace_root).ok();
    let selected = select_crates(workspace_root, config, workspace.as_ref(), effective_filter);
    // `select_crates` already collapses a flat aggregate to ONE shared-root
    // entry, so the JSON array holds a single whole-release entry rather than N
    // identical per-crate duplicates; only a distinct-prefix `PerCrate` yields N.
    if selected.is_empty() {
        log.warn("no crates selected for changelog json");
    }

    let mut elems: Vec<serde_json::Value> = Vec::new();
    for (name, dir, prefix) in &selected {
        let from_tag = resolve_start_bound(&resolved.start, workspace_root, prefix)?;
        let json = anodizer_stage_changelog::render_changelog_json(
            workspace_root,
            dir,
            from_tag.as_deref(),
            resolved.to.as_deref(),
        )
        .with_context(|| format!("render json changelog for {}", name))?;
        // `None` (no config / no commits) still contributes a stable entry so
        // the array shape is predictable; lift its payload onto a `crate` field.
        let payload: serde_json::Value = match json {
            Some(s) => serde_json::from_str(&s)
                .with_context(|| format!("parse json changelog for {}", name))?,
            None => serde_json::json!({
                "from": from_tag,
                "to": resolved.to.clone().unwrap_or_else(|| "HEAD".to_string()),
                "groups": [],
            }),
        };
        let mut obj = serde_json::Map::new();
        obj.insert("crate".to_string(), serde_json::Value::String(name.clone()));
        if let serde_json::Value::Object(map) = payload {
            for (k, v) in map {
                obj.insert(k, v);
            }
        }
        elems.push(serde_json::Value::Object(obj));
    }
    elems.sort_by(|a, b| {
        a.get("crate")
            .and_then(|v| v.as_str())
            .cmp(&b.get("crate").and_then(|v| v.as_str()))
    });

    let out = serde_json::to_string_pretty(&serde_json::Value::Array(elems))
        .context("serialize changelog json array")?;
    let mut stdout = std::io::stdout();
    writeln!(stdout, "{}", out).context("changelog: write json")?;
    Ok(())
}

#[cfg(test)]
mod tests {
    use super::*;
    use anodizer_core::config::CrateConfig;
    use serial_test::serial;

    fn default_opts(config: Option<&Path>) -> ChangelogOpts {
        ChangelogOpts {
            crate_name: None,
            range: None,
            format: ChangelogFormat::default(),
            write: false,
            snapshot: false,
            config_override: config.map(|p| p.to_path_buf()),
            verbose: false,
            debug: false,
            quiet: true,
        }
    }

    fn crate_cfg(name: &str, tag_template: &str) -> CrateConfig {
        CrateConfig {
            name: name.to_string(),
            tag_template: tag_template.to_string(),
            ..Default::default()
        }
    }

    fn cfg_with_crates(crates: Vec<CrateConfig>) -> Config {
        Config {
            crates,
            ..Default::default()
        }
    }

    #[test]
    fn default_format_is_keep_a_changelog() {
        assert_eq!(ChangelogFormat::default(), ChangelogFormat::KeepAChangelog);
    }

    #[test]
    #[serial]
    fn missing_config_returns_err() {
        let tmp = tempfile::tempdir().unwrap();
        let bogus = tmp.path().join("missing.yaml");
        let err = run(default_opts(Some(&bogus))).unwrap_err().to_string();
        assert!(err.contains("config file not found"), "{err}");
    }

    #[test]
    #[serial]
    fn write_with_release_notes_format_errors() {
        let tmp = tempfile::tempdir().unwrap();
        let bogus = tmp.path().join("missing.yaml");
        let mut opts = default_opts(Some(&bogus));
        opts.write = true;
        opts.format = ChangelogFormat::ReleaseNotes;
        let err = run(opts).unwrap_err().to_string();
        assert!(err.contains("--write is only valid"), "{err}");
    }

    #[test]
    #[serial]
    fn write_with_json_format_errors() {
        let tmp = tempfile::tempdir().unwrap();
        let bogus = tmp.path().join("missing.yaml");
        let mut opts = default_opts(Some(&bogus));
        opts.write = true;
        opts.format = ChangelogFormat::Json;
        let err = run(opts).unwrap_err().to_string();
        assert!(err.contains("--write is only valid"), "{err}");
    }

    /// The `--write` guard fires before config loading, so a missing config
    /// never masks the format error.
    #[test]
    #[serial]
    fn write_guard_precedes_config_load() {
        let tmp = tempfile::tempdir().unwrap();
        let bogus = tmp.path().join("missing.yaml");
        let mut opts = default_opts(Some(&bogus));
        opts.write = true;
        opts.format = ChangelogFormat::Json;
        // Even with a bogus config path, the format/write conflict wins.
        let err = run(opts).unwrap_err().to_string();
        assert!(err.contains("--write"), "{err}");
    }

    #[test]
    fn resolve_range_none_is_pending() {
        let cfg = Config::default();
        let tmp = tempfile::tempdir().unwrap();
        let r = resolve_range(tmp.path(), &cfg, None).unwrap();
        assert!(matches!(r.start, RangeStart::Pending));
        assert!(r.to.is_none());
        assert!(r.pinned_crate.is_none());
    }

    #[test]
    fn resolve_range_explicit_range_splits() {
        let cfg = Config::default();
        let tmp = tempfile::tempdir().unwrap();
        let r = resolve_range(tmp.path(), &cfg, Some("v0.1.0..v0.2.0")).unwrap();
        assert!(matches!(r.start, RangeStart::Ref(ref f) if f == "v0.1.0"));
        assert_eq!(r.to.as_deref(), Some("v0.2.0"));
        assert!(r.pinned_crate.is_none());
    }

    /// An explicit empty left side (`..<ref>`) means full history, distinct
    /// from an omitted arg (which is `Pending` / since-last-release).
    #[test]
    fn resolve_range_open_ended_left_is_full_history() {
        let cfg = Config::default();
        let tmp = tempfile::tempdir().unwrap();
        let r = resolve_range(tmp.path(), &cfg, Some("..v0.2.0")).unwrap();
        assert!(matches!(r.start, RangeStart::FullHistory));
        assert_eq!(r.to.as_deref(), Some("v0.2.0"));
    }

    /// Bare `..` (empty both sides) is full history to HEAD.
    #[test]
    fn resolve_range_bare_dotdot_is_full_history() {
        let cfg = Config::default();
        let tmp = tempfile::tempdir().unwrap();
        let r = resolve_range(tmp.path(), &cfg, Some("..")).unwrap();
        assert!(matches!(r.start, RangeStart::FullHistory));
        assert!(r.to.is_none());
    }

    #[test]
    fn resolve_tag_owner_picks_longest_prefix() {
        let cfg = cfg_with_crates(vec![
            crate_cfg("app", "v{{ .Version }}"),
            crate_cfg("core", "core-v{{ .Version }}"),
        ]);
        let (name, prefix) = resolve_tag_owner(&cfg, "core-v0.2.0").unwrap();
        assert_eq!(name, "core");
        assert_eq!(prefix, "core-v");
        let (name, prefix) = resolve_tag_owner(&cfg, "v1.0.0").unwrap();
        assert_eq!(name, "app");
        assert_eq!(prefix, "v");
    }

    #[test]
    fn resolve_tag_owner_no_match_errors() {
        let cfg = cfg_with_crates(vec![crate_cfg("core", "core-v{{ .Version }}")]);
        let err = resolve_tag_owner(&cfg, "other-v1.0.0")
            .unwrap_err()
            .to_string();
        assert!(err.contains("no crate"), "{err}");
    }

    #[test]
    fn select_crates_per_crate_filters() {
        let cfg = cfg_with_crates(vec![
            crate_cfg("app", "v{{ .Version }}"),
            crate_cfg("core", "core-v{{ .Version }}"),
        ]);
        let tmp = tempfile::tempdir().unwrap();
        let all = select_crates(tmp.path(), &cfg, None, None);
        assert_eq!(all.len(), 2);
        let filtered = select_crates(tmp.path(), &cfg, None, Some("core"));
        assert_eq!(filtered.len(), 1);
        assert_eq!(filtered[0].0, "core");
        assert_eq!(filtered[0].2, "core-v");
    }

    /// A `WorkspaceInfo` with no `[workspace.package].version`, so the prefix
    /// axis (not the Cargo signal) decides the shape regardless of cwd.
    fn ws_no_lockstep() -> WorkspaceInfo {
        WorkspaceInfo {
            workspace_package_version: None,
            members: vec![],
        }
    }

    /// A same-prefix flat `crates:` list (`FlatAggregate`) collapses through the
    /// REAL production path (`select_crates` → `detect_repo_shape`) to ONE
    /// workspace-root entry keyed by `project_name`, NOT N per-crate entries.
    #[test]
    #[serial]
    fn select_crates_flat_aggregate_collapses_to_one_root_entry() {
        let tmp = tempfile::tempdir().unwrap();
        let mut cfg = cfg_with_crates(vec![
            crate_cfg("core", "v{{ .Version }}"),
            crate_cfg("cli", "v{{ .Version }}"),
        ]);
        cfg.project_name = "proj".into();
        let selected = select_crates(tmp.path(), &cfg, Some(&ws_no_lockstep()), None);
        assert_eq!(
            selected.len(),
            1,
            "flat aggregate must collapse to one entry"
        );
        assert_eq!(selected[0].0, "proj");
        assert_eq!(selected[0].1, tmp.path());
        assert_eq!(selected[0].2, "v");
    }

    /// A single shared-root entry on shared-root-only routing renders flat.
    #[test]
    fn resolve_single_track_one_shared_root_entry_is_flat() {
        let tmp = tempfile::tempdir().unwrap();
        let selected = vec![("proj".into(), tmp.path().to_path_buf(), "v".into())];
        assert!(resolve_single_track(&selected, true, false, false));
    }

    /// Distinct-prefix multi-track (N entries) is NOT single-track.
    #[test]
    fn resolve_single_track_multi_entry_is_per_crate() {
        let tmp = tempfile::tempdir().unwrap();
        let selected = vec![
            (
                "core".into(),
                tmp.path().join("crates/core"),
                "core-v".into(),
            ),
            ("cli".into(), tmp.path().join("crates/cli"), "cli-v".into()),
        ];
        assert!(!resolve_single_track(&selected, true, false, false));
    }

    /// An explicit `--crate` filter never forces single_track: a genuine
    /// multi-track repo must refresh only that crate's subsection.
    #[test]
    fn resolve_single_track_respects_explicit_crate_filter() {
        let tmp = tempfile::tempdir().unwrap();
        let selected = vec![("core".into(), tmp.path().join("crates/core"), "v".into())];
        assert!(!resolve_single_track(&selected, true, false, true));
    }

    /// Per-crate files configured (`per_crate: true`) keep per-crate behaviour.
    #[test]
    fn resolve_single_track_per_crate_files_is_per_crate() {
        let tmp = tempfile::tempdir().unwrap();
        let selected = vec![("proj".into(), tmp.path().to_path_buf(), "v".into())];
        assert!(!resolve_single_track(&selected, true, true, false));
    }
}