raz-override 0.2.4

Override management system for raz with stable key generation
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
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
use crate::{
    OverrideEntry,
    backup::BackupManager,
    error::{OverrideError, Result},
};
use indexmap::IndexMap;
use serde::{Deserialize, Serialize};
use std::path::{Path, PathBuf};
use std::sync::{Arc, RwLock};

/// Override storage format
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct StorageFormat {
    version: u32,
    overrides: IndexMap<String, OverrideEntry>,
}

impl Default for StorageFormat {
    fn default() -> Self {
        Self {
            version: 1,
            overrides: IndexMap::new(),
        }
    }
}

/// Manages persistent storage of overrides
pub struct OverrideStorage {
    storage_path: PathBuf,
    #[allow(dead_code)]
    workspace_path: PathBuf,
    cache: RwLock<StorageFormat>,
    backup_manager: Arc<BackupManager>,
    hierarchy: Option<raz_config::ConfigHierarchy>,
}

impl OverrideStorage {
    /// Create new storage instance for testing (bypasses hierarchy)
    #[cfg(test)]
    pub fn new_for_test(storage_path: &Path) -> Result<Self> {
        let storage_file = storage_path.join("overrides.toml");

        // Ensure directory exists
        if let Some(parent) = storage_file.parent() {
            std::fs::create_dir_all(parent)?;
        }

        // Load existing data or create new
        let cache = if storage_file.exists() {
            let content = std::fs::read_to_string(&storage_file)?;
            toml::from_str(&content)?
        } else {
            StorageFormat::default()
        };

        // Create backup manager with default 5 backups
        let backup_manager = Arc::new(BackupManager::new(storage_path, 5)?);

        Ok(Self {
            storage_path: storage_file,
            workspace_path: storage_path.to_path_buf(),
            cache: RwLock::new(cache),
            backup_manager,
            hierarchy: None,
        })
    }

    /// Create new storage instance
    pub fn new(workspace_path: &Path) -> Result<Self> {
        // Use config hierarchy to determine storage location
        let hierarchy = raz_config::ConfigHierarchy::discover(workspace_path).map_err(|e| {
            OverrideError::StorageError(format!("Failed to discover config hierarchy: {e}"))
        })?;

        let storage_path = hierarchy.get_override_storage_path().map_err(|e| {
            OverrideError::StorageError(format!("Failed to get override storage path: {e}"))
        })?;

        // Ensure directory exists
        if let Some(parent) = storage_path.parent() {
            std::fs::create_dir_all(parent)?;
        }

        // Load existing data or create new
        let cache = if storage_path.exists() {
            let content = std::fs::read_to_string(&storage_path)?;
            toml::from_str(&content)?
        } else {
            StorageFormat::default()
        };

        // Create backup manager with default 5 backups
        let backup_manager = Arc::new(BackupManager::new(workspace_path, 5)?);

        Ok(Self {
            storage_path,
            workspace_path: workspace_path.to_path_buf(),
            cache: RwLock::new(cache),
            backup_manager,
            hierarchy: Some(hierarchy),
        })
    }

    /// Save an override entry
    pub fn save(&self, entry: &OverrideEntry) -> Result<()> {
        let mut cache = self
            .cache
            .write()
            .map_err(|e| OverrideError::StorageError(format!("Lock poisoned: {e}")))?;

        // Create backup before modification
        let _ = self
            .backup_manager
            .create_backup(&*cache)
            .map_err(|e| log::warn!("Failed to create backup: {e}"));

        // Store by primary key
        cache
            .overrides
            .insert(entry.key.primary.clone(), entry.clone());

        // Persist to disk
        self.persist(&cache)?;

        Ok(())
    }

    /// Save an override entry with validation check
    pub fn save_with_validation(
        &self,
        entry: &OverrideEntry,
        validate_fn: impl FnOnce(&OverrideEntry) -> Result<()>,
    ) -> Result<()> {
        // Validate before any modifications
        validate_fn(entry)?;

        // If validation passes, save with backup
        self.save(entry)
    }

    /// Get override by primary key
    pub fn get_by_primary_key(&self, key: &str) -> Result<Option<OverrideEntry>> {
        let cache = self
            .cache
            .read()
            .map_err(|e| OverrideError::StorageError(format!("Lock poisoned: {e}")))?;

        Ok(cache.overrides.get(key).cloned())
    }

    /// Get override by any key (primary or fallback)
    pub fn get_by_key(&self, key: &str) -> Result<Option<OverrideEntry>> {
        let cache = self
            .cache
            .read()
            .map_err(|e| OverrideError::StorageError(format!("Lock poisoned: {e}")))?;

        // First try primary key
        if let Some(entry) = cache.overrides.get(key) {
            return Ok(Some(entry.clone()));
        }

        // Then search fallbacks
        for entry in cache.overrides.values() {
            if entry.key.fallbacks.contains(&key.to_string()) {
                return Ok(Some(entry.clone()));
            }
        }

        Ok(None)
    }

    /// Get all overrides for a file
    pub fn get_by_file(&self, file_path: &Path) -> Result<Vec<OverrideEntry>> {
        let cache = self
            .cache
            .read()
            .map_err(|e| OverrideError::StorageError(format!("Lock poisoned: {e}")))?;

        let normalized_path = file_path.to_string_lossy().replace('\\', "/");

        Ok(cache
            .overrides
            .values()
            .filter(|entry| {
                let entry_path = entry
                    .metadata
                    .file_path
                    .to_string_lossy()
                    .replace('\\', "/");
                entry_path == normalized_path
            })
            .cloned()
            .collect())
    }

    /// Delete an override
    pub fn delete(&self, key: &str) -> Result<bool> {
        let mut cache = self
            .cache
            .write()
            .map_err(|e| OverrideError::StorageError(format!("Lock poisoned: {e}")))?;

        let removed = cache.overrides.shift_remove(key).is_some();

        if removed {
            self.persist(&cache)?;
        }

        Ok(removed)
    }

    /// List all overrides from the current storage location
    pub fn list_all(&self) -> Result<Vec<OverrideEntry>> {
        let cache = self
            .cache
            .read()
            .map_err(|e| OverrideError::StorageError(format!("Lock poisoned: {e}")))?;

        Ok(cache.overrides.values().cloned().collect())
    }

    /// List all overrides from all hierarchy levels
    pub fn list_all_hierarchical(
        &self,
    ) -> Result<Vec<(raz_config::ConfigLevel, Vec<OverrideEntry>)>> {
        let mut results = Vec::new();

        if let Some(ref hierarchy) = self.hierarchy {
            for location in hierarchy.locations() {
                if location.exists {
                    let override_path = location.path.join("overrides.toml");
                    if override_path.exists() {
                        if let Ok(content) = std::fs::read_to_string(&override_path) {
                            if let Ok(storage_format) = toml::from_str::<StorageFormat>(&content) {
                                let entries: Vec<OverrideEntry> =
                                    storage_format.overrides.values().cloned().collect();
                                if !entries.is_empty() {
                                    results.push((location.level.clone(), entries));
                                }
                            }
                        }
                    }
                }
            }
        } else {
            // Fallback to current storage if no hierarchy
            results.push((raz_config::ConfigLevel::Project, self.list_all()?));
        }

        Ok(results)
    }

    /// Clear all overrides
    pub fn clear(&self) -> Result<()> {
        let mut cache = self
            .cache
            .write()
            .map_err(|e| OverrideError::StorageError(format!("Lock poisoned: {e}")))?;

        cache.overrides.clear();
        self.persist(&cache)?;

        Ok(())
    }

    /// Clear overrides for a specific file
    pub fn clear_by_file(&self, file_path: &Path) -> Result<usize> {
        let mut cache = self
            .cache
            .write()
            .map_err(|e| OverrideError::StorageError(format!("Lock poisoned: {e}")))?;

        let normalized_path = file_path.to_string_lossy().replace('\\', "/");

        // Find keys of overrides for this file
        let keys_to_remove: Vec<String> = cache
            .overrides
            .iter()
            .filter(|(_, entry)| {
                let entry_path = entry
                    .metadata
                    .file_path
                    .to_string_lossy()
                    .replace('\\', "/");
                entry_path == normalized_path
            })
            .map(|(key, _)| key.clone())
            .collect();

        let count = keys_to_remove.len();

        // Remove the overrides
        for key in keys_to_remove {
            cache.overrides.shift_remove(&key);
        }

        if count > 0 {
            self.persist(&cache)?;
        }

        Ok(count)
    }

    /// Migrate overrides from old format
    pub fn migrate_from_legacy(&self, legacy_data: &str) -> Result<Vec<String>> {
        let mut migrated_keys = Vec::new();

        // Parse legacy format (simplified for now)
        // In real implementation, this would handle the old format
        if let Ok(legacy_map) = toml::from_str::<toml::Value>(legacy_data) {
            if let Some(overrides) = legacy_map.get("overrides").and_then(|v| v.as_table()) {
                for (old_key, _value) in overrides {
                    // Convert old key format to new
                    // Old: "file:line:column"
                    // New: "file:function_name" or "file:L<line>"

                    log::info!("Migrating override: {old_key}");
                    migrated_keys.push(old_key.clone());
                }
            }
        }

        Ok(migrated_keys)
    }

    /// Persist cache to disk
    fn persist(&self, cache: &StorageFormat) -> Result<()> {
        let content = toml::to_string_pretty(cache)?;
        std::fs::write(&self.storage_path, content)?;
        Ok(())
    }

    /// Update execution status of an override
    pub fn update_execution_status(&self, key: &str, success: bool) -> Result<()> {
        let mut cache = self
            .cache
            .write()
            .map_err(|e| OverrideError::StorageError(format!("Lock poisoned: {e}")))?;

        if let Some(entry) = cache.overrides.get_mut(key) {
            let now = chrono::Utc::now();
            entry.metadata.last_execution_time = Some(now);
            entry.metadata.last_execution_success = Some(success);

            if success {
                entry.metadata.validation_status = crate::ValidationStatus::Validated;
                entry.metadata.failure_count = 0;
            } else {
                entry.metadata.failure_count += 1;
                entry.metadata.validation_status =
                    crate::ValidationStatus::Failed(entry.metadata.failure_count);
            }

            entry.metadata.modified_at = now;

            // Persist changes
            self.persist(&cache)?;
        }

        Ok(())
    }

    /// Rollback to the last backup
    pub fn rollback_to_last_backup(&self) -> Result<()> {
        if let Some(backup_info) = self.backup_manager.get_last_backup()? {
            let restored: StorageFormat = self.backup_manager.restore_backup(&backup_info.path)?;

            let mut cache = self
                .cache
                .write()
                .map_err(|e| OverrideError::StorageError(format!("Lock poisoned: {e}")))?;

            *cache = restored;
            self.persist(&cache)?;

            log::info!("Rolled back to backup from {}", backup_info.created_at);
            Ok(())
        } else {
            Err(OverrideError::StorageError(
                "No backup available for rollback".to_string(),
            ))
        }
    }

    /// Get backup manager reference
    pub fn backup_manager(&self) -> &BackupManager {
        &self.backup_manager
    }

    /// Export overrides for backup
    pub fn export(&self) -> Result<String> {
        let cache = self
            .cache
            .read()
            .map_err(|e| OverrideError::StorageError(format!("Lock poisoned: {e}")))?;

        Ok(toml::to_string_pretty(&*cache)?)
    }

    /// Import overrides from backup
    pub fn import(&self, data: &str) -> Result<usize> {
        let imported: StorageFormat = toml::from_str(data)?;

        let mut cache = self
            .cache
            .write()
            .map_err(|e| OverrideError::StorageError(format!("Lock poisoned: {e}")))?;

        let count = imported.overrides.len();

        // Merge with existing (imported takes precedence)
        for (key, entry) in imported.overrides {
            cache.overrides.insert(key, entry);
        }

        self.persist(&cache)?;

        Ok(count)
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::{CommandOverride, FunctionContext, OverrideKey, OverrideMetadata};
    use tempfile::TempDir;

    #[test]
    fn test_storage_operations() {
        let temp_dir = TempDir::new().unwrap();
        let storage = OverrideStorage::new_for_test(temp_dir.path()).unwrap();

        // Create test entry
        let context = FunctionContext {
            file_path: PathBuf::from("src/test.rs"),
            function_name: Some("test_func".to_string()),
            line_number: 10,
            context: None,
        };

        let key = OverrideKey::new(&context).unwrap();
        let entry = OverrideEntry {
            key: key.clone(),
            override_config: CommandOverride::new("test".to_string()),
            metadata: OverrideMetadata {
                created_at: chrono::Utc::now(),
                modified_at: chrono::Utc::now(),
                file_path: context.file_path.clone(),
                function_name: context.function_name.clone(),
                original_line: Some(context.line_number),
                notes: None,
                validation_status: crate::ValidationStatus::Pending,
                last_execution_time: None,
                last_execution_success: None,
                failure_count: 0,
            },
        };

        // Test save
        storage.save(&entry).unwrap();

        // Test get by primary key
        let retrieved = storage.get_by_primary_key(&key.primary).unwrap();
        assert!(retrieved.is_some());
        assert_eq!(retrieved.unwrap().key.primary, key.primary);

        // Test get by file
        let file_overrides = storage.get_by_file(&context.file_path).unwrap();
        assert_eq!(file_overrides.len(), 1);

        // Test delete
        assert!(storage.delete(&key.primary).unwrap());
        assert!(storage.get_by_primary_key(&key.primary).unwrap().is_none());
    }

    #[test]
    fn test_persistence() {
        let temp_dir = TempDir::new().unwrap();
        let storage_path = temp_dir.path();

        // Create and save
        {
            let storage = OverrideStorage::new_for_test(storage_path).unwrap();

            let context = FunctionContext {
                file_path: PathBuf::from("src/main.rs"),
                function_name: Some("main".to_string()),
                line_number: 1,
                context: None,
            };

            let key = OverrideKey::new(&context).unwrap();
            let entry = OverrideEntry {
                key,
                override_config: CommandOverride::new("run".to_string()),
                metadata: OverrideMetadata {
                    created_at: chrono::Utc::now(),
                    modified_at: chrono::Utc::now(),
                    file_path: context.file_path,
                    function_name: context.function_name,
                    original_line: Some(context.line_number),
                    notes: Some("Test override".to_string()),
                    validation_status: crate::ValidationStatus::Pending,
                    last_execution_time: None,
                    last_execution_success: None,
                    failure_count: 0,
                },
            };

            storage.save(&entry).unwrap();
        }

        // Load and verify
        {
            let storage = OverrideStorage::new_for_test(storage_path).unwrap();
            let all = storage.list_all().unwrap();
            assert_eq!(all.len(), 1);
            assert_eq!(all[0].metadata.notes.as_deref(), Some("Test override"));
        }
    }
}