In a multibranch pipeline, there is an option to build PR merged with the base branch. When this option is enabled GIT_COMMIT environment variable contains the hash of the merged commit not the hash of the last hash of the change branch. There is no other environment variable set with the branch revision hash.
But I want the hash of the branch revision to run Sonar PR analysis and for some other reporting tasks. How can I achieve this?
https://issues.jenkins-ci.org/browse/JENKINS-39496 describes about PullRequestSCMRevision. But I have no idea on how to call the PullRequestSCMRevision.getPullHash() function inside a Jenkinsfile in a declarative pipeline.
I don't see my requirement is supported by Jenkins. But as suggested by @Omer in the above comment we can get our work done by calling git rev-parse remotes/origin/$BRANCH_NAME
in the Jenkinsfile. You can introduce a new environment variable to your build environment of a declarative pipeline by calling this in a scripted environment variable as follows.
REVISION = """${
sh(
returnStdout: true,
script: '''
if [ ${CHANGE_ID+x} ]; then
git rev-parse remotes/origin/$BRANCH_NAME
else
echo "$GIT_COMMIT"
fi
'''
).trim()
}"""
Then you can use REVISION
environment variable to refer to the git revision for any kind of build (branch, pull request revision, pull request merge revision).
Note: git rev-parse $BRANCH_NAME
may not work pull request merge revision pipelines because this command return the revision of your local branch which is different from the remote branch due to the auto merge commit done by Jenkins.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.