vtcode_commons/
vtcodegitignore.rs1use anyhow::{Result, anyhow};
7use ignore::gitignore::{Gitignore, GitignoreBuilder};
8use std::path::{Path, PathBuf};
9use std::sync::Arc;
10use tokio::fs;
11
12#[derive(Debug, Clone)]
14pub struct VTCodeGitignore {
15 root_dir: PathBuf,
17 matcher: Gitignore,
19 loaded: bool,
21}
22
23impl VTCodeGitignore {
24 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(¤t_dir).await
30 }
31
32 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 tracing::warn!("Failed to load .vtcodegitignore: {}", e);
47 }
48 }
49 }
50
51 let matcher = builder.build().unwrap_or_else(|_| {
52 Gitignore::empty()
54 });
55
56 Ok(Self { root_dir: root_dir.to_path_buf(), matcher, loaded })
57 }
58
59 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 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 pub fn should_exclude(&self, file_path: &Path) -> bool {
83 if !self.loaded {
84 return false;
85 }
86
87 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 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 pub fn is_loaded(&self) -> bool {
109 self.loaded
110 }
111
112 pub fn pattern_count(&self) -> usize {
114 self.matcher.num_ignores() as usize
115 }
116
117 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
131pub 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
135pub 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
143pub async fn snapshot_global_vtcode_gitignore() -> Arc<VTCodeGitignore> {
145 VTCODE_GITIGNORE.read().await.clone()
146}
147
148pub 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
154pub async fn filter_paths(paths: Vec<PathBuf>) -> Vec<PathBuf> {
156 let gitignore = snapshot_global_vtcode_gitignore().await;
157 gitignore.filter_paths(paths)
158}
159
160pub async fn reload_vtcode_gitignore() -> Result<()> {
162 initialize_vtcode_gitignore().await
163}