Skip to main content

lean_ctx/core/
compressor.rs

1use similar::{ChangeTag, TextDiff};
2
3pub fn aggressive_compress(content: &str, ext: Option<&str>) -> String {
4    let mut result = Vec::new();
5    let is_python = matches!(ext, Some("py"));
6    let is_html = matches!(ext, Some("html" | "htm" | "xml" | "svg"));
7    let is_sql = matches!(ext, Some("sql"));
8    let is_shell = matches!(ext, Some("sh" | "bash" | "zsh" | "fish"));
9
10    let mut in_block_comment = false;
11
12    for line in content.lines() {
13        let trimmed = line.trim();
14
15        if trimmed.is_empty() {
16            continue;
17        }
18
19        if in_block_comment {
20            if trimmed.contains("*/") || (is_html && trimmed.contains("-->")) {
21                in_block_comment = false;
22            }
23            continue;
24        }
25
26        if trimmed.starts_with("/*") || (is_html && trimmed.starts_with("<!--")) {
27            if !(trimmed.contains("*/") || trimmed.contains("-->")) {
28                in_block_comment = true;
29            }
30            continue;
31        }
32
33        if trimmed.starts_with("//") && !trimmed.starts_with("///") {
34            continue;
35        }
36        if trimmed.starts_with('*') || trimmed.starts_with("*/") {
37            continue;
38        }
39        if is_python && trimmed.starts_with('#') {
40            continue;
41        }
42        if is_sql && trimmed.starts_with("--") {
43            continue;
44        }
45        if is_shell && trimmed.starts_with('#') && !trimmed.starts_with("#!") {
46            continue;
47        }
48        if !is_python && trimmed.starts_with('#') && trimmed.contains('[') {
49            continue;
50        }
51
52        if trimmed == "}" || trimmed == "};" || trimmed == ");" || trimmed == "});" {
53            result.push(trimmed.to_string());
54            continue;
55        }
56
57        let normalized = normalize_indentation(line);
58        result.push(normalized);
59    }
60
61    result.join("\n")
62}
63
64/// Lightweight post-processing cleanup: collapses consecutive closing braces,
65/// removes whitespace-only lines, and limits consecutive blank lines to 1.
66pub fn lightweight_cleanup(content: &str) -> String {
67    let mut result: Vec<String> = Vec::new();
68    let mut blank_count = 0u32;
69    let mut close_brace_count = 0u32;
70
71    for line in content.lines() {
72        let trimmed = line.trim();
73
74        if trimmed.is_empty() {
75            close_brace_count = 0;
76            blank_count += 1;
77            if blank_count <= 1 {
78                result.push(String::new());
79            }
80            continue;
81        }
82        blank_count = 0;
83
84        if matches!(trimmed, "}" | "};" | ");" | "});" | ")") {
85            close_brace_count += 1;
86            if close_brace_count <= 2 {
87                result.push(trimmed.to_string());
88            }
89            continue;
90        }
91        close_brace_count = 0;
92
93        result.push(line.to_string());
94    }
95
96    result.join("\n")
97}
98
99/// Safeguard: ensures compression ratio stays within safe bounds.
100/// Returns the compressed content if ratio is in [0.15, 1.0], otherwise the original.
101pub fn safeguard_ratio(original: &str, compressed: &str) -> String {
102    let orig_tokens = super::tokens::count_tokens(original);
103    let comp_tokens = super::tokens::count_tokens(compressed);
104
105    if orig_tokens == 0 {
106        return compressed.to_string();
107    }
108
109    let ratio = comp_tokens as f64 / orig_tokens as f64;
110    if ratio < 0.15 || comp_tokens > orig_tokens {
111        original.to_string()
112    } else {
113        compressed.to_string()
114    }
115}
116
117fn normalize_indentation(line: &str) -> String {
118    let content = line.trim_start();
119    let leading = line.len() - content.len();
120    let has_tabs = line.starts_with('\t');
121    let reduced = if has_tabs { leading } else { leading / 2 };
122    format!("{}{}", " ".repeat(reduced), content)
123}
124
125pub fn diff_content(old_content: &str, new_content: &str) -> String {
126    if old_content == new_content {
127        return "āˆ… no changes".to_string();
128    }
129
130    let diff = TextDiff::from_lines(old_content, new_content);
131    let mut changes = Vec::new();
132    let mut additions = 0usize;
133    let mut deletions = 0usize;
134
135    for change in diff.iter_all_changes() {
136        let line_no = change.new_index().or(change.old_index()).map(|i| i + 1);
137        let text = change.value().trim_end_matches('\n');
138        match change.tag() {
139            ChangeTag::Insert => {
140                additions += 1;
141                if let Some(n) = line_no {
142                    changes.push(format!("+{n}: {text}"));
143                }
144            }
145            ChangeTag::Delete => {
146                deletions += 1;
147                if let Some(n) = line_no {
148                    changes.push(format!("-{n}: {text}"));
149                }
150            }
151            ChangeTag::Equal => {}
152        }
153    }
154
155    if changes.is_empty() {
156        return "āˆ… no changes".to_string();
157    }
158
159    changes.push(format!("\nāˆ‚ +{additions}/-{deletions} lines"));
160    changes.join("\n")
161}
162
163#[cfg(test)]
164mod tests {
165    use super::*;
166
167    #[test]
168    fn test_diff_insertion() {
169        let old = "line1\nline2\nline3";
170        let new = "line1\nline2\nnew_line\nline3";
171        let result = diff_content(old, new);
172        assert!(result.contains("+"), "should show additions");
173        assert!(result.contains("new_line"));
174    }
175
176    #[test]
177    fn test_diff_deletion() {
178        let old = "line1\nline2\nline3";
179        let new = "line1\nline3";
180        let result = diff_content(old, new);
181        assert!(result.contains("-"), "should show deletions");
182        assert!(result.contains("line2"));
183    }
184
185    #[test]
186    fn test_diff_no_changes() {
187        let content = "same\ncontent";
188        assert_eq!(diff_content(content, content), "āˆ… no changes");
189    }
190
191    #[test]
192    fn test_lightweight_cleanup_collapses_braces() {
193        let input = "fn main() {\n    inner()\n}\n}\n}\n}\n}\nfn next() {}";
194        let result = lightweight_cleanup(input);
195        assert!(
196            result.matches('}').count() <= 3,
197            "should collapse consecutive closing braces"
198        );
199        assert!(result.contains("fn next()"));
200    }
201
202    #[test]
203    fn test_lightweight_cleanup_blank_lines() {
204        let input = "line1\n\n\n\n\nline2";
205        let result = lightweight_cleanup(input);
206        let blank_runs = result.split("line1").nth(1).unwrap();
207        let blanks = blank_runs.matches('\n').count();
208        assert!(blanks <= 2, "should collapse multiple blank lines");
209    }
210
211    #[test]
212    fn test_safeguard_ratio_prevents_over_compression() {
213        let original = "a ".repeat(100);
214        let too_compressed = "a";
215        let result = safeguard_ratio(&original, too_compressed);
216        assert_eq!(result, original, "should return original when ratio < 0.15");
217    }
218
219    #[test]
220    fn test_aggressive_strips_comments() {
221        let code = "fn main() {\n    // a comment\n    let x = 1;\n}";
222        let result = aggressive_compress(code, Some("rs"));
223        assert!(!result.contains("// a comment"));
224        assert!(result.contains("let x = 1"));
225    }
226
227    #[test]
228    fn test_aggressive_python_comments() {
229        let code = "def main():\n    # comment\n    x = 1";
230        let result = aggressive_compress(code, Some("py"));
231        assert!(!result.contains("# comment"));
232        assert!(result.contains("x = 1"));
233    }
234
235    #[test]
236    fn test_aggressive_preserves_doc_comments() {
237        let code = "/// Doc comment\nfn main() {}";
238        let result = aggressive_compress(code, Some("rs"));
239        assert!(result.contains("/// Doc comment"));
240    }
241
242    #[test]
243    fn test_aggressive_block_comment() {
244        let code = "/* start\n * middle\n */ end\nfn main() {}";
245        let result = aggressive_compress(code, Some("rs"));
246        assert!(!result.contains("start"));
247        assert!(!result.contains("middle"));
248        assert!(result.contains("fn main()"));
249    }
250}