loctree 0.8.16

Structural code intelligence for AI agents. Scan once, query everything.
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
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
use std::collections::HashSet;
use std::io;
use std::path::{Path, PathBuf};

use serde_json::json;
use std::io::IsTerminal;

use crate::fs_utils::{
    GitIgnoreChecker, build_ignore_matchers, count_lines, is_allowed_hidden, should_ignore,
    sort_dir_entries,
};
use crate::types::{
    COLOR_RED, COLOR_RESET, Collectors, ColorMode, LargeEntry, LineEntry, Options, OutputMode,
    Stats,
};

/// List of common build artifact directory names that typically contain
/// millions of files and slow down tools like Spotlight.
const BUILD_ARTIFACT_DIRS: &[&str] = &[
    // JavaScript/Node.js
    "node_modules",
    ".pnpm-store",
    // PHP
    "vendor",
    // Python
    ".venv",
    "venv",
    "env",
    "ENV",
    // Rust
    "target",
    // General build outputs
    "dist",
    "build",
    "out",
    // Testing/Coverage
    "coverage",
    ".tox",
    ".mypy_cache",
    ".pytest_cache",
    // Java/Gradle
    ".gradle",
    // JavaScript bundlers
    ".parcel-cache",
    ".next",
    ".nuxt",
    ".turbo",
    ".cache",
    // Dart/Flutter
    ".dart_tool",
    // Terraform
    ".terraform",
    ".terraform.d",
    // iOS/macOS
    "Pods",
    "DerivedData",
    // React Native/Expo
    ".expo",
    ".expo-shared",
    // Svelte/Angular/Vercel/Serverless
    ".svelte-kit",
    ".angular",
    ".vercel",
    ".serverless",
];

#[allow(clippy::too_many_arguments, clippy::only_used_in_recursion)]
fn walk(
    dir: &Path,
    options: &Options,
    prefix_parts: &mut Vec<bool>,
    collectors: &mut Collectors,
    depth: usize,
    root: &Path,
    root_canon: &Path,
    git_checker: Option<&GitIgnoreChecker>,
    visited: &mut HashSet<PathBuf>,
) -> io::Result<bool> {
    let dir_canon = dir.canonicalize()?;
    if !dir_canon.starts_with(root_canon) {
        return Ok(false);
    }
    if !visited.insert(dir_canon.clone()) {
        return Ok(false);
    }

    // nosemgrep:rust.actix.path-traversal.tainted-path.tainted-path - dir path canonicalized and bounded to root_canon
    let mut dir_entries: Vec<_> = std::fs::read_dir(&dir_canon)?
        .filter_map(Result::ok)
        .filter(|entry| {
            let name = entry.file_name();
            let name_str = name.to_string_lossy();
            let is_hidden = name_str.starts_with('.');
            options.show_hidden || !is_hidden || is_allowed_hidden(&name_str)
        })
        .collect();

    sort_dir_entries(dir_entries.as_mut_slice());

    let len = dir_entries.len();
    let mut any_included = false;
    for (idx, entry) in dir_entries.into_iter().enumerate() {
        let path = entry.path();
        let is_last = idx + 1 == len;
        let mut prefix = String::new();
        for &has_more in prefix_parts.iter() {
            if has_more {
                prefix.push_str("│   ");
            } else {
                prefix.push_str("    ");
            }
        }
        let branch = if is_last { "└── " } else { "├── " };
        let name = entry.file_name().to_string_lossy().to_string();
        let label = format!("{}{}{}", prefix, branch, name);

        let relative = path
            .canonicalize()
            .unwrap_or_else(|_| path.clone())
            .strip_prefix(root_canon)
            .unwrap_or(&path)
            .to_path_buf();

        // Handle --find-artifacts mode: find build artifact directories
        if options.find_artifacts {
            let is_dir = path.is_dir();
            // Skip files - we only care about directories
            if !is_dir {
                continue;
            }
            // Check if this directory is a build artifact
            let is_artifact = BUILD_ARTIFACT_DIRS.contains(&name.as_str());
            if is_artifact {
                // Found an artifact directory - output its path and DON'T recurse into it (prune)
                let relative_display = if relative.as_os_str().is_empty() {
                    name.clone()
                } else {
                    relative.to_string_lossy().to_string()
                };
                collectors.entries.push(LineEntry {
                    label: relative_display.clone(),
                    loc: None,
                    relative_path: relative_display,
                    is_dir: true,
                    is_large: false,
                });
                collectors.stats.directories += 1;
                any_included = true;
                // Don't recurse - prune this directory
                continue;
            }
            // Not an artifact - recurse to find artifacts inside
            if options.max_depth.is_none_or(|max| depth < max) {
                prefix_parts.push(!is_last);
                let child_has = walk(
                    &path,
                    options,
                    prefix_parts,
                    collectors,
                    depth + 1,
                    root,
                    root_canon,
                    git_checker,
                    visited,
                )?;
                prefix_parts.pop();
                if child_has {
                    any_included = true;
                }
            }
            continue;
        }

        // Handle --show-ignored mode: show ONLY gitignored files
        if options.show_ignored {
            // In show_ignored mode, we want to show files that ARE ignored
            // Check if this file is ignored by gitignore
            let is_gitignored = git_checker
                .map(|checker| checker.is_ignored(&path))
                .unwrap_or(false);
            // Skip files that are NOT ignored (we only want ignored files)
            if !is_gitignored {
                // But still recurse into directories to find ignored files within
                if path.is_dir() && options.max_depth.is_none_or(|max| depth < max) {
                    prefix_parts.push(!is_last);
                    let _ = walk(
                        &path,
                        options,
                        prefix_parts,
                        collectors,
                        depth + 1,
                        root,
                        root_canon,
                        git_checker,
                        visited,
                    );
                    prefix_parts.pop();
                }
                continue;
            }
        } else if should_ignore(&path, options, git_checker) {
            // Normal mode: skip ignored files
            continue;
        }

        let mut loc = None;
        let is_dir = path.is_dir();
        let mut include_current = false;

        if path.is_file() {
            let ext = path
                .extension()
                .and_then(|ext| ext.to_str())
                .unwrap_or("")
                .to_lowercase();
            let matches_ext = options
                .extensions
                .as_ref()
                .is_none_or(|set| set.contains(&ext));
            if matches_ext {
                loc = count_lines(&path);
                if let Some(value) = loc {
                    collectors.stats.files += 1;
                    collectors.stats.files_with_loc += 1;
                    collectors.stats.total_loc += value;
                    if value >= options.loc_threshold {
                        let relative_display = if relative.as_os_str().is_empty() {
                            name.clone()
                        } else {
                            relative.to_string_lossy().to_string()
                        };
                        collectors.large_entries.push(LargeEntry {
                            path: relative_display.clone(),
                            loc: value,
                        });
                    }
                    include_current = true;
                }
            }
        }

        let relative_display = if relative.as_os_str().is_empty() {
            name.clone()
        } else {
            relative.to_string_lossy().to_string()
        };
        let is_large = loc.is_some_and(|v| v >= options.loc_threshold);

        if is_dir && options.max_depth.is_none_or(|max| depth < max) {
            // Save position BEFORE recursing so we can insert directory entry
            // before its children (not after, which causes inverted hierarchy)
            let insert_pos = collectors.entries.len();
            prefix_parts.push(!is_last);
            let child_has = walk(
                &path,
                options,
                prefix_parts,
                collectors,
                depth + 1,
                root,
                root_canon,
                git_checker,
                visited,
            )?;
            prefix_parts.pop();
            if child_has {
                collectors.stats.directories += 1;
                // Insert directory BEFORE its children (at saved position)
                collectors.entries.insert(
                    insert_pos,
                    LineEntry {
                        label,
                        loc,
                        relative_path: relative_display,
                        is_dir,
                        is_large,
                    },
                );
                any_included = true;
            }
        } else if include_current {
            // Files: push at end (correct order)
            collectors.entries.push(LineEntry {
                label,
                loc,
                relative_path: relative_display,
                is_dir,
                is_large,
            });
            any_included = true;
        }
    }

    Ok(any_included)
}

pub fn run_tree(root_list: &[PathBuf], parsed: &crate::args::ParsedArgs) -> io::Result<()> {
    let options = Options {
        extensions: parsed.extensions.clone(),
        ignore_paths: Vec::new(),
        ignore_globs: None,
        use_gitignore: parsed.use_gitignore,
        max_depth: parsed.max_depth,
        color: parsed.color,
        output: parsed.output,
        summary: parsed.summary,
        summary_limit: parsed.summary_limit,
        summary_only: parsed.summary_only,
        show_hidden: parsed.show_hidden,
        show_ignored: parsed.show_ignored,
        loc_threshold: parsed.loc_threshold,
        analyze_limit: parsed.analyze_limit,
        report_path: None,
        serve: false,
        editor_cmd: None,
        max_graph_nodes: parsed.max_graph_nodes,
        max_graph_edges: parsed.max_graph_edges,
        verbose: parsed.verbose,
        scan_all: parsed.scan_all,
        symbol: None,
        impact: None,
        find_artifacts: parsed.find_artifacts,
    };

    let mut json_results = Vec::new();

    for (idx, root_path) in root_list.iter().enumerate() {
        let ignore_matchers = build_ignore_matchers(&parsed.ignore_patterns, root_path);
        let root_canon = root_path
            .canonicalize()
            .unwrap_or_else(|_| root_path.clone());
        let root_options = Options {
            ignore_paths: ignore_matchers.ignore_paths,
            ignore_globs: ignore_matchers.ignore_globs,
            loc_threshold: parsed.loc_threshold,
            ..options.clone()
        };

        let git_checker = if root_options.use_gitignore {
            GitIgnoreChecker::new(root_path)
        } else {
            None
        };

        let mut entries: Vec<LineEntry> = Vec::new();
        let mut large_entries: Vec<LargeEntry> = Vec::new();
        let mut prefix_parts: Vec<bool> = Vec::new();
        let mut stats = Stats::default();
        let mut visited: HashSet<PathBuf> = HashSet::new();

        let mut collectors = Collectors {
            entries: &mut entries,
            large_entries: &mut large_entries,
            stats: &mut stats,
        };

        walk(
            root_path,
            &root_options,
            &mut prefix_parts,
            &mut collectors,
            0,
            root_path,
            &root_canon,
            git_checker.as_ref(),
            &mut visited,
        )?;

        // Special output for --find-artifacts: just paths, one per line
        if root_options.find_artifacts {
            for entry in &entries {
                // Output absolute path for easy use with rm/trash commands
                let abs_path = root_canon.join(&entry.relative_path);
                println!("{}", abs_path.display());
            }
            continue;
        }

        let mut sorted_large = large_entries;
        sorted_large.sort_by(|a, b| b.loc.cmp(&a.loc));

        let summary = json!({
            "directories": stats.directories,
            "files": stats.files,
            "filesWithLoc": stats.files_with_loc,
            "totalLoc": stats.total_loc,
            "largeFiles": sorted_large
                .iter()
                .take(root_options.summary_limit)
                .map(|e| json!({"path": e.path, "loc": e.loc}))
                .collect::<Vec<_>>()
        });

        if matches!(root_options.output, OutputMode::Json | OutputMode::Jsonl) {
            let entries_json: Vec<_> = if root_options.summary_only {
                sorted_large
                    .iter()
                    .take(root_options.summary_limit)
                    .map(|entry| {
                        json!({
                            "path": entry.path,
                            "type": "file",
                            "loc": entry.loc,
                            "isLarge": true,
                        })
                    })
                    .collect()
            } else {
                entries
                    .iter()
                    .map(|entry| {
                        json!({
                            "path": entry.relative_path,
                            "type": if entry.is_dir { "dir" } else { "file" },
                            "loc": entry.loc,
                            "isLarge": entry.is_large,
                        })
                    })
                    .collect()
            };

            let payload = json!({
                "root": root_path,
                "options": {
                    "exts": root_options.extensions.as_ref().map(|set| {
                        let mut exts: Vec<_> = set.iter().cloned().collect();
                        exts.sort();
                        exts
                    }),
                    "ignore": root_options
                        .ignore_paths
                        .iter()
                        .map(|p| p.display().to_string())
                        .collect::<Vec<_>>(),
                    "maxDepth": root_options.max_depth,
                    "useGitignore": root_options.use_gitignore,
                    "color": match root_options.color {
                        ColorMode::Auto => "auto",
                        ColorMode::Always => "always",
                        ColorMode::Never => "never",
                    },
                    "summary": if root_options.summary {
                        serde_json::Value::from(root_options.summary_limit)
                    } else {
                        serde_json::Value::Bool(false)
                    },
                },
                "summary": summary,
                "entries": entries_json,
            });

            if matches!(root_options.output, OutputMode::Jsonl) {
                match serde_json::to_string(&payload) {
                    Ok(line) => println!("{}", line),
                    Err(err) => {
                        eprintln!("[loctree][warn] failed to serialize JSONL line: {}", err)
                    }
                }
            } else {
                json_results.push(payload);
            }
            continue;
        }

        if root_options.summary_only && matches!(root_options.output, OutputMode::Human) {
            if idx > 0 {
                println!();
            }

            let root_name = root_path
                .file_name()
                .map(|name| name.to_string_lossy().into_owned())
                .unwrap_or_else(|| root_path.display().to_string());

            println!("{}/", root_name);
            if sorted_large.is_empty() {
                println!(
                    "No files exceed the large-file threshold ({} LOC).",
                    root_options.loc_threshold
                );
            } else {
                println!(
                    "Top {} files (>= {} LOC):",
                    root_options.summary_limit, root_options.loc_threshold
                );
                for item in sorted_large.iter().take(root_options.summary_limit) {
                    println!("  {} ({} LOC)", item.path, item.loc);
                }
            }
            println!(
                "\nSummary: directories: {}, files: {}, files with LOC: {}, total LOC: {}",
                stats.directories, stats.files, stats.files_with_loc, stats.total_loc
            );
            continue;
        }

        if idx > 0 {
            println!();
        }

        if entries.is_empty() {
            println!("{}/ (empty)", root_path.display());
            continue;
        }

        let max_label_len = entries
            .iter()
            .map(|entry| entry.label.len())
            .max()
            .unwrap_or(0);
        let root_name = root_path
            .file_name()
            .map(|name| name.to_string_lossy().into_owned())
            .unwrap_or_else(|| root_path.display().to_string());

        let color_enabled = matches!(root_options.color, ColorMode::Always)
            || (matches!(root_options.color, ColorMode::Auto) && std::io::stdout().is_terminal());

        println!("{}/", root_name);
        for entry in &entries {
            if let Some(loc) = entry.loc {
                let line = format!("{:<width$}  {:>6}", entry.label, loc, width = max_label_len);
                if color_enabled && entry.is_large {
                    println!("{}{}{}", COLOR_RED, line, COLOR_RESET);
                } else {
                    println!("{}", line);
                }
            } else {
                println!("{}", entry.label);
            }
        }

        if !sorted_large.is_empty() {
            println!("\nLarge files (>= {} LOC):", root_options.loc_threshold);
            for item in &sorted_large {
                let summary_line = format!("  {} ({} LOC)", item.path, item.loc);
                if color_enabled {
                    println!("{}{}{}", COLOR_RED, summary_line, COLOR_RESET);
                } else {
                    println!("{}", summary_line);
                }
            }
        }

        if root_options.summary {
            println!(
                "\nSummary: directories: {}, files: {}, files with LOC: {}, total LOC: {}",
                stats.directories, stats.files, stats.files_with_loc, stats.total_loc
            );
            if sorted_large.is_empty() {
                println!("No files exceed the large-file threshold.");
            }
        }
    }

    if matches!(options.output, OutputMode::Json) {
        if json_results.len() == 1 {
            match serde_json::to_string_pretty(&json_results[0]) {
                Ok(out) => println!("{}", out),
                Err(err) => eprintln!("[loctree][warn] failed to serialize JSON: {}", err),
            }
        } else {
            match serde_json::to_string_pretty(&json_results) {
                Ok(out) => println!("{}", out),
                Err(err) => eprintln!("[loctree][warn] failed to serialize JSON: {}", err),
            }
        }
    }

    Ok(())
}

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

    fn create_test_tree() -> TempDir {
        let temp = TempDir::new().unwrap();
        let root = temp.path();

        // Create directories
        fs::create_dir_all(root.join("src")).unwrap();
        fs::create_dir_all(root.join("lib")).unwrap();

        // Create files with content
        fs::write(
            root.join("src/main.ts"),
            "export function main() {\n  console.log('hello');\n}\n",
        )
        .unwrap();
        fs::write(
            root.join("src/utils.ts"),
            "export const add = (a: number, b: number) => a + b;\n",
        )
        .unwrap();
        fs::write(
            root.join("lib/helper.ts"),
            "export function help() { return 'help'; }\n",
        )
        .unwrap();

        temp
    }

    fn default_parsed_args() -> crate::args::ParsedArgs {
        crate::args::ParsedArgs::default()
    }

    #[test]
    fn test_run_tree_basic() {
        let temp = create_test_tree();
        let roots = vec![temp.path().to_path_buf()];
        let parsed = default_parsed_args();

        let result = run_tree(&roots, &parsed);
        assert!(result.is_ok());
    }

    #[test]
    fn test_run_tree_with_summary() {
        let temp = create_test_tree();
        let roots = vec![temp.path().to_path_buf()];
        let mut parsed = default_parsed_args();
        parsed.summary = true;

        let result = run_tree(&roots, &parsed);
        assert!(result.is_ok());
    }

    #[test]
    fn test_run_tree_json_output() {
        let temp = create_test_tree();
        let roots = vec![temp.path().to_path_buf()];
        let mut parsed = default_parsed_args();
        parsed.output = OutputMode::Json;

        let result = run_tree(&roots, &parsed);
        assert!(result.is_ok());
    }

    #[test]
    fn test_run_tree_jsonl_output() {
        let temp = create_test_tree();
        let roots = vec![temp.path().to_path_buf()];
        let mut parsed = default_parsed_args();
        parsed.output = OutputMode::Jsonl;

        let result = run_tree(&roots, &parsed);
        assert!(result.is_ok());
    }

    #[test]
    fn test_run_tree_with_extension_filter() {
        let temp = create_test_tree();
        let roots = vec![temp.path().to_path_buf()];
        let mut parsed = default_parsed_args();
        parsed.extensions = Some(["ts".to_string()].into_iter().collect());

        let result = run_tree(&roots, &parsed);
        assert!(result.is_ok());
    }

    #[test]
    fn test_run_tree_with_max_depth() {
        let temp = create_test_tree();
        let roots = vec![temp.path().to_path_buf()];
        let mut parsed = default_parsed_args();
        parsed.max_depth = Some(1);

        let result = run_tree(&roots, &parsed);
        assert!(result.is_ok());
    }

    #[test]
    fn test_run_tree_empty_directory() {
        let temp = TempDir::new().unwrap();
        let roots = vec![temp.path().to_path_buf()];
        let parsed = default_parsed_args();

        let result = run_tree(&roots, &parsed);
        assert!(result.is_ok());
    }

    #[test]
    fn test_run_tree_multiple_roots() {
        let temp1 = create_test_tree();
        let temp2 = create_test_tree();
        let roots = vec![temp1.path().to_path_buf(), temp2.path().to_path_buf()];
        let parsed = default_parsed_args();

        let result = run_tree(&roots, &parsed);
        assert!(result.is_ok());
    }

    #[test]
    fn test_run_tree_show_hidden() {
        let temp = TempDir::new().unwrap();
        let root = temp.path();

        // Create hidden file
        fs::write(root.join(".hidden.ts"), "const hidden = true;\n").unwrap();
        fs::write(root.join("visible.ts"), "const visible = true;\n").unwrap();

        let roots = vec![temp.path().to_path_buf()];
        let mut parsed = default_parsed_args();
        parsed.show_hidden = true;

        let result = run_tree(&roots, &parsed);
        assert!(result.is_ok());
    }

    #[test]
    fn test_run_tree_with_gitignore() {
        let temp = TempDir::new().unwrap();
        let root = temp.path();

        // Create .gitignore
        fs::write(root.join(".gitignore"), "*.log\nnode_modules/\n").unwrap();
        fs::write(root.join("app.ts"), "const app = 'app';\n").unwrap();
        fs::write(root.join("debug.log"), "log content\n").unwrap();

        let roots = vec![temp.path().to_path_buf()];
        let mut parsed = default_parsed_args();
        parsed.use_gitignore = true;

        let result = run_tree(&roots, &parsed);
        assert!(result.is_ok());
    }

    #[test]
    fn test_run_tree_with_loc_threshold() {
        let temp = TempDir::new().unwrap();
        let root = temp.path();

        // Create a file with many lines
        let large_content: String = (0..100)
            .map(|i| format!("const line{} = {};\n", i, i))
            .collect();
        fs::write(root.join("large.ts"), large_content).unwrap();

        let roots = vec![temp.path().to_path_buf()];
        let mut parsed = default_parsed_args();
        parsed.loc_threshold = 50;

        let result = run_tree(&roots, &parsed);
        assert!(result.is_ok());
    }

    #[test]
    fn test_find_artifacts_mode() {
        let temp = TempDir::new().unwrap();
        let root = temp.path();

        // Create build artifact directories
        fs::create_dir_all(root.join("node_modules")).unwrap();
        fs::create_dir_all(root.join("dist")).unwrap();
        fs::create_dir_all(root.join("target")).unwrap();
        fs::create_dir_all(root.join("src")).unwrap();

        // Add some files
        fs::write(root.join("node_modules/package.json"), "{}").unwrap();
        fs::write(root.join("src/main.ts"), "export default {};\n").unwrap();

        let roots = vec![temp.path().to_path_buf()];
        let mut parsed = default_parsed_args();
        parsed.find_artifacts = true;

        let result = run_tree(&roots, &parsed);
        assert!(result.is_ok());
    }

    #[test]
    fn test_build_artifact_dirs_constant() {
        // Verify BUILD_ARTIFACT_DIRS contains expected directories
        assert!(BUILD_ARTIFACT_DIRS.contains(&"node_modules"));
        assert!(BUILD_ARTIFACT_DIRS.contains(&"target"));
        assert!(BUILD_ARTIFACT_DIRS.contains(&"dist"));
        assert!(BUILD_ARTIFACT_DIRS.contains(&".venv"));
        assert!(BUILD_ARTIFACT_DIRS.contains(&"vendor"));
    }

    #[test]
    fn test_run_tree_with_ignore_patterns() {
        let temp = create_test_tree();
        let roots = vec![temp.path().to_path_buf()];
        let mut parsed = default_parsed_args();
        parsed.ignore_patterns = vec!["lib".to_string()];

        let result = run_tree(&roots, &parsed);
        assert!(result.is_ok());
    }

    #[test]
    fn test_run_tree_with_color_always() {
        let temp = create_test_tree();
        let roots = vec![temp.path().to_path_buf()];
        let mut parsed = default_parsed_args();
        parsed.color = ColorMode::Always;

        let result = run_tree(&roots, &parsed);
        assert!(result.is_ok());
    }

    #[test]
    fn test_run_tree_nested_directories() {
        let temp = TempDir::new().unwrap();
        let root = temp.path();

        // Create deeply nested structure
        fs::create_dir_all(root.join("a/b/c/d")).unwrap();
        fs::write(
            root.join("a/b/c/d/deep.ts"),
            "export const deep = 'deep';\n",
        )
        .unwrap();

        let roots = vec![temp.path().to_path_buf()];
        let parsed = default_parsed_args();

        let result = run_tree(&roots, &parsed);
        assert!(result.is_ok());
    }
}