Skip to main content

vtcode_core/terminal_setup/
backup.rs

1//! Configuration backup and restore system.
2//!
3//! Provides timestamped backups with retention policies to safely modify terminal configs.
4
5use crate::utils::file_utils::ensure_dir_exists_sync;
6use anyhow::{Context, Result};
7use chrono::Local;
8use std::fs;
9use std::path::{Path, PathBuf};
10
11use super::detector::TerminalType;
12
13/// Maximum number of backups to retain per config file
14const MAX_BACKUPS: usize = 5;
15
16/// Manages configuration file backups for terminal setup
17pub struct ConfigBackupManager {
18    #[expect(
19        dead_code,
20        reason = "Intentional compatibility, platform, test, or API-shape suppression."
21    )]
22    terminal_type: TerminalType,
23}
24
25impl ConfigBackupManager {
26    /// Create a new backup manager for the given terminal type
27    pub fn new(terminal_type: TerminalType) -> Self {
28        Self { terminal_type }
29    }
30
31    /// Create a timestamped backup of the config file
32    ///
33    /// Returns the path to the created backup file
34    pub fn backup_config(&self, config_path: &Path) -> Result<PathBuf> {
35        // Check if config file exists
36        if !config_path.exists() {
37            anyhow::bail!("Config file does not exist: {}", config_path.display());
38        }
39
40        // Generate backup path with timestamp
41        let backup_path = self.generate_backup_path(config_path)?;
42
43        // Create parent directory if needed
44        if let Some(parent) = backup_path.parent() {
45            ensure_dir_exists_sync(parent)
46                .with_context(|| format!("Failed to create backup directory: {}", parent.display()))?;
47        }
48
49        // Copy config to backup
50        fs::copy(config_path, &backup_path).with_context(|| {
51            format!("Failed to backup config from {} to {}", config_path.display(), backup_path.display())
52        })?;
53
54        // Cleanup old backups
55        self.cleanup_old_backups(config_path)?;
56
57        Ok(backup_path)
58    }
59
60    /// Restore a config file from a backup
61    pub fn restore_backup(&self, original_path: &Path, backup_path: &Path) -> Result<()> {
62        if !backup_path.exists() {
63            anyhow::bail!("Backup file does not exist: {}", backup_path.display());
64        }
65
66        // Create parent directory if needed
67        if let Some(parent) = original_path.parent() {
68            ensure_dir_exists_sync(parent)
69                .with_context(|| format!("Failed to create config directory: {}", parent.display()))?;
70        }
71
72        fs::copy(backup_path, original_path).with_context(|| {
73            format!("Failed to restore backup from {} to {}", backup_path.display(), original_path.display())
74        })?;
75
76        Ok(())
77    }
78
79    /// List all available backups for a config file
80    pub fn list_backups(&self, config_path: &Path) -> Result<Vec<PathBuf>> {
81        let config_name = config_path.file_name().context("Invalid config path")?.to_string_lossy();
82
83        let config_dir = config_path.parent().context("Config file has no parent directory")?;
84
85        if !config_dir.exists() {
86            return Ok(Vec::new());
87        }
88
89        // Match pattern: config_name.vtcode_backup_YYYYMMDD_HHMMSS. The full
90        // delimiter is part of the prefix so `alacritty.toml` never matches
91        // backups of `alacritty.toml.bak` sharing the directory.
92        let expected_prefix = format!("{config_name}.vtcode_backup_");
93        let mut backups = Vec::new();
94
95        for entry in
96            fs::read_dir(config_dir).with_context(|| format!("Failed to read directory: {}", config_dir.display()))?
97        {
98            let entry = entry.with_context(|| "Failed to read directory entry")?;
99            let file_name = entry.file_name();
100            let file_name_str = file_name.to_string_lossy();
101
102            if file_name_str.starts_with(&expected_prefix) {
103                backups.push(entry.path());
104            }
105        }
106
107        // Sort by modification time (newest first)
108        backups.sort_by(|a, b| {
109            let a_meta = fs::metadata(a).ok();
110            let b_meta = fs::metadata(b).ok();
111            let a_modified = a_meta
112                .as_ref()
113                .and_then(|meta| meta.modified().ok())
114                .unwrap_or(std::time::SystemTime::UNIX_EPOCH);
115            let b_modified = b_meta
116                .as_ref()
117                .and_then(|meta| meta.modified().ok())
118                .unwrap_or(std::time::SystemTime::UNIX_EPOCH);
119
120            match b_modified.cmp(&a_modified) {
121                std::cmp::Ordering::Equal => b
122                    .file_name()
123                    .and_then(|name| name.to_str())
124                    .cmp(&a.file_name().and_then(|name| name.to_str())),
125                other => other,
126            }
127        });
128
129        Ok(backups)
130    }
131
132    /// Clean up old backups, keeping only the most recent MAX_BACKUPS
133    pub fn cleanup_old_backups(&self, config_path: &Path) -> Result<()> {
134        let backups = self.list_backups(config_path)?;
135
136        // Remove backups beyond MAX_BACKUPS
137        for backup in backups.iter().skip(MAX_BACKUPS) {
138            fs::remove_file(backup).with_context(|| format!("Failed to remove old backup: {}", backup.display()))?;
139        }
140
141        Ok(())
142    }
143
144    /// Generate a timestamped backup path
145    fn generate_backup_path(&self, config_path: &Path) -> Result<PathBuf> {
146        let timestamp = Local::now().format("%Y%m%d_%H%M%S_%6f");
147
148        let config_name = config_path.file_name().context("Invalid config path")?.to_string_lossy();
149
150        let backup_name = format!("{config_name}.vtcode_backup_{timestamp}");
151        let parent = config_path.parent().context("Config file has no parent directory")?;
152
153        let mut backup_path = parent.join(&backup_name);
154        let mut collision_suffix: u32 = 0;
155        while backup_path.exists() {
156            collision_suffix += 1;
157            backup_path = parent.join(format!("{backup_name}_{collision_suffix}"));
158        }
159
160        Ok(backup_path)
161    }
162}
163
164#[cfg(test)]
165mod tests {
166    use super::*;
167    use std::fs;
168    use tempfile::TempDir;
169
170    #[test]
171    fn test_backup_and_restore() {
172        let temp_dir = TempDir::new().unwrap();
173        let config_path = temp_dir.path().join("test.conf");
174
175        // Create original config
176        fs::write(&config_path, "original content").unwrap();
177
178        // Create backup
179        let manager = ConfigBackupManager::new(TerminalType::Kitty);
180        let backup_path = manager.backup_config(&config_path).unwrap();
181
182        assert!(backup_path.exists());
183        assert_eq!(fs::read_to_string(&backup_path).unwrap(), "original content");
184
185        // Modify original
186        fs::write(&config_path, "modified content").unwrap();
187
188        // Restore from backup
189        manager.restore_backup(&config_path, &backup_path).unwrap();
190
191        assert_eq!(fs::read_to_string(&config_path).unwrap(), "original content");
192    }
193
194    #[test]
195    fn test_list_backups() {
196        let temp_dir = TempDir::new().unwrap();
197        let config_path = temp_dir.path().join("test.conf");
198
199        fs::write(&config_path, "content").unwrap();
200
201        let manager = ConfigBackupManager::new(TerminalType::Kitty);
202
203        // Create multiple backups
204        let backup1 = manager.backup_config(&config_path).unwrap();
205        std::thread::sleep(std::time::Duration::from_millis(10));
206        let backup2 = manager.backup_config(&config_path).unwrap();
207
208        let backups = manager.list_backups(&config_path).unwrap();
209
210        assert_eq!(backups.len(), 2);
211        // Newest should be first
212        assert_eq!(backups[0], backup2);
213        assert_eq!(backups[1], backup1);
214    }
215
216    #[test]
217    fn test_cleanup_old_backups() {
218        let temp_dir = TempDir::new().unwrap();
219        let config_path = temp_dir.path().join("test.conf");
220
221        fs::write(&config_path, "content").unwrap();
222
223        let manager = ConfigBackupManager::new(TerminalType::Kitty);
224
225        // Create more than MAX_BACKUPS
226        for _ in 0..7 {
227            manager.backup_config(&config_path).unwrap();
228            std::thread::sleep(std::time::Duration::from_millis(10));
229        }
230
231        let backups = manager.list_backups(&config_path).unwrap();
232
233        // Should only have MAX_BACKUPS (5) remaining
234        assert_eq!(backups.len(), MAX_BACKUPS);
235    }
236
237    #[test]
238    fn cleanup_preserves_backups_of_other_configs_sharing_the_dir() {
239        let temp_dir = TempDir::new().unwrap();
240        let main_path = temp_dir.path().join("alacritty.toml");
241        let sibling_path = temp_dir.path().join("alacritty.toml.bak");
242        fs::write(&main_path, "main").unwrap();
243        fs::write(&sibling_path, "sibling").unwrap();
244
245        let manager = ConfigBackupManager::new(TerminalType::Alacritty);
246        manager.backup_config(&main_path).unwrap();
247        for _ in 0..6 {
248            manager.backup_config(&sibling_path).unwrap();
249        }
250
251        manager.cleanup_old_backups(&main_path).unwrap();
252
253        assert_eq!(manager.list_backups(&main_path).unwrap().len(), 1);
254        assert_eq!(
255            manager.list_backups(&sibling_path).unwrap().len(),
256            MAX_BACKUPS,
257            "cleanup for one config must not delete a sibling config's backups"
258        );
259    }
260
261    #[test]
262    fn test_backup_nonexistent_file() {
263        let temp_dir = TempDir::new().unwrap();
264        let config_path = temp_dir.path().join("nonexistent.conf");
265
266        let manager = ConfigBackupManager::new(TerminalType::Kitty);
267        let result = manager.backup_config(&config_path);
268
269        result.unwrap_err();
270    }
271}