Worktrunk is a CLI for Git worktree management, designed for parallel AI agent workflows
Simplify worktree API and bare repository support (#312)
Maximilian Roos43d78ae56d28
diff --git a/docs/content/tips-patterns.md b/docs/content/tips-patterns.mdindex ba7676f37..90f0cded8 100644--- a/docs/content/tips-patterns.md+++ b/docs/content/tips-patterns.md@@ -149,3 +149,37 @@ wt switch --create feature-part2 --base=@```Creates a worktree that builds on the current branch's changes.++## Bare repository layout++An alternative to the default sibling layout (`myproject.feature/`) uses a bare repository with worktrees as subdirectories:++```+myproject/+├── .git/ # bare repository+├── main/ # main branch+├── feature/ # feature branch+└── bugfix/ # bugfix branch+```++Setup:++```bash+git clone --bare <url> myproject/.git+cd myproject+```++Configure worktrunk to create worktrees as subdirectories:++```toml+# ~/.config/worktrunk/config.toml+worktree-path = "{{ branch | sanitize }}"+```++Create the first worktree:++```bash+wt switch --create main+```++Now `wt switch --create feature` creates `myproject/feature/`.diff --git a/src/commands/for_each.rs b/src/commands/for_each.rsindex b06f6ab4f..14c2571fe 100644--- a/src/commands/for_each.rs+++ b/src/commands/for_each.rs@@ -50,7 +50,7 @@ pub fn step_for_each(args: Vec<String>) -> anyhow::Result<()> {let config = WorktrunkConfig::load()?;let mut failed: Vec<String> = Vec::new();- let total = worktrees.worktrees.len();+ let total = worktrees.len();// Join args into a template string (will be expanded per-worktree)let command_template = args.join(" ");@@ -58,7 +58,7 @@ pub fn step_for_each(args: Vec<String>) -> anyhow::Result<()> {// Get repo root for contextlet repo_root = repo.worktree_base()?;- for wt in &worktrees.worktrees {+ for wt in &worktrees {let display_name = worktree_display_name(wt, &repo, &config);output::print(progress_message(format!("Running in {display_name}...")))?;diff --git a/src/commands/list/collect.rs b/src/commands/list/collect.rsindex 972e7230b..c089e14ff 100644--- a/src/commands/list/collect.rs+++ b/src/commands/list/collect.rs@@ -662,7 +662,7 @@ pub fn collect(// Phase 1: Get worktree list (required for everything else)let worktrees = repo.list_worktrees().context("Failed to list worktrees")?;- if worktrees.worktrees.is_empty() {+ if worktrees.is_empty() {return Ok(None);}@@ -670,7 +670,7 @@ pub fn collect(// This avoids a git command - we just compare canonicalized paths.let repo_path_canonical = canonicalize(repo.base_path()).ok();let current_worktree_path = repo_path_canonical.as_ref().and_then(|repo_path| {- worktrees.worktrees.iter().find_map(|wt| {+ worktrees.iter().find_map(|wt| {canonicalize(&wt.path).ok().filter(|wt_path| repo_path.starts_with(wt_path))@@ -688,7 +688,7 @@ pub fn collect(|| repo.is_bare().unwrap_or(false),|| {if show_branches {- get_branches_without_worktrees(repo, &worktrees.worktrees)+ get_branches_without_worktrees(repo, &worktrees)} else {Ok(Vec::new())}@@ -707,18 +707,16 @@ pub fn collect(// Main worktree is the worktree on the default branch (if exists), else first worktreelet main_worktree = worktrees- .worktrees.iter().find(|wt| wt.branch.as_deref() == Some(default_branch.as_str())).cloned()- .unwrap_or_else(|| worktrees.main().clone());+ .unwrap_or_else(|| worktrees[0].clone());// Defer previous_branch lookup until after skeleton - set is_previous later// (skeleton shows placeholder gutter, actual symbols appear when data loads)// Phase 3: Batch fetch timestamps (needs all SHAs from worktrees + branches)let all_shas: Vec<&str> = worktrees- .worktrees.iter().map(|wt| wt.head.as_str()).chain(@@ -732,7 +730,7 @@ pub fn collect(// Sort worktrees: current first, main second, then by timestamp descendinglet sorted_worktrees = sort_worktrees_with_cache(- worktrees.worktrees.clone(),+ worktrees.clone(),&main_worktree,current_worktree_path.as_ref(),×tamps,diff --git a/src/commands/merge.rs b/src/commands/merge.rsindex 59da2bf32..e296a5ef7 100644--- a/src/commands/merge.rs+++ b/src/commands/merge.rs@@ -222,7 +222,7 @@ pub fn handle_merge(opts: MergeOptions<'_>) -> anyhow::Result<()> {// Destination: prefer the target branch's worktree; fall back to main when absentlet destination_path = target_worktree_path.clone()- .unwrap_or_else(|| worktrees.main().path.clone());+ .unwrap_or_else(|| worktrees[0].path.clone());// Finish worktree unless --no-remove was specifiedif remove_effective {diff --git a/src/commands/repository_ext.rs b/src/commands/repository_ext.rsindex ef0c8fe6a..c4afbfa27 100644--- a/src/commands/repository_ext.rs+++ b/src/commands/repository_ext.rs@@ -16,9 +16,6 @@ pub trait RepositoryCliExt {/// Load the project configuration if it exists.fn load_project_config(&self) -> anyhow::Result<Option<ProjectConfig>>;- /// Load the project configuration, emitting a helpful hint if missing.- fn require_project_config(&self) -> anyhow::Result<ProjectConfig>;-/// Warn about untracked files being auto-staged.fn warn_if_auto_staging_untracked(&self) -> anyhow::Result<()>;@@ -62,17 +59,9 @@ pub trait RepositoryCliExt {impl RepositoryCliExt for Repository {fn load_project_config(&self) -> anyhow::Result<Option<ProjectConfig>> {- let repo_root = self.worktree_root()?;- load_project_config_at(repo_root)- }-- fn require_project_config(&self) -> anyhow::Result<ProjectConfig> {- let repo_root = self.worktree_root()?;- let config_path = repo_root.join(".config").join("wt.toml");-- match load_project_config_at(repo_root)? {- Some(cfg) => Ok(cfg),- None => Err(GitError::ProjectConfigNotFound { config_path }.into()),+ match self.worktree_root() {+ Ok(root) => ProjectConfig::load(root).context("Failed to load project config"),+ Err(_) => Ok(None), // Not in a worktree, no project config}}@@ -137,7 +126,7 @@ impl RepositoryCliExt for Repository {let (main_path, changed_directory) = if removing_current {let worktrees = self.list_worktrees()?;- (worktrees.main().path.clone(), true)+ (worktrees[0].path.clone(), true)} else {(current_worktree, false)};@@ -182,24 +171,16 @@ impl RepositoryCliExt for Repository {return Err(GitError::CannotRemoveMainWorktree.into());}- // Get current worktree path+ // Get current worktree path and branchlet current_path = self.worktree_root()?.to_path_buf();-- // Find this worktree in the list to get its metadata- let worktrees = self.list_worktrees()?;- let current_wt = worktrees- .worktrees- .iter()- .find(|wt| wt.path == current_path);-- // Get branch name if available (None for detached HEAD)- let branch_name = current_wt.and_then(|wt| wt.branch.clone());+ let branch_name = self.current_branch()?.map(str::to_string);// Ensure the working tree is cleanself.ensure_clean_working_tree("remove worktree", branch_name.as_deref())?;// Get main worktree path (we're removing current, so we'll cd to main)- let main_path = worktrees.main().path.clone();+ let worktrees = self.list_worktrees()?;+ let main_path = worktrees[0].path.clone();// Resolve default branch for integration reason display// Skip if removing the default branch itself (avoids tautological "main (ancestor of main)")@@ -331,10 +312,6 @@ impl RepositoryCliExt for Repository {}}-fn load_project_config_at(repo_root: &Path) -> anyhow::Result<Option<ProjectConfig>> {- ProjectConfig::load(repo_root).context("Failed to load project config")-}-/// Compute integration reason for branch deletion.////// Returns `None` if:diff --git a/src/commands/standalone.rs b/src/commands/standalone.rsindex f6c99c229..23177489b 100644--- a/src/commands/standalone.rs+++ b/src/commands/standalone.rs@@ -3,7 +3,7 @@ use color_print::cformat;use std::fmt::Write as _;use worktrunk::HookType;use worktrunk::config::{CommandConfig, ProjectConfig, WorktrunkConfig};-use worktrunk::git::Repository;+use worktrunk::git::{GitError, Repository};use worktrunk::path::format_path_for_display;use worktrunk::styling::{INFO_SYMBOL, PROMPT_SYMBOL, format_bash_with_gutter, format_heading, format_with_gutter,@@ -559,8 +559,11 @@ pub fn add_approvals(show_all: bool) -> anyhow::Result<()> {let project_id = repo.project_identifier()?;let config = WorktrunkConfig::load().context("Failed to load config")?;- // Load project config (show helpful error if missing)- let project_config = repo.require_project_config()?;+ // Load project config (error if missing - this command requires it)+ let config_path = repo.worktree_root()?.join(".config").join("wt.toml");+ let project_config = repo+ .load_project_config()?+ .ok_or(GitError::ProjectConfigNotFound { config_path })?;// Collect all commands from the project configlet all_hooks = [diff --git a/src/commands/statusline.rs b/src/commands/statusline.rsindex 7aec194e0..b50fc9ee8 100644--- a/src/commands/statusline.rs+++ b/src/commands/statusline.rs@@ -210,10 +210,7 @@ pub fn run(claude_code: bool) -> Result<()> {fn get_git_status(repo: &Repository, cwd: &Path) -> Result<Option<String>> {// Get current worktree infolet worktrees = repo.list_worktrees()?;- let current_worktree = worktrees- .worktrees- .iter()- .find(|wt| cwd.starts_with(&wt.path));+ let current_worktree = worktrees.iter().find(|wt| cwd.starts_with(&wt.path));let Some(wt) = current_worktree else {// Not in a worktree - just show branch name@@ -236,10 +233,9 @@ fn get_git_status(repo: &Repository, cwd: &Path) -> Result<Option<String>> {// Determine if this is the main worktreelet main_worktree = worktrees- .worktrees.iter().find(|w| w.branch.as_deref() == Some(default_branch.as_str()))- .unwrap_or_else(|| worktrees.main());+ .unwrap_or(&worktrees[0]);let is_main = wt.path == main_worktree.path;// Build item with identity fieldsdiff --git a/src/commands/worktree.rs b/src/commands/worktree.rsindex 8ebcd9b0f..008e2b141 100644--- a/src/commands/worktree.rs+++ b/src/commands/worktree.rs@@ -154,7 +154,6 @@ pub fn resolve_worktree_arg(let path = repo.worktree_root()?.to_path_buf();let worktrees = repo.list_worktrees()?;let branch = worktrees- .worktrees.iter().find(|wt| wt.path == path).and_then(|wt| wt.branch.clone());@@ -633,11 +632,12 @@ pub fn handle_switch(// Build git worktree add commandlet mut args = vec!["worktree", "add", worktree_path.to_str().unwrap()];- // Use the resolved base, or default to default branch if creating without a base+ // Use the resolved base, or default to default branch if creating without a base.+ // For bare repos with no branches yet (bootstrap case), allow None to create orphan branch.let base_for_creation = if create {match resolved_base {Some(b) => Some(b),- None => Some(repo.resolve_target_branch(None)?),+ None => repo.resolve_target_branch(None).ok(),}} else {Nonediff --git a/src/git/mod.rs b/src/git/mod.rsindex 979ee4465..339c3628f 100644--- a/src/git/mod.rs+++ b/src/git/mod.rs@@ -278,8 +278,8 @@ pub struct CompletionBranch {// Re-export parsing helpers for internal usepub(crate) use parse::DefaultBranchName;-// 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.+// 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./// Hook types for git operations#[derive(Debug, Clone, Copy, PartialEq, Eq, clap::ValueEnum, strum::Display, strum::EnumString)]@@ -327,57 +327,6 @@ impl Worktree {}}-/// A list of worktrees with automatic bare worktree filtering.-///-/// This type ensures:-/// - Bare worktrees are filtered out (only worktrees with working trees are included)-/// - The main worktree is at index 0 (accessible via `.main()`) for non-bare repos-/// - Construction fails if no valid worktrees exist-///-/// Git guarantees that the main worktree is listed first in `git worktree list` output,-/// so index 0 is always the main worktree after filtering. For bare repositories where-/// the main worktree is filtered out, index 0 will be the first linked worktree.-#[derive(Debug, Clone)]-pub struct WorktreeList {- pub worktrees: Vec<Worktree>,-}--impl WorktreeList {- /// Create from raw worktrees, filtering bare entries.- ///- /// Preserves git's ordering where the main worktree is first.- pub(crate) fn from_raw(raw_worktrees: Vec<Worktree>) -> anyhow::Result<Self> {- let worktrees: Vec<_> = raw_worktrees.into_iter().filter(|wt| !wt.bare).collect();-- if worktrees.is_empty() {- return Err(GitError::Other {- message: "No worktrees found".into(),- }- .into());- }-- Ok(Self { worktrees })- }-- /// Returns the main worktree (at index 0).- ///- /// For non-bare repositories, this is the original working tree created by- /// `git init` or `git clone`. For bare repositories, this returns the first- /// linked worktree (since bare worktrees are filtered out).- pub fn main(&self) -> &Worktree {- &self.worktrees[0]- }-}--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:@@ -426,137 +375,6 @@ pub(crate) fn finalize_worktree(mut wt: Worktree) -> Worktree {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.worktrees.len(), 2);- assert_eq!(list.worktrees[0].branch, Some("main".to_string()));- assert_eq!(list.worktrees[1].branch, Some("feature".to_string()));- }-- #[test]- fn test_worktree_list_main() {- 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();-- let main = list.main();- assert_eq!(main.branch, Some("main".to_string()));- assert_eq!(main.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- .worktrees- .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()]- );- }-#[test]fn test_check_integration() {// Each integration reason + not integrateddiff --git a/src/git/repository/mod.rs b/src/git/repository/mod.rsindex 4779d8cb8..f913985cb 100644--- a/src/git/repository/mod.rs+++ b/src/git/repository/mod.rs@@ -12,7 +12,7 @@ use dunce::canonicalize;// Import types and functions from parent module (mod.rs)use super::{BranchCategory, CompletionBranch, DefaultBranchName, DiffStats, GitError, GitRemoteUrl,- LineDiff, Worktree, WorktreeList,+ LineDiff, Worktree,};/// Result of resolving a worktree name.@@ -358,7 +358,6 @@ impl Repository {let path = self.worktree_root()?.to_path_buf();let worktrees = self.list_worktrees()?;let branch = worktrees- .worktrees.iter().find(|wt| wt.path == path).and_then(|wt| wt.branch.clone());@@ -1177,7 +1176,6 @@ impl Repository {// Get worktree brancheslet worktrees = self.list_worktrees()?;let worktree_branches: HashSet<String> = worktrees- .worktrees.iter().filter_map(|wt| wt.branch.clone()).collect();@@ -1353,12 +1351,29 @@ impl Repository {/// List all worktrees for this repository.///- /// Returns a WorktreeList that automatically filters out bare repositories- /// and provides access to the main worktree.- pub fn list_worktrees(&self) -> anyhow::Result<WorktreeList> {+ /// Returns a list of worktrees with bare entries filtered out.+ ///+ /// **Ordering:** Git lists the main worktree first. For normal repos, `[0]` is+ /// the main worktree. For bare repos, the bare entry is filtered out, so `[0]`+ /// is the first linked worktree (no semantic "main" exists).+ ///+ /// Returns an empty vec for bare repos with no linked worktrees.+ pub fn list_worktrees(&self) -> anyhow::Result<Vec<Worktree>> {let stdout = self.run_command(&["worktree", "list", "--porcelain"])?;let raw_worktrees = Worktree::parse_porcelain_list(&stdout)?;- WorktreeList::from_raw(raw_worktrees)+ Ok(raw_worktrees.into_iter().filter(|wt| !wt.bare).collect())+ }++ /// Get the current worktree if we're inside one.+ ///+ /// Returns `None` if not in a worktree (e.g., in bare repo directory).+ pub fn current_worktree(&self) -> anyhow::Result<Option<Worktree>> {+ let current_path = match self.worktree_root() {+ Ok(p) => p.to_path_buf(),+ Err(_) => return Ok(None),+ };+ let worktrees = self.list_worktrees()?;+ Ok(worktrees.into_iter().find(|wt| wt.path == current_path))}/// Find the worktree path for a given branch, if one exists.@@ -1366,7 +1381,6 @@ impl Repository {let worktrees = self.list_worktrees()?;Ok(worktrees- .worktrees.iter().find(|wt| wt.branch.as_deref() == Some(branch)).map(|wt| wt.path.clone()))@@ -1385,7 +1399,6 @@ impl Repository {let normalized_path = path.normalize();Ok(worktrees- .worktrees.iter().find(|wt| wt.path.normalize() == normalized_path).map(|wt| (wt.path.clone(), wt.branch.clone())))@@ -1398,7 +1411,6 @@ impl Repository {// Collect branches that have worktreeslet branches_with_worktrees: std::collections::HashSet<String> = worktrees- .worktrees.iter().filter_map(|wt| wt.branch.clone()).collect();diff --git a/tests/integration_tests/bare_repository.rs b/tests/integration_tests/bare_repository.rsindex e6947995d..ff9761bde 100644--- a/tests/integration_tests/bare_repository.rs+++ b/tests/integration_tests/bare_repository.rs@@ -594,3 +594,129 @@ fn test_bare_repo_background_logs_location() {"Log should NOT be in worktree's .git directory");}++#[test]+fn test_bare_repo_slashed_branch_with_sanitize() {+ // Test that slashed branch names work with bare repos and the sanitize filter+ // This matches the documented workflow in tips-patterns.md+ let test = BareRepoTest::new();++ // Override config to use sanitize filter (matches documented config)+ fs::write(+ test.config_path(),+ "worktree-path = \"{{ branch | sanitize }}\"\n",+ )+ .unwrap();++ // Create main worktree+ let main_worktree = test.create_worktree("main", "main");+ test.commit_in_worktree(&main_worktree, "Initial commit");++ // Create feature branch with slash using wt switch+ let (directive_path, _guard) = directive_file();+ let mut cmd = wt_command();+ test.configure_wt_cmd(&mut cmd);+ configure_directive_file(&mut cmd, &directive_path);+ cmd.args(["switch", "--create", "feature/auth"])+ .current_dir(&main_worktree);++ let output = cmd.output().unwrap();++ 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 with sanitized name (feature-auth, not feature/auth)+ let expected_path = test.bare_repo_path().join("feature-auth");+ assert!(+ expected_path.exists(),+ "Expected worktree at {:?} (sanitized from feature/auth)",+ expected_path+ );++ // Verify slashed path was NOT created+ let wrong_path = test.bare_repo_path().join("feature/auth");+ assert!(+ !wrong_path.exists(),+ "Should not create nested directory for slashed branch"+ );++ // Verify git branch name is preserved (not sanitized)+ let mut cmd = Command::new("git");+ cmd.args([+ "-C",+ expected_path.to_str().unwrap(),+ "rev-parse",+ "--abbrev-ref",+ "HEAD",+ ]);+ test.configure_wt_cmd(&mut cmd);+ let branch_output = cmd.output().unwrap();+ assert_eq!(+ String::from_utf8_lossy(&branch_output.stdout).trim(),+ "feature/auth",+ "Git branch name should be preserved as feature/auth"+ );+}++#[test]+fn test_bare_repo_bootstrap_first_worktree() {+ // Test that we can create the first worktree in a bare repo using wt switch --create+ // without needing to manually run `git worktree add` first.+ // This tests that load_project_config() returns None for bare repos without worktrees,+ // allowing the bootstrap workflow to proceed.+ let test = BareRepoTest::new();++ // Unlike other tests, we do NOT create any worktrees first.+ // We run wt switch --create directly on the bare repo.++ let (directive_path, _guard) = directive_file();+ let mut cmd = wt_command();+ test.configure_wt_cmd(&mut cmd);+ configure_directive_file(&mut cmd, &directive_path);+ cmd.args(["switch", "--create", "main"])+ .current_dir(test.bare_repo_path());++ let output = cmd.output().unwrap();++ if !output.status.success() {+ panic!(+ "wt switch --create main from bare repo with no worktrees failed:\nstdout: {}\nstderr: {}",+ String::from_utf8_lossy(&output.stdout),+ String::from_utf8_lossy(&output.stderr)+ );+ }++ // Verify the worktree was created inside the bare repo+ // Template: {{ branch }} -> repo/main+ let expected_path = test.bare_repo_path().join("main");+ assert!(+ expected_path.exists(),+ "Expected first worktree at {:?}",+ expected_path+ );++ // Verify git worktree list shows the new worktree+ let mut cmd = Command::new("git");+ cmd.args([+ "-C",+ test.bare_repo_path().to_str().unwrap(),+ "worktree",+ "list",+ ]);+ test.configure_wt_cmd(&mut cmd);+ let output = cmd.output().unwrap();+ let stdout = String::from_utf8_lossy(&output.stdout);++ // Should show 2 entries: bare repo + main worktree+ assert_eq!(+ stdout.lines().count(),+ 2,+ "Should have bare repo + 1 worktree"+ );+ assert!(stdout.contains("main"), "Should list main worktree");+}