Running Sonar locally

Using Sonar helps improve the code quality. Sonar identifies code smells, bugs, and vulnerabilities, it provides an overview of the code coverage and complexity and finds duplications. There are more advantages if one integrates it in the pipeline and decides to customise its rule, but it is possible to gain a lot just by running it locally.

Running it locally it’s actually pretty simple with Docker.

docker run -d --name sonarqube \
  -e SONAR_ES_BOOTSTRAP_CHECKS_DISABLE=true \
  -p 9000:9000 sonarqube:latest

Alternatively this project offers a Docker image of the community version with support for branches, which is pretty useful.

Once started, connect to localhost. The credentials are admin / admin.

Create a local project with a PROJECT_KEY, generate a TOKEN, and import a project from a repository. Eventually, you will get then snippets for Maven or Gradle to submit the project, something like this:

mvn clean verify sonar:sonar \
  -Dsonar.projectKey=somekey \
  -Dsonar.projectName='yourproject' \
  -Dsonar.host.url=http://localhost:9000 \
  -Dmaven.test.skip=true \
  -Dsonar.token=sometoken

I usually store it into an alias or function in my .zshrc.sh:

sonar_test_project_x(){
  mvn clean verify sonar:sonar \
    -Dsonar.projectKey=somekey \
    -Dsonar.projectName='yourproject' \
    -Dsonar.host.url=http://localhost:9000 \
    -Dmaven.test.skip=true \
    -Dsonar.token=sometoken
}

Then it’s as simple as calling that snippet to submit the code. A few moments for the elaboration and the report will be available.

Tags: Sonar Maven