Sonarqube And Unity (code Quality)

Hi,

Has anyone used this tool before?

We are evaluating if we can install and use it in our organization in combination with Jenkins.

The problem I see is that there are rules that don’t apply to Unity specific code like errors regarding:

  • Unused methods: Unity’s magic “Awake, Start, …”
  • [SerializeField] and fields that suggest in some cases adding “readonly” or similar that we can’t because doing that it’s going to hide from inspector.
  • And I’m sure there are a lot more.

Can anyone on Unity Q&A help me? @QA-for-life @ElvisAlistar @

I also take this oportunity to inform that I have some bug reports that are stopping us from our internal Q&A pipeline to work:

Particularly this that it’s a problem for us or anyone trying to use a continuous integration tool like Jenkins:
https://fogbugz.unity3d.com/default.asp?850673_2bhp57sqgnd7ch9p

This is an API request because as you can see you only can target 64bits and in build settings there are 3 options (it’s not consistent):
https://fogbugz.unity3d.com/default.asp?850877_aeci1khcthpmd2qq

2 Likes

Hi,

We have tried using SonarQube on Unity’s code base with moderate success. It’s quite easy to setup and it works out of the box, but it does not support adding custom rules, which means that you are stuck with what it offers in the default C# analysis profile.

I guess the only way to deal with Unity’s magic methods being identified as Unused methods and so on is to mark those issues as False Positive. Assuming your code base isn’t very large, it shouldn’t take too long, and Sonar will ignore those in future analysis iterations of your code base.

Regarding the bug reports, the first one is fixed and should be included in one of the upcoming Unity builds and the other one was answered by someone in QA (I recommend you reply to them if you have further questions).

Hope this helps!

@ElvisAlistar They are working on it: c# - SonarQube using it with Unity 3D tons of problems - Stack Overflow

Can Unity staff help them? I don’t know all reflection based messages across Unity classes.

They want to release an update in a few days (ticket 1104 and 1105): https://jira.sonarsource.com/browse/SLVS-1105?jql=project = SLVS AND fixVersion = 1.22.0

1.22.0 Rule fixes Release date: 13/Dec/16

And I think that custom rules are possible but not easy to implement: GitHub - meng-hui/UnityEngineAnalyzer: Roslyn Analyzer for Unity3D

And thanks for the bug reports updates!

Currently there is no direct collaboration between Unity and Sonar. Sounds like they are working on a solution to whitelist certain type of code in the rules, in which case that would allow anyone (including us) to provide more custom-based checks on Sonar for Unity code. We will keep an eye on their progress and future Sonar updates.

Ok, thanks. I’ll reply on this thread if I see any change on Sonar regarding Unity.

There is another tool similar to SonarWube thar works better with Unity? We are triying to improve our code quality :wink:

The problem is not with Sonar itself, its because Unity has its “magic” using reflection and that’s why we have many false-positives. Its a problem that you will face in any similar tool.

Any news on this topic? Also, do you think it would be beneficial even with false positives?

I’m using it with Jenkins to analyze our codebase.

I managed to get Sonar staff involved on this and they created rules to avoid some false positives:

https://github.com/SonarSource/sonar-dotnet/issues/159

Thanks for the information! I also would like to get your suggestion to use SonarQube. Does that help? How do you measure it?

Code coverage not because with Unity it’s not possible but rules are really useful to avoid code smells or bugs that can be detected with static analysis.

In our code base we want code that it’s clean, performant and works without issues so yes, it helps.

@ElvisAlistar please move it to the appropriate subforum.

Thanks.

The SonarQube scanner for MSBuild supports OSX now and .Net core for some time now.

Was anyone successful in setting up a SonarQube scan for their Unity codebase? (i am trying to run it from a Mac machine).

I have gotten this working on macOS.

My SonarQube instance is installed on a CentOS 7 system, so I am stuck with SonarQube 7.1 for the time being. This means that I cannot use build-wrapper-macosx-x86 as mentioned on https://docs.sonarqube.org/display/PLUG/Building+on+Mac+OS+X. I am not using the commercial version at this time. I am also doing all this through Jenkins.

My basic process is like this:

  • (Do this once before analyzing and periodically to update to newer releases.) Download the newest version of sonar-scanner-msbuild from https://github.com/SonarSource/sonar-scanner-msbuild/releases and extract somewhere in the $PATH. I just extracted mine in ~/bin. Run chmod +x ~/bin/sonar-scanner-*/bin/sonar-scanner* or you will get an Access Denied error when you call SonarScanner.MSBuild.exe end.

  • (Do steps 2-10 each time you analyze.) Optionally, set VERSIONNAME to use in SQ to set a new leak period. If VERSIONNAME was set, run a script to pull the commit date from Bitbucket (see below). If you’re not using Git (or equivalent), set COMMITDATE in the format yyyy-MM-dd i.e. 2019-05-26 (or yyyy-MM-ddTHH:mm:ssZ i.e. 2019-05-26T15:42:06-0500 for additional precision).

  • To avoid any Unicode issues, set LANG=en_US.UTF-8

  • Set the project key, name, and any other sonar options.

  • Run Unity in batch mode and, among other things, have it call EditorApplication.ExecuteMenuItem("Assets/Open C# Project"); to create the solution and related files for later use by Visual Studio.

  • If VERSIONNAME is set, run . properties.sh to pull those values in as environment variables.

  • Here, briefly, is where it gets spectacularly weird. You’ll have to use the second script to:

  • Link in the source files of any Unity Packages you’re using. This step requires the jq utility that you can install using MacPorts or Homebrew.

  • Move files that have been created with Windows backslash directory delimiters in the filenames into proper directory trees i.e. foo\bar\baz to foo/bar/baz

  • Run mono SonarScanner.MSBuild.exe begin "/k:${PROJECTKEY}" "/n:${PROJECTNAME}" "/v:${VERSIONNAME}" "/d:sonar.projectDate=${COMMITDATE}" "/d:sonar.host.url=http://sonar.foo.com:9000" /d:sonar.login=${SonarQubeToken}

  • Run msbuild /p:Configuration=Debug /p:Platform="Any CPU" /maxcpucount /nodeReuse:false /nologo /target:rebuild /verbosity:quiet solution.sln

  • Run mono SonarScanner.MSBuild.exe end /d:sonar.login=${SonarQubeToken}

cat /dev/null > properties.sh
JSON=$(curl --fail -k --silent --show-error https://jenkins:${PASSWORD}@stash.foo.com/rest/api/1.0/projects/${PROJECT}/repos/${REPOSITORY}/commits/HEAD)
echo COMMIT=$(echo $JSON | jq -r '.id') >> properties.sh
echo COMMITDATE=$(date -d @$(expr $(echo ${JSON} | jq -r '.committerTimestamp') / 1000) -Iseconds) >> properties.sh
echo COMMITDATEPARAMETER="/d:sonar.projectDate=${COMMITDATE}" >> properties.sh
# Mimic the Unity Package Manager
# ASSUMPTION: there is only one match of */Packages/manifest.json in the repository
pushd $(find . -path '*/Packages/manifest.json' | rev | cut -d / -f 2- | rev)
ln -s $(ls -d ${HOME}/Library/Unity/cache/packages/packages.unity.com/com.unity.standardevents* | tail -1) com.unity.standardevents
/usr/local/bin/jq -r '.dependencies | to_entries | map("ln -s ${HOME}/Library/Unity/cache/packages/packages.unity.com/\(.key)@\(.value|tostring) \(.key)") | .[]' < manifest.json | sh
popd

# Fix some Windows backslashes
pushd ${TMPDIR}/.sonarqube/resources
find . -name \*\\\\\* | tr \\ / | rev | cut -d / -f 2- | rev | sort -u | xargs -t mkdir -p
for file in $(find . -name \*\\\\\* )
do
  mv -v "$file" "$(/bin/echo "$file" | tr \\ /)"
done
popd

Scientific Dave, thank you!!! I have been struggling with this for a week!!!

@SciPlayDave I’m trying to configure sonar scanner with macOS (I already have it working on Windows) and it does all the process correctly without errors but I see tons of:

WARN: File ‘{A C# script}’ referenced by the protobuf ‘MetricsInfo’ does not exist in the analysis context
WARN: File ‘{A C# script}’ referenced by the protobuf ‘TokenTypeInfo’ does not exist in the analysis context
WARN: File ‘{A C# script}’ referenced by the protobuf ‘SymbolReferenceInfo’ does not exist in the analysis context

And I get no code on sonar side.

You know what that might be?

Thanks.

@bdovaz can you sure more details on how you have setup the runner on mac? which version did you use and how are you executing it ?

Hi all,

For checking code quality in local, I got successful. But, when I integrate my scripts with Unity Cloud build and I got the results:

mono: command not found
msbuild: command not found

And I tried to install mono by using Homebrew, but still error occurs. The problems are that I don’t have permission to install mono.

Have someone had experience about this. Please share with me how to fix my problems.
Thanks

This works great for me, I create a custom Quality Profile and add/remove any rule I want.

You can see my current CI/CD pipeline here:

and you can see the results here:
https://sonarcloud.io/project/overview?id=MirageNet_Mirage

@goldbug are you using GitHub actions? i’d like to ask you what is the support for running Unity there? should you bring your own on-prem machine to run the actual build, or does your build pipeline need to install Unity on the VM? how does it work exactly ?

Also, is SonarQube supported “out of the box” or you had to do some initial setup to get it up and running ?