vtcode_config/loader/manager/
persistence.rs1use std::fs;
4use std::path::Path;
5
6use anyhow::{Context, Result, bail};
7use vtcode_commons::VtCodePaths;
8
9use super::{ConfigLayerSource, ConfigManager, VTCodeConfig};
10
11fn ensure_private_parent_dir(path: &Path) -> Result<()> {
12 let Some(parent) = path.parent() else {
13 return Ok(());
14 };
15 let _ = VtCodePaths::ensure_user_dir(parent)
16 .with_context(|| format!("Failed to create directory: {}", parent.display()))?;
17 Ok(())
18}
19
20impl ConfigManager {
21 pub fn save_config_to_path(path: impl AsRef<Path>, config: &VTCodeConfig) -> Result<()> {
23 Self::save_config_to_path_internal(path, config, false)
24 }
25
26 pub fn save_repository_config_to_path(path: impl AsRef<Path>, config: &VTCodeConfig) -> Result<()> {
34 Self::save_config_to_path_internal(path, config, true)
35 }
36
37 fn save_config_to_path_internal(
38 path: impl AsRef<Path>,
39 config: &VTCodeConfig,
40 repository_controlled: bool,
41 ) -> Result<()> {
42 let path = path.as_ref();
43 ensure_private_parent_dir(path)?;
44 let config_to_persist = if repository_controlled {
45 Self::repository_safe_config(config)
46 } else {
47 config.clone()
48 };
49 let sparse_value =
50 Self::sparse_config_value(&config_to_persist).context("Failed to prepare sparse configuration")?;
51 let sparse_content =
52 toml::to_string_pretty(&sparse_value).context("Failed to serialize sparse configuration")?;
53
54 let existing_content = match fs::symlink_metadata(path) {
58 Ok(metadata) if metadata.file_type().is_symlink() => {
59 bail!("Refusing to read symlinked config file: {}", path.display())
60 }
61 Ok(metadata) if !metadata.is_file() => {
62 bail!("Config path is not a regular file: {}", path.display())
63 }
64 Ok(_) => Some(
65 String::from_utf8(VtCodePaths::read_file_no_follow(path)?)
66 .with_context(|| format!("Failed to read existing config: {}", path.display()))?,
67 ),
68 Err(error) if error.kind() == std::io::ErrorKind::NotFound => None,
69 Err(error) => {
70 return Err(error).with_context(|| format!("Failed to inspect config: {}", path.display()));
71 }
72 };
73
74 if let Some(original_content) = existing_content {
75 let mut doc = original_content
76 .parse::<toml_edit::DocumentMut>()
77 .with_context(|| format!("Failed to parse existing config: {}", path.display()))?;
78 Self::remove_deprecated_config_keys(&mut doc);
79 if repository_controlled {
80 Self::remove_repository_provider_settings(&mut doc);
81 }
82
83 let new_doc: toml_edit::DocumentMut = sparse_content
84 .parse()
85 .context("Failed to parse sparse serialized configuration")?;
86 let default_value =
87 toml::Value::try_from(VTCodeConfig::default()).context("Failed to serialize default configuration")?;
88 let default_doc: toml_edit::DocumentMut = toml::to_string_pretty(&default_value)
89 .context("Failed to serialize default configuration")?
90 .parse()
91 .context("Failed to parse default serialized configuration")?;
92
93 Self::merge_sparse_toml_documents(&mut doc, &new_doc, &default_doc);
95 Self::prune_cleared_optional_fields(&mut doc, &config_to_persist);
101
102 VtCodePaths::write_private_file_atomic(path, doc.to_string().as_bytes())
103 .with_context(|| format!("Failed to write config file: {}", path.display()))?;
104 } else {
105 VtCodePaths::write_private_file_atomic(path, sparse_content.as_bytes())
106 .with_context(|| format!("Failed to write config file: {}", path.display()))?;
107 }
108
109 Ok(())
110 }
111
112 fn repository_safe_config(config: &VTCodeConfig) -> VTCodeConfig {
113 let mut safe_config = config.clone();
114 safe_config.custom_providers.clear();
115 for provider_override in safe_config.provider_overrides.values_mut() {
116 provider_override.base_url = None;
117 provider_override.api_key_env = None;
118 }
119 safe_config
120 }
121
122 fn prune_cleared_optional_fields(doc: &mut toml_edit::DocumentMut, config: &VTCodeConfig) {
130 let cleared: &[(&[&str], bool)] = &[
132 (&["provider", "openai", "service_tier"], config.provider.openai.service_tier.is_none()),
133 (&["provider", "anthropic", "speed"], config.provider.anthropic.speed.is_none()),
134 ];
135 for (path, is_cleared) in cleared {
136 if *is_cleared {
137 Self::remove_path_and_prune_empty_parents(doc.as_table_mut(), path);
138 }
139 }
140 }
141
142 fn remove_path_and_prune_empty_parents(table: &mut toml_edit::Table, path: &[&str]) -> bool {
145 let Some((first, rest)) = path.split_first() else {
146 return table.is_empty();
147 };
148 if rest.is_empty() {
149 table.remove(first);
150 } else if let Some(child) = table.get_mut(first).and_then(toml_edit::Item::as_table_mut) {
151 if Self::remove_path_and_prune_empty_parents(child, rest) {
152 table.remove(first);
153 }
154 }
155 table.is_empty()
156 }
157
158 fn remove_deprecated_config_keys(doc: &mut toml_edit::DocumentMut) {
159 let table = doc.as_table_mut();
160 table.remove("project_doc_max_bytes");
161 table.remove("project_doc_fallback_filenames");
162 Self::remove_table_keys(table, "agent", &["autonomous_mode", "default_editing_mode"]);
163 Self::remove_table_keys(table, "permissions", &["allowed_tools", "disallowed_tools", "auto_permission"]);
164 }
165
166 fn remove_table_keys(table: &mut toml_edit::Table, section: &str, keys: &[&str]) {
167 let Some(section) = table.get_mut(section).and_then(toml_edit::Item::as_table_mut) else {
168 return;
169 };
170
171 for key in keys {
172 section.remove(key);
173 }
174 }
175
176 pub fn sparse_config_value(config: &VTCodeConfig) -> Result<toml::Value> {
177 let mut value = toml::Value::try_from(config).context("Failed to serialize configuration")?;
178 let default_value =
179 toml::Value::try_from(VTCodeConfig::default()).context("Failed to serialize default configuration")?;
180 Self::prune_default_values(&mut value, &default_value);
181 Ok(value)
182 }
183
184 fn prune_default_values(value: &mut toml::Value, default_value: &toml::Value) -> bool {
185 match (value, default_value) {
186 (toml::Value::Table(table), toml::Value::Table(default_table)) => {
187 table.retain(|key, child| {
188 default_table
189 .get(key)
190 .is_none_or(|default_child| !Self::prune_default_values(child, default_child))
191 });
192 table.is_empty()
193 }
194 (value, default_value) => value == default_value,
195 }
196 }
197
198 fn merge_sparse_toml_documents(
200 original: &mut toml_edit::DocumentMut,
201 new: &toml_edit::DocumentMut,
202 default_doc: &toml_edit::DocumentMut,
203 ) {
204 Self::merge_sparse_tables(original.as_table_mut(), new.as_table(), default_doc.as_table());
205 }
206
207 fn merge_sparse_tables(original: &mut toml_edit::Table, new: &toml_edit::Table, default_table: &toml_edit::Table) {
208 let mut remove_keys = Vec::with_capacity(default_table.len());
209
210 for (key, default_value) in default_table.iter() {
211 if let Some(new_value) = new.get(key) {
212 if let Some(original_value) = original.get_mut(key) {
213 Self::merge_sparse_items(original_value, new_value, default_value);
214 } else {
215 original[key] = new_value.clone();
216 }
217 } else {
218 let Some(original_value) = original.get_mut(key) else {
219 continue;
220 };
221 if Self::remove_known_default_item(original_value, default_value) {
222 remove_keys.push(key.to_string());
223 }
224 }
225 }
226
227 for key in remove_keys {
228 original.remove(&key);
229 }
230
231 for (key, new_value) in new.iter() {
232 if default_table.contains_key(key) {
233 continue;
234 }
235 if let Some(original_value) = original.get_mut(key) {
236 *original_value = new_value.clone();
237 } else {
238 original[key] = new_value.clone();
239 }
240 }
241 }
242
243 fn merge_sparse_items(original: &mut toml_edit::Item, new: &toml_edit::Item, default_value: &toml_edit::Item) {
244 match (original, new, default_value) {
245 (
246 toml_edit::Item::Table(orig_table),
247 toml_edit::Item::Table(new_table),
248 toml_edit::Item::Table(default_table),
249 ) => Self::merge_sparse_tables(orig_table, new_table, default_table),
250 (orig, new, _) => {
251 *orig = new.clone();
252 }
253 }
254 }
255
256 fn remove_known_default_item(original: &mut toml_edit::Item, default_value: &toml_edit::Item) -> bool {
257 match (original, default_value) {
258 (toml_edit::Item::Table(orig_table), toml_edit::Item::Table(default_table)) => {
259 let mut remove_keys = Vec::new();
260 for (key, default_child) in default_table.iter() {
261 let Some(orig_child) = orig_table.get_mut(key) else {
262 continue;
263 };
264 if Self::remove_known_default_item(orig_child, default_child) {
265 remove_keys.push(key.to_string());
266 }
267 }
268 for key in remove_keys {
269 orig_table.remove(&key);
270 }
271 orig_table.is_empty()
272 }
273 _ => true,
274 }
275 }
276
277 pub fn save_config(&mut self, config: &VTCodeConfig) -> Result<()> {
279 let (target, repository_controlled) = if let Some(path) = &self.config_path {
280 if self.write_global_config_to_canonical || self.is_global_config_path(path) {
281 (self.preferred_user_config_path().unwrap_or_else(|| path.clone()), false)
282 } else {
283 (path.clone(), !self.explicit_config_is_trusted)
284 }
285 } else if let Some(workspace_root) = &self.workspace_root {
286 (workspace_root.join(&self.config_file_name), !self.explicit_config_is_trusted)
287 } else {
288 let cwd = std::env::current_dir().context("Failed to resolve current directory")?;
289 (cwd.join(&self.config_file_name), !self.explicit_config_is_trusted)
290 };
291
292 if repository_controlled {
293 Self::save_repository_config_to_path(target, config)?;
294 } else {
295 Self::save_config_to_path(target, config)?;
296 }
297
298 #[cfg(not(test))]
299 if let Some(workspace) = &self.workspace_root {
300 Self::invalidate_workspace_cache(workspace);
301 }
302
303 self.sync_from_config(config)
304 }
305
306 fn is_global_config_path(&self, path: &Path) -> bool {
307 self.layer_stack.layers().iter().any(|layer| {
308 layer.is_enabled()
309 && matches!(layer.source, ConfigLayerSource::System { .. } | ConfigLayerSource::User { .. })
310 && match &layer.source {
311 ConfigLayerSource::System { file } | ConfigLayerSource::User { file } => file == path,
312 _ => false,
313 }
314 })
315 }
316
317 fn sync_from_config(&mut self, config: &VTCodeConfig) -> Result<()> {
320 self.config = config.clone();
321 Ok(())
322 }
323}