git-repository
Compare original and translation side by side
🇺🇸
Original
English🇨🇳
Translation
ChineseGit Repository Management Skill
Git 仓库管理技能
This skill provides comprehensive guidance on repository management strategies, branching models, repository organization patterns, and scaling git for large teams and codebases.
本技能提供关于仓库管理策略、分支模型、仓库组织模式以及为大型团队和代码库扩展Git的全面指导。
When to Use
适用场景
Activate this skill when:
- Setting up new repository structure
- Choosing branching strategy
- Managing monorepo vs polyrepo
- Organizing multi-project repositories
- Implementing submodule or subtree strategies
- Scaling git for large teams
- Migrating repository structures
- Establishing team workflows
在以下场景激活本技能:
- 搭建新的仓库结构
- 选择分支策略
- 管理单体仓库(Monorepo)与多仓库(Polyrepo)
- 组织多项目仓库
- 实施子模块或子树策略
- 为大型团队扩展Git
- 迁移仓库结构
- 建立团队工作流
Branching Strategies
分支策略
Git Flow
Git Flow
Branch Structure:
- (or
main) - Production releases onlymaster - - Integration branch for next release
develop - - Feature development branches
feature/* - - Release preparation branches
release/* - - Emergency production fixes
hotfix/*
Workflow:
bash
undefined分支结构:
- (或
main)- 仅用于生产版本发布master - - 下一个版本的集成分支
develop - - 功能开发分支
feature/* - - 版本发布准备分支
release/* - - 生产环境紧急修复分支
hotfix/*
工作流:
bash
undefinedFeature Development
Feature Development
git checkout develop
git checkout -b feature/user-authentication
git checkout develop
git checkout -b feature/user-authentication
Work on feature...
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
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
Release Preparation
git checkout develop
git checkout -b release/v1.2.0
git checkout develop
git checkout -b release/v1.2.0
Bump version, update changelog, final testing...
Bump version, update changelog, final testing...
git commit -m "chore: prepare release v1.2.0"
git commit -m "chore: prepare release v1.2.0"
Deploy Release
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
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
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
**Best For:**
- Scheduled releases
- Multiple production versions
- Large teams with QA process
- Products with maintenance windows
- Enterprise software
**Drawbacks:**
- Complex workflow
- Long-lived branches
- Potential merge conflicts
- Delayed integrationgit 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
GitHub Flow
Branch Structure:
- - Production-ready code (always deployable)
main - - All feature and fix branches
feature/*
Workflow:
bash
undefined分支结构:
- - 可直接部署的生产就绪代码
main - - 所有功能和修复分支
feature/*
工作流:
bash
undefinedCreate Feature Branch
Create Feature Branch
git checkout main
git pull origin main
git checkout -b feature/add-api-logging
git checkout main
git pull origin main
git checkout -b feature/add-api-logging
Develop Feature
Develop Feature
git commit -m "feat: add structured logging middleware"
git push -u origin feature/add-api-logging
git commit -m "feat: add structured logging middleware"
git push -u origin feature/add-api-logging
Open Pull Request on GitHub
Open Pull Request on GitHub
Review, discuss, CI passes
Review, discuss, CI passes
Merge and Deploy
Merge and Deploy
Merge PR on GitHub
Merge PR on GitHub
Automatic deployment from main
Automatic deployment from main
Cleanup
Cleanup
git checkout main
git pull origin main
git branch -d feature/add-api-logging
**Best For:**
- Continuous deployment
- Small to medium teams
- Web applications
- Rapid iteration
- Cloud-native applications
**Drawbacks:**
- Requires robust CI/CD
- No release staging
- Less structured than Git Flowgit checkout main
git pull origin main
git branch -d feature/add-api-logging
**适用场景:**
- 持续部署
- 中小型团队
- Web应用
- 快速迭代
- 云原生应用
**缺点:**
- 需要健壮的CI/CD体系
- 无发布预演阶段
- 结构不如Git Flow严谨Trunk-Based Development
基于主干的开发(Trunk-Based Development)
Branch Structure:
- (or
main) - Single source of truthtrunk - Short-lived feature branches (< 2 days, optional)
- Feature flags for incomplete work
Workflow:
bash
undefined分支结构:
- (或
main)- 唯一的可信源trunk - 短期功能分支(时长<2天,可选)
- 功能标记(Feature Flags)用于未完成的工作
工作流:
bash
undefinedDirect Commit to Main (Small Changes)
Direct Commit to Main (Small Changes)
git checkout main
git pull origin main
git checkout main
git pull origin main
Make small change...
Make small change...
git commit -m "fix: correct validation logic"
git push origin main
git commit -m "fix: correct validation logic"
git push origin main
Short-Lived Branch (Larger Changes)
Short-Lived Branch (Larger Changes)
git checkout -b optimize-query
git checkout -b optimize-query
Work for < 1 day
Work for < 1 day
git commit -m "perf: optimize database query"
git push -u origin optimize-query
git commit -m "perf: optimize database query"
git push -u origin optimize-query
Immediate PR, quick review, merge same day
Immediate PR, quick review, merge same day
Feature Flags for Incomplete Features
Feature Flags for Incomplete Features
git checkout main
git commit -m "feat: add payment gateway (behind feature flag)"
git checkout main
git commit -m "feat: add payment gateway (behind feature flag)"
Feature disabled in production until complete
Feature disabled in production until complete
git push origin main
**Best For:**
- High-velocity teams
- Continuous integration
- Automated testing
- Feature flag infrastructure
- DevOps culture
**Drawbacks:**
- Requires discipline
- Needs comprehensive tests
- Feature flag management
- Higher deployment frequencygit push origin main
**适用场景:**
- 高迭代速度的团队
- 持续集成
- 自动化测试
- 具备功能标记基础设施
- DevOps文化
**缺点:**
- 需要团队自律
- 需全面的测试覆盖
- 功能标记管理复杂度高
- 部署频率更高Release Branch Strategy
发布分支策略
Branch Structure:
- - Current development
main - - Long-lived release branches
release/v* - - Feature branches
feature/*
Workflow:
bash
undefined分支结构:
- - 当前开发分支
main - - 长期存在的发布分支
release/v* - - 功能分支
feature/*
工作流:
bash
undefinedCreate Release Branch
Create Release Branch
git checkout -b release/v1.0 main
git push -u origin release/v1.0
git checkout -b release/v1.0 main
git push -u origin release/v1.0
Continue Development on Main
Continue Development on Main
git checkout main
git checkout main
Work on v2.0 features...
Work on v2.0 features...
Backport Fixes to Release
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
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
Multiple Release Maintenance
git checkout release/v0.9
git cherry-pick def456
git tag -a v0.9.8 -m "Security patch v0.9.8"
**Best For:**
- Multiple product versions
- Long-term support releases
- Enterprise customers
- Regulated industries
**Drawbacks:**
- Maintenance overhead
- Complex cherry-picking
- Diverging codebasesgit checkout release/v0.9
git cherry-pick def456
git tag -a v0.9.8 -m "Security patch v0.9.8"
**适用场景:**
- 多产品版本维护
- 长期支持版本
- 企业客户
- 受监管行业
**缺点:**
- 维护开销大
- 樱桃拣选(Cherry-Pick)操作复杂
- 代码库逐渐分化Feature Branch Workflow
功能分支工作流
Branch Structure:
- - Stable production code
main - - Feature branches from main
feature/* - - Bug fix branches
bugfix/*
Workflow:
bash
undefined分支结构:
- - 稳定的生产代码
main - - 从main分支创建的功能分支
feature/* - - Bug修复分支
bugfix/*
工作流:
bash
undefinedFeature Development
Feature Development
git checkout main
git checkout -b feature/payment-integration
git checkout main
git checkout -b feature/payment-integration
Long-Running Feature (Sync with Main)
Long-Running Feature (Sync with Main)
git fetch origin
git rebase origin/main
git fetch origin
git rebase origin/main
Or merge
Or merge
git merge origin/main
git merge origin/main
Complete Feature
Complete Feature
git push origin feature/payment-integration
git push origin feature/payment-integration
Create pull request
Create pull request
After review and approval, merge to main
After review and approval, merge to main
**Best For:**
- Medium-sized teams
- Code review processes
- Parallel feature development
- Quality gates before merge
**适用场景:**
- 中等规模团队
- 代码审查流程
- 并行功能开发
- 合并前的质量把关Repository Organization
仓库组织
Monorepo
单体仓库(Monorepo)
Structure:
monorepo/
├── .git/
├── services/
│ ├── api/
│ ├── web/
│ └── worker/
├── packages/
│ ├── shared-utils/
│ ├── ui-components/
│ └── api-client/
├── tools/
│ ├── build-tools/
│ └── scripts/
└── docs/Advantages:
- Single source of truth
- Shared code visibility
- Atomic cross-project changes
- Unified versioning
- Simplified dependency management
- Consistent tooling
Disadvantages:
- Large repository size
- Slower clone/fetch
- Complex CI/CD
- Access control challenges
- Tooling requirements
Implementation:
bash
undefined结构:
monorepo/
├── .git/
├── services/
│ ├── api/
│ ├── web/
│ └── worker/
├── packages/
│ ├── shared-utils/
│ ├── ui-components/
│ └── api-client/
├── tools/
│ ├── build-tools/
│ └── scripts/
└── docs/优势:
- 单一可信源
- 共享代码可见性高
- 跨项目的原子性变更
- 统一版本管理
- 简化依赖管理
- 一致的工具链
劣势:
- 仓库体积大
- 克隆/拉取速度慢
- CI/CD复杂度高
- 访问控制挑战
- 对工具链有特定要求
实现方式:
bash
undefinedInitialize Monorepo
Initialize Monorepo
git init
mkdir -p services/api services/web packages/shared-utils
git init
mkdir -p services/api services/web packages/shared-utils
Workspace Setup (Node.js example)
Workspace Setup (Node.js example)
cat > package.json << EOF
{
"name": "monorepo",
"private": true,
"workspaces": [
"services/",
"packages/"
]
}
EOF
cat > package.json << EOF
{
"name": "monorepo",
"private": true,
"workspaces": [
"services/",
"packages/"
]
}
EOF
Sparse Checkout (Partial Clone)
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
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
Build Only Changed Packages
git diff --name-only HEAD~1 | grep "^services/api" && cd services/api && npm run build
**Tools:**
- **Bazel** - Build system for large monorepos
- **Nx** - Monorepo build system (Node.js)
- **Lerna** - JavaScript monorepo management
- **Turborepo** - High-performance build system
- **Git-subtree** - Merge external repositoriesgit diff --name-only HEAD~1 | grep "^services/api" && cd services/api && npm run build
**工具:**
- **Bazel** - 用于大型单体仓库的构建系统
- **Nx** - 单体仓库构建系统(Node.js)
- **Lerna** - JavaScript单体仓库管理工具
- **Turborepo** - 高性能构建系统
- **Git-subtree** - 合并外部仓库Polyrepo
多仓库(Polyrepo)
Structure:
organization/
├── api-service/ (separate repo)
├── web-app/ (separate repo)
├── mobile-app/ (separate repo)
├── shared-utils/ (separate repo)
└── documentation/ (separate repo)Advantages:
- Clear ownership boundaries
- Independent versioning
- Smaller repository size
- Granular access control
- Flexible CI/CD
- Team autonomy
Disadvantages:
- Dependency version conflicts
- Cross-repo changes are complex
- Duplicated tooling/config
- Harder to refactor across repos
Implementation:
bash
undefined结构:
organization/
├── api-service/ (separate repo)
├── web-app/ (separate repo)
├── mobile-app/ (separate repo)
├── shared-utils/ (separate repo)
└── documentation/ (separate repo)优势:
- 清晰的所有权边界
- 独立版本管理
- 仓库体积小
- 细粒度的访问控制
- 灵活的CI/CD
- 团队自主性
劣势:
- 依赖版本冲突
- 跨仓库变更复杂
- 工具链/配置重复
- 跨仓库重构难度大
实现方式:
bash
undefinedTemplate Repository
Template Repository
git clone git@github.com:org/template-service.git new-service
cd new-service
rm -rf .git
git init
git remote add origin git@github.com:org/new-service.git
git clone git@github.com:org/template-service.git new-service
cd new-service
rm -rf .git
git init
git remote add origin git@github.com:org/new-service.git
Shared Configuration
Shared Configuration
Use git submodules or packages
Use git submodules or packages
git submodule add git@github.com:org/shared-config.git config
undefinedgit submodule add git@github.com:org/shared-config.git config
undefinedMonorepo vs Polyrepo Decision Matrix
Monorepo vs Polyrepo 决策矩阵
| Factor | Monorepo | Polyrepo |
|---|---|---|
| Team Size | Large teams | Small, autonomous teams |
| Code Sharing | High code reuse | Limited sharing |
| Deployment | Coordinated releases | Independent deployments |
| Access Control | Coarse-grained | Fine-grained |
| Repository Size | Very large | Small to medium |
| CI/CD Complexity | High | Low to medium |
| Tooling Requirements | Specialized tools | Standard git tools |
| Refactoring | Easy cross-project | Complex cross-repo |
| 因素 | Monorepo | Polyrepo |
|---|---|---|
| 团队规模 | 大型团队 | 小型、自主团队 |
| 代码共享 | 高复用率 | 有限共享 |
| 部署方式 | 协调式发布 | 独立部署 |
| 访问控制 | 粗粒度 | 细粒度 |
| 仓库体积 | 非常大 | 中小型 |
| CI/CD复杂度 | 高 | 中低 |
| 工具链要求 | 专用工具 | 标准Git工具 |
| 重构难度 | 跨项目易操作 | 跨仓库复杂 |
Submodule Management
子模块管理
Basic Submodules
基础子模块操作
bash
undefinedbash
undefinedAdd Submodule
Add Submodule
git submodule add https://github.com/org/shared-lib.git libs/shared
git submodule add https://github.com/org/shared-lib.git libs/shared
Clone with Submodules
Clone with Submodules
git clone --recurse-submodules <url>
git clone --recurse-submodules <url>
Initialize After Clone
Initialize After Clone
git submodule init
git submodule update
git submodule init
git submodule update
Update Submodule
Update Submodule
cd libs/shared
git pull origin main
cd ../..
git add libs/shared
git commit -m "chore: update shared library"
cd libs/shared
git pull origin main
cd ../..
git add libs/shared
git commit -m "chore: update shared library"
Update All Submodules
Update All Submodules
git submodule update --remote --merge
git submodule update --remote --merge
Remove Submodule
Remove Submodule
git submodule deinit libs/shared
git rm libs/shared
rm -rf .git/modules/libs/shared
undefinedgit submodule deinit libs/shared
git rm libs/shared
rm -rf .git/modules/libs/shared
undefinedSubmodule Strategies
子模块策略
Pinned Version Strategy:
bash
undefined固定版本策略:
bash
undefinedSubmodule points to specific commit
Submodule points to specific commit
Manual updates with testing
Manual updates with testing
git submodule update --remote libs/shared
git submodule update --remote libs/shared
Test changes...
Test changes...
git add libs/shared
git commit -m "chore: update shared-lib to v1.2.3"
**Auto-Update Strategy:**
```bashgit add libs/shared
git commit -m "chore: update shared-lib to v1.2.3"
**自动更新策略:**
```bashCI automatically updates submodules
CI automatically updates submodules
.github/workflows/update-submodules.yml
.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
undefinedname: 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
undefinedNested Submodules
嵌套子模块
bash
undefinedbash
undefinedAdd Nested Submodule
Add Nested Submodule
cd libs/framework
git submodule add https://github.com/org/utils.git utils
cd libs/framework
git submodule add https://github.com/org/utils.git utils
Update Recursively
Update Recursively
git submodule update --init --recursive
git submodule update --init --recursive
Run Command in All Submodules
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)'
undefinedgit submodule foreach 'git checkout main'
git submodule foreach 'git pull'
git submodule foreach --recursive 'echo $name: $(git rev-parse HEAD)'
undefinedSubtree Management
子树管理
Git Subtree vs Submodule
Git Subtree vs Submodule
Subtree Advantages:
- Simpler for contributors
- No separate clone steps
- Part of main repository history
- No broken references
Subtree Disadvantages:
- More complex to update
- Pollutes main history
- Larger repository
Subtree优势:
- 对贡献者更简单
- 无需单独克隆步骤
- 属于主仓库历史的一部分
- 无引用断裂问题
Subtree劣势:
- 更新操作更复杂
- 会污染主仓库历史
- 仓库体积更大
Subtree Operations
子树操作
bash
undefinedbash
undefinedAdd Subtree
Add Subtree
git subtree add --prefix=libs/shared https://github.com/org/shared.git main --squash
git subtree add --prefix=libs/shared https://github.com/org/shared.git main --squash
Update Subtree
Update Subtree
git subtree pull --prefix=libs/shared https://github.com/org/shared.git main --squash
git subtree pull --prefix=libs/shared https://github.com/org/shared.git main --squash
Push Changes Back to Subtree
Push Changes Back to Subtree
git subtree push --prefix=libs/shared https://github.com/org/shared.git feature-branch
git subtree push --prefix=libs/shared https://github.com/org/shared.git feature-branch
Split Subtree (Extract to New Repo)
Split Subtree (Extract to New Repo)
git subtree split --prefix=libs/shared -b shared-lib-branch
git push git@github.com:org/new-shared-lib.git shared-lib-branch:main
undefinedgit subtree split --prefix=libs/shared -b shared-lib-branch
git push git@github.com:org/new-shared-lib.git shared-lib-branch:main
undefinedSubtree Workflow
子树工作流
bash
undefinedbash
undefinedSetup Remote for Easier Management
Setup Remote for Easier Management
git remote add shared-lib https://github.com/org/shared.git
git remote add shared-lib https://github.com/org/shared.git
Add Subtree with Remote
Add Subtree with Remote
git subtree add --prefix=libs/shared shared-lib main --squash
git subtree add --prefix=libs/shared shared-lib main --squash
Pull Updates
Pull Updates
git fetch shared-lib
git subtree pull --prefix=libs/shared shared-lib main --squash
git fetch shared-lib
git subtree pull --prefix=libs/shared shared-lib main --squash
Contribute Back
Contribute Back
git subtree push --prefix=libs/shared shared-lib feature-branch
undefinedgit subtree push --prefix=libs/shared shared-lib feature-branch
undefinedRepository Templates
仓库模板
GitHub Template Repository
GitHub 模板仓库
bash
undefinedbash
undefinedCreate Template Structure
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
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
Template Files
touch .gitignore README.md LICENSE CONTRIBUTING.md
mkdir -p docs src tests
touch .gitignore README.md LICENSE CONTRIBUTING.md
mkdir -p docs src tests
Mark as Template on GitHub Settings
Mark as Template on GitHub Settings
Use template to create new repositories
Use template to create new repositories
undefinedundefinedCookiecutter Template
Cookiecutter 模板
bash
undefinedbash
undefinedInstall Cookiecutter
Install Cookiecutter
pip install cookiecutter
pip install cookiecutter
Create from Template
Create from Template
cookiecutter https://github.com/org/project-template.git
cookiecutter https://github.com/org/project-template.git
Template Structure
Template Structure
project-template/
├── cookiecutter.json
└── {{cookiecutter.project_name}}/
├── .git/
├── src/
├── tests/
└── README.md
undefinedproject-template/
├── cookiecutter.json
└── {{cookiecutter.project_name}}/
├── .git/
├── src/
├── tests/
└── README.md
undefinedLarge Repository Management
大型仓库管理
Partial Clone
部分克隆
bash
undefinedbash
undefinedBlobless Clone (No file contents initially)
Blobless Clone (No file contents initially)
git clone --filter=blob:none <url>
git clone --filter=blob:none <url>
Treeless Clone (Even more minimal)
Treeless Clone (Even more minimal)
git clone --filter=tree:0 <url>
git clone --filter=tree:0 <url>
Shallow Clone (Limited History)
Shallow Clone (Limited History)
git clone --depth 1 <url>
git clone --depth 1 <url>
Shallow Clone with Single Branch
Shallow Clone with Single Branch
git clone --depth 1 --single-branch --branch main <url>
undefinedgit clone --depth 1 --single-branch --branch main <url>
undefinedSparse Checkout
稀疏检出
bash
undefinedbash
undefinedEnable Sparse Checkout
Enable Sparse Checkout
git sparse-checkout init --cone
git sparse-checkout init --cone
Specify Directories
Specify Directories
git sparse-checkout set src/api src/shared
git sparse-checkout set src/api src/shared
Add More Directories
Add More Directories
git sparse-checkout add docs
git sparse-checkout add docs
List Current Sparse Checkout
List Current Sparse Checkout
git sparse-checkout list
git sparse-checkout list
Disable Sparse Checkout
Disable Sparse Checkout
git sparse-checkout disable
undefinedgit sparse-checkout disable
undefinedGit LFS (Large File Storage)
Git LFS(大文件存储)
bash
undefinedbash
undefinedInstall Git LFS
Install Git LFS
git lfs install
git lfs install
Track Large Files
Track Large Files
git lfs track ".psd"
git lfs track ".zip"
git lfs track "data/**"
git lfs track ".psd"
git lfs track ".zip"
git lfs track "data/**"
Track Files in .gitattributes
Track Files in .gitattributes
cat .gitattributes
cat .gitattributes
*.psd filter=lfs diff=lfs merge=lfs -text
*.psd filter=lfs diff=lfs merge=lfs -text
Clone with LFS
Clone with LFS
git clone <url>
cd repo
git lfs pull
git clone <url>
cd repo
git lfs pull
Migrate Existing Files to LFS
Migrate Existing Files to LFS
git lfs migrate import --include="*.zip"
undefinedgit lfs migrate import --include="*.zip"
undefinedRepository Splitting
仓库拆分
Extract Subdirectory to New Repo
提取子目录到新仓库
bash
undefinedbash
undefinedUsing git filter-repo (recommended)
Using git filter-repo (recommended)
git filter-repo --path services/api --path-rename services/api:
git filter-repo --path services/api --path-rename services/api:
Result: New repo with only services/api content and history
Result: New repo with only services/api content and history
Using git subtree
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
undefinedgit subtree split --prefix=services/api -b api-service
mkdir ../api-service
cd ../api-service
git init
git pull ../original-repo api-service
undefinedMerge Multiple Repos
合并多个仓库
bash
undefinedbash
undefinedAdd Remote
Add Remote
git remote add project-b ../project-b
git remote add project-b ../project-b
Fetch History
Fetch History
git fetch project-b
git fetch project-b
Merge with Unrelated Histories
Merge with Unrelated Histories
git merge --allow-unrelated-histories project-b/main
git merge --allow-unrelated-histories project-b/main
Move Files to Subdirectory
Move Files to Subdirectory
mkdir project-b
git mv * project-b/
git commit -m "chore: organize project-b into subdirectory"
undefinedmkdir project-b
git mv * project-b/
git commit -m "chore: organize project-b into subdirectory"
undefinedRepository Maintenance
仓库维护
Regular Maintenance Tasks
常规维护任务
bash
undefinedbash
undefinedOptimize Repository
Optimize Repository
git gc --aggressive
git gc --aggressive
Prune Unreachable Objects
Prune Unreachable Objects
git prune --expire now
git prune --expire now
Verify Integrity
Verify Integrity
git fsck --full
git fsck --full
Repack Repository
Repack Repository
git repack -a -d --depth=250 --window=250
git repack -a -d --depth=250 --window=250
Update Server Info (for dumb HTTP)
Update Server Info (for dumb HTTP)
git update-server-info
undefinedgit update-server-info
undefinedAutomation Script
自动化脚本
bash
#!/bin/bashbash
#!/bin/bashrepo-maintenance.sh
repo-maintenance.sh
echo "Starting repository maintenance..."
echo "Starting repository maintenance..."
Fetch all branches
Fetch all branches
git fetch --all --prune
git fetch --all --prune
Clean up stale branches
Clean up stale branches
git branch -vv | grep ': gone]' | awk '{print $1}' | xargs -r git branch -D
git branch -vv | grep ': gone]' | awk '{print $1}' | xargs -r git branch -D
Garbage collection
Garbage collection
git gc --auto
git gc --auto
Verify integrity
Verify integrity
git fsck --full --strict
echo "Maintenance complete!"
undefinedgit fsck --full --strict
echo "Maintenance complete!"
undefinedScheduled Maintenance
定时维护
yaml
undefinedyaml
undefined.github/workflows/maintenance.yml
.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
undefinedname: 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
undefinedAccess Control and Permissions
访问控制与权限
Branch Protection Rules
分支保护规则
yaml
undefinedyaml
undefinedExample Configuration
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]
undefinedprotected_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]
undefinedCODEOWNERS File
CODEOWNERS 文件
bash
undefinedbash
undefined.github/CODEOWNERS
.github/CODEOWNERS
Global owners
Global owners
-
@org/core-team
-
@org/core-team
Service owners
Service owners
/services/api/ @org/backend-team
/services/web/ @org/frontend-team
/services/mobile/ @org/mobile-team
/services/api/ @org/backend-team
/services/web/ @org/frontend-team
/services/mobile/ @org/mobile-team
Specific files
Specific files
/docs/ @org/documentation-team
/.github/ @org/devops-team
/security/ @org/security-team @org/lead-architect
/docs/ @org/documentation-team
/.github/ @org/devops-team
/security/ @org/security-team @org/lead-architect
Require multiple reviews
Require multiple reviews
/packages/shared/ @org/core-team @org/architecture-team
undefined/packages/shared/ @org/core-team @org/architecture-team
undefinedMigration Strategies
迁移策略
SVN to Git
SVN 迁移到 Git
bash
undefinedbash
undefinedCreate Authors File
Create Authors File
svn log --quiet | grep "^r" | awk '{print $3}' | sort -u > authors.txt
svn log --quiet | grep "^r" | awk '{print $3}' | sort -u > authors.txt
Edit authors.txt:
Edit authors.txt:
john = John Doe john@example.com
john = John Doe john@example.com
Convert Repository
Convert Repository
git svn clone <svn-url> --authors-file=authors.txt --stdlayout repo
git svn clone <svn-url> --authors-file=authors.txt --stdlayout repo
Convert Tags and Branches
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/{}
cut -d / -f 3 | xargs -I {} git tag {} refs/remotes/tags/{}
cd repo
git for-each-ref --format="%(refname:short)" refs/remotes/tags |
cut -d / -f 3 | xargs -I {} git tag {} refs/remotes/tags/{}
cut -d / -f 3 | xargs -I {} git tag {} refs/remotes/tags/{}
Push to Git
Push to Git
git remote add origin <git-url>
git push -u origin --all
git push origin --tags
undefinedgit remote add origin <git-url>
git push -u origin --all
git push origin --tags
undefinedMercurial to Git
Mercurial 迁移到 Git
bash
undefinedbash
undefinedUsing hg-git
Using hg-git
hg bookmark -r default main
hg push git+ssh://git@github.com/org/repo.git
hg bookmark -r default main
hg push git+ssh://git@github.com/org/repo.git
Using fast-export
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
undefinedgit 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
undefinedBest Practices
最佳实践
- Choose Appropriate Strategy: Match branching model to team size and deployment frequency
- Document Workflows: Keep team documentation current
- Automate Maintenance: Regular repository health checks
- Use Branch Protection: Enforce code review and CI
- Clear Ownership: Define code owners for all areas
- Regular Cleanup: Remove stale branches and merged features
- Monitor Repository Size: Use LFS for large files
- Template Repositories: Standardize new project structure
- Access Control: Implement principle of least privilege
- Migration Planning: Test migrations thoroughly before production
- 选择合适的策略: 根据团队规模和部署频率匹配分支模型
- 文档化工作流: 保持团队文档更新
- 自动化维护: 定期进行仓库健康检查
- 使用分支保护: 强制执行代码审查和CI验证
- 明确所有权: 为所有代码区域定义代码所有者
- 定期清理: 删除 stale 分支和已合并的功能分支
- 监控仓库体积: 使用LFS存储大文件
- 仓库模板化: 标准化新项目结构
- 访问控制: 实施最小权限原则
- 迁移规划: 生产迁移前进行充分测试
Resources
资源
Additional repository management resources are available in the directory:
assets/- - Repository structure templates
templates/ - - Automation and maintenance scripts
scripts/ - - CI/CD workflow examples
workflows/
See directory for:
references/- Branching strategy comparison guides
- Monorepo tool documentation
- Enterprise git patterns
- Repository scaling strategies
更多仓库管理资源请查看 目录:
assets/- - 仓库结构模板
templates/ - - 自动化与维护脚本
scripts/ - - CI/CD工作流示例
workflows/
references/- 分支策略对比指南
- Monorepo工具文档
- 企业级Git模式
- 仓库扩展策略