diffler 0.9.0

Terminal code review for AI coding agents
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
//! The shared sidebar row vocabulary (`TreeRow`/`TreeNode`) and pure
//! directory-trie flattening, used by the diff sidebar and the status
//! sections. `visible_rows` turns a file list (repo-relative paths, in input
//! order) into visible rows honoring fold state: directories before files at
//! each level, input order preserved within a kind, folded directories hiding
//! their subtree. It only ever emits Dir and File rows; Section rows are
//! composed by the diff sidebar's review layout on top of the same vocabulary.
//! No rendering and no app state, so the navigation math is fully
//! unit-testable.

use std::collections::BTreeSet;

/// The review-mode bucket a section header stands for: files still needing
/// review, or files already marked viewed.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Bucket {
    ToReview,
    Viewed,
}

impl Bucket {
    pub fn label(self) -> &'static str {
        match self {
            Self::ToReview => "To review",
            Self::Viewed => "Viewed",
        }
    }
}

/// One node in a flattened tree row: a directory (carrying its full path as the
/// fold key, and the last path segment as its display name), a file (carrying
/// its index into the source path slice, and its basename), or a review-mode
/// bucket header. Sections are composed by the diff sidebar's review layout;
/// the trie flattening below never produces them.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum TreeNode {
    Dir {
        path: String,
        name: String,
    },
    File {
        index: usize,
        name: String,
    },
    Section {
        bucket: Bucket,
        count: usize,
        folded: bool,
    },
}

/// A flattened tree row: a node and its indentation depth (0 at the root).
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct TreeRow {
    pub depth: usize,
    pub node: TreeNode,
}

/// An entry under a directory while the trie is built, before flattening.
enum Entry {
    Dir(Node),
    File { index: usize, name: String },
}

/// A directory's children, kept in insertion order so input order survives
/// within a kind; directories are pulled ahead of files only at flatten time.
struct Node {
    path: String,
    name: String,
    children: Vec<Entry>,
}

impl Node {
    fn root() -> Self {
        Self {
            path: String::new(),
            name: String::new(),
            children: Vec::new(),
        }
    }

    /// Find the index of the child directory named `name`, creating it if
    /// absent. New directories carry the full path so they can serve as fold
    /// keys. Returning the index (not a reference) lets the caller re-borrow
    /// `children` to descend, keeping the build panic-free.
    fn dir_child_index(&mut self, name: &str) -> usize {
        if let Some(position) = self
            .children
            .iter()
            .position(|child| matches!(child, Entry::Dir(node) if node.name == name))
        {
            return position;
        }
        let path = if self.path.is_empty() {
            name.to_owned()
        } else {
            format!("{}/{name}", self.path)
        };
        self.children.push(Entry::Dir(Node {
            path,
            name: name.to_owned(),
            children: Vec::new(),
        }));
        self.children.len() - 1
    }
}

/// Insert one file path (its components) under `root`, recording the index it
/// occupies in the source slice on the leaf.
fn insert(root: &mut Node, path: &str, index: usize) {
    let mut node = root;
    let mut components = path.split('/').peekable();
    while let Some(component) = components.next() {
        if components.peek().is_none() {
            node.children.push(Entry::File {
                index,
                name: component.to_owned(),
            });
            return;
        }
        let child = node.dir_child_index(component);
        let Some(Entry::Dir(next)) = node.children.get_mut(child) else {
            return;
        };
        node = next;
    }
}

/// Append a node's children to `rows`, directories first then files, recursing
/// into expanded directories. A folded directory contributes its own row but
/// none of its descendants.
/// Collapse a chain of single-directory children into one row, neo-tree style:
/// `a/b/c` where each level holds exactly one subdirectory becomes a single
/// `a/b/c` node. Returns the joined display name and the deepest node (whose
/// path is the fold key and whose children are rendered beneath the row). The
/// chain stops at the first directory that holds a file or more than one child.
fn collapse_chain(dir: &Node) -> (String, &Node) {
    let mut name = dir.name.clone();
    let mut node = dir;
    while node.children.len() == 1 {
        let Some(Entry::Dir(only)) = node.children.first() else {
            break;
        };
        name.push('/');
        name.push_str(&only.name);
        node = only;
    }
    (name, node)
}

fn flatten(node: &Node, depth: usize, folded: &BTreeSet<String>, rows: &mut Vec<TreeRow>) {
    for child in &node.children {
        if let Entry::Dir(dir) = child {
            let (name, deepest) = collapse_chain(dir);
            rows.push(TreeRow {
                depth,
                node: TreeNode::Dir {
                    path: deepest.path.clone(),
                    name,
                },
            });
            if !folded.contains(&deepest.path) {
                flatten(deepest, depth + 1, folded, rows);
            }
        }
    }
    for child in &node.children {
        if let Entry::File { index, name } = child {
            rows.push(TreeRow {
                depth,
                node: TreeNode::File {
                    index: *index,
                    name: name.clone(),
                },
            });
        }
    }
}

/// Build the flattened, fold-respecting visible rows for `paths` (each a
/// file's repo-relative path, in input order). `folded` holds folded directory
/// paths. Directories are sorted before files at each level; entries keep input
/// order within a kind. A directory not in `folded` is expanded.
pub fn visible_rows(paths: &[&str], folded: &BTreeSet<String>) -> Vec<TreeRow> {
    let mut root = Node::root();
    for (index, path) in paths.iter().enumerate() {
        insert(&mut root, path, index);
    }
    let mut rows = Vec::new();
    flatten(&root, 0, folded, &mut rows);
    rows
}

/// The flat-list rows for `paths`: one `File` row per entry, depth 0, full
/// path as its name, index into the source slice. A degenerate tree (no
/// `Dir` rows) so callers can drive the same cursor and file-navigation
/// logic over the flat list and the tree layout alike.
pub fn flat_rows(paths: &[&str]) -> Vec<TreeRow> {
    paths
        .iter()
        .enumerate()
        .map(|(index, path)| TreeRow {
            depth: 0,
            node: TreeNode::File {
                index,
                name: (*path).to_owned(),
            },
        })
        .collect()
}

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

    fn no_folds() -> BTreeSet<String> {
        BTreeSet::new()
    }

    /// Compact `(depth, kind, name)` view of a row for terse assertions.
    fn shape(row: &TreeRow) -> (usize, &'static str, String) {
        match &row.node {
            TreeNode::Dir { name, .. } => (row.depth, "dir", name.clone()),
            TreeNode::File { name, .. } => (row.depth, "file", name.clone()),
            TreeNode::Section { bucket, .. } => (row.depth, "section", bucket.label().to_owned()),
        }
    }

    fn shapes(rows: &[TreeRow]) -> Vec<(usize, &'static str, String)> {
        rows.iter().map(shape).collect()
    }

    #[test]
    fn single_directory_chains_collapse_into_one_row() {
        // a/b/c/d each hold exactly one subdirectory → one joined row
        let rows = visible_rows(&["a/b/c/d/file.rs"], &no_folds());
        assert_eq!(
            shapes(&rows),
            vec![
                (0, "dir", "a/b/c/d".to_owned()),
                (1, "file", "file.rs".to_owned()),
            ]
        );
    }

    #[test]
    fn a_chain_stops_collapsing_where_a_directory_branches() {
        // top/ holds one dir (mid/) → collapses to top/mid; mid/ branches
        // (a dir and a file) so it stops there
        let rows = visible_rows(&["top/mid/sub/x.rs", "top/mid/y.rs"], &no_folds());
        assert_eq!(
            shapes(&rows),
            vec![
                (0, "dir", "top/mid".to_owned()),
                (1, "dir", "sub".to_owned()),
                (2, "file", "x.rs".to_owned()),
                (1, "file", "y.rs".to_owned()),
            ]
        );
    }

    #[test]
    fn folding_a_collapsed_chain_hides_its_file_via_the_deepest_path() {
        let mut folded = no_folds();
        folded.insert("a/b/c/d".to_owned());
        let rows = visible_rows(&["a/b/c/d/file.rs"], &folded);
        assert_eq!(shapes(&rows), vec![(0, "dir", "a/b/c/d".to_owned())]);
    }

    #[test]
    fn nested_paths_produce_dir_then_file_rows_in_depth_order() {
        let rows = visible_rows(&["src/app/diff.rs", "src/lib.rs"], &no_folds());
        assert_eq!(
            shapes(&rows),
            vec![
                (0, "dir", "src".to_owned()),
                (1, "dir", "app".to_owned()),
                (2, "file", "diff.rs".to_owned()),
                (1, "file", "lib.rs".to_owned()),
            ]
        );
    }

    #[test]
    fn a_shared_directory_appears_once_for_many_files() {
        let rows = visible_rows(&["src/a.rs", "src/b.rs", "src/c.rs"], &no_folds());
        let dirs = rows
            .iter()
            .filter(|r| matches!(r.node, TreeNode::Dir { .. }))
            .count();
        assert_eq!(dirs, 1, "src/ collapses to a single dir row");
        assert_eq!(
            shapes(&rows),
            vec![
                (0, "dir", "src".to_owned()),
                (1, "file", "a.rs".to_owned()),
                (1, "file", "b.rs".to_owned()),
                (1, "file", "c.rs".to_owned()),
            ]
        );
    }

    #[test]
    fn dirs_sort_before_files_with_stable_order_within_a_kind() {
        // input order: a root file, then a dir's file, then another root file
        let rows = visible_rows(&["z_root.rs", "pkg/inner.rs", "a_root.rs"], &no_folds());
        assert_eq!(
            shapes(&rows),
            vec![
                (0, "dir", "pkg".to_owned()),
                (1, "file", "inner.rs".to_owned()),
                // root files keep their input order, after the dir
                (0, "file", "z_root.rs".to_owned()),
                (0, "file", "a_root.rs".to_owned()),
            ]
        );
    }

    #[test]
    fn folding_a_dir_hides_its_subtree_but_keeps_its_row() {
        let mut folded = BTreeSet::new();
        folded.insert("src".to_owned());
        let rows = visible_rows(&["src/app/diff.rs", "src/lib.rs", "top.rs"], &folded);
        assert_eq!(
            shapes(&rows),
            vec![
                (0, "dir", "src".to_owned()),
                (0, "file", "top.rs".to_owned()),
            ],
            "folded src/ shows its row only, its files and subdirs hidden"
        );
    }

    #[test]
    fn folding_an_inner_dir_hides_only_that_subtree() {
        let mut folded = BTreeSet::new();
        folded.insert("src/app".to_owned());
        let rows = visible_rows(&["src/app/diff.rs", "src/lib.rs"], &folded);
        assert_eq!(
            shapes(&rows),
            vec![
                (0, "dir", "src".to_owned()),
                (1, "dir", "app".to_owned()),
                (1, "file", "lib.rs".to_owned()),
            ],
            "src/app is folded; src itself stays expanded"
        );
    }

    #[test]
    fn root_level_files_sit_at_depth_zero() {
        let rows = visible_rows(&["a.rs", "b.rs"], &no_folds());
        assert_eq!(
            shapes(&rows),
            vec![
                (0, "file", "a.rs".to_owned()),
                (0, "file", "b.rs".to_owned()),
            ]
        );
    }

    #[test]
    fn a_single_file_is_one_row() {
        let rows = visible_rows(&["only.rs"], &no_folds());
        assert_eq!(rows.len(), 1);
        assert_eq!(shape(&rows[0]), (0, "file", "only.rs".to_owned()));
    }

    #[test]
    fn empty_input_is_no_rows() {
        assert!(visible_rows(&[], &no_folds()).is_empty());
    }

    #[test]
    fn flat_rows_is_one_file_row_per_path_at_depth_zero() {
        let rows = flat_rows(&["src/lib.rs", "top.rs"]);
        assert_eq!(
            shapes(&rows),
            vec![
                (0, "file", "src/lib.rs".to_owned()),
                (0, "file", "top.rs".to_owned()),
            ]
        );
    }

    #[test]
    fn identical_basenames_in_different_dirs_keep_their_own_indices() {
        let paths = ["a/mod.rs", "b/mod.rs"];
        let rows = visible_rows(&paths, &no_folds());
        let files: Vec<(usize, &str)> = rows
            .iter()
            .filter_map(|r| match &r.node {
                TreeNode::File { index, name } => Some((*index, name.as_str())),
                TreeNode::Dir { .. } | TreeNode::Section { .. } => None,
            })
            .collect();
        assert_eq!(files, vec![(0, "mod.rs"), (1, "mod.rs")]);
    }

    #[test]
    fn file_index_points_back_into_the_source_slice() {
        let paths = ["src/lib.rs", "top.rs", "src/app/diff.rs"];
        let rows = visible_rows(&paths, &no_folds());
        for row in &rows {
            if let TreeNode::File { index, name } = &row.node {
                let basename = paths[*index].rsplit('/').next().unwrap();
                assert_eq!(name, basename, "index {index} addresses its own path");
            }
        }
    }
}