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
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
//! `oakum generate`: derive one bump file from branch commits (ADR-0029 / `okm-j1r`).

use std::collections::{BTreeMap, BTreeSet};

use clap::Args;

use oakum::changeset::PackageSpec;
use oakum::commits::{commit_type, message_intent, CommitIntent, MessageIntent};
use oakum::plan::{BumpLevel, Package, PackageId, Workspace};
use oakum::state::UnresolvedScope;

use super::add::{bump_file_body, knope_presence, write_bump_file_in};
use super::config::{load_config, require_config, unresolved_scope_line};
use super::deliver_block;
use super::dependency_updates::{self, CommitReach};
use super::git::{Git, Op};
use super::install_pin::{self, PinPolicy};
use super::repository;
use super::workspace::discover_validated;
use super::CliError;

#[derive(Debug, Args)]
pub(super) struct GenerateArgs {
    #[arg(long, value_name = "REF", help = super::FROM_MERGE_BASE)]
    from: Option<String>,

    /// Print the planned bump file without writing.
    #[arg(long)]
    dry_run: bool,

    /// Filename stem (slugified). Defaults to a generated name.
    #[arg(long, value_name = "SLUG")]
    name: Option<String>,
}

pub(super) fn run(args: &GenerateArgs) -> Result<(), Box<dyn std::error::Error>> {
    let repo = repository::discover()?;
    let config = load_config(&repo)?;
    require_config(&config)?;
    install_pin::gate(&repo, PinPolicy::Writer)?;
    if !config.generate_allowed() {
        return Err(Box::new(CliError::new(
            "`oakum generate` needs both `change-files` and `conventional-commits` enabled in `.changeset/_config.toml` (ADR-0029)",
        )));
    }

    let workspace = discover_validated(&repo, &config)?;
    let git = Git::at_repository(&repo)?;
    let from = resolve_from_ref(&git, args.from.as_deref())?;
    // A package the config does not version is never released, so a bump file
    // naming it is one every later step refuses.
    let found = commit_intents(
        &git,
        &workspace,
        &CommitRanges::from_base(&from, &workspace),
        |package| config.version_managed(package),
    )?;
    for commit in &found.unresolved {
        super::say_err(&unresolved_scope_line(commit));
    }
    for (hash, why) in &found.unread_paths {
        let short = hash.get(..7).unwrap_or(hash);
        super::say_err(&format!(
            "commit {short}'s paths could not be read, so it is attributed by its scope alone: {why}"
        ));
    }
    if found.intents.is_empty() {
        return nothing_attributed(&found);
    }
    let intents = found.intents;

    // A bump file names packages, so a Cargo crate and an npm package sharing
    // a name take one line at the higher of their levels.
    let mut levels: BTreeMap<String, BumpLevel> = BTreeMap::new();
    let mut notes: Vec<String> = Vec::new();
    let mut coverage_notes: Vec<String> = Vec::new();
    for (_, intent) in &intents {
        let names: BTreeSet<&str> = intent
            .packages()
            .iter()
            .map(|id| id.name.as_str())
            .collect();
        for name in names {
            let level = levels.entry(String::from(name)).or_insert(BumpLevel::None);
            *level = (*level).max(intent.level());
            let line = format!("- {name}: {}", intent.summary());
            if intent.level().is_release() {
                notes.push(line);
            } else {
                coverage_notes.push(line);
            }
        }
    }
    // The note reaches every package the file releases, so a commit that
    // releases nothing stays out of it unless nothing in the file releases.
    let note = if notes.is_empty() {
        coverage_notes
    } else {
        notes
    }
    .join("\n");

    // No dropped-note check on this arm, unlike `write_bump_file_in` below:
    // the note is composed from commits as `- <package>: <summary>` lines, so
    // it always carries body text and never renders as a bare heading.
    if args.dry_run {
        let knope = knope_presence(&repo)?;
        let entries: Vec<(String, BumpLevel)> = levels.into_iter().collect();
        let body =
            bump_file_body(&entries, &note, knope).map_err(|err| CliError::new(err.to_string()))?;
        deliver_block(&body)
            .map_err(|err| CliError::undelivered("bump file composed, but it", &err))?;
        return Ok(());
    }

    let specs: Vec<PackageSpec> = levels
        .into_iter()
        .map(|(name, level)| PackageSpec::new(name, level))
        .collect();
    write_bump_file_in(
        &repo,
        &workspace,
        &config,
        &specs,
        &note,
        args.name.as_deref(),
    )?;
    Ok(())
}

/// What a report says of each commit read, by hash.
pub(super) type CommitTypes = BTreeMap<String, CommitRead>;

#[derive(Clone, Debug, Default)]
pub(super) struct CommitRead {
    /// The conventional type, `None` when the message is not conventional.
    pub(super) kind: Option<String>,
    pub(super) subject: String,
}

pub(super) struct CommitIntents {
    /// Keyed by commit hash.
    pub(super) intents: Vec<(String, CommitIntent)>,
    /// Hashes of the merge commits among `intents`.
    pub(super) merges: BTreeSet<String>,
    /// Every commit read that asks for a release, by hash, whatever it was
    /// attributed to, with the managed packages its paths reach by changes
    /// that need intent, or why they could not be read.
    pub(super) releasing: Vec<(String, BumpLevel, Result<BTreeSet<PackageId>, CliError>)>,
    pub(super) types: CommitTypes,
    /// Named by a releasing commit, left out by `keep`.
    pub(super) left_out: BTreeSet<PackageId>,
    pub(super) unresolved: Vec<UnresolvedScope>,
    /// Commits that moved only dependencies, which release nothing whatever
    /// their message says (ADR-0040).
    pub(super) dependency_updates: BTreeSet<String>,
    /// Scoped commits attributed by scope alone, by hash, with why.
    pub(super) unread_paths: Vec<(String, String)>,
}

/// Where each package's commits start: after its base, or at the root of
/// `HEAD`'s history when the base is `None`. A map, so no package can read
/// from two bases.
pub(super) struct CommitRanges(BTreeMap<PackageId, Option<String>>);

impl CommitRanges {
    pub(super) const fn new(bases: BTreeMap<PackageId, Option<String>>) -> Self {
        Self(bases)
    }

    pub(super) const fn bases(&self) -> &BTreeMap<PackageId, Option<String>> {
        &self.0
    }

    pub(super) fn from_base(base: &str, workspace: &Workspace) -> Self {
        Self::new(
            workspace
                .packages()
                .map(|package| (package.id().clone(), Some(String::from(base))))
                .collect(),
        )
    }
}

/// An in-range commit with what its message asks for.
struct ReadCommit<'a> {
    commit: &'a GitCommit,
    reading: &'a Reading,
    in_range: BTreeSet<PackageId>,
    message: String,
    intent: MessageIntent,
}

/// The in-range commits' intents in order, up to the first message that
/// refuses, and that refusal.
fn read_messages<'a>(
    commits: &'a [(GitCommit, Reading)],
    cancelled: &BTreeMap<&str, BTreeSet<PackageId>>,
    workspace: &Workspace,
) -> (Vec<ReadCommit<'a>>, Option<CliError>) {
    let mut read = Vec::new();
    for (commit, reading) in commits {
        let in_range: BTreeSet<PackageId> = match cancelled.get(commit.hash.as_str()) {
            Some(both) => reading.packages.difference(both).cloned().collect(),
            None => reading.packages.clone(),
        };
        if in_range.is_empty() {
            continue;
        }
        let message = commit.message();
        match message_intent(&message, workspace) {
            Ok(intent) => read.push(ReadCommit {
                commit,
                reading,
                in_range,
                message,
                intent,
            }),
            Err(why) => return (read, Some(CliError::new(why))),
        }
    }
    (read, None)
}

/// Each commit in `ranges` that names a package `keep` admits, attributed only
/// to the packages whose range holds it.
pub(super) fn commit_intents(
    git: &Git,
    workspace: &Workspace,
    ranges: &CommitRanges,
    keep: impl Fn(&Package) -> bool,
) -> Result<CommitIntents, Box<dyn std::error::Error>> {
    let mut intents = Vec::new();
    let mut left_out_released = BTreeSet::new();
    let mut unresolved = Vec::new();
    let mut merges = BTreeSet::new();
    let mut releasing = Vec::new();
    let mut dependency_updates = BTreeSet::new();
    let mut unread_paths = Vec::new();
    let mut types = BTreeMap::new();
    let commits = commits_in(git, ranges)?;
    let cancelled = reverted_pairs(&commits, |revert, target| undoes(git, revert, target))?;
    let (read, refused) = read_messages(&commits, &cancelled, workspace);
    // Merges carry no paths of their own: `diff-tree -m` unions both parents
    // and would credit base-branch-only files when main is merged in.
    let wanted: Vec<&str> = read
        .iter()
        .filter(|read| !read.commit.merge)
        .map(|read| read.commit.hash.as_str())
        .collect();
    let mut paths = git.commit_paths(&wanted);
    for ReadCommit {
        commit,
        reading,
        in_range,
        message,
        intent,
    } in read
    {
        if commit.merge {
            merges.insert(commit.hash.clone());
        }
        types.insert(
            commit.hash.clone(),
            CommitRead {
                kind: commit_type(&message),
                subject: commit.subject.clone(),
            },
        );
        let files = paths.remove(&commit.hash).unwrap_or(Ok(Vec::new()));
        let (by_paths, unread) = read_paths(git, workspace, commit, files, &intent, &keep)?;
        if by_paths.intent.is_empty() && by_paths.touched {
            dependency_updates.insert(commit.hash.clone());
        }
        let (packages, level, summary, unresolved_scope) = attributed(intent, &by_paths);
        let names_nothing = packages.is_empty() && !by_paths.touched;
        let reached = oakum::plan::reach(workspace, &packages, &keep);
        let kept: BTreeSet<PackageId> = reached
            .managed
            .into_keys()
            .filter(|id| in_range.contains(id) && !by_paths.update_only.contains(id))
            .collect();
        let left_out: BTreeSet<PackageId> = reached
            .stranded
            .into_iter()
            .filter(|id| in_range.contains(id))
            .collect();
        // Only a commit that asks for a release drops intent; routine work
        // under an unknown scope or on an unversioned package is not that. A
        // scope naming nothing is reported only while every range holds the
        // commit, so history before a release does not resurface.
        if let Some(err) = &unread {
            unread_paths.push((commit.hash.clone(), err.detail()));
        }
        if level.is_release() {
            let by_intent = oakum::plan::reach(workspace, &by_paths.intent, &keep).managed;
            let touched = match unread {
                Some(err) => Err(err),
                None => Ok(by_intent.into_keys().collect()),
            };
            releasing.push((commit.hash.clone(), level, touched));
            match unresolved_scope {
                Some(scope) if names_nothing && reading.in_every_range => {
                    unresolved.push(UnresolvedScope {
                        commit: commit.hash.clone(),
                        scope,
                    });
                }
                _ => left_out_released.extend(left_out),
            }
        }
        if let Some(intent) = CommitIntent::new(kept, level, summary) {
            intents.push((commit.hash.clone(), intent));
        }
    }
    // Read after the commits before it, so an earlier commit's unreadable
    // paths are reported first.
    if let Some(refused) = refused {
        return Err(Box::new(refused));
    }
    Ok(CommitIntents {
        intents,
        merges,
        releasing,
        types,
        left_out: left_out_released,
        unresolved,
        dependency_updates,
        unread_paths,
    })
}

/// Why a range wrote no file. Every releasing commit having moved only
/// dependencies is no error: such commits need no intent (ADR-0040).
fn nothing_attributed(found: &CommitIntents) -> Result<(), Box<dyn std::error::Error>> {
    if !found.left_out.is_empty() {
        let names: BTreeSet<&str> = found.left_out.iter().map(|id| id.name.as_str()).collect();
        return Err(Box::new(CliError::new(format!(
            "the commits touched only packages the config does not version: {}; adjust `include`/`exclude` or set `private-packages.version = true`",
            names.into_iter().collect::<Vec<_>>().join(", ")
        ))));
    }
    let only_dependencies = !found.dependency_updates.is_empty()
        && found
            .releasing
            .iter()
            .all(|(hash, ..)| found.dependency_updates.contains(hash));
    if only_dependencies {
        super::say_out(&format!(
            "no bump file written: {} commit(s) moved only dependencies, which need no intent (ADR-0040)",
            found.dependency_updates.len()
        ));
        return Ok(());
    }
    Err(Box::new(CliError::new(
        "no package bumps detected from commits (need a conventional scope matching a workspace package, or changed files under a package directory)",
    )))
}

/// What `commit`'s own paths reach. A scoped commit whose paths or root files
/// cannot be read is attributed by its scope; the error beside that reach says
/// nothing can tell what else the paths touched.
fn read_paths(
    git: &Git,
    workspace: &Workspace,
    commit: &GitCommit,
    files: Result<Vec<String>, CliError>,
    intent: &MessageIntent,
    keep: impl Fn(&Package) -> bool,
) -> Result<(CommitReach, Option<CliError>), CliError> {
    if commit.merge {
        return Ok((CommitReach::default(), None));
    }
    let reach = files.and_then(|files| {
        dependency_updates::commit_reach(git, workspace, &commit.hash, &files, keep)
    });
    match (reach, intent) {
        (Ok(reach), _) => Ok((reach, None)),
        (Err(err), MessageIntent::Scoped { package, .. }) => Ok((
            CommitReach {
                intent: BTreeSet::from([package.clone()]),
                update_only: BTreeSet::new(),
                touched: true,
            },
            Some(err),
        )),
        (Err(err), MessageIntent::PathFallback { .. }) => Err(err),
    }
}

/// The packages a commit names, its level, summary and any unresolved scope:
/// its scope unless its paths reach nothing but dependency updates and
/// development-only edits, or reach the scope only by those, otherwise what
/// they reach by changes that need intent. The caller drops what they reach
/// only by dependency updates.
fn attributed(
    intent: MessageIntent,
    by_paths: &CommitReach,
) -> (BTreeSet<PackageId>, BumpLevel, String, Option<String>) {
    match intent {
        MessageIntent::Scoped {
            package,
            level,
            summary,
        } => {
            let only_updates = by_paths.intent.is_empty() && by_paths.touched;
            let packages = if only_updates {
                BTreeSet::new()
            } else if by_paths.update_only.contains(&package) {
                by_paths.intent.clone()
            } else {
                BTreeSet::from([package])
            };
            (packages, level, summary, None)
        }
        MessageIntent::PathFallback {
            level,
            summary,
            unresolved_scope,
        } => (by_paths.intent.clone(), level, summary, unresolved_scope),
    }
}

/// For each git revert (`Revert "…"`, or `Reapply "…"` for a revert of one)
/// whose target, named by its full hash as git writes it, is in the listing,
/// the packages whose own range holds both: for
/// those the pair changes nothing, so neither releases nor covers (ADR-0039).
/// Elsewhere, as for a target outside the listing, the revert undoes something
/// already released and is read like any other message. Newest first, so a
/// re-apply cancels the revert it undoes rather than leaving it to cancel the
/// original.
fn reverted_pairs(
    commits: &[(GitCommit, Reading)],
    undoes: impl Fn(&str, &str) -> Result<bool, CliError>,
) -> Result<BTreeMap<&str, BTreeSet<PackageId>>, CliError> {
    let mut cancelled: BTreeMap<&str, BTreeSet<PackageId>> = BTreeMap::new();
    for (commit, reading) in commits.iter().rev() {
        if cancelled.contains_key(commit.hash.as_str())
            || !(commit.subject.starts_with("Revert \"")
                || commit.subject.starts_with("Reapply \""))
        {
            continue;
        }
        let Some(target) = commit.body.lines().find_map(|line| {
            line.trim()
                .strip_prefix("This reverts commit ")
                .and_then(|rest| rest.strip_suffix('.'))
        }) else {
            continue;
        };
        let reverted = commits.iter().find(|(other, _)| {
            other.hash != commit.hash
                && other.hash == target
                && !cancelled.contains_key(other.hash.as_str())
        });
        let Some((reverted, its_reading)) = reverted else {
            continue;
        };
        let both: BTreeSet<PackageId> = reading
            .packages
            .intersection(&its_reading.packages)
            .cloned()
            .collect();
        if !both.is_empty() && undoes(&commit.hash, &reverted.hash)? {
            cancelled.insert(&reverted.hash, both.clone());
            cancelled.insert(&commit.hash, both);
        }
    }
    Ok(cancelled)
}

/// Whether `revert` undoes exactly what `target` did: its patch, reversed,
/// is the target's, line positions and blob ids aside. The message alone would
/// let a commit that undoes part of a fix cancel all of it. A binary file's
/// patch holds no content to compare, so a pair touching one is never
/// confirmed and each commit reads as it is.
fn undoes(git: &Git, revert: &str, target: &str) -> Result<bool, CliError> {
    let patch = |hash, reverse| -> Result<Option<Vec<String>>, CliError> {
        let text = git.text(Op::CommitPatch { hash, reverse })?;
        if text.lines().any(|line| line.starts_with("Binary files ")) {
            return Ok(None);
        }
        Ok(Some(
            text.lines()
                .filter(|line| !line.starts_with("index ") && !line.starts_with("@@"))
                .map(String::from)
                .collect(),
        ))
    };
    Ok(match (patch(revert, true)?, patch(target, false)?) {
        (Some(revert), Some(target)) => revert == target,
        _ => false,
    })
}

#[derive(Debug)]
struct GitCommit {
    hash: String,
    /// More than one parent: a merge, which carries no paths of its own.
    merge: bool,
    subject: String,
    body: String,
}

impl GitCommit {
    fn message(&self) -> String {
        if self.body.is_empty() {
            self.subject.clone()
        } else {
            format!("{}\n\n{}", self.subject, self.body)
        }
    }
}

pub(super) fn resolve_from_ref(
    git: &Git,
    explicit: Option<&str>,
) -> Result<String, Box<dyn std::error::Error>> {
    if let Some(from) = explicit {
        return Ok(String::from(from));
    }
    Ok(git.default_base(|| default_base(git))?)
}

fn default_base(git: &Git) -> Result<String, CliError> {
    for candidate in ["origin/main", "main", "master"] {
        if git.predicate(Op::RefExists {
            reference: candidate,
        })? {
            // No common ancestor is a real answer (exit 1, empty streams);
            // fall back to the tip. A failure to look is an error.
            return Ok(match merge_base(git, candidate)? {
                Some(base) => base,
                None => String::from(candidate),
            });
        }
    }
    Err(CliError::new(
        "could not find a default base ref; pass `--from <ref>`",
    ))
}

fn merge_base(git: &Git, tip: &str) -> Result<Option<String>, CliError> {
    git.optional_text(Op::MergeBase { tip })
}

/// Which packages read a commit, and whether every base's range holds it.
#[derive(Debug, Default)]
struct Reading {
    packages: BTreeSet<PackageId>,
    in_every_range: bool,
}

/// Every commit some range holds, oldest first. One base lists its own range.
/// Several list `HEAD`'s whole history for the order, since ranges from tags on
/// diverging lines do not nest and no single range orders their union.
fn commits_in(
    git: &Git,
    ranges: &CommitRanges,
) -> Result<Vec<(GitCommit, Reading)>, Box<dyn std::error::Error>> {
    let mut by_base: BTreeMap<Option<&str>, BTreeSet<PackageId>> = BTreeMap::new();
    for (id, base) in &ranges.0 {
        by_base
            .entry(base.as_deref())
            .or_default()
            .insert(id.clone());
    }
    if let [(base, packages)] = by_base.iter().collect::<Vec<_>>().as_slice() {
        return Ok(list_commits(git, **base)?
            .into_iter()
            .map(|commit| {
                let reading = Reading {
                    packages: (*packages).clone(),
                    in_every_range: true,
                };
                (commit, reading)
            })
            .collect());
    }
    let mut held: BTreeMap<String, (BTreeSet<PackageId>, usize)> = BTreeMap::new();
    for (base, packages) in &by_base {
        for commit in list_commits(git, *base)? {
            let entry = held.entry(commit.hash).or_default();
            entry.0.extend(packages.iter().cloned());
            entry.1 += 1;
        }
    }
    if held.is_empty() {
        return Ok(Vec::new());
    }
    Ok(list_commits(git, None)?
        .into_iter()
        .filter_map(|commit| {
            let (packages, count) = held.remove(&commit.hash)?;
            let reading = Reading {
                packages,
                in_every_range: count == by_base.len(),
            };
            Some((commit, reading))
        })
        .collect())
}

fn list_commits(
    git: &Git,
    from: Option<&str>,
) -> Result<Vec<GitCommit>, Box<dyn std::error::Error>> {
    let raw = git.commits(from)?;
    let mut commits = Vec::new();
    for chunk in raw.split('\0').collect::<Vec<_>>().chunks(4) {
        if chunk.len() < 4 {
            continue;
        }
        let hash = chunk[0].trim();
        if hash.is_empty() {
            continue;
        }
        commits.push(GitCommit {
            hash: String::from(hash),
            merge: chunk[1].split_whitespace().count() > 1,
            subject: String::from(chunk[2].trim()),
            body: String::from(chunk[3].trim()),
        });
    }
    Ok(commits)
}

#[cfg(test)]
mod tests {
    use std::collections::BTreeMap;

    use oakum::plan::{Ecosystem, Package, PackageId, ResolvesDependenciesAt, Workspace};
    use semver::Version;

    use super::{commit_intents, merge_base, resolve_from_ref, CommitRanges, Git};
    use crate::cli::git::Reply;

    fn workspace(names: &[&str]) -> Workspace {
        Workspace::new(names.iter().map(|name| {
            Package::new(
                PackageId::new(Ecosystem::Cargo, *name),
                Version::new(0, 1, 0),
                ResolvesDependenciesAt::Install,
                true,
                Vec::new(),
            )
            .with_manifest_dir(*name)
        }))
        .expect("workspace")
    }

    fn cargo(name: &str) -> PackageId {
        PackageId::new(Ecosystem::Cargo, name)
    }

    /// `git log` output for `(hash, subject)` pairs, oldest first.
    fn log(commits: &[(&str, &str)]) -> Reply {
        Reply::said(
            commits
                .iter()
                .flat_map(|(hash, subject)| [hash, "\0p\0", subject, "\0\0\n"])
                .collect::<String>(),
        )
    }

    fn ranges(bases: &[(&str, Option<&str>)]) -> CommitRanges {
        CommitRanges::new(
            bases
                .iter()
                .map(|(name, base)| (cargo(name), base.map(String::from)))
                .collect::<BTreeMap<_, _>>(),
        )
    }

    /// Tags on diverging lines: neither range holds the other, so each
    /// package's commits keep `HEAD`'s order only if the union is ordered by
    /// one listing.
    #[test]
    fn diverging_ranges_keep_history_order() {
        let git = Git::answering([
            (
                "log",
                log(&[
                    ("b1", "fix(alpha): b1"),
                    ("B", "fix(alpha): B"),
                    ("h1", "fix(beta): h1"),
                ]),
            ),
            (
                "log",
                log(&[
                    ("a1", "fix(beta): a1"),
                    ("A", "fix(beta): A"),
                    ("h1", "fix(beta): h1"),
                ]),
            ),
            (
                "log",
                log(&[
                    ("r", "chore: root"),
                    ("a1", "fix(beta): a1"),
                    ("b1", "fix(alpha): b1"),
                    ("A", "fix(beta): A"),
                    ("B", "fix(alpha): B"),
                    ("h1", "fix(beta): h1"),
                ]),
            ),
            (
                "diff-tree --stdin",
                Reply::said("\u{1}a1\0\u{1}b1\0\u{1}A\0\u{1}B\0\u{1}h1\0"),
            ),
        ]);
        let ws = workspace(&["alpha", "beta"]);
        let found = commit_intents(
            &git,
            &ws,
            &ranges(&[("alpha", Some("tagA")), ("beta", Some("tagB"))]),
            |_| true,
        )
        .expect("intents");
        let order: Vec<&str> = found
            .intents
            .iter()
            .map(|(hash, _)| hash.as_str())
            .collect();
        assert_eq!(order, ["a1", "b1", "A", "B", "h1"]);
    }

    /// A package reads only its own range: `b1` is before beta's base.
    #[test]
    fn a_commit_outside_a_package_range_is_not_its_intent() {
        let git = Git::answering([
            (
                "log",
                log(&[("b1", "fix(beta): b1"), ("h1", "fix(alpha): h1")]),
            ),
            ("log", log(&[("h1", "fix(alpha): h1")])),
            (
                "log",
                log(&[("b1", "fix(beta): b1"), ("h1", "fix(alpha): h1")]),
            ),
            ("diff-tree --stdin", Reply::said("\u{1}b1\0\u{1}h1\0")),
        ]);
        let ws = workspace(&["alpha", "beta"]);
        // Ranges list in base order, so `a-old` answers first.
        let found = commit_intents(
            &git,
            &ws,
            &ranges(&[("alpha", Some("a-old")), ("beta", Some("b-new"))]),
            |_| true,
        )
        .expect("intents");
        let named: Vec<(&str, Vec<&PackageId>)> = found
            .intents
            .iter()
            .map(|(hash, intent)| (hash.as_str(), intent.packages().iter().collect()))
            .collect();
        assert_eq!(named, [("h1", vec![&cargo("alpha")])]);
    }

    /// A scope naming nothing is reported only while every range holds the
    /// commit; one already behind a package's base has been released past.
    #[test]
    fn an_unresolved_scope_behind_a_base_is_not_reported() {
        let git = Git::answering([
            (
                "log",
                log(&[("x1", "fix(zzz): old"), ("x2", "fix(zzz): new")]),
            ),
            ("log", log(&[("x2", "fix(zzz): new")])),
            (
                "log",
                log(&[("x1", "fix(zzz): old"), ("x2", "fix(zzz): new")]),
            ),
            (
                "diff-tree --stdin",
                Reply::said("\u{1}x1\0\nREADME.md\0\u{1}x2\0\nREADME.md\0"),
            ),
        ]);
        let ws = workspace(&["alpha", "beta"]);
        let found = commit_intents(
            &git,
            &ws,
            &ranges(&[("alpha", Some("a-old")), ("beta", Some("b-new"))]),
            |_| true,
        )
        .expect("intents");
        let reported: Vec<&str> = found.unresolved.iter().map(|u| u.commit.as_str()).collect();
        assert_eq!(reported, ["x2"]);
    }

    /// The paths named a package, just not one this read covers, so the scope
    /// did reach a package.
    #[test]
    fn a_scope_whose_paths_name_an_unread_package_is_not_unresolved() {
        let git = Git::answering([
            ("log", log(&[("x1", "fix(typo): p")])),
            (
                "diff-tree --stdin",
                Reply::said("\u{1}x1\0\npending/src/lib.rs\0"),
            ),
        ]);
        let ws = workspace(&["alpha", "pending"]);
        let found = commit_intents(&git, &ws, &ranges(&[("alpha", Some("v1"))]), |_| true)
            .expect("intents");
        assert!(found.unresolved.is_empty(), "{:?}", found.unresolved);
        assert_eq!(found.intents.len(), 0);
    }

    #[test]
    fn an_earlier_unreadable_commit_is_reported_before_a_later_refused_scope() {
        let package = |ecosystem| {
            Package::new(
                PackageId::new(ecosystem, "dup"),
                Version::new(0, 1, 0),
                ResolvesDependenciesAt::Install,
                true,
                Vec::new(),
            )
            .with_manifest_dir(match ecosystem {
                Ecosystem::Cargo => "crates/dup",
                Ecosystem::Npm => "packages/dup",
            })
        };
        let ws = Workspace::new([package(Ecosystem::Cargo), package(Ecosystem::Npm)])
            .expect("workspace");
        let git = Git::answering([
            (
                "log",
                log(&[("x1", "chore: tidy"), ("x2", "fix(dup): both")]),
            ),
            (
                "diff-tree --stdin",
                Reply::said(b"\x01x1\0\nbad\xff\0".to_vec()),
            ),
            ("diff-tree", Reply::said(b"bad\xff\0".to_vec())),
        ]);
        let err = commit_intents(&git, &ws, &ranges(&[("dup", Some("v1"))]), |_| true)
            .err()
            .expect("refused");
        assert!(err.to_string().contains("not valid UTF-8"), "{err}");
    }

    /// Nothing to read means no git at all.
    #[test]
    fn no_ranges_list_nothing() {
        let git = Git::answering([]);
        let found =
            commit_intents(&git, &workspace(&["alpha"]), &ranges(&[]), |_| true).expect("intents");
        assert_eq!(found.intents.len(), 0);
        assert!(git.asked().is_empty(), "{:?}", git.asked());
    }

    #[test]
    fn resolve_from_ref_keeps_an_explicit_ref() {
        let git = Git::answering([]);
        let from = resolve_from_ref(&git, Some("v1.0.0")).expect("explicit");
        assert_eq!(from, "v1.0.0");
        assert!(git.asked().is_empty(), "{:?}", git.asked());
    }

    #[test]
    fn resolve_from_ref_uses_the_merge_base_when_one_exists() {
        // `--quiet` still prints the object id on success.
        let git = Git::answering([
            ("rev-parse --verify", Reply::said("tipsha")),
            ("merge-base", Reply::said("abc123")),
        ]);
        let from = resolve_from_ref(&git, None).expect("resolved");
        assert_eq!(from, "abc123");
        assert_eq!(
            git.asked(),
            vec![
                String::from("rev-parse --verify"),
                String::from("merge-base"),
            ]
        );
    }

    #[test]
    fn resolve_from_ref_falls_back_to_the_tip_when_histories_are_unrelated() {
        // Measured: unrelated histories → exit 1, empty streams (`said_no`).
        let git = Git::answering([
            ("rev-parse --verify", Reply::said("tipsha")),
            ("merge-base", Reply::absent()),
        ]);
        let from = resolve_from_ref(&git, None).expect("resolved");
        assert_eq!(from, "origin/main");
    }

    #[test]
    fn resolve_from_ref_propagates_a_diagnosed_merge_base_failure() {
        let git = Git::answering([
            ("rev-parse --verify", Reply::said("tipsha")),
            (
                "merge-base",
                Reply::failed(128, "fatal: Not a valid object name origin/main"),
            ),
        ]);
        let err = resolve_from_ref(&git, None).expect_err("diagnosed failure");
        assert!(
            err.to_string().contains("merge-base") || err.to_string().contains("valid object"),
            "{err}"
        );
    }

    #[test]
    fn merge_base_distinguishes_no_ancestor_from_a_failed_look() {
        let unrelated = Git::answering([("merge-base", Reply::absent())]);
        assert_eq!(
            merge_base(&unrelated, "main").expect("looked"),
            None,
            "no common ancestor is Ok(None)"
        );

        let diagnosed = Git::answering([(
            "merge-base",
            Reply::failed(128, "fatal: Not a valid object name main"),
        )]);
        let err = merge_base(&diagnosed, "main").expect_err("failed look");
        assert!(
            err.to_string().contains("merge-base") || err.to_string().contains("valid object"),
            "{err}"
        );
    }
}