mcpField
C
claude-git-branching

claude-git-branching

github.com/jackspace開発1642 回インストール12 週間前に更新
リポジトリ

claude-git-branching について

Claude Code のセッション向けに、ブランチ規則、再試行付きプッシュ、コミット、プルリクエスト、リポジトリ連携を扱う Git ワークフロースキルです。単一または複数のリポジトリでの AI 支援開発に再利用できる手順を示します。

主な機能

  1. 01Claude 用ブランチ命名規則
  2. 02バックオフ付きプッシュ再試行
  3. 03アトミックコミットと形式
  4. 04プルリクエストの作成と管理
  5. 05複数リポジトリの連携
  6. 06コンフリクト対応とブランチ整理

活用シーン

  1. 01Claude Code セッション用の追跡可能なブランチ作成
  2. 02ネットワーク障害時のプッシュ再試行
  3. 03生成した変更からのプルリクエスト作成
  4. 04複数リポジトリでの機能開発の調整

インストール

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

$npx skills add https://github.com/jackspace/claudeskillz --skill claude-git-branching

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

詳細

Claude Git ブランチ運用

インテリジェントなブランチ運用、リトライロジック、自動 PR 作成を活用して、Claude Code の開発セッションに最適化された Git ワークフローを習得しましょう。

概要

このスキルでは、Claude Code のセッションに特化した、実績のある Git ワークフローを紹介します。以下を含みます。

  • Claude 固有のブランチ命名規則
  • 指数バックオフによる自動プッシュ再試行
  • 複数リポジトリの連携
  • コンフリクトのない共同作業パターン
  • PR の自動作成と管理

使用する場面

次のような場合に、このスキルを使用してください。

  • 新しい Claude Code 開発セッションを開始するとき
  • 複数のセッションにまたがる複数の機能ブランチを管理するとき
  • プッシュ中に断続的なネットワークの問題が発生したとき
  • Claude が生成したコードから PR を作成するとき
  • 複数のリポジトリにまたがる作業を調整するとき
  • AI 支援開発におけるチームの Git 規約に従うとき
  • 長期にわたるセッションでマージコンフリクトに対処するとき

ブランチの命名規則

Claude Code 標準形式
# Standard format
claude/[feature-name]-[session-id]

# Examples
claude/harvest-claude-skills-01MtCwKhDQhWyZCgwfkhdVG5
claude/fix-auth-bug-01NAB2cDE3FgHiJ4KlM5NoPq
claude/add-api-endpoints-01PQRsT6UvWxY7ZaBcD8EfGh

形式の要件:

  • プレフィックス:claude/ で始める必要があります
  • 機能名:作業内容を表すケバブケースの説明
  • セッション ID:セッションを識別する一意の ID
  • 最大長:100 文字を推奨

この形式を使う理由

  • ✅ AI 支援開発であることを明確に示せます
  • ✅ 人間の開発者のブランチとのコンフリクトを防ぎます
  • ✅ 特定のセッションまで追跡できます
  • ✅ フィルタリングと管理が簡単です
  • ✅ GitHub のアクセス制御に対応します(プッシュに必要)
代替形式
# Team-based
claude/[team]/[feature]-[session-id]
claude/backend/api-optimization-01ABC

# Priority-based
claude/[priority]/[feature]-[session-id]
claude/urgent/security-patch-01DEF

# Issue-based
claude/issue-[number]-[session-id]
claude/issue-1234-01GHI

ブランチ作成のワークフロー

ステップ 1:現在の状態を確認する
# Verify current branch
git branch --show-current

# Check status
git status

# View recent branches
git branch -a | grep "claude/" | head -10
ステップ 2:機能ブランチを作成する
# From main/master
git checkout main
git pull origin main

# Create Claude branch
FEATURE="add-user-authentication"
SESSION_ID="01MtCwKhDQhWyZCgwfkhdVG5"
BRANCH="claude/${FEATURE}-${SESSION_ID}"

git checkout -b "$BRANCH"
echo "Created branch: $BRANCH"
ステップ 3:ブランチ名を確認する
# Ensure proper format
CURRENT_BRANCH=$(git branch --show-current)

if [[ ! "$CURRENT_BRANCH" =~ ^claude/.+-[0-9A-Za-z]{20,}$ ]]; then
    echo "⚠️  Warning: Branch name doesn't match Claude format"
    echo "Expected: claude/[feature-name]-[session-id]"
    echo "Got: $CURRENT_BRANCH"
fi

リトライロジックを使ったプッシュ

標準的なプッシュパターン
#!/bin/bash
# push-with-retry.sh - Push with exponential backoff

BRANCH=$(git branch --show-current)
MAX_RETRIES=4
RETRY_COUNT=0
DELAYS=(2 4 8 16)  # Exponential backoff in seconds

echo "Pushing branch: $BRANCH"

while [ $RETRY_COUNT -lt $MAX_RETRIES ]; do
    if git push -u origin "$BRANCH"; then
        echo "✓ Successfully pushed to origin/$BRANCH"
        exit 0
    else
        EXIT_CODE=$?
        RETRY_COUNT=$((RETRY_COUNT + 1))

        # Check if it's a 403 error (branch name issue)
        if git push -u origin "$BRANCH" 2>&1 | grep -q "403"; then
            echo "✗ Push failed with 403 - Check branch naming convention"
            echo "Branch must start with 'claude/' and end with session ID"
            exit 1
        fi

        if [ $RETRY_COUNT -lt $MAX_RETRIES ]; then
            DELAY=${DELAYS[$RETRY_COUNT-1]}
            echo "⚠️  Push failed (attempt $RETRY_COUNT/$MAX_RETRIES)"
            echo "Retrying in ${DELAY}s..."
            sleep $DELAY
        fi
    fi
done

echo "✗ Push failed after $MAX_RETRIES attempts"
exit 1

使用方法:

chmod +x push-with-retry.sh
./push-with-retry.sh
インラインのリトライパターン
# Quick inline version
for i in {1..4}; do
    if git push -u origin $(git branch --show-current); then
        echo "✓ Pushed successfully"
        break
    else
        [ $i -lt 4 ] && echo "Retry $i/4..." && sleep $((2**i))
    fi
done

コミットのベストプラクティス

アトミックコミット
# Make focused, atomic commits
git add src/auth/login.ts
git commit -m "feat: Add JWT-based login authentication"

git add src/auth/middleware.ts
git commit -m "feat: Add auth middleware for protected routes"

git add tests/auth.test.ts
git commit -m "test: Add authentication test suite"
コミットメッセージの形式
# Format: <type>: <description>
# Types: feat, fix, docs, refactor, test, chore, style, perf

git commit -m "$(cat <<'EOF'
feat: Add user authentication system

- Implement JWT-based authentication
- Add login/logout endpoints
- Create auth middleware
- Add session management

Closes #123
EOF
)"
Conventional Commits
# Feature
git commit -m "feat(auth): Add JWT authentication"

# Bug fix
git commit -m "fix(api): Handle null user in middleware"

# Documentation
git commit -m "docs(readme): Update authentication setup"

# Refactoring
git commit -m "refactor(auth): Extract token validation logic"

# Breaking change
git commit -m "feat(api)!: Change auth response format

BREAKING CHANGE: Auth response now returns user object instead of ID"

プルリクエストの作成

PR の自動作成
#!/bin/bash
# create-pr.sh - Create PR with gh CLI

BRANCH=$(git branch --show-current)
BASE_BRANCH="${1:-main}"

# Ensure we're on a Claude branch
if [[ ! "$BRANCH" =~ ^claude/ ]]; then
    echo "⚠️  Warning: Not on a Claude branch"
    read -p "Continue anyway? (y/n) " -n 1 -r
    echo
    [[ ! $REPLY =~ ^[Yy]$ ]] && exit 1
fi

# Get commit history since divergence
COMMITS=$(git log ${BASE_BRANCH}...HEAD --oneline)
DIFF_STAT=$(git diff ${BASE_BRANCH}...HEAD --stat)

# Analyze changes
FILES_CHANGED=$(git diff ${BASE_BRANCH}...HEAD --name-only | wc -l)
LINES_ADDED=$(git diff ${BASE_BRANCH}...HEAD --numstat | awk '{sum+=$1} END {print sum}')
LINES_REMOVED=$(git diff ${BASE_BRANCH}...HEAD --numstat | awk '{sum+=$2} END {print sum}')

echo "=== PR Summary ==="
echo "Branch: $BRANCH"
echo "Base: $BASE_BRANCH"
echo "Files changed: $FILES_CHANGED"
echo "Lines added: $LINES_ADDED"
echo "Lines removed: $LINES_REMOVED"
echo ""

# Extract feature description from branch name
FEATURE=$(echo "$BRANCH" | sed 's/claude\/\(.*\)-[0-9A-Za-z]\{20,\}/\1/' | tr '-' ' ')
TITLE="feat: ${FEATURE^}"

# Create PR body
PR_BODY="$(cat <<EOF
## Summary

This PR implements ${FEATURE}.

### Changes
$(git log ${BASE_BRANCH}...HEAD --pretty=format:"- %s" | head -10)

### Stats
- **Files changed**: $FILES_CHANGED
- **Lines added**: $LINES_ADDED
- **Lines removed**: $LINES_REMOVED

### Test Plan
- [ ] Code builds successfully
- [ ] Tests pass
- [ ] Manual testing completed
- [ ] Documentation updated

### Checklist
- [ ] Code follows project conventions
- [ ] No console errors or warnings
- [ ] Security considerations reviewed
- [ ] Performance impact assessed

---
*Generated by Claude Code session*
EOF
)"

# Push if needed
echo "Ensuring branch is pushed..."
git push -u origin "$BRANCH" 2>&1 | grep -v "up-to-date" || true

# Create PR
echo ""
echo "Creating pull request..."
gh pr create \
    --base "$BASE_BRANCH" \
    --head "$BRANCH" \
    --title "$TITLE" \
    --body "$PR_BODY"

if [ $? -eq 0 ]; then
    echo "✓ PR created successfully"
    gh pr view --web
else
    echo "✗ Failed to create PR"
    exit 1
fi
PR テンプレート


## Description


## Type of Change
- [ ] 🎯 New feature
- [ ] 🐛 Bug fix
- [ ] 📚 Documentation update
- [ ] ♻️ Refactoring
- [ ] ⚡ Performance improvement
- [ ] ✅ Test addition/update

## Claude Code Session
- **Branch**: `[branch-name]`
- **Session ID**: `[session-id]`
- **Duration**: `[time spent]`

## Changes Made
- Change 1
- Change 2
- Change 3

## Testing
- [ ] Unit tests added/updated
- [ ] Integration tests pass
- [ ] Manual testing completed
- [ ] No regressions identified

## Checklist
- [ ] Code follows project style guide
- [ ] Self-review completed
- [ ] Comments added for complex logic
- [ ] Documentation updated
- [ ] No new warnings introduced

## Screenshots (if applicable)


## Related Issues

複数リポジトリの管理

リポジトリ間の連携
#!/bin/bash
# sync-multi-repo.sh - Sync work across multiple repositories

REPOS=(
    "/path/to/frontend"
    "/path/to/backend"
    "/path/to/shared-lib"
)

BRANCH_PREFIX="claude/sync-auth-update"
SESSION_ID="01MtCwKhDQhWyZCgwfkhdVG5"

for REPO in "${REPOS[@]}"; do
    echo "=== Processing: $REPO ==="
    cd "$REPO" || continue

    REPO_NAME=$(basename "$REPO")
    BRANCH="${BRANCH_PREFIX}-${REPO_NAME}-${SESSION_ID}"

    # Create branch
    git checkout -b "$BRANCH" 2>/dev/null || git checkout "$BRANCH"

    echo "Ready for changes in: $BRANCH"
    echo ""
done
一括コミットとプッシュ
#!/bin/bash
# commit-multi-repo.sh - Commit across multiple repos

REPOS=("frontend" "backend" "shared-lib")
COMMIT_MSG="$1"

if [ -z "$COMMIT_MSG" ]; then
    echo "Usage: $0 <commit-message>"
    exit 1
fi

for REPO in "${REPOS[@]}"; do
    echo "=== $REPO ==="
    cd "$REPO" || continue

    # Check if there are changes
    if [ -n "$(git status --porcelain)" ]; then
        git add .
        git commit -m "$COMMIT_MSG"

        # Push with retry
        for i in {1..4}; do
            if git push -u origin $(git branch --show-current); then
                echo "✓ Pushed $REPO"
                break
            else
                [ $i -lt 4 ] && sleep $((2**i))
            fi
        done
    else
        echo "No changes in $REPO"
    fi

    cd - > /dev/null
    echo ""
done

コンフリクトの解決

マージ前のコンフリクト検出
# Before merging, check for conflicts
git fetch origin main
git merge-base origin/main HEAD
git diff origin/main...HEAD --name-only

# Test merge without committing
git merge --no-commit --no-ff origin/main

# If conflicts, abort and review
git merge --abort
コンフリクト解決のワークフロー
#!/bin/bash
# resolve-conflicts.sh

# Update main
git fetch origin main

# Attempt merge
if git merge origin/main; then
    echo "✓ Merged cleanly"
else
    echo "⚠️  Conflicts detected"

    # Show conflicts
    git diff --name-only --diff-filter=U

    # For each conflict
    git status | grep "both modified" | awk '{print $3}' | while read file; do
        echo ""
        echo "=== Conflict in: $file ==="

        # Show conflict markers
        grep -n "<<<<<<< HEAD" "$file"

        # Options
        echo "1) Keep ours (current branch)"
        echo "2) Keep theirs (main)"
        echo "3) Manual edit"

        read -p "Choose (1-3): " choice

        case $choice in
            1) git checkout --ours "$file" && git add "$file" ;;
            2) git checkout --theirs "$file" && git add "$file" ;;
            3) ${EDITOR:-vim} "$file" ;;
        esac
    done

    # Complete merge
    git commit -m "Merge branch 'main' and resolve conflicts"
fi
履歴を整理するためのリベース
# Interactive rebase to clean up commits
git fetch origin main
git rebase -i origin/main

# Squash related commits
# pick abc1234 feat: Add auth
# squash def5678 fix: Auth typo
# squash ghi9012 refactor: Auth cleanup

# Force push (only on feature branches!)
git push --force-with-lease origin $(git branch --show-current)

ブランチ管理

Claude ブランチの一覧表示
# Local Claude branches
git branch | grep "claude/"

# Remote Claude branches
git branch -r | grep "claude/"

# With last commit date
git for-each-ref --sort=-committerdate refs/heads/claude/ \
    --format='%(committerdate:short) %(refname:short) %(subject)'
古いブランチのクリーンアップ
#!/bin/bash
# cleanup-claude-branches.sh - Remove merged Claude branches

# Delete local branches that are merged
git branch --merged main | grep "claude/" | while read branch; do
    echo "Deleting merged branch: $branch"
    git branch -d "$branch"
done

# Delete remote branches (be careful!)
read -p "Delete remote merged branches? (y/n) " -n 1 -r
echo
if [[ $REPLY =~ ^[Yy]$ ]]; then
    git branch -r --merged main | grep "claude/" | sed 's/origin\///' | while read branch; do
        echo "Deleting remote branch: $branch"
        git push origin --delete "$branch"
    done
fi
完了した作業のアーカイブ
# Tag before deleting
git tag archive/claude-2025-11-18 claude/feature-name-session123
git push origin archive/claude-2025-11-18
git branch -d claude/feature-name-session123

Claude セッション向けの Git 設定

推奨設定
# Set credentials helper
git config --local credential.helper store

# Set push default
git config --local push.default current

# Auto-setup remote tracking
git config --local push.autoSetupRemote true

# Rebase by default when pulling
git config --local pull.rebase true

# Show branch in prompt
git config --local oh-my-zsh.hide-status 0
セッション固有の設定
# Create .git/config settings for Claude sessions
cat >> .git/config << EOF

[branch "claude/*"]
    # Auto-setup upstream
    autoSetupMerge = always

[remote "origin"]
    # Fetch all claude branches
    fetch = +refs/heads/claude/*:refs/remotes/origin/claude/*
EOF

トラブルシューティング

問題 1:プッシュ時の 403 エラー

症状:

error: failed to push some refs to 'https://github.com/user/repo.git'
! [remote rejected] claude/feature-abc123 (permission denied)

原因: ブランチ名が、必須の claude/*-[session-id] 形式と一致していません

解決策:

# Check current branch name
CURRENT=$(git branch --show-current)
echo "Current: $CURRENT"

# Rename if needed
SESSION_ID="01MtCwKhDQhWyZCgwfkhdVG5"
NEW_BRANCH="claude/feature-name-${SESSION_ID}"
git branch -m "$CURRENT" "$NEW_BRANCH"

# Push with new name
git push -u origin "$NEW_BRANCH"
問題 2:プッシュ中のネットワークタイムアウト

症状:

fatal: the remote end hung up unexpectedly
error: failed to push some refs

原因: 断続的なネットワークの問題

解決策: リトライロジックを使用してください(「リトライロジックを使ったプッシュ」セクションを参照)

問題 3:ブランチの履歴が分岐している

症状:

hint: You have divergent branches and need to specify how to reconcile them.

原因: ローカルブランチとリモートブランチで履歴が異なっています

解決策:

# Option 1: Rebase (cleaner history)
git pull --rebase origin $(git branch --show-current)

# Option 2: Merge (preserves all history)
git pull --no-rebase origin $(git branch --show-current)

# Option 3: Reset to remote (discard local changes)
git reset --hard origin/$(git branch --show-current)

ベストプラクティス

✅ 実施すること
  1. セッションブランチには必ず claude/ プレフィックスを使用する
  2. ブランチ名にセッション ID を含める
  3. ネットワーク障害に備え、リトライロジックを使ってプッシュする
  4. 明確なメッセージを付けてアトミックコミットを作成する
  5. 履歴を整理するため、PR の前にリベースする
  6. ビルドの失敗を防ぐため、プッシュ前にテストする
  7. 履歴を明確にするため、Conventional Commits を使用する
  8. マージ済みのブランチを定期的にクリーンアップする
❌ 避けること
  1. シークレットや認証情報をコミットしない
  2. main/master に強制プッシュしない
  3. セッション ID のない汎用的なブランチ名を作成しない
  4. コミットメッセージを省略したり、プレースホルダーを使ったりしない
  5. 未解決のコンフリクトをコミットに残さない
  6. LFS を使わずに大きなバイナリファイルをコミットしない
  7. 十分な理由なく CI チェックを回避しない
  8. 無関係な変更を 1 つのコミットにまとめない

クイックリファレンス

よく使うコマンド
# Create Claude branch
git checkout -b claude/feature-name-$(date +%s)

# Push with retry
for i in {1..4}; do git push -u origin $(git branch --show-current) && break || sleep $((2**i)); done

# Create PR
gh pr create --title "feat: Description" --body "Details here"

# Clean merged branches
git branch --merged main | grep "claude/" | xargs git branch -d

# Show branch stats
git log main..HEAD --oneline --stat

# Squash last 3 commits
git rebase -i HEAD~3
ワークフロー早見表
  1. 開始:git checkout -b claude/[feature]-[session-id]
  2. 作業:変更を加え、アトミックにコミットします
  3. プッシュ:git push -u origin $(git branch --show-current)(リトライ付き)
  4. PR:gh pr create を実行するか、GitHub の UI を使用します
  5. マージ:GitHub でスカッシュしてマージします
  6. クリーンアップ:git branch -d claude/[feature]-[session-id]

バージョン:1.0.0 作成者:your_claude_skills リポジトリから収集 最終更新日:2025-11-18 ライセンス:MIT

Claude Code との連携

このスキルは Claude Code のワークフローにシームレスに統合されます。

  • セッション開始時にブランチ名を自動的に提案します
  • 不安定なネットワーク向けのリトライロジックを提供します
  • コミット履歴から PR の説明を生成します
  • 複数のリポジトリ間の連携を処理します
  • 古いブランチのクリーンアップを管理します

Git のワークフローを最適に管理するため、Claude Code の各セッション開始時にこのスキルを使用してください! 🚀

コメント