[go: up one dir, main page]

uncomment 2.8.2

A CLI tool to remove comments from code using tree-sitter for accurate parsing
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
use crate::ast::visitor::{CommentInfo, CommentVisitor};
use crate::config::{ConfigManager, ResolvedConfig};
use crate::grammar::GrammarManager;
use crate::languages::registry::LanguageRegistry;
use crate::rules::preservation::PreservationRule;
use anyhow::{Context, Result};
use std::path::Path;
use tree_sitter::Parser;

#[derive(Debug, Clone)]
pub struct ProcessingOptions {
    pub remove_todo: bool,
    pub remove_fixme: bool,
    pub remove_doc: bool,
    pub custom_preserve_patterns: Vec<String>,
    pub use_default_ignores: bool,
    pub dry_run: bool,
    pub respect_gitignore: bool,
    pub traverse_git_repos: bool,
}

pub struct Processor {
    parser: Parser,
    registry: LanguageRegistry,
    grammar_manager: GrammarManager,
}

impl Default for Processor {
    fn default() -> Self {
        Self::new()
    }
}

impl Processor {
    pub fn new() -> Self {
        Self {
            parser: Parser::new(),
            registry: LanguageRegistry::new(),
            grammar_manager: GrammarManager::new().expect("Failed to initialize GrammarManager"),
        }
    }

    /// Create a new processor with configured languages from a configuration manager
    pub fn new_with_config(config_manager: &ConfigManager) -> Self {
        let mut registry = LanguageRegistry::new();

        // Register configured languages
        let all_languages = config_manager.get_all_languages();
        registry.register_configured_languages(&all_languages);

        Self {
            parser: Parser::new(),
            registry,
            grammar_manager: GrammarManager::new().expect("Failed to initialize GrammarManager"),
        }
    }

    /// Process a single file with configuration manager
    pub fn process_file_with_config(
        &mut self,
        path: &Path,
        config_manager: &ConfigManager,
        cli_overrides: Option<&ProcessingOptions>,
    ) -> Result<ProcessedFile> {
        // Read file content
        let content = std::fs::read_to_string(path)
            .with_context(|| format!("Failed to read file: {}", path.display()))?;

        // Get language configuration first
        let language_config = self
            .registry
            .detect_language(path)
            .with_context(|| format!("Unsupported file type: {}", path.display()))?
            .clone();

        // Get the language name for configuration lookup
        let language_name = language_config.name.to_lowercase();

        // Get resolved configuration for this file with language-specific overrides
        let mut resolved_config =
            config_manager.get_config_for_file_with_language(path, &language_name);

        // Apply CLI overrides if provided
        if let Some(overrides) = cli_overrides {
            if overrides.remove_doc {
                resolved_config.remove_docs = true;
            }
            if overrides.remove_todo {
                resolved_config.remove_todos = true;
            }
            if overrides.remove_fixme {
                resolved_config.remove_fixme = true;
            }
            // CLI patterns extend config patterns rather than replacing them
            if !overrides.custom_preserve_patterns.is_empty() {
                resolved_config
                    .preserve_patterns
                    .extend(overrides.custom_preserve_patterns.clone());
            }
            // Apply gitignore and traversal settings
            resolved_config.respect_gitignore = overrides.respect_gitignore;
            resolved_config.traverse_git_repos = overrides.traverse_git_repos;
        }

        // Process the content
        let (processed_content, comments_removed) =
            self.process_content_with_config(&content, &language_config, &resolved_config)?;

        Ok(ProcessedFile {
            path: path.to_path_buf(),
            original_content: content,
            processed_content,
            modified: false, // Will be set by the caller after comparison
            comments_removed,
        })
    }

    /// Process file content with resolved configuration
    fn process_content_with_config(
        &mut self,
        content: &str,
        language_config: &crate::languages::config::LanguageConfig,
        resolved_config: &ResolvedConfig,
    ) -> Result<(String, usize)> {
        // Determine which language to use - dynamic or static
        let language = if let Some(grammar_config) = &resolved_config.grammar_config {
            // Use dynamic grammar loading
            self.grammar_manager
                .get_language(&language_config.name, grammar_config)
                .with_context(|| {
                    format!(
                        "Failed to load dynamic grammar for {}",
                        language_config.name
                    )
                })?
        } else {
            // Use static built-in language
            language_config.tree_sitter_language()
        };

        self.parser
            .set_language(&language)
            .context("Failed to set parser language")?;

        // Parse the content
        let tree = self
            .parser
            .parse(content, None)
            .context("Failed to parse source code")?;

        // Create preservation rules based on resolved config
        let preservation_rules = self.create_preservation_rules_from_config(resolved_config);

        // Collect comments using the language-aware visitor
        let mut visitor = CommentVisitor::new_with_language(
            content,
            &preservation_rules,
            language_config.comment_types.clone(),
            language_config.doc_comment_types.clone(),
            language_config.name.clone(),
        );
        visitor.visit_node(tree.root_node());

        let comments_to_remove = visitor.get_comments_to_remove();
        let comments_removed = comments_to_remove.len();

        // Generate output by removing comments
        let output = self.remove_comments_from_content(content, &comments_to_remove);

        Ok((output, comments_removed))
    }

    fn create_preservation_rules_from_config(
        &self,
        config: &ResolvedConfig,
    ) -> Vec<PreservationRule> {
        let mut rules = Vec::new();

        // Always preserve ~keep
        rules.push(PreservationRule::pattern("~keep"));

        // Preserve TODO/FIXME unless explicitly removed
        if !config.remove_todos {
            rules.push(PreservationRule::pattern("TODO"));
            rules.push(PreservationRule::pattern("todo"));
        }
        if !config.remove_fixme {
            rules.push(PreservationRule::pattern("FIXME"));
            rules.push(PreservationRule::pattern("fixme"));
        }

        // Preserve documentation unless explicitly removed
        if !config.remove_docs {
            rules.push(PreservationRule::documentation());
        }

        // Add configured patterns
        for pattern in &config.preserve_patterns {
            rules.push(PreservationRule::pattern(pattern));
        }

        // Add default ignores if enabled
        if config.use_default_ignores {
            let mut comprehensive_rules = PreservationRule::comprehensive_rules();

            // Remove TODO/FIXME rules if they should be removed according to config
            if config.remove_todos {
                comprehensive_rules
                    .retain(|rule| !rule.pattern_matches("TODO") && !rule.pattern_matches("todo"));
            }
            if config.remove_fixme {
                comprehensive_rules.retain(|rule| {
                    !rule.pattern_matches("FIXME") && !rule.pattern_matches("fixme")
                });
            }

            // Remove documentation rules if docs should be removed
            if config.remove_docs {
                comprehensive_rules.retain(|rule| !matches!(rule, PreservationRule::Documentation));
            }

            rules.extend(comprehensive_rules);
        }

        rules
    }

    fn remove_comments_from_content(
        &self,
        content: &str,
        comments_to_remove: &[CommentInfo],
    ) -> String {
        if comments_to_remove.is_empty() {
            return content.to_string();
        }

        // Convert byte positions to char positions once, before any modifications
        let char_positions: Vec<usize> = content
            .char_indices()
            .map(|(byte_pos, _)| byte_pos)
            .collect();
        let total_chars = content.chars().count();

        // Helper function to convert byte position to char position
        let byte_to_char = |byte_pos: usize| -> usize {
            match char_positions.binary_search(&byte_pos) {
                Ok(char_pos) => char_pos,
                Err(char_pos) => char_pos.min(total_chars),
            }
        };

        let mut chars: Vec<char> = content.chars().collect();

        // Sort comments by start position in reverse order to avoid offset issues
        let mut sorted_comments = comments_to_remove.to_vec();
        sorted_comments.sort_by(|a, b| b.start_byte.cmp(&a.start_byte));

        for comment in sorted_comments {
            let start_char = byte_to_char(comment.start_byte);
            let end_char = byte_to_char(comment.end_byte);

            // Find the start and end of the line containing the comment
            let line_start = self.find_line_start(content, comment.start_byte);
            let line_end = self.find_line_end(content, comment.end_byte);
            let line_start_char = byte_to_char(line_start);
            let line_end_char = byte_to_char(line_end);

            // Validate bounds before attempting to slice
            if start_char >= chars.len()
                || end_char > chars.len()
                || start_char > end_char
                || line_start_char >= chars.len()
                || line_end_char > chars.len()
                || line_start_char > line_end_char
            {
                // Skip this comment if indices are out of bounds
                // This can happen when previous removals affected the indices
                continue;
            }

            // Get the line text
            let has_non_whitespace_before = chars[line_start_char..start_char]
                .iter()
                .any(|c| !c.is_whitespace());
            let has_non_whitespace_after = chars[end_char..line_end_char]
                .iter()
                .any(|c| !c.is_whitespace());

            if !has_non_whitespace_before && !has_non_whitespace_after {
                // Remove the entire line (including newline)
                chars.drain(line_start_char..line_end_char);
            } else {
                // Only remove the comment text, leave the rest of the line intact
                chars.drain(start_char..end_char);
            }
        }

        chars.into_iter().collect()
    }

    fn find_line_start(&self, content: &str, byte_pos: usize) -> usize {
        content[..byte_pos]
            .rfind('\n')
            .map(|pos| pos + 1)
            .unwrap_or(0)
    }

    fn find_line_end(&self, content: &str, byte_pos: usize) -> usize {
        content[byte_pos..]
            .find('\n')
            .map(|pos| byte_pos + pos + 1)
            .unwrap_or(content.len())
    }
}

#[derive(Debug)]
pub struct ProcessedFile {
    pub path: std::path::PathBuf,
    pub original_content: String,
    pub processed_content: String,
    pub modified: bool,
    pub comments_removed: usize,
}

// Simple output writer
pub struct OutputWriter {
    dry_run: bool,
    verbose: bool,
}

impl OutputWriter {
    pub fn new(dry_run: bool, verbose: bool) -> Self {
        Self { dry_run, verbose }
    }

    pub fn write_file(&self, processed_file: &ProcessedFile) -> Result<()> {
        let modified = processed_file.original_content != processed_file.processed_content;

        if !modified {
            if self.verbose {
                println!("✓ No changes needed: {}", processed_file.path.display());
            }
            return Ok(());
        }

        if self.dry_run {
            println!("[DRY RUN] Would modify: {}", processed_file.path.display());
            if self.verbose {
                println!("  Removed {} comment(s)", processed_file.comments_removed);
            }
            self.show_diff(processed_file)?;
        } else {
            std::fs::write(&processed_file.path, &processed_file.processed_content).with_context(
                || format!("Failed to write file: {}", processed_file.path.display()),
            )?;

            if self.verbose {
                println!(
                    "✓ Modified: {} (removed {} comment(s))",
                    processed_file.path.display(),
                    processed_file.comments_removed
                );
            } else {
                println!("Modified: {}", processed_file.path.display());
            }
        }

        Ok(())
    }

    fn show_diff(&self, processed_file: &ProcessedFile) -> Result<()> {
        println!("\n--- {}", processed_file.path.display());
        println!("+++ {} (processed)", processed_file.path.display());

        let original_lines: Vec<&str> = processed_file.original_content.lines().collect();
        let processed_lines: Vec<&str> = processed_file.processed_content.lines().collect();

        let max_lines = original_lines.len().max(processed_lines.len());

        for i in 0..max_lines {
            let original_line = original_lines.get(i).copied().unwrap_or("");
            let processed_line = processed_lines.get(i).copied().unwrap_or("");

            if original_line != processed_line {
                if i < original_lines.len() && i >= processed_lines.len() {
                    println!("-{original_line}");
                } else if i >= original_lines.len() && i < processed_lines.len() {
                    println!("+{processed_line}");
                } else if original_line != processed_line {
                    println!("-{original_line}");
                    println!("+{processed_line}");
                }
            }
        }

        Ok(())
    }

    pub fn print_summary(&self, total_files: usize, modified_files: usize) {
        if self.dry_run {
            println!(
                "\n[DRY RUN] Summary: {total_files} files processed, {modified_files} would be modified"
            );
        } else {
            println!("\nSummary: {total_files} files processed, {modified_files} modified");
        }

        if total_files > 0 && modified_files == 0 {
            println!("All files were already comment-free or only contained preserved comments.");
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::config::ResolvedConfig;
    use crate::languages::config::LanguageConfig;

    fn default_resolved_config() -> ResolvedConfig {
        ResolvedConfig {
            remove_todos: false,
            remove_fixme: false,
            remove_docs: false,
            preserve_patterns: Vec::new(),
            use_default_ignores: true,
            respect_gitignore: true,
            traverse_git_repos: false,
            language_config: None,
            grammar_config: None,
        }
    }

    fn process_rust(source: &str) -> String {
        let mut processor = Processor::new();
        let language_config = LanguageConfig::rust();
        let resolved_config = default_resolved_config();
        let (output, _) = processor
            .process_content_with_config(source, &language_config, &resolved_config)
            .expect("processing rust source");
        output
    }

    #[test]
    fn preserves_strings_matching_comment_text() {
        let source = r#"fn main() {
    let pattern = "// comment";
    println!("{}", pattern); // comment
}
"#;

        let processed = process_rust(source);

        assert!(processed.contains("\"// comment\""));
        assert!(!processed.contains("; // comment"));
    }

    #[test]
    fn preserves_macro_invocations_with_comment_like_strings() {
        let source = r#"macro_rules! announce {
    ($msg:expr) => {{
        println!("{}", $msg); // keep
    }};
}

fn main() {
    announce!("// keep");
}
"#;

        let processed = process_rust(source);

        assert!(processed.contains("announce!(\"// keep\");"));
        assert!(!processed.contains("// keep\n"));
    }
}