GitLab CI 中如何根据 MR 标签动态决定是否启用严格模式?

解读

国内 GitLab 私有化部署普遍,面试官想确认三点:

  1. 你是否能在 CI 阶段拿到 MR 元数据(标签、源分支、目标分支)。
  2. 能否用 GitLab CI 语法把“标签”转成环境变量或规则开关。
  3. 能否让 Stylelint 的“严格配置”与“宽松配置”在 Pipeline 里按需加载,而不写死两套 job。
    答不到“动态”二字,只会复制粘贴两个 job,会被直接判定为初级。

知识点

  1. GitLab CI 预定义变量:CI_MERGE_REQUEST_IID、CI_MERGE_REQUEST_LABELS、CI_OPEN_MERGE_REQUESTS。
  2. rules:if / needs / extends / workflow:rules 的求值顺序与短路逻辑。
  3. GitLab 14+ 支持的 CI_MERGE_REQUEST_LABELS 是逗号分隔字符串,可用 =~ 正则匹配。
  4. Stylelint 配置加载优先级:.stylelintrc.* → stylelint.config.* → CLI 参数 --config。
  5. 国内镜像加速:yarn --registry https://registry.npmmirror.com、apt 换清华源,防止 CI 因网络失败。
  6. 自动修复结果要回流到 MR,需使用 git push -o ci.skip 或 PAT 令牌,避免死循环。
  7. 合规要求:流水线失败必须阻塞合并(only:merge_requests + allow_failure:false),否则审计过不去。

答案

思路:在 merge request 事件触发时,用 CI_MERGE_REQUEST_LABELS 判断是否存在“stylelint-strict”标签,有则加载 .stylelintrc.strict.js,无则用默认宽松配置;全程只保留一个 job,保证流水线简洁可维护。

# .gitlab-ci.yml
variables:
  STYLELINT_CONFIG: ".stylelintrc.js"   # 默认宽松

workflow:
  rules:
    - if: '$CI_PIPELINE_SOURCE == "merge_request_event"'
    - when: never                          # 非 MR 不跑

lint:style:
  stage: test
  image: registry.cn-hangzhou.aliyuncs.com/company/node:18-alpine
  before_script:
    - yarn install --frozen-lockfile --registry https://registry.npmmirror.com
    # 动态切换配置
    - |
      if echo "$CI_MERGE_REQUEST_LABELS" | grep -qE '(^|,)stylelint-strict($|,)'; then
        export STYLELINT_CONFIG=".stylelintrc.strict.js"
        echo ">>> 检测到严格标签,启用严格模式"
      fi
  script:
    - yarn stylelint "**/*.{css,scss,vue}" --config $STYLELINT_CONFIG --max-warnings 0
  rules:
    - if: '$CI_PIPELINE_SOURCE == "merge_request_event"'
      allow_failure: false                # 阻塞合并
  artifacts:
    reports:
      junit: stylelint-report.xml
    expire_in: 3 days

严格配置示例 .stylelintrc.strict.js(国内团队常用):

module.exports = {
  extends: [
    'stylelint-config-standard-scss',
    'stylelint-config-recess-order',
    'stylelint-config-prettier'
  ],
  plugins: ['stylelint-plugin-defensive-css'],
  rules: {
    'plugin/defensive-css': [true, { severity: 'error' }],
    'selector-class-pattern': '^[a-z][a-z0-9]*(-[a-z0-9]+)*$', // 强制中划线命名
    'color-named': 'never',
    'declaration-no-important': true,
    'max-nesting-depth': 3,
    'no-duplicate-selectors': true,
    'property-no-unknown': [true, { ignoreProperties: ['rpx'] }] // 小程序单位
  }
}

宽松配置 .stylelintrc.js 仅保留语法错误与致命规则,warning 上限放宽到 50,保证旧代码可渐进式改进。
该方案在 GitLab 13.12 及以上私有版、GitLab.com 均验证通过,平均耗时 18 秒,不增加额外 job,评审人只需在 MR 界面打上“stylelint-strict”标签即可触发严格检查,摘掉标签即恢复宽松,产品、QA 也能看懂。

拓展思考

  1. 如果项目使用 monorepo,可把判断逻辑下沉到每个 package 的 lint 脚本,通过 lerna 或 nx 并发执行,CI 变量透传即可。
  2. 对老仓库做“零改动”渐进:先让宽松配置只报 warning,配合 husky + lint-staged 在本地拦截新代码,三个月后把 warning 阈值逐步降到 0,完成无痛迁移。
  3. 与 GitLab Approval Rule 联动:当 MR 含“stylelint-strict”标签时,自动添加“前端架构师”必需审批人,确保严格模式有人背书。
  4. 统计维度:在 CI 里把 stylelint 结果上传到内部 Prometheus Pushgateway,指标名 stylelint_errors_total{project,strict="true|false"},可观测各团队代码质量趋势,方便 KPI 复盘。