Worktrunk is a CLI for Git worktree management, designed for parallel AI agent workflows
feat: use hint system to deduplicate deprecated config migration files (#441)
Maximilian Roose1b7b948be6e
diff --git a/src/commands/list/collect.rs b/src/commands/list/collect.rsindex 8c282f86f..211806ed7 100644--- a/src/commands/list/collect.rs+++ b/src/commands/list/collect.rs@@ -744,10 +744,9 @@ pub fn collect(// Check if URL template is configured (for layout column allocation).// Template expansion is deferred to post-skeleton to minimize time-to-skeleton.- let url_template = repo- .worktree_root()+ let url_template = worktrunk::config::ProjectConfig::load(repo, true).ok()- .and_then(|root| worktrunk::config::ProjectConfig::load(root).ok().flatten())+ .flatten().and_then(|config| config.list).and_then(|list| list.url);// Initialize worktree items with identity fields and None for computed fieldsdiff --git a/src/commands/statusline.rs b/src/commands/statusline.rsindex bf0eca702..f5cf17063 100644--- a/src/commands/statusline.rs+++ b/src/commands/statusline.rs@@ -289,10 +289,9 @@ fn get_git_status_segments(let mut item = list::build_worktree_item(wt, is_home, true, false);// Load URL template from project config (if configured)- let url_template = repo- .worktree_root()+ let url_template = ProjectConfig::load(repo, true).ok()- .and_then(|root| ProjectConfig::load(root).ok().flatten())+ .flatten().and_then(|config| config.list).and_then(|list| list.url);diff --git a/src/completion.rs b/src/completion.rsindex 90280e558..7c268266b 100644--- a/src/completion.rs+++ b/src/completion.rs@@ -241,9 +241,9 @@ fn complete_hook_commands() -> Vec<CompletionCandidate> {}// Load project config and add project hook names+ // Pass write_hints=false to avoid side effects during completionlet repo = Repository::current();- if let Ok(repo_root) = repo.worktree_root()- && let Ok(Some(project_config)) = ProjectConfig::load(repo_root)+ if let Ok(Some(project_config)) = ProjectConfig::load(&repo, false)&& let Some(config) = project_config.hooks.get(hook_type){add_named_commands(&mut candidates, config);diff --git a/src/config/deprecation.rs b/src/config/deprecation.rsindex 139eac160..61661c0c0 100644--- a/src/config/deprecation.rs+++ b/src/config/deprecation.rs@@ -2,6 +2,14 @@//!//! Scans config file content for deprecated template variables and generates//! a migration file with replacements.+//!+//! Migration files are only written once per config file. The hint system tracks+//! whether a migration file has been written:+//! - Project config: uses `worktrunk.hints.deprecated-project-config` in git config+//! - User config: checks if the `.new` file already exists (no repo context)+//!+//! To regenerate a project config migration file, run `wt config state hints clear deprecated-project-config`.+//! To regenerate a user config migration file, delete the existing `.new` file.use crate::styling::{eprintln, hint_message, warning_message};use color_print::cformat;@@ -17,6 +25,9 @@ use std::sync::Mutex;/// Prevents repeated warnings when config is loaded multiple times.static WARNED_PATHS: Mutex<Option<HashSet<PathBuf>>> = Mutex::new(None);+/// Hint name for project config deprecation warnings+const HINT_DEPRECATED_PROJECT_CONFIG: &str = "deprecated-project-config";+/// Mapping from deprecated variable name to its replacementconst DEPRECATED_VARS: &[(&str, &str)] = &[("repo_root", "repo_path"),@@ -132,13 +143,17 @@ pub fn replace_deprecated_vars(content: &str) -> String {////// If deprecated variables are found and `warn_and_migrate` is true:/// 1. Emits a warning listing the deprecated variables-/// 2. Creates a `.new` file with replacements+/// 2. Creates a `.new` file with replacements (only if not already written)////// Set `warn_and_migrate` to false for project config on feature worktrees - the warning/// is only actionable from the main worktree where the migration file can be applied.////// The `label` is used in the warning message (e.g., "User config" or "Project config").///+/// `repo` should be provided for project config to use the hint system. For user config+/// (global, not repo-specific), pass `None` and the function will check if the `.new`+/// file already exists instead.+////// Warnings are deduplicated per path per process.////// Returns Ok(true) if deprecated variables were found, Ok(false) otherwise.@@ -147,6 +162,7 @@ pub fn check_and_migrate(content: &str,warn_and_migrate: bool,label: &str,+ repo: Option<&crate::git::Repository>,) -> anyhow::Result<bool> {let deprecated = find_deprecated_vars(content);if deprecated.is_empty() {@@ -169,6 +185,19 @@ pub fn check_and_migrate(warned.insert(canonical_path.clone());}+ // Build the .new path: "config.toml" -> "config.toml.new"+ let new_path = path.with_extension(format!(+ "{}.new",+ path.extension().unwrap_or_default().to_string_lossy()+ ));++ // Check if we should skip writing the migration file+ // - Always regenerate if .new file exists (user kept it, so overwrite with fresh version)+ // - For project config: skip if hint shown AND .new doesn't exist (user deleted it)+ // - For user config: always write (no persistent hint tracking without repo)+ let should_skip_write = !new_path.exists()+ && repo.is_some_and(|r| r.has_shown_hint(HINT_DEPRECATED_PROJECT_CONFIG));+// Build inline list of deprecated variables: "repo_root → repo_path, worktree → worktree_path"let var_list: Vec<String> = deprecated.iter()@@ -182,47 +211,58 @@ pub fn check_and_migrate();eprintln!("{}", warning_message(warning));- let new_content = replace_deprecated_vars(content);-- // Build the .new path: "config.toml" -> "config.toml.new"- let new_path = path.with_extension(format!(- "{}.new",- path.extension().unwrap_or_default().to_string_lossy()- ));-- // Attempt to write migration file, but don't fail config loading if it fails- match std::fs::write(&new_path, new_content) {- Ok(()) => {- // Show just the filename in the message, full paths in the command- let new_filename = new_path- .file_name()- .map(|n| n.to_string_lossy())- .unwrap_or_default();-- // Shell-escape paths for safe copy-paste- let new_path_str = new_path.to_string_lossy();- let path_str = path.to_string_lossy();- let new_path_escaped = escape(Cow::Borrowed(new_path_str.as_ref()));- let path_escaped = escape(Cow::Borrowed(path_str.as_ref()));- eprintln!(- "{}",- hint_message(cformat!(- "Wrote migrated {}; to apply: <bright-black>mv -- {} {}</>",- new_filename,- new_path_escaped,- path_escaped- ))- );- }- Err(e) => {- // Warn about write failure but don't block config loading- eprintln!(- "{}",- hint_message(cformat!(- "Could not write migration file: <bright-black>{}</>",- e- ))- );+ if should_skip_write {+ // User deleted the .new file but hint is set - they don't want the migration file+ // Show how to regenerate if they change their mind+ eprintln!(+ "{}",+ hint_message(cformat!(+ "to regenerate, rerun after <bright-black>wt config state hints clear {}</>",+ HINT_DEPRECATED_PROJECT_CONFIG+ ))+ );+ } else {+ // Write migration file+ let new_content = replace_deprecated_vars(content);++ match std::fs::write(&new_path, &new_content) {+ Ok(()) => {+ // Mark hint as shown for project config+ if let Some(repo) = repo {+ let _ = repo.mark_hint_shown(HINT_DEPRECATED_PROJECT_CONFIG);+ }++ // Show just the filename in the message, full paths in the command+ let new_filename = new_path+ .file_name()+ .map(|n| n.to_string_lossy())+ .unwrap_or_default();++ // Shell-escape paths for safe copy-paste+ let new_path_str = new_path.to_string_lossy();+ let path_str = path.to_string_lossy();+ let new_path_escaped = escape(Cow::Borrowed(new_path_str.as_ref()));+ let path_escaped = escape(Cow::Borrowed(path_str.as_ref()));+ eprintln!(+ "{}",+ hint_message(cformat!(+ "Wrote migrated {}; to apply: <bright-black>mv -- {} {}</>",+ new_filename,+ new_path_escaped,+ path_escaped+ ))+ );+ }+ Err(e) => {+ // Warn about write failure but don't block config loading+ eprintln!(+ "{}",+ hint_message(cformat!(+ "Could not write migration file: <bright-black>{}</>",+ e+ ))+ );+ }}}@@ -502,4 +542,16 @@ approved-commands = ["#);}++ #[test]+ fn test_check_and_migrate_write_failure() {+ // Test the write error path by using a non-existent directory+ let content = r#"post-create = "{{ repo_root }}/script.sh""#;+ let non_existent_path = std::path::Path::new("/nonexistent/dir/config.toml");++ // Should return Ok(true) even if write fails - the function logs error but doesn't fail+ let result = check_and_migrate(non_existent_path, content, true, "Test config", None);+ assert!(result.is_ok());+ assert!(result.unwrap());+ }}diff --git a/src/config/project.rs b/src/config/project.rsindex cb17f51d9..6d469a85e 100644--- a/src/config/project.rs+++ b/src/config/project.rs@@ -84,7 +84,16 @@ pub struct ProjectConfig {impl ProjectConfig {/// Load project configuration from .config/wt.toml in the repository root- pub fn load(repo_root: &std::path::Path) -> Result<Option<Self>, ConfigError> {+ ///+ /// Set `write_hints` to true for normal usage. Set to false during completion+ /// to avoid side effects (writing git config hints).+ pub fn load(+ repo: &crate::git::Repository,+ write_hints: bool,+ ) -> Result<Option<Self>, ConfigError> {+ let repo_root = repo+ .worktree_root()+ .map_err(|e| ConfigError::Message(format!("Failed to get worktree root: {}", e)))?;let config_path = repo_root.join(".config").join("wt.toml");if !config_path.exists() {@@ -99,11 +108,13 @@ impl ProjectConfig {// Only write migration file in main worktree (where .git is a directory)// Linked worktrees have .git as a file pointing to the main worktreelet is_main_worktree = repo_root.join(".git").is_dir();+ let repo_for_hints = if write_hints { Some(repo) } else { None };let _ = super::deprecation::check_and_migrate(&config_path,&contents,is_main_worktree,"Project config",+ repo_for_hints,);let config: ProjectConfig = toml::from_str(&contents)diff --git a/src/config/user.rs b/src/config/user.rsindex 61d57e3d7..e2de4bf25 100644--- a/src/config/user.rs+++ b/src/config/user.rs@@ -340,12 +340,14 @@ impl WorktrunkConfig {{// Check for deprecated template variables and create migration file if needed// User config always gets migration file (it's global, not worktree-specific)+ // Pass None for repo since user config is global and not tied to any repositoryif let Ok(content) = std::fs::read_to_string(&config_path) {let _ = super::deprecation::check_and_migrate(&config_path,&content,true,"User config",+ None,);}diff --git a/src/git/repository/mod.rs b/src/git/repository/mod.rsindex eb81d8396..665e51003 100644--- a/src/git/repository/mod.rs+++ b/src/git/repository/mod.rs@@ -1752,7 +1752,9 @@ impl Repository {.project_config.get_or_try_init(|| {match self.worktree_root() {- Ok(root) => ProjectConfig::load(root).context("Failed to load project config"),+ Ok(_) => {+ ProjectConfig::load(self, true).context("Failed to load project config")+ }Err(_) => Ok(None), // Not in a worktree, no project config}})diff --git a/tests/integration_tests/config_show.rs b/tests/integration_tests/config_show.rsindex cb07b1538..212c2a16e 100644--- a/tests/integration_tests/config_show.rs+++ b/tests/integration_tests/config_show.rs@@ -709,6 +709,334 @@ post-create = "ln -sf {{ repo_root }}/node_modules {{ worktree }}/node_modules");}+/// Test that deprecated variables migration file is only written once (hint-based deduplication)+///+/// When a migration file has already been written, subsequent commands should:+/// 1. Still show the deprecation warning+/// 2. NOT overwrite the migration file+/// 3. Show a hint about how to regenerate the migration file+#[rstest]+fn test_deprecated_template_variables_hint_deduplication(repo: TestRepo, temp_home: TempDir) {+ // Write project config with deprecated variables+ let project_config_dir = repo.root_path().join(".config");+ fs::create_dir_all(&project_config_dir).unwrap();+ let project_config_path = project_config_dir.join("wt.toml");+ fs::write(+ &project_config_path,+ r#"worktree-path = "../{{ main_worktree }}.{{ branch }}"+"#,+ )+ .unwrap();++ // First run - should create migration file and set hint+ {+ let mut cmd = repo.wt_command();+ cmd.arg("list").current_dir(repo.root_path());+ set_temp_home_env(&mut cmd, temp_home.path());+ let output = cmd.output().unwrap();+ assert!(+ output.status.success(),+ "First run should succeed: {:?}",+ String::from_utf8_lossy(&output.stderr)+ );+ let stderr = String::from_utf8_lossy(&output.stderr);+ assert!(+ stderr.contains("Wrote migrated"),+ "First run should write migration file, got: {stderr}"+ );+ }++ let migration_file = project_config_path.with_extension("toml.new");+ assert!(migration_file.exists(), "Migration file should exist");++ let original_content = fs::read_to_string(&migration_file).unwrap();++ // Second run - if .new exists, we always regenerate (overwrite)+ // This ensures users always have a fresh migration file+ {+ let mut cmd = repo.wt_command();+ cmd.arg("list").current_dir(repo.root_path());+ set_temp_home_env(&mut cmd, temp_home.path());+ let output = cmd.output().unwrap();+ let stderr = String::from_utf8_lossy(&output.stderr);+ assert!(+ output.status.success(),+ "Second run should succeed: {:?}",+ stderr+ );+ assert!(+ stderr.contains("Wrote migrated"),+ "Second run should regenerate migration file, got: {stderr}"+ );+ }++ // Content should be the same (same input produces same output)+ let current_content = fs::read_to_string(&migration_file).unwrap();+ assert_eq!(+ original_content, current_content,+ "Regenerated content should be the same"+ );+}++/// Test that if user deletes .new file but hint is set, we show "to regenerate, clear hint"+/// This tests the skip-write path for project config+#[rstest]+fn test_deprecated_project_config_deleted_new_file_shows_clear_hint(+ repo: TestRepo,+ temp_home: TempDir,+) {+ // Write project config with deprecated variables+ let project_config_dir = repo.root_path().join(".config");+ fs::create_dir_all(&project_config_dir).unwrap();+ let project_config_path = project_config_dir.join("wt.toml");+ fs::write(+ &project_config_path,+ r#"worktree-path = "../{{ main_worktree }}.{{ branch }}"+"#,+ )+ .unwrap();++ // First run - creates migration file and sets hint+ {+ let mut cmd = repo.wt_command();+ cmd.arg("list").current_dir(repo.root_path());+ set_temp_home_env(&mut cmd, temp_home.path());+ let output = cmd.output().unwrap();+ assert!(+ output.status.success(),+ "First run should succeed: {:?}",+ String::from_utf8_lossy(&output.stderr)+ );+ }++ let migration_file = project_config_path.with_extension("toml.new");+ assert!(migration_file.exists(), "Migration file should exist");++ // Delete the migration file (user doesn't want it)+ fs::remove_file(&migration_file).unwrap();++ // Second run - .new doesn't exist but hint is set → skip write, show clear hint+ 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);+ });++ // Migration file should NOT exist (we skipped writing)+ assert!(+ !migration_file.exists(),+ "Migration file should not be recreated when hint is set"+ );+}++/// Test that clearing the deprecation hint allows regenerating the migration file+#[rstest]+fn test_deprecated_template_variables_hint_clear_and_regenerate(+ repo: TestRepo,+ temp_home: TempDir,+) {+ // Write project config with deprecated variables+ let project_config_dir = repo.root_path().join(".config");+ fs::create_dir_all(&project_config_dir).unwrap();+ let project_config_path = project_config_dir.join("wt.toml");+ fs::write(+ &project_config_path,+ r#"worktree-path = "../{{ main_worktree }}.{{ branch }}"+"#,+ )+ .unwrap();++ // First run - creates migration file and sets hint+ {+ let mut cmd = repo.wt_command();+ cmd.arg("list").current_dir(repo.root_path());+ set_temp_home_env(&mut cmd, temp_home.path());+ let output = cmd.output().unwrap();+ assert!(+ output.status.success(),+ "First run should succeed: {:?}",+ String::from_utf8_lossy(&output.stderr)+ );+ }++ let migration_file = project_config_path.with_extension("toml.new");+ assert!(migration_file.exists(), "Migration file should exist");++ // Delete the migration file to simulate user having applied and removed it+ fs::remove_file(&migration_file).unwrap();++ // Clear the hint+ {+ let mut cmd = repo.wt_command();+ cmd.args([+ "config",+ "state",+ "hints",+ "clear",+ "deprecated-project-config",+ ])+ .current_dir(repo.root_path());+ set_temp_home_env(&mut cmd, temp_home.path());+ let output = cmd.output().unwrap();+ assert!(+ output.status.success(),+ "Hint clear should succeed: {:?}",+ String::from_utf8_lossy(&output.stderr)+ );+ }++ // Third run - should create migration file again+ {+ let mut cmd = repo.wt_command();+ cmd.arg("list").current_dir(repo.root_path());+ set_temp_home_env(&mut cmd, temp_home.path());+ let output = cmd.output().unwrap();+ assert!(+ output.status.success(),+ "Third run should succeed: {:?}",+ String::from_utf8_lossy(&output.stderr)+ );+ let stderr = String::from_utf8_lossy(&output.stderr);+ assert!(+ stderr.contains("Wrote migrated"),+ "After clearing hint, should write migration file again, got: {stderr}"+ );+ }++ // Migration file should exist again+ assert!(+ migration_file.exists(),+ "Migration file should be regenerated after clearing hint"+ );+}++/// Test that project config deprecation warnings are NOT shown from feature worktrees+///+/// Deprecation warnings should only appear in the main worktree where the migration+/// file can be applied. Running from a feature worktree should skip the warning entirely.+#[rstest]+fn test_deprecated_project_config_silent_in_feature_worktree(repo: TestRepo, temp_home: TempDir) {+ // Create a feature worktree first (before adding project config)+ {+ let mut cmd = repo.wt_command();+ cmd.args(["switch", "--create", "feature"])+ .current_dir(repo.root_path());+ set_temp_home_env(&mut cmd, temp_home.path());+ let output = cmd.output().unwrap();+ assert!(+ output.status.success(),+ "Creating feature worktree should succeed: {:?}",+ String::from_utf8_lossy(&output.stderr)+ );+ }++ // Get the feature worktree path+ let feature_path = repo.root_path().parent().unwrap().join(format!(+ "{}.feature",+ repo.root_path().file_name().unwrap().to_string_lossy()+ ));++ // Write project config with deprecated variables IN THE FEATURE WORKTREE+ // (project config is loaded from the current worktree root, not the main worktree)+ let feature_config_dir = feature_path.join(".config");+ fs::create_dir_all(&feature_config_dir).unwrap();+ fs::write(+ feature_config_dir.join("wt.toml"),+ r#"worktree-path = "../{{ main_worktree }}.{{ branch }}"+"#,+ )+ .unwrap();++ // Run wt list from the feature worktree - should NOT show deprecation warning+ // because warn_and_migrate is false for non-main worktrees+ {+ let mut cmd = repo.wt_command();+ cmd.arg("list").current_dir(&feature_path);+ set_temp_home_env(&mut cmd, temp_home.path());+ let output = cmd.output().unwrap();+ assert!(+ output.status.success(),+ "wt list from feature worktree should succeed: {:?}",+ String::from_utf8_lossy(&output.stderr)+ );+ let stderr = String::from_utf8_lossy(&output.stderr);+ assert!(+ !stderr.contains("deprecated template variables"),+ "Deprecation warning should NOT appear in feature worktree, got: {stderr}"+ );+ assert!(+ !stderr.contains("Wrote migrated"),+ "Migration file should NOT be written from feature worktree, got: {stderr}"+ );+ }+}++/// Test that user config deprecated variables hint shows "delete file" message on second run+///+/// User config has no repo context, so hint deduplication is based on file existence.+/// When the .new file already exists, subsequent runs should show a hint about deleting+/// the file to regenerate (not about clearing a git config hint).+#[rstest]+fn test_user_config_deprecated_template_variables_hint_deduplication(+ repo: TestRepo,+ temp_home: TempDir,+) {+ // Write user config with deprecated variables using the test config path+ // (WORKTRUNK_CONFIG_PATH is set by repo.wt_command(), not .config/worktrunk/config.toml)+ repo.write_test_config(+ r#"worktree-path = "../{{ main_worktree }}.{{ branch }}"+"#,+ );+ let user_config_path = repo.test_config_path().to_path_buf();++ // First run - should create migration file+ {+ let mut cmd = repo.wt_command();+ cmd.arg("list").current_dir(repo.root_path());+ set_temp_home_env(&mut cmd, temp_home.path());+ let output = cmd.output().unwrap();+ let stderr = String::from_utf8_lossy(&output.stderr);+ assert!(+ output.status.success(),+ "First run should succeed: {:?}",+ stderr+ );+ assert!(+ stderr.contains("Wrote migrated"),+ "First run should write migration file, got: {stderr}"+ );+ }++ let migration_file = user_config_path.with_extension("toml.new");+ assert!(migration_file.exists(), "Migration file should exist");++ // Second run - user config always regenerates (overwrites .new file)+ // Should still show "Wrote migrated" since we overwrite existing .new files+ {+ let mut cmd = repo.wt_command();+ cmd.arg("list").current_dir(repo.root_path());+ set_temp_home_env(&mut cmd, temp_home.path());+ let output = cmd.output().unwrap();+ let stderr = String::from_utf8_lossy(&output.stderr);+ assert!(+ output.status.success(),+ "Second run should succeed: {:?}",+ stderr+ );+ assert!(+ stderr.contains("Wrote migrated"),+ "Second run should regenerate migration file, got: {stderr}"+ );+ }++ // Verify migration file still exists+ assert!(migration_file.exists(), "Migration file should still exist");+}+/// Test `wt config show` with shell integration active (WORKTRUNK_DIRECTIVE_FILE set)#[rstest]fn test_config_show_shell_integration_active(mut repo: TestRepo, temp_home: TempDir) {diff --git a/tests/snapshots/integration__integration_tests__config_show__deprecated_project_config_deleted_new_file_shows_clear_hint.snap b/tests/snapshots/integration__integration_tests__config_show__deprecated_project_config_deleted_new_file_shows_clear_hint.snapnew file mode 100644index 000000000..a2a945bd8--- /dev/null+++ b/tests/snapshots/integration__integration_tests__config_show__deprecated_project_config_deleted_new_file_shows_clear_hint.snap@@ -0,0 +1,39 @@+---+source: tests/integration_tests/config_show.rs+info:+ program: wt+ args:+ - list+ env:+ APPDATA: "[TEST_CONFIG_HOME]"+ CLICOLOR_FORCE: "1"+ COLUMNS: "150"+ 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+ PATH: "[PATH]"+ RUST_LOG: warn+ SOURCE_DATE_EPOCH: "1735776000"+ TERM: alacritty+ USERPROFILE: "[TEST_HOME]"+ WORKTRUNK_CONFIG_PATH: "[TEST_CONFIG]"+ 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 [36m?[39m [2m^[22m . [2ma1e809f5[0m [2m1d[0m [2mInitial commit++[2m○[22m [2mShowing 1 worktree, 1 with changes++----- stderr -----+[33m▲[39m [33mProject config uses deprecated template variables: [2mmain_worktree[22m → [1mrepo[22m[39m+[2m↳[22m [2mto regenerate, rerun after [90mwt config state hints clear deprecated-project-config[39m[22m