跳转到内容

Git 工作流与 CI/CD 集成实战 2026 | 团队协作完全指南

Git 工作流与 CI/CD 集成实战

优秀的 Git 工作流和自动化 CI/CD 是团队高效协作的基石。本文将系统讲解主流 Git 工作流、分支策略、代码审查规范,以及基于 GitHub Actions 的完整 CI/CD 流水线搭建。


一、主流 Git 工作流对比

1.1 Git Flow

main(生产环境)

develop(开发环境)

feature/*    release/*    hotfix/*

特点:

  • 严格的分支模型,适合版本发布周期长的项目
  • 有明确的 maindevelopfeaturereleasehotfix 分支
  • 适合传统软件团队,有明确版本号管理

适用场景: 大型企业项目、桌面软件、有明确版本周期的产品

操作流程:

bash
# 1. 从 develop 创建功能分支
git checkout develop
git checkout -b feature/user-login

# 2. 开发完成后合并回 develop
git checkout develop
git merge --no-ff feature/user-login
git branch -d feature/user-login

# 3. 发布版本
git checkout develop
git checkout -b release/1.2.0
# ... 修复 bug ...
git checkout main
git merge --no-ff release/1.2.0
git tag -a v1.2.0

git checkout develop
git merge --no-ff release/1.2.0
git branch -d release/1.2.0

# 4. 紧急修复
git checkout main
git checkout -b hotfix/1.2.1
# ... 修复 ...
git checkout main
git merge --no-ff hotfix/1.2.1
git tag -a v1.2.1

git checkout develop
git merge --no-ff hotfix/1.2.1
git branch -d hotfix/1.2.1

1.2 GitHub Flow

main

feature/xxx  →  PR →  Code Review →  Merge

特点:

  • 简单直接,只有 main 分支 + 功能分支
  • 通过 Pull Request 进行代码审查
  • 适合持续部署,main 分支随时可发布
  • 是目前最流行的工作流

适用场景: Web 应用、SaaS 产品、持续部署项目

操作流程:

bash
# 1. 从 main 创建分支
git checkout main
git pull origin main
git checkout -b feature/new-dashboard

# 2. 提交代码
git add .
git commit -m "feat: add new dashboard"

# 3. 推送到远程
git push origin feature/new-dashboard

# 4. 创建 Pull Request
# 在 GitHub/GitLab 上操作

# 5. Code Review 通过后合并
# 使用 Squash merge 或 Merge commit

# 6. 删除分支
git checkout main
git pull origin main
git branch -d feature/new-dashboard

1.3 Trunk-Based Development

main (trunk)

short-lived feature branches (max 1-2 days)

特点:

  • 所有人直接向主干(main)提交
  • 功能分支生命周期极短(1-2 天)
  • 配合功能开关(Feature Flag)控制发布
  • CI/CD 要求极高,必须有完善的自动化测试

适用场景: 高绩效团队、快速迭代产品、有完善测试体系的团队

1.4 工作流对比

特性Git FlowGitHub FlowTrunk-Based
复杂度
分支数量
发布频率低(按版本)中(按 PR)高(持续部署)
代码审查可选核心机制快速审查
回滚难度低(版本清晰)
适合团队传统企业团队大多数团队高绩效团队
CI 依赖度极高

二、分支命名规范

2.1 分支命名约定

<类型>/<描述>-<工单ID>

常用类型:

类型说明示例
feature/新功能feature/user-login-#123
fix/Bug 修复fix/login-error-#456
hotfix/紧急修复hotfix/payment-bug-#789
refactor/代码重构refactor/auth-module
docs/文档更新docs/api-update
style/格式调整style/format-code
perf/性能优化perf/query-optimization
chore/构建/工具chore/update-deps

2.2 提交信息规范(Conventional Commits)

<type>(<scope>): <subject>

<body>

<footer>

type 类型:

类型说明
feat新功能
fixBug 修复
docs文档变更
style代码格式(不影响功能)
refactor重构(非新功能也非修 bug)
perf性能优化
test测试相关
chore构建/工具/依赖
ciCI 配置

示例:

feat(auth): add OAuth2 login support

- 实现 Google/GitHub OAuth 登录
- 添加登录状态持久化
- 增加登录失败错误提示

Closes #123
fix(api): handle empty response from user endpoint

当用户未设置头像时返回空字符串导致前端报错,
现在返回默认头像 URL。

Fixes #456

2.3 Commitlint 配置

javascript
// commitlint.config.js
module.exports = {
  extends: ['@commitlint/config-conventional'],
  rules: {
    'type-enum': [2, 'always', [
      'feat', 'fix', 'docs', 'style', 'refactor',
      'perf', 'test', 'chore', 'ci', 'build', 'revert'
    ]],
    'subject-case': [0],
    'subject-max-length': [2, 'always', 72]
  }
}
json
// package.json
{
  "scripts": {
    "prepare": "husky install"
  },
  "devDependencies": {
    "@commitlint/cli": "^19.0.0",
    "@commitlint/config-conventional": "^19.0.0",
    "husky": "^9.0.0"
  }
}
bash
# 安装
npx husky add .husky/commit-msg 'npx --no-install commitlint --edit $1'

三、代码审查(Code Review)

3.1 PR/MR 模板

markdown
<!-- pull_request_template.md -->

## 变更描述

<!-- 简要描述本次变更的内容和目的 -->

## 类型

- [ ] feat: 新功能
- [ ] fix: Bug 修复
- [ ] docs: 文档更新
- [ ] refactor: 代码重构
- [ ] perf: 性能优化
- [ ] test: 测试补充
- [ ] chore: 构建/工具

## 关联 Issue

<!-- Closes #123 -->

## 测试

- [ ] 单元测试通过
- [ ] 集成测试通过
- [ ] E2E 测试通过
- [ ] 已在测试环境验证

## 截图/录屏

<!-- 如有 UI 变更,请附上截图 -->

## 注意事项

<!-- 部署注意事项、数据库迁移等 -->

3.2 代码审查清单

审查者检查清单:

3.3 审查礼仪

  • 对事不对人:评论代码,不评论人
  • 提供建议而非命令:用「建议」「可以考虑」代替「必须」
  • 明确优先级:区分「必须修改」和「可选改进」
  • 及时响应:收到审查请求后尽快处理
  • 小步提交:PR 不要太大,控制在 400 行以内

四、GitHub Actions CI/CD

4.1 基础 CI 流水线

yaml
# .github/workflows/ci.yml
name: CI

on:
  push:
    branches: [main]
  pull_request:
    branches: [main]

jobs:
  lint-and-test:
    runs-on: ubuntu-latest
    steps:
      - name: Checkout
        uses: actions/checkout@v4

      - name: Setup pnpm
        uses: pnpm/action-setup@v3
        with:
          version: 9

      - name: Setup Node.js
        uses: actions/setup-node@v4
        with:
          node-version: 20
          cache: 'pnpm'

      - name: Install dependencies
        run: pnpm install --frozen-lockfile

      - name: Lint
        run: pnpm lint

      - name: Type check
        run: pnpm typecheck

      - name: Test
        run: pnpm test -- --coverage

      - name: Upload coverage
        uses: codecov/codecov-action@v4
        with:
          token: ${{ secrets.CODECOV_TOKEN }}

4.2 构建并部署到 GitHub Pages

yaml
# .github/workflows/deploy.yml
name: Deploy

on:
  push:
    branches: [main]
  workflow_dispatch:

permissions:
  contents: read
  pages: write
  id-token: write

concurrency:
  group: "pages"
  cancel-in-progress: false

jobs:
  build:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v4

      - uses: pnpm/action-setup@v3
        with:
          version: 9

      - uses: actions/setup-node@v4
        with:
          node-version: 20
          cache: 'pnpm'

      - run: pnpm install --frozen-lockfile
      - run: pnpm build

      - uses: actions/configure-pages@v5
      - uses: actions/upload-pages-artifact@v3
        with:
          path: dist

  deploy:
    environment:
      name: github-pages
      url: ${{ steps.deployment.outputs.page_url }}
    runs-on: ubuntu-latest
    needs: build
    steps:
      - id: deployment
        uses: actions/deploy-pages@v4

4.3 Docker 构建与推送

yaml
# .github/workflows/docker.yml
name: Docker Build

on:
  push:
    tags: ['v*']
    branches: [main]

env:
  REGISTRY: ghcr.io
  IMAGE_NAME: ${{ github.repository }}

jobs:
  build:
    runs-on: ubuntu-latest
    permissions:
      contents: read
      packages: write

    steps:
      - uses: actions/checkout@v4

      - name: Set up Docker Buildx
        uses: docker/setup-buildx-action@v3

      - name: Log in to GitHub Container Registry
        uses: docker/login-action@v3
        with:
          registry: ${{ env.REGISTRY }}
          username: ${{ github.actor }}
          password: ${{ secrets.GITHUB_TOKEN }}

      - name: Extract metadata
        id: meta
        uses: docker/metadata-action@v5
        with:
          images: ${{ env.REGISTRY }}/${{ env.IMAGE_NAME }}
          tags: |
            type=ref,event=branch
            type=ref,event=pr
            type=semver,pattern={{version}}
            type=sha

      - name: Build and push
        uses: docker/build-push-action@v5
        with:
          context: .
          push: true
          tags: ${{ steps.meta.outputs.tags }}
          labels: ${{ steps.meta.outputs.labels }}
          cache-from: type=gha
          cache-to: type=gha,mode=max

4.4 矩阵测试

yaml
# .github/workflows/test-matrix.yml
name: Test Matrix

on: [push, pull_request]

jobs:
  test:
    runs-on: ${{ matrix.os }}
    strategy:
      fail-fast: false
      matrix:
        os: [ubuntu-latest, macos-latest, windows-latest]
        node-version: [18, 20, 22]
        exclude:
          - os: windows-latest
            node-version: 18

    steps:
      - uses: actions/checkout@v4

      - name: Setup Node.js ${{ matrix.node-version }}
        uses: actions/setup-node@v4
        with:
          node-version: ${{ matrix.node-version }}
          cache: 'pnpm'

      - name: Install
        run: pnpm install --frozen-lockfile

      - name: Test
        run: pnpm test

4.5 自动发布 npm 包

yaml
# .github/workflows/release.yml
name: Release

on:
  push:
    tags: ['v*']

jobs:
  release:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v4

      - uses: pnpm/action-setup@v3
        with:
          version: 9

      - uses: actions/setup-node@v4
        with:
          node-version: 20
          cache: 'pnpm'
          registry-url: 'https://registry.npmjs.org'

      - run: pnpm install --frozen-lockfile
      - run: pnpm build

      - name: Publish
        run: pnpm publish --access public
        env:
          NODE_AUTH_TOKEN: ${{ secrets.NPM_TOKEN }}

      - name: Create GitHub Release
        uses: softprops/action-gh-release@v2
        with:
          generate_release_notes: true

五、高级 CI/CD 配置

5.1 缓存优化

yaml
# 依赖缓存
- uses: actions/cache@v4
  with:
    path: |
      ~/.pnpm-store
      **/node_modules
    key: ${{ runner.os }}-pnpm-${{ hashFiles('**/pnpm-lock.yaml') }}
    restore-keys: |
      ${{ runner.os }}-pnpm-

# 构建缓存(Vite)
- uses: actions/cache@v4
  with:
    path: .vite
    key: ${{ runner.os }}-vite-${{ hashFiles('**/vite.config.*') }}
    restore-keys: |
      ${{ runner.os }}-vite-

5.2 条件执行

yaml
jobs:
  test:
    runs-on: ubuntu-latest
    if: |
      github.event_name == 'pull_request' ||
      contains(github.event.head_commit.message, '[ci]')
    steps:
      - uses: actions/checkout@v4
      # ...

  deploy-staging:
    runs-on: ubuntu-latest
    needs: [test]
    if: github.ref == 'refs/heads/main'
    steps:
      - name: Deploy to Staging
        run: echo "Deploying..."

5.3 环境变量与 Secrets

yaml
jobs:
  deploy:
    runs-on: ubuntu-latest
    environment: production  # 环境保护规则
    env:
      API_URL: ${{ vars.API_URL }}
      DB_HOST: ${{ secrets.DB_HOST }}
    steps:
      - run: echo "$API_URL"

5.4 手动触发

yaml
on:
  workflow_dispatch:
    inputs:
      environment:
        description: '部署环境'
        required: true
        default: 'staging'
        type: choice
        options:
          - staging
          - production
      version:
        description: '版本号'
        required: true

jobs:
  deploy:
    runs-on: ubuntu-latest
    steps:
      - run: |
          echo "部署到: ${{ github.event.inputs.environment }}"
          echo "版本: ${{ github.event.inputs.version }}"

六、Git 高级技巧

6.1 交互式变基

bash
# 合并多个提交
git rebase -i HEAD~5

# 常用操作:
# p, pick = 使用该提交
# s, squash = 合并到前一个提交
# f, fixup = 合并到前一个提交(丢弃提交信息)
# r, reword = 修改提交信息
# e, edit = 编辑该提交
# d, drop = 删除该提交

6.2 Cherry-pick

bash
# 挑选某个提交应用到当前分支
git cherry-pick <commit-hash>

# 挑选多个提交
git cherry-pick <commit1> <commit2>

# 挑选一个范围
git cherry-pick <start>..<end>

6.3 Bisect 二分查找 Bug

bash
# 开始二分查找
git bisect start

# 标记当前版本为坏
git bisect bad

# 标记某个版本为好
git bisect good v1.0.0

# 测试当前版本,标记好/坏
git bisect good   # 好版本
git bisect bad    # 坏版本

# 找到引入 bug 的提交后,结束
git bisect reset

6.4 工作暂存

bash
# 暂存当前工作
git stash push -m "wip: user login"

# 查看暂存列表
git stash list

# 应用最新暂存
git stash pop

# 应用指定暂存
git stash apply stash@{1}

# 删除暂存
git stash drop stash@{0}

# 清空所有暂存
git stash clear

七、团队协作最佳实践

7.1 保护主分支

yaml
# GitHub 分支保护规则建议
# Settings → Branches → Branch protection rules

Branch name pattern: main

✅ Require a pull request before merging
   ✅ Require approvals: 1

✅ Require status checks to pass before merging
   ✅ Require branches to be up to date before merging
   Status checks: lint, test, build

✅ Require signed commits
✅ Require linear history
✅ Include administrators

7.2 Git 配置建议

bash
# 全局配置
git config --global user.name "Your Name"
git config --global user.email "your@email.com"

# 默认推送当前分支
git config --global push.default current

# 拉取时自动变基(避免无谓的 merge commit)
git config --global pull.rebase true

# 自动设置上游分支
git config --global push.autoSetupRemote true

# 设置默认分支名
git config --global init.defaultBranch main

# 换行符处理
git config --global core.autocrlf input  # macOS/Linux
git config --global core.autocrlf true   # Windows

# 编辑器
git config --global core.editor "code --wait"

7.3 .gitignore 最佳实践

gitignore
# Dependencies
node_modules/
.pnp
.pnp.js

# Build output
dist/
build/
.next/
.nuxt/

# Environment files
.env
.env.local
.env.*.local

# IDE
.vscode/
.idea/
*.swp
*.swo

# OS
.DS_Store
Thumbs.db

# Logs
logs/
*.log
npm-debug.log*

# Testing
coverage/
.nyc_output/

# Cache
.cache/
.parcel-cache/
.turbo/

八、总结

  • ✅ 掌握三种主流 Git 工作流(Git Flow、GitHub Flow、Trunk-Based)
  • ✅ 规范的分支命名与 Conventional Commits 提交规范
  • ✅ 代码审查流程与审查清单
  • ✅ GitHub Actions 完整 CI/CD 流水线(测试、构建、部署、Docker)
  • ✅ 高级 CI/CD 配置(缓存、条件执行、环境变量、手动触发)
  • ✅ Git 高级技巧(变基、cherry-pick、bisect、stash)
  • ✅ 团队协作最佳实践(分支保护、Git 配置、.gitignore)

优秀的 Git 工作流和 CI/CD 不是一蹴而就的,需要根据团队规模和项目特点持续迭代优化。


相关阅读: