oakum 0.12.1

A polyglot release tool that derives dependent version bumps from the dependency graph
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
//! What `migrate` says — the printed steps and the text of the refusal a failed
//! look owes stderr. Rendering only: every decision and every look at the tree
//! stays in `migrate`, which chooses whether to raise what this module worded.

use oakum::detect::ReleaseTool;
use oakum::plan::{format_versions, PlanComparison, Versioning};
use semver::Version;

use super::ci::VERSION_BRANCH;
use super::install_pin::Owed;
use super::migrate::{BumpRewrite, VersioningChoice};
use super::migrate_config::{chosen_commit_message, SourceConfig};
use super::migrate_gates::{GateLook, HookLook, IndexLook};
use super::owned_files::{
    commit_message_line, ConfigSettings, OwnedPlan, ReadmeState, SchemaState, README_REL,
};
use super::quoted;
use super::say_out;
use super::tag_shape::{ReadableTemplate, TagShape};
use super::workflow::{workflow_text, WorkflowPins};
use super::CliError;

/// The pending line for the owned files, from the same probe the writes use.
pub(super) fn pending_owned_line(owned: OwnedPlan) -> String {
    let schema = match owned.schema {
        SchemaState::Absent => "write .changeset/_schema.json",
        SchemaState::Stale => "replace the existing .changeset/_schema.json",
        SchemaState::Current => "leave the current .changeset/_schema.json",
    };
    match owned.readme {
        ReadmeState::Absent => {
            format!("write .changeset/_config.toml and .changeset/README.md, and {schema}")
        }
        ReadmeState::Stale => format!(
            "write .changeset/_config.toml, replace the earlier oakum .changeset/README.md, and {schema}"
        ),
        ReadmeState::Ours | ReadmeState::Theirs => format!(
            "write .changeset/_config.toml and {schema} (keeping the existing .changeset/README.md)"
        ),
    }
}

/// What the existing tags settled, once the writes are done. Silent when the
/// repository has no tags and when the shape they settle is the default
/// `release` applies anyway — a line restating the default is noise.
pub(super) fn print_tag_shape(shape: &TagShape, written: Option<ReadableTemplate>) {
    if let Some(template) = written {
        say_out(&format!(
            "carried over: `tag-format = \"{}\"` (derived from the existing tags{})",
            template.as_str(),
            skipped_clause(shape)
        ));
        return;
    }
    // Only the look that failed is reported here. Tags oakum read but could not
    // explain are an action the reader owes, so they go in the remaining steps.
    if let TagShape::Unread(why) = shape {
        say_out(&format!(
            "not derived: `tag-format` (could not read the existing tags: {why})"
        ));
    }
}

/// Tags the derivation stepped over, named on the line that reports what it
/// derived. A shape read off a subset while the rest went unmentioned would
/// claim a look at tags nobody weighed — the same collapse as reporting an
/// empty search as silence.
fn skipped_clause(shape: &TagShape) -> String {
    let TagShape::Derived { skipped, .. } = shape else {
        return String::new();
    };
    if skipped.is_empty() {
        return String::new();
    }
    format!(
        "; {} state no version and were not weighed",
        quoted(skipped)
    )
}

/// The remaining step for tags oakum read and could not explain: nothing was
/// written, so the shape is the reader's to set before the first release.
fn undecided_tag_step(shape: &TagShape) -> Option<String> {
    let TagShape::Undecided { why, offerable } = shape else {
        return None;
    };
    // The reader is asked for a value, so the shapes this repository could
    // adopt travel with the ask; which of them is right depends on tags oakum
    // could not reconcile.
    Some(format!(
        "- set `tag-format` to match the existing tags ({why}); `release` refuses at the first tag rather than writing a shape the repository does not use\n  oakum reads {}",
        quoted(offerable.iter().map(|template| template.as_str()))
    ))
}

/// The `versioning` line, which is the one line in the written config a reader
/// cannot check by reading the config.
///
/// `semver` is the non-default ([ADR-0022](../../../../docs/decisions/0022-zero-major-versioning.md)),
/// it is what every source tool but knope implies, and below 1.0.0 it is the
/// difference between the next release being `0.18.0` and `1.0.0`. It was
/// written silently (`okm-404.9`).
pub(super) fn versioning_line(chosen: VersioningChoice) -> String {
    let versioning = chosen.versioning();
    let why = match (chosen, versioning) {
        (VersioningChoice::Requested(_), _) => {
            String::from("from `--versioning`, not the source tool")
        }
        (VersioningChoice::Inferred(from), Versioning::ZeroMajor) => {
            format!("{} holds a breaking change below 1.0.0", from.name())
        }
        (VersioningChoice::Inferred(from), Versioning::Semver) => format!(
            "{} takes 0.1.3 to 1.0.0, and renumbering an established release line is not a migration's job; oakum's own default is `zero-major`",
            from.name()
        ),
    };
    format!("  write `versioning = \"{versioning}\"` ({why})")
}

pub(super) fn print_pending(
    planned: &[BumpRewrite],
    sources: &[SourceConfig],
    settings: &ConfigSettings,
    owned: OwnedPlan,
    chosen: VersioningChoice,
) {
    let carried = settings.private_packages;
    say_out("pending:");
    for rewrite in planned {
        // `rewrite` claims a transformation in place, which a file pulled out
        // of the old tool's directory does not get (`okm-404.4`).
        match rewrite.leftover() {
            Some(source) => say_out(&format!("  write {} from {source}", rewrite.dest())),
            None => say_out(&format!("  rewrite {}", rewrite.dest())),
        }
    }
    say_out(&format!("  {}", pending_owned_line(owned)));
    for source in sources {
        let file = source.file;
        if let Some(private) = source.carried_private_packages() {
            say_out(&format!(
                "  carry {} from `{file}`",
                private
                    .axis_names()
                    .iter()
                    .map(|axis| format!("`privatePackages.{axis}`"))
                    .collect::<Vec<_>>()
                    .join(" and ")
            ));
        }
        for key in &source.dropped {
            say_out(&format!("  leave `{key}` behind in `{file}` (not carried)"));
        }
    }
    // The line the write produces, once. Naming a whole line per source would
    // quote something no file receives when two sources contribute different
    // axes and the write is their union.
    if carried.any() {
        say_out(&format!("  write `{}`", carried.toml_line()));
    }
    say_out(&versioning_line(chosen));
    // Resolved once, and shown in the form the file receives: the write is
    // first-wins across source files, so announcing each `Carried` value told a
    // reader two messages were written when one was.
    if let Some((file, message)) = chosen_commit_message(sources) {
        say_out(&format!(
            "  carry `versionCommitMessage` from `{file}` as `{}`",
            commit_message_line(message)
        ));
    }
    // Derived from the repository rather than from a source config, in the
    // voice of the carried `privatePackages` line above.
    if let Some(template) = settings.tag_format {
        say_out(&format!(
            "  carry the existing tag shape as `tag-format = \"{}\"`",
            template.as_str()
        ));
    }
}

pub(super) fn print_left_alone(
    readme: ReadmeState,
    sources: &[SourceConfig],
    unreadable: &[String],
) {
    if readme == ReadmeState::Theirs {
        say_out(&format!(
            "kept {README_REL} (oakum did not write it; left as is)"
        ));
    }
    // Repeated here, not only where the file was reached: this is the one case
    // where a carried setting may have been lost, and the summary a reader
    // scrolls back to is where the record has to be.
    for line in unreadable {
        say_out(line);
    }
    if let Some((file, _)) = chosen_commit_message(sources) {
        say_out(&format!(
            "carried over: `versionCommitMessage` from `{file}` as `commit-message`"
        ));
    }
    for source in sources {
        let file = source.file;
        if let Some(private) = source.carried_private_packages() {
            say_out(&format!(
                "carried over: {} from `{file}`",
                private
                    .axis_names()
                    .iter()
                    .map(|axis| format!("`privatePackages.{axis}`"))
                    .collect::<Vec<_>>()
                    .join(" and ")
            ));
        }
        for key in &source.dropped {
            // Deliberately silent about whether oakum has a counterpart. It has
            // one for some of these, and claiming otherwise forecloses a
            // question the reader should still ask. The keys oakum does map are
            // reported by name elsewhere rather than through this line.
            say_out(&format!(
                "not carried over: `{key}` (`{file}` is untouched)"
            ));
        }
    }
}

/// Everything `migrate` saw and will not act on.
///
/// One value rather than nine arguments, because the list only grows: each is
/// something the command knows and the reader has to be told, and adding the
/// next one should not be a decision about argument order.
pub(super) struct Remaining<'a> {
    pub(super) detections: &'a [oakum::detect::Detection],
    pub(super) knope: bool,
    pub(super) foreign_changelogs: &'a [String],
    /// A pin the install-pin gate let through that the reader still owes.
    pub(super) owed_pin: Option<&'a Owed>,
    pub(super) pins: &'a WorkflowPins,
    pub(super) binary: &'a Version,
    pub(super) shape: &'a TagShape,
    /// Source bump files copied into `.changeset/`, originals still on disk.
    pub(super) leftovers: &'a [&'a str],
    pub(super) gates: &'a GateLook,
    /// Remaining steps the source configs left the reader, in print order.
    /// Not only lossy mappings: a setting oakum reproduces exactly is reported
    /// here too, so the reader is not told it was lost.
    pub(super) owed: &'a [String],
}

pub(super) fn print_remaining_steps(remaining: &Remaining<'_>) {
    let Remaining {
        detections,
        knope,
        foreign_changelogs,
        owed_pin,
        pins,
        binary,
        shape,
        leftovers,
        gates,
        owed,
    } = *remaining;
    say_out("remaining (oakum does not perform these):");
    // First: every writer refuses until the pin is settled.
    for step in pins.owed_steps(owed_pin, binary, &workflow_text(binary, pins)) {
        say_out(&format!("- {step}"));
    }
    for report in foreign_changelogs {
        say_out(&format!("- {report}"));
    }
    if let Some(step) = undecided_tag_step(shape) {
        say_out(&step);
    }
    say_out("- add oakum to a workflow (YAML printed below)");
    say_out(
        "- publish: `oakum release` only tags and creates the GitHub release; the old workflow's publish step (`npm publish`, `cargo publish`) needs a job of its own on the tag push (`on: push: tags`)"
    );
    say_out(&format!(
        "- the version PR opens on branch `{VERSION_BRANCH}`; add it to any branch-name filters that need it"
    ));
    for hit in detections {
        if let Some(path) = remaining_removal(hit.evidence()) {
            say_out(&format!("- remove {path} ({})", hit.tool().name()));
        }
    }
    if let Some(step) = leftover_bump_files_step(leftovers) {
        say_out(&step);
    }
    for step in bump_file_gate_steps(gates) {
        say_out(&step);
    }
    if let Some(step) =
        kept_bump_directory_step(detections.iter().map(oakum::detect::Detection::tool))
    {
        say_out(&step);
    }
    for step in owed {
        say_out(step);
    }
    say_out("- remove the old tool's dependency and its workflow");
    if knope {
        say_out(
            "- `.changeset/README.md` aborts knope until `knope.toml` and its workflow are removed",
        );
    }
    print_adoptable();
}

/// What the repository could now retire, as opposed to what it still owes. A
/// cutover's strongest argument was reachable only by noticing the phrase
/// "declared extra-files" in `oakum version --help` and then reading
/// `_schema.json`; a migration that can delete a script, a CI job and a test
/// suite should say so rather than wait to be discovered.
fn print_adoptable() {
    say_out("also available (oakum does these; the old tool may not have):");
    say_out(
        "- `extra-files`: declare a JSON file that carries a version — a plugin manifest, a \
         marketplace entry — and `oakum version` writes it in the same pass as the manifest, \
         under the same rollback. A sync script, its drift job and its tests can go. v1 writes \
         JSON only (ADR-0033)",
    );
    say_out(
        "- the changelog oakum writes is generated markdown that also reads as prose, so a \
         repository linting it needs no per-release fixup step — once its linter turns MD041 \
         off for `.changeset/*.md` and sets MD024 `siblings_only` (ADR-0031)",
    );
}

/// The bump files `migrate` copied rather than moved. `migrate` does not own the
/// old tool's directory ([ADR-0003]), so the originals stay — and the old tool
/// goes on counting them.
///
/// Measured in a clone (`okm-404.4`): after `migrate` and `version` consumed the
/// `.changeset/` copies and released `review-cycle` 0.17.0 to 0.18.0, `bumpy
/// status` still showed 3 pending and would take it to 0.19.0 a second time. A
/// workflow still wired to the old tool on every push to `main` makes that a
/// duplicate release on the merge commit, not a hypothetical.
///
/// [ADR-0003]: ../../../../docs/decisions/0003-write-only-what-a-command-owns.md
fn leftover_bump_files_step(leftovers: &[&str]) -> Option<String> {
    if leftovers.is_empty() {
        return None;
    }
    Some(format!(
        "- remove the bump files oakum copied out and left behind ({}); the old tool still counts them, so a workflow still wired to it releases the same packages a second time",
        quoted(leftovers)
    ))
}

/// What the gate search does not reach, on every line that reports its result.
/// The arm asserting a negative needs this most, and used to carry the least of
/// it: a reader told "nothing names it" acts on the sentence, not on the search
/// behind it.
/// Names the hooks as searched only when their look ran.
fn unsearched(hooks: &HookLook) -> String {
    let (searched, untracked) = match hooks {
        HookLook::Read { .. } => (
            " and the directories git runs hooks from",
            "untracked elsewhere",
        ),
        HookLook::Failed(_) => ("", "untracked"),
    };
    format!(
        "oakum searched git's index outside `.changeset/`{searched}, so a gate that is {untracked}, an unstaged edit, inside a submodule, or a hook set in git config (`hook.<name>.command`) is not covered — check those before the first release"
    )
}

/// A gate this repository points at the old bump-file directory.
///
/// From the claude-plugins field record (`okm-404.24`): adopting oakum broke
/// that repository's own commit gate, and fixing it there took a pathspec
/// widening, a narrowing against oakum's skip list, a `:(glob)`, and six
/// regression tests. None of that is oakum's work — but the gate's existence is
/// the fifth thing `migrate` could see and did not say, beside
/// `private-packages`, `extra-files`, `commit-message` and `tag-format`.
///
/// A failed look says so. A look that found nothing says what it looked at,
/// so silence never claims a search of what the look cannot reach
/// (`okm-404.35`).
fn bump_file_gate_steps(gates: &GateLook) -> Vec<String> {
    let mut steps: Vec<String> = gates
        .failure()
        .map(|why| {
            format!(
                "- unverified: oakum {}; a commit or CI gate pointed at it will reject oakum's bump files",
                gate_look_failed(&why)
            )
        })
        .into_iter()
        .collect();
    if let GateLook::Looked { index, hooks } = gates {
        steps.extend(index_step(index, hooks));
        steps.extend(hooks_step(hooks));
    }
    steps
}

/// changesets and knope keep `.changeset/`, so no path look names a gate on
/// it, but oakum writes its own bump files there; oakum cannot tell a check of
/// their content from someone's script (`okm-404.41`).
fn kept_bump_directory_step(tools: impl IntoIterator<Item = ReleaseTool>) -> Option<String> {
    tools
        .into_iter()
        .any(|tool| matches!(tool, ReleaseTool::Changesets | ReleaseTool::Knope))
        .then(|| {
            String::from(
                "- check any commit or CI gate that reads `.changeset/*.md`: oakum writes its own bump files there, and a gate written for the old tool's files may reject them; oakum did not look for one",
            )
        })
}

fn index_step(index: &IndexLook, hooks: &HookLook) -> Option<String> {
    let unsearched = unsearched(hooks);
    match index {
        IndexLook::Failed(_) => None,
        IndexLook::NothingTracked => Some(format!(
            "- git reports no commit and its index lists no file, so no tracked file could have gated anything. {unsearched}"
        )),
        IndexLook::Found { named, unmerged } if named.is_empty() => {
            // The unmerged files went unread, so "no file" would claim them too.
            let other = if unmerged.is_empty() { "" } else { " other" };
            Some(format!(
                "- no{other} file in the index outside `.changeset/` names the old bump-file directory. {unsearched}"
            ))
        }
        IndexLook::Found { named, .. } => Some(format!(
            "- check what names the old bump-file directory ({}); oakum cannot tell a commit or CI gate from a mention in prose, and a gate matching those paths rejects the bump files oakum writes. {unsearched}",
            quoted(named)
        )),
    }
}

fn hooks_step(hooks: &HookLook) -> Option<String> {
    match hooks {
        HookLook::Failed(_) => None,
        HookLook::Read {
            dirs,
            named,
            unread,
        } if named.is_empty() => {
            let other = if unread.is_empty() { "" } else { " other" };
            let dirs = dirs
                .iter()
                .map(|dir| format!("`{dir}`"))
                .collect::<Vec<_>>()
                .join(" or ");
            Some(format!(
                "- no{other} hook in {dirs} names the old bump-file directory"
            ))
        }
        HookLook::Read { named, .. } => Some(format!(
            "- check the hooks git runs that name the old bump-file directory ({}); a hook matching those paths rejects the bump files oakum writes",
            quoted(named)
        )),
    }
}

/// The fact a failed gate look establishes, in the words both readers get. The
/// printed step and the refusal below were two separately-authored sentences
/// about one outcome, each free to drift from the other.
pub(super) fn gate_look_failed(why: &str) -> String {
    format!(
        "could not look for files gating on the old bump-file directory ({})",
        one_line(why)
    )
}

/// The clause every post-write verdict opens with, said once however many
/// causes join it.
const KEPT: &str = "migrated files were kept; ";

/// One verdict from every cause a run ends with. The first decides the
/// class: a finding outranks a look that did not happen, and two unverified
/// causes are the same class. Each cause's own outcome token is dropped;
/// `main` says it once.
pub(super) fn verdict(causes: impl IntoIterator<Item = CliError>) -> Result<(), CliError> {
    let Some(joined) = causes.into_iter().reduce(|first, second| {
        first.recast(format!("{}; and {}", first.detail(), second.detail()))
    }) else {
        return Ok(());
    };
    Err(joined.recast(format!("{KEPT}{}", joined.detail())))
}

/// What a failed gate look owes stderr. Built here beside the step rather than
/// in `migrate`, which decides only *whether* to raise it — so there is no
/// sentence for a caller to hand-write, and the two cannot drift into
/// describing different failures. Git's own diagnostic starts with `error:`,
/// which is why the detail is flattened rather than interpolated raw.
pub(super) fn gate_look_refusal(why: &str) -> CliError {
    CliError::unverified(format!("oakum {}", gate_look_failed(why)))
}

/// One bullet from a diagnostic that may span lines, so a reader parsing the
/// list by its leading dash does not meet a stray one. Lines repeated verbatim
/// collapse; lines that differ are kept, since each may name a different path.
fn one_line(detail: &str) -> String {
    let mut seen: Vec<&str> = Vec::new();
    for line in detail
        .lines()
        .map(str::trim)
        .filter(|line| !line.is_empty())
    {
        if !seen.contains(&line) {
            seen.push(line);
        }
    }
    seen.join("; ")
}

/// `.changeset/` is oakum's directory after migrate. Only the old changesets
/// config file is still foreign.
fn remaining_removal(evidence: &str) -> Option<&str> {
    if evidence == ".changeset/" {
        return None;
    }
    if evidence.starts_with(".changeset/") && evidence != ".changeset/config.json" {
        return None;
    }
    Some(evidence)
}

/// One of four verdict lines plus the per-package differences; the
/// verdict itself is `migrate`'s.
pub(super) fn print_plan_comparison(
    comparison: &PlanComparison,
    before_label: &str,
    planned_by: &str,
    match_suffix: &str,
    planned: usize,
) {
    if let Some(diffs) = comparison.expected_knope_feature() {
        say_out(
            "plan comparison: knope maps a pending feature on a pre-1.0 package to patch; oakum maps it to minor"
        );
        for diff in diffs {
            say_out(&format!(
                "  {}: {} ({before_label}) vs {} (oakum)",
                diff.id(),
                format_versions(diff.before()),
                format_versions(diff.after()),
            ));
        }
        return;
    }
    if let Some(parts) = comparison.unexpected() {
        say_out("plan comparison: unexpected difference");
        for diff in parts.expected.iter().chain(parts.unexpected.iter()) {
            say_out(&format!(
                "  {}: {} vs {}",
                diff.id(),
                format_versions(diff.before()),
                format_versions(diff.after()),
            ));
        }
        return;
    }
    // Reached only for `Equal`, so an empty plan here means both sides were
    // empty. A repository is usually migrated right after a release, which makes
    // this the common case rather than the edge one — and a comparison of two
    // empty plans proves nothing about the transform (`okm-404.6`).
    if planned == 0 {
        say_out(&format!(
            "plan comparison: nothing pending under {before_label} or oakum; the transform was not exercised{match_suffix}"
        ));
        return;
    }
    say_out(&format!(
        "plan comparison: {planned} package(s) {planned_by} and by oakum; match{match_suffix}"
    ));
}

#[cfg(test)]
mod gate_steps {
    use super::super::migrate_gates::{GateLook, HookLook, IndexLook};
    use super::{
        bump_file_gate_steps, gate_look_refusal, hooks_step, kept_bump_directory_step, one_line,
        verdict,
    };
    use oakum::detect::ReleaseTool;

    /// The index line beside a hooks look that ran.
    fn index_step(index: &IndexLook) -> Option<String> {
        super::index_step(index, &hooks(&[], &[]))
    }

    fn found(named: &[&str], unmerged: &[&str]) -> IndexLook {
        IndexLook::Found {
            named: named.iter().map(ToString::to_string).collect(),
            unmerged: unmerged.iter().map(ToString::to_string).collect(),
        }
    }

    fn hooks(named: &[&str], unread: &[&str]) -> HookLook {
        HookLook::Read {
            dirs: vec![String::from(".git/hooks")],
            named: named.iter().map(ToString::to_string).collect(),
            unread: unread.iter().map(ToString::to_string).collect(),
        }
    }

    fn looked(index: IndexLook) -> GateLook {
        GateLook::Looked {
            index,
            hooks: hooks(&[], &[]),
        }
    }

    fn bump_file_gate_step(gates: &GateLook) -> Option<String> {
        let mut steps = bump_file_gate_steps(gates);
        assert!(steps.len() <= 1, "{steps:?}");
        steps.pop()
    }

    /// Only a source that kept `.changeset/` is told to check gates on it,
    /// beside bumpy too, since its files there are rewritten as well.
    #[test]
    fn only_a_kept_bump_directory_is_noted() {
        for tools in [
            vec![ReleaseTool::Changesets],
            vec![ReleaseTool::Knope],
            vec![ReleaseTool::Bumpy, ReleaseTool::Changesets],
        ] {
            let kept = kept_bump_directory_step(tools.clone()).expect("a kept directory speaks");
            assert!(
                kept.contains("`.changeset/*.md`") && kept.contains("did not look"),
                "{tools:?}: {kept}"
            );
        }
        for tools in [
            vec![ReleaseTool::Bumpy],
            vec![ReleaseTool::ReleasePlease],
            vec![ReleaseTool::SemanticRelease],
            vec![],
        ] {
            assert_eq!(kept_bump_directory_step(tools.clone()), None, "{tools:?}");
        }
    }

    /// The outcomes must not render alike. An empty look is not silence: the
    /// line says what was searched, and what was not.
    #[test]
    fn every_outcome_has_its_own_line() {
        assert_eq!(bump_file_gate_step(&GateLook::NothingToRepoint), None);

        let empty = index_step(&found(&[], &[])).expect("empty look speaks");
        assert!(empty.contains("no file in the index"), "{empty}");
        // The arm asserting a negative carries the whole caveat, not half of it.
        for unsearched in ["untracked", "unstaged edit", "submodule", "git config"] {
            assert!(empty.contains(unsearched), "{unsearched}: {empty}");
        }
        assert!(
            empty.contains("the directories git runs hooks from") && !empty.contains(".git/hooks/"),
            "the hooks are searched, so the caveat no longer disclaims them: {empty}"
        );

        let nothing = index_step(&IndexLook::NothingTracked).expect("an empty index speaks");
        assert!(nothing.contains("git reports no commit"), "{nothing}");
        assert!(
            nothing.contains("submodule"),
            "every arm carries the caveat: {nothing}"
        );
        assert_ne!(
            nothing, empty,
            "searched nothing is not searched and found none"
        );

        // One file is the common case, and `name it` read wrong there.
        let one = index_step(&found(&["hook.sh"], &[])).expect("a hit speaks");
        assert!(
            one.contains("check what names the old bump-file directory (`hook.sh`)"),
            "{one}"
        );
        assert!(
            one.contains("cannot tell a commit or CI gate from a mention in prose"),
            "a match is a mention, not a proven gate: {one}"
        );
        assert_ne!(one, empty);

        let two = index_step(&found(&["hook.sh", "gate.yml"], &[])).expect("two hits speak");
        assert!(two.contains("(`hook.sh`, `gate.yml`)"), "{two}");

        let failed =
            bump_file_gate_step(&GateLook::Failed(String::from("boom"))).expect("a failure speaks");
        assert!(failed.starts_with("- unverified:"), "{failed}");
        assert_eq!(index_step(&IndexLook::Failed(String::from("boom"))), None);

        let no_hook = hooks_step(&hooks(&[], &[])).expect("an empty hook look speaks");
        assert_eq!(
            no_hook,
            "- no hook in `.git/hooks` names the old bump-file directory"
        );
        let both = HookLook::Read {
            dirs: vec![String::from("rel"), String::from(".git/rel")],
            named: Vec::new(),
            unread: Vec::new(),
        };
        assert_eq!(
            hooks_step(&both).expect("an empty hook look speaks"),
            "- no hook in `rel` or `.git/rel` names the old bump-file directory"
        );
        let hook = hooks_step(&hooks(&[".git/hooks/pre-commit"], &[])).expect("a hit speaks");
        assert!(
            hook.contains("check the hooks git runs that name the old bump-file directory (`.git/hooks/pre-commit`)"),
            "{hook}"
        );
        assert_eq!(hooks_step(&HookLook::Failed(String::from("boom"))), None);
    }

    /// An unmerged file was never read, so the look is unverified and names
    /// it, and the negative line stops covering it.
    #[test]
    fn an_unmerged_file_is_named_as_unsearched() {
        let steps = bump_file_gate_steps(&looked(found(&[], &["gate.sh"])));
        assert_eq!(steps.len(), 3, "{steps:?}");
        assert!(steps[0].starts_with("- unverified:"), "{steps:?}");
        assert!(
            steps[0].contains("unmerged") && steps[0].contains("`gate.sh`"),
            "{steps:?}"
        );
        assert!(
            steps[1].starts_with("- no other file in the index"),
            "{steps:?}"
        );

        let steps = bump_file_gate_steps(&looked(found(&["hook.sh"], &["gate.sh"])));
        assert!(steps[0].starts_with("- unverified:"), "{steps:?}");
        assert!(steps[1].contains("(`hook.sh`)"), "{steps:?}");
    }

    /// A hook oakum could not read is unverified, and the negative line stops
    /// covering it; a found hook is still named beside it.
    #[test]
    fn an_unread_hook_is_unverified() {
        let steps = bump_file_gate_steps(&GateLook::Looked {
            index: found(&[], &[]),
            hooks: hooks(&[], &["`.git/hooks/pre-push` (Permission denied)"]),
        });
        assert!(steps[0].starts_with("- unverified:"), "{steps:?}");
        assert!(steps[0].contains("`.git/hooks/pre-push`"), "{steps:?}");
        assert_eq!(
            steps.last().map(String::as_str),
            Some("- no other hook in `.git/hooks` names the old bump-file directory")
        );

        // The caveat names what was searched, and a failed hooks look searched none.
        let steps = bump_file_gate_steps(&GateLook::Looked {
            index: found(&[], &[]),
            hooks: HookLook::Failed(String::from("hooks gone")),
        });
        assert!(steps[0].starts_with("- unverified:"), "{steps:?}");
        assert!(steps[1].starts_with("- no file in the index"), "{steps:?}");
        assert!(!steps[1].contains("hooks from"), "{steps:?}");
        assert!(steps[1].contains("submodule"), "{steps:?}");

        let both = GateLook::Looked {
            index: IndexLook::Failed(String::from("index gone")),
            hooks: HookLook::Failed(String::from("hooks gone")),
        };
        assert_eq!(
            both.failure().as_deref(),
            Some("index gone; hooks gone"),
            "both causes, in one fact"
        );
    }

    /// Verbatim from a `git grep` over an unreadable tracked file: two lines,
    /// identical, inside what has to stay one bullet.
    #[test]
    fn a_multi_line_git_diagnostic_becomes_one_bullet() {
        let detail = "exit 1: error: failed to stat 'gate.sh': Permission denied\nerror: failed to stat 'gate.sh': Permission denied";
        assert_eq!(
            one_line(detail),
            "exit 1: error: failed to stat 'gate.sh': Permission denied; error: failed to stat 'gate.sh': Permission denied"
        );
        let step = bump_file_gate_step(&GateLook::Failed(String::from(detail))).expect("a line");
        assert_eq!(step.lines().count(), 1, "{step}");
    }

    /// The step and the refusal were separately-authored sentences about one
    /// outcome. They still read differently — one is a bullet, one sets the
    /// exit code — but the fact they state now comes from one place, so a
    /// reader cannot be told the look failed for two different reasons.
    #[test]
    fn the_step_and_the_refusal_state_one_fact() {
        let why = "exit 1: error: failed to stat 'gate.sh': Permission denied";
        let fact = "could not look for files gating on the old bump-file directory";
        let step = bump_file_gate_step(&GateLook::Failed(String::from(why))).expect("a step");
        let refusal = verdict([gate_look_refusal(why)]).unwrap_err().to_string();
        for said in [&step, &refusal] {
            assert!(said.contains(fact), "{said}");
            assert!(said.contains(one_line(why).as_str()), "{said}");
        }
        assert!(
            refusal.starts_with("migrated files were kept; oakum"),
            "{refusal}"
        );
        assert_eq!(refusal.matches("unverified").count(), 0, "{refusal}");
    }

    /// Which arm refuses is the type's to say. Asked at two call sites by hand,
    /// it held only until one of them was edited.
    #[test]
    fn only_a_failed_look_is_a_failure() {
        assert_eq!(
            GateLook::Failed(String::from("boom")).failure().as_deref(),
            Some("boom")
        );
        assert!(looked(found(&[], &["gate.sh"])).failure().is_some());
        for gates in [
            looked(found(&[], &[])),
            looked(found(&["hook.sh"], &[])),
            looked(IndexLook::NothingTracked),
            GateLook::Looked {
                index: found(&[], &[]),
                hooks: hooks(&[".git/hooks/pre-commit"], &[]),
            },
            GateLook::NothingToRepoint,
        ] {
            assert_eq!(gates.failure(), None, "{gates:?}");
        }
    }
}

#[cfg(test)]
mod versioning_wording {
    use oakum::detect::ReleaseTool;
    use oakum::plan::Versioning;

    use super::super::migrate::VersioningChoice;
    use super::versioning_line;

    /// Every arm, and the rendered mode spelled the way the config file spells
    /// it — a line quoting a value the config does not contain would send a
    /// reader looking for a key that is not there.
    #[test]
    fn each_provenance_names_the_mode_and_what_settled_it() {
        assert_eq!(
            versioning_line(VersioningChoice::Inferred(ReleaseTool::Bumpy)),
            "  write `versioning = \"semver\"` (bumpy takes 0.1.3 to 1.0.0, and renumbering an established release line is not a migration's job; oakum's own default is `zero-major`)"
        );
        assert_eq!(
            versioning_line(VersioningChoice::Inferred(ReleaseTool::Knope)),
            "  write `versioning = \"zero-major\"` (knope holds a breaking change below 1.0.0)"
        );
        assert_eq!(
            versioning_line(VersioningChoice::Requested(Versioning::ZeroMajor)),
            "  write `versioning = \"zero-major\"` (from `--versioning`, not the source tool)"
        );
    }
}

#[cfg(test)]
mod pending_wording {
    use super::super::owned_files::{OwnedPlan, ReadmeState, SchemaState};
    use super::pending_owned_line;

    fn plan(schema: SchemaState, readme: ReadmeState) -> OwnedPlan {
        OwnedPlan { schema, readme }
    }

    #[test]
    fn every_owned_file_state_has_its_sentence() {
        assert_eq!(
            pending_owned_line(plan(SchemaState::Absent, ReadmeState::Absent)),
            "write .changeset/_config.toml and .changeset/README.md, and write .changeset/_schema.json"
        );
        assert_eq!(
            pending_owned_line(plan(SchemaState::Stale, ReadmeState::Absent)),
            "write .changeset/_config.toml and .changeset/README.md, and replace the existing .changeset/_schema.json"
        );
        assert_eq!(
            pending_owned_line(plan(SchemaState::Current, ReadmeState::Absent)),
            "write .changeset/_config.toml and .changeset/README.md, and leave the current .changeset/_schema.json"
        );
        assert_eq!(
            pending_owned_line(plan(SchemaState::Absent, ReadmeState::Theirs)),
            "write .changeset/_config.toml and write .changeset/_schema.json (keeping the existing .changeset/README.md)"
        );
        assert_eq!(
            pending_owned_line(plan(SchemaState::Stale, ReadmeState::Ours)),
            "write .changeset/_config.toml and replace the existing .changeset/_schema.json (keeping the existing .changeset/README.md)"
        );
        assert_eq!(
            pending_owned_line(plan(SchemaState::Current, ReadmeState::Stale)),
            "write .changeset/_config.toml, replace the earlier oakum .changeset/README.md, and leave the current .changeset/_schema.json"
        );
        assert_eq!(
            pending_owned_line(plan(SchemaState::Current, ReadmeState::Ours)),
            "write .changeset/_config.toml and leave the current .changeset/_schema.json (keeping the existing .changeset/README.md)"
        );
    }
}