bmrk 0.4.0

A fast TUI for directory navigation and bookmark management
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
use anyhow::Result;
use std::cell::RefCell;
use std::fs;
use std::path::PathBuf;
use std::rc::Rc;

pub type TreeNodeRef = Rc<RefCell<TreeNode>>;

/// Returns true if a file or directory name should be treated as hidden — currently just
/// "starts with a dot", matching standard Unix dotfile convention. Single source of truth for
/// this rule across `tree_node.rs`, `search.rs`, and `quick_jump.rs` (`.debug/BDP.md` Part 5,
/// Finding #10 — the same check used to be hand-duplicated six times).
pub(crate) fn is_hidden_name(name: &str) -> bool {
    name.starts_with('.')
}

pub struct TreeNode {
    pub path: PathBuf,
    pub name: String,
    pub is_dir: bool,
    pub is_expanded: bool,
    pub depth: usize,
    pub children: Vec<TreeNodeRef>,
    pub has_error: bool,               // Indicates read/access errors
    pub error_message: Option<String>, // Optional error description
    /// Whether this directory has any visible children under the current settings.
    /// `None` means unknown (not yet probed); `Some(false)` means leaf — do not show `>`.
    pub has_children: Option<bool>,
    is_sorted: bool, // Cache flag: true if children are already sorted
}

impl TreeNode {
    pub fn new(path: PathBuf, depth: usize) -> Result<Self> {
        let name = path
            .file_name()
            .and_then(|n| n.to_str())
            .unwrap_or("")
            .to_string();

        let is_dir = path.is_dir();

        Ok(TreeNode {
            path,
            name,
            is_dir,
            is_expanded: false,
            depth,
            children: Vec::new(),
            has_error: false,
            error_message: None,
            has_children: None,
            is_sorted: false,
        })
    }

    /// Probe whether this directory has any visible children under the given settings,
    /// without fully loading children. Result is cached in `has_children`.
    /// Hidden-file filtering matches `load_children` via the shared [`is_hidden_name`] helper.
    pub fn probe_has_children(
        &mut self,
        show_files: bool,
        show_hidden: bool,
        follow_symlinks: bool,
    ) {
        if !self.is_dir {
            self.has_children = Some(false);
            return;
        }
        let entries = match fs::read_dir(&self.path) {
            Ok(e) => e,
            Err(e) => {
                self.has_error = true;
                self.error_message = Some(format!("Cannot read: {}", e));
                return;
            }
        };
        for entry in entries.flatten() {
            let path = entry.path();
            if !follow_symlinks {
                if let Ok(meta) = fs::symlink_metadata(&path) {
                    if meta.is_symlink() {
                        continue;
                    }
                }
            }
            if !show_hidden {
                if let Some(name) = path.file_name().and_then(|n| n.to_str()) {
                    if is_hidden_name(name) {
                        continue;
                    }
                }
            }
            if path.is_dir() || show_files {
                self.has_children = Some(true);
                return;
            }
        }
        self.has_children = Some(false);
    }

    pub fn load_children(
        &mut self,
        show_files: bool,
        show_hidden: bool,
        follow_symlinks: bool,
    ) -> Result<()> {
        // If children are already loaded and sorted, skip
        if !self.is_dir || (!self.children.is_empty() && self.is_sorted) {
            return Ok(());
        }

        // If we're reloading (children exist but not sorted), clear them first
        if !self.children.is_empty() {
            self.children.clear();
            self.is_sorted = false;
            self.has_children = None;
        }

        // Try to read directory
        let entries = match fs::read_dir(&self.path) {
            Ok(entries) => entries,
            Err(e) => {
                // Mark this node as having an error
                self.has_error = true;
                self.error_message = Some(format!("Cannot read: {}", e));
                return Ok(()); // Don't propagate error, just mark the node
            }
        };

        let mut error_count = 0;
        let mut skipped_entries = Vec::new();

        // Process entries, tracking errors
        for entry in entries {
            match entry {
                Ok(entry) => {
                    let path = entry.path();

                    // Check if entry is a symlink and whether to follow it
                    if !follow_symlinks {
                        if let Ok(metadata) = fs::symlink_metadata(&path) {
                            if metadata.is_symlink() {
                                continue; // Skip symlinks if follow_symlinks is false
                            }
                        }
                    }

                    let is_dir = path.is_dir();

                    // Check if file/directory is hidden (starts with .)
                    if !show_hidden {
                        if let Some(name) = path.file_name().and_then(|n| n.to_str()) {
                            if is_hidden_name(name) {
                                continue; // Skip hidden files/directories
                            }
                        }
                    }

                    // Show directories always, files only if show_files == true
                    if is_dir || show_files {
                        match TreeNode::new(path.clone(), self.depth + 1) {
                            Ok(node) => {
                                self.children.push(Rc::new(RefCell::new(node)));
                            }
                            Err(e) => {
                                error_count += 1;
                                skipped_entries.push(format!(
                                    "{}: {}",
                                    path.file_name().unwrap_or_default().to_string_lossy(),
                                    e
                                ));
                            }
                        }
                    }
                }
                Err(e) => {
                    error_count += 1;
                    skipped_entries.push(format!("unknown entry: {}", e));
                }
            }
        }

        // If we had errors, mark the node and store summary
        if error_count > 0 {
            self.has_error = true;
            if error_count <= 3 {
                self.error_message = Some(skipped_entries.join(", "));
            } else {
                self.error_message = Some(format!("{} entries inaccessible", error_count));
            }
        }

        // Sort: directories first, then files, sorted by name within each group
        self.children.sort_by(|a, b| {
            let a_borrowed = a.borrow();
            let b_borrowed = b.borrow();
            match (a_borrowed.is_dir, b_borrowed.is_dir) {
                (true, false) => std::cmp::Ordering::Less,
                (false, true) => std::cmp::Ordering::Greater,
                _ => a_borrowed.name.cmp(&b_borrowed.name),
            }
        });

        // Mark as sorted so we don't re-sort on next load
        self.is_sorted = true;

        // Update has_children for self based on loaded children
        self.has_children = Some(!self.children.is_empty());

        // Each child's own `has_children` is left `None` (unknown) here rather than eagerly
        // probed — probing every child turns one directory expansion into N+1 blocking
        // `read_dir` calls for a wide directory (`.debug/BDP.md` Part 5, Finding #6). Probing is
        // instead done lazily, only for rows about to be rendered, in `ui.rs`'s tree-render loop.

        Ok(())
    }

    pub fn toggle_expand(
        &mut self,
        show_files: bool,
        show_hidden: bool,
        follow_symlinks: bool,
    ) -> Result<()> {
        if !self.is_dir {
            return Ok(());
        }

        // Leaf directories (confirmed empty) cannot be expanded
        if self.has_children == Some(false) {
            return Ok(());
        }

        if self.is_expanded {
            self.is_expanded = false;
        } else {
            self.load_children(show_files, show_hidden, follow_symlinks)?;
            // Only expand if no access error occurred AND there's something to show. The second
            // check matters specifically for a node whose `has_children` was still `None`
            // (unprobed) when this ran — since Step 9 (`.debug/BDP.md` Part 5, Finding #6) made
            // that reachable here: rapid keypresses are drained in a batch before the next
            // render, so a freshly-selected row can still be unprobed when `l`/`Enter` toggles
            // it. `load_children` above always resolves `has_children` for real by the time we
            // get here, so if it turns out `Some(false)` (a genuine leaf), skip setting
            // `is_expanded` — doing it anyway would land on `is_expanded == true` +
            // `has_children == Some(false)` simultaneously, which the leaf guard above then
            // blocks from ever being undone again.
            if !self.has_error && self.has_children != Some(false) {
                self.is_expanded = true;
            }
        }

        Ok(())
    }
}

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

    fn make_dir_node(path: PathBuf) -> TreeNode {
        TreeNode::new(path, 0).expect("TreeNode::new failed")
    }

    #[test]
    fn is_hidden_name_matches_dotfile_convention() {
        assert!(is_hidden_name("."));
        assert!(is_hidden_name(".."));
        assert!(is_hidden_name(".git"));
        assert!(is_hidden_name(".hidden"));
        assert!(!is_hidden_name("normal"));
        assert!(!is_hidden_name(""));
    }

    #[test]
    fn leaf_dir_has_children_false_after_load() {
        let tmp = TempDir::new().unwrap();
        let mut node = make_dir_node(tmp.path().to_path_buf());
        node.load_children(false, false, false).unwrap();
        assert_eq!(
            node.has_children,
            Some(false),
            "empty dir should be Some(false)"
        );
    }

    #[test]
    fn dir_with_subdir_has_children_true_after_load() {
        let tmp = TempDir::new().unwrap();
        std::fs::create_dir(tmp.path().join("sub")).unwrap();
        let mut node = make_dir_node(tmp.path().to_path_buf());
        node.load_children(false, false, false).unwrap();
        assert_eq!(node.has_children, Some(true));
    }

    #[test]
    fn child_leaf_gets_has_children_false_after_explicit_probe() {
        // `load_children` no longer probes children itself (Finding #6) — a child's
        // `has_children` starts unknown and is only resolved by an explicit probe, which
        // `ui.rs`'s render loop now does lazily for on-screen rows.
        let tmp = TempDir::new().unwrap();
        let child = tmp.path().join("leaf");
        std::fs::create_dir(&child).unwrap();

        let mut root = make_dir_node(tmp.path().to_path_buf());
        root.load_children(false, false, false).unwrap();
        assert_eq!(
            root.children[0].borrow().has_children,
            None,
            "load_children must leave children unprobed"
        );

        root.children[0]
            .borrow_mut()
            .probe_has_children(false, false, false);
        assert_eq!(
            root.children[0].borrow().has_children,
            Some(false),
            "an explicit probe must still correctly identify a leaf child"
        );
    }

    #[test]
    fn child_with_subdir_gets_has_children_true_after_explicit_probe() {
        let tmp = TempDir::new().unwrap();
        let child = tmp.path().join("inner");
        std::fs::create_dir(&child).unwrap();
        std::fs::create_dir(child.join("nested")).unwrap();

        let mut root = make_dir_node(tmp.path().to_path_buf());
        root.load_children(false, false, false).unwrap();
        assert_eq!(
            root.children[0].borrow().has_children,
            None,
            "load_children must leave children unprobed"
        );

        root.children[0]
            .borrow_mut()
            .probe_has_children(false, false, false);
        assert_eq!(root.children[0].borrow().has_children, Some(true));
    }

    #[test]
    fn load_children_no_longer_probes_children_eagerly() {
        let tmp = TempDir::new().unwrap();
        for i in 0..5 {
            std::fs::create_dir(tmp.path().join(format!("sub{i}"))).unwrap();
        }

        let mut root = make_dir_node(tmp.path().to_path_buf());
        root.load_children(false, false, false).unwrap();

        assert_eq!(root.children.len(), 5);
        for child in &root.children {
            assert_eq!(
                child.borrow().has_children,
                None,
                "load_children must not eagerly probe any child"
            );
        }
    }

    #[test]
    fn toggle_expand_does_not_expand_leaf_dir() {
        let tmp = TempDir::new().unwrap();
        let mut node = make_dir_node(tmp.path().to_path_buf());
        // Probe first — since Step 9 (`.debug/BDP.md` Part 5, Finding #6) a node's own probe is
        // no longer something its parent does automatically; the caller decides when it happens.
        node.probe_has_children(false, false, false);
        assert_eq!(node.has_children, Some(false));

        node.toggle_expand(false, false, false).unwrap();
        assert!(!node.is_expanded, "leaf dir must not expand");
    }

    #[test]
    fn toggle_expand_on_unprobed_leaf_does_not_get_stuck_expanded() {
        // Regression test: `toggle_expand` can now run on a node whose `has_children` is still
        // `None` (unprobed) — since Step 9, rapid keypresses are drained in a batch before the
        // next render can probe a freshly-selected row. Expanding an unprobed node that turns
        // out to be a genuine leaf must not set `is_expanded = true`, since the leaf guard above
        // (`has_children == Some(false)`) would then block ever toggling it back off.
        let tmp = TempDir::new().unwrap();
        let mut node = make_dir_node(tmp.path().to_path_buf());
        assert_eq!(node.has_children, None, "node must start unprobed");

        node.toggle_expand(false, false, false).unwrap();

        assert_eq!(
            node.has_children,
            Some(false),
            "load_children (called by toggle_expand) must resolve has_children for real"
        );
        assert!(
            !node.is_expanded,
            "an unprobed node that turns out to be a leaf must not end up expanded"
        );
    }

    #[test]
    fn toggle_expand_expands_dir_with_subdir() {
        let tmp = TempDir::new().unwrap();
        std::fs::create_dir(tmp.path().join("child")).unwrap();
        let mut node = make_dir_node(tmp.path().to_path_buf());
        node.probe_has_children(false, false, false);
        assert_eq!(node.has_children, Some(true));

        node.toggle_expand(false, false, false).unwrap();
        assert!(node.is_expanded);
    }

    #[cfg(unix)]
    #[test]
    fn probe_marks_unreadable_dir_as_error() {
        use std::os::unix::fs::PermissionsExt;
        let tmp = TempDir::new().unwrap();
        let locked = tmp.path().join("locked");
        std::fs::create_dir(&locked).unwrap();
        std::fs::set_permissions(&locked, std::fs::Permissions::from_mode(0o000)).unwrap();

        let mut root = make_dir_node(tmp.path().to_path_buf());
        root.load_children(false, false, false).unwrap();

        let child_ref = root
            .children
            .iter()
            .find(|c| c.borrow().name == "locked")
            .expect("locked child must exist");
        // `load_children` no longer probes children itself (Finding #6) — probe explicitly,
        // as `ui.rs`'s render loop now does for on-screen rows, while permissions are still
        // locked down (probing after restoring them would find no error at all).
        child_ref
            .borrow_mut()
            .probe_has_children(false, false, false);

        // Restore permissions so TempDir cleanup doesn't fail
        std::fs::set_permissions(&locked, std::fs::Permissions::from_mode(0o755)).unwrap();

        let child = child_ref.borrow();
        assert!(child.has_error, "probe must mark unreadable dir as error");
        assert!(
            child.error_message.is_some(),
            "error_message must be set by probe"
        );
    }
}