如何设置 GitHub Actions 卡点禁止合并不合规代码?

解读

面试官问的不是“CI 怎么跑”,而是“怎么让不合规的代码根本进不了主干”。
在国内真实场景里,仓库往往放在 GitHub(或 Gitee 企业版),合并方式以 Pull Request(Merge Request)为主,合规定义通常包含:

  1. 代码风格(stylelint + prettier)
  2. 静态质量(eslint、typescript、postcss-safe-parser)
  3. 单元测试(jest、vitest)
  4. 构建产物体积(postcss + cssnano 后大小阈值)
  5. 安全与合规(依赖漏洞扫描、license 检查)

卡点 = 把上述检查变成“Required Status Check”,任一项失败即禁止 GitHub 合并按钮变绿,并同步到企业微信/飞书群,让代码审查者无法强行合并。

知识点

  • GitHub Actions workflow 触发事件:pull_request、push、workflow_call
  • job 级别 strategy.matrix 可并行跑多版本 Node
  • status check 与 branch protection rule(分支保护规则)
  • actions 生态:actions/checkout、actions/setup-node、reviewdog、wearerequired/lint-action
  • PostCSS 特有卡点:
    – postcss-safe-parser 必须零 warning
    – autoprefixer 与 browserslist 需命中国内双端清单(Android 7+、iOS 10+)
    – cssnano 压缩后体积 diff 不超过主分支 3 %
  • 失败上报:GitHub Checks API、PR comment、飞书机器人 webhook
  • 缓存策略:actions/cache 锁定 pnpm-lock.yaml 的 hash,减少安装耗时
  • 权限最小化:GITHUB_TOKEN 默认只读,需额外申请 contents:write、pull-requests:write 才能回写评论

答案

  1. 在项目根目录创建 .github/workflows/css-gate.yml
name: CSS Gate

on:
  pull_request:
    types: [opened, synchronize, reopened]
    paths:
      - '**/*.css'
      - '**/*.pcss'
      - '**/*.scss'
      - 'package.json'
      - 'pnpm-lock.yaml'
      - '.browserslistrc'

concurrency:
  group: ${{ github.workflow }}-${{ github.head_ref }}
  cancel-in-progress: true

jobs:
  lint-and-build:
    runs-on: ubuntu-latest
    strategy:
      matrix:
        node: [18, 20]
    steps:
      - name: Checkout
        uses: actions/checkout@v4
        with:
          fetch-depth: 0

      - name: Setup pnpm
        uses: pnpm/action-setup@v2
        with:
          version: 8

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

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

      - name: Lint CSS
        run: |
          pnpm exec stylelint "**/*.{css,pcss,scss}" --formatter json --output lint-result.json
        continue-on-error: false

      - name: Parse & Validate PostCSS AST
        run: |
          pnpm exec postcss **/*.pcss --parser postcss-safe-parser --map false --verbose 2>&1 | tee postcss.log
          if grep -q "Warning\|Error" postcss.log; then exit 1; fi

      - name: Build & Size Diff
        run: |
          pnpm run build:css
          echo "BASE_SIZE=$(git show origin/${{ github.base_ref }}:dist/index.css | wc -c)" >> $GITHUB_ENV
          echo "HEAD_SIZE=$(wc -c < dist/index.css)" >> $GITHUB_ENV

      - name: Check Bundle Size
        run: |
          MAX_SIZE=$(($BASE_SIZE * 103 / 100))
          if [ $HEAD_SIZE -gt $MAX_SIZE ]; then
            echo "::error::CSS体积超出阈值,基线${BASE_SIZE}字节,当前${HEAD_SIZE}字节"
            exit 1
          fi

      - name: Upload Size Report
        if: always()
        uses: actions/github-script@v7
        with:
          script: |
            const fs = require('fs');
            const head = process.env.HEAD_SIZE;
            const base = process.env.BASE_SIZE;
            const diff = ((head - base) / base * 100).toFixed(2);
            const body = `📦 CSS 体积变化:基线 ${base} → 当前 ${head} 字节(${diff > 0 ? '+' : ''}${diff}%)`;
            github.rest.issues.createComment({
              issue_number: context.issue.number,
              owner: context.repo.owner,
              repo: context.repo.repo,
              body
            });
  1. 在 GitHub 仓库 Settings → Branches → Add rule,勾选:

    • Restrict pushes that create files larger than 100 KB
    • Require a pull request before merging
    • Require status checks to pass before merging
    • 搜索并选中 CSS Gate (lint-and-build) 作为 Required Status
    • 勾选 Require branches to be up to date before merging
    • 勾选 Include administrators
  2. 如需飞书提醒,在 job 末尾加一步:

      - name: Notify Feishu
        if: failure()
        run: |
          curl -X POST ${{ secrets.FEISHU_BOT_HOOK }} \
            -H 'Content-Type: application/json' \
            -d '{"msg_type":"text","content":{"text":"🔴 PostCSS 质量卡点失败,PR #'${{ github.event.number }}'"}}'

至此,任何一次 PR 只要 stylelint 报错、PostCSS AST 解析告警、或构建体积超标,GitHub 都会把合并按钮置灰,并同步到飞书群,实现真正的“零不合规代码进主干”。

拓展思考

  1. 多仓库复用:把 css-gate.yml 做成 reusable workflow,放到 .github 仓库,其他业务库一行调用即可,避免重复 YAML。
  2. 渐进式迁移:老项目存量 warning 过多,可先在 workflow 里加 continue-on-error: true 并只作 comment,待清零后再改为 hard fail。
  3. 性能优化:把 PostCSS 插件链做成 esbuild 插件,利用原生速度把 30 s 的 CI 降到 8 s,提升开发者体验。
  4. 安全左移:在本地 git hooks(husky + lint-staged)先跑一遍 postcss-safe-parser,90 % 问题在 push 前解决,CI 只做兜底。
  5. 国内替代:若代码托管在 Gitee 企业版,可用 Gitee Go 的 gate 节点,脚本逻辑完全一致,只需把 secrets 换成 Gitee 的凭据。