AirLibrary/Indexing/Scan/
ScanFile.rs1use std::{
72 path::PathBuf,
73 time::{Duration, Instant},
74};
75
76use crate::dev_log;
78use crate::{
79 AirError,
80 Configuration::IndexingConfig,
81 Indexing::{
82 Process::{
83 ExtractSymbols::ExtractSymbols,
84 ProcessContent::{DetectEncoding, DetectLanguage, DetectMimeType},
85 },
86 State::CreateState::{FileMetadata, SymbolInfo},
87 },
88 Result,
89};
90
91pub async fn IndexFileInternal(
103 file_path:&PathBuf,
104
105 config:&IndexingConfig,
106
107 _patterns:&[String],
108) -> Result<(FileMetadata, Vec<SymbolInfo>)> {
109 let start_time = Instant::now();
110
111 let metadata = std::fs::metadata(file_path)
113 .map_err(|e| AirError::FileSystem(format!("Failed to get file metadata: {}", e)))?;
114
115 let modified = metadata
117 .modified()
118 .map_err(|e| AirError::FileSystem(format!("Failed to get modification time: {}", e)))?;
119
120 let modified_time = chrono::DateTime::<chrono::Utc>::from(modified);
121
122 let file_size = metadata.len();
124
125 if file_size > config.MaxFileSizeMb as u64 * 1024 * 1024 {
126 return Err(AirError::FileSystem(format!(
127 "File size {} exceeds limit {} MB",
128 file_size, config.MaxFileSizeMb
129 )));
130 }
131
132 let content = tokio::time::timeout(Duration::from_secs(30), tokio::fs::read(file_path))
134 .await
135 .map_err(|_| AirError::FileSystem(format!("Timeout reading file: {} (30s limit)", file_path.display())))?
136 .map_err(|e| AirError::FileSystem(format!("Failed to read file: {}", e)))?;
137
138 let is_symlink = std::fs::symlink_metadata(file_path)
140 .map(|m| m.file_type().is_symlink())
141 .unwrap_or(false);
142
143 let checksum = CalculateChecksum(&content);
145
146 let encoding = DetectEncoding(&content);
148
149 let mime_type = DetectMimeType(file_path, &content);
151
152 let language = DetectLanguage(file_path);
154
155 let line_count = if mime_type.starts_with("text/") {
157 Some(content.iter().filter(|&&b| b == b'\n').count() as u32 + 1)
158 } else {
159 None
160 };
161
162 let symbols = if let Some(lang) = &language {
164 ExtractSymbols(file_path, &content, lang).await?
165 } else {
166 Vec::new()
167 };
168
169 let permissions = GetPermissionsString(&metadata);
170
171 let elapsed = start_time.elapsed();
172
173 dev_log!(
174 "indexing",
175 "indexed {} in {}ms ({} symbols)",
176 file_path.display(),
177 elapsed.as_millis(),
178 symbols.len()
179 );
180
181 Ok((
182 FileMetadata {
183 path:file_path.clone(),
184 size:file_size,
185 modified:modified_time,
186 mime_type,
187 language,
188 line_count,
189 checksum,
190 is_symlink,
191 permissions,
192 encoding,
193 indexed_at:chrono::Utc::now(),
194 symbol_count:symbols.len() as u32,
195 },
196 symbols,
197 ))
198}
199
200pub async fn ValidateFileAccess(file_path:&PathBuf) -> bool {
202 tokio::task::spawn_blocking({
203 let file_path = file_path.to_path_buf();
204 move || {
205 let can_access = std::fs::metadata(&file_path).is_ok();
207 if can_access {
208 std::fs::File::open(&file_path).is_ok()
210 } else {
211 false
212 }
213 }
214 })
215 .await
216 .unwrap_or(false)
217}
218
219pub fn CalculateChecksum(content:&[u8]) -> String {
221 use sha2::{Digest, Sha256};
226
227 let mut hasher = Sha256::new();
228
229 hasher.update(content);
230
231 hex::encode(hasher.finalize())
232}
233
234#[cfg(unix)]
236pub fn GetPermissionsString(metadata:&std::fs::Metadata) -> String {
237 use std::os::unix::fs::PermissionsExt;
238
239 let mode = metadata.permissions().mode();
240
241 let mut perms = String::new();
242
243 perms.push(if mode & 0o400 != 0 { 'r' } else { '-' });
245
246 perms.push(if mode & 0o200 != 0 { 'w' } else { '-' });
248
249 perms.push(if mode & 0o100 != 0 { 'x' } else { '-' });
251
252 perms.push(if mode & 0o040 != 0 { 'r' } else { '-' });
254
255 perms.push(if mode & 0o020 != 0 { 'w' } else { '-' });
256
257 perms.push(if mode & 0o010 != 0 { 'x' } else { '-' });
258
259 perms.push(if mode & 0o004 != 0 { 'r' } else { '-' });
261
262 perms.push(if mode & 0o002 != 0 { 'w' } else { '-' });
263
264 perms.push(if mode & 0o001 != 0 { 'x' } else { '-' });
265
266 perms
267}
268
269#[cfg(not(unix))]
271pub fn GetPermissionsString(_metadata:&std::fs::Metadata) -> String { "--------".to_string() }
272
273pub async fn ScanFileMetadata(file_path:&PathBuf) -> Result<FileMetadata> {
275 let metadata = std::fs::metadata(file_path)
276 .map_err(|e| AirError::FileSystem(format!("Failed to get file metadata: {}", e)))?;
277
278 let modified = metadata
279 .modified()
280 .map_err(|e| AirError::FileSystem(format!("Failed to get modification time: {}", e)))?;
281
282 let modified_time = chrono::DateTime::<chrono::Utc>::from(modified);
283
284 Ok(FileMetadata {
285 path:file_path.clone(),
286 size:metadata.len(),
287 modified:modified_time,
288 mime_type:"application/octet-stream".to_string(),
289 language:None,
290 line_count:None,
291 checksum:String::new(),
292 is_symlink:metadata.file_type().is_symlink(),
293 permissions:GetPermissionsString(&metadata),
294 encoding:None,
295 indexed_at:chrono::Utc::now(),
296 symbol_count:0,
297 })
298}
299
300pub fn FileModifiedSince(file_path:&PathBuf, last_indexed:chrono::DateTime<chrono::Utc>) -> Result<bool> {
302 let metadata = std::fs::metadata(file_path)
303 .map_err(|e| AirError::FileSystem(format!("Failed to get file metadata: {}", e)))?;
304
305 let modified = metadata
306 .modified()
307 .map_err(|e| AirError::FileSystem(format!("Failed to get modification time: {}", e)))?;
308
309 let modified_time = chrono::DateTime::<chrono::Utc>::from(modified);
310
311 Ok(modified_time > last_indexed)
312}
313
314pub async fn GetFileSize(file_path:&PathBuf) -> Result<u64> {
316 tokio::task::spawn_blocking({
317 let file_path = file_path.to_path_buf();
318 move || {
319 let metadata = std::fs::metadata(&file_path)
320 .map_err(|e| AirError::FileSystem(format!("Failed to get file metadata: {}", e)))?;
321 Ok(metadata.len())
322 }
323 })
324 .await?
325}
326
327pub fn IsTextFile(metadata:&FileMetadata) -> bool {
329 metadata.mime_type.starts_with("text/")
330 || metadata.mime_type.contains("json")
331 || metadata.mime_type.contains("xml")
332 || metadata.mime_type.contains("yaml")
333 || metadata.mime_type.contains("toml")
334 || metadata.language.is_some()
335}
336
337pub fn IsBinaryFile(metadata:&FileMetadata) -> bool {
339 !IsTextFile(metadata)
340 || metadata.mime_type == "application/octet-stream"
341 || metadata.mime_type == "application/zip"
342 || metadata.mime_type == "application/x-tar"
343 || metadata.mime_type == "application/x-gzip"
344 || metadata.mime_type == "application/x-bzip2"
345}