vtcode_core/terminal_setup/
config_writer.rs1use 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#[derive(Debug, Clone, Copy, PartialEq, Eq)]
13pub enum ConfigFormat {
14 PlainText,
16 Toml,
18 Json,
21 Yaml,
23 JavaScript,
25}
26
27pub const VTCODE_BEGIN_MARKER: &str = "BEGIN VTCODE CONFIGURATION";
29pub const VTCODE_END_MARKER: &str = "END VTCODE CONFIGURATION";
31
32pub struct ConfigWriter;
34
35impl ConfigWriter {
36 pub fn write_atomic(path: &Path, content: &str) -> Result<()> {
40 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 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 temp_file
52 .as_file()
53 .write_all(content.as_bytes())
54 .with_context(|| "Failed to write content to temp file")?;
55
56 temp_file
58 .as_file()
59 .sync_all()
60 .with_context(|| "Failed to sync temp file to disk")?;
61
62 temp_file
64 .persist(path)
65 .with_context(|| format!("Failed to write config file: {}", path.display()))?;
66
67 Ok(())
68 }
69
70 pub fn merge_with_markers(existing: &str, new_section: &str, format: ConfigFormat) -> Result<String> {
77 let cleaned = Self::remove_vtcode_section(existing)?;
79
80 let vtcode_section = Self::wrap_with_markers(new_section, format);
82
83 let merged = if cleaned.trim().is_empty() {
85 vtcode_section
87 } else {
88 format!("{}\n\n{}", vtcode_section, cleaned.trim_start())
91 };
92
93 Ok(merged)
94 }
95
96 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 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 => "//", 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 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}