The Bitbucket, GitHub and Gitlab Branch Source Plugins are a popular way to trigger project analysis from Jenkins.
Jenkins will set up the job and perform SCM checkout based on values exposed by those plugins through an API.
It also sets environment variables that we could use to make configuration of SonarQube analysis simpler.
First, to detect that the scanner is running on Jenkins, we could verify that JENKINS_URL and JENKINS_HOME are set.
On a PR, CHANGE_TARGET is set and can be used to detect that what is being built is a P/R.
The scanner can be configured in the following way.
- sonar.pullrequest.base: use CHANGE_TARGET
- sonar.pullrequest.branch: use CHANGE_BRANCH
- sonar.pullrequest.key: use CHANGE_ID
For sonar.scm.revision it's a little bit trickier because unfortunately there is no environment variable exposed that will always contain the correct value.
CHANGE_ID contains the commit ID being built but it's not necessarily the HEAD of the branch from where the P/R originates from.
The default checkout strategy used by Jenkins is to merge the target branch onto the P/R branch. If both branches have diverged, this will create a merge commit that only exists locally. In that case, that's the commit in CHANGE_ID and it will be useless for P/R decoration since it doesn't even exist in the ALM.
To find the HEAD of the branch from where the pull request was created, we can try to use git to read the local references. Jenkins fetches the pull request branch to refs/remotes/origin/[PR ID] in both checkout strategies. "PR ID" will be something like "PR-7", and it can be detected using the environment variables BRANCH_NAME or GIT_BRANCH.
This strategy was tested with GitLab branch plugin and GitHub branch plugin.
we would like:
If any of the 4 parameters is manually specified by the user, the automatic detection is disabled for all 4 parameters.
Implementation can be done in the scanner-engine (or in one of its extensions).
It will require a new dependency on JGit, to avoid having to use the Git SCM plugin for it.
Log a info/warn if user is configuring branch/PR analysis and we know we can do it automatically.