Skip to content

Git 与 CI/CD

Git 事件是 CI/CD(持续集成/持续部署)的核心触发机制。将 Git 操作与自动化流水线结合,实现代码质量保证和自动部署。

Git 事件触发构建

GitHub Actions 触发事件

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

on:
  # Push 到指定分支时触发
  push:
    branches: [main, develop]
    paths:
      - 'src/**'
      - 'tests/**'
      - 'package.json'

  # PR 时触发(针对目标分支)
  pull_request:
    branches: [main, develop]
    types: [opened, synchronize, reopened]

  # PR review 后触发
  pull_request_review:
    types: [submitted]

  # 定时触发(每天凌晨 2 点)
  schedule:
    - cron: '0 2 * * *'

  # 手动触发
  workflow_dispatch:
    inputs:
      environment:
        description: '部署环境'
        required: true
        default: 'staging'

jobs:
  test:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v4
      - uses: actions/setup-node@v4
        with:
          node-version: '20'
          cache: 'npm'
      - run: npm ci
      - run: npm test
      - run: npm run build

GitLab CI 触发事件

yaml
# .gitlab-ci.yml
stages:
  - test
  - build
  - deploy

test:
  stage: test
  rules:
    - if: '$CI_PIPELINE_SOURCE == "push"'
    - if: '$CI_MERGE_REQUEST_ID'
  script:
    - npm ci
    - npm test

build:
  stage: build
  rules:
    - if: '$CI_COMMIT_BRANCH == "main"'
  script:
    - npm run build
  artifacts:
    paths:
      - dist/

基于 Tag 的自动发布

当推送 Tag 时,自动触发发布流程:

GitHub Actions 自动发布

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

on:
  push:
    tags:
      - 'v*'  # 匹配 v1.0.0、v2.1.3 等

jobs:
  release:
    runs-on: ubuntu-latest
    permissions:
      contents: write

    steps:
      - uses: actions/checkout@v4
        with:
          fetch-depth: 0  # 完整历史(用于生成 CHANGELOG)

      - name: 安装依赖
        run: npm ci

      - name: 运行测试
        run: npm test

      - name: 构建
        run: npm run build

      - name: 发布到 npm
        run: npm publish
        env:
          NODE_AUTH_TOKEN: ${{ secrets.NPM_TOKEN }}

      - name: 创建 GitHub Release
        uses: softprops/action-gh-release@v1
        with:
          generate_release_notes: true  # 自动生成发布说明
          files: |
            dist/*.zip
            dist/*.tar.gz

版本号提取和验证

yaml
- name: 获取版本号
  id: version
  run: echo "VERSION=${GITHUB_REF#refs/tags/v}" >> $GITHUB_OUTPUT

- name: 验证版本号格式
  run: |
    VERSION="${{ steps.version.outputs.VERSION }}"
    if ! echo "$VERSION" | grep -qE '^[0-9]+\.[0-9]+\.[0-9]+'; then
      echo "版本号格式不正确:$VERSION"
      exit 1
    fi

分支策略与环境部署

常见的分支到环境映射策略:

三环境部署策略

main → 生产环境(production)
develop → 测试环境(staging)
feature/* → 预览环境(preview,按需创建)
yaml
# .github/workflows/deploy.yml
name: Deploy

on:
  push:
    branches: [main, develop]

jobs:
  deploy:
    runs-on: ubuntu-latest
    environment: ${{ github.ref == 'refs/heads/main' && 'production' || 'staging' }}

    steps:
      - uses: actions/checkout@v4

      - name: 确定部署环境
        id: env
        run: |
          if [[ "${{ github.ref }}" == "refs/heads/main" ]]; then
            echo "ENV=production" >> $GITHUB_OUTPUT
            echo "URL=https://app.example.com" >> $GITHUB_OUTPUT
          else
            echo "ENV=staging" >> $GITHUB_OUTPUT
            echo "URL=https://staging.example.com" >> $GITHUB_OUTPUT
          fi

      - name: 部署到 ${{ steps.env.outputs.ENV }}
        run: |
          echo "部署到 ${{ steps.env.outputs.ENV }}..."
          # 你的部署命令

PR 预览环境

yaml
name: Preview Environment

on:
  pull_request:
    types: [opened, synchronize, closed]

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

      - name: 部署预览
        if: github.event.action != 'closed'
        run: |
          # 创建 PR 专属的预览环境
          PREVIEW_URL="https://pr-${{ github.event.number }}.preview.example.com"
          echo "预览地址:$PREVIEW_URL"

      - name: 清理预览
        if: github.event.action == 'closed'
        run: |
          echo "清理 PR #${{ github.event.number }} 的预览环境"

Git Hooks + CI 联动

客户端钩子减轻 CI 负担

在本地提前发现问题,减少 CI 失败率:

bash
# .husky/pre-commit(本地快速检查)
npm run lint:staged    # 只检查暂存区文件(快)

# .husky/pre-push(本地完整检查)
npm test               # 完整测试(慢,但在推送前执行)
npm run build          # 确保能构建成功

CI 检查清单

yaml
# 完整的 CI 检查流水线
jobs:
  quality-check:
    runs-on: ubuntu-latest
    steps:
      - name: 代码风格检查
        run: npm run lint

      - name: 类型检查(TypeScript)
        run: npm run type-check

      - name: 单元测试
        run: npm run test:unit

      - name: 集成测试
        run: npm run test:integration

      - name: 测试覆盖率检查
        run: npm run test:coverage -- --threshold 80

      - name: 安全漏洞扫描
        run: npm audit --audit-level high

      - name: 构建检查
        run: npm run build

      - name: Bundle 大小检查
        run: npx bundlesize

保护分支与必须通过的检查

配置"必须通过某些 CI 检查才能合并":

GitHub 设置路径:
Repository → Settings → Branches → Branch protection rules

必须通过的状态检查:
✅ CI / quality-check(lint、test、build)
✅ security-scan
✅ coverage-check

实用技巧

跳过 CI 触发

bash
# 某些小改动不需要 CI(如更新 README)
git commit -m "docs: 更新 README [skip ci]"
git commit -m "docs: 更新 README [ci skip]"

# GitHub Actions 支持:
# git commit -m "docs: 更新 README

# skip-checks: true

在 CI 中使用 Git 操作

yaml
- name: 设置 Git 身份(CI 环境)
  run: |
    git config user.name "GitHub Actions Bot"
    git config user.email "actions@github.com"

- name: 自动提交(如更新版本号)
  run: |
    git add package.json
    git commit -m "chore: bump version to ${{ steps.version.outputs.VERSION }}"
    git push

总结

触发器用途
push: branches: [main]部署到生产环境
pull_requestPR 质量检查
push: tags: ['v*']自动发布
schedule定时任务(安全扫描等)
workflow_dispatch手动部署

将 Git 工作流与 CI/CD 紧密结合,是现代软件开发的核心实践。自动化测试、检查和部署,让团队能以更高的频率和信心交付软件。