关于 claude-git-branching
面向 Claude Code 会话的 Git 工作流技能,涵盖分支约定、推送重试、提交、拉取请求和仓库协作。它为单个或多个仓库中的 AI 辅助开发提供可复用流程。
主要功能
- 01Claude 分支命名约定
- 02带退避机制的推送重试
- 03原子提交与提交格式
- 04创建和管理拉取请求
- 05多仓库协作
- 06冲突处理与分支清理
适用场景
- 01为 Claude Code 会话创建可追踪分支
- 02在网络中断时重试推送
- 03为生成的代码创建拉取请求
- 04跨仓库协调功能开发
安装
复制下面的命令,在终端中运行。
$
npx skills add https:/ / github.com/ jackspace/ claudeskillz --skill claude-git-branching安装后在 Claude Code 中输入/claude-git-branching确认已加载。
详细介绍
Claude Git 分支管理
掌握针对 Claude Code 开发会话优化的 Git 工作流,包含智能分支管理、重试逻辑和自动创建 PR。
概述
此技能提供经过实战检验的 Git 工作流,专为 Claude Code 会话设计,包括:
- 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/开头 - 功能名称:以 kebab-case 格式描述工作内容
- 会话 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
)"
约定式提交
# 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)
最佳实践
✅ 应该做
- 会话分支始终使用 claude/ 前缀
- 在分支名称中包含会话 ID
- 推送时使用重试逻辑,增强网络容错能力
- 创建带有清晰消息的原子提交
- 创建 PR 前进行变基,整理历史记录
- 推送前进行测试,避免构建失败
- 使用约定式提交,保持历史记录清晰
- 定期清理已合并的分支
❌ 不应该做
- 不要提交机密信息或凭据
- 不要对 main/master 强制推送
- 不要创建缺少会话 ID 的通用分支名称
- 不要省略提交消息或使用占位符
- 不要在提交中遗留未解决的冲突
- 不要在未使用 LFS 的情况下提交大型二进制文件
- 不要无正当理由绕过 CI 检查
- 不要在单次提交中混合无关更改
快速参考
常用命令
# 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
工作流速查表
- 开始:
git checkout -b claude/[feature]-[session-id] - 工作:进行更改,原子化提交
- 推送:
git push -u origin $(git branch --show-current)(失败时重试) - PR:运行
gh pr create或使用 GitHub UI - 合并:通过 GitHub 压缩并合并
- 清理:
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 会话开始时使用此技能!🚀
评论
支持 Markdown