我需要在创建合并请求时自动触发gitlab管道。该管道应在单击合并之前自动启动。我已经编写了这个管道,但没有按我的预期工作。现在通过单击合并按钮来完成此操作。我需要从自动创建合并请求开始。
default:
tags:
- $RUNNER_TAG
stages:
- sonarqube
- merge
# SonarQube scan on the source branch (relative branch)
sonarqube-check:
stage: sonarqube
image: node:slim
cache:
key: "${CI_JOB_NAME}"
paths:
- .sonar/cache
script:
- apt-get update -y
- apt-get install -y git
- git checkout $CI_COMMIT_REF_NAME # Check out the branch related to the MR
- git pull origin $CI_COMMIT_REF_NAME # Pull latest changes
- yarn install
- yarn coverage:ci
- npx sonarqube-scanner -Dproject.settings=./sonar-project-el.properties
# Extract project key from sonar-project.properties
- PROJECT_KEY=$(grep sonar.projectKey sonar-project-el.properties | cut -d '=' -f2)
# Fetch the quality gate result from SonarQube API
- |
QUALITY_GATE=$(curl -s -u $SONAR_LOGIN: $SONAR_HOST_URL/api/qualitygates/project_status?projectKey=$PROJECT_KEY | jq -r .projectStatus.status)
if [ "$QUALITY_GATE" != "OK" ]; then
echo "SonarQube quality gate failed. MR cannot be merged."
exit 1
fi
allow_failure: false
rules:
- if: '$CI_PIPELINE_SOURCE == "merge_request_event"'
when: never
- if: $CI_COMMIT_BRANCH != $CI_DEFAULT_BRANCH
when: always
# Job for the automatic merge, triggered when the SonarQube check passes
merge-to-develop:
stage: merge
image: alpine/git
script:
- git fetch origin
- git checkout develop
- git pull origin develop
- git merge --no-ff origin/$CI_COMMIT_REF_NAME # Merge dynamically determined MR branch into develop
- git push origin develop # Push the merged changes to develop
rules:
- if: '$CI_MERGE_REQUEST_TARGET_BRANCH_NAME == "develop"' # Run only if MR targets develop
when: on_success
如何解决这个问题?
在你的
sonarqube-check
工作中,你的规则是错误的:
rules:
- if: '$CI_PIPELINE_SOURCE == "merge_request_event"'
when: never
- if: $CI_COMMIT_BRANCH != $CI_DEFAULT_BRANCH
when: always
$CI_PIPELINE_SOURCE == "merge_request_event"
是创建新MR时触发的事件。删除那里的when: never
。