repotoire 0.9.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
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
use super::*;

// ── Static helper tests ─────────────────────────────────────────────

#[test]
fn test_entry_points() {
    assert!(DeadCodeDetector::is_entry_point("main"));
    assert!(DeadCodeDetector::is_entry_point("__init__"));
    assert!(DeadCodeDetector::is_entry_point("__main__"));
    assert!(DeadCodeDetector::is_entry_point("setUp"));
    assert!(DeadCodeDetector::is_entry_point("tearDown"));
    assert!(DeadCodeDetector::is_entry_point("test_something"));
    assert!(!DeadCodeDetector::is_entry_point("my_function"));
    assert!(!DeadCodeDetector::is_entry_point("helper"));
}

#[test]
fn test_dunder_methods_by_pattern() {
    // Dunder methods are now checked via starts_with("__") && ends_with("__")
    // instead of a static list
    let dunder = |name: &str| name.starts_with("__") && name.ends_with("__");

    assert!(dunder("__str__"));
    assert!(dunder("__repr__"));
    assert!(dunder("__enter__"));
    assert!(dunder("__exit__"));
    assert!(dunder("__call__"));
    assert!(dunder("__post_init__"));
    assert!(dunder("__init_subclass__"));
    assert!(!dunder("my_method"));
    assert!(!dunder("__private")); // Single underscore prefix, not dunder
    assert!(!dunder("regular"));
}

#[test]
fn test_trait_impl_method() {
    // Trait impl methods: QN contains impl<Trait for Type>
    assert!(DeadCodeDetector::is_trait_impl_method(
        "src/detectors/god_class.rs::impl<Detector for GodClassDetector>::detect:42"
    ));
    assert!(DeadCodeDetector::is_trait_impl_method(
        "src/lib.rs::impl<Display for MyStruct>::fmt:15"
    ));
    assert!(DeadCodeDetector::is_trait_impl_method(
        "src/lib.rs::impl<Default for Config>::default:10"
    ));

    // Inherent impl methods: QN has impl<Type> but NOT " for "
    assert!(!DeadCodeDetector::is_trait_impl_method(
        "src/lib.rs::impl<MyStruct>::new:5"
    ));
    // Regular functions
    assert!(!DeadCodeDetector::is_trait_impl_method(
        "src/lib.rs::my_function:1"
    ));
    // Class methods (Python-style)
    assert!(!DeadCodeDetector::is_trait_impl_method(
        "src/app.py::MyClass.process"
    ));
}

#[test]
fn test_severity() {
    let detector = DeadCodeDetector::new();

    assert_eq!(detector.calculate_function_severity(5), Severity::Low);
    assert_eq!(detector.calculate_function_severity(10), Severity::Medium);
    assert_eq!(detector.calculate_function_severity(25), Severity::High);

    assert_eq!(detector.calculate_class_severity(3, 10), Severity::Low);
    assert_eq!(detector.calculate_class_severity(5, 10), Severity::Medium);
    assert_eq!(detector.calculate_class_severity(10, 10), Severity::High);
}

#[test]
fn test_is_test_path() {
    // Rust test module files (tests.rs, test.rs)
    assert!(DeadCodeDetector::is_test_path(
        "src/detectors/dead_code/tests.rs"
    ));
    assert!(DeadCodeDetector::is_test_path("src/some_module/test.rs"));

    // Test directories
    assert!(DeadCodeDetector::is_test_path(
        "tests/integration/test_api.rs"
    ));
    assert!(DeadCodeDetector::is_test_path("src/tests/helpers.rs"));
    assert!(DeadCodeDetector::is_test_path(
        "src/__tests__/utils.test.ts"
    ));
    assert!(DeadCodeDetector::is_test_path("src/spec/helpers.js"));

    // Should NOT match regular files
    assert!(!DeadCodeDetector::is_test_path(
        "src/detectors/dead_code/mod.rs"
    ));
    assert!(!DeadCodeDetector::is_test_path(
        "src/utils/testing_utils.rs"
    ));
    // "test" as substring in filename shouldn't match
    assert!(!DeadCodeDetector::is_test_path("src/contest.rs"));
}

#[test]
fn test_is_benchmark_path() {
    // Rust benches directory
    assert!(DeadCodeDetector::is_benchmark_path(
        "benches/parser_bench.rs"
    ));
    assert!(DeadCodeDetector::is_benchmark_path(
        "repotoire-cli/benches/graph.rs"
    ));

    // Benchmark directories
    assert!(DeadCodeDetector::is_benchmark_path(
        "benchmark/perf_test.py"
    ));
    assert!(DeadCodeDetector::is_benchmark_path(
        "src/benchmarks/throughput.rs"
    ));

    // Should NOT match regular files
    assert!(!DeadCodeDetector::is_benchmark_path("src/detectors/mod.rs"));
    assert!(!DeadCodeDetector::is_benchmark_path("src/bench_utils.rs"));
}

#[test]
fn test_is_pub_api_surface() {
    // Public functions in lib.rs
    assert!(DeadCodeDetector::is_pub_api_surface("src/lib.rs", true));
    assert!(DeadCodeDetector::is_pub_api_surface(
        "repotoire-cli/src/lib.rs",
        true
    ));

    // Public functions in mod.rs
    assert!(DeadCodeDetector::is_pub_api_surface(
        "src/detectors/mod.rs",
        true
    ));
    assert!(DeadCodeDetector::is_pub_api_surface(
        "src/graph/mod.rs",
        true
    ));

    // Non-exported functions in lib.rs should NOT be exempt
    assert!(!DeadCodeDetector::is_pub_api_surface("src/lib.rs", false));
    assert!(!DeadCodeDetector::is_pub_api_surface(
        "src/detectors/mod.rs",
        false
    ));

    // Regular files should NOT be exempt even if exported
    assert!(!DeadCodeDetector::is_pub_api_surface(
        "src/detectors/dead_code.rs",
        true
    ));
    assert!(!DeadCodeDetector::is_pub_api_surface("src/utils.rs", true));
}

// ── Graph flag exemption tests ──────────────────────────────────────

#[test]
fn test_exported_functions_are_skipped() {
    use crate::graph::builder::GraphBuilder;
    use crate::graph::store_models::{CodeNode, FLAG_IS_EXPORTED};

    let mut store = GraphBuilder::new();

    // Add an exported function with no callers
    let mut func =
        CodeNode::function("my_api", "src/lib.rs").with_qualified_name("src/lib.rs::my_api");
    func.flags |= FLAG_IS_EXPORTED;
    store.add_node(func);

    // Add a non-exported function with no callers (should be flagged)
    let internal_func = CodeNode::function("internal_helper", "src/core.rs")
        .with_qualified_name("src/core.rs::internal_helper");
    store.add_node(internal_func);

    let ctx = make_test_analysis_ctx(&store);
    let detector = DeadCodeDetector::new();
    let findings = detector.find_dead_functions(&ctx);

    // Exported function should NOT appear in findings
    assert!(
        !findings.iter().any(|f| f.title.contains("my_api")),
        "Exported function should be skipped"
    );

    // Internal function should appear
    assert!(
        findings.iter().any(|f| f.title.contains("internal_helper")),
        "Non-exported function should be flagged"
    );
}

#[test]
fn test_decorated_functions_are_skipped() {
    use crate::graph::builder::GraphBuilder;
    use crate::graph::store_models::{CodeNode, FLAG_HAS_DECORATORS};

    let mut store = GraphBuilder::new();

    // Add a decorated function with no callers
    let mut func = CodeNode::function("route_handler", "src/routes.py")
        .with_qualified_name("src/routes.py::route_handler");
    func.flags |= FLAG_HAS_DECORATORS;
    store.add_node(func);

    let ctx = make_test_analysis_ctx(&store);
    let detector = DeadCodeDetector::new();
    let findings = detector.find_dead_functions(&ctx);

    assert!(
        !findings.iter().any(|f| f.title.contains("route_handler")),
        "Decorated function should be skipped"
    );
}

#[test]
fn test_address_taken_functions_are_skipped() {
    use crate::graph::builder::GraphBuilder;
    use crate::graph::store_models::{CodeNode, FLAG_ADDRESS_TAKEN};

    let mut store = GraphBuilder::new();

    // Add a function whose address is taken (used as callback)
    let mut func = CodeNode::function("my_callback", "src/events.rs")
        .with_qualified_name("src/events.rs::my_callback");
    func.flags |= FLAG_ADDRESS_TAKEN;
    store.add_node(func);

    let ctx = make_test_analysis_ctx(&store);
    let detector = DeadCodeDetector::new();
    let findings = detector.find_dead_functions(&ctx);

    assert!(
        !findings.iter().any(|f| f.title.contains("my_callback")),
        "Address-taken function should be skipped"
    );
}

#[test]
fn test_dunder_methods_are_skipped() {
    use crate::graph::builder::GraphBuilder;
    use crate::graph::store_models::CodeNode;

    let mut store = GraphBuilder::new();

    // Add a dunder method with no callers
    let func = CodeNode::function("__repr__", "src/model.py")
        .with_qualified_name("src/model.py::__repr__");
    store.add_node(func);

    let ctx = make_test_analysis_ctx(&store);
    let detector = DeadCodeDetector::new();
    let findings = detector.find_dead_functions(&ctx);

    assert!(
        !findings.iter().any(|f| f.title.contains("__repr__")),
        "Dunder method should be skipped"
    );
}

#[test]
fn test_test_functions_skipped_via_role() {
    use crate::detectors::function_context::FunctionContext as FuncCtx;
    use crate::graph::builder::GraphBuilder;
    use crate::graph::store_models::CodeNode;

    let mut store = GraphBuilder::new();

    let func = CodeNode::function("verify_output", "tests/test_api.py")
        .with_qualified_name("tests/test_api.py::verify_output");
    store.add_node(func);

    // Build context with function marked as Test role
    let mut functions = std::collections::HashMap::new();
    functions.insert(
        "tests/test_api.py::verify_output".to_string(),
        FuncCtx {
            qualified_name: "tests/test_api.py::verify_output".to_string(),
            name: "verify_output".to_string(),
            file_path: "tests/test_api.py".to_string(),
            module: "tests".to_string(),
            in_degree: 0,
            out_degree: 0,
            betweenness: 0.0,
            caller_modules: 0,
            callee_modules: 0,
            call_depth: 0,
            role: FunctionRole::Test,
            is_exported: false,
            is_test: true,
            is_in_utility_module: false,
            complexity: None,
            loc: 5,
        },
    );

    let ctx = make_test_analysis_ctx_with_functions(&store, functions);
    let detector = DeadCodeDetector::new();
    let findings = detector.find_dead_functions(&ctx);

    assert!(
        !findings.iter().any(|f| f.title.contains("verify_output")),
        "Test function should be skipped via role"
    );
}

#[test]
fn test_entry_point_role_skipped() {
    use crate::detectors::function_context::FunctionContext as FuncCtx;
    use crate::graph::builder::GraphBuilder;
    use crate::graph::store_models::CodeNode;

    let mut store = GraphBuilder::new();

    let func = CodeNode::function("app_entry", "src/main.py")
        .with_qualified_name("src/main.py::app_entry");
    store.add_node(func);

    let mut functions = std::collections::HashMap::new();
    functions.insert(
        "src/main.py::app_entry".to_string(),
        FuncCtx {
            qualified_name: "src/main.py::app_entry".to_string(),
            name: "app_entry".to_string(),
            file_path: "src/main.py".to_string(),
            module: "main".to_string(),
            in_degree: 0,
            out_degree: 3,
            betweenness: 0.0,
            caller_modules: 0,
            callee_modules: 2,
            call_depth: 0,
            role: FunctionRole::EntryPoint,
            is_exported: true,
            is_test: false,
            is_in_utility_module: false,
            complexity: Some(5),
            loc: 20,
        },
    );

    let ctx = make_test_analysis_ctx_with_functions(&store, functions);
    let detector = DeadCodeDetector::new();
    let findings = detector.find_dead_functions(&ctx);

    assert!(
        !findings.iter().any(|f| f.title.contains("app_entry")),
        "EntryPoint role should be skipped"
    );
}

#[test]
fn test_hub_role_skipped() {
    use crate::detectors::function_context::FunctionContext as FuncCtx;
    use crate::graph::builder::GraphBuilder;
    use crate::graph::store_models::CodeNode;

    let mut store = GraphBuilder::new();

    let func =
        CodeNode::function("dispatch", "src/core.rs").with_qualified_name("src/core.rs::dispatch");
    store.add_node(func);

    let mut functions = std::collections::HashMap::new();
    functions.insert(
        "src/core.rs::dispatch".to_string(),
        FuncCtx {
            qualified_name: "src/core.rs::dispatch".to_string(),
            name: "dispatch".to_string(),
            file_path: "src/core.rs".to_string(),
            module: "core".to_string(),
            in_degree: 0,
            out_degree: 10,
            betweenness: 0.8,
            caller_modules: 0,
            callee_modules: 5,
            call_depth: 1,
            role: FunctionRole::Hub,
            is_exported: false,
            is_test: false,
            is_in_utility_module: false,
            complexity: Some(15),
            loc: 40,
        },
    );

    let ctx = make_test_analysis_ctx_with_functions(&store, functions);
    let detector = DeadCodeDetector::new();
    let findings = detector.find_dead_functions(&ctx);

    assert!(
        !findings.iter().any(|f| f.title.contains("dispatch")),
        "Hub role should be skipped"
    );
}

#[test]
fn test_hmm_handler_skipped() {
    use crate::graph::builder::GraphBuilder;
    use crate::graph::store_models::CodeNode;

    let mut store = GraphBuilder::new();

    let func = CodeNode::function("on_message", "src/events.py")
        .with_qualified_name("src/events.py::on_message");
    store.add_node(func);

    let mut hmm = std::collections::HashMap::new();
    hmm.insert(
        "src/events.py::on_message".to_string(),
        (context_hmm::FunctionContext::Handler, 0.85),
    );

    let ctx = make_test_analysis_ctx_with_hmm(&store, hmm);
    let detector = DeadCodeDetector::new();
    let findings = detector.find_dead_functions(&ctx);

    assert!(
        !findings.iter().any(|f| f.title.contains("on_message")),
        "HMM Handler should be skipped"
    );
}

#[test]
fn test_trait_impl_method_skipped_in_detection() {
    use crate::graph::builder::GraphBuilder;
    use crate::graph::store_models::CodeNode;

    let mut store = GraphBuilder::new();

    // A trait impl method: QN has impl<Trait for Type> pattern
    let func = CodeNode::function("detect", "src/detectors/god_class.rs").with_qualified_name(
        "src/detectors/god_class.rs::impl<Detector for GodClassDetector>::detect:42",
    );
    store.add_node(func);

    // An inherent impl method: QN has impl<Type> but NOT " for "
    let func2 = CodeNode::function("helper", "src/core.rs")
        .with_qualified_name("src/core.rs::impl<MyStruct>::helper:10");
    store.add_node(func2);

    let ctx = make_test_analysis_ctx(&store);
    let detector = DeadCodeDetector::new();
    let findings = detector.find_dead_functions(&ctx);

    // Trait impl method should NOT be flagged
    assert!(
        !findings.iter().any(|f| f.title.contains("detect")),
        "Trait impl method should be skipped"
    );

    // Inherent impl method SHOULD be flagged (not a trait impl)
    assert!(
        findings.iter().any(|f| f.title.contains("helper")),
        "Inherent impl method without callers should be flagged"
    );
}

#[test]
fn test_uncalled_function_is_flagged() {
    use crate::graph::builder::GraphBuilder;
    use crate::graph::store_models::CodeNode;

    let mut store = GraphBuilder::new();

    // A plain function with no callers, no flags, not in test path
    let func = CodeNode::function("unused_helper", "src/core.rs")
        .with_qualified_name("src/core.rs::unused_helper");
    store.add_node(func);

    let ctx = make_test_analysis_ctx(&store);
    let detector = DeadCodeDetector::new();
    let findings = detector.find_dead_functions(&ctx);

    assert!(
        findings.iter().any(|f| f.title.contains("unused_helper")),
        "Uncalled function with no exemptions should be flagged"
    );
}

#[test]
fn test_detector_name() {
    let detector = DeadCodeDetector::new();
    assert_eq!(detector.name(), "DeadCodeDetector");
}

// ── Test helpers ────────────────────────────────────────────────────

fn make_test_analysis_ctx(graph: &dyn crate::graph::GraphQuery) -> AnalysisContext<'_> {
    make_test_analysis_ctx_with_functions(graph, std::collections::HashMap::new())
}

fn make_test_analysis_ctx_with_functions(
    graph: &dyn crate::graph::GraphQuery,
    functions: crate::detectors::function_context::FunctionContextMap,
) -> AnalysisContext<'_> {
    make_test_analysis_ctx_full(graph, functions, std::collections::HashMap::new())
}

fn make_test_analysis_ctx_with_hmm(
    graph: &dyn crate::graph::GraphQuery,
    hmm: std::collections::HashMap<String, (context_hmm::FunctionContext, f64)>,
) -> AnalysisContext<'_> {
    make_test_analysis_ctx_full(graph, std::collections::HashMap::new(), hmm)
}

fn make_test_analysis_ctx_full(
    graph: &dyn crate::graph::GraphQuery,
    functions: crate::detectors::function_context::FunctionContextMap,
    hmm: std::collections::HashMap<String, (context_hmm::FunctionContext, f64)>,
) -> AnalysisContext<'_> {
    use crate::detectors::detector_context::DetectorContext;
    use crate::detectors::file_index::FileIndex;
    use crate::detectors::taint::centralized::CentralizedTaintResults;
    use std::collections::HashMap;
    use std::path::Path;
    use std::sync::Arc;

    let files = Arc::new(FileIndex::new(vec![]));
    let taint = Arc::new(CentralizedTaintResults {
        cross_function: HashMap::new(),
        intra_function: HashMap::new(),
    });

    let (det_ctx, _) = DetectorContext::build(graph, &[], None, Path::new("/repo"));

    AnalysisContext {
        graph,
        files,
        functions: Arc::new(functions),
        taint,
        detector_ctx: Arc::new(det_ctx),
        hmm_classifications: Arc::new(hmm),
        resolver: Arc::new(crate::calibrate::ThresholdResolver::default()),
        reachability: Arc::new(crate::detectors::reachability::ReachabilityIndex::empty()),
        public_api: Arc::new(std::collections::HashSet::new()),
        module_metrics: Arc::new(HashMap::new()),
        class_cohesion: Arc::new(HashMap::new()),
        decorator_index: Arc::new(HashMap::new()),
        git_churn: Arc::new(HashMap::new()),
        co_change_summary: Arc::new(HashMap::new()),
        co_change_matrix: None,
        ownership: None,
        cached_embeddings: None,
        dual_branch: std::sync::Arc::new(crate::config::DualBranchConfig::default()),
    }
}