Skip to content

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

feat: Support bare repositories

Maximilian Roos3fb7bbe14cde
diff --git a/src/commands/list/model.rs b/src/commands/list/model.rs
index 4254399e4..654cc50fd 100644
--- a/src/commands/list/model.rs
+++ b/src/commands/list/model.rs
@@ -551,14 +551,15 @@ pub fn gather_list_data(
return Ok(None);
}
- // First worktree is the primary - clone it for use in closure
- let primary = worktrees[0].clone();
+ // Get primary worktree - clone it for use in closure
+ let primary = worktrees.primary().clone();
// Get current worktree to identify active one
let current_worktree_path = repo.worktree_root().ok();
// Gather enhanced information for all worktrees in parallel
let worktree_results: Vec<Result<WorktreeInfo, GitError>> = worktrees
+ .all()
.par_iter()
.map(|wt| WorktreeInfo::from_worktree(wt, &primary, fetch_ci, check_conflicts))
.collect();
diff --git a/src/commands/merge.rs b/src/commands/merge.rs
index 96c07ece4..efcb1938a 100644
--- a/src/commands/merge.rs
+++ b/src/commands/merge.rs
@@ -233,7 +233,8 @@ pub fn handle_merge(
)?;
// Get primary worktree path before cleanup (while we can still run git commands)
- let primary_worktree_dir = repo.main_worktree_root()?;
+ let worktrees = repo.list_worktrees()?;
+ let primary_worktree_dir = worktrees.primary().path.clone();
// Finish worktree unless --no-remove was specified
if !no_remove {
@@ -484,7 +485,7 @@ pub fn run_pre_merge_commands(
return Ok(());
};
- let repo_root = repo.main_worktree_root()?;
+ let repo_root = repo.worktree_base()?;
let ctx = CommandContext::new(
repo,
config,
@@ -601,7 +602,7 @@ pub fn run_pre_commit_commands(
return Ok(());
};
- let repo_root = repo.main_worktree_root()?;
+ let repo_root = repo.worktree_base()?;
let ctx = CommandContext::new(
repo,
config,
diff --git a/src/commands/worktree.rs b/src/commands/worktree.rs
index 9033c00e3..f76b90ed4 100644
--- a/src/commands/worktree.rs
+++ b/src/commands/worktree.rs
@@ -201,7 +201,7 @@ pub fn handle_switch(
}
// No existing worktree, create one
- let repo_root = repo.main_worktree_root()?;
+ let repo_root = repo.worktree_base()?;
let repo_name = repo_root
.file_name()
@@ -309,7 +309,8 @@ fn remove_current_worktree(repo: &Repository) -> Result<RemoveResult, GitError>
// In worktree: navigate to primary worktree and remove this one
// (no need to check default branch in this path)
let worktree_root = repo.worktree_root()?;
- let primary_worktree_dir = repo.main_worktree_root()?;
+ let worktrees = repo.list_worktrees()?;
+ let primary_worktree_dir = worktrees.primary().path.clone();
// Return paths - deletion will happen in output handler after cd directive is emitted
Ok(RemoveResult::RemovedWorktree {
@@ -366,8 +367,9 @@ fn remove_worktree_by_name(repo: &Repository, branch_name: &str) -> Result<Remov
// Return paths for all cases - deletion happens in output handler
let (primary_path, changed_directory) = if removing_current {
- // Removing current worktree - will cd to main worktree
- (repo.main_worktree_root()?, true)
+ // Removing current worktree - will cd to primary worktree
+ let worktrees = repo.list_worktrees()?;
+ (worktrees.primary().path.clone(), true)
} else {
// Removing different worktree - stay in current location
(repo.worktree_root()?, false)
@@ -450,7 +452,7 @@ pub fn execute_post_create_commands(
return Ok(());
};
- let repo_root = repo.main_worktree_root()?;
+ let repo_root = repo.worktree_base()?;
let ctx = CommandContext::new(repo, config, branch, worktree_path, &repo_root, force);
let commands = prepare_project_commands(post_create_config, &ctx, false, &[], "post-create")?;
@@ -499,7 +501,7 @@ pub fn spawn_post_start_commands(
return Ok(());
};
- let repo_root = repo.main_worktree_root()?;
+ let repo_root = repo.worktree_base()?;
let ctx = CommandContext::new(repo, config, branch, worktree_path, &repo_root, force);
let commands = prepare_project_commands(post_start_config, &ctx, false, &[], "post-start")?;
@@ -555,7 +557,7 @@ pub fn execute_post_start_commands_sequential(
return Ok(());
};
- let repo_root = repo.main_worktree_root()?;
+ let repo_root = repo.worktree_base()?;
let ctx = CommandContext::new(repo, config, branch, worktree_path, &repo_root, force);
let commands = prepare_project_commands(post_start_config, &ctx, false, &[], "post-start")?;
diff --git a/src/git/mod.rs b/src/git/mod.rs
index 01aa7ce11..325a32f93 100644
--- a/src/git/mod.rs
+++ b/src/git/mod.rs
@@ -19,8 +19,8 @@ pub(crate) use parse::{
parse_local_default_branch, parse_numstat, parse_remote_default_branch, parse_worktree_list,
};
-// Note: HookType and Worktree are defined in this module and are already public.
-// They're accessible as git::HookType and git::Worktree without needing re-export.
+// Note: HookType, Worktree, and WorktreeList are defined in this module and are already public.
+// They're accessible as git::HookType, git::Worktree, and git::WorktreeList without needing re-export.
/// Hook types for git operations
#[derive(Debug, Clone, Copy, clap::ValueEnum, strum::Display)]
@@ -45,6 +45,64 @@ pub struct Worktree {
pub prunable: Option<String>,
}
+/// A list of worktrees with automatic bare worktree filtering and primary identification.
+///
+/// This type ensures:
+/// - Bare worktrees are filtered out (only worktrees with working trees are included)
+/// - The primary worktree is always identifiable (first non-bare worktree)
+/// - Construction fails if no valid worktrees exist
+#[derive(Debug, Clone)]
+pub struct WorktreeList {
+ worktrees: Vec<Worktree>,
+}
+
+impl WorktreeList {
+ /// Create from raw worktrees, filtering bare entries and identifying primary.
+ pub(crate) fn from_raw(raw_worktrees: Vec<Worktree>) -> Result<Self, GitError> {
+ let worktrees: Vec<_> = raw_worktrees.into_iter().filter(|wt| !wt.bare).collect();
+
+ if worktrees.is_empty() {
+ return Err(GitError::CommandFailed("No worktrees found".to_string()));
+ }
+
+ Ok(Self { worktrees })
+ }
+
+ /// Get the primary worktree (first non-bare worktree).
+ pub fn primary(&self) -> &Worktree {
+ &self.worktrees[0]
+ }
+
+ /// Get all worktrees (non-bare only).
+ pub fn all(&self) -> &[Worktree] {
+ &self.worktrees
+ }
+
+ /// Number of worktrees.
+ pub fn len(&self) -> usize {
+ self.worktrees.len()
+ }
+
+ /// Check if empty (should never be true for successfully constructed instances).
+ pub fn is_empty(&self) -> bool {
+ self.worktrees.is_empty()
+ }
+
+ /// Iterate over worktrees.
+ pub fn iter(&self) -> impl Iterator<Item = &Worktree> {
+ self.worktrees.iter()
+ }
+}
+
+impl IntoIterator for WorktreeList {
+ type Item = Worktree;
+ type IntoIter = std::vec::IntoIter<Worktree>;
+
+ fn into_iter(self) -> Self::IntoIter {
+ self.worktrees.into_iter()
+ }
+}
+
// Helper functions for worktree parsing
//
// These live in mod.rs rather than parse.rs because they bridge multiple concerns:
@@ -88,3 +146,135 @@ pub(crate) fn finalize_worktree(mut wt: Worktree) -> Worktree {
}
wt
}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ #[test]
+ fn test_worktree_list_filters_bare() {
+ let worktrees = vec![
+ Worktree {
+ path: PathBuf::from("/repo"),
+ head: String::new(),
+ branch: None,
+ bare: true,
+ detached: false,
+ locked: None,
+ prunable: None,
+ },
+ Worktree {
+ path: PathBuf::from("/repo/main"),
+ head: "abc123".to_string(),
+ branch: Some("main".to_string()),
+ bare: false,
+ detached: false,
+ locked: None,
+ prunable: None,
+ },
+ Worktree {
+ path: PathBuf::from("/repo/feature"),
+ head: "def456".to_string(),
+ branch: Some("feature".to_string()),
+ bare: false,
+ detached: false,
+ locked: None,
+ prunable: None,
+ },
+ ];
+
+ let list = WorktreeList::from_raw(worktrees).unwrap();
+
+ assert_eq!(list.len(), 2);
+ assert_eq!(list.all().len(), 2);
+ assert_eq!(list.all()[0].branch, Some("main".to_string()));
+ assert_eq!(list.all()[1].branch, Some("feature".to_string()));
+ }
+
+ #[test]
+ fn test_worktree_list_primary() {
+ let worktrees = vec![
+ Worktree {
+ path: PathBuf::from("/repo"),
+ head: String::new(),
+ branch: None,
+ bare: true,
+ detached: false,
+ locked: None,
+ prunable: None,
+ },
+ Worktree {
+ path: PathBuf::from("/repo/main"),
+ head: "abc123".to_string(),
+ branch: Some("main".to_string()),
+ bare: false,
+ detached: false,
+ locked: None,
+ prunable: None,
+ },
+ ];
+
+ let list = WorktreeList::from_raw(worktrees).unwrap();
+
+ assert_eq!(list.primary().branch, Some("main".to_string()));
+ assert_eq!(list.primary().path, PathBuf::from("/repo/main"));
+ }
+
+ #[test]
+ fn test_worktree_list_all_bare_error() {
+ let worktrees = vec![Worktree {
+ path: PathBuf::from("/repo"),
+ head: String::new(),
+ branch: None,
+ bare: true,
+ detached: false,
+ locked: None,
+ prunable: None,
+ }];
+
+ let result = WorktreeList::from_raw(worktrees);
+
+ assert!(result.is_err());
+ assert!(
+ result
+ .unwrap_err()
+ .to_string()
+ .contains("No worktrees found")
+ );
+ }
+
+ #[test]
+ fn test_worktree_list_iteration() {
+ let worktrees = vec![
+ Worktree {
+ path: PathBuf::from("/repo/main"),
+ head: "abc123".to_string(),
+ branch: Some("main".to_string()),
+ bare: false,
+ detached: false,
+ locked: None,
+ prunable: None,
+ },
+ Worktree {
+ path: PathBuf::from("/repo/feature"),
+ head: "def456".to_string(),
+ branch: Some("feature".to_string()),
+ bare: false,
+ detached: false,
+ locked: None,
+ prunable: None,
+ },
+ ];
+
+ let list = WorktreeList::from_raw(worktrees).unwrap();
+
+ let branches: Vec<_> = list.iter().filter_map(|wt| wt.branch.as_ref()).collect();
+ assert_eq!(branches, vec!["main", "feature"]);
+
+ let branches_owned: Vec<_> = list.into_iter().filter_map(|wt| wt.branch).collect();
+ assert_eq!(
+ branches_owned,
+ vec!["main".to_string(), "feature".to_string()]
+ );
+ }
+}
diff --git a/src/git/repository.rs b/src/git/repository.rs
index d79bf4c3f..7b46a12fd 100644
--- a/src/git/repository.rs
+++ b/src/git/repository.rs
@@ -1,9 +1,10 @@
use std::path::PathBuf;
use std::process::Command;
+use std::sync::OnceLock;
// Import types and functions from parent module (mod.rs)
use super::{
- GitError, Worktree, parse_local_default_branch, parse_numstat, parse_remote_default_branch,
+ GitError, WorktreeList, parse_local_default_branch, parse_numstat, parse_remote_default_branch,
parse_worktree_list,
};
@@ -45,6 +46,15 @@ impl<T, E: std::fmt::Display> GitResultExt<T> for Result<T, E> {
}
}
+/// Internal layout information for a repository.
+///
+/// Cached to avoid repeated git queries.
+#[derive(Debug, Clone)]
+struct RepositoryLayout {
+ /// Base path for worktrees (repo root for normal repos, bare repo path for bare repos)
+ worktree_base: PathBuf,
+}
+
/// Repository context for git operations.
///
/// Provides a more ergonomic API than the `*_in(path, ...)` functions by
@@ -60,15 +70,19 @@ impl<T, E: std::fmt::Display> GitResultExt<T> for Result<T, E> {
/// let is_dirty = repo.is_dirty()?;
/// # Ok::<(), worktrunk::git::GitError>(())
/// ```
-#[derive(Debug, Clone)]
+#[derive(Debug)]
pub struct Repository {
path: PathBuf,
+ layout: OnceLock<RepositoryLayout>,
}
impl Repository {
/// Create a repository context at the specified path.
pub fn at(path: impl Into<PathBuf>) -> Self {
- Self { path: path.into() }
+ Self {
+ path: path.into(),
+ layout: OnceLock::new(),
+ }
}
/// Create a repository context for the current directory.
@@ -83,6 +97,43 @@ impl Repository {
&self.path
}
+ /// Get the repository layout, initializing it if needed.
+ fn layout(&self) -> Result<&RepositoryLayout, GitError> {
+ if let Some(layout) = self.layout.get() {
+ return Ok(layout);
+ }
+
+ let git_common_dir = self
+ .git_common_dir()?
+ .canonicalize()
+ .map_err(|e| GitError::CommandFailed(format!("Failed to canonicalize path: {}", e)))?;
+
+ let is_bare = self.is_bare_repo()?;
+
+ let worktree_base = if is_bare {
+ git_common_dir.clone()
+ } else {
+ git_common_dir
+ .parent()
+ .ok_or_else(|| GitError::CommandFailed("Invalid git directory".to_string()))?
+ .to_path_buf()
+ };
+
+ let layout = RepositoryLayout { worktree_base };
+
+ // set() returns Err if already set, but we checked above, so ignore the result
+ let _ = self.layout.set(layout);
+
+ // Now get() will succeed
+ Ok(self.layout.get().expect("just set"))
+ }
+
+ /// Check if this is a bare repository (no working tree).
+ fn is_bare_repo(&self) -> Result<bool, GitError> {
+ let output = self.run_command(&["config", "--bool", "core.bare"])?;
+ Ok(output.trim() == "true")
+ }
+
/// Get the primary remote name for this repository.
///
/// Uses the following strategy:
@@ -271,21 +322,14 @@ impl Repository {
Ok(PathBuf::from(stdout.trim()))
}
- /// Get the main worktree root (top-level directory of the main worktree).
+ /// Get the base directory where worktrees are created relative to.
///
- /// This returns the main worktree's root, even when called from a linked worktree.
- /// The main worktree is the original repository created by git-init or git-clone.
- /// Use this when you need to reference the primary worktree location.
- pub fn main_worktree_root(&self) -> Result<PathBuf, GitError> {
- let git_common_dir = self
- .git_common_dir()?
- .canonicalize()
- .map_err(|e| GitError::CommandFailed(format!("Failed to canonicalize path: {}", e)))?;
-
- git_common_dir
- .parent()
- .ok_or_else(|| GitError::CommandFailed("Invalid git directory".to_string()))
- .map(|p| p.to_path_buf())
+ /// For normal repositories: the parent of .git (the repo root).
+ /// For bare repositories: the bare repository directory itself.
+ ///
+ /// This is the path that should be used when constructing worktree paths.
+ pub fn worktree_base(&self) -> Result<PathBuf, GitError> {
+ Ok(self.layout()?.worktree_base.clone())
}
/// Check if the working tree has uncommitted changes.
@@ -518,9 +562,13 @@ impl Repository {
}
/// List all worktrees for this repository.
- pub fn list_worktrees(&self) -> Result<Vec<Worktree>, GitError> {
+ ///
+ /// Returns a WorktreeList that automatically filters out bare repositories
+ /// and provides access to the primary worktree.
+ pub fn list_worktrees(&self) -> Result<WorktreeList, GitError> {
let stdout = self.run_command(&["worktree", "list", "--porcelain"])?;
- parse_worktree_list(&stdout)
+ let raw_worktrees = parse_worktree_list(&stdout)?;
+ WorktreeList::from_raw(raw_worktrees)
}
/// Find the worktree path for a given branch, if one exists.
@@ -528,9 +576,9 @@ impl Repository {
let worktrees = self.list_worktrees()?;
Ok(worktrees
- .into_iter()
+ .iter()
.find(|wt| wt.branch.as_deref() == Some(branch))
- .map(|wt| wt.path))
+ .map(|wt| wt.path.clone()))
}
/// Get branches that don't have worktrees (available for switch).
@@ -539,8 +587,10 @@ impl Repository {
let worktrees = self.list_worktrees()?;
// Collect branches that have worktrees
- let branches_with_worktrees: std::collections::HashSet<String> =
- worktrees.into_iter().filter_map(|wt| wt.branch).collect();
+ let branches_with_worktrees: std::collections::HashSet<String> = worktrees
+ .iter()
+ .filter_map(|wt| wt.branch.clone())
+ .collect();
// Filter out branches with worktrees
Ok(all_branches
@@ -658,8 +708,8 @@ impl Repository {
return Ok(url.to_string());
}
- // Fall back to repository name (use main worktree for consistency across all worktrees)
- let repo_root = self.main_worktree_root()?;
+ // Fall back to repository name (use worktree base for consistency across all worktrees)
+ let repo_root = self.worktree_base()?;
let repo_name = repo_root
.file_name()
.and_then(|name| name.to_str())
@@ -771,7 +821,7 @@ impl Repository {
#[cfg(test)]
mod tests {
- use super::super::finalize_worktree;
+ use super::super::{Worktree, finalize_worktree};
use super::*;
#[test]
diff --git a/tests/integration_tests/bare_repository.rs b/tests/integration_tests/bare_repository.rs
new file mode 100644
index 000000000..7c2f2ef6e
--- /dev/null
+++ b/tests/integration_tests/bare_repository.rs
@@ -0,0 +1,449 @@
+use crate::common::TestRepo;
+use insta_cmd::{assert_cmd_snapshot, get_cargo_bin};
+use std::fs;
+use std::path::PathBuf;
+use std::process::Command;
+
+/// Helper to create a bare repository test setup
+struct BareRepoTest {
+ temp_dir: tempfile::TempDir,
+ bare_repo_path: PathBuf,
+ test_config_path: PathBuf,
+}
+
+impl BareRepoTest {
+ fn new() -> Self {
+ let temp_dir = tempfile::TempDir::new().expect("Failed to create temp directory");
+ let bare_repo_path = temp_dir.path().join("test-repo.git");
+ let test_config_path = temp_dir.path().join("test-config.toml");
+
+ let mut test = Self {
+ temp_dir,
+ bare_repo_path,
+ test_config_path,
+ };
+
+ // Create bare repository
+ let output = Command::new("git")
+ .args(["init", "--bare", "--initial-branch", "main"])
+ .current_dir(test.temp_dir.path())
+ .arg(&test.bare_repo_path)
+ .env("GIT_CONFIG_GLOBAL", "/dev/null")
+ .env("GIT_CONFIG_SYSTEM", "/dev/null")
+ .output()
+ .expect("Failed to create bare repo");
+
+ if !output.status.success() {
+ panic!(
+ "Failed to init bare repo:\nstdout: {}\nstderr: {}",
+ String::from_utf8_lossy(&output.stdout),
+ String::from_utf8_lossy(&output.stderr)
+ );
+ }
+
+ // Canonicalize path
+ test.bare_repo_path = test
+ .bare_repo_path
+ .canonicalize()
+ .expect("Failed to canonicalize bare repo path");
+
+ test
+ }
+
+ fn bare_repo_path(&self) -> &PathBuf {
+ &self.bare_repo_path
+ }
+
+ fn temp_path(&self) -> &std::path::Path {
+ self.temp_dir.path()
+ }
+
+ fn config_path(&self) -> &PathBuf {
+ &self.test_config_path
+ }
+
+ /// Create a worktree from the bare repository
+ fn create_worktree(&self, branch: &str, worktree_name: &str) -> PathBuf {
+ let worktree_path = self.temp_dir.path().join(worktree_name);
+
+ let mut cmd = Command::new("git");
+ cmd.args([
+ "-C",
+ self.bare_repo_path.to_str().unwrap(),
+ "worktree",
+ "add",
+ "-b",
+ branch,
+ worktree_path.to_str().unwrap(),
+ ])
+ .env("GIT_CONFIG_GLOBAL", "/dev/null")
+ .env("GIT_CONFIG_SYSTEM", "/dev/null")
+ .env("GIT_AUTHOR_DATE", "2025-01-01T00:00:00Z")
+ .env("GIT_COMMITTER_DATE", "2025-01-01T00:00:00Z");
+
+ let output = cmd.output().expect("Failed to create worktree");
+
+ if !output.status.success() {
+ panic!(
+ "Failed to create worktree:\nstdout: {}\nstderr: {}",
+ String::from_utf8_lossy(&output.stdout),
+ String::from_utf8_lossy(&output.stderr)
+ );
+ }
+
+ worktree_path
+ .canonicalize()
+ .expect("Failed to canonicalize worktree path")
+ }
+
+ /// Create a commit in the specified worktree
+ fn commit_in_worktree(&self, worktree_path: &PathBuf, message: &str) {
+ // Create a file
+ let file_path = worktree_path.join("file.txt");
+ fs::write(&file_path, message).expect("Failed to write file");
+
+ // Add file
+ let output = Command::new("git")
+ .args(["add", "file.txt"])
+ .current_dir(worktree_path)
+ .env("GIT_CONFIG_GLOBAL", "/dev/null")
+ .env("GIT_CONFIG_SYSTEM", "/dev/null")
+ .output()
+ .expect("Failed to add file");
+
+ if !output.status.success() {
+ panic!(
+ "Failed to add file:\nstdout: {}\nstderr: {}",
+ String::from_utf8_lossy(&output.stdout),
+ String::from_utf8_lossy(&output.stderr)
+ );
+ }
+
+ // Commit
+ let output = Command::new("git")
+ .args(["commit", "-m", message])
+ .current_dir(worktree_path)
+ .env("GIT_CONFIG_GLOBAL", "/dev/null")
+ .env("GIT_CONFIG_SYSTEM", "/dev/null")
+ .env("GIT_AUTHOR_DATE", "2025-01-01T00:00:00Z")
+ .env("GIT_COMMITTER_DATE", "2025-01-01T00:00:00Z")
+ .output()
+ .expect("Failed to commit");
+
+ if !output.status.success() {
+ panic!(
+ "Failed to commit:\nstdout: {}\nstderr: {}",
+ String::from_utf8_lossy(&output.stdout),
+ String::from_utf8_lossy(&output.stderr)
+ );
+ }
+ }
+
+ /// Configure a wt command with test environment
+ fn configure_wt_cmd(&self, cmd: &mut Command) {
+ cmd.env("WORKTRUNK_CONFIG", self.test_config_path.to_str().unwrap())
+ .env("GIT_CONFIG_GLOBAL", "/dev/null")
+ .env("GIT_CONFIG_SYSTEM", "/dev/null")
+ .env("SOURCE_DATE_EPOCH", "1761609600")
+ .env("LC_ALL", "C")
+ .env("LANG", "C")
+ .env_remove("NO_COLOR")
+ .env_remove("CLICOLOR_FORCE");
+ }
+}
+
+#[test]
+fn test_bare_repo_list_worktrees() {
+ let test = BareRepoTest::new();
+
+ // Create two worktrees
+ let main_worktree = test.create_worktree("main", "test-repo.main");
+ test.commit_in_worktree(&main_worktree, "Initial commit on main");
+
+ let feature_worktree = test.create_worktree("feature", "test-repo.feature");
+ test.commit_in_worktree(&feature_worktree, "Work on feature");
+
+ // Run wt list from the main worktree
+ let mut cmd = Command::new(get_cargo_bin("wt"));
+ test.configure_wt_cmd(&mut cmd);
+ cmd.arg("list").current_dir(&main_worktree);
+
+ assert_cmd_snapshot!(cmd);
+}
+
+#[test]
+fn test_bare_repo_list_shows_no_bare_entry() {
+ let test = BareRepoTest::new();
+
+ // Create one worktree
+ let main_worktree = test.create_worktree("main", "test-repo.main");
+ test.commit_in_worktree(&main_worktree, "Initial commit");
+
+ // Run wt list and verify bare repo is NOT shown
+ let mut cmd = Command::new(get_cargo_bin("wt"));
+ test.configure_wt_cmd(&mut cmd);
+ cmd.arg("list").current_dir(&main_worktree);
+
+ let output = cmd.output().expect("Failed to run wt list");
+ let stdout = String::from_utf8_lossy(&output.stdout);
+
+ // Should only show the main worktree, not the bare repo
+ assert!(stdout.contains("main"));
+ assert!(!stdout.contains(".git"));
+ assert!(!stdout.contains("bare"));
+}
+
+#[test]
+fn test_bare_repo_switch_creates_worktree() {
+ let test = BareRepoTest::new();
+
+ // Create initial worktree
+ let main_worktree = test.create_worktree("main", "test-repo.main");
+ test.commit_in_worktree(&main_worktree, "Initial commit");
+
+ // Create worktrunk config to use worktree naming pattern suitable for bare repos
+ let config = r#"
+worktree-path = "{branch}"
+"#;
+ fs::write(test.config_path(), config).expect("Failed to write config");
+
+ // Run wt switch --create to create a new worktree
+ let mut cmd = Command::new(get_cargo_bin("wt"));
+ test.configure_wt_cmd(&mut cmd);
+ cmd.args(["switch", "--create", "feature", "--internal"])
+ .current_dir(&main_worktree);
+
+ let output = cmd.output().expect("Failed to run wt switch");
+
+ if !output.status.success() {
+ panic!(
+ "wt switch failed:\nstdout: {}\nstderr: {}",
+ String::from_utf8_lossy(&output.stdout),
+ String::from_utf8_lossy(&output.stderr)
+ );
+ }
+
+ // Debug: check where worktrees actually are
+ let list_output = Command::new("git")
+ .args([
+ "-C",
+ test.bare_repo_path().to_str().unwrap(),
+ "worktree",
+ "list",
+ ])
+ .env("GIT_CONFIG_GLOBAL", "/dev/null")
+ .output()
+ .expect("Failed to list worktrees");
+
+ eprintln!(
+ "Git worktree list:\n{}",
+ String::from_utf8_lossy(&list_output.stdout)
+ );
+
+ // Verify the new worktree was created
+ // With template "{branch}", it creates as sibling: bare-repo-name.feature
+ let bare_name = test.bare_repo_path().file_name().unwrap().to_str().unwrap();
+ let expected_path = test.temp_path().join(format!("{}.feature", bare_name));
+ assert!(
+ expected_path.exists(),
+ "Expected worktree at {:?} but it doesn't exist.\nGit worktree list:\n{}",
+ expected_path,
+ String::from_utf8_lossy(&list_output.stdout)
+ );
+
+ // Verify git worktree list shows both worktrees (but not bare repo)
+ let mut cmd = Command::new("git");
+ cmd.args([
+ "-C",
+ test.bare_repo_path().to_str().unwrap(),
+ "worktree",
+ "list",
+ ])
+ .env("GIT_CONFIG_GLOBAL", "/dev/null")
+ .env("GIT_CONFIG_SYSTEM", "/dev/null");
+
+ let output = cmd.output().expect("Failed to run git worktree list");
+ let stdout = String::from_utf8_lossy(&output.stdout);
+
+ // Should show 3 entries: bare repo + 2 worktrees
+ assert_eq!(stdout.lines().count(), 3);
+}
+
+#[test]
+fn test_bare_repo_switch_with_default_naming() {
+ let test = BareRepoTest::new();
+
+ // Create initial worktree
+ let main_worktree = test.create_worktree("main", "test-repo.main");
+ test.commit_in_worktree(&main_worktree, "Initial commit");
+
+ // Use default naming pattern (should still work with bare repos)
+ // Default is "../{main-worktree}.{branch}" which becomes "test-repo.git.feature"
+ let mut cmd = Command::new(get_cargo_bin("wt"));
+ test.configure_wt_cmd(&mut cmd);
+ cmd.args(["switch", "--create", "feature", "--internal"])
+ .current_dir(&main_worktree);
+
+ let output = cmd.output().expect("Failed to run wt switch");
+
+ if !output.status.success() {
+ panic!(
+ "wt switch failed:\nstdout: {}\nstderr: {}",
+ String::from_utf8_lossy(&output.stdout),
+ String::from_utf8_lossy(&output.stderr)
+ );
+ }
+
+ // Verify worktree was created as sibling to bare repo
+ let bare_name = test.bare_repo_path().file_name().unwrap().to_str().unwrap();
+ let expected_path = test.temp_path().join(format!("{}.feature", bare_name));
+ assert!(
+ expected_path.exists(),
+ "Expected worktree at {:?}",
+ expected_path
+ );
+}
+
+#[test]
+fn test_bare_repo_remove_worktree() {
+ let test = BareRepoTest::new();
+
+ // Create two worktrees
+ let main_worktree = test.create_worktree("main", "test-repo.main");
+ test.commit_in_worktree(&main_worktree, "Initial commit");
+
+ let feature_worktree = test.create_worktree("feature", "test-repo.feature");
+ test.commit_in_worktree(&feature_worktree, "Feature work");
+
+ // Remove feature worktree from main worktree
+ let mut cmd = Command::new(get_cargo_bin("wt"));
+ test.configure_wt_cmd(&mut cmd);
+ cmd.args(["remove", "feature", "--internal"])
+ .current_dir(&main_worktree);
+
+ let output = cmd.output().expect("Failed to run wt remove");
+
+ if !output.status.success() {
+ panic!(
+ "wt remove failed:\nstdout: {}\nstderr: {}",
+ String::from_utf8_lossy(&output.stdout),
+ String::from_utf8_lossy(&output.stderr)
+ );
+ }
+
+ // Verify feature worktree was removed
+ assert!(
+ !feature_worktree.exists(),
+ "Feature worktree should be removed"
+ );
+
+ // Verify main worktree still exists
+ assert!(main_worktree.exists(), "Main worktree should still exist");
+}
+
+#[test]
+fn test_bare_repo_identifies_primary_correctly() {
+ let test = BareRepoTest::new();
+
+ // Create multiple worktrees
+ let main_worktree = test.create_worktree("main", "test-repo.main");
+ test.commit_in_worktree(&main_worktree, "Main commit");
+
+ let _feature1 = test.create_worktree("feature1", "test-repo.feature1");
+ let _feature2 = test.create_worktree("feature2", "test-repo.feature2");
+
+ // Run wt list to see which is marked as primary
+ let mut cmd = Command::new(get_cargo_bin("wt"));
+ test.configure_wt_cmd(&mut cmd);
+ cmd.arg("list").current_dir(&main_worktree);
+
+ let output = cmd.output().expect("Failed to run wt list");
+ let stdout = String::from_utf8_lossy(&output.stdout);
+
+ // First non-bare worktree (main) should be primary
+ // The exact formatting may vary, but main should be listed
+ assert!(stdout.contains("main"));
+}
+
+#[test]
+fn test_bare_repo_worktree_base_used_for_paths() {
+ let test = BareRepoTest::new();
+
+ // Create initial worktree
+ let main_worktree = test.create_worktree("main", "test-repo.main");
+ test.commit_in_worktree(&main_worktree, "Initial commit");
+
+ // Configure to use simple branch naming
+ let config = r#"
+worktree-path = "{branch}"
+"#;
+ fs::write(test.config_path(), config).expect("Failed to write config");
+
+ // Create new worktree - should be created relative to bare repo root
+ let mut cmd = Command::new(get_cargo_bin("wt"));
+ test.configure_wt_cmd(&mut cmd);
+ cmd.args(["switch", "--create", "dev", "--internal"])
+ .current_dir(&main_worktree);
+
+ cmd.output().expect("Failed to run wt switch");
+
+ // Verify path is created as sibling to bare repo (using worktree_base)
+ let bare_name = test.bare_repo_path().file_name().unwrap().to_str().unwrap();
+ let expected = test.temp_path().join(format!("{}.dev", bare_name));
+ assert!(
+ expected.exists(),
+ "Worktree should be created using worktree_base: {:?}",
+ expected
+ );
+
+ // Should NOT be relative to main worktree
+ let wrong_path = main_worktree.join("dev");
+ assert!(
+ !wrong_path.exists(),
+ "Worktree should not be relative to main worktree"
+ );
+}
+
+#[test]
+fn test_bare_repo_equivalent_to_normal_repo() {
+ // This test verifies that bare repos behave identically to normal repos
+ // from the user's perspective
+
+ // Set up bare repo
+ let bare_test = BareRepoTest::new();
+ let bare_main = bare_test.create_worktree("main", "bare-repo.main");
+ bare_test.commit_in_worktree(&bare_main, "Commit in bare repo");
+
+ // Set up normal repo
+ let normal_test = TestRepo::new();
+ normal_test.commit("Commit in normal repo");
+
+ // Configure both with same worktree path pattern
+ let config = r#"
+worktree-path = "{branch}"
+"#;
+ fs::write(bare_test.config_path(), config).expect("Failed to write bare config");
+ fs::write(normal_test.test_config_path(), config).expect("Failed to write normal config");
+
+ // List worktrees in both - should show similar structure
+ let mut bare_list = Command::new(get_cargo_bin("wt"));
+ bare_test.configure_wt_cmd(&mut bare_list);
+ bare_list.arg("list").current_dir(&bare_main);
+
+ let mut normal_list = Command::new(get_cargo_bin("wt"));
+ normal_test.clean_cli_env(&mut normal_list);
+ normal_list.arg("list").current_dir(normal_test.root_path());
+
+ let bare_output = bare_list.output().expect("Failed to list bare worktrees");
+ let normal_output = normal_list
+ .output()
+ .expect("Failed to list normal worktrees");
+
+ // Both should show 1 worktree (main/main)
+ let bare_stdout = String::from_utf8_lossy(&bare_output.stdout);
+ let normal_stdout = String::from_utf8_lossy(&normal_output.stdout);
+
+ assert!(bare_stdout.contains("main"));
+ assert!(normal_stdout.contains("main"));
+ assert_eq!(bare_stdout.lines().count(), normal_stdout.lines().count());
+}
diff --git a/tests/integration_tests/mod.rs b/tests/integration_tests/mod.rs
index 938ab1675..53c95af37 100644
--- a/tests/integration_tests/mod.rs
+++ b/tests/integration_tests/mod.rs
@@ -1,6 +1,7 @@
// column_alignment merged into spacing_edge_cases
pub mod approval_save;
pub mod approval_ui;
+pub mod bare_repository;
pub mod column_alignment_verification;
pub mod completion;
pub mod completion_validation;
diff --git a/tests/integration_tests/snapshots/integration__integration_tests__bare_repository__bare_repo_list_worktrees.snap b/tests/integration_tests/snapshots/integration__integration_tests__bare_repository__bare_repo_list_worktrees.snap
new file mode 100644
index 000000000..d93ab6e6f
--- /dev/null
+++ b/tests/integration_tests/snapshots/integration__integration_tests__bare_repository__bare_repo_list_worktrees.snap
@@ -0,0 +1,26 @@
+---
+source: tests/integration_tests/bare_repository.rs
+info:
+ program: wt
+ args:
+ - list
+ env:
+ CLICOLOR_FORCE: ""
+ GIT_CONFIG_GLOBAL: /dev/null
+ GIT_CONFIG_SYSTEM: /dev/null
+ LANG: C
+ LC_ALL: C
+ NO_COLOR: ""
+ SOURCE_DATE_EPOCH: "1761609600"
+ WORKTRUNK_CONFIG: /var/folders/wf/s6ycxvvs4ln8qsdbfx40hnc40000gn/T/.tmp058jKO/test-config.toml
+---
+success: true
+exit_code: 0
+----- stdout -----
+Branch Status Main ↕ State Path Commit
+feature ./test-repo.feature 5c078f19
+main ↓ ↓1 (no commits) ./test-repo.main 039e01d8
+
+Showing 2 worktrees, 1 behind
+
+----- stderr -----