1use crate::utils::error::{Error, Result};
10use sha2::{Digest, Sha256};
11use std::collections::HashMap;
12use std::fs;
13use std::io::Read;
14use std::path::{Path, PathBuf};
15
16#[derive(Debug, Clone)]
18pub struct ContentHash {
19 pub hash: String,
21 pub file_path: PathBuf,
23}
24
25impl ContentHash {
26 pub fn new(hash: String, file_path: PathBuf) -> Self {
28 Self { hash, file_path }
29 }
30}
31
32#[derive(Debug, Clone)]
34pub struct FileState {
35 pub content_hash: String,
37 pub spec_hash: String,
39 pub file_path: PathBuf,
41 pub timestamp: u64,
43}
44
45impl FileState {
46 pub fn new(
48 content_hash: String, spec_hash: String, file_path: PathBuf, timestamp: u64,
49 ) -> Self {
50 Self {
51 content_hash,
52 spec_hash,
53 file_path,
54 timestamp,
55 }
56 }
57
58 pub fn needs_regeneration(&self, current_spec_hash: &str) -> bool {
60 self.spec_hash != current_spec_hash
61 }
62}
63
64#[derive(Debug, Clone, Default)]
66pub struct IncrementalCache {
67 states: HashMap<PathBuf, FileState>,
69 cache_size: usize,
71}
72
73impl IncrementalCache {
74 pub fn new() -> Self {
76 Self {
77 states: HashMap::new(),
78 cache_size: 0,
79 }
80 }
81
82 pub fn get(&self, path: &Path) -> Option<&FileState> {
84 self.states.get(path)
85 }
86
87 pub fn insert(&mut self, path: PathBuf, state: FileState) {
89 self.states.insert(path, state);
90 self.cache_size = self.states.len();
91 }
92
93 pub fn contains(&self, path: &Path) -> bool {
95 self.states.contains_key(path)
96 }
97
98 pub fn size(&self) -> usize {
100 self.cache_size
101 }
102
103 pub fn clear(&mut self) {
105 self.states.clear();
106 self.cache_size = 0;
107 }
108}
109
110#[derive(Debug, Clone)]
112pub struct IncrementalConfig {
113 pub use_cache: bool,
115 pub max_cache_size_mb: u64,
117}
118
119impl Default for IncrementalConfig {
120 fn default() -> Self {
121 Self {
122 use_cache: true,
123 max_cache_size_mb: 0, }
125 }
126}
127
128#[derive(Debug, Clone)]
130pub struct IncrementalResult {
131 pub total_files: usize,
133 pub regenerated_files: usize,
135 pub skipped_files: usize,
137 pub skip_percentage: f64,
139 pub error_files: usize,
141}
142
143impl IncrementalResult {
144 pub fn new(
146 total_files: usize, regenerated_files: usize, skipped_files: usize, error_files: usize,
147 ) -> Self {
148 let skip_percentage = if total_files > 0 {
149 (skipped_files as f64 / total_files as f64) * 100.0
150 } else {
151 0.0
152 };
153
154 Self {
155 total_files,
156 regenerated_files,
157 skipped_files,
158 error_files,
159 skip_percentage,
160 }
161 }
162
163 pub fn all_passed(&self) -> bool {
165 self.error_files == 0
166 }
167}
168
169#[derive(Default)]
171pub struct IncrementalGenerator {
172 cache: IncrementalCache,
174 config: IncrementalConfig,
176}
177
178impl IncrementalGenerator {
179 pub fn new(config: IncrementalConfig) -> Self {
181 Self {
182 cache: IncrementalCache::new(),
183 config,
184 }
185 }
186
187 pub fn with_default_config() -> Self {
189 Self::new(IncrementalConfig::default())
190 }
191
192 pub fn compute_content_hash(file_path: &Path) -> Result<String> {
194 let mut file = fs::File::open(file_path).map_err(|e| {
195 Error::io_error(format!(
196 "Failed to open file '{}': {}",
197 file_path.display(),
198 e
199 ))
200 })?;
201
202 let mut hasher = Sha256::new();
203 let mut buffer = [0; 8192]; loop {
206 let bytes_read = file.read(&mut buffer).map_err(|e| {
207 Error::io_error(format!(
208 "Failed to read file '{}': {}",
209 file_path.display(),
210 e
211 ))
212 })?;
213
214 if bytes_read == 0 {
215 break;
216 }
217
218 hasher.update(&buffer[..bytes_read]);
219 }
220
221 let hash = hasher.finalize();
222 Ok(format!("{:x}", hash))
223 }
224
225 pub fn compute_string_hash(content: &str) -> String {
227 let mut hasher = Sha256::new();
228 hasher.update(content.as_bytes());
229 let hash = hasher.finalize();
230 format!("{:x}", hash)
231 }
232
233 pub fn should_regenerate(&self, file_path: &Path, current_spec_hash: &str) -> Result<bool> {
235 if !self.config.use_cache {
236 return Ok(true);
238 }
239
240 let Some(cached_state) = self.cache.get(file_path) else {
242 return Ok(true);
243 };
244
245 if cached_state.needs_regeneration(current_spec_hash) {
247 return Ok(true);
248 }
249
250 if !file_path.exists() {
252 return Ok(true); }
254
255 let current_content_hash = Self::compute_content_hash(file_path)?;
256 Ok(current_content_hash != cached_state.content_hash)
257 }
258
259 pub fn store_file_state(&mut self, file_path: PathBuf, spec_hash: &str) -> Result<()> {
261 let content_hash = Self::compute_content_hash(&file_path)?;
262 let timestamp = std::time::SystemTime::now()
263 .duration_since(std::time::UNIX_EPOCH)
264 .map_err(|e| Error::io_error(format!("Failed to get timestamp: {}", e)))?
265 .as_secs();
266
267 let file_state = FileState::new(
268 content_hash,
269 spec_hash.to_string(),
270 file_path.clone(),
271 timestamp,
272 );
273
274 self.cache.insert(file_path, file_state);
275 Ok(())
276 }
277
278 pub fn check_files(&self, files: &[PathBuf], spec_hash: &str) -> Result<Vec<bool>> {
281 let mut results = Vec::with_capacity(files.len());
282
283 for file_path in files {
284 let needs_regen = self.should_regenerate(file_path, spec_hash)?;
285 results.push(needs_regen);
286 }
287
288 Ok(results)
289 }
290
291 pub fn cache_size(&self) -> usize {
293 self.cache.size()
294 }
295
296 pub fn clear_cache(&mut self) {
298 self.cache.clear();
299 }
300
301 pub fn get_cache(&self) -> &IncrementalCache {
303 &self.cache
304 }
305}
306
307#[cfg(test)]
308mod tests {
309 use super::*;
310 use tempfile::tempdir;
311
312 #[test]
313 fn test_compute_content_hash() -> Result<()> {
314 let dir = tempdir().map_err(|e| Error::io_error(format!("{}", e)))?;
315 let file_path = dir.path().join("test.txt");
316
317 fs::write(&file_path, b"hello world").map_err(|e| Error::io_error(format!("{}", e)))?;
318
319 let hash1 = IncrementalGenerator::compute_content_hash(&file_path)?;
320 let hash2 = IncrementalGenerator::compute_content_hash(&file_path)?;
321
322 assert_eq!(hash1, hash2);
324 assert!(!hash1.is_empty());
325
326 Ok(())
327 }
328
329 #[test]
330 fn test_compute_string_hash() {
331 let hash1 = IncrementalGenerator::compute_string_hash("test content");
332 let hash2 = IncrementalGenerator::compute_string_hash("test content");
333 let hash3 = IncrementalGenerator::compute_string_hash("different content");
334
335 assert_eq!(hash1, hash2);
337 assert_ne!(hash1, hash3);
339 }
340
341 #[test]
342 fn test_incremental_cache_operations() -> Result<()> {
343 let mut cache = IncrementalCache::new();
344 let path = PathBuf::from("test.rs");
345
346 assert!(!cache.contains(&path));
347 assert_eq!(cache.size(), 0);
348
349 let state = FileState::new(
350 "abc123".to_string(),
351 "def456".to_string(),
352 path.clone(),
353 12345,
354 );
355
356 cache.insert(path.clone(), state);
357 assert!(cache.contains(&path));
358 assert_eq!(cache.size(), 1);
359
360 let retrieved = cache.get(&path);
361 assert!(retrieved.is_some());
362 assert_eq!(retrieved.unwrap().content_hash, "abc123");
363
364 cache.clear();
365 assert!(!cache.contains(&path));
366 assert_eq!(cache.size(), 0);
367
368 Ok(())
369 }
370
371 #[test]
372 fn test_should_regenerate_force_mode() -> Result<()> {
373 let config = IncrementalConfig {
374 use_cache: false, max_cache_size_mb: 0,
376 };
377 let gen = IncrementalGenerator::new(config);
378
379 let dir = tempdir().map_err(|e| Error::io_error(format!("{}", e)))?;
380 let file_path = dir.path().join("test.rs");
381 fs::write(&file_path, b"code").map_err(|e| Error::io_error(format!("{}", e)))?;
382
383 assert!(gen.should_regenerate(&file_path, "any_hash")?);
385
386 Ok(())
387 }
388
389 #[test]
390 fn test_incremental_result_percentage() {
391 let result = IncrementalResult::new(100, 20, 80, 0);
392 assert_eq!(result.skip_percentage, 80.0);
393 assert!(result.all_passed());
394
395 let result = IncrementalResult::new(100, 100, 0, 5);
396 assert_eq!(result.skip_percentage, 0.0);
397 assert!(!result.all_passed());
398
399 let result = IncrementalResult::new(0, 0, 0, 0);
400 assert_eq!(result.skip_percentage, 0.0);
401 assert!(result.all_passed());
402 }
403
404 #[test]
405 fn test_file_state_needs_regeneration() {
406 let state = FileState::new(
407 "content123".to_string(),
408 "spec456".to_string(),
409 PathBuf::from("test.rs"),
410 12345,
411 );
412
413 assert!(!state.needs_regeneration("spec456"));
415
416 assert!(state.needs_regeneration("spec789"));
418 }
419}