Skip to main content

treesearch/output/
plain.rs

1//! Plain text output for search results (no ANSI escape codes).
2//!
3//! Same layout as TTY output but suitable for piping to other tools.
4
5use unicode_width::UnicodeWidthStr;
6
7use crate::document::SearchResult;
8
9use super::OutputFormat;
10
11/// Max display width for plain text output.
12const MAX_WIDTH: usize = 100;
13
14/// Truncate a string to fit within `max_width` display columns,
15/// accounting for CJK double-width characters.
16fn truncate_to_width(s: &str, max_width: usize) -> String {
17    if s.width() <= max_width {
18        return s.to_string();
19    }
20    if max_width <= 3 {
21        return ".".repeat(max_width);
22    }
23    let mut width = 0;
24    let mut result = String::new();
25    for ch in s.chars() {
26        let cw = unicode_width::UnicodeWidthChar::width(ch).unwrap_or(0);
27        if width + cw + 3 > max_width {
28            result.push_str("...");
29            break;
30        }
31        result.push(ch);
32        width += cw;
33    }
34    result
35}
36
37/// Plain text output formatter (no colors, no ANSI codes).
38pub struct PlainOutput;
39
40impl PlainOutput {
41    pub fn new() -> Self {
42        Self
43    }
44}
45
46impl Default for PlainOutput {
47    fn default() -> Self {
48        Self::new()
49    }
50}
51
52impl OutputFormat for PlainOutput {
53    fn render(&self, results: &[SearchResult], verbose: u8) -> String {
54        if results.is_empty() {
55            return "No results found.\n".to_string();
56        }
57
58        let mut out = String::new();
59
60        for (i, result) in results.iter().enumerate() {
61            // Result separator
62            out.push_str(&format!("── Result {} ──\n", i + 1));
63
64            // Header: source_path [source_type] (score: X.XX)
65            out.push_str(&format!(
66                "{} [{}] (score: {:.2})\n",
67                result.source_path, result.source_type, result.score
68            ));
69
70            // Breadcrumb path with tree characters
71            if !result.breadcrumb.is_empty() {
72                let crumb_len = result.breadcrumb.len();
73                for (j, crumb) in result.breadcrumb.iter().enumerate() {
74                    let is_last = j == crumb_len - 1;
75                    let prefix = if is_last {
76                        "  └── "
77                    } else {
78                        "  ├── "
79                    };
80                    let truncated = truncate_to_width(crumb, MAX_WIDTH.saturating_sub(8));
81                    out.push_str(&format!("{}{}\n", prefix, truncated));
82                }
83            }
84
85            // Title
86            if !result.title.is_empty() {
87                out.push_str(&format!(
88                    "  Title: {}\n",
89                    truncate_to_width(&result.title, MAX_WIDTH.saturating_sub(10))
90                ));
91            }
92
93            // Summary (verbose >= 1)
94            if verbose >= 1 && !result.summary.is_empty() {
95                out.push_str(&format!(
96                    "  Summary: {}\n",
97                    truncate_to_width(&result.summary, MAX_WIDTH.saturating_sub(12))
98                ));
99            }
100
101            // Text (verbose >= 2)
102            if verbose >= 2 && !result.text.is_empty() {
103                out.push_str(&format!(
104                    "  Text: {}\n",
105                    truncate_to_width(&result.text, MAX_WIDTH.saturating_sub(10))
106                ));
107            }
108
109            // Line numbers
110            if let (Some(start), Some(end)) = (result.line_start, result.line_end) {
111                out.push_str(&format!("  Lines: {}-{}\n", start, end));
112            }
113
114            out.push('\n'); // Blank line between results
115        }
116
117        out
118    }
119}
120
121#[cfg(test)]
122mod tests {
123    use super::*;
124
125    fn sample_result() -> SearchResult {
126        SearchResult {
127            node_id: "1".into(),
128            doc_id: "doc1".into(),
129            doc_name: "test.py".into(),
130            title: "Data Processing".into(),
131            summary: "Process input data for the pipeline".into(),
132            text: "def process_data(input): ...".into(),
133            source_type: "code".into(),
134            source_path: "src/process.py".into(),
135            line_start: Some(42),
136            line_end: Some(58),
137            score: 0.72,
138            depth: 2,
139            breadcrumb: vec!["Module".into(), "Pipeline".into(), "Data Processing".into()],
140        }
141    }
142
143    #[test]
144    fn test_plain_output_basic() {
145        let plain = PlainOutput::new();
146        let output = plain.render(&[sample_result()], 1);
147        assert!(output.contains("src/process.py"));
148        assert!(output.contains("[code]"));
149        assert!(output.contains("0.72"));
150        assert!(output.contains("Data Processing"));
151    }
152
153    #[test]
154    fn test_plain_output_empty() {
155        let plain = PlainOutput::new();
156        let output = plain.render(&[], 0);
157        assert_eq!(output, "No results found.\n");
158    }
159
160    #[test]
161    fn test_plain_output_no_ansi() {
162        let plain = PlainOutput::new();
163        let output = plain.render(&[sample_result()], 2);
164        // Should not contain ANSI escape sequences
165        assert!(!output.contains("\x1b["));
166    }
167
168    #[test]
169    fn test_plain_output_breadcrumb() {
170        let plain = PlainOutput::new();
171        let output = plain.render(&[sample_result()], 0);
172        assert!(output.contains("├──"));
173        assert!(output.contains("└──"));
174    }
175
176    #[test]
177    fn test_plain_output_verbose_0() {
178        let plain = PlainOutput::new();
179        let output = plain.render(&[sample_result()], 0);
180        assert!(output.contains("Title:"));
181        // verbose=0 should NOT include summary
182        assert!(!output.contains("Summary:"));
183    }
184
185    #[test]
186    fn test_plain_output_verbose_1() {
187        let plain = PlainOutput::new();
188        let output = plain.render(&[sample_result()], 1);
189        assert!(output.contains("Summary:"));
190        // verbose=1 should NOT include text
191        assert!(!output.contains("Text:"));
192    }
193
194    #[test]
195    fn test_plain_output_verbose_2() {
196        let plain = PlainOutput::new();
197        let output = plain.render(&[sample_result()], 2);
198        assert!(output.contains("Summary:"));
199        assert!(output.contains("Text:"));
200        assert!(output.contains("Lines: 42-58"));
201    }
202
203    #[test]
204    fn test_plain_output_line_numbers() {
205        let plain = PlainOutput::new();
206        let output = plain.render(&[sample_result()], 0);
207        assert!(output.contains("Lines: 42-58"));
208    }
209
210    #[test]
211    fn test_plain_output_multiple_results() {
212        let plain = PlainOutput::new();
213        let results = vec![sample_result(), sample_result()];
214        let output = plain.render(&results, 0);
215        assert!(output.contains("Result 1"));
216        assert!(output.contains("Result 2"));
217    }
218
219    #[test]
220    fn test_truncate_to_width_short() {
221        assert_eq!(truncate_to_width("hello", 100), "hello");
222    }
223
224    #[test]
225    fn test_truncate_to_width_exact() {
226        let s = "abcde";
227        assert_eq!(truncate_to_width(s, 5), "abcde");
228    }
229
230    #[test]
231    fn test_truncate_to_width_long() {
232        let long = "a".repeat(200);
233        let truncated = truncate_to_width(&long, 50);
234        assert!(truncated.ends_with("..."));
235        assert!(truncated.width() <= 50);
236    }
237
238    #[test]
239    fn test_truncate_to_tiny_width_never_exceeds_limit() {
240        for width in 0..=3 {
241            assert_eq!(truncate_to_width("知识库", width).width(), width);
242        }
243    }
244}