"worktree作成", "create a worktree", "並行開発環境", "ブランチを隔離して作業"といった操作や、Agent Teamが隔離された開発環境を必要とする場面で使用する。.worktrees/配下にworktreeを作成し、依存関係のセットアップまで行う。
プロジェクトルートの .worktrees/ にworktreeを作成・管理する。
# gh CLIがインストール・認証済みか確認
gh auth status
gh CLIが利用できない場合はエラーを報告し、インストール・認証を促す。
project_root=$(git rev-parse --show-toplevel)
cd "$project_root"
original_branch=$(git branch --show-current)
# 未コミットの変更がないか確認
if ! git diff --quiet || ! git diff --cached --quiet; then
echo "未コミットの変更があります。stashしてから続行します。"
git stash push -m "auto-stash before worktree creation"
fi
git fetch origin
base_branch=$(gh repo view --json defaultBranchRef -q '.defaultBranchRef.name')
git checkout "$base_branch"
git pull origin "$base_branch"
mkdir -p "$project_root/.worktrees"
# .gitignoreに.worktrees/がなければ追加
if ! git check-ignore -q .worktrees 2>/dev/null; then
echo ".worktrees/" >> .gitignore
git add .gitignore
git commit -m "chore: add .worktrees/ to .gitignore"
fi
branch_name="<feature-branch-name>"
git worktree add "$project_root/.worktrees/$branch_name" -b "$branch_name"
cd "$project_root/.worktrees/$branch_name"
worktreeディレクトリ($project_root/.worktrees/$branch_name)で、プロジェクトに応じて自動検出・実行(該当ファイルがない場合はスキップ):
cd "$project_root/.worktrees/$branch_name"
| ファイル | コマンド |
|---|---|
| package.json | npm install |
| Cargo.toml | cargo fetch |
| requirements.txt | pip install -r requirements.txt |
| pyproject.toml | poetry install |
| go.mod | go mod download |
worktreeが正常かを確認するため、テストを実行して結果を報告する。
# Step 2でstashした場合、元のブランチに戻してstashを復元
cd "$project_root"
git checkout "$original_branch"
git stash pop
feat/<short-description> — 新機能fix/<short-description> — バグ修正refactor/<short-description> — リファクタリングdocs/<short-description> — ドキュメントgit worktree remove "$project_root/.worktrees/$branch_name"
.worktrees/ 配下に作成するgh repo view でベースを特定し、fetch + pullしてから作成gh CLIが利用可能であることを事前に確認する