Restric sonar-scanner to only files in compile-commands.json

In the process of evaluating sonarcloud for our organization we are trying to get one of our c/c++ project uploaded to sonarcloud using sonar-scanner with a compilation database generated from our build system.

when running sonar-scanner it seem to search the whole source area for anything looking like a source file, regardless of it being used in the build, as indicated by the compilation database supplied to sonar-scanner.
This results in a large amount of code being analyzed that are not part of the build, and makes the analysis fail since it is over the limit of lines set for our organization.

Is there a way to restrict sonar-scanner to only analyze files that are in the compilation database (and dependencies ofc)?

Hey there.

There isn’t – and we don’t think there should be. One of the strengths of Sonar is that it’s multi-language by-default, so if you have a project with many languages, like C++ and Python, all of your information is kept in one project without additional configuration. For such a project, no Python files would be found in the compilation of C++, and wouldn’t end up in the build wrapper.

And, you are able to restrict the Analysis Scope of your projects if you want to exclude files / only include some files.

Thank you for your answer.

We have a single source tree that is used to build for something like thirty different targets, making it entirely impractical to have sonar-scanner gobble up all source code in existence for each build-type.

The whole point of having a compilation database in my mind is tho know exactly what has been used in a particular build, en exactly how it was built.
Excluding/including files by path, and only once the whole lot has been uploaded, makes the tool almost completely unusable for us.

In the one target I tried to analyze sonar-scanner uploaded just over two million lines of code, when the actual lines of code used by that build is more like sixty thousand lines of code. I can see why you want to have it that way since the license is per line of code, but for our purposes this is not very practical.

Since you have a json file you could have a script that would parse your json file and generate an ant style list of directories, or files, that you want sonar to include.

In sonar-project.properties you would have:

sonar.inclusions = ${env.SONAR_INCLUSIONS}

With your tool generating SONAR_INCLUSIONS=path/to/source.file,other/path/to/source.xyz.

If your list is not too large it should work.

See Narrowing the Focus | SonarQube Docs

You might need to tune other settings such as sonar.test.inclusions.

Aditionally, if the code you want to scan is restricted to a single folder (and it’s descendants), you can set sonar.sources=theFolderIWantToScan