Skip to content

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

Add initial project structure and fish functions

Maximilian Roos9fc349ca3924
diff --git a/TODO.md b/TODO.md
new file mode 100644
index 000000000..ea25eac57
--- /dev/null
+++ b/TODO.md
@@ -0,0 +1,146 @@
+# Arbor: Git Worktree Management in Rust
+
+Port of git worktree fish functions to a Rust crate with enhanced capabilities.
+
+## Analysis of Existing Functionality
+
+The fish functions provide:
+- **git-worktree-switch**: Create/switch to worktrees with branch management
+- **git-worktree-finish**: Cleanup and return to primary worktree
+- **git-worktree-push**: Fast-forward push between worktrees with conflict detection
+- **git-worktree-merge**: Rebase, merge, and cleanup with optional squashing
+- **git-worktree-llm**: Convenience wrapper for LLM-assisted development
+
+## Workstreams
+
+### 1. Foundation: Git Primitives
+Core git operations that all other components depend on.
+
+**Key capabilities:**
+- Execute git commands and parse output
+- Detect repository state (current branch, default branch, dirty state)
+- Find git directories (git-dir, common-dir, toplevel)
+- Parse worktree list (porcelain format)
+- Check merge ancestry and fast-forward status
+- Detect operations in progress (merge, rebase, cherry-pick)
+
+**Dependencies:** `std::process::Command`, likely `git2` crate for some operations
+
+### 2. Worktree Core
+Primary worktree management operations.
+
+**Key capabilities:**
+- List existing worktrees with branch associations
+- Create worktrees (with/without new branch, custom base)
+- Switch to existing worktrees (cd integration)
+- Remove worktrees (foreground/background)
+- Validate worktree state and detect missing directories
+
+**Dependencies:** Workstream 1 (Git Primitives)
+
+**Challenges:** Shell integration for `cd` - may need to output shell commands for sourcing
+
+### 3. Advanced Operations
+Complex multi-step operations involving multiple worktrees.
+
+**Key capabilities:**
+- Fast-forward push between worktrees
+ - Validate ancestry and fast-forward status
+ - Detect and handle merge commits
+ - Stash/unstash in target worktree
+ - Detect file conflicts between push and working tree
+ - Configure `receive.denyCurrentBranch`
+- Merge and cleanup workflow
+ - Auto-commit dirty state
+ - Squash commits with rebase
+ - Fast-forward target branch
+ - Finish worktree after merge
+- Branch finishing (commit, cleanup, switch)
+
+**Dependencies:** Workstreams 1, 2, and 4 (for user confirmation)
+
+### 4. CLI and UX
+Command-line interface with rich user experience.
+
+**Key capabilities:**
+- Argument parsing (likely using `clap`)
+- Colored terminal output (similar to fish functions)
+- Progress indicators
+- Error messages with actionable suggestions
+- Subcommand structure (switch, finish, push, merge)
+
+**Dependencies:** `clap` for argument parsing, `colored` or `owo-colors` for terminal colors
+
+### 5. External Integrations
+Interface with shell and external tools.
+
+**Key capabilities:**
+- Execute shell commands (git-commit-llm, claude, task)
+- Background process management (disown equivalent)
+- Shell function generation (for `cd` integration)
+- Hook system for custom commands
+
+**Dependencies:** Workstream 1
+
+**Design considerations:**
+- How to handle `cd` in a compiled binary? Options:
+ - Output shell commands to eval
+ - Generate shell wrapper functions
+ - Use shell integration (similar to `zoxide`)
+
+### 6. Testing and Validation
+Ensure correctness with real git repositories.
+
+**Key capabilities:**
+- Integration tests with temporary git repos
+- Test multiple worktree scenarios
+- Validate edge cases (conflicts, missing dirs, operations in progress)
+- Test shell integration
+
+**Dependencies:** All workstreams
+
+**Tools:** `tempfile` crate for temporary directories, possibly `insta` for snapshot testing
+
+## Implementation Order
+
+1. **Phase 1: Foundation**
+ - Workstream 1: Git Primitives (core library)
+ - Workstream 4: Basic CLI (minimal viable interface)
+
+2. **Phase 2: Core Operations**
+ - Workstream 2: Worktree Core (switch, list, create, remove)
+ - Workstream 6: Basic testing
+
+3. **Phase 3: Advanced Features**
+ - Workstream 3: Advanced Operations (push, merge)
+ - Workstream 5: External Integrations
+ - Workstream 6: Comprehensive testing
+
+## Open Questions
+
+1. **Shell integration approach**: How to handle `cd` in a compiled binary?
+ - Generate eval-able shell output?
+ - Provide shell wrapper functions?
+ - Use shell integration hooks?
+
+2. **External command dependencies**: How to handle git-commit-llm, claude, task?
+ - Configurable hooks?
+ - Plugin system?
+ - Just execute if available?
+
+3. **Cross-platform support**: Focus on Unix-like systems only or support Windows?
+ - Fish-specific features may not translate
+
+4. **Git library choice**: Use `git2-rs` for everything or mix with command execution?
+ - `git2` is more robust but less flexible
+ - Commands are easier to debug but more fragile
+
+## Success Criteria
+
+- [ ] Can create and switch between worktrees from CLI
+- [ ] Can push fast-forward changes between worktrees
+- [ ] Can merge and cleanup worktrees
+- [ ] Provides colored, user-friendly output
+- [ ] Handles edge cases gracefully (dirty state, conflicts, missing directories)
+- [ ] Integrates with shell for directory changes
+- [ ] Passes integration tests with real git repositories
diff --git a/fish-functions/git-worktree-finish.fish b/fish-functions/git-worktree-finish.fish
new file mode 100644
index 000000000..c7aab3ab3
--- /dev/null
+++ b/fish-functions/git-worktree-finish.fish
@@ -0,0 +1,51 @@
+function git-worktree-finish -d "Finish work on a git worktree or branch without merging"
+
+ # Save current state early, before any operations that might fail
+ set branch (git branch --show-current)
+ set default_branch (git default-branch)
+ set worktree_root (git rev-parse --show-toplevel)
+ set git_dir (git rev-parse --git-dir)
+ set common_dir (git rev-parse --git-common-dir)
+
+ # Check for uncommitted changes (staged, unstaged, and untracked)
+ if __git_is_dirty
+ git-commit-llm || return 1
+ end
+
+ # Skip this message if we're in a worktree - we'll have a more specific message later
+ if test "$git_dir" = "$common_dir"
+ # Only show branch transition if we're not in a worktree
+ echo (set_color cyan)"πŸ”„ Branch: "(set_color cyan --bold)"$branch"(set_color normal)(set_color cyan)" β†’ "(set_color cyan --bold)"$default_branch"(set_color normal)(set_color cyan)" "(set_color normal) >&2
+ end
+
+ # Skip if already on default branch AND not in a worktree
+ if test "$branch" = "$default_branch" -a "$git_dir" = "$common_dir"
+ echo (set_color green)"βœ… Already on default branch"(set_color normal) >&2
+ return 0
+ end
+
+ # Move back to primary worktree and remove worktree
+ if test "$git_dir" != "$common_dir"
+ # In worktree: go to primary worktree, remove worktree
+ # Navigate to the primary worktree directory (parent of .git)
+ set -l primary_worktree_dir (dirname $common_dir)
+ # Get the branch in the primary worktree
+ set -l primary_branch (git -C "$primary_worktree_dir" branch --show-current)
+ echo (set_color cyan)"πŸ”„ Moving from $branch worktree to primary at $primary_worktree_dir on $primary_branch"(set_color normal) >&2
+ cd "$primary_worktree_dir"
+
+ echo (set_color cyan)"πŸ”„ Removing worktree at $worktree_root in background..."(set_color normal) >&2
+ # Remove worktree in background to avoid waiting
+ git worktree remove "$worktree_root" </dev/null >/dev/null 2>&1 &
+ disown 2>/dev/null
+ else
+ # Regular branch with available default branch, switch if needed
+ if test "$branch" != "$default_branch"
+ echo (set_color cyan)"πŸ”„ Switching to $default_branch"(set_color normal) >&2
+ git switch $default_branch
+ end
+ end
+
+ # Return the branch name as status so it can be captured
+ return 0
+end
diff --git a/fish-functions/git-worktree-llm.fish b/fish-functions/git-worktree-llm.fish
new file mode 100644
index 000000000..b83d8aad2
--- /dev/null
+++ b/fish-functions/git-worktree-llm.fish
@@ -0,0 +1,9 @@
+function git-worktree-llm -d "Create a git worktree and start claude"
+ # Create the worktree, then run setup in background and start claude
+ if git-worktree-switch --create $argv
+ task setup-worktree </dev/null >/dev/null 2>&1 & disown
+ task install </dev/null >/dev/null 2>&1 & disown
+ echo (set_color brblack)"πŸ”„ Running setup in background..."(set_color normal) >&2
+ claude
+ end
+end
diff --git a/fish-functions/git-worktree-merge.fish b/fish-functions/git-worktree-merge.fish
new file mode 100644
index 000000000..44f81c8a8
--- /dev/null
+++ b/fish-functions/git-worktree-merge.fish
@@ -0,0 +1,104 @@
+function git-worktree-merge -d "Finish worktree and merge branch into target branch (default: main)"
+ argparse -n git-worktree-merge s/squash k/keep -- $argv
+ or return 1
+
+ # Get current branch
+ set -l branch (git branch --show-current)
+ if test -z "$branch"
+ echo (set_color red)"❌ Failed to determine current branch"(set_color normal) >&2
+ return 1
+ end
+
+ # Get target branch
+ set -l target_branch $argv[1]
+ if test -z "$target_branch"
+ set target_branch (git default-branch)
+ or return 1
+ end
+
+ # Handle uncommitted changes (including untracked files)
+ if __git_is_dirty
+ # Warn if user had staged changes that will be mixed in
+ if not git diff --cached --quiet --exit-code
+ echo (set_color yellow)"πŸ’‘ Note: Adding all changes (you had some staged changes)"(set_color normal) >&2
+ end
+
+ if set -ql _flag_squash
+ # When squashing, just stage changes - they'll be included in the squash
+ git add .
+ else
+ # When not squashing, commit changes normally
+ git add .
+ # Check if there's actually anything to commit after staging
+ if not git diff --cached --quiet --exit-code
+ echo (set_color cyan)"πŸ”„ Committing uncommitted changes..."(set_color normal) >&2
+ if not git-commit-llm
+ echo (set_color red)"❌ Failed to commit changes"(set_color normal) >&2
+ return 1
+ end
+ end
+ end
+ end
+
+ # Check primary worktree state if we're in a worktree
+ set -l git_dir (git rev-parse --git-dir)
+ set -l common_dir (git rev-parse --git-common-dir)
+
+ if test "$git_dir" != "$common_dir"
+ set -l primary_worktree_dir (dirname $common_dir)
+
+ if set -l operation (fish -c "cd '$primary_worktree_dir' && git-is-operation-in-progress")
+ echo (set_color red)"❌ Primary worktree has a $operation in progress"(set_color normal) >&2
+ git -C "$primary_worktree_dir" status --short
+ return 1
+ end
+ end
+
+ # Prepare commits
+ if set -ql _flag_squash
+ if not git-squash --rebase "$target_branch"
+ echo (set_color red)"❌ Failed to squash and rebase commits"(set_color normal) >&2
+ return 1
+ end
+ else
+ if not git rebase "$target_branch"
+ echo (set_color red)"❌ Failed to rebase onto "(set_color red --bold)"$target_branch"(set_color normal)(set_color red)" "(set_color normal) >&2
+ return 1
+ end
+ end
+
+ # Check if we're already on the target branch
+ if test "$branch" = "$target_branch"
+ echo (set_color -d)"πŸ’¬ Already on "(set_color -d --bold)"$target_branch"(set_color normal -d)", nothing to merge"(set_color normal) >&2
+ return 0
+ end
+
+ # Fast-forward target branch
+ if not git-worktree-push "$target_branch"
+ echo (set_color red)"❌ Failed to fast-forward "(set_color red --bold)"$target_branch"(set_color normal)(set_color red)" "(set_color normal) >&2
+ return 1
+ end
+
+ # Finish worktree unless --keep was specified
+ if not set -q _flag_keep
+ # Always finish the current worktree first (handles cleanup)
+ if not git-worktree-finish
+ echo (set_color red)"❌ Failed to finish worktree"(set_color normal) >&2
+ return 1
+ end
+
+ # Now try to switch to the target branch
+ set -l current_branch (git branch --show-current)
+ if test "$current_branch" != "$target_branch"
+ echo (set_color cyan)"πŸ”„ Switching to $target_branch..."(set_color normal) >&2
+ # Try regular switch first
+ if not git switch "$target_branch" 2>/dev/null
+ # If switch fails, target branch is likely in another worktree
+ # Use git-worktree-switch to handle that case
+ git-worktree-switch "$target_branch"
+ end
+ end
+ else
+ echo (set_color green)"βœ… Branch merged to $target_branch (worktree preserved)"(set_color normal) >&2
+ end
+end
diff --git a/fish-functions/git-worktree-push.fish b/fish-functions/git-worktree-push.fish
new file mode 100644
index 000000000..a84f97938
--- /dev/null
+++ b/fish-functions/git-worktree-push.fish
@@ -0,0 +1,132 @@
+function git-worktree-push -d "Fast-forward push to a branch from another worktree"
+ argparse -n git-worktree-push 'allow-merge-commits' -- $argv
+ or return 1
+
+ set -l target_branch $argv[1]
+ test -z "$target_branch"; and set target_branch (git default-branch)
+
+ # Check if it's a fast-forward
+ if not git merge-base --is-ancestor $target_branch HEAD
+ echo (set_color red)"❌ Not a fast-forward from "(set_color red --bold)"$target_branch"(set_color normal)(set_color red)" to HEAD"(set_color normal) >&2
+ echo (set_color -d)"πŸ’‘ The target branch has commits not in your current branch. Consider 'git pull' or 'git rebase'"(set_color normal) >&2
+ return 1
+ end
+
+ # Check for merge commits unless --allow-merge-commits is specified
+ if not set -q _flag_allow_merge_commits
+ set -l merge_commits (git rev-list --merges $target_branch..HEAD)
+ if test -n "$merge_commits"
+ set -l merge_count (count $merge_commits)
+ echo (set_color red)"❌ Found $merge_count merge commit(s) in the push range:"(set_color normal) >&2
+ for commit in $merge_commits
+ echo " "(git log --oneline -n1 $commit) >&2
+ end
+ echo (set_color yellow)"🟑 Use --allow-merge-commits to push non-linear history"(set_color normal) >&2
+ return 1
+ end
+ end
+
+ # Get the git common directory (the actual .git folder)
+ set -l git_common_dir (git rev-parse --git-common-dir)
+
+ # One-time setup check: ensure receive.denyCurrentBranch is configured
+ set -l deny_config (git config receive.denyCurrentBranch)
+ if test "$deny_config" != "updateInstead"
+ git config receive.denyCurrentBranch updateInstead
+ end
+
+ # Check if target branch is checked out in any worktree
+ set -l worktree_path ""
+ set -l current_worktree ""
+ for line in (git worktree list --porcelain | string split "\n")
+ if string match -q "worktree *" $line
+ set current_worktree (string replace "worktree " "" $line)
+ else if string match -q "branch refs/heads/$target_branch" $line
+ set worktree_path $current_worktree
+ break
+ end
+ end
+
+ # Check if we have a target worktree
+ set -l stash_created 0
+ if test -n "$worktree_path"
+ # Check for changes in the target worktree
+ set -l has_changes (git -C "$worktree_path" status --porcelain)
+
+ if test -n "$has_changes"
+ # Check for file overlap between push changes and working tree changes
+ set -l push_files (git diff --name-only $target_branch..HEAD)
+ set -l worktree_files (git -C "$worktree_path" status --porcelain | string match -r '^\s*[MADRCU?!]\s+(.*)$' | string replace -r '^\s*[MADRCU?!]\s+' '')
+
+ # Find overlapping files
+ set -l overlapping_files
+ for file in $push_files
+ if contains -- $file $worktree_files
+ set -a overlapping_files $file
+ end
+ end
+
+ # If there are overlapping files, always fail
+ if test (count $overlapping_files) -gt 0
+ echo (set_color red)"❌ Cannot push: conflicting uncommitted changes in:"(set_color normal) >&2
+ for file in $overlapping_files
+ echo " - $file" >&2
+ end
+ echo (set_color -d)"πŸ’‘ Commit or stash these changes in $worktree_path first"(set_color normal) >&2
+ return 1
+ end
+
+ # No overlapping changes - stash any other changes (including untracked)
+ echo (set_color cyan)"πŸ”„ Stashing changes in $worktree_path..."(set_color normal) >&2
+ # Use --include-untracked to stash untracked files too
+ set -l stash_output (git -C "$worktree_path" stash push --include-untracked -m "git-worktree-push autostash" 2>&1)
+ if test $status -eq 0
+ # Check if anything was actually stashed
+ if not string match -q "No local changes to save" "$stash_output"
+ set stash_created 1
+ end
+ else
+ echo (set_color red)"❌ Failed to stash changes"(set_color normal) >&2
+ return 1
+ end
+ end
+ end
+
+ # Count commits being pushed
+ set -l commit_count (git rev-list --count $target_branch..HEAD)
+ set -l commit_text "commit"
+ if test $commit_count -ne 1
+ set commit_text "commits"
+ end
+
+ # Show what will be pushed - graph of commits between target and HEAD
+ if test "$commit_count" -gt 0
+ echo (set_color cyan)"πŸ”„ Pushing $commit_count $commit_text to "(set_color cyan --bold)"$target_branch"(set_color normal)(set_color cyan)" @ "(git rev-parse --short HEAD)":"(set_color normal) >&2
+ echo >&2
+ # Show graph with decorations, limited to the relevant range
+ git --no-pager log --graph --oneline --decorate $target_branch..HEAD >&2
+ echo >&2
+ else
+ echo (set_color cyan)"πŸ”„ Pushing to "(set_color cyan --bold)"$target_branch"(set_color normal)(set_color cyan)"..."(set_color normal) >&2
+ end
+
+ # Perform the push
+ if not git push "$git_common_dir" HEAD:$target_branch
+ echo (set_color red)"❌ Push failed (check git permissions and branch protection)"(set_color normal) >&2
+
+ # Try to restore the stash if we created one
+ if test $stash_created -eq 1
+ echo (set_color cyan)"πŸ”„ Restoring stashed changes..."(set_color normal) >&2
+ git -C "$worktree_path" stash pop --quiet
+ end
+ return 1
+ end
+
+ # Pop the stash if we created one
+ if test $stash_created -eq 1
+ echo (set_color cyan)"πŸ”„ Restoring stashed changes..."(set_color normal) >&2
+ if not git -C "$worktree_path" stash pop --quiet
+ echo (set_color yellow)"🟑 Failed to restore stash - run 'git stash pop' in $worktree_path"(set_color normal) >&2
+ end
+ end
+end
diff --git a/fish-functions/git-worktree-switch.fish b/fish-functions/git-worktree-switch.fish
new file mode 100644
index 000000000..e9d2f85b4
--- /dev/null
+++ b/fish-functions/git-worktree-switch.fish
@@ -0,0 +1,71 @@
+function git-worktree-switch --description "Switch to a git worktree, creating branch/worktree as needed"
+ # Parse arguments
+ argparse -n git-worktree-switch --min-args=1 --max-args=1 'c/create' 'b/base=' -- $argv
+ or return 1
+
+ set -l branch_name $argv[1]
+
+ # Check for conflicting conditions
+ if set -q _flag_create; and __git_branch_exists "$branch_name"
+ echo (set_color red)"❌ Branch "(set_color red --bold)"$branch_name"(set_color normal)(set_color red)" already exists. Remove --create flag to switch to it."(set_color normal) >&2
+ return 1
+ end
+ # With worktree.guessRemote=true, git will automatically create from remote branches
+
+ # Check if base flag was provided without create flag
+ if set -q _flag_base; and not set -q _flag_create
+ echo (set_color yellow)"🟑 Warning: --base flag is only used with --create, ignoring"(set_color normal) >&2
+ end
+
+ # Check if worktree already exists for this branch
+ set -l existing_path ""
+ for line in (string split \n (git worktree list --porcelain | string collect))
+ if string match -q "worktree *" $line
+ set existing_path (string replace "worktree " "" $line)
+ else if string match -q "branch refs/heads/$branch_name" $line
+ # Worktree already exists for this branch
+ if test -d "$existing_path"
+ cd "$existing_path"
+ return 0
+ else
+ echo (set_color yellow)"🟑 Worktree directory missing for "(set_color yellow --bold)"$branch_name"(set_color normal)(set_color yellow)". Run 'git worktree prune' to clean up."(set_color normal) >&2
+ return 1
+ end
+ end
+ end
+
+ # No existing worktree, create one
+ set -l git_common_dir (realpath (git rev-parse --git-common-dir))
+ set -l repo_root (dirname $git_common_dir)
+ set -l repo_name (basename $repo_root)
+ set -l parent_dir (dirname $repo_root)
+ set -l worktree_path "$parent_dir/$repo_name.$branch_name"
+
+ # Create the worktree
+ set -l success_msg ""
+ if set -q _flag_create
+ # Creating new branch
+ if set -q _flag_base
+ git worktree add "$worktree_path" -b "$branch_name" "$_flag_base"
+ else
+ git worktree add "$worktree_path" -b "$branch_name"
+ end
+ set success_msg "βœ… Created new branch and worktree for "
+ else
+ # Using existing branch
+ git worktree add "$worktree_path" "$branch_name"
+ set success_msg "βœ… Added worktree for existing branch "
+ end
+
+ # Check if worktree creation succeeded
+ if test $status -eq 0
+ echo (set_color green)"$success_msg"(set_color green --bold)"$branch_name"(set_color normal)(set_color green)" at $worktree_path"(set_color normal) >&2
+ cd "$worktree_path"
+ else
+ return 1
+ end
+end
+
+# Completions for this function are defined in ~/.config/fish/completions/git.fish
+# They must be there because this function is invoked as "git worktree-switch"
+# and Fish loads completions based on the first token (git)