Skip to content

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

refactor(hooks): drop primary-worktree config fallback; surface parse errors (#2714)

Maximilian Roos1dbbe84b8dac
diff --git a/src/commands/hooks.rs b/src/commands/hooks.rs
index 39b1eba0b..71f97c1f5 100644
--- a/src/commands/hooks.rs
+++ b/src/commands/hooks.rs
@@ -11,14 +11,17 @@
//! `Repository::project_config_path` keys that off whichever worktree
//! `ctx.repo` was rooted at. So the rule reduces to **`ctx.repo` is rooted at
//! the worktree the hook acts on** (not, in general, where `wt` was invoked),
-//! and the construction sites enforce it:
+//! and the construction sites enforce it. Each worktree's `.config/wt.toml`
+//! stands alone — there is no fallback to the primary worktree's config when
+//! the acting worktree has none, and a present-but-malformed config aborts the
+//! operation rather than silently using a different one.
//!
//! | Hook | `ctx.repo` rooted at → config from | Set in |
//! |---|---|---|
-//! | `pre-remove` | the worktree being removed (still on disk at hook time); if it has no `.config/wt.toml`, the post-removal working directory (`RemoveResult.main_path`) — the **primary worktree** for `wt remove` / `wt step prune`, the merge destination for `wt merge` | `output::handlers::execute_pre_remove_hooks_if_needed`; the three approval call sites (`main.rs`'s `approve_remove` for `wt remove`, `merge::collect_merge_commands` for `wt merge`, `step::prune::approve_prune_hooks` for `wt step prune`) all delegate to [`super::project_config::collect_remove_hook_commands`], which mirrors the executor's fallback |
+//! | `pre-remove` | the worktree being removed (still on disk at hook time) | `output::handlers::execute_pre_remove_hooks_if_needed`; the three approval call sites (`main.rs`'s `approve_remove` for `wt remove`, `merge::collect_merge_commands` for `wt merge`, `step::prune::approve_prune_hooks` for `wt step prune`) all delegate to [`super::project_config::collect_remove_hook_commands`] |
//! | `post-merge`, `post-remove`, `post-switch` after a removal | the destination — for `wt merge`, the target branch's worktree (else the primary); for `wt remove` / `wt step prune`, the primary worktree — the removed/feature worktree is gone by then | `worktree::finish::finish_after_merge`, `output::handlers::spawn_hooks_after_remove` (approval of `post-remove`/`post-switch` for the three remove flows runs through [`super::project_config::collect_remove_hook_commands`]; `post-merge` is added by `merge::collect_merge_commands` directly) |
//! | `pre-commit` / `post-commit` | the worktree being committed — the cwd worktree, or `<b>`'s worktree for `wt step commit --branch <b>` | `commands::commit`, `step::commit` (via `CommandEnv::for_branch`) |
-//! | `wt switch`'s `pre-start` / `post-start` / `post-switch` | the new (`--create`) or destination (`wt switch <existing>`) worktree, where these run; if it has no `.config/wt.toml`, the primary worktree's. For `--create` the target doesn't exist yet at approval time, so the approval prompt and template pre-flight read its base ref's committed `.config/wt.toml` via `git show` (`git fetch`ing a `pr:`/`mr:` fork head first) — the new worktree, once created, is a checkout of that ref | `worktree::switch` — `hook_repo_for_worktree` (execution), `switch_hook_project_config` (approval / pre-flight) |
+//! | `wt switch`'s `pre-start` / `post-start` / `post-switch` | the new (`--create`) or destination (`wt switch <existing>`) worktree, where these run. For `--create` the target doesn't exist yet at approval time, so the approval prompt and template pre-flight read its base ref's committed `.config/wt.toml` via `git show` (`git fetch`ing a `pr:`/`mr:` fork head first) — the new worktree, once created, is a checkout of that ref | `worktree::switch` — `hook_repo_for_worktree` (execution), `switch_hook_project_config` (approval / pre-flight) |
//! | `pre-switch`, `pre-merge`, `wt hook <type>`, aliases | the worktree `wt` was invoked in (= where they run) | the respective command entry points |
//!
//! `WORKTRUNK_PROJECT_CONFIG_PATH` overrides the path regardless of the root
diff --git a/src/commands/merge.rs b/src/commands/merge.rs
index 6d1b61887..b6989db55 100644
--- a/src/commands/merge.rs
+++ b/src/commands/merge.rs
@@ -87,9 +87,9 @@ pub struct MergeOptions<'a> {
/// - `pre-remove` / `post-remove` / `post-switch` (when the feature worktree
/// is being removed) → resolved by [`collect_remove_hook_commands`], which
/// reads `pre-remove` from the feature worktree's own `.config/wt.toml`
-/// (falling back to the destination's) and `post-remove` / `post-switch`
-/// from the destination — mirroring
-/// `output::handlers::execute_pre_remove_hooks_if_needed`.
+/// and `post-remove` / `post-switch` from the destination — mirroring
+/// `output::handlers::execute_pre_remove_hooks_if_needed`. No fallback
+/// between worktrees — each `.config/wt.toml` stands alone.
fn collect_merge_commands(
repo: &Repository,
destination_path: &Path,
diff --git a/src/commands/picker/mod.rs b/src/commands/picker/mod.rs
index c0e6513c8..a5a9de3b1 100644
--- a/src/commands/picker/mod.rs
+++ b/src/commands/picker/mod.rs
@@ -842,7 +842,6 @@ pub fn handle_picker(
let template_vars = TemplateVars::for_post_switch(&result, &branch_info, "", "");
let extra_vars = template_vars.as_extra_vars();
spawn_switch_background_hooks(
- &repo,
&config,
&result,
branch_info.branch.as_deref(),
diff --git a/src/commands/step/prune.rs b/src/commands/step/prune.rs
index e8bf96c77..9d58ce075 100644
--- a/src/commands/step/prune.rs
+++ b/src/commands/step/prune.rs
@@ -390,7 +390,8 @@ fn render_dry_run(
/// `pre-remove`/`post-remove`/`post-switch`). The integration checks haven't
/// run yet, so every linked worktree is fed to the helper — its `pre-remove`
/// approval is a superset of what executes. `post-remove` / `post-switch`
-/// resolve from the primary worktree's config (the same helper input).
+/// resolve from the primary worktree's config (the same helper input). No
+/// fallback between worktrees — each `.config/wt.toml` stands alone.
///
/// Returns `true` when hooks should run, `false` when the user declined.
fn approve_prune_hooks(
diff --git a/src/commands/worktree/finish.rs b/src/commands/worktree/finish.rs
index 3f2175b8d..b859c530d 100644
--- a/src/commands/worktree/finish.rs
+++ b/src/commands/worktree/finish.rs
@@ -161,7 +161,9 @@ pub fn finish_after_merge(
// destination (the feature worktree may be gone by now). Bare template
// vars still point to the Active (feature branch) per the template
// variable model; those are repo-wide lookups, unaffected by the root.
- let dest_repo = Repository::at(&destination_path).unwrap_or_else(|_| repo.clone());
+ // No fallback to `repo`: if the destination has no `.config/wt.toml`,
+ // no project `post-merge` runs.
+ let dest_repo = Repository::at(&destination_path)?;
let ctx = CommandContext::new(
&dest_repo,
config,
diff --git a/src/commands/worktree/switch.rs b/src/commands/worktree/switch.rs
index 34e4a0093..5cbe67672 100644
--- a/src/commands/worktree/switch.rs
+++ b/src/commands/worktree/switch.rs
@@ -1095,10 +1095,10 @@ pub fn execute_switch(
};
// Execute pre-start commands. The hook resolves its `.config/wt.toml`
- // from the new worktree (created just above), falling back to the
- // primary worktree's — see `hook_repo_for_worktree`.
+ // from the new worktree (created just above) — see
+ // `hook_repo_for_worktree`.
if run_hooks {
- let hook_repo = hook_repo_for_worktree(repo, &worktree_path);
+ let hook_repo = hook_repo_for_worktree(&worktree_path)?;
let ctx =
CommandContext::new(&hook_repo, config, Some(&branch), &worktree_path, force);
let mut vars = TemplateVars::new()
@@ -1354,10 +1354,11 @@ fn base_ref_for_create(
/// For an existing destination the worktree is on disk, so its config is read
/// directly. For `--create` the new worktree is a checkout of the resolved
/// base ref (or, for `pr:`/`mr:` fork refs, the fetched PR/MR head), so the
-/// committed `.config/wt.toml` at that ref is read via `git show`. In both
-/// cases, if there's no `.config/wt.toml` there, fall back to the primary
-/// worktree's — a project-wide hook on the default branch still applies to a
-/// worktree branched before that hook was added (matching `pre-remove`).
+/// committed `.config/wt.toml` at that ref is read via `git show`. In either
+/// case `Ok(None)` means the destination worktree has no `.config/wt.toml`
+/// at all — no project hooks run; the primary worktree's config is not
+/// consulted. A present-but-malformed config surfaces as `Err` so the user
+/// fixes it rather than silently running a different one.
///
/// May `git fetch` a `pr:`/`mr:` fork head ref — `wt switch pr:`/`mr:` is the
/// user explicitly invoking network work, so fetching at the approval gate is
@@ -1366,10 +1367,8 @@ pub(crate) fn switch_hook_project_config(
repo: &Repository,
plan: &SwitchPlan,
) -> anyhow::Result<Option<ProjectConfig>> {
- let direct = match plan {
- SwitchPlan::Existing { path, .. } => Repository::at(path)
- .ok()
- .and_then(|r| r.load_project_config().ok().flatten()),
+ match plan {
+ SwitchPlan::Existing { path, .. } => Repository::at(path)?.load_project_config(),
SwitchPlan::Create { method, branch, .. } => {
let base_ref = match method {
CreationMethod::ForkRef {
@@ -1387,32 +1386,16 @@ pub(crate) fn switch_hook_project_config(
};
repo.project_config_at_ref(&base_ref)
}
- };
- if direct.is_some() {
- return Ok(direct);
}
-
- // No `.config/wt.toml` at the new/destination worktree (or its base ref) →
- // fall back to the primary worktree's, so a project-wide hook on the
- // default branch still applies (matching `pre-remove`).
- Repository::at(repo.home_path()?)?.load_project_config()
}
/// The `Repository` whose `.config/wt.toml` a post-switch hook running in
-/// `worktree_path` should read: the new/destination worktree itself when it
-/// carries a `.config/wt.toml`, otherwise the primary worktree (so a
-/// project-wide hook on the default branch still applies). Mirrors
-/// `execute_pre_remove_hooks_if_needed`; the `repo.clone()` arm only triggers
-/// if even the primary worktree can't be opened.
-fn hook_repo_for_worktree(repo: &Repository, worktree_path: &Path) -> Repository {
- if let Ok(wt_repo) = Repository::at(worktree_path)
- && wt_repo.load_project_config().ok().flatten().is_some()
- {
- return wt_repo;
- }
- repo.home_path()
- .and_then(Repository::at)
- .unwrap_or_else(|_| repo.clone())
+/// `worktree_path` should read: the new/destination worktree itself. No
+/// fallback — when the worktree has no `.config/wt.toml`, no project hooks
+/// run, matching what [`switch_hook_project_config`] surfaced to the approval
+/// prompt.
+fn hook_repo_for_worktree(worktree_path: &Path) -> anyhow::Result<Repository> {
+ Repository::at(worktree_path)
}
/// Approve switch hooks upfront and show "Commands declined" if needed.
@@ -1454,7 +1437,6 @@ pub(crate) fn approve_switch_hooks(
/// Spawn post-switch (and post-start for creates) background hooks.
pub(crate) fn spawn_switch_background_hooks(
- repo: &Repository,
config: &UserConfig,
result: &SwitchResult,
branch: Option<&str>,
@@ -1463,8 +1445,9 @@ pub(crate) fn spawn_switch_background_hooks(
hooks_display_path: Option<&Path>,
) -> anyhow::Result<()> {
// Background hooks run in the new/destination worktree and resolve their
- // `.config/wt.toml` from there (fallback: the primary worktree's).
- let hook_repo = hook_repo_for_worktree(repo, result.path());
+ // `.config/wt.toml` from there. No fallback — if the worktree has no
+ // `.config/wt.toml`, no project hooks fire.
+ let hook_repo = hook_repo_for_worktree(result.path())?;
let ctx = CommandContext::new(&hook_repo, config, branch, result.path(), yes);
let mut announcer = HookAnnouncer::new(&hook_repo, config, false);
@@ -1681,7 +1664,6 @@ pub fn run_switch(
// Batch hooks into a single message when both types are present
if hooks_approved {
spawn_switch_background_hooks(
- &repo,
config,
&result,
branch_info.branch.as_deref(),
diff --git a/src/git/repository/config.rs b/src/git/repository/config.rs
index 12d5fed3b..365d0035e 100644
--- a/src/git/repository/config.rs
+++ b/src/git/repository/config.rs
@@ -628,25 +628,30 @@ impl Repository {
/// Unlike [`load_project_config`](Self::load_project_config) this never
/// touches the working tree and never writes a `.new` migration file —
/// it must not, since the content comes from an arbitrary ref rather than
- /// the user's working copy. Returns `None` when the ref has no
- /// `.config/wt.toml` (git exits non-zero) or the content fails to parse.
+ /// the user's working copy. Returns `Ok(None)` only when the ref has no
+ /// `.config/wt.toml` (git exits non-zero); a present file that fails to
+ /// parse is surfaced as `Err` so the caller can abort rather than silently
+ /// fall through to another config.
///
/// [`project_config_path`]: Self::project_config_path
- pub fn project_config_at_ref(&self, gitref: &str) -> Option<ProjectConfig> {
+ pub fn project_config_at_ref(&self, gitref: &str) -> anyhow::Result<Option<ProjectConfig>> {
if std::env::var_os("WORKTRUNK_PROJECT_CONFIG_PATH").is_some() {
- return self.load_project_config().ok().flatten();
+ return self.load_project_config();
}
// `--end-of-options` keeps a ref like `-foo` from being parsed as a
// flag (git's option parser would otherwise reject `-foo:.config/wt.toml`).
- let content = self
- .run_command(&[
- "show",
- "--end-of-options",
- &format!("{gitref}:.config/wt.toml"),
- ])
- .ok()?;
+ let Ok(content) = self.run_command(&[
+ "show",
+ "--end-of-options",
+ &format!("{gitref}:.config/wt.toml"),
+ ]) else {
+ return Ok(None);
+ };
let migrated = crate::config::migrate_content(&content);
- toml::from_str::<ProjectConfig>(&migrated).ok()
+ let config = toml::from_str::<ProjectConfig>(&migrated).with_context(|| {
+ format!("Failed to parse committed `.config/wt.toml` at `{gitref}`")
+ })?;
+ Ok(Some(config))
}
}
@@ -660,9 +665,9 @@ mod tests {
let test = TestRepo::with_initial_commit();
let repo = Repository::at(test.root_path()).unwrap();
- // No `.config/wt.toml` committed yet, and a nonexistent ref → None.
- assert!(repo.project_config_at_ref("HEAD").is_none());
- assert!(repo.project_config_at_ref("no-such-ref").is_none());
+ // No `.config/wt.toml` committed yet, and a nonexistent ref → Ok(None).
+ assert!(repo.project_config_at_ref("HEAD").unwrap().is_none());
+ assert!(repo.project_config_at_ref("no-such-ref").unwrap().is_none());
// Commit one and read it back at that branch.
test.write_project_config(r#"post-start = "echo hi""#);
@@ -670,14 +675,23 @@ mod tests {
test.run_git(&["commit", "-m", "Add config"]);
let cfg = repo
.project_config_at_ref("HEAD")
+ .unwrap()
.expect("config committed at HEAD");
assert!(cfg.hooks.post_start.is_some());
- // A committed file that doesn't parse → None (rather than erroring).
+ // A committed file that doesn't parse → Err. Callers must abort rather
+ // than silently fall through to a different config.
test.write_project_config("this is not [ valid toml");
test.run_git(&["add", ".config/wt.toml"]);
test.run_git(&["commit", "-m", "Break config"]);
- assert!(repo.project_config_at_ref("HEAD").is_none());
+ let err = repo
+ .project_config_at_ref("HEAD")
+ .expect_err("malformed committed config should surface as Err");
+ let msg = format!("{err:#}");
+ assert!(
+ msg.contains("Failed to parse committed `.config/wt.toml`"),
+ "error should name the ref it failed to parse; got: {msg}"
+ );
}
/// A ref literally named `-foo` must round-trip through
@@ -701,6 +715,7 @@ mod tests {
let cfg = repo
.project_config_at_ref("-foo")
+ .unwrap()
.expect("config readable at hyphen-prefixed ref");
assert!(cfg.hooks.post_start.is_some());
}
diff --git a/src/main.rs b/src/main.rs
index be727994c..32683206b 100644
--- a/src/main.rs
+++ b/src/main.rs
@@ -895,14 +895,12 @@ fn handle_remove_command(args: RemoveArgs, yes: bool) -> anyhow::Result<()> {
// Helper: approve every command the removal will run, in one batch.
// `pre-remove` runs in — and resolves its `.config/wt.toml` from —
- // each worktree being removed (falling back to the primary
- // worktree's config when the removed one carries none, same rule
- // as `execute_pre_remove_hooks_if_needed`); `post-remove` and
- // `post-switch` run in the primary worktree afterwards and resolve
- // their config from there. The shared helper assembles both,
- // dedup'd by template (multiple worktrees often fall back to the
- // same primary config). Returns `true` when the prompt was
- // accepted or there was nothing to approve.
+ // each worktree being removed (no fallback to the primary worktree's
+ // config, same rule as `execute_pre_remove_hooks_if_needed`);
+ // `post-remove` and `post-switch` run in the primary worktree
+ // afterwards and resolve their config from there. The shared helper
+ // assembles both, dedup'd by template. Returns `true` when the prompt
+ // was accepted or there was nothing to approve.
let approve_remove = |removed_worktree_paths: &[&Path], yes: bool| -> anyhow::Result<bool> {
let primary_path = repo.home_path()?;
let primary_repo = Repository::at(&primary_path)?;
diff --git a/src/output/handlers.rs b/src/output/handlers.rs
index cd1002bdc..cc5094d2c 100644
--- a/src/output/handlers.rs
+++ b/src/output/handlers.rs
@@ -1193,22 +1193,12 @@ fn execute_pre_remove_hooks_if_needed(
// being removed. It's still on disk here (removal happens after this), so
// resolve the config from there rather than from `repo`, which is rooted at
// the post-removal working directory (usually the primary worktree, or the
- // merge destination). If the removed worktree carries no `.config/wt.toml`
- // — e.g. it was branched before the project added one — fall back to `repo`
- // so a project-wide `pre-remove` on the default branch still applies. The
- // `wt remove` approval helper in `main.rs` resolves the same config.
- //
- // A `Repository::at` failure means git can't recognize the path as a
- // worktree — propagate rather than silently fall back, matching the
- // approval helpers (`main.rs::approve_remove`, `prune::approve_prune_hooks`).
- // The `UserConfig::load()` silent-skip above is a different case: user
- // config can be benignly malformed and shouldn't fail a remove.
- let wt_at_path = Repository::at(ctx.worktree_path)?;
- let pre_remove_repo = if wt_at_path.load_project_config().ok().flatten().is_some() {
- wt_at_path
- } else {
- repo.clone()
- };
+ // merge destination). No fallback to `repo`: if the removed worktree
+ // carries no `.config/wt.toml`, no project `pre-remove` runs. A
+ // present-but-malformed config surfaces as an error from
+ // `load_project_config`, which aborts removal. The `wt remove` approval
+ // helper in `main.rs` resolves the same config.
+ let pre_remove_repo = Repository::at(ctx.worktree_path)?;
let command_ctx = CommandContext::new(
&pre_remove_repo,
&config,
diff --git a/tests/integration_tests/approval_pty.rs b/tests/integration_tests/approval_pty.rs
index 2b88b55d7..201036b40 100644
--- a/tests/integration_tests/approval_pty.rs
+++ b/tests/integration_tests/approval_pty.rs
@@ -396,6 +396,12 @@ fn test_approval_prompt_remove_decline(repo: TestRepo) {
// Remove origin so worktrunk uses directory name as project identifier
repo.run_git(&["remote", "remove", "origin"]);
+ // Add pre-remove hook before creating the worktree so the new worktree
+ // inherits the committed config — each worktree's `.config/wt.toml` stands
+ // alone, with no fallback to the primary worktree's.
+ repo.write_project_config(r#"pre-remove = "echo 'pre-remove hook'""#);
+ repo.commit("Add pre-remove config");
+
// Create a worktree to remove
let output = repo
.wt_command()
@@ -404,10 +410,6 @@ fn test_approval_prompt_remove_decline(repo: TestRepo) {
.unwrap();
assert!(output.status.success(), "Initial switch should succeed");
- // Add pre-remove hook
- repo.write_project_config(r#"pre-remove = "echo 'pre-remove hook'""#);
- repo.commit("Add pre-remove config");
-
// Configure shell integration
repo.configure_shell_integration();
let env_vars = test_env_vars_with_shell(&repo);
diff --git a/tests/integration_tests/merge.rs b/tests/integration_tests/merge.rs
index 5fdb8a4f3..85163e76e 100644
--- a/tests/integration_tests/merge.rs
+++ b/tests/integration_tests/merge.rs
@@ -1745,30 +1745,39 @@ fn test_merge_primary_on_different_branch_dirty(mut repo: TestRepo) {
));
}
-/// `wt merge`'s teardown hooks resolve `.config/wt.toml` from the destination
-/// worktree, not the feature worktree being merged: `post-merge` always (it
-/// runs in the target), and `pre-remove` when the feature worktree has no
-/// `.config/wt.toml` of its own (the same fallback the executor takes). Here
-/// only the destination — `main`'s worktree — carries the config; the feature
-/// branch was created before it was added.
-#[rstest]
-fn test_merge_teardown_hooks_read_destination_worktree_config(mut repo: TestRepo) {
+/// `wt merge` resolves each hook from the worktree it acts on: `post-merge`
+/// runs in the destination (target's worktree) and reads its config there;
+/// `pre-remove` runs in the feature worktree (still on disk before removal)
+/// and reads its config there. No fallback between worktrees — each
+/// `.config/wt.toml` stands alone.
+#[rstest]
+fn test_merge_teardown_hooks_read_acting_worktree_config(mut repo: TestRepo) {
use crate::common::wait_for_file_content;
- let feature_wt = repo.add_worktree_with_commit("feature-pm", "feature.txt", "x", "feat: x");
-
let pre_remove_marker = repo.root_path().join("pre-remove-ran.txt");
let post_merge_marker = repo.root_path().join("post-merge-ran.txt");
- repo.write_project_config(&format!(
+
+ // Commit both hooks on `main` so the feature branch inherits them. The
+ // feature worktree then defines them in its own `.config/wt.toml` — same
+ // text as main's. After the merge lands, main still has these definitions
+ // (it fast-forwards to the feature tip), so the `post-merge` hook on the
+ // destination (main) fires from main's post-merge config.
+ let config_body = format!(
r#"pre-remove = "echo 'removing {{{{ branch }}}}' > {}"
[post-merge]
sync = "echo 'merged {{{{ branch }}}}' > {}"
"#,
pre_remove_marker.to_slash_lossy(),
post_merge_marker.to_slash_lossy(),
- ));
+ );
+ repo.write_project_config(&config_body);
repo.commit("Add merge hooks on main");
+ // The feature worktree inherits the same `.config/wt.toml` because it was
+ // branched off main after the commit above — the feature worktree owns its
+ // own `pre-remove` config locally, no fallback to main needed.
+ let feature_wt = repo.add_worktree_with_commit("feature-pm", "feature.txt", "x", "feat: x");
+
let output = repo
.wt_command()
.current_dir(&feature_wt)
@@ -1787,12 +1796,12 @@ sync = "echo 'merged {{{{ branch }}}}' > {}"
"merged feature-pm",
"post-merge should run with the destination worktree's config"
);
- // pre-remove runs synchronously before removal; the feature worktree has no
- // `.config/wt.toml`, so it falls back to the destination's.
+ // pre-remove runs synchronously before removal; the feature worktree's
+ // own `.config/wt.toml` defines it.
assert_eq!(
std::fs::read_to_string(&pre_remove_marker).unwrap().trim(),
"removing feature-pm",
- "pre-remove should fall back to the destination worktree's config"
+ "pre-remove should run with the feature worktree's own config"
);
}
diff --git a/tests/integration_tests/remove.rs b/tests/integration_tests/remove.rs
index afeeac2e5..3090207ab 100644
--- a/tests/integration_tests/remove.rs
+++ b/tests/integration_tests/remove.rs
@@ -1758,6 +1758,45 @@ fn test_pre_remove_hook_reads_removed_worktree_config(mut repo: TestRepo) {
);
}
+/// A worktree with a malformed `.config/wt.toml` makes `wt remove` abort with
+/// the parse error in stderr — no silent fall-through to a different config,
+/// and the worktree stays on disk so the user can fix it.
+#[rstest]
+fn test_remove_aborts_on_malformed_worktree_config(mut repo: TestRepo) {
+ let worktree_path = repo.add_worktree("feature-bad-config");
+ std::fs::create_dir_all(worktree_path.join(".config")).unwrap();
+ std::fs::write(
+ worktree_path.join(".config/wt.toml"),
+ "this is not [ valid toml",
+ )
+ .unwrap();
+
+ let output = repo
+ .wt_command()
+ .args([
+ "remove",
+ "--foreground",
+ "--force",
+ "--yes",
+ "feature-bad-config",
+ ])
+ .output()
+ .unwrap();
+ let stderr = String::from_utf8_lossy(&output.stderr);
+ assert!(
+ !output.status.success(),
+ "wt remove should abort on a malformed worktree config; stderr:\n{stderr}"
+ );
+ assert!(
+ stderr.contains("wt.toml"),
+ "error should name the offending config file; stderr:\n{stderr}"
+ );
+ assert!(
+ worktree_path.exists(),
+ "worktree should stay on disk so the user can fix the broken config"
+ );
+}
+
#[rstest]
fn test_pre_remove_hook_failure_aborts(mut repo: TestRepo) {
// Create project config with failing hook
diff --git a/tests/integration_tests/switch.rs b/tests/integration_tests/switch.rs
index 20b9739f9..477375f7c 100644
--- a/tests/integration_tests/switch.rs
+++ b/tests/integration_tests/switch.rs
@@ -978,6 +978,32 @@ fn test_switch_existing_reads_destination_worktree_config(mut repo: TestRepo) {
);
}
+/// A destination worktree with a malformed `.config/wt.toml` makes `wt switch
+/// <existing>` abort with the parse error in stderr — no silent fall-through
+/// to a different config. The path is surfaced so the user can find and fix
+/// the offending file.
+#[rstest]
+fn test_switch_existing_aborts_on_malformed_destination_config(mut repo: TestRepo) {
+ let dest = repo.add_worktree("dest");
+ fs::create_dir_all(dest.join(".config")).unwrap();
+ fs::write(dest.join(".config/wt.toml"), "this is not [ valid toml").unwrap();
+
+ let output = repo
+ .wt_command()
+ .args(["switch", "dest", "--yes"])
+ .output()
+ .unwrap();
+ let stderr = String::from_utf8_lossy(&output.stderr);
+ assert!(
+ !output.status.success(),
+ "wt switch should abort on a malformed destination config; stderr:\n{stderr}"
+ );
+ assert!(
+ stderr.contains("wt.toml"),
+ "error should name the offending config file; stderr:\n{stderr}"
+ );
+}
+
/// `WORKTRUNK_PROJECT_CONFIG_PATH` overrides the path for *every* config read —
/// including `wt switch --create`'s base-ref preview — so the override file's
/// hooks run, not the base branch's committed `.config/wt.toml`.
@@ -2299,10 +2325,24 @@ fn test_switch_pr_fork(#[from(repo_with_remote)] repo: TestRepo) {
fn test_switch_pr_hooks_see_pr_vars(#[from(repo_with_remote)] repo: TestRepo) {
// Set up the same fork-PR scenario as test_switch_pr_fork: a refs/pull/42/head on the
// bare remote, origin redirected to GitHub-style URL, and `gh api` mocked.
+ // The PR commit carries the project config so the post-switch hooks read it
+ // from the new worktree (a checkout of refs/pull/42/head) directly.
repo.run_git(&["checkout", "-b", "pr-source"]);
fs::write(repo.root_path().join("pr-file.txt"), "PR content").unwrap();
- repo.run_git(&["add", "pr-file.txt"]);
- repo.run_git(&["commit", "-m", "PR commit"]);
+ // Each hook writes its own marker in the primary worktree so we can verify
+ // post-switch + post-start (background) populate pr_number/pr_url too.
+ // {{ repo_path }} is always the main repo's working tree.
+ fs::create_dir_all(repo.root_path().join(".config")).unwrap();
+ fs::write(
+ repo.root_path().join(".config/wt.toml"),
+ r#"pre-start = "echo 'pr_number={{ pr_number }} pr_url={{ pr_url }}' > {{ repo_path }}/pre_start.txt"
+post-start = "echo 'pr_number={{ pr_number }} pr_url={{ pr_url }}' > {{ repo_path }}/post_start.txt"
+post-switch = "echo 'pr_number={{ pr_number }} pr_url={{ pr_url }}' > {{ repo_path }}/post_switch.txt"
+"#,
+ )
+ .unwrap();
+ repo.run_git(&["add", "pr-file.txt", ".config/wt.toml"]);
+ repo.run_git(&["commit", "-m", "PR commit with hook config"]);
let commit_sha = repo
.git_command()
@@ -2354,16 +2394,6 @@ fn test_switch_pr_hooks_see_pr_vars(#[from(repo_with_remote)] repo: TestRepo) {
}"#;
let mock_bin = setup_mock_gh_for_pr(&repo, Some(gh_response));
- // Each hook writes its own marker in the primary worktree so we can verify
- // post-switch + post-start (background) populate pr_number/pr_url too.
- // {{ repo_path }} is always the main repo's working tree.
- repo.write_project_config(
- r#"pre-start = "echo 'pr_number={{ pr_number }} pr_url={{ pr_url }}' > {{ repo_path }}/pre_start.txt"
-post-start = "echo 'pr_number={{ pr_number }} pr_url={{ pr_url }}' > {{ repo_path }}/post_start.txt"
-post-switch = "echo 'pr_number={{ pr_number }} pr_url={{ pr_url }}' > {{ repo_path }}/post_switch.txt"
-"#,
- );
-
let mut cmd = repo.wt_command();
cmd.args(["switch", "pr:42", "--yes"]);
configure_mock_cli_env(&mut cmd, &mock_bin);
diff --git a/tests/snapshots/integration__integration_tests__approval_pty__approval_prompt_remove_decline.snap b/tests/snapshots/integration__integration_tests__approval_pty__approval_prompt_remove_decline.snap
index 6b7d2f1cf..c1c2c56b6 100644
--- a/tests/snapshots/integration__integration_tests__approval_pty__approval_prompt_remove_decline.snap
+++ b/tests/snapshots/integration__integration_tests__approval_pty__approval_prompt_remove_decline.snap
@@ -8,4 +8,4 @@ expression: "&output"
❯ Allow and remember? [y/N] n
○ Commands declined, continuing removal
-◎ Removing to-remove worktree & branch in background (ancestor of main, ⊂)
+◎ Removing to-remove worktree & branch in background (same commit as main, _)