Gitlab CI规则:合并提交时跳过commitlint校验任务
解决GitLab CI中commitlint跳过自动合并提交的问题
你的核心问题是:GitLab自动生成的合并提交(Merge Request合并时创建的提交)会触发main分支的commitlint校验Job,而这类提交不需要遵循规范。原配置只限制了流水线来源和分支,但未区分手动提交与自动合并提交,因此会触发Job。
解决方案1:通过提交信息关键词排除
GitLab自动合并的提交信息通常以Merge branch或Merge remote-tracking branch开头,直接在rules里增加排除条件:
lint:commitMain: image: registry.hub.docker.com/library/node:alpine tags: - docker stage: lint variables: GIT_DEPTH: 0 before_script: - apk add --no-cache git - npm install --save-dev @commitlint/config-conventional @commitlint/cli script: - npx commitlint --from $CI_COMMIT_BEFORE_SHA --to $CI_COMMIT_SHA rules: - if: '$CI_PIPELINE_SOURCE == "merge_request_event"' when: never # 排除GitLab自动生成的合并提交 - if: '$CI_PIPELINE_SOURCE == "push" && $CI_COMMIT_BRANCH == "main" && !$CI_COMMIT_MESSAGE =~ /^Merge branch/ && !$CI_COMMIT_MESSAGE =~ /^Merge remote-tracking branch/' when: on_success - when: never
解决方案2:通过Git命令判断合并提交(更准确)
合并提交存在两个父节点,可在脚本阶段先判断是否为合并提交,是则直接跳过校验:
lint:commitMain: image: registry.hub.docker.com/library/node:alpine tags: - docker stage: lint variables: GIT_DEPTH: 0 before_script: - apk add --no-cache git - npm install --save-dev @commitlint/config-conventional @commitlint/cli script: - | # 检查当前提交是否为合并提交(存在第二个父节点) if git rev-parse --verify $CI_COMMIT_SHA^2 >/dev/null 2>&1; then echo "检测到合并提交,跳过commitlint校验" exit 0 fi npx commitlint --from $CI_COMMIT_BEFORE_SHA --to $CI_COMMIT_SHA rules: - if: '$CI_PIPELINE_SOURCE == "merge_request_event"' when: never - if: '$CI_PIPELINE_SOURCE == "push" && $CI_COMMIT_BRANCH == "main"' when: on_success - when: never
原配置失效原因
自动合并提交的流水线来源是push,分支也是main,完全符合原配置的触发条件,因此会执行Job。新增的排除条件能精准区分这类自动提交,避免不必要的校验。
内容的提问来源于stack exchange,提问作者Finkman
相关产品推荐
相关产品推荐

