Worktrunk is a CLI for Git worktree management, designed for parallel AI agent workflows
feat: Preserve TOML comments when saving config
Maximilian Roosb66aa5fc37c7
diff --git a/Cargo.lock b/Cargo.lockindex a6d31095a..f1f3232d5 100644--- a/Cargo.lock+++ b/Cargo.lock@@ -1561,7 +1561,7 @@ version = "3.4.0"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "219cb19e96be00ab2e37d6e299658a0cfa83e52429179969b0f0121b4ac46983"dependencies = [- "toml_edit",+ "toml_edit 0.23.7",][[package]]@@ -2277,12 +2277,18 @@ dependencies = ["indexmap","serde_core","serde_spanned",- "toml_datetime",+ "toml_datetime 0.7.3","toml_parser","toml_writer","winnow",]+[[package]]+name = "toml_datetime"+version = "0.6.11"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "22cddaf88f4fbc13c51aebbf5f8eceb5c7c5a9da2ac40a13519eb5b0a0e8f11c"+[[package]]name = "toml_datetime"version = "0.7.3"@@ -2292,6 +2298,18 @@ dependencies = ["serde_core",]+[[package]]+name = "toml_edit"+version = "0.22.27"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "41fe8c660ae4257887cf66394862d21dbca4a6ddd26f04a3560410406a2f819a"+dependencies = [+ "indexmap",+ "toml_datetime 0.6.11",+ "toml_write",+ "winnow",+]+[[package]]name = "toml_edit"version = "0.23.7"@@ -2299,7 +2317,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "6485ef6d0d9b5d0ec17244ff7eb05310113c3f316f2d14200d4de56b3cb98f8d"dependencies = ["indexmap",- "toml_datetime",+ "toml_datetime 0.7.3","toml_parser","winnow",]@@ -2313,6 +2331,12 @@ dependencies = ["winnow",]+[[package]]+name = "toml_write"+version = "0.1.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "5d99f8c9a7727884afe522e9bd5edbfc91a3312b36a77b5fb8926e4c31a41801"+[[package]]name = "toml_writer"version = "1.0.4"@@ -2894,6 +2918,7 @@ dependencies = ["tempfile","terminal_size","toml",+ "toml_edit 0.22.27","tree-sitter","tree-sitter-bash","tree-sitter-highlight",diff --git a/Cargo.toml b/Cargo.tomlindex ef6a81341..b6a22bdbc 100644--- a/Cargo.toml+++ b/Cargo.toml@@ -61,6 +61,7 @@ strum = { version = "0.27", features = ["derive"] }synoptic = "2"terminal_size = "0.4"toml = { version = "0.9", features = ["preserve_order"] }+toml_edit = "0.22"# All three crates must use the same version series to avoid native library conflicts# These are optional dependencies controlled by the "syntax-highlighting" feature.# To build without C compilation requirements, use: cargo install worktrunk --no-default-featuresdiff --git a/src/config/user.rs b/src/config/user.rsindex 09a343c0f..66d18e4c0 100644--- a/src/config/user.rs+++ b/src/config/user.rs@@ -459,6 +459,7 @@ impl WorktrunkConfig {/// Save the current configuration to a specific file path////// Use this in tests to save to a temporary location instead of the user's config.+ /// Preserves comments and formatting in the existing file when possible.pub fn save_to(&self, config_path: &std::path::Path) -> Result<(), ConfigError> {// Create parent directory if it doesn't existif let Some(parent) = config_path.parent() {@@ -467,8 +468,49 @@ impl WorktrunkConfig {})?;}- let toml_string = toml::to_string_pretty(self)- .map_err(|e| ConfigError::Message(format!("Failed to serialize config: {}", e)))?;+ // If file exists, use toml_edit to preserve comments and formatting+ let toml_string = if config_path.exists() {+ let existing_content = std::fs::read_to_string(config_path)+ .map_err(|e| ConfigError::Message(format!("Failed to read config file: {}", e)))?;++ let mut doc: toml_edit::DocumentMut = existing_content+ .parse()+ .map_err(|e| ConfigError::Message(format!("Failed to parse config file: {}", e)))?;++ // Only update the projects section - that's the only thing we modify programmatically+ // Ensure projects table exists+ if !doc.contains_key("projects") {+ doc["projects"] = toml_edit::Item::Table(toml_edit::Table::new());+ }++ if let Some(projects) = doc["projects"].as_table_mut() {+ // Remove stale projects+ let stale: Vec<_> = projects+ .iter()+ .filter(|(k, _)| !self.projects.contains_key(*k))+ .map(|(k, _)| k.to_string())+ .collect();+ for key in stale {+ projects.remove(&key);+ }++ // Add/update projects+ for (project_id, project_config) in &self.projects {+ if !projects.contains_key(project_id) {+ projects[project_id] = toml_edit::Item::Table(toml_edit::Table::new());+ }+ let commands: toml_edit::Array =+ project_config.approved_commands.iter().collect();+ projects[project_id]["approved-commands"] = toml_edit::value(commands);+ }+ }++ doc.to_string()+ } else {+ // No existing file, create from scratch+ toml::to_string_pretty(self)+ .map_err(|e| ConfigError::Message(format!("Failed to serialize config: {}", e)))?+ };std::fs::write(config_path, toml_string).map_err(|e| ConfigError::Message(format!("Failed to write config file: {}", e)))?;diff --git a/tests/integration_tests/approval_save.rs b/tests/integration_tests/approval_save.rsindex f57e3ca0d..f32567bfc 100644--- a/tests/integration_tests/approval_save.rs+++ b/tests/integration_tests/approval_save.rs@@ -143,10 +143,7 @@ fn test_multiple_project_approvals() {args = [][projects."github.com/user1/repo1"]- approved-commands = [- "npm install",- "npm test",- ]+ approved-commands = ["npm install", "npm test"][projects."github.com/user2/repo2"]approved-commands = ["cargo build"]@@ -270,6 +267,68 @@ fn test_force_flag_saves_to_new_config_file() {"#);}+/// Test that saving config preserves TOML comments+///+/// When a user has a config file with comments and we save an approval,+/// all their comments should be preserved. This test verifies the behavior.+#[test]+fn test_saving_approval_preserves_toml_comments() {+ let temp_dir = TempDir::new().unwrap();+ let config_path = temp_dir.path().join("config.toml");++ // Create a config file with comments+ let initial_content = r#"# User preferences for worktrunk+# These comments should be preserved after saving++worktree-path = "../{{ main_worktree }}.{{ branch }}"++# LLM commit generation settings+[commit-generation]+command = "llm" # inline comment should also be preserved+args = ["-s"]++# Per-project settings below+"#;+ fs::write(&config_path, initial_content).unwrap();++ // Load the config manually by deserializing from TOML+ // (bypasses WorktrunkConfig::load() which requires WORKTRUNK_CONFIG_PATH)+ let toml_str = fs::read_to_string(&config_path).unwrap();+ let mut config: WorktrunkConfig = toml::from_str(&toml_str).unwrap();++ // Add an approval and save back to the same file+ config+ .approve_command_to(+ "github.com/test/repo".to_string(),+ "npm install".to_string(),+ &config_path,+ )+ .unwrap();++ // Read back the saved config+ let saved_content = fs::read_to_string(&config_path).unwrap();++ // Verify comments are preserved+ assert!(+ saved_content.contains("# User preferences for worktrunk"),+ "Top-level comment was lost. Saved content:\n{saved_content}"+ );+ assert!(+ saved_content.contains("# LLM commit generation settings"),+ "Section comment was lost. Saved content:\n{saved_content}"+ );+ assert!(+ saved_content.contains("# inline comment should also be preserved"),+ "Inline comment was lost. Saved content:\n{saved_content}"+ );++ // Verify the approval was also saved+ assert!(+ saved_content.contains("npm install"),+ "Approval was not saved. Saved content:\n{saved_content}"+ );+}+/// Test that permission errors when saving config are handled gracefully////// This tests the lower-level `approve_command_to()` method fails when permissions