Skip to main content

diffler_core/
review.rs

1//! Facade tying the VCS backend, session, and store together: the one
2//! entry point the TUI and MCP layers consume.
3
4use std::cell::OnceCell;
5use std::collections::{BTreeMap, HashMap};
6use std::path::{Path, PathBuf};
7
8use thiserror::Error;
9
10use crate::git::GitVcs;
11use crate::model::DiffModel;
12use crate::session::Session;
13use crate::source::ReviewSource;
14use crate::store::{self, StoreError};
15use crate::vcs::{StatusModel, Vcs, VcsError};
16
17#[derive(Debug, Error)]
18pub enum ReviewError {
19    #[error(transparent)]
20    Vcs(#[from] VcsError),
21    #[error(transparent)]
22    Store(#[from] StoreError),
23}
24
25pub struct Review {
26    pub repo_root: PathBuf,
27    pub vcs: Box<dyn Vcs>,
28    pub status: StatusModel,
29    /// HEAD vs workdir+index including untracked: the review view. Computed
30    /// lazily on first [`Review::model`] access — the status screen is the
31    /// initial view and never needs the whole working diff up front.
32    model: OnceCell<DiffModel>,
33    /// The working-tree review session, the default view.
34    pub session: Session,
35    /// Lazily-loaded sessions for non-working sources (commits, ranges), keyed
36    /// by [`ReviewSource::key`].
37    sources: HashMap<String, (ReviewSource, Session)>,
38    /// Returned by [`Review::session_for`] for a source that has no review yet.
39    empty: Session,
40}
41
42impl Review {
43    /// Open the git backend, load the persisted session (if any), and compute
44    /// the status sections. The working-tree review diff is deferred until
45    /// first [`Review::model`] access. Diffs carry git's default hunk context.
46    pub fn open(repo_root: &Path) -> Result<Self, ReviewError> {
47        Self::open_with_context(repo_root, crate::git::DEFAULT_CONTEXT_LINES)
48    }
49
50    /// Like [`Review::open`] with a custom number of context lines around
51    /// diff hunks (config key `ui.context_lines`).
52    pub fn open_with_context(repo_root: &Path, context_lines: u32) -> Result<Self, ReviewError> {
53        let vcs: Box<dyn Vcs> = Box::new(GitVcs::open_with_context(repo_root, context_lines)?);
54        let status = vcs.status()?;
55        let session = store::load(repo_root)?;
56        Ok(Self {
57            repo_root: repo_root.to_path_buf(),
58            vcs,
59            status,
60            model: OnceCell::new(),
61            session,
62            sources: HashMap::new(),
63            empty: Session::default(),
64        })
65    }
66
67    /// The working-tree review diff, computed and cached on first access. A
68    /// backend error yields an empty diff rather than panicking; the next
69    /// [`Review::refresh`] gets another chance to compute it.
70    pub fn model(&self) -> &DiffModel {
71        self.model
72            .get_or_init(|| self.vcs.working_tree_diff().unwrap_or_default())
73    }
74
75    /// Mutable view of the working-tree review diff, computing it first if
76    /// needed. The TUI uses this to enrich a file with intra-line emphasis
77    /// just before rendering it.
78    pub fn model_mut(&mut self) -> &mut DiffModel {
79        self.model();
80        #[allow(clippy::expect_used)]
81        self.model.get_mut().expect("model just initialized")
82    }
83
84    /// Recompute status + diff (the watcher calls this on changes) and drop
85    /// viewed marks for files that changed or left the diff.
86    pub fn refresh(&mut self) -> Result<(), ReviewError> {
87        self.status = self.vcs.status()?;
88        let model = self.vcs.working_tree_diff()?;
89        self.session.reconcile(&model);
90        self.model = OnceCell::from(model);
91        Ok(())
92    }
93
94    pub fn save(&self) -> Result<(), ReviewError> {
95        store::save(&self.repo_root, &self.session)?;
96        Ok(())
97    }
98
99    /// Load a non-working source's session into the cache if not already there.
100    /// Call before reading via [`Review::session_for`] for that source.
101    pub fn ensure_source(&mut self, source: &ReviewSource) -> Result<(), ReviewError> {
102        if matches!(source, ReviewSource::WorkingTree) {
103            return Ok(());
104        }
105        let key = source.key();
106        if !self.sources.contains_key(&key) {
107            let session = store::load_source(&self.repo_root, source)?;
108            self.sources.insert(key, (source.clone(), session));
109        }
110        Ok(())
111    }
112
113    /// The session for a source. The working tree is always present; other
114    /// sources must be [`Review::ensure_source`]d first, else an empty session
115    /// is returned.
116    pub fn session_for(&self, source: &ReviewSource) -> &Session {
117        match source {
118            ReviewSource::WorkingTree => &self.session,
119            other => self
120                .sources
121                .get(&other.key())
122                .map_or(&self.empty, |(_, session)| session),
123        }
124    }
125
126    pub fn session_for_mut(&mut self, source: &ReviewSource) -> &mut Session {
127        match source {
128            ReviewSource::WorkingTree => &mut self.session,
129            other => {
130                &mut self
131                    .sources
132                    .entry(other.key())
133                    .or_insert_with(|| (other.clone(), Session::default()))
134                    .1
135            }
136        }
137    }
138
139    pub fn save_for(&self, source: &ReviewSource) -> Result<(), ReviewError> {
140        store::save_source(&self.repo_root, source, self.session_for(source))?;
141        Ok(())
142    }
143
144    /// Every review across all sources, in-memory state overriding disk, sorted
145    /// by source key. Powers the agent-facing aggregate feed.
146    pub fn all_reviews(&self) -> Result<Vec<(ReviewSource, Session)>, ReviewError> {
147        let mut by_key: BTreeMap<String, (ReviewSource, Session)> =
148            store::load_all(&self.repo_root)?
149                .into_iter()
150                .map(|(source, session)| (source.key(), (source, session)))
151                .collect();
152        by_key.insert(
153            ReviewSource::WorkingTree.key(),
154            (ReviewSource::WorkingTree, self.session.clone()),
155        );
156        for (key, (source, session)) in &self.sources {
157            by_key.insert(key.clone(), (source.clone(), session.clone()));
158        }
159        Ok(by_key.into_values().collect())
160    }
161
162    /// Whether the working-tree model has been computed yet.
163    #[cfg(test)]
164    fn model_is_cached(&self) -> bool {
165        self.model.get().is_some()
166    }
167}
168
169#[cfg(test)]
170mod tests {
171    use crate::repo;
172
173    use super::*;
174
175    #[allow(clippy::expect_used)]
176    fn write(root: &std::path::Path, rel: &str, content: &str) {
177        std::fs::write(root.join(rel), content).expect("write");
178    }
179
180    #[allow(clippy::expect_used)]
181    fn commit_all(root: &std::path::Path, message: &str) {
182        for args in [&["add", "-A"][..], &["commit", "-q", "-m", message][..]] {
183            let status = std::process::Command::new("git")
184                .arg("-C")
185                .arg(root)
186                .args(args)
187                .env("GIT_AUTHOR_NAME", "t")
188                .env("GIT_AUTHOR_EMAIL", "t@t")
189                .env("GIT_COMMITTER_NAME", "t")
190                .env("GIT_COMMITTER_EMAIL", "t@t")
191                .status()
192                .expect("git");
193            assert!(status.success(), "git {args:?}");
194        }
195    }
196
197    #[allow(clippy::expect_used)]
198    fn init_repo(root: &std::path::Path) {
199        let status = std::process::Command::new("git")
200            .arg("-C")
201            .arg(root)
202            .args(["init", "-q"])
203            .status()
204            .expect("git init");
205        assert!(status.success());
206    }
207
208    #[test]
209    fn open_defers_the_working_model_until_first_access() {
210        let dir = tempfile::tempdir().expect("tempdir");
211        let root = dir.path();
212        init_repo(root);
213        write(root, "a.py", "value = old\n");
214        commit_all(root, "base");
215        write(root, "a.py", "value = new\n");
216
217        let root = repo::discover(root).expect("discover");
218        let review = Review::open(&root).expect("open");
219        // the status sections are computed eagerly; the review model is not
220        assert!(
221            !review.model_is_cached(),
222            "open must not compute the working model"
223        );
224        assert_eq!(review.status.unstaged.files.len(), 1);
225
226        // first access computes it; it matches a fresh working_tree_diff
227        let lazy = review.model().clone();
228        assert!(review.model_is_cached(), "access caches the model");
229        let eager = review.vcs.working_tree_diff().expect("diff");
230        assert_eq!(lazy, eager, "lazy model equals the eager build");
231    }
232
233    #[test]
234    fn per_source_sessions_persist_independently_and_aggregate() {
235        let dir = tempfile::tempdir().expect("tempdir");
236        let root = dir.path();
237        init_repo(root);
238        write(root, "a.py", "value = old\n");
239        commit_all(root, "base");
240        write(root, "a.py", "value = new\n");
241
242        let root = repo::discover(root).expect("discover");
243        let mut review = Review::open(&root).expect("open");
244
245        let commit = crate::source::ReviewSource::commit("deadbeef");
246        review.ensure_source(&commit).expect("ensure");
247        review
248            .session_for_mut(&commit)
249            .mark_viewed("a.py", "hash-commit");
250        review.save_for(&commit).expect("save commit");
251        review.session.mark_viewed("a.py", "hash-working");
252        review.save().expect("save working");
253
254        // the same path means different things per source
255        assert!(review.session_for(&commit).is_viewed("a.py", "hash-commit"));
256        assert!(!review.session.is_viewed("a.py", "hash-commit"));
257
258        // a fresh open reloads each source from its own file
259        let mut reopened = Review::open(&root).expect("reopen");
260        reopened.ensure_source(&commit).expect("ensure");
261        assert!(
262            reopened
263                .session_for(&commit)
264                .is_viewed("a.py", "hash-commit")
265        );
266        assert!(reopened.session.is_viewed("a.py", "hash-working"));
267
268        let all = reopened.all_reviews().expect("all");
269        let keys: Vec<String> = all.iter().map(|(s, _)| s.key()).collect();
270        assert_eq!(keys, ["commit-deadbeef", "working"]);
271    }
272}