Skip to content

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

fix: use primary worktree for project config path in bare repos (#1745)

worktrunk-bot7d5bc8447349
diff --git a/src/commands/config/create.rs b/src/commands/config/create.rs
index 69de2e9a4..d4b10a78a 100644
--- a/src/commands/config/create.rs
+++ b/src/commands/config/create.rs
@@ -44,7 +44,9 @@ pub(super) fn comment_out_config(content: &str) -> String {
pub fn handle_config_create(project: bool) -> anyhow::Result<()> {
if project {
let repo = Repository::current()?;
- let config_path = repo.current_worktree().root()?.join(".config/wt.toml");
+ let config_path = repo
+ .project_config_path()?
+ .context("Cannot determine project config location — no worktree found")?;
let user_config_exists = require_user_config_path()
.map(|p| p.exists())
.unwrap_or(false);
@@ -61,8 +63,10 @@ pub fn handle_config_create(project: bool) -> anyhow::Result<()> {
)
} else {
let project_config_exists = Repository::current()
- .and_then(|repo| repo.current_worktree().root())
- .map(|root| root.join(".config/wt.toml").exists())
+ .and_then(|repo| repo.project_config_path())
+ .ok()
+ .and_then(|opt| opt)
+ .map(|path| path.exists())
.unwrap_or(false);
create_config_file(
require_user_config_path()?,
diff --git a/src/commands/config/show.rs b/src/commands/config/show.rs
index 834dcf328..ee80e72e8 100644
--- a/src/commands/config/show.rs
+++ b/src/commands/config/show.rs
@@ -519,9 +519,9 @@ fn render_project_config(out: &mut String) -> anyhow::Result<()> {
return Ok(());
}
};
- let repo_root = match repo.current_worktree().root() {
- Ok(root) => root,
- Err(_) => {
+ let config_path = match repo.project_config_path() {
+ Ok(Some(path)) => path,
+ _ => {
writeln!(
out,
"{}",
@@ -533,7 +533,6 @@ fn render_project_config(out: &mut String) -> anyhow::Result<()> {
return Ok(());
}
};
- let config_path = repo_root.join(".config").join("wt.toml");
writeln!(
out,
diff --git a/src/commands/config/update.rs b/src/commands/config/update.rs
index f37929a09..595f37055 100644
--- a/src/commands/config/update.rs
+++ b/src/commands/config/update.rs
@@ -145,12 +145,10 @@ fn check_project_config() -> anyhow::Result<Option<UpdateCandidate>> {
Err(_) => return Ok(None),
};
- let root = match repo.current_worktree().root() {
- Ok(root) => root,
- Err(_) => return Ok(None),
+ let config_path = match repo.project_config_path() {
+ Ok(Some(path)) => path,
+ _ => return Ok(None),
};
-
- let config_path = root.join(".config").join("wt.toml");
if !config_path.exists() {
return Ok(None);
}
diff --git a/src/commands/hook_commands.rs b/src/commands/hook_commands.rs
index caebb66f2..9db774da2 100644
--- a/src/commands/hook_commands.rs
+++ b/src/commands/hook_commands.rs
@@ -319,10 +319,8 @@ pub fn add_approvals(show_all: bool) -> anyhow::Result<()> {
// Load project config (error if missing - this command requires it)
let config_path = repo
- .current_worktree()
- .root()?
- .join(".config")
- .join("wt.toml");
+ .project_config_path()?
+ .context("Cannot determine project config location — no worktree found")?;
let project_config = repo
.load_project_config()?
.ok_or(GitError::ProjectConfigNotFound { config_path })?;
@@ -551,8 +549,9 @@ fn render_project_hooks(
filter: Option<HookType>,
ctx: Option<&CommandContext>,
) -> anyhow::Result<()> {
- let repo_root = repo.current_worktree().root()?;
- let config_path = repo_root.join(".config").join("wt.toml");
+ let config_path = repo
+ .project_config_path()?
+ .context("Cannot determine project config location — no worktree found")?;
writeln!(
out,
diff --git a/src/config/project.rs b/src/config/project.rs
index e34433003..8608cb800 100644
--- a/src/config/project.rs
+++ b/src/config/project.rs
@@ -150,33 +150,12 @@ impl ProjectConfig {
repo: &crate::git::Repository,
write_hints: bool,
) -> Result<Option<Self>, ConfigError> {
- // For bare repos, go straight to the primary worktree for config.
- // `root()` falls back to the bare repo directory when `--show-toplevel`
- // fails, which would incorrectly pick up a `.config/wt.toml` placed in
- // the bare repo root — that's an accidental side effect, not a real
- // worktree root (#1691).
- let config_path = if repo.is_bare().unwrap_or(false) {
- let primary = repo
- .primary_worktree()
- .ok()
- .flatten()
- .map(|p| p.join(".config").join("wt.toml"))
- .filter(|p| p.exists());
- match primary {
- Some(path) => path,
- None => return Ok(None),
- }
- } else {
- let repo_root = repo
- .current_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() {
- config_path
- } else {
- return Ok(None);
- }
+ let config_path = match repo
+ .project_config_path()
+ .map_err(|e| ConfigError::Message(format!("Failed to get config path: {}", e)))?
+ {
+ Some(path) if path.exists() => path,
+ _ => return Ok(None),
};
// Load directly with toml crate to preserve insertion order (with preserve_order feature)
diff --git a/src/diagnostic.rs b/src/diagnostic.rs
index 172a79474..70972946c 100644
--- a/src/diagnostic.rs
+++ b/src/diagnostic.rs
@@ -323,8 +323,7 @@ fn config_show_output(repo: &Repository) -> Option<String> {
}
// Project config
- if let Ok(root) = repo.current_worktree().root() {
- let project_config_path = root.join(".config/wt.toml");
+ if let Ok(Some(project_config_path)) = repo.project_config_path() {
output.push_str(&format!(
"\n{}",
format_config_section(&project_config_path, "Project config")
diff --git a/src/git/repository/config.rs b/src/git/repository/config.rs
index 85f645047..1825cbec4 100644
--- a/src/git/repository/config.rs
+++ b/src/git/repository/config.rs
@@ -1,5 +1,7 @@
//! Git config, hints, marker, and default branch operations for Repository.
+use std::path::PathBuf;
+
use anyhow::Context;
use color_print::cformat;
@@ -403,6 +405,39 @@ impl Repository {
// Project config
// =========================================================================
+ /// Return the path for the project config file.
+ ///
+ /// Uses the current worktree when inside one (both normal and bare repos).
+ /// For bare repos at the bare root (outside any worktree), falls back to
+ /// the primary worktree. Returns `None` when no worktree can be determined
+ /// (bare repo with no linked worktrees).
+ pub fn project_config_path(&self) -> anyhow::Result<Option<PathBuf>> {
+ let in_worktree = self
+ .current_worktree()
+ .run_command(&["rev-parse", "--is-inside-work-tree"])
+ .map(|s| s.trim() == "true")
+ .unwrap_or(false);
+
+ if in_worktree {
+ // Inside a worktree — use it (normal repo or linked worktree in bare repo)
+ return Ok(Some(
+ self.current_worktree()
+ .root()?
+ .join(".config")
+ .join("wt.toml"),
+ ));
+ }
+
+ if self.is_bare().unwrap_or(false) {
+ // At bare repo root — use primary worktree
+ return Ok(self
+ .primary_worktree()?
+ .map(|p| p.join(".config").join("wt.toml")));
+ }
+
+ Ok(None)
+ }
+
/// Load the project configuration (.config/wt.toml) if it exists.
///
/// Result is cached in the repository's shared cache (same for all clones).
diff --git a/tests/integration_tests/approvals.rs b/tests/integration_tests/approvals.rs
index 7b24acd7d..a735d77cd 100644
--- a/tests/integration_tests/approvals.rs
+++ b/tests/integration_tests/approvals.rs
@@ -1,6 +1,9 @@
//! Integration tests for add-approvals and clear-approvals commands
-use crate::common::{TestRepo, make_snapshot_cmd, repo, setup_snapshot_settings};
+use crate::common::{
+ BareRepoTest, TestRepo, TestRepoBase, make_snapshot_cmd, repo, setup_snapshot_settings,
+ setup_temp_snapshot_settings, wt_command,
+};
use insta_cmd::assert_cmd_snapshot;
use rstest::rstest;
use worktrunk::config::Approvals;
@@ -224,3 +227,129 @@ url = "http://localhost:8080"
// Try to add approvals - should show "no commands configured"
snapshot_add_approvals("add_approvals_no_commands", &repo, &[]);
}
+
+// ============================================================================
+// bare repository tests
+// ============================================================================
+
+/// Regression test for #1744: `wt hook approvals add` should find project config
+/// in a bare repo's primary worktree. `config create --project` should place it
+/// there (not in the bare repo root), consistent with `ProjectConfig::load`.
+#[test]
+fn test_add_approvals_bare_repo_config_in_primary_worktree() {
+ let test = BareRepoTest::new();
+ let main_worktree = test.create_worktree("main", "main");
+ test.commit_in(&main_worktree, "Initial commit");
+
+ // Write project config in the primary worktree's .config/wt.toml
+ // This is where `config create --project` should place it for bare repos
+ let config_dir = main_worktree.join(".config");
+ std::fs::create_dir_all(&config_dir).unwrap();
+ std::fs::write(
+ config_dir.join("wt.toml"),
+ r#"post-create = "echo 'hello'"
+"#,
+ )
+ .unwrap();
+
+ let settings = setup_temp_snapshot_settings(test.temp_path());
+ settings.bind(|| {
+ // Run `wt hook approvals add --all` from the main worktree
+ let mut cmd = wt_command();
+ test.configure_wt_cmd(&mut cmd);
+ cmd.current_dir(&main_worktree)
+ .args(["hook", "approvals", "add", "--all"]);
+ assert_cmd_snapshot!("add_approvals_bare_repo_config_in_primary_worktree", cmd);
+ });
+}
+
+/// Test that `project_config_path` returns None (and config create errors)
+/// when no linked worktrees exist in a bare repo.
+#[test]
+fn test_config_create_project_bare_repo_no_worktrees_errors() {
+ let test = BareRepoTest::new();
+ // Don't create any worktrees — no config location available
+
+ // Run `wt config create --project` from the bare repo root — should fail
+ let mut cmd = wt_command();
+ test.configure_wt_cmd(&mut cmd);
+ cmd.current_dir(test.bare_repo_path())
+ .args(["config", "create", "--project"]);
+ let output = cmd.output().unwrap();
+ assert!(
+ !output.status.success(),
+ "wt config create --project should fail with no worktrees"
+ );
+
+ // Config should NOT be created at the bare repo root
+ let bare_root_config = test.bare_repo_path().join(".config").join("wt.toml");
+ assert!(
+ !bare_root_config.exists(),
+ "Config should NOT be created in bare repo root at {:?}",
+ bare_root_config
+ );
+}
+
+/// `hook approvals add` and `hook list` should error in a bare repo with
+/// no linked worktrees (project_config_path returns None).
+#[test]
+fn test_hook_commands_bare_repo_no_worktrees_errors() {
+ let test = BareRepoTest::new();
+
+ // hook approvals add --all should fail
+ let mut cmd = wt_command();
+ test.configure_wt_cmd(&mut cmd);
+ cmd.current_dir(test.bare_repo_path())
+ .args(["hook", "approvals", "add", "--all"]);
+ let output = cmd.output().unwrap();
+ assert!(
+ !output.status.success(),
+ "hook approvals add should fail with no worktrees"
+ );
+
+ // hook show should fail
+ let mut cmd = wt_command();
+ test.configure_wt_cmd(&mut cmd);
+ cmd.current_dir(test.bare_repo_path())
+ .args(["hook", "show"]);
+ let output = cmd.output().unwrap();
+ assert!(
+ !output.status.success(),
+ "hook show should fail with no worktrees"
+ );
+}
+
+/// Regression test for #1744: `wt config create --project` in a bare repo
+/// should create config in the primary worktree, not the bare repo root.
+#[test]
+fn test_config_create_project_bare_repo_uses_primary_worktree() {
+ let test = BareRepoTest::new();
+ let main_worktree = test.create_worktree("main", "main");
+ test.commit_in(&main_worktree, "Initial commit");
+
+ // Run `wt config create --project` from the bare repo root
+ let mut cmd = wt_command();
+ test.configure_wt_cmd(&mut cmd);
+ cmd.current_dir(test.bare_repo_path())
+ .args(["config", "create", "--project"]);
+ let output = cmd.output().unwrap();
+ assert!(
+ output.status.success(),
+ "wt config create --project failed:\nstderr: {}",
+ String::from_utf8_lossy(&output.stderr)
+ );
+
+ // Config should be in the primary worktree, NOT the bare repo root
+ let primary_config = main_worktree.join(".config").join("wt.toml");
+ let bare_root_config = test.bare_repo_path().join(".config").join("wt.toml");
+ assert!(
+ primary_config.exists(),
+ "Config should be created in primary worktree at {:?}",
+ primary_config
+ );
+ assert!(
+ !bare_root_config.exists(),
+ "Config should NOT be created in bare repo root at {:?}",
+ bare_root_config
+ );
+}
diff --git a/tests/snapshots/integration__integration_tests__approvals__add_approvals_bare_repo_config_in_primary_worktree.snap b/tests/snapshots/integration__integration_tests__approvals__add_approvals_bare_repo_config_in_primary_worktree.snap
new file mode 100644
index 000000000..abfeb2952
--- /dev/null
+++ b/tests/snapshots/integration__integration_tests__approvals__add_approvals_bare_repo_config_in_primary_worktree.snap
@@ -0,0 +1,45 @@
+---
+source: tests/integration_tests/approvals.rs
+info:
+ program: wt
+ args:
+ - hook
+ - approvals
+ - add
+ - "--all"
+ env:
+ CLICOLOR_FORCE: ""
+ COLUMNS: "500"
+ GIT_AUTHOR_DATE: "2025-01-01T00:00:00Z"
+ GIT_COMMITTER_DATE: "2025-01-01T00:00:00Z"
+ GIT_CONFIG_GLOBAL: "[TEST_GIT_CONFIG]"
+ GIT_CONFIG_SYSTEM: /dev/null
+ GIT_EDITOR: ""
+ GIT_TERMINAL_PROMPT: "0"
+ LANG: C
+ LC_ALL: C
+ NO_COLOR: ""
+ PSModulePath: ""
+ RUST_LOG: warn
+ SHELL: ""
+ TERM: alacritty
+ WORKTRUNK_APPROVALS_PATH: "[TEST_APPROVALS]"
+ WORKTRUNK_CONFIG_PATH: "[TEST_CONFIG]"
+ WORKTRUNK_SYSTEM_CONFIG_PATH: "[TEST_SYSTEM_CONFIG]"
+ WORKTRUNK_TEST_CLAUDE_INSTALLED: "0"
+ WORKTRUNK_TEST_DELAYED_STREAM_MS: "-1"
+ WORKTRUNK_TEST_EPOCH: "1735776000"
+ WORKTRUNK_TEST_NUSHELL_ENV: "0"
+ WORKTRUNK_TEST_POWERSHELL_ENV: "0"
+ WORKTRUNK_TEST_SKIP_URL_HEALTH_CHECK: "1"
+---
+success: false
+exit_code: 1
+----- stdout -----
+
+----- stderr -----
+▲ repo needs approval to execute 1 command:
+○ pre-start:
+ echo 'hello'
+✗ Cannot prompt for approval in non-interactive environment
+↳ To skip prompts in CI/CD, add --yes; to pre-approve commands, run wt hook approvals add