Worktrunk is a CLI for Git worktree management, designed for parallel AI agent workflows
fix: copy approved-commands to approvals.toml during migration (#1079)
Maximilian Roos968f49b5837d
diff --git a/src/config/approvals.rs b/src/config/approvals.rsindex 8449d3753..87cd03a38 100644--- a/src/config/approvals.rs+++ b/src/config/approvals.rs@@ -264,7 +264,7 @@ impl Approvals {}/// Extract approved-commands from a specific config file.- fn load_from_config_file(config_path: &Path) -> Result<Self, ConfigError> {+ pub(crate) fn load_from_config_file(config_path: &Path) -> Result<Self, ConfigError> {let content = std::fs::read_to_string(config_path).map_err(|e| {ConfigError::Message(format!("Failed to read config file {}: {}",diff --git a/src/config/deprecation.rs b/src/config/deprecation.rsindex 566e4efb4..343ee0b3f 100644--- a/src/config/deprecation.rs+++ b/src/config/deprecation.rs@@ -462,6 +462,27 @@ pub fn remove_approved_commands_from_config(content: &str) -> String {}}+/// Copy approved-commands from config.toml to approvals.toml.+///+/// Called during migration to ensure approved-commands are preserved before+/// the migration file removes them from config.toml. Without this, applying+/// `mv config.toml.new config.toml` would lose approval data.+///+/// Returns `Some(path)` if approvals.toml was created, `None` if it already+/// existed or there was nothing to copy.+fn copy_approved_commands_to_approvals_file(config_path: &Path) -> Option<PathBuf> {+ let approvals_path = config_path.with_file_name("approvals.toml");+ if approvals_path.exists() {+ return None; // Already authoritative, don't overwrite+ }++ let approvals = super::approvals::Approvals::load_from_config_file(config_path).ok()?;+ approvals.projects().next()?; // Nothing to copy if empty++ approvals.save_to(&approvals_path).ok()?;+ Some(approvals_path)+}+/// Merge args array into command string////// Converts: command = "llm", args = ["-m", "haiku"]@@ -529,6 +550,8 @@ pub struct DeprecationInfo {pub label: String,/// True if in a linked worktree (migration file written to main worktree only)pub in_linked_worktree: bool,+ /// Path to approvals.toml if approved-commands were copied there during migration+ pub approvals_copied_to: Option<PathBuf>,}impl DeprecationInfo {@@ -608,6 +631,7 @@ pub fn check_and_migrate(deprecations,label: label.to_string(),in_linked_worktree: !warn_and_migrate,+ approvals_copied_to: None,};// Skip warning entirely if not in main worktree (for project config)@@ -629,10 +653,30 @@ pub fn check_and_migrate(guard.insert(canonical_path.clone());}+ // Copy approved-commands to approvals.toml before generating the migration+ // file that removes them from config.toml. Without this, applying the+ // migration (`mv config.toml.new config.toml`) would lose approval data.+ if info.deprecations.approved_commands {+ info.approvals_copied_to = copy_approved_commands_to_approvals_file(path);+ }+// For brief warnings (non-config-show commands), just show a pointerif show_brief_warning {eprintln!("{}", format_brief_warning(label));+ if let Some(approvals_path) = &info.approvals_copied_to {+ let approvals_filename = approvals_path+ .file_name()+ .map(|n| n.to_string_lossy())+ .unwrap_or_default();+ eprintln!(+ "{}",+ hint_message(cformat!(+ "Copied approved commands to <bright-black>{approvals_filename}</>"+ ))+ );+ }+// Still write migration file if needed (first time only)if !should_skip_write&& let Some(new_path) = write_migration_file(path, content, &info.deprecations, repo)@@ -814,6 +858,19 @@ pub fn format_deprecation_details(info: &DeprecationInfo) -> String {info.label)));+ if let Some(approvals_path) = &info.approvals_copied_to {+ let approvals_filename = approvals_path+ .file_name()+ .map(|n| n.to_string_lossy())+ .unwrap_or_default();+ let _ = writeln!(+ out,+ "{}",+ hint_message(cformat!(+ "Copied approved commands to <bright-black>{approvals_filename}</>"+ ))+ );+ }}// Migration hint with apply command@@ -2009,6 +2066,7 @@ approved-commands = ["npm install"]},label: "User config".to_string(),in_linked_worktree: false,+ approvals_copied_to: None,};let output = format_deprecation_details(&info);assert!(@@ -2023,6 +2081,28 @@ approved-commands = ["npm install"]);}+ #[test]+ fn test_format_deprecation_details_approvals_copied() {+ let info = DeprecationInfo {+ config_path: std::path::PathBuf::from("/tmp/test-config.toml"),+ migration_path: None,+ deprecations: Deprecations {+ vars: vec![],+ commit_gen: CommitGenerationDeprecations::default(),+ approved_commands: true,+ },+ label: "User config".to_string(),+ in_linked_worktree: false,+ approvals_copied_to: Some(std::path::PathBuf::from("/tmp/approvals.toml")),+ };+ let output = format_deprecation_details(&info);+ assert!(+ output.contains("Copied approved commands"),+ "Should mention approvals were copied: {}",+ output+ );+ }+#[test]fn test_write_migration_file_with_approved_commands() {let temp_dir = tempfile::TempDir::new().unwrap();@@ -2049,6 +2129,80 @@ approved-commands = ["npm install"]assert!(!migrated.contains("approved-commands"));}+ #[test]+ fn test_copy_approved_commands_creates_approvals_file() {+ let temp_dir = tempfile::TempDir::new().unwrap();+ let config_path = temp_dir.path().join("config.toml");+ let content = r#"+[projects."github.com/user/repo"]+approved-commands = ["npm install", "npm test"]++[projects."github.com/other/repo"]+approved-commands = ["cargo build"]+"#;+ std::fs::write(&config_path, content).unwrap();++ let result = copy_approved_commands_to_approvals_file(&config_path);+ assert!(result.is_some(), "Should create approvals.toml");++ let approvals_path = result.unwrap();+ assert_eq!(approvals_path, temp_dir.path().join("approvals.toml"));++ let approvals_content = std::fs::read_to_string(&approvals_path).unwrap();+ assert!(+ approvals_content.contains("npm install"),+ "Should contain npm install: {}",+ approvals_content+ );+ assert!(+ approvals_content.contains("npm test"),+ "Should contain npm test: {}",+ approvals_content+ );+ assert!(+ approvals_content.contains("cargo build"),+ "Should contain cargo build: {}",+ approvals_content+ );+ }++ #[test]+ fn test_copy_approved_commands_skips_when_approvals_exists() {+ let temp_dir = tempfile::TempDir::new().unwrap();+ let config_path = temp_dir.path().join("config.toml");+ let approvals_path = temp_dir.path().join("approvals.toml");+ let content = r#"+[projects."github.com/user/repo"]+approved-commands = ["npm install"]+"#;+ std::fs::write(&config_path, content).unwrap();+ std::fs::write(&approvals_path, "# existing approvals\n").unwrap();++ let result = copy_approved_commands_to_approvals_file(&config_path);+ assert!(result.is_none(), "Should skip when approvals.toml exists");++ // Verify existing file was not overwritten+ let existing = std::fs::read_to_string(&approvals_path).unwrap();+ assert_eq!(existing, "# existing approvals\n");+ }++ #[test]+ fn test_copy_approved_commands_skips_when_empty() {+ let temp_dir = tempfile::TempDir::new().unwrap();+ let config_path = temp_dir.path().join("config.toml");+ let content = r#"+[projects."github.com/user/repo"]+worktree-path = ".worktrees/{{ branch | sanitize }}"+"#;+ std::fs::write(&config_path, content).unwrap();++ let result = copy_approved_commands_to_approvals_file(&config_path);+ assert!(+ result.is_none(),+ "Should skip when no approved-commands exist"+ );+ }+#[test]fn test_set_implicit_suppresses_parent_header() {// Verifies that set_implicit(true) prevents an empty parent table fromdiff --git a/tests/integration_tests/config_show.rs b/tests/integration_tests/config_show.rsindex 6c75fa920..524f44de6 100644--- a/tests/integration_tests/config_show.rs+++ b/tests/integration_tests/config_show.rs@@ -2383,6 +2383,65 @@ command = "llm -m gpt-4");}+/// Test that deprecated approved-commands in [projects] sections are copied to approvals.toml+#[rstest]+fn test_deprecated_approved_commands_copies_to_approvals_file(repo: TestRepo, temp_home: TempDir) {+ // Write user config with approved-commands in [projects] section+ let config_path = repo.test_config_path();+ fs::write(+ config_path,+ r#"worktree-path = "../{{ repo }}.{{ branch }}"++[projects."github.com/user/repo"]+approved-commands = ["npm install", "npm test"]+"#,+ )+ .unwrap();++ // Use `wt list` which loads config and triggers deprecation check+ let settings = setup_snapshot_settings_with_home(&repo, &temp_home);+ settings.bind(|| {+ let mut cmd = wt_command();+ repo.configure_wt_cmd(&mut cmd);+ cmd.arg("list").current_dir(repo.root_path());+ set_temp_home_env(&mut cmd, temp_home.path());++ assert_cmd_snapshot!(cmd);+ });++ // Verify migration file removes approved-commands+ let migration_file = config_path.with_extension("toml.new");+ assert!(+ migration_file.exists(),+ "Migration file should be created at {:?}",+ migration_file+ );+ let migrated_content = fs::read_to_string(&migration_file).unwrap();+ assert!(+ !migrated_content.contains("approved-commands"),+ "Migration should remove approved-commands"+ );++ // Verify approvals were copied to approvals.toml (sibling of config file)+ let approvals_file = config_path.with_file_name("approvals.toml");+ assert!(+ approvals_file.exists(),+ "Approvals should be copied to {:?}",+ approvals_file+ );+ let approvals_content = fs::read_to_string(&approvals_file).unwrap();+ assert!(+ approvals_content.contains("npm install"),+ "Approvals file should contain npm install: {}",+ approvals_content+ );+ assert!(+ approvals_content.contains("npm test"),+ "Approvals file should contain npm test: {}",+ approvals_content+ );+}+/// Test that explicitly specified --config path that doesn't exist shows a warning#[rstest]fn test_explicit_config_path_not_found_shows_warning(repo: TestRepo) {diff --git a/tests/snapshots/integration__integration_tests__config_show__deprecated_approved_commands_copies_to_approvals_file.snap b/tests/snapshots/integration__integration_tests__config_show__deprecated_approved_commands_copies_to_approvals_file.snapnew file mode 100644index 000000000..60533289e--- /dev/null+++ b/tests/snapshots/integration__integration_tests__config_show__deprecated_approved_commands_copies_to_approvals_file.snap@@ -0,0 +1,53 @@+---+source: tests/integration_tests/config_show.rs+info:+ program: wt+ args:+ - list+ env:+ APPDATA: "[TEST_CONFIG_HOME]"+ CLICOLOR_FORCE: "1"+ COLUMNS: "500"+ GIT_AUTHOR_DATE: "2025-01-01T00:00:00Z"+ GIT_COMMITTER_DATE: "2025-01-01T00:00:00Z"+ GIT_CONFIG_GLOBAL: "[TEST_GIT_CONFIG]"+ GIT_CONFIG_SYSTEM: /dev/null+ GIT_EDITOR: ""+ GIT_TERMINAL_PROMPT: "0"+ HOME: "[TEST_HOME]"+ LANG: C+ LC_ALL: C+ MOCK_CONFIG_DIR: "[MOCK_CONFIG_DIR]"+ PATH: "[PATH]"+ PSModulePath: ""+ RUST_LOG: warn+ SHELL: ""+ TERM: alacritty+ USERPROFILE: "[TEST_HOME]"+ WORKTRUNK_APPROVALS_PATH: "[TEST_APPROVALS]"+ WORKTRUNK_CONFIG_PATH: "[TEST_CONFIG]"+ WORKTRUNK_SYSTEM_CONFIG_PATH: "[TEST_SYSTEM_CONFIG]"+ WORKTRUNK_TEST_CLAUDE_INSTALLED: "0"+ WORKTRUNK_TEST_DELAYED_STREAM_MS: "-1"+ WORKTRUNK_TEST_EPOCH: "1735776000"+ WORKTRUNK_TEST_NUSHELL_ENV: "0"+ WORKTRUNK_TEST_POWERSHELL_ENV: "0"+ WORKTRUNK_TEST_SKIP_URL_HEALTH_CHECK: "1"+ XDG_CONFIG_HOME: "[TEST_CONFIG_HOME]"+---+success: true+exit_code: 0+----- stdout -----+ [1mBranch[0m [1mStatus[0m [1mHEAD±[0m [1mmain↕[0m [1mPath[0m [1mRemote⇅[0m [1mCommit[0m [1mAge[0m [1mMessage+@ main [2m^[22m[2m|[22m . [2m|[0m [2m05a4a45d[0m [2m16h[0m [2mInitial commit++ feature-a [2m↑[22m [32m↑1[0m ../repo.feature-a [2m1b87d473[0m [2m16h[0m [2mAdd feature-a file++ feature-b [2m↑[22m [32m↑1[0m ../repo.feature-b [2mf62940fc[0m [2m16h[0m [2mAdd feature-b file++ feature-c [2m↑[22m [32m↑1[0m ../repo.feature-c [2m345c7c93[0m [2m16h[0m [2mAdd feature-c file++[2m○[22m [2mShowing 4 worktrees, 3 ahead++----- stderr -----+[33m▲[39m [33mUser config has deprecated settings. To see details, run [1mwt config show[22m[39m+[2m↳[22m [2mCopied approved commands to [90mapprovals.toml[39m[22m+[2m○[22m Wrote migrated [1mtest-config.toml.new[22m. To apply:+[107m [0m [2m[0m[2m[34mmv[0m[2m [0m[2m[36m--[0m[2m [TEST_CONFIG_NEW] [TEST_CONFIG]