git-workflow

Compare original and translation side by side

🇺🇸

Original

English
🇨🇳

Translation

Chinese

Git Workflow

Git工作流

Implement effective branching strategies and pull request workflows for team collaboration.
为团队协作实施有效的分支策略和拉取请求(PR)工作流。

When to Use This Skill

何时使用此技能

Use this skill when:
  • Establishing team Git workflows
  • Implementing branching strategies
  • Configuring pull request processes
  • Setting up release management
  • Improving code review practices
在以下场景使用此技能:
  • 建立团队Git工作流
  • 实施分支策略
  • 配置拉取请求流程
  • 设置发布管理机制
  • 改进代码评审实践

Prerequisites

前置条件

  • Git installed
  • Repository hosting (GitHub, GitLab, Bitbucket)
  • Basic Git knowledge
  • 已安装Git
  • 代码仓库托管服务(GitHub、GitLab、Bitbucket)
  • 具备Git基础知识

Branching Strategies

分支策略

Trunk-Based Development

基于主干的开发

Best for: Continuous deployment, small teams, mature CI/CD
main ─────●─────●─────●─────●─────●─────●─────●
          │     │     │     │     │     │
          └─●   └─●   └─●   └─●   └─●   └─●
         feature branches (short-lived)
bash
undefined
最适合:持续部署、小型团队、成熟的CI/CD
main ─────●─────●─────●─────●─────●─────●─────●
          │     │     │     │     │     │
          └─●   └─●   └─●   └─●   └─●   └─●
         feature branches (short-lived)
bash
undefined

Create short-lived feature branch

Create short-lived feature branch

git checkout main git pull origin main git checkout -b feature/add-login
git checkout main git pull origin main git checkout -b feature/add-login

Work and commit frequently

Work and commit frequently

git add . git commit -m "feat: add login form"
git add . git commit -m "feat: add login form"

Keep branch updated

Keep branch updated

git fetch origin git rebase origin/main
git fetch origin git rebase origin/main

Merge quickly (same day ideally)

Merge quickly (same day ideally)

git checkout main git pull origin main git merge feature/add-login git push origin main git branch -d feature/add-login
undefined
git checkout main git pull origin main git merge feature/add-login git push origin main git branch -d feature/add-login
undefined

GitHub Flow

GitHub Flow

Best for: Continuous delivery, web applications
main ─────●─────●───────────●─────────────●─────●
          │           ↑           ↑       ↑
          └───●───●───┘           │       │
              feature/login       │       │
                                  │       │
          └───●───●───●───●───────┘       │
              feature/dashboard           │
          └───●─────────────────────────┘
              hotfix/security-patch
bash
undefined
最适合:持续交付、Web应用
main ─────●─────●───────────●─────────────●─────●
          │           ↑           ↑       ↑
          └───●───●───┘           │       │
              feature/login       │       │
                                  │       │
          └───●───●───●───●───────┘       │
              feature/dashboard           │
          └───●─────────────────────────┘
              hotfix/security-patch
bash
undefined

Create feature branch from main

Create feature branch from main

git checkout main git pull origin main git checkout -b feature/user-dashboard
git checkout main git pull origin main git checkout -b feature/user-dashboard

Push and create PR

Push and create PR

git push -u origin feature/user-dashboard
git push -u origin feature/user-dashboard

After review, merge via PR (squash recommended)

After review, merge via PR (squash recommended)

Delete branch after merge

Delete branch after merge

undefined
undefined

GitFlow

GitFlow

Best for: Scheduled releases, versioned products
main     ────────●────────────────●──────────────●
                 ↑                ↑              ↑
release  ────────┼────●───●──────┼──────────────┼
                 │    │   │      │              │
develop  ───●────●────┼───●──●───●───●───●───●──┼
            │         │      │       │   │      │
feature  ───┴─────────┘      │       │   │      │
                             │       │   │      │
hotfix   ────────────────────┴───────┼───┼──────┘
                                     │   │
feature  ────────────────────────────┴───┘
bash
undefined
最适合:定时发布、版本化产品
main     ────────●────────────────●──────────────●
                 ↑                ↑              ↑
release  ────────┼────●───●──────┼──────────────┼
                 │    │   │      │              │
develop  ───●────●────┼───●──●───●───●───●───●──┼
            │         │      │       │   │      │
feature  ───┴─────────┘      │       │   │      │
                             │       │   │      │
hotfix   ────────────────────┴───────┼───┼──────┘
                                     │   │
feature  ────────────────────────────┴───┘
bash
undefined

Initialize GitFlow

Initialize GitFlow

git flow init
git flow init

Start feature

Start feature

git flow feature start user-auth
git flow feature start user-auth

Finish feature (merges to develop)

Finish feature (merges to develop)

git flow feature finish user-auth
git flow feature finish user-auth

Start release

Start release

git flow release start 1.0.0
git flow release start 1.0.0

Finish release (merges to main and develop)

Finish release (merges to main and develop)

git flow release finish 1.0.0
git flow release finish 1.0.0

Hotfix

Hotfix

git flow hotfix start security-fix git flow hotfix finish security-fix
undefined
git flow hotfix start security-fix git flow hotfix finish security-fix
undefined

Commit Conventions

提交规范

Conventional Commits

约定式提交

<type>(<scope>): <description>

[optional body]

[optional footer(s)]
Types:
  • feat
    : New feature
  • fix
    : Bug fix
  • docs
    : Documentation
  • style
    : Formatting
  • refactor
    : Code restructuring
  • test
    : Adding tests
  • chore
    : Maintenance
Examples:
bash
git commit -m "feat(auth): add OAuth2 login support"
git commit -m "fix(api): handle null response from payment service"
git commit -m "docs: update API documentation for v2 endpoints"
git commit -m "refactor(db): optimize user query performance"
<type>(<scope>): <description>

[optional body]

[optional footer(s)]
类型说明:
  • feat
    : 新功能
  • fix
    : Bug修复
  • docs
    : 文档更新
  • style
    : 格式调整(不影响代码逻辑)
  • refactor
    : 代码重构
  • test
    : 添加/更新测试
  • chore
    : 维护工作(构建、依赖更新等)
示例:
bash
git commit -m "feat(auth): add OAuth2 login support"
git commit -m "fix(api): handle null response from payment service"
git commit -m "docs: update API documentation for v2 endpoints"
git commit -m "refactor(db): optimize user query performance"

Breaking change

Breaking change

git commit -m "feat(api)!: change response format for user endpoint
BREAKING CHANGE: The user endpoint now returns an object instead of array"
undefined
git commit -m "feat(api)!: change response format for user endpoint
BREAKING CHANGE: The user endpoint now returns an object instead of array"
undefined

Commit Message Template

提交消息模板

bash
undefined
bash
undefined

Create template file ~/.gitmessage

Create template file ~/.gitmessage

Subject line (50 chars max)

Subject line (50 chars max)

Body (72 chars per line max)

Body (72 chars per line max)

- What changed

- What changed

- Why it changed

- Why it changed

- Any side effects

- Any side effects

Footer

Footer

Fixes #123

Fixes #123

Co-authored-by: Name <email>

Co-authored-by: Name <email>

Configure Git to use template

Configure Git to use template

git config --global commit.template ~/.gitmessage
undefined
git config --global commit.template ~/.gitmessage
undefined

Pull Request Workflow

拉取请求(PR)工作流

PR Template

PR模板

markdown
<!-- .github/pull_request_template.md -->
markdown
<!-- .github/pull_request_template.md -->

Description

描述

Brief description of changes
变更内容的简要说明

Type of Change

变更类型

  • Bug fix (non-breaking change)
  • New feature (non-breaking change)
  • Breaking change
  • Documentation update
  • Bug修复(非破坏性变更)
  • 新功能(非破坏性变更)
  • 破坏性变更
  • 文档更新

Testing

测试情况

  • Unit tests added/updated
  • Integration tests added/updated
  • Manual testing performed
  • 添加/更新单元测试
  • 添加/更新集成测试
  • 已执行手动测试

Checklist

检查清单

  • Code follows project style guidelines
  • Self-review performed
  • Documentation updated
  • No new warnings introduced
  • 代码符合项目风格规范
  • 已完成自我评审
  • 相关文档已更新
  • 未引入新的警告

Related Issues

关联问题

Closes #
Closes #

Screenshots (if applicable)

截图(如有需要)

undefined
undefined

Branch Protection Rules

分支保护规则

yaml
undefined
yaml
undefined

GitHub branch protection

GitHub branch protection

branch_protection: branch: main required_pull_request_reviews: required_approving_review_count: 1 dismiss_stale_reviews: true require_code_owner_reviews: true required_status_checks: strict: true contexts: - "ci/tests" - "ci/lint" restrictions: users: [] teams: ["maintainers"] enforce_admins: true required_linear_history: true allow_force_pushes: false allow_deletions: false
undefined
branch_protection: branch: main required_pull_request_reviews: required_approving_review_count: 1 dismiss_stale_reviews: true require_code_owner_reviews: true required_status_checks: strict: true contexts: - "ci/tests" - "ci/lint" restrictions: users: [] teams: ["maintainers"] enforce_admins: true required_linear_history: true allow_force_pushes: false allow_deletions: false
undefined

Code Owners

代码所有者

undefined
undefined

.github/CODEOWNERS

.github/CODEOWNERS

Default owners

默认所有者

  • @team-leads
  • @team-leads

Frontend code

前端代码

/src/frontend/ @frontend-team *.tsx @frontend-team *.css @frontend-team
/src/frontend/ @frontend-team *.tsx @frontend-team *.css @frontend-team

Backend code

后端代码

/src/api/ @backend-team /src/services/ @backend-team
/src/api/ @backend-team /src/services/ @backend-team

Infrastructure

基础设施

/terraform/ @platform-team /k8s/ @platform-team Dockerfile @platform-team
/terraform/ @platform-team /k8s/ @platform-team Dockerfile @platform-team

Documentation

文档

/docs/ @tech-writers *.md @tech-writers
undefined
/docs/ @tech-writers *.md @tech-writers
undefined

Git Hooks

Git钩子

Pre-commit Hook

预提交钩子

bash
#!/bin/sh
bash
#!/bin/sh

.git/hooks/pre-commit

.git/hooks/pre-commit

Run linting

Run linting

npm run lint if [ $? -ne 0 ]; then echo "Linting failed. Fix errors before committing." exit 1 fi
npm run lint if [ $? -ne 0 ]; then echo "Linting failed. Fix errors before committing." exit 1 fi

Run tests

Run tests

npm run test:unit if [ $? -ne 0 ]; then echo "Tests failed. Fix tests before committing." exit 1 fi
npm run test:unit if [ $? -ne 0 ]; then echo "Tests failed. Fix tests before committing." exit 1 fi

Check for debug statements

Check for debug statements

if grep -r "console.log|debugger|binding.pry" --include=".js" --include=".ts" --include="*.rb" src/; then echo "Remove debug statements before committing." exit 1 fi
undefined
if grep -r "console.log|debugger|binding.pry" --include=".js" --include=".ts" --include="*.rb" src/; then echo "Remove debug statements before committing." exit 1 fi
undefined

Using Husky

使用Husky

json
// package.json
{
  "husky": {
    "hooks": {
      "pre-commit": "lint-staged",
      "commit-msg": "commitlint -E HUSKY_GIT_PARAMS"
    }
  },
  "lint-staged": {
    "*.{js,ts,tsx}": ["eslint --fix", "prettier --write"],
    "*.{css,scss}": ["prettier --write"]
  }
}
json
// package.json
{
  "husky": {
    "hooks": {
      "pre-commit": "lint-staged",
      "commit-msg": "commitlint -E HUSKY_GIT_PARAMS"
    }
  },
  "lint-staged": {
    "*.{js,ts,tsx}": ["eslint --fix", "prettier --write"],
    "*.{css,scss}": ["prettier --write"]
  }
}

Commitlint Configuration

Commitlint配置

javascript
// commitlint.config.js
module.exports = {
  extends: ['@commitlint/config-conventional'],
  rules: {
    'type-enum': [
      2,
      'always',
      ['feat', 'fix', 'docs', 'style', 'refactor', 'test', 'chore', 'revert']
    ],
    'subject-max-length': [2, 'always', 72],
    'body-max-line-length': [2, 'always', 100]
  }
};
javascript
// commitlint.config.js
module.exports = {
  extends: ['@commitlint/config-conventional'],
  rules: {
    'type-enum': [
      2,
      'always',
      ['feat', 'fix', 'docs', 'style', 'refactor', 'test', 'chore', 'revert']
    ],
    'subject-max-length': [2, 'always', 72],
    'body-max-line-length': [2, 'always', 100]
  }
};

Release Workflow

发布工作流

Automated Release with Tags

带标签的自动化发布

bash
undefined
bash
undefined

Create annotated tag

Create annotated tag

git tag -a v1.0.0 -m "Release version 1.0.0"
git tag -a v1.0.0 -m "Release version 1.0.0"

Push tag

Push tag

git push origin v1.0.0
git push origin v1.0.0

Create release from tag (GitHub CLI)

Create release from tag (GitHub CLI)

gh release create v1.0.0
--title "Release 1.0.0"
--notes "Release notes here"
--target main
undefined
gh release create v1.0.0
--title "Release 1.0.0"
--notes "Release notes here"
--target main
undefined

Changelog Generation

变更日志生成

bash
undefined
bash
undefined

Using conventional-changelog

Using conventional-changelog

npx conventional-changelog -p angular -i CHANGELOG.md -s
npx conventional-changelog -p angular -i CHANGELOG.md -s

Using git-cliff

Using git-cliff

git cliff -o CHANGELOG.md
undefined
git cliff -o CHANGELOG.md
undefined

Common Git Operations

常见Git操作

Rebase vs Merge

变基(Rebase)与合并(Merge)

bash
undefined
bash
undefined

Rebase (clean history)

Rebase (clean history)

git checkout feature/my-feature git rebase main git push --force-with-lease
git checkout feature/my-feature git rebase main git push --force-with-lease

Merge (preserve history)

Merge (preserve history)

git checkout main git merge feature/my-feature
git checkout main git merge feature/my-feature

Squash merge (single commit)

Squash merge (single commit)

git merge --squash feature/my-feature git commit -m "feat: add feature X"
undefined
git merge --squash feature/my-feature git commit -m "feat: add feature X"
undefined

Cherry Pick

拣选提交(Cherry Pick)

bash
undefined
bash
undefined

Apply specific commit to current branch

Apply specific commit to current branch

git cherry-pick abc123
git cherry-pick abc123

Cherry pick range

Cherry pick range

git cherry-pick abc123..def456
git cherry-pick abc123..def456

Cherry pick without committing

Cherry pick without committing

git cherry-pick -n abc123
undefined
git cherry-pick -n abc123
undefined

Interactive Rebase

交互式变基

bash
undefined
bash
undefined

Clean up last 3 commits

Clean up last 3 commits

git rebase -i HEAD~3
git rebase -i HEAD~3

In editor:

In editor:

pick abc123 First commit

pick abc123 First commit

squash def456 Second commit

squash def456 Second commit

reword ghi789 Third commit

reword ghi789 Third commit

undefined
undefined

Common Issues

常见问题

Issue: Merge Conflicts

问题:合并冲突

Problem: Conflicts when merging branches Solution: Rebase frequently, communicate with team, use smaller PRs
现象:合并分支时出现冲突 解决方案:定期变基更新分支、与团队沟通、拆分更小的PR

Issue: Diverged Branches

问题:分支偏离

Problem: Local branch far behind remote Solution:
git pull --rebase
or
git fetch && git rebase origin/main
现象:本地分支与远程分支差距较大 解决方案
git pull --rebase
git fetch && git rebase origin/main

Issue: Accidental Commit to Wrong Branch

问题:误提交到错误分支

Problem: Committed to main instead of feature Solution:
git reset HEAD~1
, checkout correct branch, recommit
现象:本该提交到功能分支的代码提交到了main分支 解决方案
git reset HEAD~1
,切换到正确分支后重新提交

Best Practices

最佳实践

  • Keep branches short-lived (< 1 week)
  • Write meaningful commit messages
  • Use PR templates consistently
  • Require code reviews
  • Protect main/master branch
  • Automate checks with CI
  • Squash merge for clean history
  • Delete branches after merge
  • 保持功能分支生命周期较短(<1周)
  • 编写有意义的提交消息
  • 统一使用PR模板
  • 要求代码评审
  • 保护main/master分支
  • 通过CI自动化检查
  • 使用 squash merge 保持提交历史整洁
  • 合并后删除功能分支

Related Skills

相关技能

  • semantic-versioning - Version management
  • github-actions - CI/CD automation
  • feature-flags - Feature management
  • semantic-versioning - 版本管理
  • github-actions - CI/CD自动化
  • feature-flags - 功能管理