SonarQube

SonarQube

How to run SonarQube in local slice or developer machine ?

Get Started in Two Minutes Guide Download the SonarQube Community Edition

Unzip it, let’s say in C:\sonarqube or /etc/sonarqube

Start the SonarQube Server:

C:\sonarqube\bin\windows-x86-xx\StartSonar.bat
/etc/sonarqube/bin/[OS]/sonar.sh console

Log in to http://localhost:9000 with System Administrator credentials (admin/admin)

For multi-language projects, remove the property “sonar.language=java” from “sonar-project.properties”

Question about customization

There are a lot of generated or configuration packages/classes that can be excluded from “test coverage” report that Sonarqube shows. How can we customize the coverage percentage that Sonarqube shows in its dashboard?

The pipeline exports jacoco.xml to Sonarqube and that is what Sonarqube uses for display on the dashboard. Please look for options to customie while generating jacoco.xml

Reading material

  1. SonarQube Community Build analysis overview https://docs.sonarsource.com/sonarqube-community-build/analyzing-source-code/analysis-overview/
  2. Simple demo project to run a Sonar analysis on a js project: https://github.com/xseignard/sonar-js/tree/master

How to use sonarqube community edition for analyzing a local React project?

Analyzing a local React project with the SonarQube Community Edition is a multi-step process that involves setting up a SonarQube server, configuring your project, and running the analysis. This guide provides a comprehensive walkthrough to get you started.

1. Prerequisites

Before you begin, ensure you have the following installed on your local machine:

  1. Node.js: A recent version (LTS recommended).
  2. Docker and Docker Compose: The most common and recommended way to run SonarQube locally.

2. Setting Up the SonarQube Server

The easiest way to get a SonarQube server running is by using Docker.

Step 1: Create a docker-compose.yml file

In a directory of your choice, create a file named docker-compose.yml with the following content. This will set up SonarQube along with a PostgreSQL database.

version: "3"
services:
  sonarqube:
    image: sonarqube:community
    ports:
      - "9000:9000"
    environment:
      - SONAR_JDBC_URL=jdbc:postgresql://db:5432/sonar
      - SONAR_JDBC_USERNAME=sonar
      - SONAR_JDBC_PASSWORD=sonar
    volumes:
      - sonarqube_conf:/opt/sonarqube/conf
      - sonarqube_data:/opt/sonarqube/data
      - sonarqube_extensions:/opt/sonarqube/extensions
      - sonarqube_logs:/opt/sonarqube/logs
    depends_on:
      - db
  db:
    image: postgres
    environment:
      - POSTGRES_USER=sonar
      - POSTGRES_PASSWORD=sonar
      - POSTGRES_DB=sonar
    volumes:
      - postgresql:/var/lib/postgresql
      - postgresql_data:/var/lib/postgresql/data

volumes:
  sonarqube_conf:
  sonarqube_data:
  sonarqube_extensions:
  sonarqube_logs:
  postgresql:
  postgresql_data:

Step 2: Start the Server

Open a terminal in the directory where you created the docker-compose.yml file and run the following command:

docker-compose up -d

It might take a few minutes for the SonarQube server to start up completely. You can monitor the logs using docker-compose logs -f sonarqube.

Step 3: Access SonarQube and Change Password

Once the server is running, you can access the SonarQube dashboard in your web browser at http://localhost:9000.

  1. Log in with the default credentials:
    1. Username: admin
    2. Password: admin
  2. You will be prompted to change your password upon the first login.

3. Configuring Your React Project

Now, you need to configure your local React project to be analyzed by SonarQube. There are two ways to do this.

The more standard way - irrespective of the type of the project - java or any other language - is the SonarScanner CLI approach.

  1. Using sonarqube-scanner
    1. https://www.npmjs.com/package/sonarqube-scanner
    2. https://github.com/SonarSource/sonar-scanner-npm
    3. The npm sonarqube-scanner package is a third-party integration that isn’t built by Sonar.
  2. Simply running a plain SonarScanner CLI analysis.
    1. https://docs.sonarsource.com/sonarqube-server/latest/analyzing-source-code/scanners/sonarscanner/
    2. To help you get started, simple project samples are available for most languages on GitHub. https://github.com/SonarSource/sonar-scanning-examples

Step 1: Install the SonarQube Scanner Package

Navigate to the root directory of your React project in a terminal and install the sonarqube-scanner package as a development dependency.

npm install sonarqube-scanner --save-dev

or

yarn add sonarqube-scanner --dev

Step 2: Create a SonarQube Configuration File

https://docs.sonarsource.com/sonarqube-server/9.9/analyzing-source-code/languages/javascript-typescript-css/

In the root of your React project, create a file named sonar-project.js. This file will contain the configuration for the analysis.

const sonarqubeScanner = require('sonarqube-scanner');

sonarqubeScanner({
  serverUrl: 'http://localhost:9000',
  options: {
    'sonar.projectKey': 'my-react-app',
    'sonar.projectName': 'My React App',
    'sonar.sources': 'src',
    'sonar.tests': 'src',
    'sonar.test.inclusions': '**/*.test.js,**/*.test.jsx,**/*.test.ts,**/*.test.tsx',
    'sonar.exclusions': '**/node_modules/**,src/reportWebVitals.js,src/setupTests.js',
    'sonar.javascript.lcov.reportPaths': 'coverage/lcov.info'
  }
}, () => {});

Some folks seem to recommend using sonar-scanner.properties and sonar-project.properties instead of sonar-project.js

sonar-project.properties

sonar.projectName = Test-Project
sonar.projectKey = Test-Project
sonar.login=4d922 — — — — — — — — — — — — — — — — — — — — — -
sonar.sources = .
sonar.language = js,
sonar.sourceEncoding = UTF-8
sonar.coverage.exclusions = **/*.*

sonar-scanner.properties

#Configure here general information about the environment, such as SonarQube server connection details for example
#No information about specific project should appear here
# — — — Default SonarQube server
sonar.host.url=http://localhost:9000/
# — — — Default source code encoding
sonar.sourceEncoding=UTF-8

Customizing the Configuration:

  1. sonar.projectKey: A unique identifier for your project in SonarQube.
  2. sonar.projectName: The name of your project that will be displayed on the dashboard.
  3. sonar.sources: The directory containing your source code.
  4. sonar.tests: The directory containing your test files.
  5. sonar.test.inclusions: Patterns to identify your test files.
  6. sonar.exclusions: Comma-separated list of files and directories to exclude from the analysis.
  7. sonar.javascript.lcov.reportPaths: The path to the code coverage report. SonarQube doesn’t run your tests, but it can import existing reports.

Step 3: Generate a Code Coverage Report

To see code coverage metrics in your SonarQube report, you need to generate a coverage report first. Most React projects set up with Create React App can do this by running:

npm test -- --coverage --watchAll=false

This command will create a coverage directory in your project’s root, which contains the lcov.info file.

Step 4: Generate a SonarQube Token

For security, it’s best to use a token to authenticate the scanner.

  1. In your SonarQube dashboard (http://localhost:9000), go to My Account > Security.
  2. Generate a new token by giving it a name and clicking Generate.
  3. Copy this token and update your sonar-project.js to include it.
const sonarqubeScanner = require('sonarqube-scanner');

sonarqubeScanner({
  serverUrl: 'http://localhost:9000',
  token: 'YOUR_GENERATED_TOKEN', // Add your token here
  options: {
    // ... your other options
  }
}, () => {});

4. Running the Analysis

After setting everything up, you can now run the SonarQube scanner.

Step 1: Add a Script to package.json

To make it easier to run the analysis, add a new script to your package.json file:

"scripts": {
  "sonar": "node sonar-project.js"
  // ... your other scripts
}

Step 2: Run the Analysis

Execute the script from your terminal:

npm run sonar

Or, run this command from terminal

sonar-scanner

The scanner will now analyze your code, and you’ll see output in your terminal. Once it’s finished, it will have sent the report to your local SonarQube server.

5. Viewing the Analysis Results

Go back to your SonarQube dashboard at http://localhost:9000. You should now see your project listed. Click on it to view the detailed analysis, which includes information on bugs, vulnerabilities, code smells, and test coverage.