SonarQube: How To Measure Your Code Quality in 5 Easy Steps

SonarQube, developed by SonarSource, is an open-source tool for automated code review and analysis. Consistent code quality is something every manager or technical director aims to maintain, and although new tools pop up frequently, each promising more features than the last, very few code quality and security tools come close to competing with SonarQube. Supporting static code analysis for 20+ languages, this Sonar code quality tool is trusted and used by many professional teams worldwide.

In this article, we will be looking over how to start using the SonarQube tool for code quality in your own projects to generate detailed reports on bugs, security vulnerabilities, duplicate code, code smells, and much more. Let’s get started.

Features:

  • Can perform automatic reviews with static code analysis for many problems that affect code quality.
  • Helps maintain quality and reliability of code projects over its life-span using advanced quality test metrics and graphs.
  • Integrates seamlessly with other tools like Jenkins, Atlassian, MSBuild, etc, which helps productive workflow.
  • Supports most popular programming languages like Java, Python, JavaScript, etc (along with framework support).

How SonarQube helps to assess the quality of the code

SQALE approach is used in the SonarQube top-notch design, with specific changes. The SQALE technique, widely recognized, concentrates primarily on programming difficulty, maintenance and will not consider the program's hazards.

In essence, if a significant safety issue is found in a program, one needs to solve every stability, modifications, usability, and running strictly according to the SQALE approach and after turn again in the latest severe problem. In reality, if possible flaws in the program for such a lengthy period and gets zero consumer error complaints, it is far more critical to concentrate on remediating the latest deficiencies.

Taking it into consideration, programmers in SonarQube have changed the SQALE quality model, focusing on these key issues:
● As easy as conceivable, the system architecture must be
● Bugs and weaknesses in maintenance problems must not be missed.
● Significant development problems and privacy flaws should result in the quality gate criteria not being fulfilled.
● Code maintenance concerns are also crucial, so they shouldn't be overlooked.
● The financial plan is vital and must be conducted utilizing the SQALE analysis model.

The SonarQube Quality Gate ethics employs the feature vectors to evaluate when the program completed these controls:
● No latest bugs
● Zero latest security flaws
● New code technical debt ratio<= 5%
● Equal or more than 80 percent modified system's availability

Sonar squad must list seven terrible programers' faults for growing technical debt:
● Bugs and possible errors
● Coding principles breached
● Redundancy of the program
● Inadequate coverage of consumers modules
● Lack of structure diffusion
● Pattern of Spaghetti
● Excessive amounts of comments

How to Use SonarQube Tool For Code Quality:


Step 1: Download and Unzip SonarQube

Prerequisites: Java (Oracle JRE11 or OpenJDK 11 minimum)

SonarQube comes in four different editions, including paid ones, however, for the purpose of this article, we will be using their free open-source community edition.

Click here to download SonarQube Community Edition from their official Downloads page.

After your download has completed, you should find a zip file waiting for you. On Windows, right click and select unzip and double click and extract on MacOS using the Archive Utility.

Also for Linux, you can unzip it using the `unzip` terminal tool.

unzip xyz.zip


Step 2: Run the SonarQube local server

At this point, you should be greeted with a little `.bat` file (if you are on windows) or a `.sh` file (if you are on Linux or Mac). The next step will be to execute this file to proceed into the console.

On Windows, navigate into the parent directory containing the `StartSonar.bat` file. This can be done by navigating to the unzipped folder ('sonarqube') and into the bin and windows-x86-xx folder as:

>> cd C:\sonarqube\bin\windows-x86-xx\

Then, run the following command to start the console:

>> StartSonar.bat

On Mac or Linux, run the following command from your shell terminal:

/opt/sonarqube/bin/[your_OS_name]/sonar.sh console

That’s it! You’ve successfully started the SonarQube local server on your device. You can go to the URL `http://localhost:9000` (9000 is the default port, which can be changed later), and log in using the default credentials:

Login: admin

Password: admin

If you wish to containerize SonarQube, you’ll be pleased to know that the Community, Developer, and Enterprise Editions of the tool are also available as images on Docker Hub as well. Download and start docker container as:

docker run -d --name sonarqube -p 9000:9000 <img_name>


Step 3: Start a new SonarQube project

Now that you have successfully run your SonarQube server, you can proceed to start your first code project. Click on the ‘+’ icon on the top right of the navigation bar and select ‘Create New Project.’

In the next page, enter a unique project key and a short and suitable display Name and click on Set Up.

SonarQube uses tokens to identify you when an analysis is performed. So on the next page, generate a token using any word pair you like (like secret_token or my_token).

After clicking on Generate, Sonar will provide you with a unique alphanumeric secret key. Copy it down, we will need it later for verification purposes. Then click Continue.

In the next window, select your project’s main language. SonarQube supports over 27 languages including JavaScript, Python, C#, etc, so there’s a high chance your project language will be included here.

Next, click on your OS type (Windows/Linux/macOS) and click on Download. It will link you to a download of SonarScanner. After the download completes, extract the file as in step 2.


Step 4: Setup Project properties and SonarScanner

This step should be pretty straightforward if you have spent any time working on code projects.

Register the

…\sonar-scanner-cli-<version>-<OS>\sonar-scanner-<version>-<OS>\bin

directory in your environment variable list. This can be done by adding an entry in the `Add Environment Variables` window for Windows.

On macOS or Linux distros, edit the required Path file to add the bin folder to the system’s environment variable files.

Now we will need to set up a `properties` file for our sonar projects. This is important and we highly recommend that you don’t overlook this step.

On your project folder, create a file named sonar-project.properties and copy-paste the following property variables into the file:

sonar.projectKey=<YOUR_PROJECT_KEY>
sonar.projectName=<PROJECT_DISPLAY_NAME>
sonar.login = <GENERATED_KEY>
sonar.scm.provider =<SCM_PROVIDER>
sonar.projectVersion=1.0
sonar.sources=src
sonar.exclusions=<EXCLUSION_DIRECTORIES(WONT_BE_SCANNED)>
sonar.ts.tslint.configPath=<CONFIG_FILE_.JSON>
sonar.typescript.lcov.report
Paths=<PATH_FOR_REPORT>



Here we have created our .properties file for our own project, but depending on your environment and path structure, the variables for the properties file will change. Look up the Sonar documentation for property variables related to your project language. Remember that you need to include a sonar-project.properties file on the root folder of every project that you create.

Now open a new cmd shell/terminal on your device and start up the SonarScanner to scan for code quality and security issues.

On Windows, type:

>> sonar-scanner.bat

Similarly, run the sonar-scanner shell file using the terminal if you’re on macOS or Linux. If you have followed all the steps outlined in this tutorial, the scanner should start scanning without any problems.

Scanning typically takes a while, depending on the size of the project. Take a moment to relax in the meanwhile!


Step 5: View your analysis report on Sonar Dashboard

After the scan has completed through your code-base, go back to your SonarQube dashboard on http://localhost:9000 and log in using your credentials. Select your created project and you will find a code analysis report waiting for you.

The free Community Edition should include Reliability (measured in # of bugs), Security (in terms of vulnerabilities), Maintainability (depending on your code debt and smells), Coverage, and Duplications. Depending on the number and intensity of each check, the Quality Gate will either 'Pass' or 'Fail' the project. A green color grade will show areas where your code performed well while yellow and red color grades will highlight problem areas.

Furthermore, under the `Issues` tab, you can see the issues in your code, sorted according to intensity. Fixing these will help you and your team increase your quality score.

Give yourself a pat on the back, you have successfully completed a code analysis using the Sonar code quality tool! Now, you can export this report to include it in your presentations or forward it to team managers or other concerned parties.

Conclusion:

If you have followed all the steps outlined in this detailed tutorial, you should be able to conduct quality scans for your future projects without any problems. If any error pops up or you want to find certain features in your dashboard or CLI, the SonarQube documentation provides an excellent resource for your problems.

If you need easy set-up and actionable data from day one, try our tool and sonarqube alternative - duecode.io.

sonarqube alternative - duecode.io

FURTHER READING

- Complete Code Quality Guide

- Code Quality Tools

- Code Quality Metrics

- Code Quality Standards

- How to measure, check and improve code quality:

-- How To Check Code Quality?

-- How To Measure Code Quality

-- How Can I Improve My Code Quality

-- How To Build A Website With Good Quality Code?

Updated on the 1st of November, 2021