repotoire 0.8.0

Graph-powered code analysis CLI. 110 detectors for security, architecture, bus factor, and code quality.
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
//! Debug Code Detector
//!
//! Graph-enhanced detection of debug statements left in code.
//! Uses graph to:
//! - Check if function is a logging utility (acceptable)
//! - Count debug statements per function (suggests forgotten cleanup)
//! - Check if it's in a development-only module

use crate::detectors::base::{Detector, DetectorConfig};
use crate::graph::GraphQueryExt;
use crate::models::{deterministic_finding_id, Finding, Severity};
use anyhow::Result;
use regex::Regex;
use std::collections::HashMap;
use std::path::PathBuf;
use std::sync::LazyLock;
use tracing::info;

static DEBUG_PATTERN: LazyLock<Regex> = LazyLock::new(|| {
    Regex::new(r"(?i)(console\.(log|debug|info|warn)|\bprint\(|debugger;?|binding\.pry|byebug|import\s+pdb|pdb\.set_trace)").expect("valid regex")
});

pub struct DebugCodeDetector {
    #[allow(dead_code)] // Part of detector pattern, used for file scanning
    repository_path: PathBuf,
    max_findings: usize,
}

impl DebugCodeDetector {
    crate::detectors::detector_new!(100);

    /// Check if function is a logging/debug utility (acceptable)
    fn is_logging_utility(func_name: &str) -> bool {
        let logging_patterns = [
            "log", "debug", "trace", "print", "dump", "inspect", "show", "display", "info",
            "output", "report",
        ];
        let name_lower = func_name.to_lowercase();
        logging_patterns.iter().any(|p| name_lower.contains(p))
    }

    /// Check if path is a development-only module
    fn is_dev_only_path(path: &str) -> bool {
        let dev_patterns = [
            "/dev/",
            "/debug/",
            "/utils/debug",
            "/helpers/debug",
            "debug_",
            "_debug.",
            "/logging/",
            "/management/commands/",
            "/management/",
            "/cli/",
            "/cmd/",
            // Info/inspection utilities where print IS the feature
            "ogrinfo",
            "ogrinspect",
        ];
        // Normalize: ensure path starts with '/' so patterns like "/management/" match relative paths
        let normalized = if path.starts_with('/') {
            path.to_string()
        } else {
            format!("/{}", path)
        };
        dev_patterns.iter().any(|p| normalized.contains(p))
    }
}

impl Detector for DebugCodeDetector {
    fn name(&self) -> &'static str {
        "debug-code"
    }
    fn description(&self) -> &'static str {
        "Detects debug statements left in code"
    }

    fn requires_graph(&self) -> bool {
        false
    }

    fn file_extensions(&self) -> &'static [&'static str] {
        &["py", "js", "ts", "jsx", "tsx", "rb", "java", "go", "rs"]
    }

    fn detect(
        &self,
        ctx: &crate::detectors::analysis_context::AnalysisContext,
    ) -> Result<Vec<Finding>> {
        let graph = ctx.graph;
        let files = &ctx.as_file_provider();
        let mut findings = vec![];
        let mut debug_per_file: HashMap<String, usize> = HashMap::new();

        for path in
            files.files_with_extensions(&["py", "js", "ts", "jsx", "tsx", "rb", "java", "go"])
        {
            if findings.len() >= self.max_findings {
                break;
            }

            let path_str = path.to_string_lossy().to_string();

            // Skip test files
            if crate::detectors::base::is_test_path(&path_str) || path_str.contains("spec") {
                continue;
            }

            // Skip dev-only modules (acceptable to have debug code)
            if Self::is_dev_only_path(&path_str) {
                continue;
            }

            // Skip non-production paths (examples, docs, scripts)
            if crate::detectors::content_classifier::is_non_production_path(&path_str) {
                continue;
            }

            // Skip example files
            if path_str.contains("/examples/")
                || path_str.contains("/example/")
                || path_str.contains("/docs/")
                || path_str.contains("/documentation/")
            {
                continue;
            }

            if let Some(content) = files.masked_content(path) {
                let mut file_debug_count = 0;
                let lines: Vec<&str> = content.lines().collect();

                for (i, line) in lines.iter().enumerate() {
                    let prev_line = if i > 0 { Some(lines[i - 1]) } else { None };
                    if crate::detectors::is_line_suppressed(line, prev_line) {
                        continue;
                    }

                    let trimmed = line.trim();
                    if trimmed.starts_with("//") || trimmed.starts_with("#") {
                        continue;
                    }

                    // Skip verbosity-guarded prints (CLI command output)
                    if trimmed.starts_with("print(") || trimmed.starts_with("print (") {
                        if let Some(prev) = prev_line {
                            let prev_trimmed = prev.trim();
                            if prev_trimmed.contains("verbosity")
                                || prev_trimmed.contains("verbose")
                            {
                                continue;
                            }
                        }
                    }

                    // Skip print() in except/catch blocks (error reporting, not debug)
                    let trimmed_check = line.trim();
                    if trimmed_check.starts_with("print(") || trimmed_check.starts_with("print (") {
                        let current_indent = line.len() - trimmed_check.len();
                        let mut in_except = false;
                        for prev_idx in (0..i).rev() {
                            let prev_trimmed = lines[prev_idx].trim();
                            if prev_trimmed.is_empty() {
                                continue;
                            }
                            let prev_indent = lines[prev_idx].len() - prev_trimmed.len();
                            if prev_indent < current_indent
                                && (prev_trimmed.starts_with("except")
                                    || prev_trimmed.starts_with("except:"))
                            {
                                in_except = true;
                                break;
                            }
                            if prev_indent <= current_indent {
                                break;
                            }
                        }
                        if in_except {
                            continue;
                        }
                    }

                    if DEBUG_PATTERN.is_match(line) {
                        let line_num = (i + 1) as u32;
                        let containing_func =
                            graph.find_function_at(&path_str, line_num).map(|f| {
                                f.node_name(crate::graph::interner::global_interner())
                                    .to_string()
                            });

                        // Skip if in a logging utility function
                        if let Some(ref func) = containing_func {
                            if Self::is_logging_utility(func) {
                                continue;
                            }
                        }

                        file_debug_count += 1;

                        // Calculate severity
                        let severity = if line.contains("pdb")
                            || line.contains("debugger")
                            || line.contains("binding.pry")
                        {
                            Severity::High // Interactive debuggers are definitely leftover
                        } else if file_debug_count > 5 {
                            Severity::Medium // Many debug statements suggests forgotten cleanup
                        } else {
                            Severity::Low
                        };

                        let mut notes = Vec::new();
                        if let Some(func) = &containing_func {
                            notes.push(format!("📦 In function: `{}`", func));
                        }
                        if file_debug_count > 1 {
                            notes.push(format!(
                                "📊 {} debug statements in this file so far",
                                file_debug_count
                            ));
                        }

                        let context_notes = if notes.is_empty() {
                            String::new()
                        } else {
                            format!("\n\n**Analysis:**\n{}", notes.join("\n"))
                        };

                        let suggestion = if line.contains("print") {
                            "Replace with proper logging:\n\
                             ```python\n\
                             import logging\n\
                             logger = logging.getLogger(__name__)\n\
                             logger.debug('message')  # Only shows in debug mode\n\
                             ```"
                            .to_string()
                        } else if line.contains("console.log") {
                            "Remove or replace with a logging library that can be disabled:\n\
                             ```javascript\n\
                             import debug from 'debug';\n\
                             const log = debug('app:module');\n\
                             log('message');  // Only shows when DEBUG=app:*\n\
                             ```"
                            .to_string()
                        } else {
                            "Remove debug code or replace with proper logging.".to_string()
                        };

                        findings.push(Finding {
                            id: String::new(),
                            detector: "DebugCodeDetector".to_string(),
                            severity,
                            title: if line.contains("debugger") || line.contains("pdb") {
                                "Interactive debugger left in code".to_string()
                            } else {
                                "Debug code left in".to_string()
                            },
                            description: format!(
                                "Debug statements should be removed before production.{}",
                                context_notes
                            ),
                            affected_files: vec![path.to_path_buf()],
                            line_start: Some(line_num),
                            line_end: Some(line_num),
                            suggested_fix: Some(suggestion),
                            estimated_effort: Some("5 minutes".to_string()),
                            category: Some("code-quality".to_string()),
                            cwe_id: Some("CWE-489".to_string()),
                            why_it_matters: Some(
                                "Debug code can leak sensitive information, clutter logs, \
                                 and interactive debuggers will hang the application."
                                    .to_string(),
                            ),
                            ..Default::default()
                        });
                    }
                }

                if file_debug_count > 0 {
                    debug_per_file.insert(path_str, file_debug_count);
                }
            }
        }

        info!(
            "DebugCodeDetector found {} findings (graph-aware)",
            findings.len()
        );
        Ok(findings)
    }
}

impl crate::detectors::RegisteredDetector for DebugCodeDetector {
    fn create(init: &crate::detectors::DetectorInit) -> std::sync::Arc<dyn Detector> {
        std::sync::Arc::new(Self::new(init.repo_path))
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::graph::builder::GraphBuilder;

    #[test]
    fn test_detects_print_statement() {
        let store = GraphBuilder::new().freeze();
        let detector = DebugCodeDetector::new("/mock/repo");
        let ctx = crate::detectors::analysis_context::AnalysisContext::test_with_mock_files(
            &store,
            vec![(
                "app.py",
                "def process(data):\n    print(data)\n    return data + 1\n",
            )],
        );
        let findings = detector.detect(&ctx).expect("detection should succeed");
        assert!(
            !findings.is_empty(),
            "Should detect print() statement. Found: {:?}",
            findings.iter().map(|f| &f.title).collect::<Vec<_>>()
        );
    }

    #[test]
    fn test_no_finding_for_clean_code() {
        let store = GraphBuilder::new().freeze();
        let detector = DebugCodeDetector::new("/mock/repo");
        let ctx = crate::detectors::analysis_context::AnalysisContext::test_with_mock_files(&store, vec![
            ("app.py", "import logging\n\nlogger = logging.getLogger(__name__)\n\ndef process(data):\n    logger.info(\"Processing data\")\n    return data + 1\n"),
        ]);
        let findings = detector.detect(&ctx).expect("detection should succeed");
        assert!(
            findings.is_empty(),
            "Should not flag proper logging. Found: {:?}",
            findings.iter().map(|f| &f.title).collect::<Vec<_>>()
        );
    }

    #[test]
    fn test_no_finding_for_debug_in_docstring() {
        let store = GraphBuilder::new().freeze();
        let detector = DebugCodeDetector::new("/mock/repo");
        let ctx = crate::detectors::analysis_context::AnalysisContext::test_with_mock_files(&store, vec![
            ("app.py", "def run_server():\n    \"\"\"\n    Start the server.\n    Use debug = True for development.\n    The debugger provides interactive tracing.\n    \"\"\"\n    app.run()\n"),
        ]);
        let findings = detector.detect(&ctx).expect("detection should succeed");
        assert!(
            findings.is_empty(),
            "Should not flag debug/debugger inside docstrings. Found: {:?}",
            findings.iter().map(|f| &f.title).collect::<Vec<_>>()
        );
    }

    #[test]
    fn test_no_finding_for_debug_in_string_literal() {
        let store = GraphBuilder::new().freeze();
        let detector = DebugCodeDetector::new("/mock/repo");
        let ctx = crate::detectors::analysis_context::AnalysisContext::test_with_mock_files(&store, vec![
            ("cli.py", "import click\n\n@click.option(\"--debug\", is_flag=True, help=\"Enable debug mode\")\ndef main(debug):\n    pass\n"),
        ]);
        let findings = detector.detect(&ctx).expect("detection should succeed");
        assert!(
            findings.is_empty(),
            "Should not flag debug in CLI option strings. Found: {:?}",
            findings.iter().map(|f| &f.title).collect::<Vec<_>>()
        );
    }

    #[test]
    fn test_no_finding_for_pprint() {
        let store = GraphBuilder::new().freeze();
        let detector = DebugCodeDetector::new("/mock/repo");
        let ctx = crate::detectors::analysis_context::AnalysisContext::test_with_mock_files(
            &store,
            vec![(
                "filters.py",
                "def pprint(value):\n    return str(value)\n\nresult = pprint(data)\n",
            )],
        );
        let findings = detector.detect(&ctx).expect("detection should succeed");
        assert!(
            findings.is_empty(),
            "Should not flag pprint(). Found: {:?}",
            findings.iter().map(|f| &f.title).collect::<Vec<_>>()
        );
    }

    #[test]
    fn test_no_finding_for_verbosity_guarded_print() {
        let store = GraphBuilder::new().freeze();
        let detector = DebugCodeDetector::new("/mock/repo");
        let ctx = crate::detectors::analysis_context::AnalysisContext::test_with_mock_files(
            &store,
            vec![(
                "mgmt.py",
                "def handle(self):\n    if verbosity >= 2:\n        print(\"Processing...\")\n",
            )],
        );
        let findings = detector.detect(&ctx).expect("detection should succeed");
        assert!(
            findings.is_empty(),
            "Should not flag verbosity-guarded print(). Found: {:?}",
            findings.iter().map(|f| &f.title).collect::<Vec<_>>()
        );
    }

    #[test]
    fn test_no_finding_for_management_command_path() {
        let store = GraphBuilder::new().freeze();
        let detector = DebugCodeDetector::new("/mock/repo");
        let ctx = crate::detectors::analysis_context::AnalysisContext::test_with_mock_files(
            &store,
            vec![(
                "management/commands/migrate.py",
                "def handle(self):\n    print(\"Running migrations...\")\n",
            )],
        );
        let findings = detector.detect(&ctx).expect("detection should succeed");
        assert!(
            findings.is_empty(),
            "Should not flag print() in management commands. Found: {:?}",
            findings.iter().map(|f| &f.title).collect::<Vec<_>>()
        );
    }

    #[test]
    fn test_no_finding_for_debug_kwarg() {
        let store = GraphBuilder::new().freeze();
        let detector = DebugCodeDetector::new("/mock/repo");
        let ctx = crate::detectors::analysis_context::AnalysisContext::test_with_mock_files(&store, vec![
            ("views.py", "from django.template import Engine\n\nDEBUG_ENGINE = Engine(\n    debug=True,\n    libraries={},\n)\n"),
        ]);
        let findings = detector.detect(&ctx).expect("detection should succeed");
        assert!(
            findings.is_empty(),
            "Should not flag debug=True as keyword argument. Found: {:?}",
            findings.iter().map(|f| &f.title).collect::<Vec<_>>()
        );
    }

    #[test]
    fn test_no_finding_for_info_utility() {
        let store = GraphBuilder::new().freeze();
        let detector = DebugCodeDetector::new("/mock/repo");
        let ctx = crate::detectors::analysis_context::AnalysisContext::test_with_mock_files(&store, vec![
            ("utils/ogrinfo.py", "def ogrinfo(data_source):\n    \"\"\"Walk the available layers.\"\"\"\n    print(data_source.name)\n    print(layer.num_feat)\n"),
        ]);
        let findings = detector.detect(&ctx).expect("detection should succeed");
        assert!(
            findings.is_empty(),
            "Should not flag print() in info utilities. Found: {:?}",
            findings.iter().map(|f| &f.title).collect::<Vec<_>>()
        );
    }

    #[test]
    fn test_no_finding_for_print_in_except_block() {
        let store = GraphBuilder::new().freeze();
        let detector = DebugCodeDetector::new("/mock/repo");
        let ctx = crate::detectors::analysis_context::AnalysisContext::test_with_mock_files(&store, vec![
            ("utils/archive.py", "def extract(self):\n    try:\n        do_something()\n    except Exception as exc:\n        print(\"Invalid member: %s\" % exc)\n"),
        ]);
        let findings = detector.detect(&ctx).expect("detection should succeed");
        assert!(
            findings.is_empty(),
            "Should not flag print() in except blocks. Found: {:?}",
            findings.iter().map(|f| &f.title).collect::<Vec<_>>()
        );
    }
}