fruit 0.2.0

Tree but just the juicy bits
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
//! Directory tree walking logic

use std::path::{Path, PathBuf};

use glob::Pattern;
use serde::Serialize;

use crate::comments::extract_first_comment;
use crate::git::{GitFilter, GitignoreFilter};

/// File filter that can use either gitignore patterns or git tracking status.
pub enum FileFilter {
    /// Filter based on .gitignore patterns (default)
    Gitignore(GitignoreFilter),
    /// Filter based on git tracking status (--tracked mode)
    GitTracked(GitFilter),
}

impl FileFilter {
    /// Check if a path should be included.
    pub fn is_included(&self, path: &Path) -> bool {
        match self {
            FileFilter::Gitignore(f) => f.is_included(path),
            FileFilter::GitTracked(f) => f.is_tracked(path),
        }
    }
}

/// TreeNode for JSON output - still builds full tree in memory.
/// For large repos, use StreamingWalker instead for console output.
#[derive(Debug, Clone, Serialize)]
#[serde(tag = "type", rename_all = "lowercase")]
pub enum TreeNode {
    File {
        name: String,
        path: PathBuf,
        #[serde(skip_serializing_if = "Option::is_none")]
        comment: Option<String>,
    },
    Dir {
        name: String,
        path: PathBuf,
        children: Vec<TreeNode>,
    },
}

impl TreeNode {
    pub fn name(&self) -> &str {
        match self {
            TreeNode::File { name, .. } => name,
            TreeNode::Dir { name, .. } => name,
        }
    }

    pub fn is_dir(&self) -> bool {
        matches!(self, TreeNode::Dir { .. })
    }
}

#[derive(Debug, Clone, Default)]
pub struct WalkerConfig {
    pub show_all: bool,
    pub max_depth: Option<usize>,
    pub dirs_only: bool,
    pub extract_comments: bool,
    pub ignore_patterns: Vec<String>,
}

pub struct TreeWalker {
    config: WalkerConfig,
    filter: Option<FileFilter>,
}

impl TreeWalker {
    pub fn new(config: WalkerConfig) -> Self {
        Self {
            config,
            filter: None,
        }
    }

    pub fn with_filter(mut self, filter: FileFilter) -> Self {
        self.filter = Some(filter);
        self
    }

    /// Legacy method for backwards compatibility - use with_filter instead.
    pub fn with_git_filter(self, filter: GitFilter) -> Self {
        self.with_filter(FileFilter::GitTracked(filter))
    }

    /// Set gitignore-based filtering (default behavior).
    pub fn with_gitignore_filter(self, filter: GitignoreFilter) -> Self {
        self.with_filter(FileFilter::Gitignore(filter))
    }

    pub fn walk(&self, root: &Path) -> Option<TreeNode> {
        self.walk_dir(root, 0)
    }

    fn walk_dir(&self, path: &Path, depth: usize) -> Option<TreeNode> {
        // Skip symlinks to prevent infinite loops and directory traversal issues
        if path.is_symlink() {
            return None;
        }

        let at_max_depth = self.config.max_depth.map_or(false, |max| depth >= max);

        let name = path
            .file_name()
            .map(|s| s.to_string_lossy().to_string())
            .unwrap_or_else(|| ".".to_string());

        if path.is_file() {
            if self.config.dirs_only {
                return None;
            }
            if !self.should_include(path) {
                return None;
            }
            let comment = if self.config.extract_comments {
                extract_first_comment(path)
            } else {
                None
            };
            return Some(TreeNode::File {
                name,
                path: path.to_path_buf(),
                comment,
            });
        }

        if !path.is_dir() {
            return None;
        }

        // If at max depth, return the directory but don't descend
        if at_max_depth {
            return Some(TreeNode::Dir {
                name,
                path: path.to_path_buf(),
                children: Vec::new(),
            });
        }

        let mut children = Vec::new();
        let entries = match std::fs::read_dir(path) {
            Ok(e) => e,
            Err(_) => return None,
        };

        let mut entries: Vec<_> = entries.filter_map(|e| e.ok()).collect();
        entries.sort_by(|a, b| a.file_name().cmp(&b.file_name()));

        for entry in entries {
            let entry_path = entry.path();

            if self.should_ignore(&entry_path) {
                continue;
            }

            if let Some(node) = self.walk_dir(&entry_path, depth + 1) {
                // Skip empty directories (but only if not in dirs_only mode
                // and not showing a depth-limited directory)
                if let TreeNode::Dir {
                    children: ref c, ..
                } = node
                {
                    // In dirs_only mode, always show directories
                    // Otherwise, skip truly empty directories (those with no tracked files)
                    if c.is_empty()
                        && !self.config.dirs_only
                        && !self.has_included_files(&entry_path)
                    {
                        continue;
                    }
                }
                children.push(node);
            }
        }

        Some(TreeNode::Dir {
            name,
            path: path.to_path_buf(),
            children,
        })
    }

    fn has_included_files(&self, path: &Path) -> bool {
        if let Some(ref filter) = self.filter {
            filter.is_included(path)
        } else {
            // Without filter, assume directory has content
            true
        }
    }

    fn should_include(&self, path: &Path) -> bool {
        if self.config.show_all {
            return true;
        }
        if let Some(ref filter) = self.filter {
            return filter.is_included(path);
        }
        true
    }

    fn should_ignore(&self, path: &Path) -> bool {
        let name = path
            .file_name()
            .map(|s| s.to_string_lossy().to_string())
            .unwrap_or_default();

        // Always ignore .git directory
        if name == ".git" {
            return true;
        }

        // Check custom ignore patterns
        for pattern in &self.config.ignore_patterns {
            if name == *pattern || glob_match(pattern, &name) {
                return true;
            }
        }

        false
    }
}

fn glob_match(pattern: &str, name: &str) -> bool {
    Pattern::new(pattern)
        .map(|p| p.matches(name))
        .unwrap_or(false)
}

/// Streaming tree walker that outputs directly without building tree in memory.
/// Uses O(depth) memory instead of O(files) for the tree structure.
pub struct StreamingWalker {
    config: WalkerConfig,
    filter: Option<FileFilter>,
}

/// Callback for streaming output - receives name, comment, is_dir, is_last, prefix
pub trait StreamingOutput {
    fn output_node(
        &mut self,
        name: &str,
        comment: Option<&str>,
        is_dir: bool,
        is_last: bool,
        prefix: &str,
        is_root: bool,
    ) -> std::io::Result<()>;

    fn finish(&mut self, dir_count: usize, file_count: usize) -> std::io::Result<()>;
}

impl StreamingWalker {
    pub fn new(config: WalkerConfig) -> Self {
        Self {
            config,
            filter: None,
        }
    }

    pub fn with_filter(mut self, filter: FileFilter) -> Self {
        self.filter = Some(filter);
        self
    }

    /// Legacy method for backwards compatibility - use with_filter instead.
    pub fn with_git_filter(self, filter: GitFilter) -> Self {
        self.with_filter(FileFilter::GitTracked(filter))
    }

    /// Set gitignore-based filtering (default behavior).
    pub fn with_gitignore_filter(self, filter: GitignoreFilter) -> Self {
        self.with_filter(FileFilter::Gitignore(filter))
    }

    /// Walk and stream output - returns (dir_count, file_count)
    pub fn walk_streaming<O: StreamingOutput>(
        &self,
        root: &Path,
        output: &mut O,
    ) -> std::io::Result<Option<(usize, usize)>> {
        match self.walk_dir_streaming(root, 0, "", true, output) {
            Ok(Some((d, f))) => {
                output.finish(d, f)?;
                Ok(Some((d, f)))
            }
            Ok(None) => Ok(None),
            Err(e) => Err(e),
        }
    }

    fn walk_dir_streaming<O: StreamingOutput>(
        &self,
        path: &Path,
        depth: usize,
        prefix: &str,
        is_root: bool,
        output: &mut O,
    ) -> std::io::Result<Option<(usize, usize)>> {
        // Skip symlinks to prevent infinite loops and directory traversal issues
        if path.is_symlink() {
            return Ok(None);
        }

        let at_max_depth = self.config.max_depth.map_or(false, |max| depth >= max);

        // Files are handled by their parent directory iteration
        if path.is_file() || !path.is_dir() {
            return Ok(None);
        }

        // Collect and sort entries
        let entries = match std::fs::read_dir(path) {
            Ok(e) => e,
            Err(_) => return Ok(None),
        };

        let mut entries: Vec<_> = entries.filter_map(|e| e.ok()).collect();
        entries.sort_by(|a, b| a.file_name().cmp(&b.file_name()));

        // Filter entries first to know which ones will be included
        let filtered_entries: Vec<_> = entries
            .into_iter()
            .filter(|entry| {
                let entry_path = entry.path();
                !self.should_ignore(&entry_path)
            })
            .collect();

        // Get the directory name for output
        let name = path
            .file_name()
            .map(|s| s.to_string_lossy().to_string())
            .unwrap_or_else(|| ".".to_string());

        // If at max depth, output directory but don't descend
        if at_max_depth && !is_root {
            return Ok(Some((0, 0)));
        }

        // Output this directory (root handled specially)
        if is_root {
            output.output_node(&name, None, true, true, prefix, true)?;
        }

        let mut dir_count = 0usize;
        let mut file_count = 0usize;

        // We need to peek ahead to know which entries will actually produce output
        // to determine is_last correctly
        let mut valid_entries: Vec<(std::fs::DirEntry, bool, Option<String>)> = Vec::new();

        for entry in filtered_entries {
            let entry_path = entry.path();

            if entry_path.is_file() {
                if self.config.dirs_only {
                    continue;
                }
                if !self.should_include(&entry_path) {
                    continue;
                }
                let comment = if self.config.extract_comments {
                    extract_first_comment(&entry_path)
                } else {
                    None
                };
                valid_entries.push((entry, false, comment));
            } else if entry_path.is_dir() && !entry_path.is_symlink() {
                // Check if this directory has any content (or if we're in dirs_only mode)
                if self.config.dirs_only || self.has_included_files(&entry_path) {
                    valid_entries.push((entry, true, None));
                }
            }
        }

        let total = valid_entries.len();

        for (i, (entry, is_dir, comment)) in valid_entries.into_iter().enumerate() {
            let entry_path = entry.path();
            let entry_name = entry.file_name().to_string_lossy().to_string();
            let is_last = i == total - 1;

            // Calculate the prefix for this entry's children
            // (based on whether this entry is last among its siblings)
            let new_prefix = if is_last {
                format!("{}    ", prefix)
            } else {
                format!("{}", prefix)
            };

            if is_dir {
                output.output_node(&entry_name, None, true, is_last, prefix, false)?;
                dir_count += 1;

                // Recurse
                if let Ok(Some((d, f))) =
                    self.walk_dir_streaming(&entry_path, depth + 1, &new_prefix, false, output)
                {
                    dir_count += d;
                    file_count += f;
                }
            } else {
                output.output_node(
                    &entry_name,
                    comment.as_deref(),
                    false,
                    is_last,
                    prefix,
                    false,
                )?;
                file_count += 1;
            }
        }

        Ok(Some((dir_count, file_count)))
    }

    fn has_included_files(&self, path: &Path) -> bool {
        if let Some(ref filter) = self.filter {
            filter.is_included(path)
        } else {
            // Without filter, assume directory has content
            true
        }
    }

    fn should_include(&self, path: &Path) -> bool {
        if self.config.show_all {
            return true;
        }
        if let Some(ref filter) = self.filter {
            return filter.is_included(path);
        }
        true
    }

    fn should_ignore(&self, path: &Path) -> bool {
        let name = path
            .file_name()
            .map(|s| s.to_string_lossy().to_string())
            .unwrap_or_default();

        // Always ignore .git directory
        if name == ".git" {
            return true;
        }

        // Check custom ignore patterns
        for pattern in &self.config.ignore_patterns {
            if name == *pattern || glob_match(pattern, &name) {
                return true;
            }
        }

        false
    }
}

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

    #[test]
    fn test_glob_match() {
        // Basic patterns
        assert!(glob_match("*.rs", "main.rs"));
        assert!(glob_match("*.rs", "lib.rs"));
        assert!(!glob_match("*.rs", "main.py"));
        assert!(glob_match("test*", "test_foo"));
        assert!(!glob_match("test*", "foo_test"));
        assert!(glob_match("exact", "exact"));
        assert!(!glob_match("exact", "notexact"));

        // Single character wildcard
        assert!(glob_match("test?.rs", "test1.rs"));
        assert!(glob_match("test?.rs", "testa.rs"));
        assert!(!glob_match("test?.rs", "test12.rs"));

        // Character classes
        assert!(glob_match("[abc].txt", "a.txt"));
        assert!(glob_match("[abc].txt", "b.txt"));
        assert!(!glob_match("[abc].txt", "d.txt"));

        // Character ranges
        assert!(glob_match("[a-z].txt", "x.txt"));
        assert!(!glob_match("[a-z].txt", "X.txt"));
    }
}