diffler-core 0.17.0

Core review engine for diffler: diffs, sessions, comments, viewed marks
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
//! Facade tying the VCS backend, session, and store together: the one
//! entry point the TUI and MCP layers consume.

use std::cell::OnceCell;
use std::collections::{BTreeMap, HashMap};
use std::path::{Path, PathBuf};

use thiserror::Error;

use crate::diffalgo::{DiffAlgorithm, DiffSettings};
use crate::model::DiffModel;
use crate::repo;
use crate::session::Session;
use crate::source::ReviewSource;
use crate::store::{self, StoreError};
use crate::vcs::{StatusModel, Vcs, VcsError};

#[derive(Debug, Error)]
pub enum ReviewError {
    #[error(transparent)]
    Vcs(#[from] VcsError),
    #[error(transparent)]
    Store(#[from] StoreError),
}

/// One file as the file view reads it: worktree text plus per-line blame.
#[derive(Debug)]
pub struct FileSnapshot {
    pub path: String,
    pub content: String,
    /// Empty when git has nothing to attribute, e.g. an untracked file.
    pub blame: Vec<crate::vcs::BlameSpan>,
}

/// The result of [`Review::compute_walkthrough_files`]: every file it could
/// read, plus whether the revision it was asked to pin to still resolves.
#[derive(Debug, Default)]
pub struct WalkthroughFiles {
    pub contents: HashMap<String, String>,
    /// A `rev` was named but no longer resolves (a squash, a rebase, a gc):
    /// every file fell back to the worktree, and the reader is looking at
    /// live code believing it is pinned. `false` when nothing was pinned at
    /// all, which is not broken, just untracked.
    pub pin_broken: bool,
}

/// A preview reads at most this many bytes of one side (32 MiB).
pub const MAX_PREVIEW_BYTES: u64 = 32 * 1024 * 1024;

/// One side of a binary file, as [`Review::compute_binary_sides`] read it.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum BinarySide {
    Bytes(Vec<u8>),
    /// The side exists but is over [`MAX_PREVIEW_BYTES`]; its size in bytes.
    TooLarge(u64),
}

impl BinarySide {
    fn of(bytes: Vec<u8>) -> Self {
        let size = bytes.len() as u64;
        if size > MAX_PREVIEW_BYTES {
            Self::TooLarge(size)
        } else {
            Self::Bytes(bytes)
        }
    }
}

/// Both sides of a binary file; `None` for a side that does not exist.
#[derive(Debug, Clone, Default, PartialEq, Eq)]
pub struct BinarySides {
    pub old: Option<BinarySide>,
    pub new: Option<BinarySide>,
}

/// Which copy of a walkthrough's file [`Review::compute_walkthrough_files`]
/// reads first, falling back to the other.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum ReadFirst {
    /// The commit the walkthrough was pinned to, for code that was committed.
    Pin,
    /// The file on disk, for a walkthrough of uncommitted work.
    Worktree,
}

/// One landed off-thread refresh.
#[derive(Debug)]
pub struct Refreshed {
    pub status: StatusModel,
    pub model: DiffModel,
    /// The [`ReviewSource::Against`] rev the caller asked about and its
    /// recomputed diff. The rev rides along so a review swapped while the
    /// worker ran can ignore an answer meant for the previous one.
    pub against: Option<(String, Result<DiffModel, VcsError>)>,
    /// A pinned commit, range, or PR source's freshly recomputed diff, when
    /// the caller asked [`Review::compute_refresh`] for one (an algorithm
    /// switch re-diffing whatever source is open).
    pub pinned: Option<Result<DiffModel, VcsError>>,
}

/// The freshly fetched diff for a commit, range, or PR review source,
/// straight from the backend: the one place each variant's vcs call is
/// made, whether the caller reads it on the UI thread or off it.
/// `pr_head` is the PR's own `(merge_base, head)`, resolved by the caller
/// since a PR's range lives in app state; `None` rejects an unresolved PR,
/// so it is never silently read as unchanged.
/// `WorkingTree`, `Walkthrough`, and `Against` carry no pinned diff of their
/// own and read back empty.
pub fn pinned_diff(
    vcs: &dyn Vcs,
    source: &ReviewSource,
    pr_head: Option<(&str, &str)>,
) -> Result<DiffModel, VcsError> {
    match source {
        ReviewSource::Commit { oid } => vcs.commit_diff(oid),
        ReviewSource::Range { oldest, newest } => vcs.range_diff(oldest, newest),
        ReviewSource::Pr { number } => {
            let (base, head) = pr_head
                .ok_or_else(|| VcsError::Rejected(format!("PR #{number} is not resolved")))?;
            vcs.tree_diff(base, head)
        }
        ReviewSource::WorkingTree
        | ReviewSource::Walkthrough { .. }
        | ReviewSource::Against { .. } => Ok(DiffModel::default()),
    }
}

pub struct Review {
    pub repo_root: PathBuf,
    pub vcs: Box<dyn Vcs>,
    pub status: StatusModel,
    /// HEAD vs workdir+index including untracked: the review view. Computed
    /// lazily on first [`Review::model`] access: the status screen is the
    /// initial view and needs no working diff up front.
    model: OnceCell<DiffModel>,
    /// The working-tree review session, the default view.
    pub session: Session,
    /// Lazily-loaded sessions for non-working sources (commits, ranges), keyed
    /// by [`ReviewSource::key`].
    sources: HashMap<String, (ReviewSource, Session)>,
    /// Returned by [`Review::session_for`] for a source that has no review yet.
    empty: Session,
}

impl Review {
    /// Open the git backend at [`DiffSettings::default`], load the persisted
    /// session (if any), and compute the status sections. The working-tree
    /// review diff is deferred until first [`Review::model`] access.
    pub fn open(repo_root: &Path) -> Result<Self, ReviewError> {
        Self::open_with_settings(repo_root, &DiffSettings::default())
    }

    /// Like [`Review::open`] with a custom context, line-diff algorithm and
    /// indent heuristic (config keys `ui.context_lines`, `diff.algorithm`,
    /// `diff.indent_heuristic`).
    pub fn open_with_settings(
        repo_root: &Path,
        settings: &DiffSettings,
    ) -> Result<Self, ReviewError> {
        let vcs = repo::open_with_settings(repo_root, settings)?;
        let status = vcs.status()?;
        let session = store::load(repo_root)?;
        Ok(Self {
            repo_root: repo_root.to_path_buf(),
            vcs,
            status,
            model: OnceCell::new(),
            session,
            sources: HashMap::new(),
            empty: Session::default(),
        })
    }

    /// Switch the session's line-diff algorithm live, so every diff this
    /// review's own backend computes afterward uses it.
    pub fn set_diff_algorithm(&self, algorithm: DiffAlgorithm, indent_heuristic: bool) {
        self.vcs.set_diff_algorithm(algorithm, indent_heuristic);
    }

    /// The working-tree review diff, computed and cached on first access. A
    /// backend error yields an empty diff rather than panicking; the next
    /// [`Review::refresh`] gets another chance to compute it.
    pub fn model(&self) -> &DiffModel {
        self.model
            .get_or_init(|| self.vcs.working_tree_diff().unwrap_or_default())
    }

    /// Mutable view of the working-tree review diff, computing it first if
    /// needed. The TUI uses this to enrich a file with intra-line emphasis
    /// just before rendering it.
    pub fn model_mut(&mut self) -> &mut DiffModel {
        self.model();
        #[allow(clippy::expect_used)]
        self.model.get_mut().expect("model just initialized")
    }

    /// Recompute status + diff (the watcher calls this on changes) and drop
    /// viewed marks for files that changed or left the diff.
    pub fn refresh(&mut self) -> Result<(), ReviewError> {
        self.status = self.vcs.status()?;
        let model = self.vcs.working_tree_diff()?;
        self.install_refresh(self.status.clone(), model);
        Ok(())
    }

    /// Compute a refresh on a separate repo handle, so it can run off the UI
    /// thread; the result is applied later with [`Review::install_refresh`].
    /// `against` recomputes the open three-dot review in the same pass, since
    /// it tracks edits and cannot be pinned like a commit's diff. `pinned`
    /// additionally recomputes a commit, range, or PR source's diff on this
    /// same backend (an algorithm switch re-diffing whatever source is open).
    pub fn compute_refresh(
        repo_root: &Path,
        settings: &DiffSettings,
        against: Option<&str>,
        pinned: Option<(&ReviewSource, Option<(&str, &str)>)>,
    ) -> Result<Refreshed, ReviewError> {
        let vcs = repo::open_with_settings(repo_root, settings)?;
        let status = vcs.status()?;
        let model = vcs.working_tree_diff()?;
        let against =
            against.map(|rev| (rev.to_owned(), crate::vcs::against_diff(vcs.as_ref(), rev)));
        let pinned = pinned.map(|(source, pr_head)| pinned_diff(vcs.as_ref(), source, pr_head));
        Ok(Refreshed {
            status,
            model,
            against,
            pinned,
        })
    }

    /// What the repo's git attributes declare about each of `paths`, for the
    /// kinds sidebar. One attribute lookup walks the directory chain and the
    /// global attribute files, so this is real IO per path and belongs on a
    /// worker; paths the repo says nothing about are left out.
    pub fn compute_declared(
        repo_root: &Path,
        paths: &[String],
    ) -> Result<HashMap<String, crate::classify::Kind>, ReviewError> {
        let vcs = repo::open(repo_root)?;
        Ok(paths
            .iter()
            .filter_map(|path| {
                let rel = Path::new(path);
                let kind = crate::classify::declared(|name| vcs.attr(rel, name))?;
                Some((path.clone(), kind))
            })
            .collect())
    }

    /// Every requested file's content, from the copy `read_first` names and
    /// else the other: the walkthrough's own `rev`, or the live worktree (the
    /// only copy when `rev` is `None`, a walkthrough saved before it was
    /// tracked). Opens its own backend so it runs on a worker thread like
    /// [`Review::compute_refresh`]; a path neither the revision nor the
    /// worktree can produce is left out rather than failing the whole read.
    /// `rev` itself can also stop resolving (a squash, a rebase, a gc): that
    /// is distinct from a path merely absent from a revision that still
    /// resolves, so it comes back as `pin_broken` rather than folding into
    /// the same silent worktree fallback.
    pub fn compute_walkthrough_files(
        repo_root: &Path,
        rev: Option<&str>,
        read_first: ReadFirst,
        files: &[String],
    ) -> WalkthroughFiles {
        let vcs = repo::open(repo_root).ok();
        let pin_broken = match (rev, vcs.as_ref()) {
            (Some(rev), Some(vcs)) => vcs.resolve(rev).is_err(),
            (Some(_), None) => true,
            (None, _) => false,
        };
        let rev = (!pin_broken).then_some(rev).flatten();
        let contents = files
            .iter()
            .filter_map(|path| {
                let pinned = || rev.and_then(|rev| vcs.as_ref()?.read_at(rev, path).ok().flatten());
                let worktree = || std::fs::read_to_string(repo_root.join(path)).ok();
                let content = match read_first {
                    ReadFirst::Pin => pinned().or_else(worktree),
                    ReadFirst::Worktree => worktree().or_else(pinned),
                }?;
                Some((path.clone(), content))
            })
            .collect();
        WalkthroughFiles {
            contents,
            pin_broken,
        }
    }

    /// Both sides of a binary file as raw bytes, for the image preview: each
    /// side from its blob, the new side from the worktree when the store has
    /// no blob for it (a working-tree diff). A side over [`MAX_PREVIEW_BYTES`] comes
    /// back as its size alone, so a huge asset never loads into memory.
    pub fn compute_binary_sides(
        repo_root: &Path,
        path: &str,
        blobs: &crate::model::BlobIds,
        deleted: bool,
    ) -> BinarySides {
        let vcs = repo::open(repo_root).ok();
        let from_blob = |oid: &Option<String>| {
            let bytes = vcs.as_ref()?.read_blob(oid.as_deref()?).ok()??;
            Some(BinarySide::of(bytes))
        };
        let new = from_blob(&blobs.new).or_else(|| {
            if deleted {
                return None;
            }
            let full = repo_root.join(path);
            let size = std::fs::metadata(&full).ok()?.len();
            if size > MAX_PREVIEW_BYTES {
                return Some(BinarySide::TooLarge(size));
            }
            std::fs::read(full).ok().map(BinarySide::of)
        });
        BinarySides {
            old: from_blob(&blobs.old),
            new,
        }
    }

    /// One file's worktree text and blame, for the file view. Opens its own
    /// backend so it runs on a worker thread like [`Review::compute_refresh`].
    /// A file git cannot blame (untracked, or newly staged) still loads: it
    /// comes back with text and no spans.
    pub fn compute_file(repo_root: &Path, rel: &str) -> Result<FileSnapshot, ReviewError> {
        let vcs = repo::open(repo_root)?;
        let path = Path::new(rel);
        let content = std::fs::read_to_string(repo_root.join(path)).map_err(VcsError::from)?;
        Ok(FileSnapshot {
            path: rel.to_owned(),
            blame: vcs.blame(path).unwrap_or_default(),
            content,
        })
    }

    /// Swap in freshly computed status + diff and reconcile viewed marks.
    pub fn install_refresh(&mut self, status: StatusModel, model: DiffModel) {
        self.status = status;
        self.session.reconcile(&model);
        self.model = OnceCell::from(model);
    }

    pub fn save(&self) -> Result<(), ReviewError> {
        store::save(&self.repo_root, &self.session)?;
        Ok(())
    }

    /// Load a non-working source's session into the cache if not already there.
    /// Call before reading via [`Review::session_for`] for that source.
    pub fn ensure_source(&mut self, source: &ReviewSource) -> Result<(), ReviewError> {
        if matches!(source, ReviewSource::WorkingTree) {
            return Ok(());
        }
        let key = source.key();
        if !self.sources.contains_key(&key) {
            let session = store::load_source(&self.repo_root, source)?;
            self.sources.insert(key, (source.clone(), session));
        }
        Ok(())
    }

    /// The session for a source. The working tree is always present; other
    /// sources must be [`Review::ensure_source`]d first, else an empty session
    /// is returned.
    pub fn session_for(&self, source: &ReviewSource) -> &Session {
        match source {
            ReviewSource::WorkingTree => &self.session,
            other => self
                .sources
                .get(&other.key())
                .map_or(&self.empty, |(_, session)| session),
        }
    }

    pub fn session_for_mut(&mut self, source: &ReviewSource) -> &mut Session {
        match source {
            ReviewSource::WorkingTree => &mut self.session,
            other => {
                &mut self
                    .sources
                    .entry(other.key())
                    .or_insert_with(|| (other.clone(), Session::default()))
                    .1
            }
        }
    }

    pub fn save_for(&self, source: &ReviewSource) -> Result<(), ReviewError> {
        store::save_source(&self.repo_root, source, self.session_for(source))?;
        Ok(())
    }

    /// Forget a non-working source's cached session, after its file is
    /// deleted from disk (e.g. a walkthrough removed for good), so a later
    /// access reloads default state rather than serving stale memory.
    pub fn forget_source(&mut self, source: &ReviewSource) {
        self.sources.remove(&source.key());
    }

    /// Every review across all sources, in-memory state overriding disk, sorted
    /// by source key. Powers the agent-facing aggregate feed. A review file
    /// that fails to parse is skipped rather than failing the whole call; see
    /// [`Review::all_reviews_and_corrupt`] for the list of what was skipped.
    pub fn all_reviews(&self) -> Result<Vec<(ReviewSource, Session)>, ReviewError> {
        Ok(self.all_reviews_and_corrupt()?.0)
    }

    /// [`Review::all_reviews`] plus the path of every review file that failed
    /// to parse and was skipped, for a caller that wants to tell the reader.
    pub fn all_reviews_and_corrupt(&self) -> Result<store::LoadedReviews, ReviewError> {
        let (loaded, corrupt) = store::load_all(&self.repo_root)?;
        let mut by_key: BTreeMap<String, (ReviewSource, Session)> = loaded
            .into_iter()
            .map(|(source, session)| (source.key(), (source, session)))
            .collect();
        by_key.insert(
            ReviewSource::WorkingTree.key(),
            (ReviewSource::WorkingTree, self.session.clone()),
        );
        for (key, (source, session)) in &self.sources {
            by_key.insert(key.clone(), (source.clone(), session.clone()));
        }
        Ok((by_key.into_values().collect(), corrupt))
    }

    /// Swap a previously computed model back in. Used when a refresh proved
    /// a no-op (same fingerprint): the old model carries render-time emphasis
    /// the rebuilt one lacks.
    pub fn restore_model(&mut self, model: DiffModel) {
        self.model = OnceCell::from(model);
    }

    /// Whether the working-tree model has been computed yet.
    #[cfg(test)]
    fn model_is_cached(&self) -> bool {
        self.model.get().is_some()
    }
}

#[cfg(test)]
mod tests {
    use crate::repo;

    use super::*;

    #[allow(clippy::expect_used)]
    fn write(root: &std::path::Path, rel: &str, content: &str) {
        std::fs::write(root.join(rel), content).expect("write");
    }

    #[allow(clippy::expect_used)]
    fn commit_all(root: &std::path::Path, message: &str) {
        for args in [&["add", "-A"][..], &["commit", "-q", "-m", message][..]] {
            let status = std::process::Command::new("git")
                .arg("-C")
                .arg(root)
                .args(args)
                .env("GIT_AUTHOR_NAME", "t")
                .env("GIT_AUTHOR_EMAIL", "t@t")
                .env("GIT_COMMITTER_NAME", "t")
                .env("GIT_COMMITTER_EMAIL", "t@t")
                .status()
                .expect("git");
            assert!(status.success(), "git {args:?}");
        }
    }

    #[allow(clippy::expect_used)]
    fn init_repo(root: &std::path::Path) {
        let status = std::process::Command::new("git")
            .arg("-C")
            .arg(root)
            .args(["init", "-q"])
            .status()
            .expect("git init");
        assert!(status.success());
    }

    #[test]
    fn open_defers_the_working_model_until_first_access() {
        let dir = tempfile::tempdir().expect("tempdir");
        let root = dir.path();
        init_repo(root);
        write(root, "a.py", "value = old\n");
        commit_all(root, "base");
        write(root, "a.py", "value = new\n");

        let root = repo::discover(root).expect("discover");
        let review = Review::open(&root).expect("open");
        // the status sections are computed eagerly; the review model is not
        assert!(
            !review.model_is_cached(),
            "open must not compute the working model"
        );
        assert_eq!(review.status.unstaged.files.len(), 1);

        // first access computes it; it matches a fresh working_tree_diff
        let lazy = review.model().clone();
        assert!(review.model_is_cached(), "access caches the model");
        let eager = review.vcs.working_tree_diff().expect("diff");
        assert_eq!(lazy, eager, "lazy model equals the eager build");
    }

    #[allow(clippy::expect_used)]
    fn git(root: &std::path::Path, args: &[&str]) {
        let status = std::process::Command::new("git")
            .arg("-C")
            .arg(root)
            .args(args)
            .status()
            .expect("git");
        assert!(status.success(), "git {args:?}");
    }

    #[test]
    fn against_a_base_branch_shows_committed_and_uncommitted_work() {
        let dir = tempfile::tempdir().expect("tempdir");
        let root = dir.path();
        init_repo(root);
        git(root, &["symbolic-ref", "HEAD", "refs/heads/main"]);
        write(root, "base.txt", "base\n");
        commit_all(root, "base");
        git(root, &["checkout", "-q", "-b", "feature"]);
        write(root, "committed.txt", "landed\n");
        commit_all(root, "feature work");
        // main moves on after the fork: three-dot keeps it out of the diff
        git(root, &["checkout", "-q", "main"]);
        write(root, "elsewhere.txt", "not mine\n");
        commit_all(root, "base moved on");
        git(root, &["checkout", "-q", "feature"]);
        write(root, "dirty.txt", "still editing\n");

        let root = repo::discover(root).expect("discover");
        let review = Review::open(&root).expect("open");
        let model = crate::vcs::against_diff(review.vcs.as_ref(), "main").expect("against");
        let paths: Vec<&str> = model.files.iter().map(|f| f.path.as_str()).collect();
        assert_eq!(paths, ["committed.txt", "dirty.txt"]);
    }

    #[test]
    fn per_source_sessions_persist_independently_and_aggregate() {
        let dir = tempfile::tempdir().expect("tempdir");
        let root = dir.path();
        init_repo(root);
        write(root, "a.py", "value = old\n");
        commit_all(root, "base");
        write(root, "a.py", "value = new\n");

        let root = repo::discover(root).expect("discover");
        let mut review = Review::open(&root).expect("open");

        let commit = crate::source::ReviewSource::commit("deadbeef");
        review.ensure_source(&commit).expect("ensure");
        review
            .session_for_mut(&commit)
            .mark_viewed("a.py", "hash-commit");
        review.save_for(&commit).expect("save commit");
        review.session.mark_viewed("a.py", "hash-working");
        review.save().expect("save working");

        // the same path means different things per source
        assert!(review.session_for(&commit).is_viewed("a.py", "hash-commit"));
        assert!(!review.session.is_viewed("a.py", "hash-commit"));

        // a fresh open reloads each source from its own file
        let mut reopened = Review::open(&root).expect("reopen");
        reopened.ensure_source(&commit).expect("ensure");
        assert!(
            reopened
                .session_for(&commit)
                .is_viewed("a.py", "hash-commit")
        );
        assert!(reopened.session.is_viewed("a.py", "hash-working"));

        let all = reopened.all_reviews().expect("all");
        let keys: Vec<String> = all.iter().map(|(s, _)| s.key()).collect();
        assert_eq!(keys, ["commit-deadbeef", "working"]);
    }

    /// A walkthrough pinned to a revision reads a file as that revision had
    /// it, ignoring a dirty worktree, and falls back to the worktree for a
    /// path the revision never had.
    #[test]
    fn compute_walkthrough_files_reads_the_pinned_revision_and_falls_back_for_the_rest() {
        let dir = tempfile::tempdir().expect("tempdir");
        let root = dir.path();
        init_repo(root);
        write(root, "a.txt", "old\n");
        commit_all(root, "base");
        let root = repo::discover(root).expect("discover");
        let pinned = Review::open(&root)
            .expect("open")
            .vcs
            .resolve("HEAD")
            .expect("resolve");
        write(&root, "a.txt", "new\n");
        write(&root, "b.txt", "worktree only\n");

        let files = ["a.txt".to_owned(), "b.txt".to_owned()];
        let read = Review::compute_walkthrough_files(&root, Some(&pinned), ReadFirst::Pin, &files);
        assert_eq!(
            read.contents.get("a.txt").map(String::as_str),
            Some("old\n"),
            "reads the pinned revision, not the dirty worktree"
        );
        assert_eq!(
            read.contents.get("b.txt").map(String::as_str),
            Some("worktree only\n"),
            "a path the revision never had falls back to the worktree"
        );
        assert!(!read.pin_broken, "the pin itself still resolves");
    }

    /// No `rev` at all (a walkthrough saved before it was tracked) reads the
    /// worktree directly.
    #[test]
    fn compute_walkthrough_files_with_no_revision_reads_the_worktree() {
        let dir = tempfile::tempdir().expect("tempdir");
        let root = dir.path();
        init_repo(root);
        write(root, "a.txt", "committed\n");
        commit_all(root, "base");
        write(root, "a.txt", "edited\n");
        let root = repo::discover(root).expect("discover");

        let files = ["a.txt".to_owned()];
        let read = Review::compute_walkthrough_files(&root, None, ReadFirst::Pin, &files);
        assert_eq!(
            read.contents.get("a.txt").map(String::as_str),
            Some("edited\n")
        );
        assert!(
            !read.pin_broken,
            "no revision was ever pinned, so nothing is broken"
        );
    }

    /// A `rev` that no longer resolves (a squash, a rebase, a gc) is a
    /// different fact than a path merely absent from a revision that does
    /// resolve: every file still falls back to the worktree, but `pin_broken`
    /// says so, so the reader is not shown live code believing it is pinned.
    #[test]
    fn compute_walkthrough_files_with_an_unresolvable_revision_reports_the_broken_pin() {
        let dir = tempfile::tempdir().expect("tempdir");
        let root = dir.path();
        init_repo(root);
        write(root, "a.txt", "edited\n");
        commit_all(root, "base");
        let root = repo::discover(root).expect("discover");

        let files = ["a.txt".to_owned()];
        let read = Review::compute_walkthrough_files(
            &root,
            Some("0000000000000000000000000000000000dead"),
            ReadFirst::Pin,
            &files,
        );
        assert_eq!(
            read.contents.get("a.txt").map(String::as_str),
            Some("edited\n"),
            "still falls back to the worktree"
        );
        assert!(read.pin_broken, "the named revision does not resolve");
    }
}