2
votes

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.

1
If possible, I suggest you call "Sonar PR analysis" and "other reporting tasks" from a shell script that is called by the Jenkinsfile, rather than doing it directly inside the limited syntax of the Jenkinsfile. Then you can git rev-parse PRBRANCHNAMEHERE to get the actual commit of the PR branch rather than the temporary merge commit.Omer Tuchfeld
git rev-parse PRBRANCHNAMEHERE worked for me. Thanks a lot for the point.Dulaj Atapattu

1 Answers

1
votes

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.