git-workflow-designer

Compare original and translation side by side

🇺🇸

Original

English
🇨🇳

Translation

Chinese

Git Workflow Designer Skill

Git工作流设计技能

Overview

概述

This skill helps you design and implement effective Git branching strategies for teams of any size. Covers Git Flow, GitHub Flow, trunk-based development, release management, and branch protection policies.
本技能可帮助你为任何规模的团队设计并实施有效的Git分支策略,涵盖Git Flow、GitHub Flow、基于主干的开发、发布管理以及分支保护策略。

Workflow Selection Philosophy

工作流选择理念

Key Factors

关键因素

  1. Team size: Solo vs. small team vs. large organization
  2. Release frequency: Continuous vs. scheduled releases
  3. Environment complexity: Single vs. multiple deployment targets
  4. Risk tolerance: Move fast vs. stability first
  1. 团队规模:个人开发者 vs. 小型团队 vs. 大型组织
  2. 发布频率:持续发布 vs. 定期发布
  3. 环境复杂度:单一部署目标 vs. 多部署目标
  4. 风险容忍度:快速迭代 vs. 优先保证稳定性

Workflow Comparison

工作流对比

WorkflowBest ForRelease FrequencyComplexity
Trunk-BasedSmall teams, CI/CDContinuousLow
GitHub FlowMost web appsOn-demandLow
Git FlowVersioned softwareScheduledHigh
GitLab FlowEnvironment-basedMixedMedium
工作流适用场景发布频率复杂度
Trunk-Based小型团队、CI/CD场景持续发布
GitHub Flow大多数Web应用按需发布
Git Flow版本化软件定期发布
GitLab Flow基于环境的部署混合模式

GitHub Flow (Recommended for Most)

GitHub Flow(推荐大多数场景使用)

Overview

概述

Simple, effective workflow for continuous deployment.
main ─────●─────●─────●─────●─────●─────●
            \       /   \       /
feature/x    ●─────●     ●─────●
适用于持续部署的简洁高效工作流。
main ─────●─────●─────●─────●─────●─────●
            \       /   \       /
feature/x    ●─────●     ●─────●

Process

流程

  1. Branch from main
    bash
    git checkout main
    git pull origin main
    git checkout -b feature/user-authentication
  2. Commit regularly
    bash
    git add .
    git commit -m "feat: add login form component"
  3. Push and create PR
    bash
    git push -u origin feature/user-authentication
    gh pr create --title "Add user authentication" --body "..."
  4. Review and merge
    • CI runs tests
    • Peer review
    • Squash merge to main
  5. Deploy
    • Automatic deploy on merge to main
  1. 基于main分支创建分支
    bash
    git checkout main
    git pull origin main
    git checkout -b feature/user-authentication
  2. 定期提交
    bash
    git add .
    git commit -m "feat: add login form component"
  3. 推送并创建PR
    bash
    git push -u origin feature/user-authentication
    gh pr create --title "Add user authentication" --body "..."
  4. 审核并合并
    • CI运行测试
    • 同行评审
    • 压缩合并至main分支
  5. 部署
    • 合并至main分支后自动部署

Branch Naming Convention

分支命名规范

feature/  - New features
fix/      - Bug fixes
docs/     - Documentation
refactor/ - Code refactoring
test/     - Test additions
chore/    - Maintenance tasks
feature/  - 新功能
fix/      - Bug修复
docs/     - 文档更新
refactor/ - 代码重构
test/     - 添加测试用例
chore/    - 维护任务

Configuration

配置示例

yaml
undefined
yaml
undefined

.github/branch-protection.yml (pseudo-config)

.github/branch-protection.yml (伪配置)

main: required_status_checks: strict: true contexts: - "ci/tests" - "ci/lint" - "ci/build" required_pull_request_reviews: required_approving_review_count: 1 dismiss_stale_reviews: true enforce_admins: false restrictions: null
undefined
main: required_status_checks: strict: true contexts: - "ci/tests" - "ci/lint" - "ci/build" required_pull_request_reviews: required_approving_review_count: 1 dismiss_stale_reviews: true enforce_admins: false restrictions: null
undefined

Git Flow (For Versioned Releases)

Git Flow(适用于版本化发布)

Overview

概述

Structured workflow for scheduled release cycles.
main     ─────●─────────────────●─────────────●
               \               /               \
release         ●─────●─────●─                  ●───
                 \     \   /                   /
develop   ●─────●─●─────●─●─────●─────●─────●─●
            \   /   \       /     \       /
feature      ●─●     ●─────●       ●─────●
适用于定期发布周期的结构化工作流。
main     ─────●─────────────────●─────────────●
               \               /               \
release         ●─────●─────●─                  ●───
                 \     \   /                   /
develop   ●─────●─●─────●─●─────●─────●─────●─●
            \   /   \       /     \       /
feature      ●─●     ●─────●       ●─────●

Branches

分支类型

BranchPurposeMerges To
main
Production-ready code-
develop
Integration branch
main
feature/*
New features
develop
release/*
Release preparation
main
,
develop
hotfix/*
Emergency fixes
main
,
develop
分支用途合并目标
main
生产就绪代码-
develop
集成分支
main
feature/*
新功能开发
develop
release/*
发布准备
main
,
develop
hotfix/*
紧急修复
main
,
develop

Feature Development

功能开发流程

bash
undefined
bash
undefined

Start feature

启动功能开发

git checkout develop git pull origin develop git checkout -b feature/new-dashboard
git checkout develop git pull origin develop git checkout -b feature/new-dashboard

Work on feature

开发功能

git commit -m "feat: add dashboard layout" git commit -m "feat: add dashboard charts"
git commit -m "feat: add dashboard layout" git commit -m "feat: add dashboard charts"

Complete feature

完成功能开发

git checkout develop git merge --no-ff feature/new-dashboard git branch -d feature/new-dashboard git push origin develop
undefined
git checkout develop git merge --no-ff feature/new-dashboard git branch -d feature/new-dashboard git push origin develop
undefined

Release Process

发布流程

bash
undefined
bash
undefined

Start release

启动发布准备

git checkout develop git checkout -b release/1.2.0
git checkout develop git checkout -b release/1.2.0

Bump version

更新版本号

npm version 1.2.0 --no-git-tag-version git commit -am "chore: bump version to 1.2.0"
npm version 1.2.0 --no-git-tag-version git commit -am "chore: bump version to 1.2.0"

Fix release issues

修复发布问题

git commit -m "fix: correct typo in release notes"
git commit -m "fix: correct typo in release notes"

Complete release

完成发布

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

Hotfix Process

紧急修复流程

bash
undefined
bash
undefined

Start hotfix

启动紧急修复

git checkout main git checkout -b hotfix/1.2.1
git checkout main git checkout -b hotfix/1.2.1

Fix the issue

修复问题

git commit -m "fix: critical security vulnerability"
git commit -m "fix: critical security vulnerability"

Complete hotfix

完成紧急修复

git checkout main git merge --no-ff hotfix/1.2.1 git tag -a v1.2.1 -m "Hotfix 1.2.1" git push origin main --tags
git checkout develop git merge --no-ff hotfix/1.2.1 git push origin develop
git branch -d hotfix/1.2.1
undefined
git checkout main git merge --no-ff hotfix/1.2.1 git tag -a v1.2.1 -m "Hotfix 1.2.1" git push origin main --tags
git checkout develop git merge --no-ff hotfix/1.2.1 git push origin develop
git branch -d hotfix/1.2.1
undefined

Trunk-Based Development

基于主干的开发

Overview

概述

Everyone commits to main with short-lived branches.
main ─●─●─●─●─●─●─●─●─●─●─●─●─●─●─●─●
        \─/   \─/       \─/
        PR    PR        PR
所有人向main分支提交代码,使用短期分支。
main ─●─●─●─●─●─●─●─●─●─●─●─●─●─●─●─●
        \─/   \─/       \─/
        PR    PR        PR

Principles

核心原则

  1. Short-lived branches (< 1 day)
  2. Small, frequent commits
  3. Feature flags for incomplete work
  4. Comprehensive CI/CD
  1. 短期分支(< 1天)
  2. 小而频繁的提交
  3. 功能开关管理未完成工作
  4. 全面的CI/CD

Feature Flags Integration

功能开关集成示例

typescript
// src/lib/features.ts
export const features = {
  newCheckout: process.env.FEATURE_NEW_CHECKOUT === 'true',
  darkMode: process.env.FEATURE_DARK_MODE === 'true',
};

// Usage
if (features.newCheckout) {
  return <NewCheckout />;
}
return <OldCheckout />;
typescript
// src/lib/features.ts
export const features = {
  newCheckout: process.env.FEATURE_NEW_CHECKOUT === 'true',
  darkMode: process.env.FEATURE_DARK_MODE === 'true',
};

// 使用示例
if (features.newCheckout) {
  return <NewCheckout />;
}
return <OldCheckout />;

Branch Rules

分支规则示例

bash
undefined
bash
undefined

Quick feature (< 4 hours)

快速功能开发(< 4小时)

git checkout main git pull git checkout -b quick/fix-typo
git checkout main git pull git checkout -b quick/fix-typo

... work ...

... 开发工作 ...

git push -u origin quick/fix-typo gh pr create --title "Fix typo" --body ""
git push -u origin quick/fix-typo gh pr create --title "Fix typo" --body ""

Merge immediately after CI passes

CI通过后立即合并

undefined
undefined

Release Management

发布管理

Semantic Versioning

语义化版本控制

MAJOR.MINOR.PATCH

1.0.0 - Initial release
1.1.0 - New feature (backwards compatible)
1.1.1 - Bug fix
2.0.0 - Breaking change
MAJOR.MINOR.PATCH

1.0.0 - 初始版本
1.1.0 - 新增功能(向后兼容)
1.1.1 - Bug修复
2.0.0 - 破坏性变更

Automated Version Bumping

自动化版本更新

json
// package.json
{
  "scripts": {
    "release:patch": "npm version patch && git push --follow-tags",
    "release:minor": "npm version minor && git push --follow-tags",
    "release:major": "npm version major && git push --follow-tags"
  }
}
json
// package.json
{
  "scripts": {
    "release:patch": "npm version patch && git push --follow-tags",
    "release:minor": "npm version minor && git push --follow-tags",
    "release:major": "npm version major && git push --follow-tags"
  }
}

Changelog Generation

变更日志生成

yaml
undefined
yaml
undefined

.github/workflows/release.yml

.github/workflows/release.yml

name: Release
on: push: tags: - 'v*'
jobs: release: runs-on: ubuntu-latest steps: - uses: actions/checkout@v4 with: fetch-depth: 0
  - name: Generate changelog
    id: changelog
    uses: metcalfc/changelog-generator@v4
    with:
      myToken: ${{ secrets.GITHUB_TOKEN }}

  - name: Create Release
    uses: actions/create-release@v1
    env:
      GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
    with:
      tag_name: ${{ github.ref }}
      release_name: Release ${{ github.ref }}
      body: ${{ steps.changelog.outputs.changelog }}
undefined
name: Release
on: push: tags: - 'v*'
jobs: release: runs-on: ubuntu-latest steps: - uses: actions/checkout@v4 with: fetch-depth: 0
  - name: Generate changelog
    id: changelog
    uses: metcalfc/changelog-generator@v4
    with:
      myToken: ${{ secrets.GITHUB_TOKEN }}

  - name: Create Release
    uses: actions/create-release@v1
    env:
      GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
    with:
      tag_name: ${{ github.ref }}
      release_name: Release ${{ github.ref }}
      body: ${{ steps.changelog.outputs.changelog }}
undefined

Conventional Commits

规范化提交格式

bash
undefined
bash
undefined

Format

格式

<type>(<scope>): <description>
[optional body]
[optional footer(s)]
<type>(<scope>): <description>
[可选正文]
[可选页脚]

Types

提交类型

feat: New feature fix: Bug fix docs: Documentation style: Formatting, no code change refactor: Refactoring test: Tests chore: Maintenance
feat: 新功能 fix: Bug修复 docs: 文档更新 style: 格式调整,无代码变更 refactor: 代码重构 test: 测试用例添加 chore: 维护任务

Examples

示例

feat(auth): add password reset flow fix(api): handle null user gracefully docs: update README with new API endpoints chore(deps): update dependencies
undefined
feat(auth): add password reset flow fix(api): handle null user gracefully docs: update README with new API endpoints chore(deps): update dependencies
undefined

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',
        'perf',
        'ci',
        'build',
        'revert',
      ],
    ],
    'subject-case': [2, 'always', 'lower-case'],
    'header-max-length': [2, 'always', 72],
  },
};
javascript
// commitlint.config.js
module.exports = {
  extends: ['@commitlint/config-conventional'],
  rules: {
    'type-enum': [
      2,
      'always',
      [
        'feat',
        'fix',
        'docs',
        'style',
        'refactor',
        'test',
        'chore',
        'perf',
        'ci',
        'build',
        'revert',
      ],
    ],
    'subject-case': [2, 'always', 'lower-case'],
    'header-max-length': [2, 'always', 72],
  },
};

Branch Protection

分支保护

GitHub Branch Protection Rules

GitHub分支保护规则

yaml
undefined
yaml
undefined

Recommended settings for main branch

main分支推荐配置

Required status checks:
  • ci/test
  • ci/lint
  • ci/build
  • ci/typecheck
Required reviews: 1 Dismiss stale reviews: true Require review from code owners: true
Require signed commits: false # Optional Require linear history: true # Encourages squash/rebase
Include administrators: false # Allow admins to bypass
Restrict who can push:
  • Maintainers only
undefined
必填状态检查:
  • ci/test
  • ci/lint
  • ci/build
  • ci/typecheck
必填评审数: 1 驳回过时评审: 是 要求代码所有者评审: 是
要求签名提交: 否 # 可选配置 要求线性提交历史: 是 # 推荐使用压缩/变基合并
包含管理员: 否 # 允许管理员绕过规则
限制推送权限:
  • 仅维护者可推送
undefined

CODEOWNERS

CODEOWNERS示例

undefined
undefined

.github/CODEOWNERS

.github/CODEOWNERS

Default owners

默认所有者

  • @team-lead
  • @team-lead

Frontend

前端

/src/components/ @frontend-team /src/app/ @frontend-team
/src/components/ @frontend-team /src/app/ @frontend-team

Backend

后端

/src/api/ @backend-team /src/lib/db/ @backend-team
/src/api/ @backend-team /src/lib/db/ @backend-team

Infrastructure

基础设施

/.github/ @devops-team /docker/ @devops-team
/.github/ @devops-team /docker/ @devops-team

Docs

文档

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

Merge Strategies

合并策略

Squash and Merge (Recommended)

压缩合并(推荐)

bash
undefined
bash
undefined

Clean history, one commit per feature

保持提交历史整洁,每个功能对应一个提交

git merge --squash feature/branch git commit -m "feat: complete feature description"

**Pros:**
- Clean main history
- Easy to revert features
- Commit message can be edited

**Cons:**
- Loses individual commit history
git merge --squash feature/branch git commit -m "feat: complete feature description"

**优点:**
- main分支历史整洁
- 易于回滚功能
- 可编辑提交信息

**缺点:**
- 丢失单个提交历史

Rebase and Merge

变基合并

bash
undefined
bash
undefined

Linear history, preserves commits

线性提交历史,保留所有提交

git rebase main feature/branch git checkout main git merge feature/branch

**Pros:**
- Linear history
- Preserves individual commits
- Bisect-friendly

**Cons:**
- Requires clean commits
- Force push may be needed
git rebase main feature/branch git checkout main git merge feature/branch

**优点:**
- 线性提交历史
- 保留单个提交记录
- 便于二分查找定位问题

**缺点:**
- 需要提交记录整洁
- 可能需要强制推送

Merge Commit

普通合并提交

bash
undefined
bash
undefined

Preserves full history with merge points

保留完整历史及合并节点

git merge --no-ff feature/branch

**Pros:**
- Complete history preserved
- Clear merge points
- No force push needed

**Cons:**
- Noisy history
- Harder to navigate
git merge --no-ff feature/branch

**优点:**
- 保留完整提交历史
- 合并节点清晰
- 无需强制推送

**缺点:**
- 提交历史杂乱
- 难以导航

Common Scenarios

常见场景处理

Sync Feature Branch with Main

同步功能分支与main分支

bash
undefined
bash
undefined

Option 1: Rebase (clean history)

方案1: 变基(历史整洁)

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

Option 2: Merge (safe, but noisy)

方案2: 合并(安全但历史杂乱)

git checkout feature/my-feature git merge origin/main git push
undefined
git checkout feature/my-feature git merge origin/main git push
undefined

Undo Last Commit (Not Pushed)

撤销未推送的最后一次提交

bash
undefined
bash
undefined

Keep changes staged

保留变更并处于暂存状态

git reset --soft HEAD~1
git reset --soft HEAD~1

Keep changes unstaged

保留变更并处于未暂存状态

git reset HEAD~1
git reset HEAD~1

Discard changes

丢弃所有变更

git reset --hard HEAD~1
undefined
git reset --hard HEAD~1
undefined

Fix Commit Message

修改提交信息

bash
undefined
bash
undefined

Last commit only

仅修改最后一次提交

git commit --amend -m "new message"
git commit --amend -m "new message"

Older commits (interactive rebase)

修改更早的提交(交互式变基)

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

Change 'pick' to 'reword' for target commit

将目标提交的'pick'改为'reword'

undefined
undefined

Cherry-Pick Specific Commit

拣选特定提交

bash
undefined
bash
undefined

Apply specific commit to current branch

将特定提交应用到当前分支

git cherry-pick abc123
git cherry-pick abc123

Cherry-pick without committing

拣选提交但不自动提交

git cherry-pick --no-commit abc123
undefined
git cherry-pick --no-commit abc123
undefined

Recover Deleted Branch

恢复已删除的分支

bash
undefined
bash
undefined

Find the commit

查找提交记录

git reflog
git reflog

Recreate branch

重建分支

git checkout -b recovered-branch abc123
undefined
git checkout -b recovered-branch abc123
undefined

Workflow Scripts

工作流脚本

Git Aliases

Git别名

bash
undefined
bash
undefined

~/.gitconfig

~/.gitconfig

[alias] # Status s = status -sb
# Branching
co = checkout
cob = checkout -b
br = branch -vv

# Commits
cm = commit -m
ca = commit --amend --no-edit

# Logging
lg = log --oneline --graph --decorate -20
lga = log --oneline --graph --decorate --all -20

# Sync
sync = !git fetch origin && git rebase origin/main

# Cleanup
cleanup = !git branch --merged | grep -v main | xargs git branch -d

# Undo
undo = reset --soft HEAD~1
undefined
[alias] # 状态查看 s = status -sb
# 分支操作
co = checkout
cob = checkout -b
br = branch -vv

# 提交操作
cm = commit -m
ca = commit --amend --no-edit

# 日志查看
lg = log --oneline --graph --decorate -20
lga = log --oneline --graph --decorate --all -20

# 同步分支
sync = !git fetch origin && git rebase origin/main

# 清理分支
cleanup = !git branch --merged | grep -v main | xargs git branch -d

# 撤销提交
undo = reset --soft HEAD~1
undefined

Feature Branch Script

功能分支创建脚本

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

scripts/feature.sh

scripts/feature.sh

set -e
BRANCH_TYPE=${1:-feature} BRANCH_NAME=$2
if [ -z "$BRANCH_NAME" ]; then echo "Usage: ./scripts/feature.sh [type] <name>" echo "Types: feature, fix, docs, chore" exit 1 fi
FULL_BRANCH="$BRANCH_TYPE/$BRANCH_NAME"
echo "Creating branch: $FULL_BRANCH"
git checkout main git pull origin main git checkout -b "$FULL_BRANCH"
echo "Branch '$FULL_BRANCH' created and checked out" echo "Run: git push -u origin $FULL_BRANCH"
undefined
set -e
BRANCH_TYPE=${1:-feature} BRANCH_NAME=$2
if [ -z "$BRANCH_NAME" ]; then echo "Usage: ./scripts/feature.sh [type] <name>" echo "Types: feature, fix, docs, chore" exit 1 fi
FULL_BRANCH="$BRANCH_TYPE/$BRANCH_NAME"
echo "Creating branch: $FULL_BRANCH"
git checkout main git pull origin main git checkout -b "$FULL_BRANCH"
echo "Branch '$FULL_BRANCH' created and checked out" echo "Run: git push -u origin $FULL_BRANCH"
undefined

Workflow Checklist

工作流检查清单

Before Selecting Workflow

选择工作流前

  • Understand team size and distribution
  • Define release frequency
  • Assess CI/CD maturity
  • Consider deployment environments
  • 了解团队规模与分布
  • 定义发布频率
  • 评估CI/CD成熟度
  • 考虑部署环境

Implementation

实施阶段

  • Document workflow in CONTRIBUTING.md
  • Configure branch protection rules
  • Set up CODEOWNERS
  • Configure merge strategy
  • Add commit message linting
  • Create Git aliases/scripts
  • 在CONTRIBUTING.md中记录工作流
  • 配置分支保护规则
  • 设置CODEOWNERS
  • 配置合并策略
  • 添加提交信息校验
  • 创建Git别名/脚本

Maintenance

维护阶段

  • Regular branch cleanup
  • Monitor merge queue
  • Review and update protection rules
  • Train new team members
  • 定期清理分支
  • 监控合并队列
  • 评审并更新保护规则
  • 培训新团队成员

When to Use This Skill

何时使用本技能

Invoke this skill when:
  • Starting a new project and choosing a workflow
  • Scaling from solo to team development
  • Improving release management
  • Setting up branch protection rules
  • Creating contribution guidelines
  • Resolving Git workflow conflicts
  • Implementing conventional commits
在以下场景调用本技能:
  • 启动新项目并选择工作流
  • 从个人开发扩展到团队开发
  • 改进发布管理流程
  • 设置分支保护规则
  • 创建贡献指南
  • 解决Git工作流冲突
  • 实施规范化提交格式