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
//! Tree formatting and display
use std::io::{self, Write};
use termcolor::{Color, ColorChoice, ColorSpec, StandardStream, WriteColor};
use crate::tree::{StreamingOutput, TreeNode};
/// Print tree node as pretty-printed JSON to stdout.
pub fn print_json(node: &TreeNode) -> io::Result<()> {
let json =
serde_json::to_string_pretty(node).map_err(|e| io::Error::new(io::ErrorKind::Other, e))?;
println!("{}", json);
Ok(())
}
const DEFAULT_WRAP_WIDTH: usize = 100;
#[derive(Debug, Clone)]
pub struct OutputConfig {
pub use_color: bool,
pub show_full_comment: bool,
pub wrap_width: Option<usize>,
}
impl Default for OutputConfig {
fn default() -> Self {
Self {
use_color: true,
show_full_comment: false,
wrap_width: Some(DEFAULT_WRAP_WIDTH),
}
}
}
pub struct TreeFormatter {
config: OutputConfig,
}
impl TreeFormatter {
pub fn new(config: OutputConfig) -> Self {
Self { config }
}
pub fn format(&self, node: &TreeNode) -> String {
let mut output = String::new();
let (dir_count, file_count) = self.format_node(node, &mut output, "", true, true);
output.push_str(&format!(
"\n{} directories, {} files\n",
dir_count, file_count
));
output
}
pub fn print(&self, node: &TreeNode) -> io::Result<()> {
let choice = if self.config.use_color {
ColorChoice::Auto
} else {
ColorChoice::Never
};
let mut stdout = StandardStream::stdout(choice);
let (dir_count, file_count) = self.print_node(node, &mut stdout, "", true, true)?;
writeln!(stdout)?;
writeln!(stdout, "{} directories, {} files", dir_count, file_count)?;
Ok(())
}
fn format_node(
&self,
node: &TreeNode,
output: &mut String,
prefix: &str,
is_last: bool,
is_root: bool,
) -> (usize, usize) {
let connector = if is_last { "└── " } else { "├── " };
match node {
TreeNode::File { name, comment, .. } => {
output.push_str(prefix);
output.push_str(connector);
output.push_str(name);
if let Some(c) = comment {
if self.config.show_full_comment {
// Calculate padding for continuation lines
let continuation_prefix = if is_last {
format!("{} ", prefix)
} else {
format!("{}│ ", prefix)
};
let padding_len = name.len() + 4; // " # " align with text start
let padding = " ".repeat(padding_len);
// Calculate available width for text wrapping
let prefix_width = continuation_prefix.chars().count() + padding_len;
let wrap_width = self
.config
.wrap_width
.map(|w| w.saturating_sub(prefix_width))
.filter(|&w| w > 10);
let comment = c.trim();
let has_multiple_lines = comment.contains('\n');
let mut first_line_done = false;
for line in comment.lines() {
let wrapped = if let Some(width) = wrap_width {
wrap_text(line, width)
} else {
vec![line.to_string()]
};
for (i, wrapped_line) in wrapped.iter().enumerate() {
if !first_line_done && i == 0 {
output.push_str(" # ");
output.push_str(wrapped_line);
output.push('\n');
first_line_done = true;
} else {
output.push_str(&continuation_prefix);
output.push_str(&padding);
output.push_str(wrapped_line);
output.push('\n');
}
}
}
// Add blank line after multiline comments
if has_multiple_lines {
output.push_str(&continuation_prefix);
output.push('\n');
}
} else {
output.push_str(" # ");
output.push_str(first_line(c));
output.push('\n');
}
} else {
output.push('\n');
}
(0, 1)
}
TreeNode::Dir { name, children, .. } => {
if is_root {
// Root node - print without connector
output.push_str(name);
output.push('\n');
} else {
output.push_str(prefix);
output.push_str(connector);
output.push_str(name);
output.push('\n');
}
let new_prefix = if is_root {
String::new()
} else if is_last {
format!("{} ", prefix)
} else {
format!("{}│ ", prefix)
};
let mut dir_count = 0;
let mut file_count = 0;
for (i, child) in children.iter().enumerate() {
let child_is_last = i == children.len() - 1;
let (d, f) = self.format_node(child, output, &new_prefix, child_is_last, false);
dir_count += d;
file_count += f;
if child.is_dir() {
dir_count += 1;
}
}
(dir_count, file_count)
}
}
}
fn print_node(
&self,
node: &TreeNode,
stdout: &mut StandardStream,
prefix: &str,
is_last: bool,
is_root: bool,
) -> io::Result<(usize, usize)> {
let connector = if is_last { "└── " } else { "├── " };
match node {
TreeNode::File { name, comment, .. } => {
write!(stdout, "{}{}", prefix, connector)?;
stdout.set_color(ColorSpec::new().set_fg(Some(Color::White)))?;
write!(stdout, "{}", name)?;
stdout.reset()?;
if let Some(c) = comment {
stdout.set_color(
ColorSpec::new()
.set_fg(Some(Color::Black))
.set_intense(true),
)?;
if self.config.show_full_comment {
// Calculate padding for continuation lines
let continuation_prefix = if is_last {
format!("{} ", prefix)
} else {
format!("{}│ ", prefix)
};
let padding_len = name.len() + 4; // " # " align with text start
let padding = " ".repeat(padding_len);
// Calculate available width for text wrapping
let prefix_width = continuation_prefix.chars().count() + padding_len;
let wrap_width = self
.config
.wrap_width
.map(|w| w.saturating_sub(prefix_width))
.filter(|&w| w > 10); // Don't wrap if too narrow
let comment = c.trim();
let has_multiple_lines = comment.contains('\n');
let mut first_line_done = false;
for line in comment.lines() {
let wrapped = if let Some(width) = wrap_width {
wrap_text(line, width)
} else {
vec![line.to_string()]
};
for (i, wrapped_line) in wrapped.iter().enumerate() {
if !first_line_done && i == 0 {
writeln!(stdout, " # {}", wrapped_line)?;
first_line_done = true;
} else {
stdout.reset()?;
write!(stdout, "{}", continuation_prefix)?;
stdout.set_color(
ColorSpec::new()
.set_fg(Some(Color::Black))
.set_intense(true),
)?;
writeln!(stdout, "{}{}", padding, wrapped_line)?;
}
}
}
// Add blank line after multiline comments for readability
if has_multiple_lines {
stdout.reset()?;
writeln!(stdout, "{}", continuation_prefix)?;
}
} else {
writeln!(stdout, " # {}", first_line(c))?;
}
stdout.reset()?;
} else {
writeln!(stdout)?;
}
Ok((0, 1))
}
TreeNode::Dir { name, children, .. } => {
if is_root {
// Root node - print without connector
stdout.set_color(ColorSpec::new().set_fg(Some(Color::Blue)).set_bold(true))?;
writeln!(stdout, "{}", name)?;
stdout.reset()?;
} else {
write!(stdout, "{}{}", prefix, connector)?;
stdout.set_color(ColorSpec::new().set_fg(Some(Color::Blue)).set_bold(true))?;
writeln!(stdout, "{}", name)?;
stdout.reset()?;
}
let new_prefix = if is_root {
String::new()
} else if is_last {
format!("{} ", prefix)
} else {
format!("{}│ ", prefix)
};
let mut dir_count = 0;
let mut file_count = 0;
for (i, child) in children.iter().enumerate() {
let child_is_last = i == children.len() - 1;
let (d, f) =
self.print_node(child, stdout, &new_prefix, child_is_last, false)?;
dir_count += d;
file_count += f;
if child.is_dir() {
dir_count += 1;
}
}
Ok((dir_count, file_count))
}
}
}
}
fn first_line(s: &str) -> &str {
s.lines().next().unwrap_or(s)
}
/// Streaming output formatter - outputs directly to stdout without buffering.
/// Implements the StreamingOutput trait for use with StreamingWalker.
pub struct StreamingFormatter {
config: OutputConfig,
stdout: StandardStream,
}
impl StreamingFormatter {
pub fn new(config: OutputConfig) -> Self {
let choice = if config.use_color {
ColorChoice::Auto
} else {
ColorChoice::Never
};
Self {
config,
stdout: StandardStream::stdout(choice),
}
}
}
impl StreamingOutput for StreamingFormatter {
fn output_node(
&mut self,
name: &str,
comment: Option<&str>,
is_dir: bool,
is_last: bool,
prefix: &str,
is_root: bool,
) -> io::Result<()> {
let connector = if is_last { "└── " } else { "├── " };
if is_dir {
if is_root {
self.stdout
.set_color(ColorSpec::new().set_fg(Some(Color::Blue)).set_bold(true))?;
writeln!(self.stdout, "{}", name)?;
self.stdout.reset()?;
} else {
write!(self.stdout, "{}{}", prefix, connector)?;
self.stdout
.set_color(ColorSpec::new().set_fg(Some(Color::Blue)).set_bold(true))?;
writeln!(self.stdout, "{}", name)?;
self.stdout.reset()?;
}
} else {
// File
write!(self.stdout, "{}{}", prefix, connector)?;
self.stdout
.set_color(ColorSpec::new().set_fg(Some(Color::White)))?;
write!(self.stdout, "{}", name)?;
self.stdout.reset()?;
if let Some(c) = comment {
self.stdout.set_color(
ColorSpec::new()
.set_fg(Some(Color::Black))
.set_intense(true),
)?;
if self.config.show_full_comment {
// Calculate padding for continuation lines
let continuation_prefix = if is_last {
format!("{} ", prefix)
} else {
format!("{}│ ", prefix)
};
let padding_len = name.len() + 4; // " # " align with text start
let padding = " ".repeat(padding_len);
// Calculate available width for text wrapping
let prefix_width = continuation_prefix.chars().count() + padding_len;
let wrap_width = self
.config
.wrap_width
.map(|w| w.saturating_sub(prefix_width))
.filter(|&w| w > 10);
let comment = c.trim();
let has_multiple_lines = comment.contains('\n');
let mut first_line_done = false;
for line in comment.lines() {
let wrapped = if let Some(width) = wrap_width {
wrap_text(line, width)
} else {
vec![line.to_string()]
};
for (i, wrapped_line) in wrapped.iter().enumerate() {
if !first_line_done && i == 0 {
writeln!(self.stdout, " # {}", wrapped_line)?;
first_line_done = true;
} else {
self.stdout.reset()?;
write!(self.stdout, "{}", continuation_prefix)?;
self.stdout.set_color(
ColorSpec::new()
.set_fg(Some(Color::Black))
.set_intense(true),
)?;
writeln!(self.stdout, "{}{}", padding, wrapped_line)?;
}
}
}
// Add blank line after multiline comments for readability
if has_multiple_lines {
self.stdout.reset()?;
writeln!(self.stdout, "{}", continuation_prefix)?;
}
} else {
writeln!(self.stdout, " # {}", first_line(c))?;
}
self.stdout.reset()?;
} else {
writeln!(self.stdout)?;
}
}
Ok(())
}
fn finish(&mut self, dir_count: usize, file_count: usize) -> io::Result<()> {
writeln!(self.stdout)?;
writeln!(
self.stdout,
"{} directories, {} files",
dir_count, file_count
)?;
Ok(())
}
}
/// Wrap text to fit within max_width, preferring word boundaries.
/// Uses character count (not byte count) to properly handle UTF-8.
fn wrap_text(text: &str, max_width: usize) -> Vec<String> {
if max_width == 0 {
return vec![text.to_string()];
}
let mut lines = Vec::new();
let mut current_line = String::new();
let mut current_len = 0; // Character count of current_line
for word in text.split_whitespace() {
let word_len = word.chars().count();
if current_line.is_empty() {
// First word on line - may need character wrap if too long
if word_len > max_width {
// Character wrap for very long words
let mut chars = word.chars().peekable();
while chars.peek().is_some() {
let chunk: String = chars.by_ref().take(max_width).collect();
let chunk_len = chunk.chars().count();
if chars.peek().is_some() {
lines.push(chunk);
} else {
current_line = chunk;
current_len = chunk_len;
}
}
} else {
current_line = word.to_string();
current_len = word_len;
}
} else if current_len + 1 + word_len <= max_width {
// Word fits on current line
current_line.push(' ');
current_line.push_str(word);
current_len += 1 + word_len;
} else {
// Start new line
lines.push(std::mem::take(&mut current_line));
current_len = 0;
// Handle long words
if word_len > max_width {
let mut chars = word.chars().peekable();
while chars.peek().is_some() {
let chunk: String = chars.by_ref().take(max_width).collect();
let chunk_len = chunk.chars().count();
if chars.peek().is_some() {
lines.push(chunk);
} else {
current_line = chunk;
current_len = chunk_len;
}
}
} else {
current_line = word.to_string();
current_len = word_len;
}
}
}
if !current_line.is_empty() {
lines.push(current_line);
}
if lines.is_empty() {
lines.push(String::new());
}
lines
}
#[cfg(test)]
mod tests {
use super::*;
fn sample_tree() -> TreeNode {
TreeNode::Dir {
name: ".".to_string(),
path: ".".into(),
children: vec![
TreeNode::File {
name: "Cargo.toml".to_string(),
path: "Cargo.toml".into(),
comment: Some("Package manifest".to_string()),
},
TreeNode::Dir {
name: "src".to_string(),
path: "src".into(),
children: vec![
TreeNode::File {
name: "main.rs".to_string(),
path: "src/main.rs".into(),
comment: Some("CLI entry point".to_string()),
},
TreeNode::File {
name: "lib.rs".to_string(),
path: "src/lib.rs".into(),
comment: None,
},
],
},
],
}
}
#[test]
fn test_format_output() {
let tree = sample_tree();
let formatter = TreeFormatter::new(OutputConfig {
use_color: false,
show_full_comment: false,
wrap_width: None,
});
let output = formatter.format(&tree);
assert!(output.contains("."));
assert!(output.contains("├── Cargo.toml"));
assert!(output.contains("# Package manifest"));
assert!(output.contains("└── src"));
assert!(output.contains("├── main.rs"));
assert!(output.contains("└── lib.rs"));
assert!(output.contains("directories"));
assert!(output.contains("files"));
}
#[test]
fn test_dir_count() {
let tree = sample_tree();
let formatter = TreeFormatter::new(OutputConfig::default());
let output = formatter.format(&tree);
// Should count 1 directory (src) - root is not counted
assert!(output.contains("1 directories, 3 files"));
}
#[test]
fn test_wrap_text_utf8() {
// Test that emoji don't cause panics (they're 4 bytes each)
let emoji_text = "🎉🎊🎁🎂🎃";
let wrapped = wrap_text(emoji_text, 3);
assert_eq!(wrapped, vec!["🎉🎊🎁", "🎂🎃"]);
// Test CJK characters (3 bytes each)
let cjk_text = "你好世界";
let wrapped = wrap_text(cjk_text, 2);
assert_eq!(wrapped, vec!["你好", "世界"]);
// Test mixed content
let mixed = "Hello 世界 🎉";
let wrapped = wrap_text(mixed, 8);
assert_eq!(wrapped, vec!["Hello 世界", "🎉"]);
}
}