Skip to main content

vtcode_config/loader/manager/
persistence.rs

1//! Sparse configuration saves and comment-preserving TOML persistence.
2
3use 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    /// Persist configuration to a specific path, preserving comments.
22    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    /// Persist configuration to a repository-controlled path.
27    ///
28    /// Repository and project files may contain ordinary settings, but they
29    /// must never receive trusted provider definitions or provider endpoint and
30    /// credential overrides from the merged configuration. Existing protected
31    /// keys are removed as well so this method can repair files written by an
32    /// older version that flattened the effective configuration.
33    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        // If file exists, preserve comments by using toml_edit. Read and
55        // publish through the shared no-follow/atomic file policy so a
56        // user-controlled symlink cannot redirect configuration writes.
57        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            // Update values while preserving structure and comments
94            Self::merge_sparse_toml_documents(&mut doc, &new_doc, &default_doc);
95            // The sparse merge cannot express the deletion of optional fields
96            // whose default serializes to absent (they appear in neither the
97            // sparse update nor the defaults), so resets issued through save
98            // paths (e.g. service_tier back to Project default) would leave
99            // stale file values behind forever. Reconcile those explicitly.
100            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    /// Remove file values for optional fields the effective config reset to
123    /// their absent default (e.g. `provider.openai.service_tier` back to
124    /// Project default). The sparse merge cannot express these deletions
125    /// (absent from both the sparse update and the defaults), so each entry
126    /// pairs a dotted path with a typed cleared-check. Only listed paths are
127    /// touched; foreign keys are never removed. Extend the list when a new
128    /// resettable optional reaches a save path.
129    fn prune_cleared_optional_fields(doc: &mut toml_edit::DocumentMut, config: &VTCodeConfig) {
130        // Each entry: (dotted path, is_cleared).
131        let cleared: &[(&[&str], bool)] =
132            &[(&["provider", "openai", "service_tier"], config.provider.openai.service_tier.is_none())];
133        for (path, is_cleared) in cleared {
134            if *is_cleared {
135                Self::remove_path_and_prune_empty_parents(doc.as_table_mut(), path);
136            }
137        }
138    }
139
140    /// Remove `path` from `table`, then drop ancestor tables left empty.
141    /// Returns true when `table` itself is now empty.
142    fn remove_path_and_prune_empty_parents(table: &mut toml_edit::Table, path: &[&str]) -> bool {
143        let Some((first, rest)) = path.split_first() else {
144            return table.is_empty();
145        };
146        if rest.is_empty() {
147            table.remove(first);
148        } else if let Some(child) = table.get_mut(first).and_then(toml_edit::Item::as_table_mut) {
149            if Self::remove_path_and_prune_empty_parents(child, rest) {
150                table.remove(first);
151            }
152        }
153        table.is_empty()
154    }
155
156    fn remove_deprecated_config_keys(doc: &mut toml_edit::DocumentMut) {
157        let table = doc.as_table_mut();
158        table.remove("project_doc_max_bytes");
159        table.remove("project_doc_fallback_filenames");
160        Self::remove_table_keys(table, "agent", &["autonomous_mode", "default_editing_mode"]);
161        Self::remove_table_keys(table, "permissions", &["allowed_tools", "disallowed_tools", "auto_permission"]);
162    }
163
164    fn remove_table_keys(table: &mut toml_edit::Table, section: &str, keys: &[&str]) {
165        let Some(section) = table.get_mut(section).and_then(toml_edit::Item::as_table_mut) else {
166            return;
167        };
168
169        for key in keys {
170            section.remove(key);
171        }
172    }
173
174    pub fn sparse_config_value(config: &VTCodeConfig) -> Result<toml::Value> {
175        let mut value = toml::Value::try_from(config).context("Failed to serialize configuration")?;
176        let default_value =
177            toml::Value::try_from(VTCodeConfig::default()).context("Failed to serialize default configuration")?;
178        Self::prune_default_values(&mut value, &default_value);
179        Ok(value)
180    }
181
182    fn prune_default_values(value: &mut toml::Value, default_value: &toml::Value) -> bool {
183        match (value, default_value) {
184            (toml::Value::Table(table), toml::Value::Table(default_table)) => {
185                table.retain(|key, child| {
186                    default_table
187                        .get(key)
188                        .is_none_or(|default_child| !Self::prune_default_values(child, default_child))
189                });
190                table.is_empty()
191            }
192            (value, default_value) => value == default_value,
193        }
194    }
195
196    /// Merge TOML documents, preserving comments and structure from original
197    fn merge_sparse_toml_documents(
198        original: &mut toml_edit::DocumentMut,
199        new: &toml_edit::DocumentMut,
200        default_doc: &toml_edit::DocumentMut,
201    ) {
202        Self::merge_sparse_tables(original.as_table_mut(), new.as_table(), default_doc.as_table());
203    }
204
205    fn merge_sparse_tables(original: &mut toml_edit::Table, new: &toml_edit::Table, default_table: &toml_edit::Table) {
206        let mut remove_keys = Vec::with_capacity(default_table.len());
207
208        for (key, default_value) in default_table.iter() {
209            if let Some(new_value) = new.get(key) {
210                if let Some(original_value) = original.get_mut(key) {
211                    Self::merge_sparse_items(original_value, new_value, default_value);
212                } else {
213                    original[key] = new_value.clone();
214                }
215            } else {
216                let Some(original_value) = original.get_mut(key) else {
217                    continue;
218                };
219                if Self::remove_known_default_item(original_value, default_value) {
220                    remove_keys.push(key.to_string());
221                }
222            }
223        }
224
225        for key in remove_keys {
226            original.remove(&key);
227        }
228
229        for (key, new_value) in new.iter() {
230            if default_table.contains_key(key) {
231                continue;
232            }
233            if let Some(original_value) = original.get_mut(key) {
234                *original_value = new_value.clone();
235            } else {
236                original[key] = new_value.clone();
237            }
238        }
239    }
240
241    fn merge_sparse_items(original: &mut toml_edit::Item, new: &toml_edit::Item, default_value: &toml_edit::Item) {
242        match (original, new, default_value) {
243            (
244                toml_edit::Item::Table(orig_table),
245                toml_edit::Item::Table(new_table),
246                toml_edit::Item::Table(default_table),
247            ) => Self::merge_sparse_tables(orig_table, new_table, default_table),
248            (orig, new, _) => {
249                *orig = new.clone();
250            }
251        }
252    }
253
254    fn remove_known_default_item(original: &mut toml_edit::Item, default_value: &toml_edit::Item) -> bool {
255        match (original, default_value) {
256            (toml_edit::Item::Table(orig_table), toml_edit::Item::Table(default_table)) => {
257                let mut remove_keys = Vec::new();
258                for (key, default_child) in default_table.iter() {
259                    let Some(orig_child) = orig_table.get_mut(key) else {
260                        continue;
261                    };
262                    if Self::remove_known_default_item(orig_child, default_child) {
263                        remove_keys.push(key.to_string());
264                    }
265                }
266                for key in remove_keys {
267                    orig_table.remove(&key);
268                }
269                orig_table.is_empty()
270            }
271            _ => true,
272        }
273    }
274
275    /// Persist configuration to the manager's associated path or workspace
276    pub fn save_config(&mut self, config: &VTCodeConfig) -> Result<()> {
277        let (target, repository_controlled) = if let Some(path) = &self.config_path {
278            if self.write_global_config_to_canonical || self.is_global_config_path(path) {
279                (self.preferred_user_config_path().unwrap_or_else(|| path.clone()), false)
280            } else {
281                (path.clone(), !self.explicit_config_is_trusted)
282            }
283        } else if let Some(workspace_root) = &self.workspace_root {
284            (workspace_root.join(&self.config_file_name), !self.explicit_config_is_trusted)
285        } else {
286            let cwd = std::env::current_dir().context("Failed to resolve current directory")?;
287            (cwd.join(&self.config_file_name), !self.explicit_config_is_trusted)
288        };
289
290        if repository_controlled {
291            Self::save_repository_config_to_path(target, config)?;
292        } else {
293            Self::save_config_to_path(target, config)?;
294        }
295
296        #[cfg(not(test))]
297        if let Some(workspace) = &self.workspace_root {
298            Self::invalidate_workspace_cache(workspace);
299        }
300
301        self.sync_from_config(config)
302    }
303
304    fn is_global_config_path(&self, path: &Path) -> bool {
305        self.layer_stack.layers().iter().any(|layer| {
306            layer.is_enabled()
307                && matches!(layer.source, ConfigLayerSource::System { .. } | ConfigLayerSource::User { .. })
308                && match &layer.source {
309                    ConfigLayerSource::System { file } | ConfigLayerSource::User { file } => file == path,
310                    _ => false,
311                }
312        })
313    }
314
315    /// Sync internal config from a saved config
316    /// Call this after save_config to keep internal state in sync
317    fn sync_from_config(&mut self, config: &VTCodeConfig) -> Result<()> {
318        self.config = config.clone();
319        Ok(())
320    }
321}