Skip to content

Worktrunk is a CLI for Git worktree management, designed for parallel AI agent workflows

config: write the path the user named, and check every config write the same way (#4204)

Maximilian Roos2e1207771bcc
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 8cc1ac108..46e59fb32 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -10,14 +10,14 @@
- **Messages name the destination, and end with the command to run**: without shell integration, `wt merge` and `wt remove` printed `Cannot change directory — shell integration not installed` and no path; the warning now names the worktree, as `wt switch` already did. "Cannot determine default branch" had three wordings, and three recovery hints put their command first rather than last. ([#4163](https://github.com/max-sixty/worktrunk/pull/4163), [#4155](https://github.com/max-sixty/worktrunk/pull/4155), thanks @blrain3 for reporting)
+- **`wt config update --output <path>` writes the path it names**: a destination already holding a file is replaced, as `cp` and a shell redirect do, and so is the config being migrated, which used to be refused when the migration dropped `approved-commands`. Those approvals move to approvals.toml first, exactly as the in-place update moves them. ([#4153](https://github.com/max-sixty/worktrunk/pull/4153), [#4204](https://github.com/max-sixty/worktrunk/pull/4204))
+
- **`/wt-switch-create` no longer stalls at Claude Code's path-entry dialog**: Claude Code confirms every entry outside `.claude/worktrees/`, which is every Worktrunk worktree, so a background session waited for someone to attach. The plugin now approves entry into a worktree at its `worktree-path` location, and reads a bare name as the repo or the branch. ([#4158](https://github.com/max-sixty/worktrunk/pull/4158), [#4159](https://github.com/max-sixty/worktrunk/pull/4159))
### Fixed
- **Diff display config no longer changes what Worktrunk reads**: `color.ui = always` and `diff.external` reached the commit, squash, and summary prompts. Two corner cases could also hide a branch's changes from the integration check, so `wt remove` deleted the branch without `-D`: `diff.relative` set *and* the command run from a subdirectory the branch's changes sat entirely outside, or `submodule.<name>.ignore` set (git config or `.gitmodules`) *and* a submodule bump as the branch's only change. Every diff Worktrunk parses now runs plumbing, which ignores that configuration. ([#4146](https://github.com/max-sixty/worktrunk/pull/4146), [#4147](https://github.com/max-sixty/worktrunk/pull/4147))
-- **`wt config update --output <path>` asks before overwriting**: it replaced whatever was there, so `--output ~/.config/worktrunk/config.toml` from a repo with a deprecated project config wiped the user config and reported success. It now prompts, takes `--yes`, and refuses the config being migrated. (Breaking: `--output` naming the config being migrated used to succeed unless the migration dropped `approved-commands`.) ([#4153](https://github.com/max-sixty/worktrunk/pull/4153))
-
- **`wt merge` on a dirty worktree describes what it commits**: the generated message covered the branch's earlier commits and said nothing about the work the merge had just staged into the same commit. `wt step squash --dry-run` now previews what the run would commit, as `wt step commit --dry-run` does. ([#4178](https://github.com/max-sixty/worktrunk/pull/4178))
- **A config save no longer rewrites the rest of your config**: declining a prompt, or setting the commit-generation command, rewrote the whole file, dropping values written at their default and re-spelling hook pipelines and dropping their comments. It also reloaded that file over the in-memory config, so `wt step commit --config-set 'commit.stage="none"'` staged everything once it had asked about commit generation. ([#4160](https://github.com/max-sixty/worktrunk/pull/4160), [#4156](https://github.com/max-sixty/worktrunk/pull/4156), [#4151](https://github.com/max-sixty/worktrunk/pull/4151))
diff --git a/CLAUDE.md b/CLAUDE.md
index 08bfa357f..afa094d5c 100644
--- a/CLAUDE.md
+++ b/CLAUDE.md
@@ -64,6 +64,7 @@ Never risk data loss without explicit user consent. A failed command that preser
- **Favor the failing variant on races** — `git reset --keep` (fails if tracked files were modified) over `--hard`; `git checkout --merge` over `--force`. If no safer variant exists, document the risk inline.
- **Time-of-check vs time-of-use** — be conservative when there's a gap between the safety check and the operation. `wt merge` verifies clean before rebasing, but files could appear before cleanup — don't force-remove during cleanup.
- **Replace full files, never truncate them** — `fs::write` truncates before it writes, so a crash mid-write leaves the file empty. Every full-file rewrite worktrunk can't put back (shell wrappers, `config.toml`, `approvals.toml`, another tool's `settings.json`) goes through `utils::write_atomically`, which renames a sibling temp file over the target; the spec on that function covers symlinks, mode, and what a rename costs. When a user-owned file was observed missing, `utils::write_new_atomically` refuses to overwrite one that appears before persistence. Adding to an existing Bash, Zsh, or PowerShell rc file instead opens it in append mode, so a stale snapshot cannot replace concurrent edits; never truncate the file to recover from an append error. Don't grow the install path into a rebuild. Removal still rewrites those rc files whole (`uninstall_previewed_lines`), which is why the `write_atomically` spec still names them. Regenerable content (the cache, the `-vv` diagnostic report) keeps the plain write.
+- **A path the user named is written, not second-guessed** — `wt config update --output <path>` replaces whatever is there, the way `cp` and a shell redirect do, and pointed at the config being migrated it writes the migration there too. No-clobber belongs to the other case: a path worktrunk chose itself and observed absent (a shell rc file, `wt config create`), where a file appearing before the rename is one wt never read and a dangling symlink is a dotfile manager's link to keep. Deciding between the two at a call site is the smell — each write site is in one case or the other, so it calls one function unconditionally.
- **Shell-config concurrency has a deliberate boundary** — the append lock coordinates Worktrunk installers, and no-clobber creation turns the missing-file race into a fail-and-rerun outcome. An editor save racing rc-file uninstall can still be overwritten; accept this final check-to-rename window because sidecar locks, backups, retries, and extra pre-rename checks do not close it. Revisit after an observed incident or a simpler write design. Worktrunk-owned wrappers and completions use last-writer-wins semantics, as does the merge into another tool's `settings.json`.
These stop where git's own protections stop, and matching git is deliberate in each case. The named spec says why:
diff --git a/src/commands/config/create.rs b/src/commands/config/create.rs
index 436fe0ba9..cfb575c43 100644
--- a/src/commands/config/create.rs
+++ b/src/commands/config/create.rs
@@ -124,10 +124,23 @@ fn create_config_file(
std::fs::create_dir_all(parent).context("Failed to create config directory")?;
}
- // Write the example config with all values commented out
+ // Write the example config with all values commented out. The path was
+ // observed absent above, so a file that occupies it now is one wt never
+ // read, and is not replaced by an example. A dangling symlink is the case
+ // worth naming — `exists()` reads false through it, so a dotfile manager's
+ // link reaches this write every time; a file another process created in
+ // the window is a plain write failure.
let commented_config = comment_out_config(content);
- worktrunk::utils::write_atomically(&path, &commented_config)
- .context("Failed to write config file")?;
+ worktrunk::utils::write_new_atomically(&path, &commented_config).map_err(|e| {
+ let display_path = format_path_for_display(&path);
+ if e.kind() == std::io::ErrorKind::AlreadyExists && path.is_symlink() && !path.exists() {
+ anyhow::anyhow!(
+ "Failed to create {display_path}: path is a dangling symlink; restore its target or remove the link, then rerun"
+ )
+ } else {
+ anyhow::Error::new(e).context(format!("Failed to write {display_path}"))
+ }
+ })?;
// Success message
eprintln!(
diff --git a/src/commands/config/update.rs b/src/commands/config/update.rs
index 72bb39776..721ebfaae 100644
--- a/src/commands/config/update.rs
+++ b/src/commands/config/update.rs
@@ -6,7 +6,6 @@
//! migration to disk.
use std::fmt::Write as _;
-use std::io::IsTerminal;
use std::path::{Path, PathBuf};
use anyhow::{Context, bail};
@@ -22,7 +21,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 worktrunk::utils::write_atomically;
use crate::output::prompt::{PromptResponse, prompt_yes_no_preview};
@@ -70,7 +69,7 @@ pub fn handle_config_update(yes: bool, output: Option<PathBuf>) -> anyhow::Resul
}
if let Some(output) = output {
- write_migrated_output(&output, &candidates, yes)?;
+ write_migrated_output(&output, &candidates)?;
return Ok(());
}
@@ -120,27 +119,7 @@ pub fn handle_config_update(yes: bool, output: Option<PathBuf>) -> anyhow::Resul
}
for candidate in &candidates {
- // Preserve approved-commands before rewriting config (migrated content
- // drops them; approvals.toml becomes the authoritative source). Abort
- // the whole update if the copy fails — rewriting config.toml first
- // would silently lose the legacy approvals.
- if candidate
- .info
- .deprecations
- .iter()
- .any(|k| matches!(k, DeprecationKind::ApprovedCommands))
- && let Some(approvals_path) =
- copy_approved_commands_to_approvals_file(&candidate.config_path)?
- {
- let filename = approvals_path
- .file_name()
- .map(|n| n.to_string_lossy().into_owned())
- .unwrap_or_default();
- eprintln!(
- "{}",
- info_message(cformat!("Copied approved commands to <bold>{filename}</>"))
- );
- }
+ move_approvals_out_of(candidate)?;
write_atomically(&candidate.config_path, &candidate.migrated)
.with_context(|| format!("Failed to update {}", candidate.info.label()))?;
@@ -157,23 +136,16 @@ pub fn handle_config_update(yes: bool, output: Option<PathBuf>) -> anyhow::Resul
///
/// The two destinations differ in what they can carry, so they run as separate
/// 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 success line can name the config it came from.
+/// concatenates every candidate. A file takes exactly one migration, so the
+/// check below and 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<()> {
+/// The named path is written, replacing whatever is there, the way `cp` and a
+/// shell redirect do. Pointed at the config being migrated, that write drops
+/// the config's `approved-commands`, so they move to approvals.toml first,
+/// exactly as the in-place update moves them — otherwise the warning's
+/// "run `wt config update`" would name a command with nothing left to migrate.
+/// Any other destination leaves the config alone, so the warning stands.
+fn write_migrated_output(output: &Path, candidates: &[UpdateCandidate]) -> anyhow::Result<()> {
if output == Path::new("-") {
for candidate in candidates {
eprint!("{}", format_dropped_approvals_warning(candidate));
@@ -195,43 +167,16 @@ fn write_migrated_output(
let output = resolve_input_path(output);
let label = candidate.info.label().to_lowercase();
- if paths_match(&output, &candidate.config_path) {
- bail!(cformat!(
- "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);
- 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(());
- }
- }
+ if paths_match(&output, &candidate.config_path) {
+ move_approvals_out_of(candidate)?;
+ } else {
+ eprint!("{}", format_dropped_approvals_warning(candidate));
}
- let artifact = format_migrated_output(candidates);
- let written = if replace {
- write_atomically(&output, &artifact)
- } else {
- write_new_atomically(&output, &artifact)
- };
- written.with_context(|| format!("Failed to write output @ {display_path}"))?;
+ write_atomically(&output, &format_migrated_output(candidates))
+ .with_context(|| format!("Failed to write output @ {display_path}"))?;
eprintln!(
"{}",
success_message(format!("Wrote {label} migration @ {display_path}"))
@@ -239,6 +184,31 @@ fn write_migrated_output(
Ok(())
}
+/// Move a config's deprecated `approved-commands` into approvals.toml, before a
+/// migration that drops them is written over that config.
+///
+/// approvals.toml becomes the authoritative source, so this runs first and a
+/// failure aborts the write: rewriting the config first would lose them with
+/// nothing left to read them from. Both writes that land a migration on top of
+/// the config it came from reach this — the in-place update, and `--output`
+/// naming that same path.
+fn move_approvals_out_of(candidate: &UpdateCandidate) -> anyhow::Result<()> {
+ if drops_approved_commands(candidate)
+ && let Some(approvals_path) =
+ copy_approved_commands_to_approvals_file(&candidate.config_path)?
+ {
+ let filename = approvals_path
+ .file_name()
+ .map(|n| n.to_string_lossy().into_owned())
+ .unwrap_or_default();
+ eprintln!(
+ "{}",
+ info_message(cformat!("Copied approved commands to <bold>{filename}</>"))
+ );
+ }
+ Ok(())
+}
+
/// Format the migration artifact shared by file and stdout destinations.
fn format_migrated_output(candidates: &[UpdateCandidate]) -> String {
let mut artifact = String::new();
diff --git a/src/config/mod.rs b/src/config/mod.rs
index 8216be93f..9036392cf 100644
--- a/src/config/mod.rs
+++ b/src/config/mod.rs
@@ -185,10 +185,12 @@ pub fn is_user_project_override_key(key: &str) -> bool {
///
/// wt can't load such a file: every later command skips user config with a
/// warning, and the commands that need project config fail, until the user
-/// hand-edits it. Both writers of a config file the user owns check the
-/// content they are about to write: the `UserConfig` mutations and
-/// `wt config update`. Neither starts from invalid TOML, so this fires only when
-/// the edit itself broke the syntax, and the file on disk stays as it was.
+/// hand-edits it. `wt config update` runs this over the migration it computed,
+/// before either destination is written. A `UserConfig` mutation faces a
+/// stronger test of its own — that the file it is about to write loads back as
+/// the config the mutation asked for — so it needs no second, weaker one.
+/// Neither starts from invalid TOML, so this fires only when the migration
+/// itself broke the syntax, and the file on disk stays as it was.
pub fn ensure_config_parses(content: &str) -> Result<(), ConfigError> {
content.parse::<toml::Table>().map(|_| ()).map_err(|e| {
ConfigError(format!(
diff --git a/src/config/user/mutation.rs b/src/config/user/mutation.rs
index 969acaf63..f4c76fc90 100644
--- a/src/config/user/mutation.rs
+++ b/src/config/user/mutation.rs
@@ -72,7 +72,6 @@ impl UserConfig {
return Ok(());
};
let edited = file.edited(&edit, &changed)?;
- crate::config::ensure_config_parses(edited.content())?;
crate::utils::write_atomically(config_path, edited.content()).map_err(|e| {
ConfigError(format!(
"Failed to write config file {}: {}",
diff --git a/src/config/user/persistence.rs b/src/config/user/persistence.rs
index eb7e003c7..816bd0cbc 100644
--- a/src/config/user/persistence.rs
+++ b/src/config/user/persistence.rs
@@ -31,6 +31,16 @@ pub(super) struct ConfigEdit<'a> {
}
impl ConfigEdit<'_> {
+ /// The dotted key this edit writes, for naming it in an error.
+ fn key_path(&self) -> String {
+ self.tables
+ .iter()
+ .chain(std::iter::once(&self.key))
+ .copied()
+ .collect::<Vec<_>>()
+ .join(".")
+ }
+
/// Set the value in `doc`, leaving everything else as it is.
///
/// An existing value is replaced in place and keeps its decor — the spacing
@@ -118,14 +128,17 @@ impl ConfigFile {
/// The edit goes into the file as written when that loads as `expected`.
/// Otherwise a load-time migration touches the edit's path — a deprecated
/// `[commit-generation]` migrates to `[commit.generation]` only while that
- /// table is absent — and the edit goes into the migrated file, which loads
- /// as `expected` by construction: the migrations are idempotent and the
- /// edit lands after them. That file carries *every* load-path migration,
- /// not just the one on the edit's path, so it can also move an unrelated
- /// deprecated section and drop the keys its destination has no field for.
- /// A mutation is otherwise not what materializes migrations —
- /// `wt config update` is — so [`Edited::Migrated`] says so, and its caller
- /// tells the user.
+ /// table is absent — and the edit goes into the migrated file, which carries
+ /// *every* load-path migration, not just the one on the edit's path, so it
+ /// can also move an unrelated deprecated section and drop the keys its
+ /// destination has no field for. A mutation is otherwise not what
+ /// materializes migrations — `wt config update` is — so [`Edited::Migrated`]
+ /// says so, and its caller tells the user.
+ ///
+ /// Both candidates face the same test, [`loads_as`], and no content leaves
+ /// here untested: the migrated file is expected to pass by construction (the
+ /// migrations are idempotent and the edit lands after them), and an error
+ /// rather than a silent write is what says so.
pub(super) fn edited(
&self,
edit: &ConfigEdit,
@@ -133,13 +146,19 @@ impl ConfigFile {
) -> Result<Edited, ConfigError> {
let mut doc = self.doc.clone();
edit.apply(&mut doc)?;
- if load(&doc).is_ok_and(|config| &config == expected) {
+ if loads_as(&doc, expected) {
return Ok(Edited::AsWritten(doc.to_string()));
}
let mut doc = self.doc.clone();
let changes = migrate_doc(&mut doc);
edit.apply(&mut doc)?;
+ if !loads_as(&doc, expected) {
+ return Err(ConfigError(format!(
+ "Refusing to write a config file wt could not read back: {} would not load as written",
+ edit.key_path()
+ )));
+ }
Ok(Edited::Migrated {
content: doc.to_string(),
changes,
@@ -147,6 +166,12 @@ impl ConfigFile {
}
}
+/// Whether `doc` loads as `expected` — the one test a mutation's content has to
+/// pass before it is written.
+fn loads_as(doc: &DocumentMut, expected: &UserConfig) -> bool {
+ load(doc).is_ok_and(|config| &config == expected)
+}
+
/// A config file with an edit applied, and whether writing it took the load-path
/// migrations with it.
pub(super) enum Edited {
diff --git a/src/config/user/tests.rs b/src/config/user/tests.rs
index 3837ad8ff..f8b01562c 100644
--- a/src/config/user/tests.rs
+++ b/src/config/user/tests.rs
@@ -3083,9 +3083,10 @@ fn test_with_locked_mutation_propagates_write_error() {
let dir_for_closure = config_dir.clone();
let mut config = UserConfig::default();
let err = config
- .with_locked_mutation(&config_path, move |_config| {
+ .with_locked_mutation(&config_path, move |config| {
std::fs::set_permissions(&dir_for_closure, std::fs::Permissions::from_mode(0o555))
.unwrap();
+ config.skip_shell_integration_prompt = true;
Some(super::persistence::ConfigEdit {
tables: vec![],
key: "skip-shell-integration-prompt",
@@ -3101,6 +3102,35 @@ fn test_with_locked_mutation_propagates_write_error() {
assert_eq!(std::fs::read_to_string(&config_path).unwrap(), "# valid\n");
}
+/// A mutator sets a value and returns the edit that writes it, so the file
+/// loads back as the config the mutation asked for. One whose edit says
+/// something else is refused rather than written — the same test both candidate
+/// documents face, whether or not writing them takes the migrations along.
+#[test]
+fn test_with_locked_mutation_refuses_an_edit_that_does_not_load_back() {
+ let dir = tempfile::tempdir().unwrap();
+ let config_path = dir.path().join("config.toml");
+ std::fs::write(&config_path, "# valid\n").unwrap();
+
+ let mut config = UserConfig::default();
+ let err = config
+ .with_locked_mutation(&config_path, |_config| {
+ // The edit, without the matching change to the config beside it.
+ Some(super::persistence::ConfigEdit {
+ tables: vec![],
+ key: "skip-shell-integration-prompt",
+ value: true.into(),
+ })
+ })
+ .unwrap_err();
+ let msg = err.to_string();
+ assert!(
+ msg.contains("skip-shell-integration-prompt would not load as written"),
+ "the refusal should name the key, got: {msg}"
+ );
+ assert_eq!(std::fs::read_to_string(&config_path).unwrap(), "# valid\n");
+}
+
#[test]
fn test_pattern_project_key_applies_to_every_repo_on_a_host() {
let config = UserConfig::load_from_str(
diff --git a/tests/integration_tests/config_init.rs b/tests/integration_tests/config_init.rs
index 64b48d62d..a46d8ce1c 100644
--- a/tests/integration_tests/config_init.rs
+++ b/tests/integration_tests/config_init.rs
@@ -120,6 +120,78 @@ run = "echo hello"
});
}
+/// A dangling symlink occupies the path while `path.exists()` reads false, so
+/// the create reaches its write with the path looking absent. It must refuse
+/// rather than replace a dotfile manager's link with a regular file, and the
+/// error has to name what it found — "File exists" right after the existence
+/// check said otherwise explains nothing.
+#[cfg(unix)]
+#[rstest]
+fn test_config_create_project_refuses_a_dangling_symlink(repo: TestRepo) {
+ let config_dir = repo.root_path().join(".config");
+ fs::create_dir_all(&config_dir).unwrap();
+ let link = config_dir.join("wt.toml");
+ std::os::unix::fs::symlink(config_dir.join("synced/wt.toml"), &link).unwrap();
+
+ let output = repo
+ .wt_command()
+ .args(["config", "create", "--project"])
+ .output()
+ .unwrap();
+
+ assert_eq!(output.status.code(), Some(1));
+ let stderr = String::from_utf8_lossy(&output.stderr);
+ assert!(
+ stderr.contains("dangling symlink"),
+ "the error should name what occupies the path:\n{stderr}"
+ );
+ assert!(
+ link.is_symlink() && !link.exists(),
+ "the link should survive unreplaced"
+ );
+}
+
+/// A write that fails for any other reason names the path it was writing,
+/// rather than the bare I/O error.
+#[cfg(unix)]
+#[rstest]
+fn test_config_create_project_write_failure_names_the_path(repo: TestRepo) {
+ use std::fs::Permissions;
+ use std::os::unix::fs::PermissionsExt;
+
+ let config_dir = repo.root_path().join(".config");
+ fs::create_dir_all(&config_dir).unwrap();
+ // Read-only directory: the temp file the write stages beside the target
+ // can't be created.
+ fs::set_permissions(&config_dir, Permissions::from_mode(0o555)).unwrap();
+
+ // Skip when running as root — permissions don't restrict.
+ let probe = config_dir.join("__probe");
+ if fs::write(&probe, "").is_ok() {
+ let _ = fs::remove_file(&probe);
+ fs::set_permissions(&config_dir, Permissions::from_mode(0o755)).unwrap();
+ eprintln!("Skipping - running with elevated privileges");
+ return;
+ }
+
+ let output = repo
+ .wt_command()
+ .args(["config", "create", "--project"])
+ .output()
+ .unwrap();
+
+ // Restore permissions so TempDir cleanup succeeds even if assertions fail.
+ fs::set_permissions(&config_dir, Permissions::from_mode(0o755)).unwrap();
+
+ assert_eq!(output.status.code(), Some(1));
+ let stderr = String::from_utf8_lossy(&output.stderr);
+ assert!(
+ stderr.contains("Failed to write") && stderr.contains(".config/wt.toml"),
+ "the error should name the path being written:\n{stderr}"
+ );
+ assert!(!config_dir.join("wt.toml").exists());
+}
+
/// Running `wt config create --project` from inside a repo's `.git` directory
/// (not inside a worktree, not a bare repo) must fail with the generic
/// "no worktree found" error rather than the bare-repo-specific message.
diff --git a/tests/integration_tests/config_show.rs b/tests/integration_tests/config_show.rs
index 2a5b34498..7165aaf15 100644
--- a/tests/integration_tests/config_show.rs
+++ b/tests/integration_tests/config_show.rs
@@ -4209,75 +4209,70 @@ 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`.
+/// `--output` writes the path it was given, including the config being
+/// migrated. That write drops the config's `approved-commands`, so they move to
+/// approvals.toml first, exactly as the in-place update moves them — warning
+/// instead would point at a `wt config update` with nothing left to migrate.
#[rstest]
-fn test_config_update_output_rejects_source_path(repo: TestRepo) {
- let original = "worktree-path = \"../{{ main_worktree }}.{{ branch }}\"\n";
- fs::write(repo.test_config_path(), original).unwrap();
+fn test_config_update_output_writes_the_config_it_migrates(repo: TestRepo) {
+ fs::write(
+ repo.test_config_path(),
+ r#"worktree-path = "../{{ main_worktree }}.{{ branch }}"
+
+[projects."github.com/user/repo"]
+approved-commands = ["npm test"]
+"#,
+ )
+ .unwrap();
let output = repo
.wt_command()
- .args(["config", "update", "--yes", "--output"])
+ .args(["config", "update", "--output"])
.arg(repo.test_config_path())
.output()
.unwrap();
- assert_eq!(output.status.code(), Some(1));
- assert_eq!(
- fs::read_to_string(repo.test_config_path()).unwrap(),
- original
+ assert!(
+ output.status.success(),
+ "stderr:\n{}",
+ String::from_utf8_lossy(&output.stderr)
);
- let stderr = String::from_utf8_lossy(&output.stderr);
- let stderr = stderr.ansi_strip();
+ let written = fs::read_to_string(repo.test_config_path()).unwrap();
assert!(
- stderr.contains("Cannot overwrite user config") && stderr.contains("wt config update"),
- "stderr:\n{stderr}"
+ written.contains("{{ repo }}") && !written.contains("approved-commands"),
+ "the migration should land at the path it named:\n{written}"
+ );
+ let approvals = fs::read_to_string(repo.test_config_path().with_file_name("approvals.toml"))
+ .expect("approvals.toml should carry the commands the write removed");
+ assert!(
+ approvals.contains("npm test"),
+ "the approvals should survive the overwrite:\n{approvals}"
);
}
-/// 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 —
+/// An existing destination is replaced, the way `cp` and a shell redirect do —
/// 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_overwrites_existing_file_only_with_yes(repo: TestRepo) {
- let user_config = r#"worktree-path = "../{{ repo }}.{{ branch }}"
+fn test_config_update_output_replaces_an_existing_file(repo: TestRepo) {
+ fs::write(
+ repo.test_config_path(),
+ r#"worktree-path = "../{{ repo }}.{{ branch }}"
[aliases]
hi = "echo hi"
-"#;
- fs::write(repo.test_config_path(), user_config).unwrap();
+"#,
+ )
+ .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}"
- );
-
let overwritten = repo
.wt_command()
- .args(["config", "update", "--yes", "--output"])
+ .args(["config", "update", "--output"])
.arg(repo.test_config_path())
.output()
.unwrap();
diff --git a/tests/integration_tests/config_update_pty.rs b/tests/integration_tests/config_update_pty.rs
index bc241b698..e9cde58b2 100644
--- a/tests/integration_tests/config_update_pty.rs
+++ b/tests/integration_tests/config_update_pty.rs
@@ -161,59 +161,3 @@ 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.snap
deleted file mode 100644
index 4e8b11585..000000000
--- a/tests/snapshots/integration__integration_tests__config_update_pty__config_update_output_overwrite_accepted.snap
+++ /dev/null
@@ -1,6 +0,0 @@
----
-source: tests/integration_tests/config_update_pty.rs
-expression: "&accepted"
----
-❯ Overwrite migrated.toml with the user config migration? [y/N/?] y
-✓ Wrote user config migration @ migrated.toml
diff --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.snap
deleted file mode 100644
index 25b96da05..000000000
--- a/tests/snapshots/integration__integration_tests__config_update_pty__config_update_output_overwrite_declined.snap
+++ /dev/null
@@ -1,8 +0,0 @@
----
-source: tests/integration_tests/config_update_pty.rs
-expression: "&declined"
----
-▲ Output omits deprecated approved-commands; to migrate them to approvals.toml, run wt config update
-
-❯ Overwrite migrated.toml with the user config migration? [y/N/?] n
-○ Update cancelled