probe-code 0.6.0

AI-friendly, fully local, semantic code search tool for large codebases
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
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
//! Functions for extracting file paths from text.
//!
//! This module provides functions for parsing file paths with optional line numbers,
//! line ranges, or symbol references from text input.

use glob::glob;
use ignore::WalkBuilder;
use probe_code::language::is_test_file;
use probe_code::path_resolver::resolve_path;
use regex::Regex;
use std::collections::HashSet;
use std::path::PathBuf;

/// Represents a file path with optional line numbers and symbol information
///
/// - `PathBuf`: The path to the file
/// - First `Option<usize>`: Optional start line number
/// - Second `Option<usize>`: Optional end line number
/// - `Option<String>`: Optional symbol name
/// - `Option<HashSet<usize>>`: Optional set of specific line numbers
pub type FilePathInfo = (
    PathBuf,
    Option<usize>,
    Option<usize>,
    Option<String>,
    Option<HashSet<usize>>,
);
/// Check if content is in git diff format
///
/// This function checks if the content starts with "diff --git" which indicates
/// it's in git diff format.
pub fn is_git_diff_format(content: &str) -> bool {
    content.trim_start().starts_with("diff --git")
}

/// Extract file paths from git diff format
///
/// This function takes a string of text in git diff format and extracts file paths
/// with line ranges. It's used when the extract command is run with the --diff option.
///
/// The function looks for patterns like:
/// - diff --git a/path/to/file.rs b/path/to/file.rs
/// - @@ -45,7 +45,7 @@ (hunk header)
///
/// It extracts the file path from the diff header and the line range from the hunk header.
/// We don't add arbitrary context lines - instead we rely on the AST parser to find
/// the full function or code block that contains the changed lines.
///
/// If allow_tests is false, test files will be filtered out.
pub fn extract_file_paths_from_git_diff(text: &str, allow_tests: bool) -> Vec<FilePathInfo> {
    let mut results = Vec::new();
    let mut processed_files = HashSet::new();
    let mut current_file: Option<PathBuf> = None;
    let mut current_file_lines = HashSet::new();

    // Check if debug mode is enabled
    let debug_mode = std::env::var("DEBUG").unwrap_or_default() == "1";

    // Split the text into lines
    let lines: Vec<&str> = text.lines().collect();

    // Regex for diff header: diff --git a/path/to/file.rs b/path/to/file.rs
    let diff_header_regex = Regex::new(r"^diff --git a/(.*) b/(.*)$").unwrap();

    // Regex for hunk header capturing start+len for old and new lines:
    //   @@ -oldStart,oldLen +newStart,newLen @@
    // The length part may be omitted if 1 (in which case the diff might display e.g. @@ -10 +20 @@).
    // We'll default missing length to 1.
    let hunk_header_regex = Regex::new(r"^@@ -(\d+)(?:,(\d+))? \+(\d+)(?:,(\d+))? @@").unwrap();

    // Helper function to finalize a file (add to results if it has changes)
    let finalize_file = |results: &mut Vec<FilePathInfo>,
                         processed_files: &mut HashSet<String>,
                         file_path: &PathBuf,
                         changed_lines: &HashSet<usize>,
                         allow_tests: bool,
                         debug_mode: bool| {
        // Only process if we have lines and haven't processed this file yet
        if !changed_lines.is_empty()
            && !processed_files.contains(&file_path.to_string_lossy().to_string())
        {
            // Skip test files if allow_tests is false
            let is_test = is_test_file(file_path);
            if !is_ignored_by_gitignore(file_path) && (allow_tests || !is_test) {
                if debug_mode {
                    println!(
                        "[DEBUG] Adding file with {} changed lines: {:?}",
                        changed_lines.len(),
                        file_path
                    );
                }
                // Use the min and max values in the HashSet for start and end lines
                let start_line = changed_lines.iter().min().cloned();
                let end_line = changed_lines.iter().max().cloned();

                // Pass both the start/end line numbers and the full set of lines
                results.push((
                    file_path.clone(),
                    start_line,
                    end_line,
                    None,
                    Some(changed_lines.clone()),
                ));
                processed_files.insert(file_path.to_string_lossy().to_string());
            } else if debug_mode {
                if is_ignored_by_gitignore(file_path) {
                    println!("[DEBUG] Skipping ignored file: {file_path:?}");
                } else if !allow_tests && is_test {
                    println!("[DEBUG] Skipping test file: {file_path:?}");
                }
            }
        }
    };

    // Use a manual index to process the lines
    let mut i = 0;
    while i < lines.len() {
        let line = lines[i];

        // Check for diff header
        if let Some(cap) = diff_header_regex.captures(line) {
            // When we find a new file, process any lines from the previous file
            if let Some(file_path) = &current_file {
                finalize_file(
                    &mut results,
                    &mut processed_files,
                    file_path,
                    &current_file_lines,
                    allow_tests,
                    debug_mode,
                );
            }

            // Use the 'b' path (new file) as the current file
            let file_path = cap.get(2).unwrap().as_str();
            current_file = Some(PathBuf::from(file_path));
            current_file_lines = HashSet::new(); // Reset lines for the new file

            if debug_mode {
                println!("[DEBUG] Found file in git diff: {file_path:?}");
            }

            i += 1;
            continue;
        }
        // Check for hunk header
        else if let Some(cap) = hunk_header_regex.captures(line) {
            if let Some(file_path) = &current_file {
                // Get the line numbers from the hunk header
                let new_start: usize = cap.get(3).unwrap().as_str().parse().unwrap_or(1);
                let _new_len: usize = cap
                    .get(4)
                    .map(|m| m.as_str().parse().unwrap_or(1))
                    .unwrap_or(1);

                if debug_mode {
                    println!(
                        "[DEBUG] Found hunk for file {file_path:?}: parsing for actual changed lines"
                    );
                }

                // Move to the next line after the hunk header
                i += 1;

                // Process lines within this hunk
                let mut current_line = new_start;
                while i < lines.len() {
                    let hunk_line = lines[i];

                    // Check if we've reached the next hunk or next diff
                    if hunk_line.starts_with("@@") || hunk_line.starts_with("diff --git") {
                        // Do not increment i here, so the outer loop sees this line
                        break;
                    }

                    // Process lines within the hunk
                    if hunk_line.starts_with('+') && !hunk_line.starts_with("+++") {
                        // This is an added/modified line in the new version
                        if debug_mode {
                            println!("[DEBUG] Found changed line at {current_line}: {hunk_line}");
                        }
                        current_file_lines.insert(current_line);
                    }

                    // Advance the line counter for all lines except removed lines
                    if !hunk_line.starts_with('-') {
                        current_line += 1;
                    }

                    i += 1;
                }

                // We've processed this hunk, continue to the next line
                continue;
            }
        }

        // If not a diff header or hunk header, just move on
        i += 1;
    }

    // Process any lines from the last file
    if let Some(file_path) = &current_file {
        finalize_file(
            &mut results,
            &mut processed_files,
            file_path,
            &current_file_lines,
            allow_tests,
            debug_mode,
        );
    }

    results
}

/// Extract file paths from text (for stdin mode)
///
/// This function takes a string of text and extracts file paths with optional
/// line numbers or ranges. It's used when the extract command receives input from stdin.
///
/// The function looks for patterns like:
/// - File paths with extensions (e.g., file.rs, path/to/file.go)
/// - Optional line numbers after a colon (e.g., file.rs:10)
/// - Optional line ranges after a colon (e.g., file.rs:1-60)
/// - File paths with line and column numbers (e.g., file.rs:10:42)
/// - File paths with symbol references (e.g., file.rs#function_name)
/// - File paths with symbol references (e.g., file.rs#function_name)
/// - Paths can be wrapped in backticks, single quotes, or double quotes
///
/// If allow_tests is false, test files will be filtered out.
pub fn extract_file_paths_from_text(text: &str, allow_tests: bool) -> Vec<FilePathInfo> {
    let mut results = Vec::new();
    let mut processed_paths = HashSet::new();

    // Check if debug mode is enabled
    let debug_mode = std::env::var("DEBUG").unwrap_or_default() == "1";

    // Preprocess the text to handle paths wrapped in backticks or quotes
    // This replaces backticks, single quotes, and double quotes with spaces
    // around the path, making it easier to match with our regex patterns
    let mut preprocessed_text = String::with_capacity(text.len());
    let mut in_quote = false;
    let mut quote_char = ' ';
    let mut prev_char = ' ';

    for (i, c) in text.chars().enumerate() {
        let next_char = text.chars().nth(i + 1).unwrap_or(' ');

        // Check if this is an apostrophe within a word (like in "Here's")
        // An apostrophe is likely part of a word if:
        // 1. It's surrounded by alphanumeric characters (e.g., "don't", "O'Reilly")
        // 2. It's not at the beginning or end of the text
        let is_apostrophe_in_word =
            c == '\'' && prev_char.is_alphanumeric() && next_char.is_alphanumeric();

        if !in_quote && (c == '`' || c == '"' || (c == '\'' && !is_apostrophe_in_word)) {
            // Start of a quoted section
            in_quote = true;
            quote_char = c;
            preprocessed_text.push(' '); // Add space before the quoted content
        } else if in_quote && c == quote_char {
            // End of a quoted section
            in_quote = false;
            preprocessed_text.push(' '); // Add space after the quoted content
        } else {
            // Regular character
            preprocessed_text.push(c);
        }

        prev_char = c;
    }

    // Use the preprocessed text for regex matching
    let text = &preprocessed_text;

    // First, try to match file paths with symbol references (e.g., file.rs#function_name)
    let file_symbol_regex =
        Regex::new(r"(?:^|[\s\r\n])([a-zA-Z0-9_\-./\*\{\}]+\.[a-zA-Z0-9]+)#([a-zA-Z0-9_]+)")
            .unwrap();

    for cap in file_symbol_regex.captures_iter(text) {
        let file_path = cap.get(1).unwrap().as_str();
        let symbol = cap.get(2).unwrap().as_str();

        // We don't skip symbol references for the same file path
        // This allows multiple symbols from the same file to be extracted

        // Handle glob pattern
        if file_path.contains('*') || file_path.contains('{') {
            if let Ok(paths) = glob(file_path) {
                for entry in paths.flatten() {
                    // Check if the file should be ignored or is a test file
                    let is_test = is_test_file(&entry);
                    let should_include =
                        !is_ignored_by_gitignore(&entry) && (allow_tests || !is_test);
                    if should_include {
                        let path_str = entry.to_string_lossy().to_string();
                        processed_paths.insert(path_str.clone());
                        // Pass the symbol name directly instead of using environment variables
                        results.push((entry, None, None, Some(symbol.to_string()), None));
                    } else if debug_mode {
                        if is_ignored_by_gitignore(&entry) {
                            println!("DEBUG: Skipping ignored file: {entry:?}");
                        } else if !allow_tests && is_test {
                            println!("DEBUG: Skipping test file: {entry:?}");
                        }
                    }
                }
            }
        } else {
            // Check if the path needs special resolution
            match resolve_path(file_path) {
                Ok(resolved_path) => {
                    let is_test = is_test_file(&resolved_path);
                    if !is_ignored_by_gitignore(&resolved_path) && (allow_tests || !is_test) {
                        processed_paths.insert(file_path.to_string());
                        // Pass the symbol name directly instead of using environment variables
                        results.push((resolved_path, None, None, Some(symbol.to_string()), None));
                    } else if debug_mode {
                        if is_ignored_by_gitignore(&resolved_path) {
                            println!("DEBUG: Skipping ignored file: {file_path:?}");
                        } else if !allow_tests && is_test {
                            println!("DEBUG: Skipping test file: {file_path:?}");
                        }
                    }
                }
                Err(err) => {
                    if debug_mode {
                        println!("DEBUG: Failed to resolve path '{file_path}': {err}");
                    }

                    // Fall back to the original path
                    let path = PathBuf::from(file_path);
                    let is_test = is_test_file(&path);
                    if !is_ignored_by_gitignore(&path) && (allow_tests || !is_test) {
                        processed_paths.insert(file_path.to_string());
                        // Pass the symbol name directly instead of using environment variables
                        results.push((path, None, None, Some(symbol.to_string()), None));
                    } else if debug_mode {
                        if is_ignored_by_gitignore(&path) {
                            println!("DEBUG: Skipping ignored file: {file_path:?}");
                        } else if !allow_tests && is_test {
                            println!("DEBUG: Skipping test file: {file_path:?}");
                        }
                    }
                }
            }
        }
    }

    // Next, try to match file paths with line ranges (e.g., file.rs:1-60)
    let file_range_regex =
        Regex::new(r"(?:^|[\s\r\n])([a-zA-Z0-9_\-./\*\{\}]+\.[a-zA-Z0-9]+):(\d+)-(\d+)").unwrap();

    for cap in file_range_regex.captures_iter(text) {
        let file_path = cap.get(1).unwrap().as_str();

        // Skip if we've already processed this path with a symbol reference
        if processed_paths.contains(file_path) {
            continue;
        }

        let start_line = cap.get(2).and_then(|m| m.as_str().parse::<usize>().ok());
        let end_line = cap.get(3).and_then(|m| m.as_str().parse::<usize>().ok());

        if let (Some(start), Some(end)) = (start_line, end_line) {
            // Handle glob pattern
            if file_path.contains('*') || file_path.contains('{') {
                if let Ok(paths) = glob(file_path) {
                    for entry in paths.flatten() {
                        // Check if the file should be ignored or is a test file
                        let is_test = is_test_file(&entry);
                        let should_include =
                            !is_ignored_by_gitignore(&entry) && (allow_tests || !is_test);
                        if should_include {
                            processed_paths.insert(entry.to_string_lossy().to_string());
                            results.push((entry, Some(start), Some(end), None, None));
                        } else if debug_mode {
                            if is_ignored_by_gitignore(&entry) {
                                println!("DEBUG: Skipping ignored file: {entry:?}");
                            } else if !allow_tests && is_test {
                                println!("DEBUG: Skipping test file: {entry:?}");
                            }
                        }
                    }
                }
            } else {
                // Check if the path needs special resolution
                match resolve_path(file_path) {
                    Ok(resolved_path) => {
                        let is_test = is_test_file(&resolved_path);
                        if !is_ignored_by_gitignore(&resolved_path) && (allow_tests || !is_test) {
                            processed_paths.insert(file_path.to_string());
                            results.push((resolved_path, Some(start), Some(end), None, None));
                        } else if debug_mode {
                            if is_ignored_by_gitignore(&resolved_path) {
                                println!("DEBUG: Skipping ignored file: {file_path:?}");
                            } else if !allow_tests && is_test {
                                println!("DEBUG: Skipping test file: {file_path:?}");
                            }
                        }
                    }
                    Err(err) => {
                        if debug_mode {
                            println!("DEBUG: Failed to resolve path '{file_path}': {err}");
                        }

                        // Fall back to the original path
                        let path = PathBuf::from(file_path);
                        let is_test = is_test_file(&path);
                        if !is_ignored_by_gitignore(&path) && (allow_tests || !is_test) {
                            processed_paths.insert(file_path.to_string());
                            results.push((path, Some(start), Some(end), None, None));
                        } else if debug_mode {
                            if is_ignored_by_gitignore(&path) {
                                println!("DEBUG: Skipping ignored file: {file_path:?}");
                            } else if !allow_tests && is_test {
                                println!("DEBUG: Skipping test file: {file_path:?}");
                            }
                        }
                    }
                }
            }
        }
    }

    // Then, try to match file paths with single line numbers (and optional column numbers)
    let file_line_regex =
        Regex::new(r"(?:^|[\s\r\n])([a-zA-Z0-9_\-./\*\{\}]+\.[a-zA-Z0-9]+):(\d+)(?::\d+)?")
            .unwrap();

    for cap in file_line_regex.captures_iter(text) {
        let file_path = cap.get(1).unwrap().as_str();

        // Skip if we've already processed this path with a symbol reference or line range
        if processed_paths.contains(file_path) {
            continue;
        }

        let line_num = cap.get(2).and_then(|m| m.as_str().parse::<usize>().ok());

        // Handle glob pattern
        if file_path.contains('*') || file_path.contains('{') {
            if let Ok(paths) = glob(file_path) {
                for entry in paths.flatten() {
                    let path_str = entry.to_string_lossy().to_string();
                    if !processed_paths.contains(&path_str) {
                        // Check if the file should be ignored or is a test file
                        let is_test = is_test_file(&entry);
                        let should_include =
                            !is_ignored_by_gitignore(&entry) && (allow_tests || !is_test);
                        if should_include {
                            processed_paths.insert(path_str);
                            results.push((entry, line_num, None, None, None));
                        } else if debug_mode {
                            if is_ignored_by_gitignore(&entry) {
                                println!("DEBUG: Skipping ignored file: {entry:?}");
                            } else if !allow_tests && is_test {
                                println!("DEBUG: Skipping test file: {entry:?}");
                            }
                        }
                    }
                }
            }
        } else {
            // Check if the path needs special resolution
            match resolve_path(file_path) {
                Ok(path) => {
                    let is_test = is_test_file(&path);
                    if !is_ignored_by_gitignore(&path) && (allow_tests || !is_test) {
                        processed_paths.insert(file_path.to_string());
                        results.push((path, line_num, None, None, None));
                    } else if debug_mode {
                        if is_ignored_by_gitignore(&path) {
                            println!("DEBUG: Skipping ignored file: {file_path:?}");
                        } else if !allow_tests && is_test {
                            println!("DEBUG: Skipping test file: {file_path:?}");
                        }
                    }
                }
                Err(err) => {
                    if debug_mode {
                        println!("DEBUG: Failed to resolve path '{file_path}': {err}");
                    }

                    // Fall back to the original path
                    let path = PathBuf::from(file_path);
                    let is_test = is_test_file(&path);
                    if !is_ignored_by_gitignore(&path) && (allow_tests || !is_test) {
                        processed_paths.insert(file_path.to_string());
                        results.push((path, line_num, None, None, None));
                    } else if debug_mode {
                        if is_ignored_by_gitignore(&path) {
                            println!("DEBUG: Skipping ignored file: {file_path:?}");
                        } else if !allow_tests && is_test {
                            println!("DEBUG: Skipping test file: {file_path:?}");
                        }
                    }
                }
            }
        }
    }

    // Finally, match file paths without line numbers or symbols
    // But only if they haven't been processed already
    let simple_file_regex =
        Regex::new(r"(?:^|[\s\r\n])([a-zA-Z0-9_\-./\*\{\}]+\.[a-zA-Z0-9]+)").unwrap();

    for cap in simple_file_regex.captures_iter(text) {
        let file_path = cap.get(1).unwrap().as_str();

        // Skip if we've already processed this path with a symbol, line number, or range
        if !processed_paths.contains(file_path) {
            // Handle glob pattern
            if file_path.contains('*') || file_path.contains('{') {
                if let Ok(paths) = glob(file_path) {
                    for entry in paths.flatten() {
                        let path_str = entry.to_string_lossy().to_string();
                        if !processed_paths.contains(&path_str) {
                            // Check if the file should be ignored or is a test file
                            let is_test = is_test_file(&entry);
                            let should_include =
                                !is_ignored_by_gitignore(&entry) && (allow_tests || !is_test);
                            if should_include {
                                processed_paths.insert(path_str);
                                results.push((entry, None, None, None, None));
                            } else if debug_mode {
                                if is_ignored_by_gitignore(&entry) {
                                    println!("DEBUG: Skipping ignored file: {entry:?}");
                                } else if !allow_tests && is_test {
                                    println!("DEBUG: Skipping test file: {entry:?}");
                                }
                            }
                        }
                    }
                }
            } else {
                // Check if the path needs special resolution
                match resolve_path(file_path) {
                    Ok(path) => {
                        let is_test = is_test_file(&path);
                        if !is_ignored_by_gitignore(&path) && (allow_tests || !is_test) {
                            results.push((path, None, None, None, None));
                            processed_paths.insert(file_path.to_string());
                        } else if debug_mode {
                            if is_ignored_by_gitignore(&path) {
                                println!("DEBUG: Skipping ignored file: {file_path:?}");
                            } else if !allow_tests && is_test {
                                println!("DEBUG: Skipping test file: {file_path:?}");
                            }
                        }
                    }
                    Err(err) => {
                        if debug_mode {
                            println!("DEBUG: Failed to resolve path '{file_path}': {err}");
                        }

                        // Fall back to the original path
                        let path = PathBuf::from(file_path);
                        let is_test = is_test_file(&path);
                        if !is_ignored_by_gitignore(&path) && (allow_tests || !is_test) {
                            results.push((path, None, None, None, None));
                            processed_paths.insert(file_path.to_string());
                        } else if debug_mode {
                            if is_ignored_by_gitignore(&path) {
                                println!("DEBUG: Skipping ignored file: {file_path:?}");
                            } else if !allow_tests && is_test {
                                println!("DEBUG: Skipping test file: {file_path:?}");
                            }
                        }
                    }
                }
            }
        }
    }

    results
}

/// Parse a file path with optional line number or range (e.g., "file.rs:10" or "file.rs:1-60")
///
/// If allow_tests is false, test files will be filtered out.
pub fn parse_file_with_line(input: &str, allow_tests: bool) -> Vec<FilePathInfo> {
    let mut results = Vec::new();

    // Remove any surrounding backticks or quotes, but not apostrophes within words
    // First check if the input starts and ends with the same quote character
    let first_char = input.chars().next().unwrap_or(' ');
    let last_char = input.chars().last().unwrap_or(' ');

    let cleaned_input = if (first_char == '`' || first_char == '\'' || first_char == '"')
        && first_char == last_char
    {
        // If the input is fully wrapped in quotes, remove them
        &input[1..input.len() - 1]
    } else {
        // Otherwise just trim any quotes at the beginning or end
        input.trim_matches(|c| c == '`' || c == '"')
    };

    // Check if the input contains a symbol reference (file#symbol or file#parent.child)
    if let Some((file_part, symbol)) = cleaned_input.split_once('#') {
        // For symbol references, we don't have line numbers yet
        // We'll need to find the symbol in the file later
        match resolve_path(file_part) {
            Ok(path) => {
                let is_test = is_test_file(&path);
                if allow_tests || !is_test {
                    // Symbol can be a simple name or a dot-separated path (e.g., "Class.method")
                    results.push((path, None, None, Some(symbol.to_string()), None));
                }
            }
            Err(err) => {
                if std::env::var("DEBUG").unwrap_or_default() == "1" {
                    println!("DEBUG: Failed to resolve path '{file_part}': {err}");
                }

                // Fall back to the original path
                let path = PathBuf::from(file_part);
                let is_test = is_test_file(&path);
                if allow_tests || !is_test {
                    // Symbol can be a simple name or a dot-separated path (e.g., "Class.method")
                    results.push((path, None, None, Some(symbol.to_string()), None));
                }
            }
        }
        return results;
    } else if let Some((file_part, rest)) = cleaned_input.split_once(':') {
        // Extract the line specification from the rest (which might contain more colons)
        let line_spec = rest.split(':').next().unwrap_or("");

        // Check if it's a range (contains a hyphen)
        if let Some((start_str, end_str)) = line_spec.split_once('-') {
            let start_num = start_str.parse::<usize>().ok();
            let end_num = end_str.parse::<usize>().ok();

            if let (Some(start), Some(end)) = (start_num, end_num) {
                // Handle glob pattern
                if file_part.contains('*') || file_part.contains('{') {
                    // Use WalkBuilder to respect .gitignore
                    let base_dir = std::path::Path::new(".");
                    let mut builder = WalkBuilder::new(base_dir);
                    builder.git_ignore(true);
                    builder.git_global(true);
                    builder.git_exclude(true);

                    // Also try glob for backward compatibility
                    if let Ok(paths) = glob(file_part) {
                        for entry in paths.flatten() {
                            // Check if the file should be ignored or is a test file
                            let is_test = is_test_file(&entry);
                            let should_include =
                                !is_ignored_by_gitignore(&entry) && (allow_tests || !is_test);
                            if should_include {
                                results.push((entry, Some(start), Some(end), None, None));
                            }
                        }
                    }
                } else {
                    // Check if the path needs special resolution
                    match resolve_path(file_part) {
                        Ok(path) => {
                            let is_test = is_test_file(&path);
                            if !is_ignored_by_gitignore(&path) && (allow_tests || !is_test) {
                                results.push((path, Some(start), Some(end), None, None));
                            }
                        }
                        Err(err) => {
                            if std::env::var("DEBUG").unwrap_or_default() == "1" {
                                println!("DEBUG: Failed to resolve path '{file_part}': {err}");
                            }

                            // Fall back to the original path
                            let path = PathBuf::from(file_part);
                            let is_test = is_test_file(&path);
                            if !is_ignored_by_gitignore(&path) && (allow_tests || !is_test) {
                                results.push((path, Some(start), Some(end), None, None));
                            }
                        }
                    }
                }
            }
        } else {
            // Try to parse as a single line number
            let line_num = line_spec.parse::<usize>().ok();

            if let Some(num) = line_num {
                // Handle glob pattern
                if file_part.contains('*') || file_part.contains('{') {
                    // Use WalkBuilder to respect .gitignore
                    if let Ok(paths) = glob(file_part) {
                        for entry in paths.flatten() {
                            // Check if the file should be ignored or is a test file
                            let is_test = is_test_file(&entry);
                            let should_include =
                                !is_ignored_by_gitignore(&entry) && (allow_tests || !is_test);
                            if should_include {
                                // Create a HashSet with just this line number
                                let mut lines_set = HashSet::new();
                                lines_set.insert(num);
                                results.push((entry, Some(num), None, None, Some(lines_set)));
                            }
                        }
                    }
                } else {
                    // Check if the path needs special resolution
                    match resolve_path(file_part) {
                        Ok(path) => {
                            let is_test = is_test_file(&path);
                            if !is_ignored_by_gitignore(&path) && (allow_tests || !is_test) {
                                // Create a HashSet with just this line number
                                let mut lines_set = HashSet::new();
                                lines_set.insert(num);
                                results.push((path, Some(num), None, None, Some(lines_set)));
                            }
                        }
                        Err(err) => {
                            if std::env::var("DEBUG").unwrap_or_default() == "1" {
                                println!("DEBUG: Failed to resolve path '{file_part}': {err}");
                            }

                            // Fall back to the original path
                            let path = PathBuf::from(file_part);
                            let is_test = is_test_file(&path);
                            if !is_ignored_by_gitignore(&path) && (allow_tests || !is_test) {
                                // Create a HashSet with just this line number
                                let mut lines_set = HashSet::new();
                                lines_set.insert(num);
                                results.push((path, Some(num), None, None, Some(lines_set)));
                            }
                        }
                    }
                }
            }
        }
    } else {
        // No line number or symbol specified, just a file path
        // Handle glob pattern
        if cleaned_input.contains('*') || cleaned_input.contains('{') {
            if let Ok(paths) = glob(cleaned_input) {
                for entry in paths.flatten() {
                    // Check if the file should be ignored or is a test file
                    let is_test = is_test_file(&entry);
                    let should_include =
                        !is_ignored_by_gitignore(&entry) && (allow_tests || !is_test);
                    if should_include {
                        results.push((entry, None, None, None, None));
                    }
                }
            }
        } else {
            // Check if the path needs special resolution (e.g., go:github.com/user/repo)
            match resolve_path(cleaned_input) {
                Ok(path) => {
                    let is_test = is_test_file(&path);
                    if !is_ignored_by_gitignore(&path) && (allow_tests || !is_test) {
                        results.push((path, None, None, None, None));
                    }
                }
                Err(err) => {
                    // If resolution fails, log the error and try with the original path
                    if std::env::var("DEBUG").unwrap_or_default() == "1" {
                        println!("DEBUG: Failed to resolve path '{cleaned_input}': {err}");
                    }

                    // Fall back to the original path
                    let path = PathBuf::from(cleaned_input);
                    let is_test = is_test_file(&path);
                    if !is_ignored_by_gitignore(&path) && (allow_tests || !is_test) {
                        results.push((path, None, None, None, None));
                    }
                }
            }
        }
    }

    results
}

// Thread-local storage for the custom ignore patterns
thread_local! {
    static CUSTOM_IGNORES: std::cell::RefCell<Vec<String>> = const { std::cell::RefCell::new(Vec::new()) };
}

/// Set custom ignore patterns for the current thread
pub fn set_custom_ignores(patterns: &[String]) {
    CUSTOM_IGNORES.with(|cell| {
        let mut ignores = cell.borrow_mut();
        ignores.clear();
        ignores.extend(patterns.iter().cloned());
    });
}

/// Check if a file should be ignored according to .gitignore rules
fn is_ignored_by_gitignore(path: &PathBuf) -> bool {
    // Check if debug mode is enabled
    let debug_mode = std::env::var("DEBUG").unwrap_or_default() == "1";

    // Simple check for common ignore patterns in the path
    let path_str = path.to_string_lossy().to_lowercase();

    // Check for common ignore patterns directly in the path
    let common_ignore_patterns = [
        "node_modules",
        "vendor",
        "target",
        "dist",
        "build",
        ".git",
        ".svn",
        ".hg",
        ".idea",
        ".vscode",
        "__pycache__",
    ];

    // Get custom ignore patterns
    let mut custom_patterns = Vec::new();
    CUSTOM_IGNORES.with(|cell| {
        let ignores = cell.borrow();
        custom_patterns.extend(ignores.iter().cloned());
    });

    // Check if the path contains any of the common ignore patterns
    for pattern in &common_ignore_patterns {
        if path_str.contains(pattern) {
            if debug_mode {
                println!("DEBUG: File {path:?} is ignored (contains pattern '{pattern}')");
            }
            return true;
        }
    }

    // Check if the path contains any of the custom ignore patterns
    for pattern in &custom_patterns {
        if path_str.contains(pattern) {
            if debug_mode {
                println!("DEBUG: File {path:?} is ignored (contains custom pattern '{pattern}')");
            }
            return true;
        }
    }

    false
}