forked from rtk-ai/rtk
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtree.rs
More file actions
208 lines (178 loc) · 5.98 KB
/
Copy pathtree.rs
File metadata and controls
208 lines (178 loc) · 5.98 KB
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
//! tree command - proxy to native tree with token-optimized output
//!
//! This module proxies to the native `tree` command and filters the output
//! to reduce token usage while preserving structure visibility.
//!
//! Token optimization: automatically excludes noise directories via -I pattern
//! unless -a flag is present (respecting user intent).
use crate::tracking;
use crate::utils::{resolved_command, tool_exists};
use anyhow::{Context, Result};
/// Noise directories commonly excluded from LLM context
const NOISE_DIRS: &[&str] = &[
"node_modules",
".git",
"target",
"__pycache__",
".next",
"dist",
"build",
".cache",
".turbo",
".vercel",
".pytest_cache",
".mypy_cache",
".tox",
".venv",
"venv",
"env",
".env",
"coverage",
".nyc_output",
".DS_Store",
"Thumbs.db",
".idea",
".vscode",
".vs",
"*.egg-info",
".eggs",
];
pub fn run(args: &[String], verbose: u8) -> Result<()> {
let timer = tracking::TimedExecution::start();
// Check if tree is installed
if !tool_exists("tree") {
anyhow::bail!(
"tree command not found. Install it first:\n\
- macOS: brew install tree\n\
- Ubuntu/Debian: sudo apt install tree\n\
- Fedora/RHEL: sudo dnf install tree\n\
- Arch: sudo pacman -S tree"
);
}
let mut cmd = resolved_command("tree");
// Determine if user wants all files or default behavior
let show_all = args.iter().any(|a| a == "-a" || a == "--all");
let has_ignore = args.iter().any(|a| a == "-I" || a.starts_with("--ignore="));
// Auto-inject -I pattern unless user wants all or already specified -I
if !show_all && !has_ignore {
let ignore_pattern = NOISE_DIRS.join("|");
cmd.arg("-I").arg(&ignore_pattern);
}
// Pass all user args
for arg in args {
cmd.arg(arg);
}
let output = cmd.output().context("Failed to run tree")?;
if !output.status.success() {
let stderr = String::from_utf8_lossy(&output.stderr);
eprint!("{}", stderr);
std::process::exit(output.status.code().unwrap_or(1));
}
let raw = String::from_utf8_lossy(&output.stdout).to_string();
let filtered = filter_tree_output(&raw);
if verbose > 0 {
eprintln!(
"Lines: {} → {} ({}% reduction)",
raw.lines().count(),
filtered.lines().count(),
if raw.lines().count() > 0 {
100 - (filtered.lines().count() * 100 / raw.lines().count())
} else {
0
}
);
}
print!("{}", filtered);
timer.track("tree", "rtk tree", &raw, &filtered);
Ok(())
}
fn filter_tree_output(raw: &str) -> String {
let lines: Vec<&str> = raw.lines().collect();
if lines.is_empty() {
return "\n".to_string();
}
let mut filtered_lines = Vec::new();
for line in lines {
// Skip the final summary line (e.g., "5 directories, 23 files")
if line.contains("director") && line.contains("file") {
continue;
}
// Skip empty lines at the end
if line.trim().is_empty() && filtered_lines.is_empty() {
continue;
}
filtered_lines.push(line);
}
// Remove trailing empty lines
while filtered_lines.last().is_some_and(|l| l.trim().is_empty()) {
filtered_lines.pop();
}
filtered_lines.join("\n") + "\n"
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_filter_removes_summary() {
let input = ".\n├── src\n│ └── main.rs\n└── Cargo.toml\n\n2 directories, 3 files\n";
let output = filter_tree_output(input);
assert!(!output.contains("directories"));
assert!(!output.contains("files"));
assert!(output.contains("main.rs"));
assert!(output.contains("Cargo.toml"));
}
#[test]
fn test_filter_preserves_structure() {
let input = ".\n├── src\n│ ├── main.rs\n│ └── lib.rs\n└── tests\n └── test.rs\n";
let output = filter_tree_output(input);
assert!(output.contains("├──"));
assert!(output.contains("│"));
assert!(output.contains("└──"));
assert!(output.contains("main.rs"));
assert!(output.contains("test.rs"));
}
#[test]
fn test_filter_handles_empty() {
let input = "";
let output = filter_tree_output(input);
assert_eq!(output, "\n");
}
#[test]
fn test_filter_removes_trailing_empty_lines() {
let input = ".\n├── file.txt\n\n\n";
let output = filter_tree_output(input);
assert_eq!(output.matches('\n').count(), 2); // Root + file.txt + final newline
}
#[test]
fn test_filter_summary_variations() {
// Test different summary formats
let inputs = vec![
(".\n└── file.txt\n\n0 directories, 1 file\n", "1 file"),
(".\n└── file.txt\n\n1 directory, 0 files\n", "1 directory"),
(".\n└── file.txt\n\n10 directories, 25 files\n", "25 files"),
];
for (input, summary_fragment) in inputs {
let output = filter_tree_output(input);
assert!(
!output.contains(summary_fragment),
"Should remove summary '{}' from output",
summary_fragment
);
assert!(
output.contains("file.txt"),
"Should preserve file.txt in output"
);
}
}
#[test]
fn test_noise_dirs_constant() {
// Verify NOISE_DIRS contains expected patterns
assert!(NOISE_DIRS.contains(&"node_modules"));
assert!(NOISE_DIRS.contains(&".git"));
assert!(NOISE_DIRS.contains(&"target"));
assert!(NOISE_DIRS.contains(&"__pycache__"));
assert!(NOISE_DIRS.contains(&".next"));
assert!(NOISE_DIRS.contains(&"dist"));
assert!(NOISE_DIRS.contains(&"build"));
}
}