mcpField
G
git-repository

git-repository

github.com/geoffjay开发864 次安装52 周前更新
代码仓库

关于 git-repository

面向团队的 Git 仓库管理技能,涵盖工作流选择与仓库组织。内容包括分支策略、单仓库与多仓库、扩展维护、访问控制和迁移。

主要功能

  1. 01分支策略指南
  2. 02单仓库与多仓库规划
  3. 03子模块与子树工作流
  4. 04大型仓库管理
  5. 05维护与迁移指南

适用场景

  1. 01为团队选择分支模型
  2. 02规划单仓库或多仓库
  3. 03管理大型仓库和共享代码
  4. 04准备仓库维护或迁移

安装

复制下面的命令,在终端中运行。

$npx skills add https://github.com/geoffjay/claude-plugins --skill git-repository

安装后在 Claude Code 中输入/git-repository确认已加载。

详细介绍

Git 仓库管理技能

本技能全面介绍仓库管理策略、分支模型、仓库组织模式,以及如何为大型团队和代码库扩展 Git。

使用时机

在以下情况下启用此技能:

  • 设置新的仓库结构
  • 选择分支策略
  • 管理单体仓库与多仓库
  • 组织多项目仓库
  • 实施子模块或子树策略
  • 为大型团队扩展 Git
  • 迁移仓库结构
  • 建立团队工作流

分支策略

Git Flow

分支结构:

  • main(或 master)——仅用于生产发布
  • develop——下一个版本的集成分支
  • feature/*——功能开发分支
  • release/*——发布准备分支
  • hotfix/*——紧急生产修复分支

工作流:

# Feature Development
git checkout develop
git checkout -b feature/user-authentication
# Work on feature...
git commit -m "feat: add JWT authentication"
git checkout develop
git merge --no-ff feature/user-authentication
git branch -d feature/user-authentication

# Release Preparation
git checkout develop
git checkout -b release/v1.2.0
# Bump version, update changelog, final testing...
git commit -m "chore: prepare release v1.2.0"

# Deploy Release
git checkout main
git merge --no-ff release/v1.2.0
git tag -a v1.2.0 -m "Release version 1.2.0"
git checkout develop
git merge --no-ff release/v1.2.0
git branch -d release/v1.2.0
git push origin main develop --tags

# Hotfix
git checkout main
git checkout -b hotfix/security-patch
git commit -m "fix: patch security vulnerability"
git checkout main
git merge --no-ff hotfix/security-patch
git tag -a v1.2.1 -m "Hotfix v1.2.1"
git checkout develop
git merge --no-ff hotfix/security-patch
git branch -d hotfix/security-patch
git push origin main develop --tags

适用场景:

  • 定期发布
  • 有多个生产版本
  • 有 QA 流程的大型团队
  • 有维护窗口的产品
  • 企业软件

缺点:

  • 工作流复杂
  • 分支生命周期长
  • 可能产生合并冲突
  • 集成延迟
GitHub Flow

分支结构:

  • main——可用于生产的代码(始终可部署)
  • feature/*——所有功能和修复分支

工作流:

# Create Feature Branch
git checkout main
git pull origin main
git checkout -b feature/add-api-logging

# Develop Feature
git commit -m "feat: add structured logging middleware"
git push -u origin feature/add-api-logging

# Open Pull Request on GitHub
# Review, discuss, CI passes

# Merge and Deploy
# Merge PR on GitHub
# Automatic deployment from main

# Cleanup
git checkout main
git pull origin main
git branch -d feature/add-api-logging

适用场景:

  • 持续部署
  • 小型至中型团队
  • Web 应用
  • 快速迭代
  • 云原生应用

缺点:

  • 需要完善的 CI/CD
  • 没有发布暂存阶段
  • 结构不如 Git Flow 严谨
主干开发

分支结构:

  • main(或 trunk)——唯一真实来源
  • 生命周期较短的功能分支(少于 2 天,可选)
  • 用于未完成工作的功能标记

工作流:

# Direct Commit to Main (Small Changes)
git checkout main
git pull origin main
# Make small change...
git commit -m "fix: correct validation logic"
git push origin main

# Short-Lived Branch (Larger Changes)
git checkout -b optimize-query
# Work for < 1 day
git commit -m "perf: optimize database query"
git push -u origin optimize-query
# Immediate PR, quick review, merge same day

# Feature Flags for Incomplete Features
git checkout main
git commit -m "feat: add payment gateway (behind feature flag)"
# Feature disabled in production until complete
git push origin main

适用场景:

  • 高效率团队
  • 持续集成
  • 自动化测试
  • 功能标记基础设施
  • DevOps 文化

缺点:

  • 需要严格遵守纪律
  • 需要全面的测试
  • 需要管理功能标记
  • 部署频率更高
发布分支策略

分支结构:

  • main——当前开发分支
  • release/v*——长期存在的发布分支
  • feature/*——功能分支

工作流:

# Create Release Branch
git checkout -b release/v1.0 main
git push -u origin release/v1.0

# Continue Development on Main
git checkout main
# Work on v2.0 features...

# Backport Fixes to Release
git checkout release/v1.0
git cherry-pick abc123  # Fix from main
git push origin release/v1.0
git tag -a v1.0.5 -m "Patch release v1.0.5"
git push origin v1.0.5

# Multiple Release Maintenance
git checkout release/v0.9
git cherry-pick def456
git tag -a v0.9.8 -m "Security patch v0.9.8"

适用场景:

  • 多个产品版本
  • 长期支持版本
  • 企业客户
  • 受监管行业

缺点:

  • 维护开销
  • 挑选提交较复杂
  • 代码库逐渐分化
功能分支工作流

分支结构:

  • main——稳定的生产代码
  • feature/*——从 main 创建的功能分支
  • bugfix/*——错误修复分支

工作流:

# Feature Development
git checkout main
git checkout -b feature/payment-integration

# Long-Running Feature (Sync with Main)
git fetch origin
git rebase origin/main
# Or merge
git merge origin/main

# Complete Feature
git push origin feature/payment-integration
# Create pull request
# After review and approval, merge to main

适用场景:

  • 中型团队
  • 代码审查流程
  • 并行开发功能
  • 合并前设置质量门槛

仓库组织

单体仓库

结构:

monorepo/
├── .git/
├── services/
│   ├── api/
│   ├── web/
│   └── worker/
├── packages/
│   ├── shared-utils/
│   ├── ui-components/
│   └── api-client/
├── tools/
│   ├── build-tools/
│   └── scripts/
└── docs/

优点:

  • 唯一真实来源
  • 共享代码可见
  • 可跨项目原子性地修改
  • 统一版本管理
  • 简化依赖管理
  • 工具统一

缺点:

  • 仓库体积大
  • 克隆和获取速度较慢
  • CI/CD 复杂
  • 访问控制有挑战
  • 对工具有要求

实现:

# Initialize Monorepo
git init
mkdir -p services/api services/web packages/shared-utils

# Workspace Setup (Node.js example)
cat > package.json << EOF
{
  "name": "monorepo",
  "private": true,
  "workspaces": [
    "services/*",
    "packages/*"
  ]
}
EOF

# Sparse Checkout (Partial Clone)
git clone --filter=blob:none --no-checkout <url>
cd repo
git sparse-checkout init --cone
git sparse-checkout set services/api packages/shared-utils
git checkout main

# Build Only Changed Packages
git diff --name-only HEAD~1 | grep "^services/api" && cd services/api && npm run build

工具:

  • Bazel——适用于大型单体仓库的构建系统
  • Nx——单体仓库构建系统(Node.js)
  • Lerna——JavaScript 单体仓库管理工具
  • Turborepo——高性能构建系统
  • Git-subtree——合并外部仓库
多仓库

结构:

organization/
├── api-service/       (separate repo)
├── web-app/           (separate repo)
├── mobile-app/        (separate repo)
├── shared-utils/      (separate repo)
└── documentation/     (separate repo)

优点:

  • 所有权边界明确
  • 独立版本管理
  • 仓库体积较小
  • 访问控制粒度更细
  • CI/CD 灵活
  • 团队自主性高

缺点:

  • 依赖版本冲突
  • 跨仓库修改复杂
  • 工具和配置重复
  • 跨仓库重构更困难

实现:

# Template Repository
git clone [email protected]:org/template-service.git new-service
cd new-service
rm -rf .git
git init
git remote add origin [email protected]:org/new-service.git

# Shared Configuration
# Use git submodules or packages
git submodule add [email protected]:org/shared-config.git config
单体仓库与多仓库决策矩阵
因素单体仓库多仓库
团队规模大型团队小型、自主团队
代码共享高度复用代码共享有限
部署协调发布独立部署
访问控制粗粒度细粒度
仓库大小非常大小到中等
CI/CD 复杂度高低到中等
工具要求专用工具标准 git 工具
重构跨项目简单跨仓库复杂

子模块管理

基本子模块
# Add Submodule
git submodule add https://github.com/org/shared-lib.git libs/shared

# Clone with Submodules
git clone --recurse-submodules <url>

# Initialize After Clone
git submodule init
git submodule update

# Update Submodule
cd libs/shared
git pull origin main
cd ../..
git add libs/shared
git commit -m "chore: update shared library"

# Update All Submodules
git submodule update --remote --merge

# Remove Submodule
git submodule deinit libs/shared
git rm libs/shared
rm -rf .git/modules/libs/shared
子模块策略

固定版本策略:

# Submodule points to specific commit
# Manual updates with testing
git submodule update --remote libs/shared
# Test changes...
git add libs/shared
git commit -m "chore: update shared-lib to v1.2.3"

自动更新策略:

# CI automatically updates submodules
# .github/workflows/update-submodules.yml
name: Update Submodules
on:
  schedule:
    - cron: '0 0 * * 0'  # Weekly
jobs:
  update:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v3
        with:
          submodules: true
      - run: git submodule update --remote
      - run: git commit -am "chore: update submodules"
      - run: git push
嵌套子模块
# Add Nested Submodule
cd libs/framework
git submodule add https://github.com/org/utils.git utils

# Update Recursively
git submodule update --init --recursive

# Run Command in All Submodules
git submodule foreach 'git checkout main'
git submodule foreach 'git pull'
git submodule foreach --recursive 'echo $name: $(git rev-parse HEAD)'

子树管理

Git 子树与子模块

子树的优点:

  • 对贡献者来说更简单
  • 无需单独克隆
  • 属于主仓库历史的一部分
  • 不会出现引用失效

子树的缺点:

  • 更新更复杂
  • 污染主仓库历史
  • 仓库更大
子树操作
# Add Subtree
git subtree add --prefix=libs/shared https://github.com/org/shared.git main --squash

# Update Subtree
git subtree pull --prefix=libs/shared https://github.com/org/shared.git main --squash

# Push Changes Back to Subtree
git subtree push --prefix=libs/shared https://github.com/org/shared.git feature-branch

# Split Subtree (Extract to New Repo)
git subtree split --prefix=libs/shared -b shared-lib-branch
git push [email protected]:org/new-shared-lib.git shared-lib-branch:main
子树工作流
# Setup Remote for Easier Management
git remote add shared-lib https://github.com/org/shared.git

# Add Subtree with Remote
git subtree add --prefix=libs/shared shared-lib main --squash

# Pull Updates
git fetch shared-lib
git subtree pull --prefix=libs/shared shared-lib main --squash

# Contribute Back
git subtree push --prefix=libs/shared shared-lib feature-branch

仓库模板

GitHub 模板仓库
# Create Template Structure
mkdir -p .github/workflows
cat > .github/workflows/ci.yml << EOF
name: CI
on: [push, pull_request]
jobs:
  test:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v3
      - run: make test
EOF

# Template Files
touch .gitignore README.md LICENSE CONTRIBUTING.md
mkdir -p docs src tests

# Mark as Template on GitHub Settings
# Use template to create new repositories
Cookiecutter 模板
# Install Cookiecutter
pip install cookiecutter

# Create from Template
cookiecutter https://github.com/org/project-template.git

# Template Structure
project-template/
├── cookiecutter.json
└── {{cookiecutter.project_name}}/
    ├── .git/
    ├── src/
    ├── tests/
    └── README.md

大型仓库管理

部分克隆
# Blobless Clone (No file contents initially)
git clone --filter=blob:none <url>

# Treeless Clone (Even more minimal)
git clone --filter=tree:0 <url>

# Shallow Clone (Limited History)
git clone --depth 1 <url>

# Shallow Clone with Single Branch
git clone --depth 1 --single-branch --branch main <url>
稀疏检出
# Enable Sparse Checkout
git sparse-checkout init --cone

# Specify Directories
git sparse-checkout set src/api src/shared

# Add More Directories
git sparse-checkout add docs

# List Current Sparse Checkout
git sparse-checkout list

# Disable Sparse Checkout
git sparse-checkout disable
Git LFS(大文件存储)
# Install Git LFS
git lfs install

# Track Large Files
git lfs track "*.psd"
git lfs track "*.zip"
git lfs track "data/**"

# Track Files in .gitattributes
cat .gitattributes
# *.psd filter=lfs diff=lfs merge=lfs -text

# Clone with LFS
git clone <url>
cd repo
git lfs pull

# Migrate Existing Files to LFS
git lfs migrate import --include="*.zip"

拆分仓库

将子目录提取到新仓库
# Using git filter-repo (recommended)
git filter-repo --path services/api --path-rename services/api:

# Result: New repo with only services/api content and history

# Using git subtree
git subtree split --prefix=services/api -b api-service
mkdir ../api-service
cd ../api-service
git init
git pull ../original-repo api-service
合并多个仓库
# Add Remote
git remote add project-b ../project-b

# Fetch History
git fetch project-b

# Merge with Unrelated Histories
git merge --allow-unrelated-histories project-b/main

# Move Files to Subdirectory
mkdir project-b
git mv * project-b/
git commit -m "chore: organize project-b into subdirectory"

仓库维护

定期维护任务
# Optimize Repository
git gc --aggressive

# Prune Unreachable Objects
git prune --expire now

# Verify Integrity
git fsck --full

# Repack Repository
git repack -a -d --depth=250 --window=250

# Update Server Info (for dumb HTTP)
git update-server-info
自动化脚本
#!/bin/bash
# repo-maintenance.sh

echo "Starting repository maintenance..."

# Fetch all branches
git fetch --all --prune

# Clean up stale branches
git branch -vv | grep ': gone]' | awk '{print $1}' | xargs -r git branch -D

# Garbage collection
git gc --auto

# Verify integrity
git fsck --full --strict

echo "Maintenance complete!"
定期维护
# .github/workflows/maintenance.yml
name: Repository Maintenance
on:
  schedule:
    - cron: '0 2 * * 0'  # Weekly at 2 AM Sunday
jobs:
  maintain:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v3
        with:
          fetch-depth: 0
      - name: Run Maintenance
        run: |
          git gc --aggressive
          git prune --expire now
          git fsck --full

访问控制与权限

分支保护规则
# Example Configuration
protected_branches:
  main:
    required_pull_request_reviews:
      required_approving_review_count: 2
      dismiss_stale_reviews: true
      require_code_owner_reviews: true
    required_status_checks:
      strict: true
      contexts:
        - continuous-integration
        - security-scan
    enforce_admins: true
    restrictions:
      users: []
      teams: [core-team]
CODEOWNERS 文件
# .github/CODEOWNERS

# Global owners
*                    @org/core-team

# Service owners
/services/api/       @org/backend-team
/services/web/       @org/frontend-team
/services/mobile/    @org/mobile-team

# Specific files
/docs/               @org/documentation-team
/.github/            @org/devops-team
/security/           @org/security-team @org/lead-architect

# Require multiple reviews
/packages/shared/    @org/core-team @org/architecture-team

迁移策略

从 SVN 迁移到 Git
# Create Authors File
svn log --quiet | grep "^r" | awk '{print $3}' | sort -u > authors.txt

# Edit authors.txt:
# john = John Doe <[email protected]>

# Convert Repository
git svn clone <svn-url> --authors-file=authors.txt --stdlayout repo

# Convert Tags and Branches
cd repo
git for-each-ref --format="%(refname:short)" refs/remotes/tags | \
  cut -d / -f 3 | xargs -I {} git tag {} refs/remotes/tags/{}

# Push to Git
git remote add origin <git-url>
git push -u origin --all
git push origin --tags
从 Mercurial 迁移到 Git
# Using hg-git
hg bookmark -r default main
hg push git+ssh://[email protected]/org/repo.git

# Using fast-export
git clone https://github.com/frej/fast-export.git
mkdir git-repo && cd git-repo
git init
../fast-export/hg-fast-export.sh -r ../hg-repo
git checkout HEAD

最佳实践

  1. 选择合适的策略: 根据团队规模和部署频率选择分支模型
  2. 记录工作流: 保持团队文档更新
  3. 自动化维护: 定期检查仓库健康状况
  4. 使用分支保护: 强制执行代码审查和 CI
  5. 明确所有权: 为所有区域指定代码所有者
  6. 定期清理: 移除过时的分支和已合并的功能
  7. 监控仓库大小: 对大文件使用 LFS
  8. 模板仓库: 规范新项目结构
  9. 访问控制: 实施最小权限原则
  10. 规划迁移: 在投入生产前彻底测试迁移

资源

更多仓库管理资源位于 assets/ 目录中:

  • templates/ - 仓库结构模板
  • scripts/ - 自动化和维护脚本
  • workflows/ - CI/CD 工作流示例

请参阅 references/ 目录中的:

  • 分支策略对比指南
  • 单体仓库工具文档
  • 企业级 Git 模式
  • 仓库扩展策略

评论

支持 Markdown