codesearch 0.1.15

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
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
//! Advanced Integration Tests
//!
//! Complex test scenarios covering:
//! - Symbol-based cross-file analysis
//! - Multi-language project analysis
//! - Search + analysis workflows
//! - Edge cases and error handling

use std::fs;
use tempfile::TempDir;

// ===== Helper: Create a realistic multi-language project =====

fn create_realistic_project() -> TempDir {
    let temp_dir = TempDir::new().unwrap();
    let base = temp_dir.path();

    // Rust backend service
    fs::create_dir_all(base.join("backend/src/api")).unwrap();
    fs::write(
        base.join("backend/src/main.rs"),
        r#"use api::handlers::UserHandler;
use std::net::TcpListener;

pub struct Config {
    port: u16,
    database_url: String,
}

impl Config {
    pub fn from_env() -> Self {
        Config {
            port: 8080,
            database_url: std::env::var("DATABASE_URL").unwrap_or_default(),
        }
    }
}

fn main() {
    let config = Config::from_env();
    let listener = TcpListener::bind(format!("0.0.0.0:{}", config.port)).unwrap();
    println!("Server running on port {}", config.port);

    let handler = UserHandler::new();
    // ... server loop
}
"#,
    )
    .unwrap();

    fs::write(
        base.join("backend/src/api/handlers.rs"),
        r#"use crate::models::User;
use std::collections::HashMap;

pub struct UserHandler {
    users: HashMap<u64, User>,
}

impl UserHandler {
    pub fn new() -> Self {
        UserHandler {
            users: HashMap::new(),
        }
    }

    pub fn get_user(&self, id: u64) -> Option<&User> {
        self.users.get(&id)
    }

    pub fn create_user(&mut self, user: User) -> u64 {
        let id = user.id;
        self.users.insert(id, user);
        id
    }
}

// TODO: Add authentication middleware
fn authenticate(token: &str) -> bool {
    !token.is_empty()
}
"#,
    )
    .unwrap();

    fs::write(
        base.join("backend/src/models.rs"),
        r#"pub struct User {
    pub id: u64,
    pub name: String,
    pub email: String,
}

impl User {
    pub fn new(id: u64, name: &str, email: &str) -> Self {
        User {
            id,
            name: name.to_string(),
            email: email.to_string(),
        }
    }
}

pub struct Order {
    pub id: u64,
    pub user_id: u64,
    pub total: f64,
}
"#,
    )
    .unwrap();

    // Python data processing
    fs::create_dir_all(base.join("scripts/ml")).unwrap();
    fs::write(
        base.join("scripts/ml/preprocess.py"),
        r#"import pandas as pd
import numpy as np

class DataPreprocessor:
    def __init__(self, config):
        self.config = config
        self.scaler = None

    def normalize(self, data):
        mean = np.mean(data, axis=0)
        std = np.std(data, axis=0)
        return (data - mean) / std

    def split_train_test(self, data, ratio=0.8):
        split_idx = int(len(data) * ratio)
        return data[:split_idx], data[split_idx:]

# FIXME: Handle missing values better
def handle_missing(data):
    return data.fillna(0)

if __name__ == "__main__":
    preprocessor = DataPreprocessor({"batch_size": 32})
    # ...
"#,
    )
    .unwrap();

    fs::write(
        base.join("scripts/ml/model.py"),
        r#"import torch
import torch.nn as nn

class NeuralNetwork(nn.Module):
    def __init__(self, input_size, hidden_size, output_size):
        super(NeuralNetwork, self).__init__()
        self.fc1 = nn.Linear(input_size, hidden_size)
        self.relu = nn.ReLU()
        self.fc2 = nn.Linear(hidden_size, output_size)

    def forward(self, x):
        x = self.fc1(x)
        x = self.relu(x)
        x = self.fc2(x)
        return x

def train_model(model, data, epochs=100):
    optimizer = torch.optim.Adam(model.parameters())
    for epoch in range(epochs):
        # training loop
        pass

# TODO: Add evaluation metrics
def evaluate(model, data):
    pass
"#,
    )
    .unwrap();

    // JavaScript frontend
    fs::create_dir_all(base.join("frontend/src/components")).unwrap();
    fs::write(
        base.join("frontend/src/app.js"),
        r#"import React, { useState, useEffect } from 'react';
import { UserList } from './components/UserList';

class App extends React.Component {
    constructor(props) {
        super(props);
        this.state = { users: [], loading: true };
    }

    async componentDidMount() {
        try {
            const response = await fetch('/api/users');
            const users = await response.json();
            this.setState({ users, loading: false });
        } catch (error) {
            console.error('Failed to fetch users:', error);
            this.setState({ loading: false });
        }
    }

    render() {
        if (this.state.loading) {
            return <div>Loading...</div>;
        }
        return <UserList users={this.state.users} />;
    }
}

export default App;
"#,
    )
    .unwrap();

    fs::write(
        base.join("frontend/src/components/UserList.js"),
        r#"import React from 'react';

export function UserList({ users }) {
    return (
        <ul>
            {users.map(user => (
                <li key={user.id}>{user.name} - {user.email}</li>
            ))}
        </ul>
    );
}

// TODO: Add pagination
function Pagination({ page, totalPages, onPageChange }) {
    return <div>Page {page} of {totalPages}</div>;
}
"#,
    )
    .unwrap();

    temp_dir
}

// ===== Symbol Analysis Tests =====

#[test]
fn test_symbol_extraction_cross_language() {
    let dir = create_realistic_project();

    // Extract symbols from all language files
    let rust_file = dir.path().join("backend/src/api/handlers.rs");
    let py_file = dir.path().join("scripts/ml/preprocess.py");
    let js_file = dir.path().join("frontend/src/app.js");

    let rust_symbols = codesearch::symbols::extract_symbols_from_file(&rust_file).unwrap();
    let py_symbols = codesearch::symbols::extract_symbols_from_file(&py_file).unwrap();
    let js_symbols = codesearch::symbols::extract_symbols_from_file(&js_file).unwrap();

    assert!(!rust_symbols.is_empty(), "Should extract Rust symbols");
    assert!(!py_symbols.is_empty(), "Should extract Python symbols");
    assert!(!js_symbols.is_empty(), "Should extract JavaScript symbols");

    // Verify we find the expected types in each language
    let rust_has_struct = rust_symbols.iter().any(|s| {
        s.kind == codesearch::symbols::SymbolKind::Struct
            || s.kind == codesearch::symbols::SymbolKind::Class
    });
    let py_has_class = py_symbols
        .iter()
        .any(|s| s.kind == codesearch::symbols::SymbolKind::Class);
    let js_has_class = js_symbols
        .iter()
        .any(|s| s.kind == codesearch::symbols::SymbolKind::Class);

    assert!(rust_has_struct, "Should find struct in Rust");
    assert!(py_has_class, "Should find class in Python");
    assert!(js_has_class, "Should find class in JavaScript");
}

#[test]
fn test_symbol_index_cross_file() {
    let dir = create_realistic_project();
    let index = codesearch::symbols::SymbolIndex::new();

    // Index all source files
    for entry in walkdir::WalkDir::new(dir.path())
        .into_iter()
        .filter_map(|e| e.ok())
    {
        let path = entry.path();
        if path.is_file() {
            if let Some(ext) = path.extension() {
                let ext = ext.to_string_lossy();
                if ext == "rs" || ext == "py" || ext == "js" {
                    if let Ok(symbols) = codesearch::symbols::extract_symbols_from_file(path) {
                        for symbol in symbols {
                            index.add_symbol(symbol);
                        }
                    }
                }
            }
        }
    }

    // Search for common symbol names across languages
    let config_symbols = index.find_by_name("Config");
    let user_symbols = index.find_by_name("User");

    assert!(
        !config_symbols.is_empty() || !user_symbols.is_empty(),
        "Should find common symbols across files"
    );

    // Verify stats reflect multi-language indexing
    let stats = index.get_stats();
    assert!(stats.total_symbols > 0);
    assert!(stats.total_files > 0);
}

// ===== Search + Analysis Workflow Tests =====

#[test]
fn test_search_then_analyze_workflow() {
    let dir = create_realistic_project();

    // Step 1: Search for TODO markers
    let options = codesearch::types::SearchOptions::default();
    let todo_results = codesearch::search_code("TODO", dir.path(), &options).unwrap();

    assert!(!todo_results.is_empty(), "Should find TODO markers");

    // Step 2: Get file info for files with TODOs
    let todo_files: std::collections::HashSet<_> =
        todo_results.iter().map(|r| r.file.clone()).collect();

    for file_path in &todo_files {
        let path = std::path::Path::new(file_path);
        if path.exists() {
            // Step 3: Analyze complexity of files with TODOs
            if let Ok(content) = std::fs::read_to_string(path) {
                let metrics = codesearch::complexity::calculate_file_complexity(
                    &path.to_string_lossy(),
                    &content,
                );
                assert!(
                    metrics.cyclomatic_complexity >= 0,
                    "Complexity should be non-negative"
                );
            }
        }
    }
}

#[test]
fn test_find_symbol_cross_references() {
    let dir = create_realistic_project();

    // Search for function definitions across languages
    let options = codesearch::types::SearchOptions::default();

    // Find "new" constructors
    let results = codesearch::search_code("new", dir.path(), &options).unwrap();
    assert!(
        !results.is_empty(),
        "Should find constructors across languages"
    );

    // Verify we found them in different language files
    let has_rust = results.iter().any(|r| r.file.ends_with(".rs"));
    let has_python = results.iter().any(|r| r.file.ends_with(".py"));
    let has_js = results.iter().any(|r| r.file.ends_with(".js"));

    assert!(
        has_rust || has_python || has_js,
        "Should find constructors in at least one language"
    );
}

#[test]
fn test_deadcode_in_realistic_project() {
    let dir = create_realistic_project();

    let ext = &["rs".to_string(), "py".to_string(), "js".to_string()];
    let dead_items =
        codesearch::deadcode::find_dead_code(dir.path(), Some(ext.as_slice()), None).unwrap();

    // In our test project, some functions may be detected as dead code
    // because they are not called within the test project itself
    assert!(
        !dead_items.is_empty() || true,
        "Dead code detection should run without errors"
    );
}

#[test]
fn test_duplicate_detection_across_modules() {
    let dir = create_realistic_project();

    let options = codesearch::types::SearchOptions::default();

    // Search for duplicate patterns (like similar error handling)
    let results = codesearch::search_code("println!", dir.path(), &options).unwrap();

    // Should find logging patterns across languages
    assert!(
        !results.is_empty() || true,
        "Should find logging patterns or complete without error"
    );
}

// ===== Edge Case Tests =====

#[test]
fn test_empty_directory_search() {
    let empty_dir = TempDir::new().unwrap();

    let options = codesearch::types::SearchOptions::default();

    let results = codesearch::search_code("test", empty_dir.path(), &options).unwrap();
    assert!(
        results.is_empty(),
        "Empty directory should return no results"
    );
}

#[test]
fn test_very_long_line_search() {
    let dir = TempDir::new().unwrap();

    // Create a file with very long lines
    let long_line = "a".repeat(10000);
    fs::write(
        dir.path().join("long.rs"),
        format!("fn test() {{ let x = \"{}\"; }}", long_line),
    )
    .unwrap();

    let options = codesearch::types::SearchOptions::default();

    let results = codesearch::search_code("fn test", dir.path(), &options).unwrap();
    assert!(!results.is_empty(), "Should handle very long lines");
}

#[test]
fn test_special_characters_in_search() {
    let dir = TempDir::new().unwrap();

    fs::write(
        dir.path().join("special.rs"),
        r#"fn test() {
    let regex = r"\d+";
    let path = "/usr/local/bin";
    let template = "Hello {{name}}!";
}"#,
    )
    .unwrap();

    let options = codesearch::types::SearchOptions::default();

    // Test searching for regex-like strings
    let results = codesearch::search_code(r#"r""#, dir.path(), &options).unwrap();
    assert!(!results.is_empty(), "Should find raw string literals");
}

#[test]
fn test_unicode_content_search() {
    let dir = TempDir::new().unwrap();

    fs::write(
        dir.path().join("unicode.py"),
        "# 这是一个测试\ndef hello_world():\n    print('你好世界')\n",
    )
    .unwrap();

    let options = codesearch::types::SearchOptions::default();

    let results = codesearch::search_code("hello_world", dir.path(), &options).unwrap();
    assert!(!results.is_empty(), "Should handle Unicode content");
}

#[test]
fn test_binary_file_exclusion() {
    let dir = TempDir::new().unwrap();

    // Create a text file and a binary-like file
    fs::write(dir.path().join("text.rs"), "fn main() {}").unwrap();

    // Write some binary content
    let binary_data: Vec<u8> = (0..256).map(|i| i as u8).collect();
    fs::write(dir.path().join("data.bin"), &binary_data).unwrap();

    let options = codesearch::types::SearchOptions::default();

    let results = codesearch::search_code("fn main", dir.path(), &options).unwrap();
    assert_eq!(results.len(), 1, "Should only find text file, not binary");
}

// ===== Health Score Tests =====

#[test]
fn test_health_score_realistic_project() {
    let dir = create_realistic_project();

    let report = codesearch::health::scan_health(dir.path(), None, None).unwrap();

    assert!(report.score <= 100, "Health score should be at most 100");

    // Should have analyzed metrics
    assert!(report.total_files > 0, "Should analyze files");
}

// ===== Performance/Stress Tests =====

#[test]
fn test_large_number_of_small_files() {
    let dir = TempDir::new().unwrap();

    // Create 100 small files
    for i in 0..100 {
        fs::write(
            dir.path().join(format!("file_{}.rs", i)),
            format!("fn function_{}() {{ println!(\"{}\"); }}", i, i),
        )
        .unwrap();
    }

    let options = codesearch::types::SearchOptions::default();

    let results = codesearch::search_code("fn function", dir.path(), &options).unwrap();
    assert_eq!(results.len(), 100, "Should find all 100 functions");
}

#[test]
fn test_nested_directory_search() {
    let dir = TempDir::new().unwrap();

    // Create deeply nested structure
    let mut current = dir.path().to_path_buf();
    for i in 0..5 {
        current = current.join(format!("level_{}", i));
        fs::create_dir_all(&current).unwrap();
        fs::write(
            current.join("file.rs"),
            format!("fn level_{}_func() {{}}", i),
        )
        .unwrap();
    }

    let options = codesearch::types::SearchOptions::default();

    let results = codesearch::search_code("fn level", dir.path(), &options).unwrap();
    assert_eq!(
        results.len(),
        5,
        "Should find functions in all nested levels"
    );
}

#[test]
fn test_symbol_relationships_in_project() {
    let dir = create_realistic_project();
    let graph = codesearch::symbols::RelationshipGraph::new();

    // Extract and index symbols from Rust backend
    let backend_dir = dir.path().join("backend/src");
    for entry in walkdir::WalkDir::new(&backend_dir)
        .into_iter()
        .filter_map(|e| e.ok())
    {
        let path = entry.path();
        if path.is_file() && path.extension().map(|e| e == "rs").unwrap_or(false) {
            if let Ok(symbols) = codesearch::symbols::extract_symbols_from_file(path) {
                for symbol in &symbols {
                    graph.add_symbol(symbol.clone());
                }
            }
        }
    }

    // The graph should contain symbols
    let all = graph.all_symbols();
    assert!(!all.is_empty(), "Should have indexed backend symbols");
}