codesearch 0.1.14

A fast, intelligent CLI tool with multiple search modes (regex, fuzzy, semantic), code analysis, and dead code detection for popular programming languages
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
//! End-to-End Integration Tests
//!
//! Tests complete workflows from search to analysis to export.

mod fixtures;

use codesearch::search::search_code;
use codesearch::types::SearchOptions;
use codesearch::{analysis, complexity, deadcode, export};
use fixtures::TestWorkspace;
use std::fs;

#[test]
fn test_search_and_export_workflow() {
    let workspace = TestWorkspace::new();
    let options = SearchOptions::default();

    // Perform search
    let results = search_code("test", workspace.path(), &options).expect("Search failed");
    assert!(!results.is_empty(), "Should find test matches");

    // Export results
    let export_path = workspace.path().join("results.json");
    export::export_results(&results, export_path.to_str().unwrap(), "test").expect("Export failed");

    // Verify export file exists
    assert!(export_path.exists());
    let content = fs::read_to_string(&export_path).expect("Failed to read export");
    assert!(content.contains("test"));
}

#[test]
fn test_search_with_multiple_extensions() {
    let workspace = TestWorkspace::new();
    let options = SearchOptions {
        extensions: Some(vec!["rs".to_string(), "py".to_string()]),
        ..Default::default()
    };

    let results = search_code("main", workspace.path(), &options).expect("Search failed");
    assert!(!results.is_empty());

    // Verify only .rs and .py files
    for result in results {
        assert!(result.file.ends_with(".rs") || result.file.ends_with(".py"));
    }
}

#[test]
fn test_search_with_fuzzy_matching() {
    let workspace = TestWorkspace::new();
    let options = SearchOptions {
        fuzzy: true,
        fuzzy_threshold: 0.5,
        ..Default::default()
    };

    let results = search_code("tst", workspace.path(), &options).expect("Search failed");
    // Fuzzy search should find "test" even with typo
    assert!(!results.is_empty());
}

#[test]
fn test_analyze_then_search() {
    let workspace = TestWorkspace::new();

    // First analyze the codebase
    let analyze_result = analysis::analyze_codebase(workspace.path(), None, None);
    assert!(analyze_result.is_ok());

    // Then search for specific patterns
    let options = SearchOptions::default();
    let results = search_code("fn", workspace.path(), &options).expect("Search failed");
    assert!(!results.is_empty());
}

#[test]
fn test_complexity_analysis_workflow() {
    let mut workspace = TestWorkspace::new();
    workspace.add_file(
        "complex.rs",
        r#"
fn complex_function(x: i32) -> i32 {
    if x > 0 {
        if x > 10 {
            if x > 20 {
                return x * 2;
            }
            return x + 10;
        }
        return x + 5;
    }
    return 0;
}
"#,
    );

    let result = complexity::analyze_complexity(
        workspace.path(),
        Some(&[String::from("rs")]),
        None,
        Some(1),
        false,
    );
    assert!(result.is_ok());
}

#[test]
fn test_deadcode_detection_workflow() {
    let mut workspace = TestWorkspace::new();
    workspace.add_file(
        "deadcode.rs",
        r#"
fn used_function() {
    println!("Used");
}

fn unused_function() {
    // TODO: implement this
    let unused_var = 42;
}
"#,
    );

    let result = deadcode::detect_dead_code(workspace.path(), Some(&[String::from("rs")]), None);
    assert!(result.is_ok());
}

#[test]
fn test_search_ranking() {
    let workspace = TestWorkspace::new();
    let options = SearchOptions {
        rank: true,
        ..Default::default()
    };

    let results = search_code("test", workspace.path(), &options).expect("Search failed");

    if results.len() > 1 {
        // Verify results are sorted by score
        for i in 0..results.len() - 1 {
            assert!(results[i].score >= results[i + 1].score);
        }
    }
}

#[test]
fn test_search_with_exclusions() {
    let workspace = TestWorkspace::new();
    let subdir = workspace.create_subdir("excluded");
    fs::write(subdir.join("test.rs"), "fn excluded_test() {}").expect("Failed to write");

    let options = SearchOptions {
        exclude: Some(vec!["excluded".to_string()]),
        ..Default::default()
    };

    let results = search_code("excluded", workspace.path(), &options).expect("Search failed");

    // Should not find matches in excluded directory
    for result in results {
        assert!(!result.file.contains("excluded"));
    }
}

#[test]
fn test_max_results_limit() {
    let mut workspace = TestWorkspace::new();

    // Create multiple files with many matches
    for i in 0..10 {
        workspace.add_file(&format!("file{i}.txt"), "test test test test test");
    }

    let options = SearchOptions {
        max_results: 2,
        ..Default::default()
    };

    let results = search_code("test", workspace.path(), &options).expect("Search failed");

    // Each file should have at most 2 matches
    for result in results {
        assert!(result.matches.len() <= 2);
    }
}

#[test]
fn test_case_sensitive_search() {
    let mut workspace = TestWorkspace::new();
    workspace.add_file("case.txt", "Test TEST test TeSt");

    let options_sensitive = SearchOptions {
        ignore_case: false,
        ..Default::default()
    };

    let results = search_code("Test", workspace.path(), &options_sensitive).expect("Search failed");

    // Should only match exact case
    for result in results {
        assert!(result.content.contains("Test"));
    }
}

#[test]
fn test_case_insensitive_search() {
    let mut workspace = TestWorkspace::new();
    workspace.add_file("case.txt", "Test TEST test TeSt");

    let options_insensitive = SearchOptions {
        ignore_case: true,
        ..Default::default()
    };

    let results =
        search_code("test", workspace.path(), &options_insensitive).expect("Search failed");
    assert!(!results.is_empty());
}

#[test]
fn test_empty_directory() {
    let workspace = TestWorkspace::with_files(&[]);
    let options = SearchOptions::default();

    let results = search_code("test", workspace.path(), &options).expect("Search failed");
    assert!(results.is_empty());
}

#[test]
fn test_nested_directories() {
    let workspace = TestWorkspace::new();
    let subdir1 = workspace.create_subdir("level1");
    let subdir2 = subdir1.join("level2");
    fs::create_dir_all(&subdir2).expect("Failed to create nested dir");
    fs::write(subdir2.join("nested.rs"), "fn nested_test() {}").expect("Failed to write");

    let options = SearchOptions::default();
    let results = search_code("nested", workspace.path(), &options).expect("Search failed");

    assert!(!results.is_empty());
    assert!(results[0].file.contains("level1"));
    assert!(results[0].file.contains("level2"));
}

#[test]
fn test_bm25_ranking() {
    let mut workspace = TestWorkspace::new();
    // Create a file with many occurrences of "helper" (high term freq)
    workspace.add_file(
        "frequent.rs",
        "fn helper() {}
fn helper2() { helper(); }
fn helper3() { helper(); helper2(); }
",
    );
    // Create a file with a single occurrence (low term freq)
    workspace.add_file("rare.rs", "fn rare_helper() {}");

    let options = SearchOptions {
        rank: true,
        use_bm25: true,
        ..Default::default()
    };
    let results = search_code("helper", workspace.path(), &options).expect("Search failed");

    assert!(!results.is_empty(), "Should find helper matches");

    // BM25 should produce valid scores in 0-100 range
    for r in &results {
        assert!(r.score >= 0.0 && r.score <= 100.0, "BM25 score should be in 0-100 range");
    }
}

#[test]
fn test_context_filter_only_code() {
    let mut workspace = TestWorkspace::new();
    workspace.add_file(
        "mixed.rs",
        "fn helper() { println!(\"hello\"); }\n// helper is a test function\n",
    );

    let options = SearchOptions {
        context_filter: Some(codesearch::types::ContextFilter::Code),
        ..Default::default()
    };
    let results = search_code("helper", workspace.path(), &options).expect("Search failed");

    // Should only find the code line, not the comment
    assert!(
        results.iter().any(|r| r.content.contains("println!")),
        "Should find code match"
    );
    assert!(
        !results.iter().any(|r| r.content.starts_with("//")),
        "Should not find comment match"
    );
}

#[test]
fn test_context_filter_only_comments() {
    let mut workspace = TestWorkspace::new();
    workspace.add_file(
        "mixed.rs",
        "fn helper() { println!(\"hello\"); }\n// helper is a test function\n",
    );

    let options = SearchOptions {
        context_filter: Some(codesearch::types::ContextFilter::Comments),
        ..Default::default()
    };
    let results = search_code("helper", workspace.path(), &options).expect("Search failed");

    // Should only find the comment line, not the code
    assert!(
        results.iter().any(|r| r.content.starts_with("//")),
        "Should find comment match"
    );
    assert!(
        !results.iter().any(|r| r.content.contains("println!")),
        "Should not find code match"
    );
}

#[test]
fn test_fixed_string_search() {
    let mut workspace = TestWorkspace::new();
    workspace.add_file("test.rs", "fn test_helper() { let x = 42; }");

    // Fixed-string search should find literal "helper"
    let options = SearchOptions {
        fixed_string: true,
        ..Default::default()
    };
    let results = search_code("helper", workspace.path(), &options).expect("Search failed");
    assert!(!results.is_empty(), "Fixed-string should find literal match");
    assert!(results.iter().any(|r| r.content.contains("helper")));
}

#[test]
fn test_fixed_string_no_regex_interpretation() {
    let mut workspace = TestWorkspace::new();
    workspace.add_file("regex.rs", "let x = \"[a-z]+\";");

    // Searching for "[a-z]+" as fixed string should match the literal text
    let options = SearchOptions {
        fixed_string: true,
        ..Default::default()
    };
    let results = search_code("[a-z]+", workspace.path(), &options).expect("Search failed");
    assert!(
        !results.is_empty(),
        "Fixed-string should match literal regex-like text"
    );
}

#[test]
fn test_fixed_string_case_insensitive() {
    let mut workspace = TestWorkspace::new();
    workspace.add_file("case.rs", "fn Helper() {}");

    let options = SearchOptions {
        fixed_string: true,
        ignore_case: true,
        ..Default::default()
    };
    let results = search_code("helper", workspace.path(), &options).expect("Search failed");
    assert!(
        !results.is_empty(),
        "Case-insensitive fixed-string should match"
    );
}

#[test]
fn test_smart_case_lowercase_query() {
    let mut workspace = TestWorkspace::new();
    workspace.add_file("case.rs", "fn Helper() {}\nfn helper() {}");

    // Lowercase query should match both via smart case (case-insensitive)
    let options = SearchOptions {
        ignore_case: false, // no explicit -i flag
        ..Default::default()
    };
    let results = search_code("helper", workspace.path(), &options).expect("Search failed");
    assert_eq!(results.len(), 2, "Smart case: lowercase query should match both cases");
}

#[test]
fn test_smart_case_uppercase_query() {
    let mut workspace = TestWorkspace::new();
    workspace.add_file("case.rs", "fn Helper() {}\nfn helper() {}");

    // Uppercase query should only match exact case via smart case (case-sensitive)
    let options = SearchOptions {
        ignore_case: false, // no explicit -i flag
        ..Default::default()
    };
    let results = search_code("Helper", workspace.path(), &options).expect("Search failed");
    assert_eq!(results.len(), 1, "Smart case: uppercase query should match only exact case");
    assert!(results[0].content.contains("Helper"));
}

#[test]
fn test_only_declarations_filter() {
    let mut workspace = TestWorkspace::new();
    workspace.add_file(
        "decl.rs",
        "fn helper() {}\n    helper();\n",
    );

    let options = SearchOptions {
        declaration_filter: Some(codesearch::types::DeclarationFilter::Declarations),
        ..Default::default()
    };
    let results = search_code("helper", workspace.path(), &options).expect("Search failed");

    // Should only find the declaration line, not the indented call site
    assert_eq!(results.len(), 1, "Should find only declaration");
    assert!(results[0].content.contains("fn helper"));
}

#[test]
fn test_only_usages_filter() {
    let mut workspace = TestWorkspace::new();
    workspace.add_file(
        "usage.rs",
        "fn helper() {}\n    helper();\n",
    );

    let options = SearchOptions {
        declaration_filter: Some(codesearch::types::DeclarationFilter::Usages),
        ..Default::default()
    };
    let results = search_code("helper", workspace.path(), &options).expect("Search failed");

    // Should only find the indented call line, not the declaration
    assert_eq!(results.len(), 1, "Should find only usage");
    assert!(results[0].content.contains("helper();"));
}

#[test]
fn test_test_file_dampening() {
    let mut workspace = TestWorkspace::new();
    workspace.add_file("src/helper.rs", "fn helper() {}");
    workspace.add_file("tests/helper_test.rs", "fn helper() {}");

    let options = SearchOptions {
        rank: true,
        ..Default::default()
    };
    let results = search_code("helper", workspace.path(), &options).expect("Search failed");

    // With ranking enabled, the src file should appear before the test file
    let src_pos = results.iter().position(|r| r.file.contains("src/"));
    let test_pos = results.iter().position(|r| r.file.contains("tests/"));

    assert!(
        src_pos.is_some(),
        "Should find match in src file"
    );
    assert!(
        test_pos.is_some(),
        "Should find match in test file"
    );

    if let (Some(src), Some(test)) = (src_pos, test_pos) {
        assert!(
            src < test,
            "Src file match should rank higher than test file match"
        );
        assert!(
            results[src].score > results[test].score,
            "Src file score should be higher than test file score"
        );
    }
}

#[test]
fn test_json_output_contains_expected_fields() {
    let mut workspace = TestWorkspace::new();
    workspace.add_file("test.rs", "fn helper() {}");

    let options = SearchOptions::default();
    let results = search_code("helper", workspace.path(), &options).expect("Search failed");

    assert!(!results.is_empty());

    // Verify SearchResult serializes to JSON with expected fields
    let json = serde_json::to_string(&results).expect("JSON serialization failed");
    assert!(json.contains("file"), "JSON should contain file field");
    assert!(json.contains("line_number"), "JSON should contain line_number field");
    assert!(json.contains("content"), "JSON should contain content field");
    assert!(json.contains("matches"), "JSON should contain matches field");
    assert!(json.contains("score"), "JSON should contain score field");
    assert!(json.contains("relevance"), "JSON should contain relevance field");
}

#[test]
fn test_config_file_loading() {
    use std::io::Write;

    let mut workspace = TestWorkspace::new();
    workspace.add_file("src/main.rs", "fn helper() {}");
    workspace.add_file("src/lib.rs", "fn helper2() {}");

    // Write a .codesearch.toml config file
    let config_path = workspace.path().join(".codesearch.toml");
    let mut file = std::fs::File::create(&config_path).unwrap();
    file.write_all(b"max_results = 1\n").unwrap();

    let config = codesearch::config::Config::load(workspace.path())
        .expect("Config should load");
    assert_eq!(config.max_results, Some(1));
}