code-search-cli 0.3.3

Intelligent code search tool for tracing text (UI text, function names, variables) to implementation code
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
/// Integration tests for AI agent usage scenarios
///
/// These tests verify that cs can serve as a drop-in replacement for rg in AI agent workflows
/// by testing programmatic parsing of simple format output, error handling, and performance.
use assert_cmd::{cargo_bin, Command};
use std::fs;
use tempfile::TempDir;

/// Helper to parse simple format output robustly, handling Windows paths (drive letters)
fn parse_simple_output(line: &str) -> Option<(String, u32, String)> {
    let parts: Vec<&str> = line.split(':').collect();
    if parts.len() < 3 {
        return None;
    }

    // Find the first part that looks like a line number (pure digits)
    // We search from index 1 to allow for potential drive letter at index 0
    for i in 1..parts.len() {
        if let Ok(line_num) = parts[i].parse::<u32>() {
            // Found the line number!
            // Everything before it is the file path (rejoined by colon for Windows drive letters)
            let file_path = parts[0..i].join(":");
            // Everything after it is the content (rejoined by colon for content containing colons)
            let content = parts[i + 1..].join(":");

            return Some((file_path, line_num, content));
        }
    }

    None
}

#[test]
fn test_simple_format_programmatic_parsing() {
    // Test that AI agents can reliably parse simple format output
    let mut cmd = Command::new(cargo_bin!("cs"));
    let output = cmd
        .arg("add new")
        .arg("--simple")
        .current_dir("tests/fixtures/rails-app")
        .output()
        .expect("Failed to execute cs command");

    assert!(output.status.success(), "cs command should succeed");

    let stdout = String::from_utf8(output.stdout).expect("Output should be valid UTF-8");
    let stderr = String::from_utf8(output.stderr).expect("Stderr should be valid UTF-8");

    // Verify stderr is empty (all output goes to stdout)
    println!(
        "DEBUG: Verifying stderr is empty. Current stderr content: {:?}",
        stderr
    );
    assert!(
        stderr.trim().is_empty(),
        "Stderr should be empty in simple mode, but got:\n{}",
        stderr
    );

    // Parse each line of output
    let lines: Vec<&str> = stdout
        .lines()
        .filter(|line| !line.trim().is_empty())
        .collect();
    assert!(!lines.is_empty(), "Should have at least one result");

    for line in lines {
        // Use robust parser instead of simple split
        let result = parse_simple_output(line);
        assert!(result.is_some(), "Line should be parseable: {}", line);

        let (file_path, _line_num, content) = result.unwrap();

        // File path should not be empty
        assert!(
            !file_path.is_empty(),
            "File path should not be empty: {}",
            line
        );

        // Content should be present
        // Verify no tree characters or ANSI codes
        assert!(
            !content.contains("├─>"),
            "Content should not contain tree characters: {}",
            line
        );
        assert!(
            !content.contains("└─>"),
            "Content should not contain tree characters: {}",
            line
        );
        assert!(
            !content.contains("\x1b["),
            "Content should not contain ANSI codes: {}",
            line
        );
    }
}

#[test]
fn test_error_handling_in_automated_scenarios() {
    // Test that errors are properly handled and reported to stderr
    let temp_dir = TempDir::new().unwrap();

    // Test 1: Search in non-existent directory
    let mut cmd = Command::new(cargo_bin!("cs"));
    let output = cmd
        .arg("test")
        .arg("--simple")
        .current_dir(&temp_dir) // Use temp_dir itself, not a nonexistent subdirectory
        .output()
        .expect("Failed to execute cs command");

    // This should succeed but find no results (empty directory)
    assert!(
        output.status.success(),
        "cs should succeed even in empty directory"
    );

    let stdout = String::from_utf8(output.stdout).expect("Stdout should be valid UTF-8");

    // In simple mode, empty results should either produce empty output or a "No matches found" message
    // Both are acceptable for AI agents to handle
    if !stdout.trim().is_empty() {
        assert!(
            stdout.contains("No matches found"),
            "Should either be empty or contain 'No matches found' message"
        );
    }

    // Test 2: Empty search text
    let mut cmd = Command::new(cargo_bin!("cs"));
    let output = cmd
        .arg("")
        .arg("--simple")
        .current_dir("tests/fixtures/rails-app")
        .output()
        .expect("Failed to execute cs command");

    assert!(
        !output.status.success(),
        "cs should fail for empty search text"
    );

    let stderr = String::from_utf8(output.stderr).expect("Stderr should be valid UTF-8");
    assert!(
        stderr.contains("empty"),
        "Should mention empty search text in error"
    );

    // Test 3: Invalid regex (when --regex flag is used)
    let mut cmd = Command::new(cargo_bin!("cs"));
    let output = cmd
        .arg("[invalid")
        .arg("--regex")
        .arg("--simple")
        .current_dir("tests/fixtures/rails-app")
        .output()
        .expect("Failed to execute cs command");

    // This might succeed or fail depending on regex implementation, but should handle gracefully
    let stderr = String::from_utf8(output.stderr).expect("Stderr should be valid UTF-8");
    // If it fails, error should be in stderr, not stdout
    if !output.status.success() {
        assert!(
            !stderr.trim().is_empty(),
            "Should have error message in stderr for invalid regex"
        );
    }
}

#[test]
fn test_performance_with_large_codebase() {
    // Test performance characteristics that AI agents care about
    let start = std::time::Instant::now();

    let mut cmd = Command::new(cargo_bin!("cs"));
    let output = cmd
        .arg("function")
        .arg("--simple")
        .current_dir("tests/fixtures")
        .output()
        .expect("Failed to execute cs command");

    let duration = start.elapsed();

    // Should complete within reasonable time (30 seconds for test fixtures, accounting for Windows CI)
    assert!(
        duration.as_secs() < 30,
        "Search should complete within 30 seconds, took {:?}",
        duration
    );

    if output.status.success() {
        let stdout = String::from_utf8(output.stdout).expect("Output should be valid UTF-8");

        // Verify output is still parseable even with many results
        for line in stdout.lines() {
            if !line.trim().is_empty() {
                assert!(
                    parse_simple_output(line).is_some(),
                    "Line should be parseable: {}",
                    line
                );
            }
        }
    }
}

#[test]
fn test_ai_agent_workflow_simulation() {
    // Simulate a typical AI agent workflow: search -> parse -> analyze

    // Step 1: Search for a pattern
    let mut cmd = Command::new(cargo_bin!("cs"));
    let output = cmd
        .arg("add new")
        .arg("--simple")
        .current_dir("tests/fixtures/rails-app")
        .output()
        .expect("Failed to execute cs command");

    assert!(output.status.success(), "Initial search should succeed");

    let stdout = String::from_utf8(output.stdout).expect("Output should be valid UTF-8");

    // Step 2: Parse results programmatically
    let mut parsed_results = Vec::new();
    for line in stdout.lines() {
        if !line.trim().is_empty() {
            if let Some((path, line_num, content)) = parse_simple_output(line) {
                parsed_results.push((path, line_num, content));
            }
        }
    }

    assert!(
        !parsed_results.is_empty(),
        "Should parse at least one result"
    );

    // Step 3: Analyze results (simulate AI agent logic)
    let mut translation_files = 0;
    let mut code_files = 0;

    for (file_path, _line_num, _content) in &parsed_results {
        if file_path.ends_with(".yml") || file_path.ends_with(".yaml") {
            translation_files += 1;
        } else if file_path.ends_with(".ts")
            || file_path.ends_with(".js")
            || file_path.ends_with(".tsx")
        {
            code_files += 1;
        }
    }

    // Verify AI agent can distinguish between file types
    assert!(
        translation_files > 0 || code_files > 0,
        "Should find either translation or code files"
    );

    // Step 4: Follow-up search based on results (simulate AI agent decision making)
    if translation_files > 0 {
        // AI agent might want to search for specific translation keys
        let mut cmd = Command::new(cargo_bin!("cs"));
        let output = cmd
            .arg("invoice.labels")
            .arg("--simple")
            .current_dir("tests/fixtures/rails-app")
            .output()
            .expect("Failed to execute follow-up search");

        // Should handle follow-up searches gracefully
        assert!(
            output.status.success() || output.status.code() == Some(0),
            "Follow-up search should not crash"
        );
    }
}

#[test]
fn test_rg_compatibility_command_line_args() {
    // Test that cs accepts common rg-style arguments that AI agents might use

    // Test case-insensitive search (rg -i)
    let mut cmd = Command::new(cargo_bin!("cs"));
    cmd.arg("ADD NEW") // uppercase
        .arg("--ignore-case")
        .arg("--simple")
        .current_dir("tests/fixtures/rails-app")
        .assert()
        .success();

    // Test word boundary search (rg -w)
    let mut cmd = Command::new(cargo_bin!("cs"));
    cmd.arg("new")
        .arg("--word-regexp")
        .arg("--simple")
        .current_dir("tests/fixtures/rails-app")
        .assert()
        .success();

    // Test regex search (rg -e with regex)
    let mut cmd = Command::new(cargo_bin!("cs"));
    cmd.arg("add.*new")
        .arg("--regex")
        .arg("--simple")
        .current_dir("tests/fixtures/rails-app")
        .assert()
        .success();
}

#[test]
fn test_output_consistency_across_search_types() {
    // Test that different search types produce consistent output format

    let temp_dir = TempDir::new().unwrap();

    // Create test files
    let yaml_dir = temp_dir.path().join("config/locales");
    fs::create_dir_all(&yaml_dir).unwrap();

    let yaml_file = yaml_dir.join("en.yml");
    fs::write(&yaml_file, "en:\n  test:\n    key: \"test value\"").unwrap();

    let code_dir = temp_dir.path().join("src");
    fs::create_dir_all(&code_dir).unwrap();

    let code_file = code_dir.join("app.ts");
    fs::write(
        &code_file,
        "const message = 'test value';\nconsole.log('test');",
    )
    .unwrap();

    // Test translation search
    let mut cmd = Command::new(cargo_bin!("cs"));
    let translation_output = cmd
        .arg("test value")
        .arg("--simple")
        .current_dir(temp_dir.path())
        .output()
        .expect("Failed to execute translation search");

    // Test exact text search
    let mut cmd = Command::new(cargo_bin!("cs"));
    let exact_output = cmd
        .arg("test")
        .arg("--simple")
        .current_dir(temp_dir.path())
        .output()
        .expect("Failed to execute exact search");

    // Both should use the same output format
    if translation_output.status.success() {
        let stdout = String::from_utf8(translation_output.stdout).unwrap();
        for line in stdout.lines() {
            if !line.trim().is_empty() {
                assert!(
                    parse_simple_output(line).is_some(),
                    "Translation search line should be parseable: {}",
                    line
                );
            }
        }
    }

    if exact_output.status.success() {
        let stdout = String::from_utf8(exact_output.stdout).unwrap();
        for line in stdout.lines() {
            if !line.trim().is_empty() {
                assert!(
                    parse_simple_output(line).is_some(),
                    "Exact search line should be parseable: {}",
                    line
                );
            }
        }
    }
}

#[test]
fn test_large_output_handling() {
    // Test that cs can handle large amounts of output without issues

    let temp_dir = TempDir::new().unwrap();

    // Create a file with many lines containing the search term
    let test_file = temp_dir.path().join("large_file.txt");
    let mut content = String::new();
    for i in 1..=1000 {
        content.push_str(&format!("Line {} contains test pattern\n", i));
    }
    fs::write(&test_file, content).unwrap();

    let mut cmd = Command::new(cargo_bin!("cs"));
    let output = cmd
        .arg("test pattern")
        .arg("--simple")
        .current_dir(temp_dir.path())
        .output()
        .expect("Failed to execute search on large file");

    if output.status.success() {
        let stdout = String::from_utf8(output.stdout).expect("Output should be valid UTF-8");
        let lines: Vec<&str> = stdout
            .lines()
            .filter(|line| !line.trim().is_empty())
            .collect();

        // Should find many matches
        assert!(lines.len() > 100, "Should find many matches in large file");

        // All lines should still be parseable
        for line in lines {
            assert!(
                parse_simple_output(line).is_some(),
                "Large output line should be parseable: {}",
                line
            );
        }
    }
}

#[test]
fn test_special_characters_in_ai_workflows() {
    // Test handling of special characters that might appear in AI agent queries

    let temp_dir = TempDir::new().unwrap();

    // Create test file with various special characters
    let test_file = temp_dir.path().join("special.txt");
    fs::write(
        &test_file,
        "Line with spaces and symbols: $var @mention #tag\n\
         Unicode content: café naïve résumé 中文 🚀\n\
         Shell metacharacters: $(command) `backticks` |pipe| &background&\n\
         Quotes and escapes: \"double\" 'single' \\backslash\n",
    )
    .unwrap();

    // Test searching for content with special characters
    let test_cases = vec!["$var", "café", "中文", "🚀", "\"double\"", "\\backslash"];

    for search_term in test_cases {
        let mut cmd = Command::new(cargo_bin!("cs"));
        let output = cmd
            .arg(search_term)
            .arg("--simple")
            .current_dir(temp_dir.path())
            .output()
            .expect("Failed to execute search with special characters");

        // Should handle special characters gracefully (success or clean failure)
        let stderr = String::from_utf8(output.stderr).unwrap();
        if !output.status.success() {
            // If it fails, should have clean error message, not crash
            assert!(
                !stderr.contains("panic"),
                "Should not panic on special characters: {}",
                search_term
            );
        } else {
            // If it succeeds, output should be parseable
            let stdout = String::from_utf8(output.stdout).unwrap();
            for line in stdout.lines() {
                if !line.trim().is_empty() {
                    assert!(
                        parse_simple_output(line).is_some(),
                        "Special character search result should be parseable: {}",
                        line
                    );
                }
            }
        }
    }
}