vyctor 0.1.0

A fast CLI tool for semantic file search using vector embeddings
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
//! File discovery using glob patterns

use glob::Pattern;
use std::path::{Path, PathBuf};
use walkdir::{DirEntry, WalkDir};

/// File walker that discovers files matching include/exclude patterns
pub struct FileWalker {
    root: PathBuf,
    include_patterns: Vec<Pattern>,
    exclude_patterns: Vec<Pattern>,
}

impl FileWalker {
    /// Create a new file walker
    pub fn new(root: PathBuf, include: Vec<String>, exclude: Vec<String>) -> Self {
        let include_patterns = include
            .iter()
            .filter_map(|p| Pattern::new(p).ok())
            .collect();

        let exclude_patterns = exclude
            .iter()
            .filter_map(|p| Pattern::new(p).ok())
            .collect();

        Self {
            root,
            include_patterns,
            exclude_patterns,
        }
    }

    /// Get the root directory
    pub fn root(&self) -> &Path {
        &self.root
    }

    /// Walk the directory tree and return matching files
    pub fn walk(&self) -> impl Iterator<Item = PathBuf> + '_ {
        WalkDir::new(&self.root)
            .follow_links(false)
            .into_iter()
            .filter_entry(|e| !self.is_excluded_dir(e))
            .filter_map(|e| e.ok())
            .filter(|e| e.file_type().is_file())
            .filter(|e| self.should_include(e.path()))
            .map(|e| e.path().to_path_buf())
    }

    /// Check if a directory entry should be excluded (for early pruning)
    fn is_excluded_dir(&self, entry: &DirEntry) -> bool {
        if !entry.file_type().is_dir() {
            return false;
        }

        let path = entry.path();
        let relative = path.strip_prefix(&self.root).unwrap_or(path);
        let relative_str = relative.to_string_lossy();

        // Check if this directory matches any exclude pattern
        for pattern in &self.exclude_patterns {
            // Check both with and without trailing slash
            if pattern.matches(&relative_str) || pattern.matches(&format!("{}/", relative_str)) {
                return true;
            }

            // Also check for directory-specific patterns like "**/node_modules/**"
            let pattern_str = pattern.as_str();
            if pattern_str.contains("**") {
                // Extract the directory name from patterns like "**/dirname/**"
                if let Some(dir_name) = extract_dir_name(pattern_str) {
                    if let Some(entry_name) = entry.file_name().to_str() {
                        if entry_name == dir_name {
                            return true;
                        }
                    }
                }
            }
        }

        false
    }

    /// Check if a file should be included
    fn should_include(&self, path: &Path) -> bool {
        let relative = path.strip_prefix(&self.root).unwrap_or(path);
        let relative_str = relative.to_string_lossy();

        // First check exclusions
        for pattern in &self.exclude_patterns {
            if pattern.matches(&relative_str) {
                return false;
            }
        }

        // Then check inclusions
        if self.include_patterns.is_empty() {
            return true;
        }

        for pattern in &self.include_patterns {
            if pattern.matches(&relative_str) {
                return true;
            }
        }

        false
    }

    /// Check if a specific path should be indexed
    pub fn should_index(&self, path: &Path) -> bool {
        self.should_include(path)
    }
}

/// Extract directory name from a pattern like "**/dirname/**"
fn extract_dir_name(pattern: &str) -> Option<&str> {
    let trimmed = pattern.trim_start_matches("**/").trim_end_matches("/**");
    if !trimmed.contains('/') && !trimmed.contains('*') {
        Some(trimmed)
    } else {
        None
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use std::fs;
    use tempfile::tempdir;

    #[test]
    fn test_file_walker() {
        let dir = tempdir().unwrap();
        let root = dir.path();

        // Create test files
        fs::write(root.join("test.rs"), "fn main() {}").unwrap();
        fs::write(root.join("test.txt"), "hello").unwrap();
        fs::write(root.join("readme.md"), "# Test").unwrap();

        let walker = FileWalker::new(
            root.to_path_buf(),
            vec!["**/*.rs".to_string(), "**/*.md".to_string()],
            vec![],
        );

        let files: Vec<_> = walker.walk().collect();

        // Should include .rs and .md but not .txt
        assert_eq!(files.len(), 2);
    }

    #[test]
    fn test_exclusion() {
        let dir = tempdir().unwrap();
        let root = dir.path();

        // Create test structure
        fs::create_dir_all(root.join("src")).unwrap();
        fs::create_dir_all(root.join("node_modules")).unwrap();
        fs::write(root.join("src/main.rs"), "fn main() {}").unwrap();
        fs::write(root.join("node_modules/pkg.js"), "module").unwrap();

        let walker = FileWalker::new(
            root.to_path_buf(),
            vec!["**/*.rs".to_string(), "**/*.js".to_string()],
            vec!["**/node_modules/**".to_string()],
        );

        let files: Vec<_> = walker.walk().collect();

        // Should include src/main.rs but not node_modules/pkg.js
        assert_eq!(files.len(), 1);
        assert!(files[0].to_string_lossy().contains("main.rs"));
    }

    #[test]
    fn test_extract_dir_name() {
        assert_eq!(extract_dir_name("**/node_modules/**"), Some("node_modules"));
        assert_eq!(extract_dir_name("**/target/**"), Some("target"));
        assert_eq!(extract_dir_name("**/*.rs"), None);
        assert_eq!(extract_dir_name("**/src/test/**"), None);
    }

    #[test]
    fn test_empty_directory() {
        let dir = tempdir().unwrap();
        let walker = FileWalker::new(
            dir.path().to_path_buf(),
            vec!["**/*.rs".to_string()],
            vec![],
        );

        let files: Vec<_> = walker.walk().collect();
        assert!(files.is_empty());
    }

    #[test]
    fn test_nested_directories() {
        let dir = tempdir().unwrap();
        let root = dir.path();

        // Create deeply nested structure
        fs::create_dir_all(root.join("a/b/c/d")).unwrap();
        fs::write(root.join("a/file1.rs"), "// level 1").unwrap();
        fs::write(root.join("a/b/file2.rs"), "// level 2").unwrap();
        fs::write(root.join("a/b/c/file3.rs"), "// level 3").unwrap();
        fs::write(root.join("a/b/c/d/file4.rs"), "// level 4").unwrap();

        let walker = FileWalker::new(root.to_path_buf(), vec!["**/*.rs".to_string()], vec![]);

        let files: Vec<_> = walker.walk().collect();
        assert_eq!(files.len(), 4);
    }

    #[test]
    fn test_multiple_exclusion_patterns() {
        let dir = tempdir().unwrap();
        let root = dir.path();

        fs::create_dir_all(root.join("src")).unwrap();
        fs::create_dir_all(root.join("node_modules")).unwrap();
        fs::create_dir_all(root.join("target/debug")).unwrap();
        fs::create_dir_all(root.join(".git")).unwrap();

        fs::write(root.join("src/main.rs"), "code").unwrap();
        fs::write(root.join("node_modules/pkg.js"), "module").unwrap();
        fs::write(root.join("target/debug/binary"), "binary").unwrap();
        fs::write(root.join(".git/config"), "gitconfig").unwrap();

        let walker = FileWalker::new(
            root.to_path_buf(),
            vec!["**/*".to_string()],
            vec![
                "**/node_modules/**".to_string(),
                "**/target/**".to_string(),
                "**/.git/**".to_string(),
            ],
        );

        let files: Vec<_> = walker.walk().collect();
        assert_eq!(files.len(), 1);
        assert!(files[0].to_string_lossy().contains("main.rs"));
    }

    #[test]
    fn test_no_include_patterns_includes_all() {
        let dir = tempdir().unwrap();
        let root = dir.path();

        fs::write(root.join("file1.rs"), "rust").unwrap();
        fs::write(root.join("file2.txt"), "text").unwrap();
        fs::write(root.join("file3.md"), "markdown").unwrap();

        let walker = FileWalker::new(
            root.to_path_buf(),
            vec![], // No include patterns
            vec![],
        );

        let files: Vec<_> = walker.walk().collect();
        assert_eq!(files.len(), 3);
    }

    #[test]
    fn test_should_index() {
        let dir = tempdir().unwrap();
        let root = dir.path();

        let walker = FileWalker::new(
            root.to_path_buf(),
            vec!["**/*.rs".to_string()],
            vec!["**/excluded/**".to_string()],
        );

        assert!(walker.should_index(&root.join("src/main.rs")));
        assert!(!walker.should_index(&root.join("src/main.txt")));
        assert!(!walker.should_index(&root.join("excluded/file.rs")));
    }

    #[test]
    fn test_root_accessor() {
        let dir = tempdir().unwrap();
        let walker = FileWalker::new(dir.path().to_path_buf(), vec![], vec![]);

        assert_eq!(walker.root(), dir.path());
    }

    #[test]
    fn test_extension_case_sensitivity() {
        let dir = tempdir().unwrap();
        let root = dir.path();

        // On case-insensitive filesystems (macOS HFS+/APFS), these may be the same file
        // So we use distinct base names to ensure separate files
        fs::write(root.join("file_upper.RS"), "uppercase").unwrap();
        fs::write(root.join("file_lower.rs"), "lowercase").unwrap();
        fs::write(root.join("file_mixed.Rs"), "mixed").unwrap();

        let walker = FileWalker::new(root.to_path_buf(), vec!["**/*.rs".to_string()], vec![]);

        let files: Vec<_> = walker.walk().collect();
        // Glob matching is case-sensitive, so only lowercase .rs should match
        // On case-insensitive FS, the actual extension case in the filesystem is used
        assert!(
            files.len() >= 1,
            "Expected at least 1 file, got {}",
            files.len()
        );
    }

    #[test]
    fn test_files_without_extension() {
        let dir = tempdir().unwrap();
        let root = dir.path();

        fs::write(root.join("Makefile"), "all:").unwrap();
        fs::write(root.join("Dockerfile"), "FROM").unwrap();
        fs::write(root.join("README"), "readme").unwrap();

        let walker = FileWalker::new(
            root.to_path_buf(),
            vec!["**/Makefile".to_string(), "**/Dockerfile".to_string()],
            vec![],
        );

        let files: Vec<_> = walker.walk().collect();
        assert_eq!(files.len(), 2);
    }

    #[test]
    fn test_hidden_files() {
        let dir = tempdir().unwrap();
        let root = dir.path();

        fs::write(root.join(".hidden"), "hidden").unwrap();
        fs::write(root.join(".gitignore"), "gitignore").unwrap();
        fs::write(root.join("visible.txt"), "visible").unwrap();

        let walker = FileWalker::new(root.to_path_buf(), vec!["**/*".to_string()], vec![]);

        let files: Vec<_> = walker.walk().collect();
        // Should include hidden files when pattern matches
        assert!(files.len() >= 1);
    }

    #[test]
    fn test_multiple_extensions_pattern() {
        let dir = tempdir().unwrap();
        let root = dir.path();

        fs::write(root.join("file.ts"), "typescript").unwrap();
        fs::write(root.join("file.tsx"), "tsx").unwrap();
        fs::write(root.join("file.js"), "javascript").unwrap();
        fs::write(root.join("file.jsx"), "jsx").unwrap();

        let walker = FileWalker::new(
            root.to_path_buf(),
            vec!["**/*.ts".to_string(), "**/*.tsx".to_string()],
            vec![],
        );

        let files: Vec<_> = walker.walk().collect();
        assert_eq!(files.len(), 2);
    }

    #[test]
    fn test_specific_file_exclusion() {
        let dir = tempdir().unwrap();
        let root = dir.path();

        fs::write(root.join("keep.rs"), "keep").unwrap();
        fs::write(root.join("exclude.rs"), "exclude").unwrap();

        let walker = FileWalker::new(
            root.to_path_buf(),
            vec!["**/*.rs".to_string()],
            vec!["**/exclude.rs".to_string()],
        );

        let files: Vec<_> = walker.walk().collect();
        assert_eq!(files.len(), 1);
        assert!(files[0].to_string_lossy().contains("keep.rs"));
    }

    #[test]
    fn test_walks_are_deterministic() {
        let dir = tempdir().unwrap();
        let root = dir.path();

        for i in 0..5 {
            fs::write(root.join(format!("file{}.rs", i)), "content").unwrap();
        }

        let walker = FileWalker::new(root.to_path_buf(), vec!["**/*.rs".to_string()], vec![]);

        let files1: Vec<_> = walker.walk().collect();
        let files2: Vec<_> = walker.walk().collect();

        // Both walks should find the same files
        assert_eq!(files1.len(), files2.len());
    }
}