Skip to main content

vtcode_commons/
vtcodegitignore.rs

1//! .vtcodegitignore file pattern matching utilities
2//!
3//! Uses the `ignore` crate's gitignore parser for correct, battle-tested
4//! pattern matching instead of hand-rolled glob conversion.
5
6use anyhow::{Result, anyhow};
7use ignore::gitignore::{Gitignore, GitignoreBuilder};
8use std::path::{Path, PathBuf};
9use std::sync::Arc;
10use tokio::fs;
11
12/// Represents a .vtcodegitignore file with pattern matching capabilities
13#[derive(Debug, Clone)]
14pub struct VTCodeGitignore {
15    /// Root directory where .vtcodegitignore was found
16    root_dir: PathBuf,
17    /// Compiled gitignore matcher
18    matcher: Gitignore,
19    /// Whether the .vtcodegitignore file exists and was loaded
20    loaded: bool,
21}
22
23impl VTCodeGitignore {
24    /// Create a new VTCodeGitignore instance by looking for .vtcodegitignore in the current directory
25    pub async fn new() -> Result<Self> {
26        let current_dir =
27            std::env::current_dir().map_err(|e| anyhow!("Failed to get current directory: {e}"))?;
28
29        Self::from_directory(&current_dir).await
30    }
31
32    /// Create a VTCodeGitignore instance from a specific directory
33    pub async fn from_directory(root_dir: &Path) -> Result<Self> {
34        let gitignore_path = root_dir.join(".vtcodegitignore");
35
36        let mut loaded = false;
37        let mut builder = GitignoreBuilder::new(root_dir);
38
39        if gitignore_path.exists() {
40            match Self::load_patterns(&gitignore_path, &mut builder).await {
41                Ok(()) => {
42                    loaded = true;
43                }
44                Err(e) => {
45                    // Log warning but don't fail - just treat as no patterns
46                    tracing::warn!("Failed to load .vtcodegitignore: {}", e);
47                }
48            }
49        }
50
51        let matcher = builder.build().unwrap_or_else(|_| {
52            // Fallback to empty matcher on build error
53            Gitignore::empty()
54        });
55
56        Ok(Self { root_dir: root_dir.to_path_buf(), matcher, loaded })
57    }
58
59    /// Load patterns from the .vtcodegitignore file into the builder
60    async fn load_patterns(file_path: &Path, builder: &mut GitignoreBuilder) -> Result<()> {
61        let content = fs::read_to_string(file_path)
62            .await
63            .map_err(|e| anyhow!("Failed to read .vtcodegitignore: {e}"))?;
64
65        for (line_num, line) in content.lines().enumerate() {
66            let line = line.trim();
67
68            // Skip empty lines and comments
69            if line.is_empty() || line.starts_with('#') {
70                continue;
71            }
72
73            builder.add_line(None, line).map_err(|e| {
74                anyhow!("Invalid pattern on line {}: '{}': {}", line_num + 1, line, e)
75            })?;
76        }
77
78        Ok(())
79    }
80
81    /// Check if a file path should be excluded based on the .vtcodegitignore patterns
82    pub fn should_exclude(&self, file_path: &Path) -> bool {
83        if !self.loaded {
84            return false;
85        }
86
87        // Convert to relative path from the root directory
88        let relative_path = match file_path.strip_prefix(&self.root_dir) {
89            Ok(rel) => rel,
90            Err(_) => file_path,
91        };
92
93        self.matcher
94            .matched_path_or_any_parents(relative_path, file_path.is_dir())
95            .is_ignore()
96    }
97
98    /// Filter a list of file paths based on .vtcodegitignore patterns
99    pub fn filter_paths(&self, paths: Vec<PathBuf>) -> Vec<PathBuf> {
100        if !self.loaded {
101            return paths;
102        }
103
104        paths.into_iter().filter(|path| !self.should_exclude(path)).collect()
105    }
106
107    /// Check if the .vtcodegitignore file was loaded successfully
108    pub fn is_loaded(&self) -> bool {
109        self.loaded
110    }
111
112    /// Get the number of patterns loaded
113    pub fn pattern_count(&self) -> usize {
114        self.matcher.num_ignores() as usize
115    }
116
117    /// Get the root directory
118    pub fn root_dir(&self) -> &Path {
119        &self.root_dir
120    }
121}
122
123impl Default for VTCodeGitignore {
124    fn default() -> Self {
125        let root_dir = PathBuf::new();
126        let matcher = Gitignore::empty();
127        Self { root_dir, matcher, loaded: false }
128    }
129}
130
131/// Global .vtcodegitignore instance for easy access
132pub static VTCODE_GITIGNORE: once_cell::sync::Lazy<tokio::sync::RwLock<Arc<VTCodeGitignore>>> =
133    once_cell::sync::Lazy::new(|| tokio::sync::RwLock::new(Arc::new(VTCodeGitignore::default())));
134
135/// Initialize the global .vtcodegitignore instance
136pub async fn initialize_vtcode_gitignore() -> Result<()> {
137    let gitignore = VTCodeGitignore::new().await?;
138    let mut global_gitignore = VTCODE_GITIGNORE.write().await;
139    *global_gitignore = Arc::new(gitignore);
140    Ok(())
141}
142
143/// Snapshot the global .vtcodegitignore instance.
144pub async fn snapshot_global_vtcode_gitignore() -> Arc<VTCodeGitignore> {
145    VTCODE_GITIGNORE.read().await.clone()
146}
147
148/// Check if a file should be excluded by the global .vtcodegitignore
149pub async fn should_exclude_file(file_path: &Path) -> bool {
150    let gitignore = snapshot_global_vtcode_gitignore().await;
151    gitignore.should_exclude(file_path)
152}
153
154/// Filter paths using the global .vtcodegitignore
155pub async fn filter_paths(paths: Vec<PathBuf>) -> Vec<PathBuf> {
156    let gitignore = snapshot_global_vtcode_gitignore().await;
157    gitignore.filter_paths(paths)
158}
159
160/// Reload the global .vtcodegitignore from disk
161pub async fn reload_vtcode_gitignore() -> Result<()> {
162    initialize_vtcode_gitignore().await
163}