towl 0.3.7

A fast CLI tool to scan codebases for TODO comments and output them in multiple formats
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
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
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
use std::path::Path;

use regex::Regex;

use crate::{
    comment::todo::{TodoComment, TodoType},
    config::ParsingConfig,
    MAX_CONTEXT_LINES, MIN_CONTEXT_LINES,
};

use super::error::TowlParserError;
use super::pattern::{Pattern, MAX_TOTAL_PATTERNS};

/// Parses file content to extract TODO comments with context.
///
/// Uses configurable regex patterns to identify comments and TODO markers,
/// extracting surrounding context and function information for each match.
pub struct Parser {
    pub(super) comment_patterns: Vec<Regex>,
    pub(super) patterns: Vec<Pattern>,
    pub(super) function_patterns: Vec<Regex>,
    pub(super) context_lines: usize,
}

impl Parser {
    /// Creates a new parser from configuration.
    ///
    /// Compiles all regex patterns from the config at construction time for efficiency.
    ///
    /// # Errors
    /// Returns `TowlParserError::InvalidRegexPattern` if any pattern is malformed.
    /// Returns `TowlParserError::TooManyTotalPatterns` if total patterns exceed the budget.
    pub(crate) fn new(config: &ParsingConfig) -> Result<Self, TowlParserError> {
        let total_patterns = config
            .comment_prefixes
            .len()
            .saturating_add(config.todo_patterns.len())
            .saturating_add(config.function_patterns.len());

        if total_patterns > MAX_TOTAL_PATTERNS {
            return Err(TowlParserError::TooManyTotalPatterns {
                count: total_patterns,
                max_allowed: MAX_TOTAL_PATTERNS,
            });
        }

        let comment_patterns = config
            .comment_prefixes
            .iter()
            .map(|p| Self::build_regex(p))
            .collect::<Result<Vec<_>, _>>()?;

        let patterns = config
            .todo_patterns
            .iter()
            .map(|p| {
                let regex = Self::build_regex(p)?;
                let todo_type: TodoType = p
                    .as_str()
                    .try_into()
                    .map_err(TowlParserError::UnknownConfigPattern)?;
                Ok(Pattern { regex, todo_type })
            })
            .collect::<Result<Vec<_>, TowlParserError>>()?;

        let function_patterns = config
            .function_patterns
            .iter()
            .map(|p| Self::build_regex(p))
            .collect::<Result<Vec<_>, _>>()?;

        let context_lines = config
            .include_context_lines
            .clamp(MIN_CONTEXT_LINES, MAX_CONTEXT_LINES);

        Ok(Self {
            comment_patterns,
            patterns,
            function_patterns,
            context_lines,
        })
    }

    /// Parses file content to extract all TODO comments.
    ///
    /// Identifies comment lines using configured patterns, then searches for TODO markers
    /// within those comments. For each TODO found, extracts:
    /// - Description text
    /// - Surrounding context lines
    /// - Function context (if applicable)
    /// - Location information (line, column)
    ///
    /// # Errors
    /// Returns `TowlParserError` if TODO extraction fails (rare, defensive).
    pub(crate) fn parse(
        &self,
        path: &Path,
        content: &str,
    ) -> Result<Vec<TodoComment>, TowlParserError> {
        let mut todos = Vec::new();
        let lines: Vec<&str> = content.lines().collect();

        for (line_idx, line) in lines.iter().enumerate() {
            let is_comment = self
                .comment_patterns
                .iter()
                .any(|pattern| pattern.is_match(line));

            if !is_comment {
                continue;
            }

            for pattern in &self.patterns {
                if let Some(captures) = pattern.regex.captures(line) {
                    let todo = self.extract_todo(
                        path,
                        line,
                        line_idx + 1,
                        &captures,
                        &lines,
                        pattern.todo_type,
                    )?;
                    todos.push(todo);
                }
            }
        }

        Ok(todos)
    }

    fn extract_todo(
        &self,
        path: &Path,
        line: &str,
        line_number: usize,
        captures: &regex::Captures,
        all_lines: &[&str],
        todo_type: TodoType,
    ) -> Result<TodoComment, TowlParserError> {
        let description = if captures.len() > 1 {
            captures.get(1).map(|m| m.as_str().trim().to_string()) // clone: owned String for TodoComment field
        } else {
            captures.get(0).map(|m| m.as_str().trim().to_string()) // clone: owned String for TodoComment field
        }
        .unwrap_or_else(|| "No description".to_string()); // clone: owned String for TodoComment field

        let full_match = captures.get(0).ok_or(TowlParserError::RegexGroupMissing)?;
        let match_start = full_match.start();
        let match_end = full_match.end();

        let context_lines = self.extract_context(all_lines, line_number - 1);

        let function_context = self.find_function_context(all_lines, line_number - 1);

        let id = format!("{}_L{}_C{}", path.display(), line_number, match_start);

        Ok(TodoComment {
            id,
            file_path: path.to_path_buf(), // clone: owned path for TodoComment struct
            line_number,
            column_start: match_start,
            column_end: match_end,
            todo_type,
            original_text: line.to_string(), // clone: owned String for TodoComment struct
            description,
            context_lines,
            function_context,
            analysis: None,
        })
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use proptest::prelude::*;
    use rstest::rstest;
    use std::path::PathBuf;

    #[rstest]
    #[case("fn test_function() {", Some("test_function:1"))]
    #[case("pub fn public_function() {", Some("public_function:1"))]
    #[case("def python_function():", Some("python_function:1"))]
    #[case("    fn indented_function() {", Some("indented_function:1"))]
    #[case("let variable = 5;", None)]
    fn test_function_context_detection(#[case] line: &str, #[case] expected_context: Option<&str>) {
        let config = crate::config::test_parsing_config();
        let parser = Parser::new(&config).unwrap();

        let lines = vec![line];
        let context = parser.find_function_context(&lines, 0);

        match expected_context {
            Some(expected) => {
                assert_eq!(context, Some(expected.to_string()));
            }
            None => {
                assert_eq!(context, None);
            }
        }
    }

    #[rstest]
    #[case(0, vec!["2: line2", "3: line3", "4: line4"])]
    #[case(2, vec!["1: line1", "2: line2", "4: line4", "5: line5", "6: line6"])]
    #[case(4, vec!["2: line2", "3: line3", "4: line4", "6: line6"])]
    fn test_context_extraction(#[case] current_line: usize, #[case] expected_context: Vec<&str>) {
        let config = crate::config::test_parsing_config();
        let parser = Parser::new(&config).unwrap();

        let lines = vec!["line1", "line2", "line3", "line4", "line5", "line6"];
        let context = parser.extract_context(&lines, current_line);

        let expected: Vec<String> = expected_context.iter().map(ToString::to_string).collect();
        assert_eq!(context, expected);
    }

    prop_compose! {
        fn valid_comment_prefix()(prefix in r"(//|#|\*|/\*)") -> String {
            prefix
        }
    }

    prop_compose! {
        fn valid_todo_keyword()(keyword in r"(TODO|FIXME|HACK|NOTE|BUG)") -> String {
            keyword
        }
    }

    prop_compose! {
        fn valid_description()(desc in r"[a-zA-Z0-9.,!?-][a-zA-Z0-9 .,!?-]{0,99}") -> String {
            desc
        }
    }

    proptest! {
        #[test]
        fn prop_test_comment_with_todo_always_detected(
            prefix in valid_comment_prefix(),
            keyword in valid_todo_keyword(),
            description in valid_description()
        ) {
            let config = crate::config::test_parsing_config();
            let parser = Parser::new(&config).unwrap();
            let path = PathBuf::from("test.rs");

            let line = format!("{prefix} {keyword}: {description}");
            let result = parser.parse(&path, &line).unwrap();

            if prefix == "//" || prefix == "#" || prefix == "*" {
                prop_assert!(!result.is_empty(), "Failed to detect TODO in: {}", line);
                if !result.is_empty() {
                    let trimmed_desc = description.trim();
                    if !trimmed_desc.is_empty() {
                        prop_assert!(result[0].description.contains(trimmed_desc) || result[0].description.trim() == trimmed_desc);
                    }
                }
            }
        }

        #[test]
        fn prop_test_non_comment_todos_ignored(
            keyword in valid_todo_keyword(),
            description in valid_description()
        ) {
            let config = crate::config::test_parsing_config();
            let parser = Parser::new(&config).unwrap();
            let path = PathBuf::from("test.rs");

            let line = format!("let {} = \"{}: {}\";", keyword.to_lowercase(), keyword, description);
            let result = parser.parse(&path, &line).unwrap();

            prop_assert!(result.is_empty(), "Incorrectly detected TODO in string: {}", line);
        }

        #[test]
        fn prop_test_whitespace_handling(
            leading_ws in r"\s*",
            trailing_ws in r"\s*",
            keyword in valid_todo_keyword(),
            description in valid_description()
        ) {
            let config = crate::config::test_parsing_config();
            let parser = Parser::new(&config).unwrap();
            let path = PathBuf::from("test.rs");

            let line = format!("{leading_ws}// {keyword}: {description}{trailing_ws}");
            let result = parser.parse(&path, &line).unwrap();

            prop_assert!(!result.is_empty(), "Failed to detect TODO with whitespace: {}", line);
            if !result.is_empty() {
                prop_assert!(result[0].description.trim() == description.trim());
            }
        }

        #[test]
        fn prop_test_line_number_accuracy(
            lines_before in prop::collection::vec(".*", 0..10),
            keyword in valid_todo_keyword(),
            description in valid_description(),
            lines_after in prop::collection::vec(".*", 0..10)
        ) {
            let config = crate::config::test_parsing_config();
            let parser = Parser::new(&config).unwrap();
            let path = PathBuf::from("test.rs");

            let todo_line = format!("// {keyword}: {description}");
            let expected_line_number = lines_before.len() + 1;

            let mut all_lines = lines_before;
            all_lines.push(todo_line);
            all_lines.extend(lines_after);

            let content = all_lines.join("\n");
            let result = parser.parse(&path, &content).unwrap();

            prop_assert!(!result.is_empty(), "Failed to detect TODO in multi-line content");
            if !result.is_empty() {
                prop_assert_eq!(result[0].line_number, expected_line_number);
            }
        }
    }

    #[test]
    fn test_total_pattern_budget_exceeded() {
        let mut config = crate::config::test_parsing_config();
        config.comment_prefixes = (0..20).map(|i| format!("prefix_{i}")).collect();
        config.todo_patterns = (0..20).map(|i| format!("todo_{i}")).collect();
        config.function_patterns = (0..20).map(|i| format!("func_{i}")).collect();

        let result = Parser::new(&config);
        assert!(result.is_err());
        assert!(matches!(
            result,
            Err(TowlParserError::TooManyTotalPatterns {
                count: 60,
                max_allowed: 50
            })
        ));
    }

    #[test]
    fn test_malformed_regex_patterns() {
        let mut config = crate::config::test_parsing_config();
        config.todo_patterns = vec!["[invalid regex".to_string()];

        let result = Parser::new(&config);
        assert!(matches!(
            result,
            Err(TowlParserError::InvalidRegexPattern(..))
        ));
    }

    #[test]
    fn test_column_position_accuracy() {
        let config = crate::config::test_parsing_config();
        let parser = Parser::new(&config).unwrap();
        let path = PathBuf::from("test.rs");

        let content = "    // TODO: Test column positions";
        let result = parser.parse(&path, content).unwrap();

        assert_eq!(result.len(), 1);
        assert_eq!(result[0].column_start, 7);
        assert_eq!(result[0].column_end, content.len());
    }

    #[test]
    fn test_pattern_too_long_rejected() {
        let mut config = crate::config::test_parsing_config();
        config.todo_patterns = vec!["a".repeat(257)];
        let result = Parser::new(&config);
        assert!(matches!(
            result,
            Err(TowlParserError::PatternTooLong(257, 256))
        ));
    }

    proptest! {
        #[test]
        fn prop_parser_never_panics_on_any_input(
            content in ".*"
        ) {
            let config = crate::config::test_parsing_config();
            let parser = Parser::new(&config).unwrap();
            let path = PathBuf::from("test.rs");

            let _ = parser.parse(&path, &content);
        }

        #[test]
        fn prop_parsed_todos_have_valid_line_numbers(
            lines in prop::collection::vec("[^\n]*", 1..100)
        ) {
            let config = crate::config::test_parsing_config();
            let parser = Parser::new(&config).unwrap();
            let path = PathBuf::from("test.rs");

            let content = lines.join("\n");
            let todos = parser.parse(&path, &content).unwrap();

            for todo in todos {
                prop_assert!(todo.line_number > 0, "Line number must be positive");
                prop_assert!(
                    todo.line_number <= lines.len(),
                    "Line number {} exceeds total lines {}",
                    todo.line_number,
                    lines.len()
                );
            }
        }

        #[test]
        fn prop_parsed_todos_have_valid_column_positions(
            prefix in "[^\n]*",
            todo_type in prop::sample::select(vec!["TODO", "FIXME", "HACK", "NOTE", "BUG"]),
            description in "[^\n]*"
        ) {
            let config = crate::config::test_parsing_config();
            let parser = Parser::new(&config).unwrap();
            let path = PathBuf::from("test.rs");

            let line = format!("{prefix}// {todo_type}: {description}");
            let content = format!("fn main() {{\n    {line}\n}}");

            let todos = parser.parse(&path, &content).unwrap();

            for todo in &todos {
                prop_assert!(
                    todo.column_start <= todo.column_end,
                    "Column start {} must be <= column end {}",
                    todo.column_start,
                    todo.column_end
                );

                let lines: Vec<&str> = content.lines().collect();
                if todo.line_number > 0 && todo.line_number <= lines.len() {
                    let line_len = lines[todo.line_number - 1].len();
                    prop_assert!(
                        todo.column_end <= line_len,
                        "Column end {} exceeds line length {}",
                        todo.column_end,
                        line_len
                    );
                }
            }
        }

        #[test]
        fn prop_todos_preserve_original_text(
            prefix in "[^\n]*",
            todo_marker in prop::sample::select(vec!["TODO:", "FIXME:", "HACK:", "NOTE:", "BUG:"]),
            description in "[^\n]{0,100}"
        ) {
            let config = crate::config::test_parsing_config();
            let parser = Parser::new(&config).unwrap();
            let path = PathBuf::from("test.rs");

            let original_line = format!("{prefix} // {todo_marker} {description}");
            let content = original_line.clone();

            let todos = parser.parse(&path, &content).unwrap();

            if !todos.is_empty() {
                let todo = &todos[0];
                prop_assert_eq!(
                    todo.original_text.trim(),
                    original_line.trim(),
                    "Original text should be preserved"
                );
            }
        }

        #[test]
        fn prop_multiple_todos_parsed_independently(
            num_todos in 1usize..10usize,
            base_content in "[^\n]*"
        ) {
            let config = crate::config::test_parsing_config();
            let parser = Parser::new(&config).unwrap();
            let path = PathBuf::from("test.rs");

            let mut lines = vec![base_content.clone()];
            for i in 0..num_todos {
                lines.push(format!("// TODO: item {i}"));
                lines.push(base_content.clone());
            }

            let content = lines.join("\n");
            let todos = parser.parse(&path, &content).unwrap();

            prop_assert_eq!(
                todos.len(),
                num_todos,
                "Should find exactly {} TODOs",
                num_todos
            );

            let mut line_numbers: Vec<usize> = todos.iter().map(|t| t.line_number).collect();
            line_numbers.sort_unstable();
            line_numbers.dedup();
            prop_assert_eq!(
                line_numbers.len(),
                todos.len(),
                "Each TODO should have a unique line number"
            );
        }

        #[test]
        fn prop_parser_handles_empty_and_whitespace_lines(
            num_empty in 0usize..10usize,
            num_spaces in 0usize..10usize
        ) {
            let config = crate::config::test_parsing_config();
            let parser = Parser::new(&config).unwrap();
            let path = PathBuf::from("test.rs");

            let mut lines = vec![];
            for _ in 0..num_empty {
                lines.push(String::new());
            }
            lines.push("// TODO: test".to_string());
            for i in 0..num_spaces {
                lines.push(" ".repeat(i));
            }

            let content = lines.join("\n");
            let result = parser.parse(&path, &content);

            prop_assert!(
                result.is_ok(),
                "Parser should handle empty/whitespace lines"
            );

            let todos = result.unwrap();
            prop_assert_eq!(todos.len(), 1, "Should find exactly one TODO");
        }

        #[test]
        fn prop_parser_respects_comment_prefixes(
            non_comment_prefix in "[^/#]*",
            todo_text in "TODO: [^\n]*"
        ) {
            prop_assume!(!non_comment_prefix.contains("//") && !non_comment_prefix.contains('#') && !non_comment_prefix.contains('*'));
            prop_assume!(!todo_text.contains("//") && !todo_text.contains("/*") && !todo_text.contains('*'));

            let config = crate::config::test_parsing_config();
            let parser = Parser::new(&config).unwrap();
            let path = PathBuf::from("test.rs");

            let content = format!("{non_comment_prefix}{todo_text}");
            let todos = parser.parse(&path, &content).unwrap();

            if !non_comment_prefix.is_empty() {
                prop_assert!(
                    todos.is_empty(),
                    "TODO without comment prefix should not be detected"
                );
            }
        }

        #[test]
        fn prop_todo_comment_json_roundtrip(
            id in "[a-z]{10}",
            line in 1usize..10000,
            col_start in 0usize..100,
            col_end in 101usize..200,
            desc in "[a-zA-Z ]{1,100}"
        ) {
            use crate::comment::todo::{TodoComment, TodoType};

            let todo = TodoComment {
                id,
                file_path: PathBuf::from("test.rs"),
                line_number: line,
                column_start: col_start,
                column_end: col_end,
                todo_type: TodoType::Todo,
                original_text: format!("// TODO: {desc}"),
                description: desc,
                context_lines: vec!["context".to_string()],
                function_context: Some("main".to_string()),
                analysis: None,
            };

            let json = serde_json::to_string(&todo).unwrap();
            let decoded: TodoComment = serde_json::from_str(&json).unwrap();
            prop_assert_eq!(todo, decoded);
        }

        #[test]
        fn prop_match_function_name_with_special_chars(
            prefix in "[^\\n]{0,20}",
            func_name in "[a-zA-Z_][a-zA-Z0-9_]{0,20}",
            suffix in "[^\\n]{0,20}"
        ) {
            let config = crate::config::test_parsing_config();
            let parser = Parser::new(&config).unwrap();

            let line = format!("{prefix}fn {func_name}{suffix}");
            let result = parser.match_function_name(&line);

            if let Some(matched) = result {
                prop_assert!(
                    matched.chars().all(|c| c.is_alphanumeric() || c == '_'),
                    "Matched name should only contain alphanumeric or underscore: {:?}",
                    matched
                );
            }
        }
    }
}