mcpField
G
git-worktree

git-worktree

github.com/julianobarbosa開発15109 回インストール今日更新
リポジトリ

git-worktree について

git-worktreeは、Git worktreeで並行開発環境を管理するスキルです。複数のタスクやClaude Codeのインスタンスを扱う開発者向けに、tmuxまたはiTerm2と連携して作業ディレクトリを分離し、タスクを切り替えられます。

主な機能

  1. 01Git worktreeの作成と管理
  2. 02tmuxウィンドウ・セッションとの連携
  3. 03iTerm2タブとの連携
  4. 04Claude Codeの並行開発への対応
  5. 05クリーンアップとトラブル対応手順

活用シーン

  1. 01複数の機能ブランチを並行開発
  2. 02ブランチ切り替えや未コミット変更の退避を回避
  3. 03マージ後のworktreeを整理

インストール

コマンドをコピーしてターミナルで実行します。

$npx skills add https://github.com/julianobarbosa/claude-code-skills --skill git-worktree

インストール後、Claude Code で/git-worktreeを入力して読み込まれたか確認します。

同梱ファイル

SKILL.md と一緒にインストールされる参考資料やスクリプト。

references/
functions.sh
iterm2-config.md
tmux-config.md

詳細

Git Worktree スキル

シームレスなターミナル連携を使って、Git worktree で並行開発環境を管理します。

概要

Git worktree を使うと、1 つのリポジトリから複数の作業ディレクトリを作成できます。

  • ブランチを切り替えずに、分離された機能開発を行えます
  • 複数の Claude Code インスタンスを並行して実行できます
  • 未コミットの変更を stash せずに、コンテキストを切り替えられます
  • 実験的な作業を明確に分離できます

クイックコマンド

wt - Worktree マネージャー

wt コマンドは、ターミナルとの自動連携機能を備えた worktree を作成します。

# Create worktree with tmux window
wt add-new-feature

# This will:
# 1. Create git worktree named 'add-new-feature'
# 2. Create new tmux window in current session
# 3. Rename window to 'add-new-feature'
# 4. Change directory to the worktree

tmux 連携

ワークフロー:Worktree と tmux ウィンドウの作成
# Function for ~/.zshrc or ~/.bashrc
wt() {
    local name="$1"
    local base_branch="${2:-main}"
    local repo_root=$(git rev-parse --show-toplevel 2>/dev/null)
    local worktree_path="$repo_root/.worktrees/$name"

    # Validate we're in a git repo
    if [[ -z "$repo_root" ]]; then
        echo "Error: Not in a git repository"
        return 1
    fi

    # Create worktree directory
    mkdir -p "$repo_root/.worktrees"

    # Create worktree with new branch
    if git worktree add -b "$name" "$worktree_path" "$base_branch" 2>/dev/null; then
        echo "Created worktree: $worktree_path"
    elif git worktree add "$worktree_path" "$name" 2>/dev/null; then
        echo "Attached to existing branch: $name"
    else
        echo "Error: Failed to create worktree"
        return 1
    fi

    # tmux integration
    if [[ -n "$TMUX" ]]; then
        # Create new window with worktree name
        tmux new-window -n "$name" -c "$worktree_path"
        echo "Created tmux window: $name"
    else
        # Not in tmux, just cd
        cd "$worktree_path"
        echo "Changed to: $worktree_path"
    fi
}

# Remove worktree and tmux window
wt-rm() {
    local name="$1"
    local repo_root=$(git rev-parse --show-toplevel 2>/dev/null)
    local worktree_path="$repo_root/.worktrees/$name"

    # Remove git worktree
    git worktree remove "$worktree_path" --force 2>/dev/null

    # Close tmux window if exists
    if [[ -n "$TMUX" ]]; then
        tmux kill-window -t "$name" 2>/dev/null
    fi

    # Optionally delete branch
    git branch -d "$name" 2>/dev/null

    echo "Removed worktree: $name"
}

# List all worktrees
wt-ls() {
    git worktree list
}
tmux セッションの管理
# Create dedicated tmux session per project
wt-session() {
    local name="$1"
    local repo_root=$(git rev-parse --show-toplevel 2>/dev/null)
    local worktree_path="$repo_root/.worktrees/$name"

    # Create worktree first
    wt "$name"

    # Create new tmux session (or attach if exists)
    if tmux has-session -t "$name" 2>/dev/null; then
        tmux attach-session -t "$name"
    else
        tmux new-session -d -s "$name" -c "$worktree_path"
        tmux attach-session -t "$name"
    fi
}

iTerm2 連携

iTerm2 タブ用 AppleScript
# Function for ~/.zshrc
wt-iterm() {
    local name="$1"
    local base_branch="${2:-main}"
    local repo_root=$(git rev-parse --show-toplevel 2>/dev/null)
    local worktree_path="$repo_root/.worktrees/$name"

    # Create worktree
    mkdir -p "$repo_root/.worktrees"
    git worktree add -b "$name" "$worktree_path" "$base_branch" 2>/dev/null || \
    git worktree add "$worktree_path" "$name" 2>/dev/null

    # Open in new iTerm2 tab
    osascript <<EOF
tell application "iTerm2"
    tell current window
        create tab with default profile
        tell current session
            write text "cd '$worktree_path' && clear"
        end tell
    end tell
end tell
EOF

    echo "Created worktree with iTerm2 tab: $name"
}

# Open worktree in new iTerm2 window
wt-iterm-window() {
    local name="$1"
    local base_branch="${2:-main}"
    local repo_root=$(git rev-parse --show-toplevel 2>/dev/null)
    local worktree_path="$repo_root/.worktrees/$name"

    # Create worktree
    mkdir -p "$repo_root/.worktrees"
    git worktree add -b "$name" "$worktree_path" "$base_branch" 2>/dev/null || \
    git worktree add "$worktree_path" "$name" 2>/dev/null

    # Open in new iTerm2 window
    osascript <<EOF
tell application "iTerm2"
    create window with default profile
    tell current session of current window
        write text "cd '$worktree_path' && clear"
    end tell
end tell
EOF

    echo "Created worktree with iTerm2 window: $name"
}
iTerm2 プロファイルとの連携

worktree 用の専用 iTerm2 プロファイルを作成します。

{
  "Name": "Worktree",
  "Badge Text": "WT: \\(session.name)",
  "Working Directory": "$HOME/.worktrees",
  "Custom Directory": "Yes"
}

設定

環境変数
# Add to ~/.zshrc or ~/.bashrc

# Preferred terminal for worktree operations (auto-detected if not set)
export WORKTREE_TERMINAL="tmux"  # or "iterm2" or "auto"

# Auto-install dependencies after creating worktree
export WORKTREE_AUTO_INSTALL=true
Worktree の保存場所

worktree はプロジェクトディレクトリ内に保存されます。

~/Repos/github/my-project/
├── .worktrees/
│   ├── feature-auth/      # worktree for feature-auth branch
│   ├── bugfix-login/      # worktree for bugfix-login branch
│   └── add-new-skill/     # worktree for add-new-skill branch
├── src/
├── package.json
└── ...
シェルの設定

関数は ~/.zsh/functions.zsh で定義されています(すでに zshrc で読み込み済みです)。

# Functions location: ~/.zsh/functions.zsh

# Aliases
alias wt='wt'
alias wtl='wt-ls'
alias wtr='wt-rm'
alias wts='wt-session'

# Completion for wt commands
_wt_completion() {
    local branches=$(git branch --format='%(refname:short)' 2>/dev/null)
    local worktrees=$(git worktree list --porcelain 2>/dev/null | grep '^worktree' | cut -d' ' -f2 | xargs -I{} basename {})
    _alternative \
        "branches:branch:($branches)" \
        "worktrees:worktree:($worktrees)"
}
compdef _wt_completion wt wt-rm

Git Worktree コマンドのリファレンス

Worktree の作成
# Create worktree with new branch from current HEAD
git worktree add ../feature-x -b feature-x

# Create worktree from specific branch
git worktree add ../hotfix hotfix-branch

# Create worktree from remote branch
git worktree add ../upstream upstream/main

# Create worktree at specific commit
git worktree add ../review abc123
Worktree の管理
# List all worktrees
git worktree list

# Show worktree details (porcelain format)
git worktree list --porcelain

# Lock worktree (prevent pruning)
git worktree lock ../feature-x --reason "WIP"

# Unlock worktree
git worktree unlock ../feature-x

# Remove worktree
git worktree remove ../feature-x

# Force remove (discards changes)
git worktree remove ../feature-x --force

# Prune stale worktrees
git worktree prune
高度な操作
# Move worktree to new location
git worktree move ../old-path ../new-path

# Repair worktree after manual move
git worktree repair ../moved-worktree

Claude の並行開発

複数のインスタンスの実行
# Create worktrees for parallel development
wt feature-auth
wt feature-api
wt bugfix-login

# Each worktree gets its own:
# - tmux window / iTerm2 tab
# - Git index and working directory
# - Port allocation (if configured)
# - Claude Code instance
ポートの管理
# Configure port pools per worktree
export WORKTREE_PORT_BASE=8100
export WORKTREE_PORTS_PER_TREE=2

# Calculate ports for worktree
get_worktree_ports() {
    local index=$(git worktree list | grep -n "$PWD" | cut -d: -f1)
    local base=$((WORKTREE_PORT_BASE + (index - 1) * WORKTREE_PORTS_PER_TREE))
    echo "Dev server: $base, API: $((base + 1))"
}

クリーンアップのワークフロー

マージとクリーンアップ
# After PR merge, clean up worktree
wt-cleanup() {
    local name="$1"
    local repo_root=$(git rev-parse --show-toplevel 2>/dev/null)
    local worktree_path="$repo_root/.worktrees/$name"

    # Switch to main worktree
    cd "$repo_root"

    # Update main
    git fetch origin
    git pull origin main

    # Remove worktree
    git worktree remove "$worktree_path" --force

    # Delete branch if merged
    if git branch --merged | grep -q "$name"; then
        git branch -d "$name"
        echo "Branch $name was merged and deleted"
    else
        echo "Branch $name not yet merged, kept locally"
    fi

    # Close tmux window
    [[ -n "$TMUX" ]] && tmux kill-window -t "$name" 2>/dev/null
}
一括クリーンアップ
# Remove all worktrees with merged branches
wt-cleanup-merged() {
    local main_dir=$(git worktree list | head -1 | awk '{print $1}')

    git worktree list | tail -n +2 | while read -r line; do
        local wt_path=$(echo "$line" | awk '{print $1}')
        local wt_branch=$(echo "$line" | awk '{print $3}' | tr -d '[]')

        if git branch --merged main | grep -q "$wt_branch"; then
            echo "Removing merged worktree: $wt_branch"
            git worktree remove "$wt_path" --force
            git branch -d "$wt_branch"
        fi
    done
}

トラブルシューティング

よくある問題

Worktree がすでに存在する場合:

# List existing worktrees
git worktree list

# Remove stale entry
git worktree prune

ブランチがすでにチェックアウトされている場合:

# Error: 'branch' is already checked out at '/path'
# Solution: Use a different branch name or remove existing worktree
git worktree remove /path/to/existing

tmux ウィンドウ名が競合する場合:

# Rename existing window first
tmux rename-window -t old-name new-name

# Or kill conflicting window
tmux kill-window -t conflicting-name

iTerm2 AppleScript のエラー:

# Ensure iTerm2 is running
open -a iTerm

# Grant automation permissions
# System Preferences > Security & Privacy > Privacy > Automation

参考資料

外部リンク


注意点

  • Worktree のパスがメインリポジトリの作業ツリー内にあると、外側の git status の結果が分かりにくくなります — 内側の worktree 内のファイルは、親リポジトリでは未追跡ファイルとして表示されます。
  • いずれかの worktree でチェックアウトされているブランチには、git branch -d を実行できません — 先に worktree を削除する必要があります。
  • Worktree 間で .git/config は共有されます — worktree ごとの設定には、明示的に git config --worktree を使用する必要があります。
  • git worktree prune は孤立した記録を削除しますが、ディレクトリは削除しません — prune の後、手動でディレクトリをクリーンアップしてください。
  • Worktree をロックしても、ファイルシステム操作は防止されません — git worktree lock がブロックするのは git worktree remove のみです。rm -rf は引き続き実行できます。
  • macOS の大文字と小文字を区別しないファイルシステムと worktree:大文字・小文字だけが異なるパスを持つ 2 つの worktree を作成すると、Git の動作が予測不能になります。

コメント