How to Connect Your GitHub Project to Sonar

olsido

Olga Strijewski

Posted on July 6, 2024

How to Connect Your GitHub Project to Sonar

Introduction

This guide will walk you through setting up SonarCloud for a GitHub project to automatically inspect code for bugs and vulnerabilities. Additionally, it covers common errors encountered during the setup process.

You can check out the GitHub repository used for this project here: github-workflow-demo.

Difference between SonarCloud and SonarQube

Sonar comes in two flavours - SonarCloud and SonarQube.

SonarCloud is a cloud-based service provided by SonarSource for continuous code quality and security inspection, ideal for projects hosted on GitHub, Bitbucket, or Azure DevOps. SonarQube, on the other hand, is a self-hosted solution that requires you to install and manage the server infrastructure, offering greater control and customization for larger or more complex projects. Both tools provide similar functionalities for analyzing code quality but cater to different hosting and infrastructure preferences.

We will use SonarCloud in this tutorial.

What are GitHub Actions and Workflows?

GitHub Actions is a powerful automation tool integrated into GitHub, enabling users to create custom software development workflows directly within their repositories. Workflows are defined in YAML files and can be triggered by various events, such as code commits, pull requests, or scheduled times. These workflows can include multiple jobs and steps to automate tasks like building, testing, and deploying code, thus streamlining the development and CI/CD (Continuous Integration/Continuous Deployment) processes.

Connecting Your Project to SonarCloud

Please have a look at this tutorial for detailed steps on how to establish a connection between your project on GitHub and SonarCloud: How to Enable SonarCloud for Your Project.

Setting Up a Sonar Action - Easy Way

Creating an action for automated SonarCloud checks seems very straightforward. Here is how GitHub suggests doing it...

Click on the "Actions" menu:

Image description

...then search for a Sonar action template:

Image description

We already discussed the difference between SonarCloud and SonarQube in an earlier chapter.

So, for our purposes, we are going to pick "SonarCloud." Click on the "Configure" button:

Image description

GitHub will create the workflow file for you in the correct directory in your repository, which you want to connect to SonarCloud. As you can see, it has some suggestions for next steps for you in the header of the file (enclosed in the red rectangle below), followed by the instructions in YAML format:

Image description

Theoretically, if you follow the steps, it will work. Of course, in the real world, each application is different and requires adjustments to this out-of-the-box script (as did my application - I will describe this below).

But first, let's follow the steps and see what we get.

The first two steps just tell us to connect our project to SonarCloud, which we did in How to Enable SonarCloud for Your Project mentioned above.

So, let's do step number 3.

Let's go to our SonarCloud application and click on "Information:"

Image description

We can copy our Project Key and Organization Key from the Information screen:

Image description

...and then paste them in the appropriate place in the YAML config file:

Image description

To generate the token, let's go to "My Account:"

Image description

...and then, in the "Security" tab, enter the name for the token and click on "Generate Token:"

Image description

It will generate your token, and as it says - you need to copy it right away because it will not show it to you anymore:

Image description

Then go back to GitHub, "Security" tab, Secrets and variables > Actions, and click on the "New repository secret:"

Image description

It says your secret should be named "SONAR_TOKEN." Enter your secret name and value (from your clipboard), and click "Add secret:"

Image description

Commit your YAML file to the repository:

Image description

Once you commit the workflow file, your project should be set up with Sonar. You can now go to the "Actions" tab and look at your first workflow.

Issues

As I mentioned before, I had a few issues with that out-of-the-box setup, and most of those issues will be applicable to anyone who attempts it. So, read on.

Disabling Automatic Analysis

My first workflow run resulted in a failure:

Image description

When we drill into the error, we will see the following:

Image description

The issue here is that, when you first configure SonarCloud, it by default enables automatic analysis. But once you configure it to be executed as part of a GitHub workflow, you will need to go to SonarCloud and disable that automatic analysis, so now it will only be analyzed once GitHub sends that request to SonarCloud.

To disable automatic analysis, in SonarCloud, go to Administration > Analysis Method:

Image description

...and switch off the toggle:

Image description

One issue down. Now the workflows succeed:

Image description

SCM Provide Detection Failed

In SonarCloud, I see a warning:

Image description

When I click on "See details," I see the following:

Image description

To fix that warning, go to Administration > General Settings:

Image description

Then, in "SCM" tab, "Key of the SCM provider for this project" - enter "git" and click "Save:"

Image description

After adding some code to the repository to actually give it some work, I started seeing new errors in the workflow.

Not inside a Git work tree: /github/workspace

This is the next error that I got. It indicates that SonarCloud is not recognizing the directory as a Git repository. This usually happens when the Git repository is not properly checked out or initialized in the workspace. You will need to update the workflow file to ensure the repository is checked out correctly. Add the following steps before the "Analyze with SonarCloud" step:

Image description

Input required and not supported: distribution

This next error that I got indicates that the "actions/setup-java@v2" action requires the distribution input, which specifies the Java distribution to be installed. To fix this issue, we need to provide the distribution input in the "actions/setup-java@v2" step:

Image description

Your project contains .java files, please provide compiled classes...

After fixing the above errors, I got this next one:

Image description

The error message indicates that your project contains *.java files and requires compiled classes to be provided with the sonar.java.binaries property, or these files need to be excluded from the analysis using the sonar.exclusions property.
To address this issue, I added this property into my sonar-project.properties:

sonar.java.binaries=target/classes
Enter fullscreen mode Exit fullscreen mode

I set "target/classes" as the value because I have a Maven project.

I also added the compilation with Maven:

Image description

After that, my workflow was successful:

Image description

But is that all?

Configuring sonar-maven-plugin

I had an issue with the workflow being successful - actually, I introduced a Sonar bug on purpose in my code and wanted the workflow to fail because of this - but it was successful.

The log gave me a warning that SonarCloud recommends using sonar-maven-plugin instead of the regular SonarCloud workflow setup for Maven projects. So, I added the plugin to my pom.xml:

Image description

...and then removed all the template SonarCloud configuration and used sonar-maven-plugin instead:

Image description

That went well and got rid of the warning; however, the workflow was still successful, despite a Sonar bug in the code.

Sonar Quality Gate Passed When It Shouldn't

Here is the Sonar issue that I introduced on purpose:

Image description

And my workflow was successful:

Image description

I looked at SonarCloud, and amazingly, Sonar didn't consider my code to be an issue! The quality gate passed:

Image description

However, in "small type," it does say that the issue is that there are too few lines of code in my project (it is just a small sample project):

Image description

So, I increased the number of lines - I generated that same issue 10 times:

Image description

Then I was able to see the quality gate fail:

Image description

However, the workflow still succeeded:

Image description

But this is the subject of the next subsection.

Workflow Should Fail When Sonar Analysis Is Not Successful

To make the workflow fail wherever the quality gate fails, we need to add a step in our GitHub Actions workflow that checks the quality gate status after the SonarCloud analysis is complete. This can be done using the SonarCloud API.

I added the following lines to the YAML file to do that:

Image description

That worked, and the workflow failed. If you drill down to the failure, it will tell you the reason - the failure is because the quality gate didn't pass:

Image description

I also got a failure email to the email account associated with my GitHub repo:

Image description

Conclusion

By following this guide, you can successfully set up SonarCloud to automatically analyze your GitHub project for bugs and vulnerabilities. Implementing these steps ensures that your code quality and security are maintained, helping you catch issues early in the development process. As a next step, you can explore more advanced SonarCloud features and further customize your workflows.

💖 💪 🙅 🚩
olsido
Olga Strijewski

Posted on July 6, 2024

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related