Skip to main content

vtcode_core/terminal_setup/
config_writer.rs

1//! Safe atomic configuration file writing with smart merging.
2//!
3//! Provides atomic writes and marker-based config merging to preserve user customizations.
4
5use crate::utils::file_utils::ensure_dir_exists_sync;
6use anyhow::{Context, Result};
7use std::io::Write;
8use std::path::Path;
9use tempfile::NamedTempFile;
10
11/// Configuration file format
12#[derive(Debug, Clone, Copy, PartialEq, Eq)]
13pub enum ConfigFormat {
14    /// Plain text or shell-style config (# comments)
15    PlainText,
16    /// TOML format
17    Toml,
18    /// JSON with comments (JSONC, as in Zed settings). Never strict JSON:
19    /// markers render as `//` comments, which strict parsers reject.
20    Json,
21    /// YAML format
22    Yaml,
23    /// JavaScript format (for .hyper.js, etc.)
24    JavaScript,
25}
26
27/// Opening marker for a VT Code-managed configuration section.
28pub const VTCODE_BEGIN_MARKER: &str = "BEGIN VTCODE CONFIGURATION";
29/// Closing marker for a VT Code-managed configuration section.
30pub const VTCODE_END_MARKER: &str = "END VTCODE CONFIGURATION";
31
32/// Safe atomic configuration file writer
33pub struct ConfigWriter;
34
35impl ConfigWriter {
36    /// Write content to a file atomically using a temp file and rename
37    ///
38    /// This ensures that the file is never left in a partially-written state
39    pub fn write_atomic(path: &Path, content: &str) -> Result<()> {
40        // Create parent directory if it doesn't exist
41        if let Some(parent) = path.parent() {
42            ensure_dir_exists_sync(parent)
43                .with_context(|| format!("Failed to create directory: {}", parent.display()))?;
44        }
45
46        // Create temp file in the same directory for atomic rename
47        let temp_file = NamedTempFile::new_in(path.parent().unwrap_or_else(|| Path::new(".")))
48            .with_context(|| format!("Failed to create temp file in directory: {}", path.display()))?;
49
50        // Write content to temp file
51        temp_file
52            .as_file()
53            .write_all(content.as_bytes())
54            .with_context(|| "Failed to write content to temp file")?;
55
56        // Sync to ensure data is written to disk
57        temp_file
58            .as_file()
59            .sync_all()
60            .with_context(|| "Failed to sync temp file to disk")?;
61
62        // Atomically rename temp file to target path
63        temp_file
64            .persist(path)
65            .with_context(|| format!("Failed to write config file: {}", path.display()))?;
66
67        Ok(())
68    }
69
70    /// Merge new VT Code configuration section with existing config
71    ///
72    /// Removes old VT Code sections and adds the new section, preserving user customizations.
73    /// Fails without touching anything when the existing markers are unbalanced, so a
74    /// half-edited section can never silently eat user content. `Json` markers are `//`
75    /// comments: only valid for JSONC (Zed), never for strict JSON.
76    pub fn merge_with_markers(existing: &str, new_section: &str, format: ConfigFormat) -> Result<String> {
77        // Remove any existing VT Code section
78        let cleaned = Self::remove_vtcode_section(existing)?;
79
80        // Add new VT Code section with markers
81        let vtcode_section = Self::wrap_with_markers(new_section, format);
82
83        // Determine where to insert the new section
84        let merged = if cleaned.trim().is_empty() {
85            // File is empty, just use the VT Code section
86            vtcode_section
87        } else {
88            // Prepend VT Code section so user-defined settings stay authoritative.
89            // Most terminal configs resolve duplicate keys as "last value wins".
90            format!("{}\n\n{}", vtcode_section, cleaned.trim_start())
91        };
92
93        Ok(merged)
94    }
95
96    /// Remove existing VT Code configuration sections from content
97    ///
98    /// Fails closed on an unterminated section: returning the truncated text
99    /// would delete every user line after the stray marker.
100    fn remove_vtcode_section(content: &str) -> Result<String> {
101        let mut result = Vec::new();
102        let mut in_vtcode_section = false;
103
104        for line in content.lines() {
105            if line.contains(VTCODE_BEGIN_MARKER) {
106                in_vtcode_section = true;
107                continue;
108            }
109
110            if line.contains(VTCODE_END_MARKER) {
111                in_vtcode_section = false;
112                continue;
113            }
114
115            if !in_vtcode_section {
116                result.push(line);
117            }
118        }
119
120        if in_vtcode_section {
121            anyhow::bail!(
122                "unbalanced VT Code section: found '{VTCODE_BEGIN_MARKER}' without '{VTCODE_END_MARKER}'; refusing to modify the file"
123            );
124        }
125
126        Ok(result.join("\n"))
127    }
128
129    /// Wrap configuration content with VT Code markers
130    fn wrap_with_markers(content: &str, format: ConfigFormat) -> String {
131        let comment_prefix = match format {
132            ConfigFormat::PlainText | ConfigFormat::Toml | ConfigFormat::Yaml => "#",
133            ConfigFormat::Json => "//", // JSON doesn't support comments, but some parsers allow them
134            ConfigFormat::JavaScript => "//",
135        };
136
137        let header = format!(
138            "{comment_prefix} {VTCODE_BEGIN_MARKER}\n{comment_prefix} VT Code-managed section - auto-generated\n{comment_prefix} Do not edit manually"
139        );
140
141        let footer = format!("{comment_prefix} {VTCODE_END_MARKER}");
142
143        format!("{}\n{}\n{}", header, content.trim(), footer)
144    }
145
146    /// Detect config file format from extension
147    pub fn detect_format(path: &Path) -> ConfigFormat {
148        if let Some(ext) = path.extension().and_then(|e| e.to_str()) {
149            match ext {
150                "toml" => ConfigFormat::Toml,
151                "json" => ConfigFormat::Json,
152                "yaml" | "yml" => ConfigFormat::Yaml,
153                "js" => ConfigFormat::JavaScript,
154                _ => ConfigFormat::PlainText,
155            }
156        } else {
157            ConfigFormat::PlainText
158        }
159    }
160}
161
162#[cfg(test)]
163mod tests {
164    use super::*;
165    use tempfile::TempDir;
166
167    #[test]
168    fn test_atomic_write() {
169        let temp_dir = TempDir::new().unwrap();
170        let path = temp_dir.path().join("test.conf");
171
172        let content = "test content";
173        ConfigWriter::write_atomic(&path, content).unwrap();
174
175        assert!(path.exists());
176        assert_eq!(std::fs::read_to_string(&path).unwrap(), content);
177    }
178
179    #[test]
180    fn test_remove_vtcode_section() {
181        let content = r#"# User config
182user_setting = 1
183
184# BEGIN VTCODE CONFIGURATION
185# VT Code-managed section - auto-generated
186vtcode_setting = 2
187# END VTCODE CONFIGURATION
188
189# More user config
190another_setting = 3
191"#;
192
193        let result = ConfigWriter::remove_vtcode_section(content).expect("balanced section strips");
194
195        assert!(!result.contains("vtcode_setting"));
196        assert!(result.contains("user_setting"));
197        assert!(result.contains("another_setting"));
198        assert!(!result.contains("VTCODE CONFIGURATION"));
199    }
200
201    #[test]
202    fn unterminated_section_fails_closed() {
203        let content = "# User config\nuser_setting = 1\n\n# BEGIN VTCODE CONFIGURATION\nvtcode_setting = 2\n";
204
205        let result = ConfigWriter::remove_vtcode_section(content);
206        assert!(result.is_err(), "unterminated section must fail, not truncate user content");
207
208        let merged = ConfigWriter::merge_with_markers(content, "vtcode_setting = 3", ConfigFormat::PlainText);
209        assert!(merged.is_err(), "merge must propagate the failure instead of writing");
210    }
211
212    #[test]
213    fn multiple_balanced_sections_are_all_removed() {
214        let content = "# BEGIN VTCODE CONFIGURATION\nold = 1\n# END VTCODE CONFIGURATION\nuser = 2\n# BEGIN VTCODE CONFIGURATION\nolder = 0\n# END VTCODE CONFIGURATION\n";
215
216        let result = ConfigWriter::remove_vtcode_section(content).expect("balanced sections strip");
217
218        assert!(!result.contains("old"));
219        assert!(result.contains("user = 2"));
220    }
221
222    #[test]
223    fn test_merge_with_markers() {
224        let existing = r#"# User config
225user_setting = 1
226"#;
227
228        let new_section = "vtcode_setting = 2";
229
230        let result = ConfigWriter::merge_with_markers(existing, new_section, ConfigFormat::PlainText).unwrap();
231
232        assert!(result.contains("user_setting"));
233        assert!(result.contains("vtcode_setting"));
234        assert!(result.contains(VTCODE_BEGIN_MARKER));
235        assert!(result.contains(VTCODE_END_MARKER));
236        assert!(
237            result.find("vtcode_setting").expect("missing VT Code setting")
238                < result.find("user_setting").expect("missing user setting")
239        );
240    }
241
242    #[test]
243    fn test_merge_empty_file() {
244        let new_section = "vtcode_setting = 1";
245
246        let result = ConfigWriter::merge_with_markers("", new_section, ConfigFormat::PlainText).unwrap();
247
248        assert!(result.contains("vtcode_setting"));
249        assert!(result.contains(VTCODE_BEGIN_MARKER));
250    }
251
252    #[test]
253    fn test_detect_format() {
254        assert_eq!(ConfigWriter::detect_format(Path::new("test.toml")), ConfigFormat::Toml);
255        assert_eq!(ConfigWriter::detect_format(Path::new("test.json")), ConfigFormat::Json);
256        assert_eq!(ConfigWriter::detect_format(Path::new("test.yaml")), ConfigFormat::Yaml);
257        assert_eq!(ConfigWriter::detect_format(Path::new("test.js")), ConfigFormat::JavaScript);
258        assert_eq!(ConfigWriter::detect_format(Path::new("test.conf")), ConfigFormat::PlainText);
259    }
260
261    #[test]
262    fn test_wrap_with_markers_toml() {
263        let content = "setting = 1";
264        let result = ConfigWriter::wrap_with_markers(content, ConfigFormat::Toml);
265
266        assert!(result.starts_with("# BEGIN VTCODE CONFIGURATION"));
267        assert!(result.ends_with("# END VTCODE CONFIGURATION"));
268        assert!(result.contains("setting = 1"));
269    }
270
271    #[test]
272    fn test_wrap_with_markers_javascript() {
273        let content = "const setting = 1;";
274        let result = ConfigWriter::wrap_with_markers(content, ConfigFormat::JavaScript);
275
276        assert!(result.starts_with("// BEGIN VTCODE CONFIGURATION"));
277        assert!(result.contains("const setting = 1;"));
278    }
279}