Worktrunk is a CLI for Git worktree management, designed for parallel AI agent workflows
fix(config): refuse to overwrite an existing file with `wt config update --output` (#4153)
Maximilian Roos89078f257d5e
diff --git a/.claude/skills/writing-user-outputs/SKILL.md b/.claude/skills/writing-user-outputs/SKILL.mdindex 1c11886ce..6c1515f44 100644--- a/.claude/skills/writing-user-outputs/SKILL.md+++ b/.claude/skills/writing-user-outputs/SKILL.md@@ -526,12 +526,13 @@ clearer:```**Description + command in single message:** For warnings/errors that include a-recovery command, join with semicolon. Use `<bold>` for commands in+recovery command, join with semicolon, and order the recovery "To X, run Y" as+hints do, so the command still ends the line. Use `<bold>` for commands inwarnings/errors (only hints use `<underline>`):```rust// Warning with inline recovery command (bold for commands)-warning_message("Failed to restore stash; run <bold>git stash pop {ref}</> to restore manually")+warning_message("Failed to restore stash; to restore manually, run <bold>git stash pop {ref}</>")warning_message("{tool} not authenticated; run <bold>{tool} auth login</>")// For longer suggestions, use separate hint message (underline for commands)diff --git a/docs/src/content/docs/config.md b/docs/src/content/docs/config.mdindex f5bde00c8..106cbe85d 100644--- a/docs/src/content/docs/config.md+++ b/docs/src/content/docs/config.md@@ -799,15 +799,6 @@ Updates deprecated settings in user and project config filesto their current equivalents, removes deprecated keys that have no equivalent,and reports each one. Shows a diff and asks for confirmation.-Migrations are computed in memory on demand; nothing is written outside this-command. Set `--output <path>` to write a migrated config to that destination-instead of applying it in place. Use `-` for stdout. When both user and project-config need migration, stdout emits a labeled inspection artifact and file-output fails rather than combining the configs.--`--output` omits deprecated `approved-commands` with a stderr warning; only an-in-place update migrates them to `approvals.toml`.-### ExamplesPreview and apply updates:@@ -820,12 +811,12 @@ Apply without confirmation:$ wt config update --yes```-Write the migration artifact to a file:+Write the migrated config to a file instead of updating in place:```console$ wt config update --output migrated.toml```-Write the migration artifact to stdout:+Print the migrated config:```console$ wt config update --output=-```diff --git a/plugins/worktrunk/skills/worktrunk/reference/config.md b/plugins/worktrunk/skills/worktrunk/reference/config.mdindex a4b31cc6f..8f7bf8c64 100644--- a/plugins/worktrunk/skills/worktrunk/reference/config.md+++ b/plugins/worktrunk/skills/worktrunk/reference/config.md@@ -791,15 +791,6 @@ Updates deprecated settings in user and project config filesto their current equivalents, removes deprecated keys that have no equivalent,and reports each one. Shows a diff and asks for confirmation.-Migrations are computed in memory on demand; nothing is written outside this-command. Set `--output <path>` to write a migrated config to that destination-instead of applying it in place. Use `-` for stdout. When both user and project-config need migration, stdout emits a labeled inspection artifact and file-output fails rather than combining the configs.--`--output` omits deprecated `approved-commands` with a stderr warning; only an-in-place update migrates them to `approvals.toml`.-### ExamplesPreview and apply updates:@@ -812,12 +803,12 @@ Apply without confirmation:$ wt config update --yes```-Write the migration artifact to a file:+Write the migrated config to a file instead of updating in place:```console$ wt config update --output migrated.toml```-Write the migration artifact to stdout:+Print the migrated config:```console$ wt config update --output=-```diff --git a/skills/worktrunk/reference/config.md b/skills/worktrunk/reference/config.mdindex a4b31cc6f..8f7bf8c64 100644--- a/skills/worktrunk/reference/config.md+++ b/skills/worktrunk/reference/config.md@@ -791,15 +791,6 @@ Updates deprecated settings in user and project config filesto their current equivalents, removes deprecated keys that have no equivalent,and reports each one. Shows a diff and asks for confirmation.-Migrations are computed in memory on demand; nothing is written outside this-command. Set `--output <path>` to write a migrated config to that destination-instead of applying it in place. Use `-` for stdout. When both user and project-config need migration, stdout emits a labeled inspection artifact and file-output fails rather than combining the configs.--`--output` omits deprecated `approved-commands` with a stderr warning; only an-in-place update migrates them to `approvals.toml`.-### ExamplesPreview and apply updates:@@ -812,12 +803,12 @@ Apply without confirmation:$ wt config update --yes```-Write the migration artifact to a file:+Write the migrated config to a file instead of updating in place:```console$ wt config update --output migrated.toml```-Write the migration artifact to stdout:+Print the migrated config:```console$ wt config update --output=-```diff --git a/src/cli/config.rs b/src/cli/config.rsindex 6a0d84b30..8607c5388 100644--- a/src/cli/config.rs+++ b/src/cli/config.rs@@ -677,15 +677,6 @@ This tests:to their current equivalents, removes deprecated keys that have no equivalent,and reports each one. Shows a diff and asks for confirmation.-Migrations are computed in memory on demand; nothing is written outside this-command. Set `--output <path>` to write a migrated config to that destination-instead of applying it in place. Use `-` for stdout. When both user and project-config need migration, stdout emits a labeled inspection artifact and file-output fails rather than combining the configs.--`--output` omits deprecated `approved-commands` with a stderr warning; only an-in-place update migrates them to `approvals.toml`.-## ExamplesPreview and apply updates:@@ -698,12 +689,12 @@ Apply without confirmation:$ wt config update --yes```-Write the migration artifact to a file:+Write the migrated config to a file instead of updating in place:```console$ wt config update --output migrated.toml```-Write the migration artifact to stdout:+Print the migrated config:```console$ wt config update --output=-```"#diff --git a/src/commands/config/show.rs b/src/commands/config/show.rsindex 788ca4035..29e34aae0 100644--- a/src/commands/config/show.rs+++ b/src/commands/config/show.rs@@ -968,8 +968,9 @@ fn render_project_config(out: &mut String, repo: Option<&Repository>) -> anyhow:return Ok(false);}- // Check for deprecations with emit_inline_warnings=false (silent mode)- // Only write migration file in main worktree, not linked worktrees.+ // Check for deprecations with emit_inline_warnings=false (silent mode).+ // They are actionable only from the main worktree, where `wt config update`+ // rewrites the file.// Deprecated patterns supersede the TOML dump below because their diff// covers the file.let is_main_worktree = !repo.current_worktree().is_linked().unwrap_or(true);diff --git a/src/commands/config/update.rs b/src/commands/config/update.rsindex de5ad0fdb..72bb39776 100644--- a/src/commands/config/update.rs+++ b/src/commands/config/update.rs@@ -2,10 +2,11 @@//!//! Computes user- and project-config migrations in memory. The default mode//! previews and applies them atomically; output mode writes one migration-//! artifact to the named destination instead. The previous `.new` file flow-//! was removed — nothing writes to disk outside this command.+//! artifact to the named destination instead. No other command writes a+//! migration to disk.use std::fmt::Write as _;+use std::io::IsTerminal;use std::path::{Path, PathBuf};use anyhow::{Context, bail};@@ -21,6 +22,7 @@ use worktrunk::styling::{eprint, eprintln, format_bash_with_gutter, hint_message, info_message, print, success_message,suggest_command_in_dir, warning_message,};+use worktrunk::utils::{write_atomically, write_new_atomically};use crate::output::prompt::{PromptResponse, prompt_yes_no_preview};@@ -68,7 +70,7 @@ pub fn handle_config_update(yes: bool, output: Option<PathBuf>) -> anyhow::Resul}if let Some(output) = output {- write_migrated_output(&output, &candidates)?;+ write_migrated_output(&output, &candidates, yes)?;return Ok(());}@@ -110,7 +112,7 @@ pub fn handle_config_update(yes: bool, output: Option<PathBuf>) -> anyhow::Resul})?;if current != candidate.original {bail!(cformat!(- "{} changed @ <bold>{}</> since the preview; re-run <bold>wt config update</> to migrate the current contents",+ "{} changed @ <bold>{}</> since the preview; to migrate the current contents, re-run <bold>wt config update</>",candidate.info.label(),format_path_for_display(&candidate.config_path)));@@ -140,7 +142,7 @@ pub fn handle_config_update(yes: bool, output: Option<PathBuf>) -> anyhow::Resul);}- worktrunk::utils::write_atomically(&candidate.config_path, &candidate.migrated)+ write_atomically(&candidate.config_path, &candidate.migrated).with_context(|| format!("Failed to update {}", candidate.info.label()))?;eprintln!("{}",@@ -157,8 +159,21 @@ pub fn handle_config_update(yes: bool, output: Option<PathBuf>) -> anyhow::Resul/// paths rather than one path testing `-` at each step. Stdout labels and/// concatenates every candidate and needs no confirmation — the artifact is/// right there. A file takes exactly one migration, so the checks below and-/// the confirmation can name the config it came from.-fn write_migrated_output(output: &Path, candidates: &[UpdateCandidate]) -> anyhow::Result<()> {+/// the success line can name the config it came from.+///+/// A file destination replaces nothing without consent. The config being+/// migrated is refused outright: rewriting it is the in-place update's job,+/// which previews the diff, re-reads the file after the prompt, and moves+/// `approved-commands` to approvals.toml. Any other existing file is replaced+/// only after a prompt, which `--yes` answers in advance; with no terminal to+/// prompt on, the command fails instead. A destination that was absent is+/// created without clobbering, so a file that appears before the write lands+/// survives it.+fn write_migrated_output(+ output: &Path,+ candidates: &[UpdateCandidate],+ yes: bool,+) -> anyhow::Result<()> {if output == Path::new("-") {for candidate in candidates {eprint!("{}", format_dropped_approvals_warning(candidate));@@ -174,34 +189,52 @@ fn write_migrated_output(output: &Path, candidates: &[UpdateCandidate]) -> anyholet [candidate] = candidates else {bail!(cformat!(- "Cannot write <bold>user config</> and <bold>project config</> migrations to one file; use <bold>--output=-</> to inspect both or run <bold>wt config update</> to apply them in place"+ "Cannot write <bold>user config</> and <bold>project config</> migrations to one file; to inspect both, use <bold>--output=-</>; to apply them in place, run <bold>wt config update</>"));};let output = resolve_input_path(output);- if drops_approved_commands(candidate) && paths_match(&output, &candidate.config_path) {+ let label = candidate.info.label().to_lowercase();+ if paths_match(&output, &candidate.config_path) {bail!(cformat!(- "Cannot overwrite <bold>{}</> with <bold>--output</>; run <bold>wt config update</> to apply the migration in place",- candidate.info.label().to_lowercase()+ "Cannot overwrite <bold>{label}</> with <bold>--output</>; to apply the migration in place, run <bold>wt config update</>"));}+ let display_path = format_path_for_display(&output);- eprint!("{}", format_dropped_approvals_warning(candidate));+ let approvals_warning = format_dropped_approvals_warning(candidate);+ eprint!("{approvals_warning}");++ let replace = output.exists();+ if replace && !yes {+ if !std::io::stdin().is_terminal() {+ bail!(cformat!(+ "{display_path} already exists; to overwrite it with the {label} migration, add <bold>--yes</>"+ ));+ }+ if !approvals_warning.is_empty() {+ eprintln!();+ }+ let prompt = format!("Overwrite {display_path} with the {label} migration?");+ match prompt_yes_no_preview(&prompt, || {})? {+ PromptResponse::Accepted => {}+ PromptResponse::Declined => {+ eprintln!("{}", info_message("Update cancelled"));+ return Ok(());+ }+ }+ }let artifact = format_migrated_output(candidates);- worktrunk::utils::write_atomically(&output, &artifact).with_context(|| {- format!(- "Failed to write output @ {}",- format_path_for_display(&output)- )- })?;+ let written = if replace {+ write_atomically(&output, &artifact)+ } else {+ write_new_atomically(&output, &artifact)+ };+ written.with_context(|| format!("Failed to write output @ {display_path}"))?;eprintln!("{}",- success_message(format!(- "Wrote {} migration @ {}",- candidate.info.label().to_lowercase(),- format_path_for_display(&output)- ))+ success_message(format!("Wrote {label} migration @ {display_path}")));Ok(())}@@ -236,7 +269,7 @@ fn format_dropped_approvals_warning(candidate: &UpdateCandidate) -> String {format!("{}\n",warning_message(cformat!(- "Output omits deprecated <bold>approved-commands</>; run <underline>wt config update</> to migrate them to approvals.toml"+ "Output omits deprecated <bold>approved-commands</>; to migrate them to approvals.toml, run <bold>wt config update</>")))}diff --git a/src/commands/relocate.rs b/src/commands/relocate.rsindex bda92500f..0643ff721 100644--- a/src/commands/relocate.rs+++ b/src/commands/relocate.rs@@ -170,7 +170,7 @@ pub fn gather_candidates(bail!("{}",cformat!(- "Cannot relocate worktree @ {} — its directory is gone; run <bold>wt step prune</> to clear the entry",+ "Cannot relocate worktree @ {} — its directory is gone; to clear the entry, run <bold>wt step prune</>",format_path_for_display(&path)));diff --git a/src/config/project.rs b/src/config/project.rsindex ad3fcb26a..2f6690362 100644--- a/src/config/project.rs+++ b/src/config/project.rs@@ -277,8 +277,8 @@ impl ProjectConfig {},};- // Check for deprecated template variables and create migration file if needed- // Only write migration file in main worktree, not linked worktrees+ // Check for deprecated patterns. They are actionable only from the main+ // worktree, where `wt config update` rewrites the file.// emit_inline_warnings=true: print per-kind warnings inline during config loadlet is_main_worktree = !repo.current_worktree().is_linked().unwrap_or(true);let repo_for_hints = if write_hints { Some(repo) } else { None };diff --git a/tests/integration_tests/config_show.rs b/tests/integration_tests/config_show.rsindex 14cce168f..a151605bc 100644--- a/tests/integration_tests/config_show.rs+++ b/tests/integration_tests/config_show.rs@@ -3962,7 +3962,6 @@ fn test_config_update_output_destinations_emit_same_config(repo: TestRepo) {assert!(stdout_output.stderr.is_empty());let destination = repo.root_path().join("migrated.toml");- fs::write(&destination, "stale\n").unwrap();let file_output = repo.wt_command().args(["config", "update", "--output=migrated.toml"])@@ -4210,19 +4209,17 @@ approved-commands = ["cargo test"]);}+/// `--output` never rewrites the config it migrates, even with `--yes`: that is+/// the in-place update's job, which previews the diff and migrates+/// `approved-commands`.#[rstest]fn test_config_update_output_rejects_source_path(repo: TestRepo) {- let original = r#"[list]-json-schema = 1--[projects."github.com/user/repo"]-approved-commands = ["npm test"]-"#;+ let original = "worktree-path = \"../{{ main_worktree }}.{{ branch }}\"\n";fs::write(repo.test_config_path(), original).unwrap();let output = repo.wt_command()- .args(["config", "update", "--output"])+ .args(["config", "update", "--yes", "--output"]).arg(repo.test_config_path()).output().unwrap();@@ -4232,7 +4229,6 @@ approved-commands = ["npm test"]fs::read_to_string(repo.test_config_path()).unwrap(),original);- assert!(!repo.test_approvals_path().exists());let stderr = String::from_utf8_lossy(&output.stderr);let stderr = stderr.ansi_strip();assert!(@@ -4241,24 +4237,59 @@ approved-commands = ["npm test"]);}+/// An existing destination is overwritten only with `--yes`. Without it, and with+/// no terminal to prompt on, the command fails and leaves the file as it was —+/// here the user config, which has nothing to migrate but sits at the path a+/// project-config migration was sent to.#[rstest]-fn test_config_update_output_can_replace_source_without_approvals(repo: TestRepo) {- fs::write(- repo.test_config_path(),- "worktree-path = \"../{{ main_worktree }}.{{ branch }}\"\n",- )- .unwrap();+fn test_config_update_output_overwrites_existing_file_only_with_yes(repo: TestRepo) {+ let user_config = r#"worktree-path = "../{{ repo }}.{{ branch }}"- let output = repo+[aliases]+hi = "echo hi"+"#;+ fs::write(repo.test_config_path(), user_config).unwrap();+ repo.write_project_config(+ r#"pre-start = "ln -sf {{ main_worktree }}/node_modules"+"#,+ );+ repo.commit("Add deprecated project config");++ let refused = repo.wt_command().args(["config", "update", "--output"]).arg(repo.test_config_path()).output().unwrap();+ assert_eq!(refused.status.code(), Some(1));+ assert_eq!(+ fs::read_to_string(repo.test_config_path()).unwrap(),+ user_config+ );+ let stderr = String::from_utf8_lossy(&refused.stderr);+ let stderr = stderr.ansi_strip();+ assert!(+ stderr.contains(+ "already exists; to overwrite it with the project config migration, add --yes"+ ),+ "stderr:\n{stderr}"+ );- assert!(output.status.success());- let updated = fs::read_to_string(repo.test_config_path()).unwrap();- assert!(updated.contains("{{ repo }}"), "config:\n{updated}");+ let overwritten = repo+ .wt_command()+ .args(["config", "update", "--yes", "--output"])+ .arg(repo.test_config_path())+ .output()+ .unwrap();+ assert!(+ overwritten.status.success(),+ "stderr:\n{}",+ String::from_utf8_lossy(&overwritten.stderr)+ );+ assert_eq!(+ fs::read_to_string(repo.test_config_path()).unwrap(),+ "pre-start = \"ln -sf {{ repo }}/node_modules\"\n"+ );}/// `wt config update` with no deprecated settings reports nothing to dodiff --git a/tests/integration_tests/config_update_pty.rs b/tests/integration_tests/config_update_pty.rsindex e9cde58b2..bc241b698 100644--- a/tests/integration_tests/config_update_pty.rs+++ b/tests/integration_tests/config_update_pty.rs@@ -161,3 +161,59 @@ fn test_config_update_rejects_config_removed_at_apply(repo: TestRepo) {"the removed config should not be recreated from the preview");}++/// Execute `wt config update --output=<destination>` in a PTY, answering the+/// overwrite prompt.+fn exec_config_update_output_in_pty(+ repo: &TestRepo,+ destination: &str,+ input: &str,+) -> (String, i32) {+ let output_arg = format!("--output={destination}");+ let cmd = build_pty_command(+ wt_bin().to_str().unwrap(),+ &["config", "update", &output_arg],+ repo.root_path(),+ &repo.test_env_vars(),+ None,+ );+ exec_cmd_in_pty_prompted(cmd, &[input], "[y/N")+}++/// An existing `--output` destination is overwritten only once the prompt is+/// accepted. The prompt starts flush when nothing precedes it; the approvals+/// warning is narration above it, so a blank line separates the two.+#[rstest]+fn test_config_update_output_overwrite_prompt(repo: TestRepo) {+ let migrated = "worktree-path = \"../{{ repo }}.{{ branch }}\"\n";+ let deprecated = "worktree-path = \"../{{ main_worktree }}.{{ branch }}\"\n";+ fs::write(+ repo.test_config_path(),+ format!(+ r#"{deprecated}+[projects."github.com/user/repo"]+approved-commands = ["npm test"]+"#+ ),+ )+ .unwrap();+ let destination = repo.root_path().join("migrated.toml");+ fs::write(&destination, "important user data\n").unwrap();++ let (declined, exit_code) = exec_config_update_output_in_pty(&repo, "migrated.toml", "n\n");+ assert_eq!(exit_code, 0);+ assert_eq!(+ fs::read_to_string(&destination).unwrap(),+ "important user data\n"+ );++ fs::write(repo.test_config_path(), deprecated).unwrap();+ let (accepted, exit_code) = exec_config_update_output_in_pty(&repo, "migrated.toml", "y\n");+ assert_eq!(exit_code, 0);+ assert_eq!(fs::read_to_string(&destination).unwrap(), migrated);++ config_update_pty_settings(&repo).bind(|| {+ assert_snapshot!("config_update_output_overwrite_declined", &declined);+ assert_snapshot!("config_update_output_overwrite_accepted", &accepted);+ });+}diff --git a/tests/snapshots/integration__integration_tests__config_update_pty__config_update_output_overwrite_accepted.snap b/tests/snapshots/integration__integration_tests__config_update_pty__config_update_output_overwrite_accepted.snapnew file mode 100644index 000000000..4e8b11585--- /dev/null+++ b/tests/snapshots/integration__integration_tests__config_update_pty__config_update_output_overwrite_accepted.snap@@ -0,0 +1,6 @@+---+source: tests/integration_tests/config_update_pty.rs+expression: "&accepted"+---+[36m❯[39m Overwrite migrated.toml with the user config migration? [1m[y/N/?][22m y+[32m✓[39m [32mWrote user config migration @ migrated.toml[39mdiff --git a/tests/snapshots/integration__integration_tests__config_update_pty__config_update_output_overwrite_declined.snap b/tests/snapshots/integration__integration_tests__config_update_pty__config_update_output_overwrite_declined.snapnew file mode 100644index 000000000..25b96da05--- /dev/null+++ b/tests/snapshots/integration__integration_tests__config_update_pty__config_update_output_overwrite_declined.snap@@ -0,0 +1,8 @@+---+source: tests/integration_tests/config_update_pty.rs+expression: "&declined"+---+[33m▲[39m [33mOutput omits deprecated [1mapproved-commands[22m; to migrate them to approvals.toml, run [1mwt config update[22m[39m++[36m❯[39m Overwrite migrated.toml with the user config migration? [1m[y/N/?][22m n+[2m○[22m Update cancelleddiff --git a/tests/snapshots/integration__integration_tests__help__help_config_update.snap b/tests/snapshots/integration__integration_tests__help__help_config_update.snapindex e99ec91f2..d7be57e3c 100644--- a/tests/snapshots/integration__integration_tests__help__help_config_update.snap+++ b/tests/snapshots/integration__integration_tests__help__help_config_update.snap@@ -74,15 +74,6 @@ Updates deprecated settings in user and project config filesto their current equivalents, removes deprecated keys that have no equivalent,and reports each one. Shows a diff and asks for confirmation.-Migrations are computed in memory on demand; nothing is written outside this-command. Set [2m--output <path>[0m to write a migrated config to that destination-instead of applying it in place. Use [2m-[0m for stdout. When both user and project-config need migration, stdout emits a labeled inspection artifact and file-output fails rather than combining the configs.--[2m--output[0m omits deprecated [2mapproved-commands[0m with a stderr warning; only an-in-place update migrates them to [2mapprovals.toml[0m.-[1m[32mExamples[0mPreview and apply updates:@@ -91,10 +82,10 @@ Preview and apply updates:Apply without confirmation:[107m [0m [2m[0m[2m[34mwt[0m[2m config update [0m[2m[36m--yes[0m-Write the migration artifact to a file:+Write the migrated config to a file instead of updating in place:[107m [0m [2m[0m[2m[34mwt[0m[2m config update [0m[2m[36m--output[0m[2m migrated.toml[0m-Write the migration artifact to stdout:+Print the migrated config:[107m [0m [2m[0m[2m[34mwt[0m[2m config update [0m[2m[36m--output=-[0m----- stderr -----