Skip to content

worktree Git Command Guide

The git worktree command allows you to work on multiple branches simultaneously by creating additional working directories linked to the same repository. This enables concurrent development, quick context switching, and efficient handling of long-running tasks without disrupting your main working directory.

Terminal window
git worktree add [-f] [--detach] [--checkout] [--lock [--reason <string>]] [-b <new-branch>] <path> [<commit-ish>]
git worktree list [--porcelain]
git worktree lock [--reason <string>] <worktree>
git worktree move <worktree> <new-path>
git worktree prune [-n] [-v]
git worktree remove [-f] <worktree>
git worktree repair [<path>...]
git worktree unlock <worktree>
CommandDescription
addCreate a new working tree
listList all working trees
lockLock a working tree to prevent pruning
moveMove a working tree to a new location
pruneRemove worktree administrative data
removeRemove a working tree
repairRepair worktree administrative files
unlockUnlock a working tree
ParameterDescription
<path>Path for the new working tree
<commit-ish>Commit/branch to check out in new worktree
<worktree>Existing worktree path to operate on
<new-path>New path for moved worktree
Git Repository with Worktrees:
├── .git/ # Main repository metadata
│ ├── worktrees/ # Worktree administrative data
│ │ ├── main/ # Main worktree info
│ │ └── feature-x/ # Feature branch worktree info
│ └── ...
├── main-worktree/ # Main working directory
│ ├── .git -> ../.git # Symlink to main .git
│ └── ... (working files)
└── feature-worktree/ # Additional working tree
├── .git -> ../.git/worktrees/feature-x # Worktree-specific git dir
└── ... (working files)
Worktree Categories:
├── Main Worktree: Original working directory (created with git init/clone)
├── Linked Worktree: Additional working trees created with git worktree add
├── Bare Repository: Repository without working directory (--bare)
├── Detached HEAD: Worktree checked out to specific commit (no branch)
└── Locked Worktree: Protected from automatic pruning (--lock)
Worktree Isolation Features:
├── Independent Working Directory: Each worktree has its own file checkout
├── Shared Object Store: All worktrees share .git/objects for efficiency
├── Branch Independence: Different branches can be checked out simultaneously
├── Index Isolation: Each worktree maintains its own index (.git/index)
└── Configuration Sharing: Some config shared, some worktree-specific
Terminal window
# Create worktree for existing branch
git worktree add ../feature-branch feature-branch
# Create worktree with new branch
git worktree add -b new-feature ../new-feature
# Create worktree from specific commit
git worktree add --detach ../hotfix HEAD~5
# Create worktree without checking out
git worktree add --no-checkout ../bare-worktree main
Terminal window
# List all worktrees with details
git worktree list
# List in porcelain format for scripting
git worktree list --porcelain
# Show worktree status
git worktree list --verbose
Terminal window
# Remove worktree safely (checks for uncommitted changes)
git worktree remove ../feature-branch
# Force remove worktree (ignores uncommitted changes)
git worktree remove -f ../feature-branch
# Prune stale worktree metadata
git worktree prune -v
Terminal window
# Setup concurrent development environment
setup_concurrent_development() {
echo "Setting up concurrent development environment..."
# Create worktrees for different features
git worktree add ../feature-auth feature/auth
git worktree add ../feature-ui feature/ui
git worktree add ../bugfix-login bugfix/login-failure
# Create worktree for long-running task
git worktree add ../refactor-db refactor/database
echo "Concurrent development environment ready:"
git worktree list
}
# Switch between worktrees
switch_to_worktree() {
local worktree_path="$1"
if [ -d "$worktree_path" ]; then
echo "Switching to worktree: $worktree_path"
cd "$worktree_path" || return 1
echo "Current worktree: $(git worktree list | grep "$(pwd)" | awk '{print $1}')"
echo "Current branch: $(git branch --show-current)"
else
echo "Worktree not found: $worktree_path"
return 1
fi
}
# Usage
setup_concurrent_development
switch_to_worktree "../feature-auth"
Terminal window
# Manage long-running development tasks
manage_long_running_tasks() {
echo "Managing long-running development tasks..."
# Create dedicated worktrees for long tasks
git worktree add ../epic-refactor epic/refactor-legacy-code
git worktree add ../research-ai research/ai-integration
git worktree add ../prototype-new-ui prototype/new-ui-framework
# Lock worktrees to prevent accidental pruning
git worktree lock --reason "Long-running epic refactor" ../epic-refactor
git worktree lock --reason "AI research project" ../research-ai
echo "Long-running tasks worktrees created and locked:"
git worktree list
}
# Monitor worktree status
monitor_worktree_status() {
echo "Monitoring worktree status..."
git worktree list | while read -r worktree branch commit locked; do
echo "Worktree: $worktree"
echo " Branch: $branch"
echo " Commit: $commit"
echo " Locked: ${locked:-No}"
# Check for uncommitted changes
if [ -d "$worktree" ]; then
cd "$worktree" || continue
if [ -n "$(git status --porcelain)" ]; then
echo " Status: Has uncommitted changes"
else
echo " Status: Clean"
fi
cd - >/dev/null || continue
else
echo " Status: Worktree directory missing"
fi
echo
done
}
# Usage
manage_long_running_tasks
monitor_worktree_status
Terminal window
# Setup CI/CD build worktrees
setup_ci_build_worktrees() {
echo "Setting up CI/CD build worktrees..."
# Create worktrees for different build configurations
git worktree add --detach ../build-stable v2.1.0
git worktree add --detach ../build-beta v2.2.0-beta
git worktree add --detach ../build-nightly main
# Lock build worktrees
git worktree lock --reason "Stable release builds" ../build-stable
git worktree lock --reason "Beta release builds" ../build-beta
git worktree lock --reason "Nightly builds" ../build-nightly
echo "CI/CD build worktrees ready:"
git worktree list
}
# Run builds in worktrees
run_worktree_builds() {
echo "Running builds in worktree environments..."
# Build stable release
if [ -d "../build-stable" ]; then
echo "Building stable release..."
cd ../build-stable || return 1
# Run build commands
echo "Build commands would go here..."
cd - >/dev/null || return 1
fi
# Build beta release
if [ -d "../build-beta" ]; then
echo "Building beta release..."
cd ../build-beta || return 1
# Run build commands
echo "Build commands would go here..."
cd - >/dev/null || return 1
fi
echo "Builds completed"
}
# Usage
setup_ci_build_worktrees
run_worktree_builds
Terminal window
# Configure worktree behavior
git config worktree.guessRemote true # Guess remote for worktree branches
git config extensions.worktreeConfig true # Enable per-worktree config
# Configure worktree pruning
git config maintenance.auto 0 # Disable auto maintenance
git config maintenance.strategy incremental # Incremental maintenance
# Configure worktree-specific settings
git config --worktree core.editor "code --wait" # Worktree-specific editor
git config --worktree user.email "work@example.com" # Worktree-specific email
Terminal window
# Safe worktree creation with validation
safe_worktree_add() {
local path="$1"
local branch="$2"
echo "Creating worktree safely: $path (branch: $branch)"
# Validate inputs
if [ -z "$path" ] || [ -z "$branch" ]; then
echo "Error: Path and branch are required"
return 1
fi
# Check if path already exists
if [ -d "$path" ]; then
echo "Error: Path already exists: $path"
return 1
fi
# Check if branch exists
if ! git show-ref --verify --quiet "refs/heads/$branch"; then
echo "Error: Branch does not exist: $branch"
return 1
fi
# Create worktree
if git worktree add "$path" "$branch"; then
echo "✓ Worktree created successfully: $path"
return 0
else
echo "✗ Failed to create worktree"
return 1
fi
}
# Safe worktree removal
safe_worktree_remove() {
local worktree="$1"
echo "Removing worktree safely: $worktree"
# Check if worktree exists
if ! git worktree list --porcelain | grep -q "^worktree $worktree$"; then
echo "Error: Worktree does not exist: $worktree"
return 1
fi
# Check for uncommitted changes
if [ -d "$worktree" ]; then
cd "$worktree" || return 1
if [ -n "$(git status --porcelain)" ]; then
echo "Warning: Worktree has uncommitted changes"
read -p "Remove anyway? (y/N): " -n 1 -r
echo
if [[ ! $REPLY =~ ^[Yy]$ ]]; then
cd - >/dev/null || return 1
return 1
fi
fi
cd - >/dev/null || return 1
fi
# Remove worktree
if git worktree remove "$worktree"; then
echo "✓ Worktree removed successfully: $worktree"
return 0
else
echo "✗ Failed to remove worktree"
return 1
fi
}
# Usage
safe_worktree_add "../feature-x" "feature/x"
safe_worktree_remove "../feature-x"
Terminal window
# Maintain worktrees automatically
maintain_worktrees() {
echo "Performing worktree maintenance..."
# Prune stale worktrees
git worktree prune -v
# Check worktree health
git worktree list | while read -r worktree branch commit; do
if [ -d "$worktree" ]; then
echo "Checking $worktree..."
# Verify .git file exists and points correctly
if [ -f "$worktree/.git" ]; then
git_dir=$(cat "$worktree/.git")
if [ -d "$git_dir" ]; then
echo " ✓ Git directory valid"
else
echo " ✗ Git directory missing: $git_dir"
fi
else
echo " ✗ .git file missing"
fi
else
echo "Worktree directory missing: $worktree"
fi
done
# Repair broken worktrees
git worktree repair
echo "Worktree maintenance complete"
}
# Cleanup unused worktrees
cleanup_unused_worktrees() {
echo "Cleaning up unused worktrees..."
git worktree list | while read -r worktree branch commit; do
# Skip main worktree and locked worktrees
if [[ "$worktree" == "$(pwd)" ]] || [[ "$branch" == *"[locked]"* ]]; then
continue
fi
# Check if branch still exists
branch_name=$(echo "$branch" | sed 's/.*\[//;s/\].*//')
if ! git show-ref --verify --quiet "refs/heads/$branch_name"; then
echo "Branch $branch_name no longer exists, removing worktree: $worktree"
git worktree remove -f "$worktree" 2>/dev/null || echo "Failed to remove $worktree"
fi
done
echo "Cleanup complete"
}
# Usage
maintain_worktrees
cleanup_unused_worktrees
Terminal window
# Feature branch workflow with worktrees
feature_branch_workflow() {
echo "=== Feature Branch Workflow with Worktrees ==="
# Create feature branch worktree
create_feature_worktree() {
local feature_name="$1"
echo "Creating feature worktree for: $feature_name"
# Create branch if it doesn't exist
if ! git show-ref --verify --quiet "refs/heads/feature/$feature_name"; then
git branch "feature/$feature_name"
fi
# Create worktree
worktree_path="../feature-$feature_name"
if git worktree add "$worktree_path" "feature/$feature_name"; then
echo "✓ Feature worktree created: $worktree_path"
# Setup feature-specific config
cd "$worktree_path" || return 1
git config --worktree user.email "dev-$feature_name@example.com"
cd - >/dev/null || return 1
echo "Feature worktree ready for development"
else
echo "✗ Failed to create feature worktree"
return 1
fi
}
# Merge feature back to main
merge_feature_to_main() {
local feature_name="$1"
echo "Merging feature $feature_name to main..."
worktree_path="../feature-$feature_name"
if [ ! -d "$worktree_path" ]; then
echo "Feature worktree not found: $worktree_path"
return 1
fi
# Switch to main worktree
cd "$worktree_path" || return 1
# Ensure feature branch is up to date
git pull origin main
git push origin "feature/$feature_name"
# Switch back to main worktree
cd - >/dev/null || return 1
# Merge feature
git merge "feature/$feature_name" --no-ff -m "Merge feature $feature_name
- Feature implementation
- Tests added
- Documentation updated"
# Remove feature worktree
git worktree remove "$worktree_path"
# Delete feature branch
git branch -d "feature/$feature_name"
echo "✓ Feature $feature_name merged and cleaned up"
}
# Interactive feature workflow
echo "Feature Branch Workflow Options:"
echo "1. Create feature worktree"
echo "2. Merge feature to main"
read -p "Select option (1-2): " option
case "$option" in
1)
read -p "Feature name: " feature
create_feature_worktree "$feature"
;;
2)
read -p "Feature name: " feature
merge_feature_to_main "$feature"
;;
esac
}
feature_branch_workflow
Terminal window
# Hotfix workflow with worktrees
hotfix_workflow() {
echo "=== Hotfix Workflow with Worktrees ==="
# Create hotfix worktree
create_hotfix_worktree() {
local issue_id="$1"
echo "Creating hotfix worktree for issue: $issue_id"
# Create hotfix branch from main
hotfix_branch="hotfix/issue-$issue_id"
git branch "$hotfix_branch" main
# Create worktree
worktree_path="../hotfix-$issue_id"
if git worktree add "$worktree_path" "$hotfix_branch"; then
echo "✓ Hotfix worktree created: $worktree_path"
# Lock worktree for emergency response
git worktree lock --reason "Emergency hotfix for issue $issue_id" "$worktree_path"
echo "Hotfix worktree ready - proceed with emergency fix"
else
echo "✗ Failed to create hotfix worktree"
return 1
fi
}
# Deploy hotfix
deploy_hotfix() {
local issue_id="$1"
echo "Deploying hotfix for issue: $issue_id"
worktree_path="../hotfix-$issue_id"
hotfix_branch="hotfix/issue-$issue_id"
if [ ! -d "$worktree_path" ]; then
echo "Hotfix worktree not found: $worktree_path"
return 1
fi
# Switch to hotfix worktree
cd "$worktree_path" || return 1
# Ensure changes are committed
if [ -n "$(git status --porcelain)" ]; then
echo "Uncommitted changes detected - please commit first"
cd - >/dev/null || return 1
return 1
fi
# Push hotfix branch
git push origin "$hotfix_branch"
# Switch back to main worktree
cd - >/dev/null || return 1
# Merge hotfix to main
git merge "$hotfix_branch" --no-ff -m "Hotfix for issue $issue_id
Emergency fix deployed:
- Issue resolved
- Tests updated
- Deployment verified"
# Tag the hotfix
hotfix_tag="v$(date +%Y.%m.%d)-hotfix-$issue_id"
git tag -a "$hotfix_tag" -m "Hotfix tag for issue $issue_id"
# Clean up
git worktree remove "$worktree_path"
git branch -d "$hotfix_branch"
echo "✓ Hotfix deployed and tagged: $hotfix_tag"
}
# Emergency rollback
emergency_rollback() {
local issue_id="$1"
echo "Performing emergency rollback for issue: $issue_id"
# Find the hotfix tag
hotfix_tag=$(git tag | grep "hotfix-$issue_id" | sort -V | tail -1)
if [ -z "$hotfix_tag" ]; then
echo "No hotfix tag found for issue $issue_id"
return 1
fi
# Revert the hotfix merge
git revert -m 1 "$(git rev-parse "$hotfix_tag")" -n
git commit -m "Rollback hotfix for issue $issue_id
Emergency rollback performed due to:
- Unexpected side effects
- Breaking changes detected
- Alternative solution implemented"
echo "✓ Emergency rollback completed"
}
# Interactive hotfix workflow
echo "Hotfix Workflow Options:"
echo "1. Create hotfix worktree"
echo "2. Deploy hotfix"
echo "3. Emergency rollback"
read -p "Select option (1-3): " option
case "$option" in
1)
read -p "Issue ID: " issue
create_hotfix_worktree "$issue"
;;
2)
read -p "Issue ID: " issue
deploy_hotfix "$issue"
;;
3)
read -p "Issue ID: " issue
emergency_rollback "$issue"
;;
esac
}
hotfix_workflow
Terminal window
# Multi-environment development with worktrees
multi_env_development() {
echo "=== Multi-Environment Development ==="
# Setup environment worktrees
setup_environment_worktrees() {
echo "Setting up environment-specific worktrees..."
# Create worktrees for different environments
git worktree add --detach ../env-development main
git worktree add --detach ../env-staging staging
git worktree add --detach ../env-production production
# Lock production worktree
git worktree lock --reason "Production environment - do not modify" ../env-production
echo "Environment worktrees created:"
git worktree list
}
# Deploy to environment
deploy_to_environment() {
local environment="$1"
local commit="${2:-HEAD}"
echo "Deploying $commit to $environment environment..."
worktree_path="../env-$environment"
if [ ! -d "$worktree_path" ]; then
echo "Environment worktree not found: $worktree_path"
return 1
fi
# Switch to environment worktree
cd "$worktree_path" || return 1
# Checkout the specified commit
if git checkout "$commit" 2>/dev/null; then
echo "✓ Deployed $commit to $environment"
# Run environment-specific setup
case "$environment" in
"development")
echo "Development environment configured"
# Development-specific setup
;;
"staging")
echo "Staging environment configured"
# Staging-specific setup
;;
"production")
echo "Production environment configured"
# Production-specific setup
;;
esac
else
echo "✗ Failed to deploy to $environment"
cd - >/dev/null || return 1
return 1
fi
cd - >/dev/null || return 1
echo "Deployment to $environment complete"
}
# Sync environments
sync_environments() {
echo "Syncing environment worktrees..."
# Update development from main
if [ -d "../env-development" ]; then
cd ../env-development || return 1
git pull origin main
cd - >/dev/null || return 1
echo "✓ Development environment updated"
fi
# Update staging from development
if [ -d "../env-staging" ]; then
cd ../env-staging || return 1
git pull origin staging
cd - >/dev/null || return 1
echo "✓ Staging environment updated"
fi
# Production updated manually only
echo "⚠ Production environment requires manual updates"
}
# Environment status
check_environment_status() {
echo "Environment status:"
for env in development staging production; do
worktree_path="../env-$env"
if [ -d "$worktree_path" ]; then
cd "$worktree_path" || continue
current_commit=$(git rev-parse HEAD)
branch_info=$(git branch --show-current 2>/dev/null || echo "detached")
cd - >/dev/null || continue
echo "$env:"
echo " Path: $worktree_path"
echo " Commit: $current_commit"
echo " Branch: $branch_info"
else
echo "$env: Not configured"
fi
echo
done
}
# Interactive multi-environment management
echo "Multi-Environment Development Options:"
echo "1. Setup environment worktrees"
echo "2. Deploy to environment"
echo "3. Sync environments"
echo "4. Check environment status"
read -p "Select option (1-4): " option
case "$option" in
1) setup_environment_worktrees ;;
2)
read -p "Environment (development/staging/production): " env
read -p "Commit (default: HEAD): " commit
deploy_to_environment "$env" "${commit:-HEAD}"
;;
3) sync_environments ;;
4) check_environment_status ;;
esac
}
multi_env_development
Terminal window
# Troubleshoot worktree path problems
diagnose_worktree_paths() {
echo "Diagnosing worktree path issues..."
# Check worktree list
echo "Current worktrees:"
git worktree list
# Verify .git files
git worktree list --porcelain | while read -r line; do
if [[ "$line" =~ ^worktree ]]; then
worktree_path=$(echo "$line" | cut -d' ' -f2)
if [ -d "$worktree_path" ]; then
if [ -f "$worktree_path/.git" ]; then
git_file_content=$(cat "$worktree_path/.git")
echo "$worktree_path: .git file exists ($git_file_content)"
else
echo "$worktree_path: .git file missing"
fi
else
echo "$worktree_path: Directory does not exist"
fi
fi
done
# Check for broken administrative files
if [ -d ".git/worktrees" ]; then
echo "Worktree administrative data:"
find .git/worktrees -type f -name "git-dir" | while read -r git_dir_file; do
worktree_name=$(basename "$(dirname "$git_dir_file")")
git_dir_path=$(cat "$git_dir_file")
echo " $worktree_name: $git_dir_path"
if [ ! -f "$git_dir_path" ]; then
echo " ⚠ git-dir file points to missing location"
fi
done
fi
}
# Repair worktree issues
repair_worktree_issues() {
echo "Attempting to repair worktree issues..."
# Repair administrative files
git worktree repair
# Prune stale data
git worktree prune -v
# Re-lock worktrees that should be locked
git worktree list | grep "locked" | while read -r worktree _; do
# Re-lock if directory exists
if [ -d "$worktree" ]; then
git worktree lock "$worktree" 2>/dev/null || echo "Could not re-lock $worktree"
fi
done
echo "Worktree repair attempt complete"
}
# Usage
diagnose_worktree_paths
repair_worktree_issues
Terminal window
# Troubleshoot branch and commit problems
diagnose_branch_commit_issues() {
echo "Diagnosing branch and commit issues in worktrees..."
git worktree list | while read -r worktree branch commit; do
echo "Checking worktree: $worktree"
if [ -d "$worktree" ]; then
cd "$worktree" || continue
# Check if HEAD matches expected commit
actual_head=$(git rev-parse HEAD 2>/dev/null)
if [ "$actual_head" != "$commit" ]; then
echo " ⚠ HEAD mismatch: expected $commit, got $actual_head"
else
echo " ✓ HEAD matches expected commit"
fi
# Check current branch
current_branch=$(git branch --show-current 2>/dev/null || echo "detached")
expected_branch=$(echo "$branch" | sed 's/.*\[//;s/\].*//')
if [ "$current_branch" != "$expected_branch" ] && [ "$expected_branch" != "locked" ]; then
echo " ⚠ Branch mismatch: expected $expected_branch, got $current_branch"
else
echo " ✓ Branch status correct"
fi
# Check for uncommitted changes
if [ -n "$(git status --porcelain)" ]; then
echo " ⚠ Worktree has uncommitted changes"
else
echo " ✓ Worktree is clean"
fi
cd - >/dev/null || continue
else
echo " ✗ Worktree directory missing"
fi
echo
done
}
# Fix branch/commit inconsistencies
fix_branch_commit_inconsistencies() {
echo "Attempting to fix branch/commit inconsistencies..."
git worktree list | while read -r worktree branch commit; do
if [ -d "$worktree" ]; then
cd "$worktree" || continue
# Fix detached HEAD if branch exists
if [[ "$branch" != *"detached"* ]] && [[ "$branch" != *"locked"* ]]; then
branch_name=$(echo "$branch" | sed 's/.*\[//;s/\].*//')
if git show-ref --verify --quiet "refs/heads/$branch_name"; then
echo "Fixing branch in $worktree to $branch_name..."
git checkout "$branch_name" 2>/dev/null || echo "Could not checkout $branch_name"
fi
fi
cd - >/dev/null || continue
fi
done
echo "Branch/commit fix attempt complete"
}
# Usage
diagnose_branch_commit_issues
fix_branch_commit_inconsistencies
Terminal window
# Troubleshoot performance issues
diagnose_performance_issues() {
echo "Diagnosing worktree performance issues..."
# Check number of worktrees
worktree_count=$(git worktree list | wc -l)
echo "Total worktrees: $worktree_count"
if [ "$worktree_count" -gt 10 ]; then
echo "⚠ Large number of worktrees may impact performance"
fi
# Check worktree sizes
echo "Worktree sizes:"
git worktree list --porcelain | while read -r line; do
if [[ "$line" =~ ^worktree ]]; then
worktree_path=$(echo "$line" | cut -d' ' -f2)
if [ -d "$worktree_path" ]; then
size=$(du -sh "$worktree_path" 2>/dev/null | cut -f1)
echo " $worktree_path: $size"
fi
fi
done
# Check shared object store
objects_size=$(du -sh .git/objects 2>/dev/null | cut -f1)
echo "Shared objects size: $objects_size"
# Performance recommendations
echo "Performance recommendations:"
echo "- Keep worktrees on same filesystem as main repo"
echo "- Avoid excessive worktrees (>20)"
echo "- Regular pruning: git worktree prune"
echo "- Use SSD storage for better performance"
}
# Optimize worktree performance
optimize_worktree_performance() {
echo "Optimizing worktree performance..."
# Prune unused worktrees
git worktree prune -v
# Run maintenance
git maintenance run --task=gc
git maintenance run --task=commit-graph
git maintenance run --task=loose-objects
# Repack objects
git repack -a -d --depth=250 --window=250
echo "Worktree performance optimization complete"
}
# Usage
diagnose_performance_issues
optimize_worktree_performance
Terminal window
# Troubleshoot permission issues
diagnose_permission_issues() {
echo "Diagnosing worktree permission issues..."
git worktree list --porcelain | while read -r line; do
if [[ "$line" =~ ^worktree ]]; then
worktree_path=$(echo "$line" | cut -d' ' -f2)
if [ -d "$worktree_path" ]; then
# Check directory permissions
perms=$(stat -c "%a %U:%G" "$worktree_path" 2>/dev/null || echo "unknown")
echo "Permissions for $worktree_path: $perms"
# Check .git file permissions
if [ -f "$worktree_path/.git" ]; then
git_perms=$(stat -c "%a %U:%G" "$worktree_path/.git" 2>/dev/null || echo "unknown")
echo " .git file permissions: $git_perms"
fi
# Test git operations
if cd "$worktree_path" 2>/dev/null; then
if git status >/dev/null 2>&1; then
echo " ✓ Git operations work"
else
echo " ✗ Git operations fail"
fi
cd - >/dev/null 2>&1 || true
else
echo " ✗ Cannot access worktree directory"
fi
else
echo "Worktree directory missing: $worktree_path"
fi
fi
done
}
# Fix permission issues
fix_permission_issues() {
echo "Attempting to fix worktree permission issues..."
# Fix permissions for worktree directories
git worktree list --porcelain | while read -r line; do
if [[ "$line" =~ ^worktree ]]; then
worktree_path=$(echo "$line" | cut -d' ' -f2)
if [ -d "$worktree_path" ]; then
echo "Fixing permissions for $worktree_path..."
# Set proper permissions
chmod 755 "$worktree_path" 2>/dev/null || echo "Could not set directory permissions"
[ -f "$worktree_path/.git" ] && chmod 644 "$worktree_path/.git" 2>/dev/null || true
# Change ownership if running as root
if [ "$(id -u)" -eq 0 ]; then
chown -R "$(stat -c %U .git)" "$worktree_path" 2>/dev/null || echo "Could not change ownership"
fi
fi
fi
done
echo "Permission fix attempt complete"
}
# Usage
diagnose_permission_issues
fix_permission_issues
#!/bin/bash
# Enterprise worktree management system
enterprise_worktree_management() {
echo "=== Enterprise Worktree Management ==="
# Setup team worktrees
setup_team_worktrees() {
echo "Setting up team worktrees..."
# Define team structure
teams=("frontend" "backend" "devops" "qa")
projects=("web-app" "api" "infrastructure" "testing")
for team in "${teams[@]}"; do
for project in "${projects[@]}"; do
worktree_path="../${team}-${project}"
# Create worktree if it doesn't exist
if [ ! -d "$worktree_path" ]; then
echo "Creating worktree for $team/$project..."
# Create branch if needed
branch_name="team/$team/$project"
if ! git show-ref --verify --quiet "refs/heads/$branch_name"; then
git branch "$branch_name" main
fi
# Create worktree
git worktree add "$worktree_path" "$branch_name"
git worktree lock --reason "Team $team project $project" "$worktree_path"
# Setup team-specific configuration
cd "$worktree_path" || continue
git config --worktree user.email "${team}@company.com"
cd - >/dev/null || continue
fi
done
done
echo "Team worktrees setup complete:"
git worktree list
}
# Monitor team activity
monitor_team_activity() {
echo "Monitoring team worktree activity..."
cat > team-activity-report.md << EOF
# Team Worktree Activity Report
Generated: $(date)
## Active Worktrees
EOF
git worktree list | while read -r worktree branch commit; do
echo "### $worktree" >> team-activity-report.md
echo "- Branch: $branch" >> team-activity-report.md
echo "- Latest Commit: $commit" >> team-activity-report.md
if [ -d "$worktree" ]; then
cd "$worktree" || continue
# Get recent activity
last_commit=$(git log -1 --format="%h %s (%an, %ar)" 2>/dev/null || echo "No commits")
uncommitted=$(git status --porcelain | wc -l)
echo "- Last Activity: $last_commit" >> team-activity-report.md
echo "- Uncommitted Changes: $uncommitted files" >> team-activity-report.md
cd - >/dev/null || continue
else
echo "- Status: Directory missing" >> team-activity-report.md
fi
echo "" >> team-activity-report.md
done
echo "Team activity report generated: team-activity-report.md"
}
# Cleanup inactive worktrees
cleanup_inactive_worktrees() {
local days_threshold="${1:-30}"
echo "Cleaning up worktrees inactive for $days_threshold+ days..."
git worktree list | while read -r worktree branch commit; do
# Skip main worktree and locked worktrees
if [[ "$worktree" == "$(pwd)" ]] || [[ "$branch" == *"[locked]"* ]]; then
continue
fi
if [ -d "$worktree" ]; then
cd "$worktree" || continue
# Check last activity
last_activity=$(git log -1 --format="%ct" 2>/dev/null || echo "0")
current_time=$(date +%s)
days_since_activity=$(( (current_time - last_activity) / 86400 ))
if [ "$days_since_activity" -gt "$days_threshold" ]; then
echo "Removing inactive worktree: $worktree ($days_since_activity days old)"
cd - >/dev/null || continue
git worktree remove -f "$worktree" 2>/dev/null || echo "Failed to remove $worktree"
else
cd - >/dev/null || continue
fi
fi
done
echo "Inactive worktree cleanup complete"
}
# Generate enterprise worktree report
generate_enterprise_report() {
echo "Generating enterprise worktree report..."
cat > enterprise-worktree-report.md << EOF
# Enterprise Worktree Report
Generated: $(date)
Repository: $(basename "$(pwd)")
## Worktree Statistics
EOF
total_worktrees=$(git worktree list | wc -l)
locked_worktrees=$(git worktree list | grep -c "locked")
active_worktrees=$((total_worktrees - locked_worktrees))
echo "- Total worktrees: $total_worktrees" >> enterprise-worktree-report.md
echo "- Active worktrees: $active_worktrees" >> enterprise-worktree-report.md
echo "- Locked worktrees: $locked_worktrees" >> enterprise-worktree-report.md
cat >> enterprise-worktree-report.md << EOF
## Worktree Details
EOF
git worktree list | while read -r worktree branch commit; do
echo "### $(basename "$worktree")" >> enterprise-worktree-report.md
echo "- Path: $worktree" >> enterprise-worktree-report.md
echo "- Branch: $branch" >> enterprise-worktree-report.md
echo "- Latest Commit: $commit" >> enterprise-worktree-report.md
if [ -d "$worktree" ]; then
cd "$worktree" || continue
size=$(du -sh . | cut -f1)
files=$(find . -type f | wc -l)
echo "- Size: $size" >> enterprise-worktree-report.md
echo "- Files: $files" >> enterprise-worktree-report.md
cd - >/dev/null || continue
fi
echo "" >> enterprise-worktree-report.md
done
cat >> enterprise-worktree-report.md << EOF
## Recommendations
- Regular cleanup of inactive worktrees
- Monitor worktree storage usage
- Implement worktree naming conventions
- Regular backup of worktree configurations
EOF
echo "Enterprise worktree report generated: enterprise-worktree-report.md"
}
# Interactive enterprise management
echo "Enterprise Worktree Management Options:"
echo "1. Setup team worktrees"
echo "2. Monitor team activity"
echo "3. Cleanup inactive worktrees"
echo "4. Generate enterprise report"
read -p "Select option (1-4): " option
case "$option" in
1) setup_team_worktrees ;;
2) monitor_team_activity ;;
3)
read -p "Days threshold (default: 30): " days
cleanup_inactive_worktrees "${days:-30}"
;;
4) generate_enterprise_report ;;
esac
}
enterprise_worktree_management
Terminal window
# Research worktree management
research_worktree_management() {
echo "=== Research and Experimental Development ==="
# Setup research worktrees
setup_research_worktrees() {
echo "Setting up research worktrees..."
# Research categories
categories=("algorithm-research" "performance-testing" "architecture-spikes" "experimental-features")
for category in "${categories[@]}"; do
worktree_path="../research-$category"
if [ ! -d "$worktree_path" ]; then
echo "Creating research worktree: $category"
# Create research branch
research_branch="research/$category"
git branch "$research_branch" main
# Create worktree
git worktree add "$worktree_path" "$research_branch"
# Lock for research protection
git worktree lock --reason "Research worktree: $category" "$worktree_path"
# Initialize research documentation
mkdir -p "$worktree_path/research-docs"
cat > "$worktree_path/research-docs/README.md" << EOF
# Research: $category
## Overview
Research worktree for $category.
## Goals
- [ ] Define research objectives
- [ ] Implement experimental changes
- [ ] Document findings
- [ ] Evaluate results
## Timeline
- Start: $(date)
- Expected completion: TBD
## Notes
Add research notes and findings here.
EOF
echo "Research worktree initialized: $worktree_path"
fi
done
echo "Research worktrees setup complete"
}
# Track research progress
track_research_progress() {
echo "Tracking research progress..."
git worktree list | grep "research" | while read -r worktree branch commit; do
echo "Research worktree: $(basename "$worktree")"
if [ -d "$worktree" ]; then
cd "$worktree" || continue
# Count commits
commit_count=$(git rev-list --count HEAD ^main)
echo " Commits: $commit_count"
# Check documentation
if [ -f "research-docs/README.md" ]; then
doc_lines=$(wc -l < research-docs/README.md)
echo " Documentation: $doc_lines lines"
fi
# Check for experimental code
experimental_files=$(find . -name "*experimental*" -o -name "*research*" | wc -l)
echo " Experimental files: $experimental_files"
cd - >/dev/null || continue
fi
echo
done
}
# Archive completed research
archive_completed_research() {
echo "Archiving completed research worktrees..."
git worktree list | grep "research" | while read -r worktree branch commit; do
worktree_name=$(basename "$worktree")
echo "Checking $worktree_name..."
if [ -d "$worktree" ]; then
cd "$worktree" || continue
# Check if research is complete (has completion marker)
if [ -f "research-docs/COMPLETE" ]; then
echo "Archiving completed research: $worktree_name"
# Create archive
archive_name="research-archive-$worktree_name-$(date +%Y%m%d).tar.gz"
cd ..
tar -czf "$archive_name" "$worktree_name"
cd - >/dev/null || continue
# Remove worktree
git worktree remove -f "$worktree"
echo "Research archived: $archive_name"
else
echo "Research still active: $worktree_name"
fi
cd - >/dev/null || continue
fi
done
echo "Research archiving complete"
}
# Research collaboration setup
setup_research_collaboration() {
echo "Setting up research collaboration..."
# Create shared research branches
shared_topics=("ai-ml-integration" "quantum-computing" "blockchain-security")
for topic in "${shared_topics[@]}"; do
branch_name="research/shared/$topic"
if ! git show-ref --verify --quiet "refs/heads/$branch_name"; then
git branch "$branch_name" main
# Create collaboration worktree
worktree_path="../research-shared-$topic"
git worktree add "$worktree_path" "$branch_name"
# Setup collaboration docs
mkdir -p "$worktree_path/collaboration"
cat > "$worktree_path/collaboration/README.md" << EOF
# Collaborative Research: $topic
## Team Members
- Researcher 1
- Researcher 2
- Researcher 3
## Research Objectives
Define shared research goals here.
## Communication
- Slack channel: #research-$topic
- Weekly meetings: Every Friday 2 PM
- Documentation: This directory
## Progress Tracking
- [ ] Literature review
- [ ] Initial implementation
- [ ] Testing and validation
- [ ] Results analysis
- [ ] Publication preparation
EOF
echo "Collaboration worktree created: $worktree_path"
fi
done
echo "Research collaboration setup complete"