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
//! Both sides of a workspace's root files, read for the comparisons in
//! ADR-0039: a Cargo workspace's `Cargo.toml` and `Cargo.lock` for
//! [`root_changes`], and a pnpm workspace's catalogs and `pnpm-lock.yaml`.

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

use oakum::manifest::{
    changed_catalog_entries, pnpm_lock_reach, root_changes, runtime_catalog_uses, RootChanges,
    RootFile, RootFiles, RootReason,
};
use oakum::plan::{Bounds, Ecosystem, Package, PackageId, Workspace};
use oakum::state::Through;

use super::dependency_updates::Ask;
use super::git::{Commit, Followed, Git};
use super::CliError;

/// `manifest` and `lock` are where the root files lead now, which a diff
/// names; `in_place` is where they sit, which an earlier side is read
/// through, its own links followed there.
#[derive(Debug)]
struct Paths {
    manifest: String,
    lock: String,
    in_place: (String, String),
}

impl Paths {
    fn of(workspace: &Workspace) -> Option<Self> {
        let (manifest, lock) = workspace.cargo_root_files()?;
        let root = workspace.cargo_workspace_root()?;
        Some(Self {
            manifest,
            lock,
            in_place: (joined(root, "Cargo.toml"), joined(root, "Cargo.lock")),
        })
    }

    fn in_place<'a>(&'a self, path: &'a str) -> &'a str {
        if path == self.manifest {
            &self.in_place.0
        } else if path == self.lock {
            &self.in_place.1
        } else {
            path
        }
    }

    fn linked(&self, path: &str) -> bool {
        path != self.in_place(path)
    }

    fn path(&self, file: RootFile) -> &str {
        match file {
            RootFile::Manifest => &self.manifest,
            RootFile::Lock => &self.lock,
        }
    }
}

/// What a change to the root files reached; empty when neither changed.
#[derive(Debug, Default)]
pub(super) struct RootReach {
    changes: RootChanges,
    paths: Option<Paths>,
    /// Each npm member a pnpm root file reached, with what reached it.
    pnpm: BTreeMap<PackageId, BTreeSet<Through>>,
    /// Counts only toward the packages that build it in ([`built_into`]).
    locked: BTreeMap<PackageId, BTreeSet<Through>>,
}

/// What a root change reached a member through, for ADR-0040's classification.
#[derive(Debug)]
pub(super) enum Reason<'a> {
    /// A `[workspace.dependencies]` or catalog entry, by its key.
    Entry(&'a str),
    /// A lockfile row.
    Locked,
    Other,
}

impl RootReach {
    /// The packages to walk [`oakum::plan::reach`] from, split by what their
    /// reasons ask: the members a root change named, the build-resolving
    /// packages a lock change reached, and for a workspace-wide one every
    /// Cargo package `managed` accepts, which always asks for intent.
    pub(super) fn changed(
        &self,
        workspace: &Workspace,
        managed: impl Fn(&Package) -> bool,
        ask: impl Fn(&PackageId, &Reason<'_>) -> Ask,
    ) -> BTreeMap<PackageId, Ask> {
        let mut out: BTreeMap<PackageId, Ask> = BTreeMap::new();
        let mut add = |id: PackageId, asked: Ask| {
            let at = out.entry(id).or_insert(Ask::Nothing);
            *at = (*at).max(asked);
        };
        let strongest = |id: &PackageId, reasons: &mut dyn Iterator<Item = Reason<'_>>| {
            reasons
                .map(|reason| ask(id, &reason))
                .max()
                .unwrap_or(Ask::Intent)
        };
        for (id, reasons) in &self.changes.members {
            add(
                id.clone(),
                strongest(id, &mut reasons.iter().map(cargo_reason)),
            );
            if reasons.iter().any(|reason| reason.file == RootFile::Lock) {
                let asked = strongest(id, &mut std::iter::once(Reason::Locked));
                for build in builds_above(workspace, id, &managed) {
                    add(build, asked);
                }
            }
        }
        for (id, reasons) in &self.pnpm {
            add(
                id.clone(),
                strongest(
                    id,
                    &mut reasons.iter().map(|through| Reason::Entry(&through.name)),
                ),
            );
        }
        for (origin, reasons) in &self.locked {
            let asked = strongest(origin, &mut reasons.iter().map(|_| Reason::Locked));
            for id in built_into(workspace, origin, &managed) {
                add(id, asked);
            }
        }
        if !self.changes.everywhere.is_empty() {
            for package in cargo_packages(workspace).filter(|package| managed(package)) {
                add(package.id().clone(), Ask::Intent);
            }
        }
        out
    }

    /// Each lockfile row or entry a change reached a package through, with
    /// the package it reached: `Cargo.lock` by member, `pnpm-lock.yaml` by
    /// importer.
    pub(super) fn lock_hits(&self) -> Vec<(PackageId, String)> {
        let cargo = self.changes.members.iter().flat_map(|(id, reasons)| {
            reasons
                .iter()
                .filter(|reason| reason.file == RootFile::Lock)
                .map(move |reason| (id.clone(), reason.name.clone()))
        });
        let pnpm = self.locked.iter().flat_map(|(id, reasons)| {
            reasons
                .iter()
                .map(move |through| (id.clone(), through.name.clone()))
        });
        cargo.chain(pnpm).collect()
    }

    /// The members a root change named, each needing a verdict.
    pub(super) fn named(&self) -> impl Iterator<Item = PackageId> + '_ {
        self.changes
            .members
            .keys()
            .chain(self.pnpm.keys())
            .chain(self.locked.keys())
            .cloned()
    }

    /// Each managed package a root change reached, with every reason that
    /// reached it: a lock row through one internal crate and a manifest entry
    /// through another both land on the package that ships them.
    pub(super) fn through(
        &self,
        workspace: &Workspace,
        managed: impl Fn(&Package) -> bool,
    ) -> BTreeMap<PackageId, Vec<Through>> {
        let mut out: BTreeMap<PackageId, BTreeSet<Through>> = BTreeMap::new();
        for (origin, reasons) in &self.pnpm {
            for hit in oakum::plan::reach(workspace, [origin], &managed)
                .managed
                .into_keys()
            {
                out.entry(hit).or_default().extend(reasons.iter().cloned());
            }
        }
        for (origin, reasons) in &self.locked {
            for hit in built_into(workspace, origin, &managed) {
                out.entry(hit).or_default().extend(reasons.iter().cloned());
            }
        }
        let Some(paths) = &self.paths else {
            return out
                .into_iter()
                .map(|(id, through)| (id, through.into_iter().collect()))
                .collect();
        };
        let through = |reason: &RootReason| Through {
            file: paths.path(reason.file).to_owned(),
            name: reason.name.clone(),
        };
        for (origin, reasons) in &self.changes.members {
            for hit in oakum::plan::reach(workspace, [origin], &managed)
                .managed
                .into_keys()
            {
                out.entry(hit)
                    .or_default()
                    .extend(reasons.iter().map(through));
            }
            let locked = || {
                reasons
                    .iter()
                    .filter(|reason| reason.file == RootFile::Lock)
                    .map(through)
            };
            if locked().next().is_some() {
                for hit in builds_above(workspace, origin, &managed) {
                    out.entry(hit).or_default().extend(locked());
                }
            }
        }
        if !self.changes.everywhere.is_empty() {
            for package in cargo_packages(workspace).filter(|package| managed(package)) {
                out.entry(package.id().clone())
                    .or_default()
                    .extend(self.changes.everywhere.iter().map(through));
            }
        }
        out.into_iter()
            .map(|(id, through)| (id, through.into_iter().collect()))
            .collect()
    }
}

fn cargo_reason(reason: &RootReason) -> Reason<'_> {
    match reason.file {
        RootFile::Lock => Reason::Locked,
        RootFile::Manifest => reason
            .name
            .strip_prefix("[workspace.dependencies] ")
            .map_or(Reason::Other, Reason::Entry),
    }
}

/// Managed build-resolving packages at or above `origin` along runtime edges,
/// past managed libraries too: a published library ships no lockfile, a build
/// bakes in what it resolved.
fn built_into(
    workspace: &Workspace,
    origin: &PackageId,
    managed: impl Fn(&Package) -> bool,
) -> BTreeSet<PackageId> {
    let mut seen = BTreeSet::from([origin.clone()]);
    let mut queue = std::collections::VecDeque::from([origin.clone()]);
    let mut out = BTreeSet::new();
    while let Some(at) = queue.pop_front() {
        if let Some(package) = workspace.get(&at) {
            if managed(package) && oakum::plan::takes_build_rule(package) {
                out.insert(at.clone());
            }
        }
        for (dependent, _) in workspace.runtime_dependents(&at) {
            if seen.insert(dependent.id().clone()) {
                queue.push_back(dependent.id().clone());
            }
        }
    }
    out
}

/// The builds [`built_into`] finds above a member a `Cargo.lock` row reached
/// that [`oakum::plan::reach`] from it does not, as past a managed library.
fn builds_above(
    workspace: &Workspace,
    member: &PackageId,
    managed: impl Fn(&Package) -> bool,
) -> BTreeSet<PackageId> {
    let reached = oakum::plan::reach(workspace, [member], &managed).managed;
    built_into(workspace, member, &managed)
        .into_iter()
        .filter(|id| !reached.contains_key(id))
        .collect()
}

/// The managed packages a lock hit on `origin` reaches, each with the
/// managed library it was reached past, if any: for Cargo, those
/// [`oakum::plan::reach`] reaches and the builds above them; for pnpm, the
/// builds that take it in, as [`RootReach::changed`] counts them.
pub(super) fn lock_targets(
    workspace: &Workspace,
    origin: &PackageId,
    managed: impl Fn(&Package) -> bool,
) -> BTreeMap<PackageId, Option<PackageId>> {
    let mut out: BTreeMap<PackageId, Option<PackageId>> = BTreeMap::new();
    match origin.ecosystem {
        Ecosystem::Cargo => {
            let reached: Vec<PackageId> = oakum::plan::reach(workspace, [origin], &managed)
                .managed
                .into_keys()
                .collect();
            for library in &reached {
                out.insert(library.clone(), None);
            }
            for library in &reached {
                for build in built_into(workspace, library, &managed) {
                    out.entry(build).or_insert_with(|| Some(library.clone()));
                }
            }
        }
        Ecosystem::Npm => {
            let origin_managed = workspace.get(origin).is_some_and(&managed);
            for build in built_into(workspace, origin, &managed) {
                let via = (build != *origin && origin_managed).then(|| origin.clone());
                out.insert(build, via);
            }
        }
    }
    out
}

/// `package`'s importer key in the workspace's `pnpm-lock.yaml`.
pub(super) fn pnpm_importer(workspace: &Workspace, package: &Package) -> Option<String> {
    let dir = workspace.pnpm_lock_dir()?;
    let at = package.manifest_dir();
    let rest = if dir.is_empty() {
        at
    } else if at == dir {
        ""
    } else {
        at.strip_prefix(dir)?.strip_prefix('/')?
    };
    Some(if rest.is_empty() {
        String::from(".")
    } else {
        rest.to_owned()
    })
}

/// Whether `changed` lists a root file a comparison reads, or a root file is a
/// link, which [`compare_cargo`] reads whatever a non-empty diff names; asked
/// before the reads that compare them.
pub(super) fn touched(workspace: &Workspace, changed: &[String]) -> bool {
    let listed = |wanted: &str| changed.iter().any(|path| path == wanted);
    Paths::of(workspace).is_some_and(|paths| {
        [&paths.manifest, &paths.lock]
            .into_iter()
            .any(|path| paths.linked(path) || listed(path) || listed(paths.in_place(path)))
    }) || workspace.catalog_file().is_some_and(listed)
        || pnpm_lock_path(workspace).is_some_and(|path| listed(&path))
}

pub(super) fn pnpm_lock_path(workspace: &Workspace) -> Option<String> {
    workspace
        .pnpm_lock_dir()
        .map(|dir| joined(dir, "pnpm-lock.yaml"))
}

fn joined(dir: &str, path: &str) -> String {
    match (dir, path) {
        (dir, "." | "") => dir.to_owned(),
        ("", path) => path.to_owned(),
        (dir, path) => format!("{dir}/{path}"),
    }
}

fn cargo_packages(workspace: &Workspace) -> impl Iterator<Item = &Package> {
    workspace
        .packages()
        .filter(|package| package.id().ecosystem == Ecosystem::Cargo)
}

/// `base` against `head` for the root files among `changed`.
///
/// # Errors
///
/// A read git could not answer, or a side that does not parse: `unverified`,
/// since what the file changed is then unknown.
pub(super) fn between_commits(
    git: &Git,
    workspace: &Workspace,
    base: &Commit,
    head: &Commit,
    changed: &[String],
) -> Result<RootReach, CliError> {
    compare(
        git,
        workspace,
        base,
        changed,
        &Head::Commit(head),
        |wanted| git.blobs_or_absent(head, wanted),
    )
}

/// `base` against the working tree: a root file in `on_disk` is read by
/// `read_disk`, a linked one as [`root_files_read`] says, any other at `head`.
///
/// # Errors
///
/// As [`between_commits`], or `read_disk`'s own failure.
pub(super) fn against_worktree(
    git: &Git,
    workspace: &Workspace,
    base: &Commit,
    head: &Commit,
    changed: &[String],
    on_disk: &[String],
    read_disk: impl Fn(&str) -> Result<Option<String>, CliError>,
) -> Result<RootReach, CliError> {
    let side = Head::Worktree {
        commit: head,
        on_disk,
        read_disk: &read_disk,
    };
    compare(git, workspace, base, changed, &side, |wanted| {
        let committed = git.blobs_or_absent(head, wanted)?;
        wanted
            .iter()
            .zip(committed)
            .map(|(path, committed)| {
                if on_disk.iter().any(|listed| listed == path) {
                    read_disk(path)
                } else {
                    Ok(committed)
                }
            })
            .collect()
    })
}

/// `texts` holds one entry per `wanted` path; a root file not wanted reads as
/// absent on both sides, which compares as unchanged.
fn side<'a>(paths: &Paths, wanted: &[&str], texts: &'a [Option<String>]) -> RootFiles<'a> {
    let text = |path: &str| {
        wanted
            .iter()
            .position(|wanted| *wanted == path)
            .and_then(|at| texts[at].as_deref())
    };
    RootFiles {
        manifest: text(&paths.manifest),
        lock: text(&paths.lock),
    }
}

/// The later side of a comparison, for reading the Cargo root files through
/// that side's own links.
enum Head<'a> {
    Commit(&'a Commit),
    /// A file in `on_disk` is read by `read_disk`, a linked root file as
    /// [`root_files_read`] says, any other at `commit`.
    Worktree {
        commit: &'a Commit,
        on_disk: &'a [String],
        read_disk: &'a dyn Fn(&str) -> Result<Option<String>, CliError>,
    },
}

fn compare(
    git: &Git,
    workspace: &Workspace,
    base: &Commit,
    changed: &[String],
    head_side: &Head<'_>,
    head: impl Fn(&[&str]) -> Result<Vec<Option<String>>, CliError>,
) -> Result<RootReach, CliError> {
    let mut reach = compare_cargo(git, workspace, base, changed, head_side)?;
    reach.pnpm = catalog_reach(git, workspace, base, changed, &head)?;
    reach.locked = lock_reach(git, workspace, base, changed, &head)?;
    Ok(reach)
}

fn lock_reach(
    git: &Git,
    workspace: &Workspace,
    base: &Commit,
    changed: &[String],
    head: impl Fn(&[&str]) -> Result<Vec<Option<String>>, CliError>,
) -> Result<BTreeMap<PackageId, BTreeSet<Through>>, CliError> {
    let (Some(dir), Some(path)) = (workspace.pnpm_lock_dir(), pnpm_lock_path(workspace)) else {
        return Ok(BTreeMap::new());
    };
    if !changed.contains(&path) {
        return Ok(BTreeMap::new());
    }
    let base_text = git.blobs_or_absent(base, &[&path])?.pop().flatten();
    let head_text = head(&[&path])?.pop().flatten();
    let reached = pnpm_lock_reach(base_text.as_deref(), head_text.as_deref()).map_err(
        |(side, err)| {
            CliError::unverified(format!(
                "unverified: `{path}` does not parse at the {side} of the comparison, so which entries it changed is unknown: {err}"
            ))
        },
    )?;
    let mut out = BTreeMap::new();
    for (importer, names) in reached {
        let project = joined(dir, &importer);
        let Some(package) = workspace.packages().find(|package| {
            package.id().ecosystem == Ecosystem::Npm && package.manifest_dir() == project
        }) else {
            continue;
        };
        out.insert(
            package.id().clone(),
            names
                .into_iter()
                .map(|name| Through {
                    file: path.clone(),
                    name,
                })
                .collect(),
        );
    }
    Ok(out)
}

/// The npm members whose runtime dependencies take a catalog entry that moved.
/// An entry that installs one workspace package on both sides, by its key or
/// an `npm:` alias, and whose new range is its old one retargeted at that
/// package's version, is the pin `version` writes, so it reaches nothing.
fn catalog_reach(
    git: &Git,
    workspace: &Workspace,
    base: &Commit,
    changed: &[String],
    head: impl Fn(&[&str]) -> Result<Vec<Option<String>>, CliError>,
) -> Result<BTreeMap<PackageId, BTreeSet<Through>>, CliError> {
    let Some(path) = workspace
        .catalog_file()
        .filter(|path| changed.iter().any(|changed| changed == path))
    else {
        return Ok(BTreeMap::new());
    };
    let base_text = git.blobs_or_absent(base, &[path])?.pop().flatten();
    let members: Vec<&Package> = workspace
        .packages()
        .filter(|package| package.id().ecosystem == Ecosystem::Npm)
        .collect();
    let manifests: Vec<String> = members
        .iter()
        .map(|package| package.manifest_path())
        .collect();
    let wanted: Vec<&str> = std::iter::once(path)
        .chain(manifests.iter().map(String::as_str))
        .collect();
    let texts = head(&wanted)?;
    let (head_text, manifest_texts) = texts.split_first().unwrap_or((&None, &[]));
    let mut moved = changed_catalog_entries(base_text.as_deref(), head_text.as_deref())
        .map_err(|(side, err)| {
            CliError::unverified(format!(
                "unverified: `{path}` does not parse at the {side} of the comparison, so which catalog entries it changed is unknown: {err}"
            ))
        })?;
    moved.retain(|_, repinned| {
        !repinned.as_ref().is_some_and(|pin| {
            workspace
                .get(&PackageId::new(Ecosystem::Npm, pin.package.clone()))
                .is_some_and(|member| {
                    Bounds::from_npm_text(&pin.from).is_ok_and(|bounds| {
                        bounds.retargeted(member.version()).as_deref() == Some(pin.to.as_str())
                    })
                })
        })
    });
    let mut out: BTreeMap<PackageId, BTreeSet<Through>> = BTreeMap::new();
    if moved.is_empty() {
        return Ok(out);
    }
    for ((package, manifest), text) in members.iter().zip(&manifests).zip(manifest_texts) {
        let Some(text) = text else {
            continue;
        };
        let uses = runtime_catalog_uses(text).map_err(|err| {
            CliError::unverified(format!(
                "unverified: `{manifest}` does not parse, so which catalog entries it takes is unknown: {err}"
            ))
        })?;
        let reasons: BTreeSet<Through> = uses
            .iter()
            .filter(|entry| moved.contains_key(*entry))
            .map(|(_, name)| Through {
                file: path.to_owned(),
                name: name.clone(),
            })
            .collect();
        if !reasons.is_empty() {
            out.insert(package.id().clone(), reasons);
        }
    }
    Ok(out)
}

fn compare_cargo(
    git: &Git,
    workspace: &Workspace,
    base: &Commit,
    changed: &[String],
    head: &Head<'_>,
) -> Result<RootReach, CliError> {
    // An empty list is a merge's: read through its first parent, a link would
    // credit it with the merged branch's lock change.
    let Some(paths) = Paths::of(workspace).filter(|_| !changed.is_empty()) else {
        return Ok(RootReach::default());
    };
    let listed = |path: &str| {
        changed
            .iter()
            .any(|changed| changed == path || changed == paths.in_place(path))
    };
    // A link is read on both sides whatever the diff names: a link along its
    // chain retargeted, or a file it led to then, changes what cargo read,
    // and neither is a path known here. One that reads the same changed nothing.
    let wanted: Vec<&str> = [paths.manifest.as_str(), paths.lock.as_str()]
        .into_iter()
        .filter(|path| paths.linked(path) || listed(path))
        .collect();
    if wanted.is_empty() {
        return Ok(RootReach::default());
    }
    let (base_reads, head_reads) = root_files_read(git, base, head, &paths, &wanted)?;
    let mut kept = Vec::new();
    let (mut base_texts, mut head_texts) = (Vec::new(), Vec::new());
    for ((path, base), head) in wanted.into_iter().zip(base_reads).zip(head_reads) {
        let named = listed(path);
        // Unnamed and unfollowable on both sides, a link is left unread, as an
        // unnamed root file in place is.
        if !named && base.is_err() && head.is_err() {
            continue;
        }
        let (base, head) = (base?, head?);
        if named || base != head {
            kept.push(path);
            base_texts.push(base);
            head_texts.push(head);
        }
    }
    let wanted = kept;
    if wanted.is_empty() {
        return Ok(RootReach::default());
    }
    // The manifest comparison reads these only to skip `version`'s own
    // retarget, so an unread base there skips nothing.
    let base_members = if wanted.contains(&paths.lock.as_str()) {
        declared_at(git, workspace, base)?
    } else {
        declared_at(git, workspace, base).unwrap_or_default()
    };
    let found = root_changes(
        workspace,
        &base_members,
        side(&paths, &wanted, &base_texts),
        side(&paths, &wanted, &head_texts),
    )
    .map_err(|err| {
        CliError::unverified(format!(
            "unverified: `{}` does not parse on one side of the comparison, so what it changed is unknown: {}",
            paths.path(err.file),
            err.message
        ))
    })?;
    Ok(RootReach {
        changes: found,
        paths: Some(paths),
        ..RootReach::default()
    })
}

/// One side's text of a root file, or why that side's link could not be
/// followed, which is `unverified`.
type SideText = Result<Option<String>, CliError>;

/// The root files each side holds, read where they sit and through that
/// side's own links: today's link would otherwise send an earlier commit to a
/// file it never read. Both commits are read by one child; the outer error is
/// a read that did not happen.
fn root_files_read(
    git: &Git,
    base: &Commit,
    head: &Head<'_>,
    paths: &Paths,
    wanted: &[&str],
) -> Result<(Vec<SideText>, Vec<SideText>), CliError> {
    let head_commit = match head {
        Head::Commit(commit) | Head::Worktree { commit, .. } => *commit,
    };
    // Followed always: whether a side holds a link is its own, so a link
    // removed since still leads somewhere at the base.
    let queries: Vec<(&Commit, &str)> = [base, head_commit]
        .into_iter()
        .flat_map(|commit| {
            wanted
                .iter()
                .map(move |path| (commit, paths.in_place(path)))
        })
        .collect();
    let mut texts: Vec<SideText> = queries
        .iter()
        .zip(git.followed_blobs(&queries)?)
        .map(|((commit, path), followed)| followed_text(commit, path, followed))
        .collect();
    let mut head_texts = texts.split_off(wanted.len());
    if let Head::Worktree {
        on_disk, read_disk, ..
    } = head
    {
        for (path, text) in wanted.iter().zip(&mut head_texts) {
            let in_place = paths.in_place(path);
            // A link git follows at `HEAD` is read where it leads on disk,
            // since a link along its chain may have changed there.
            if (paths.linked(path) && text.is_ok())
                || on_disk
                    .iter()
                    .any(|listed| listed == path || listed == in_place)
            {
                *text = Ok(read_disk(in_place)?);
            }
        }
    }
    Ok((texts, head_texts))
}

fn followed_text(commit: &Commit, path: &str, followed: Followed) -> SideText {
    match followed {
        Followed::File(bytes) => String::from_utf8(bytes).map(Some).map_err(|_| {
            CliError::unverified(format!(
                "unverified: `{path}` at {} is not UTF-8, so what it changed is unknown",
                commit.as_str()
            ))
        }),
        Followed::Absent => Ok(None),
        Followed::Dangling => Err(CliError::unverified(format!(
            "unverified: `{path}` at {} is a link to no file there, so what it changed is unknown",
            commit.as_str()
        ))),
        Followed::Unfollowed(why) => Err(CliError::unverified(format!(
            "unverified: `{path}` at {} could not be read as a file ({why}), so what it changed is unknown",
            commit.as_str()
        ))),
    }
}

/// Each Cargo member as cargo reads it at `base`, run from the directory
/// HEAD's discovery ran from; none when the base holds no Cargo workspace.
pub(super) fn declared_at(
    git: &Git,
    workspace: &Workspace,
    base: &Commit,
) -> Result<BTreeMap<PackageId, Package>, CliError> {
    let root = git.root();
    let start = super::workspace::cargo_start(root);
    let members: Vec<(&str, &str)> = cargo_packages(workspace)
        .map(|package| (package.manifest_dir(), package.id().name.as_str()))
        .collect();
    Ok(
        super::base_tree::base_workspace(git, base, &start, root, &members)?
            .map(|workspace| {
                cargo_packages(&workspace)
                    .map(|package| (package.id().clone(), package.clone()))
                    .collect()
            })
            .unwrap_or_default(),
    )
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn the_root_importer_is_the_lock_directory() {
        assert_eq!(joined("", "."), "");
        assert_eq!(joined("js", "."), "js");
        assert_eq!(joined("", "packages/a"), "packages/a");
        assert_eq!(joined("js", "packages/a"), "js/packages/a");
    }
}