Publishing a .NET Core project to SonarCloud with Cake
Cake (C# Make) is a cross-platform build automation system with a C# DSL for tasks such as compiling code, copying files and folders, running unit tests, compressing files and building NuGet packages.
SonarCloud is a cloud service offered by SonarSource and based on SonarQube. SonarQube is a widely adopted open source platform to inspect continuously the quality of source code and detect bugs, vulnerabilities and code smells.
- Cake: install the
Cakeon your .NET Core project before start this tutorial. Follow this Setting Up A New Project.
- SonarCloud: create an account and add a project on https://sonarcloud.io.
Creating the build.cake
In project root folder, create a file called
Adding the tools and addin references
Add the lines below to the file:
We’ll use those tools and addins to create the complete .cake script.
Setting the variables
Now we need to set some variables:
- solutionDir: is the subfolder where your solution source code is located.
- sonarLogin: Change the
[SONARCLOUD-USER-TOKEN]for a token you can generate at the page https://sonarcloud.io/account/security/.
- branch: if you are using git, then the
GitBranchCurrent(".").FriendlyNamewill pass the right branch name to SonarCloud, otherwise you can set it manually.
If you are using
AppVeyor you can use line bellow to allow discover the branch name locally and in the AppVeyor:
The first task definitions will build our .NET Core project:
Now we will define the task to run our tests:
This task use
Coverlet to collect the code coverage. Install it on your test project using the
Coverlet NuGet package:
The lasts tasks to define are responsible to scan the project and send the build and tests results to SonarCloud:
- Key: is your project key on SonarCloud. You can get it throw these steps on SonarCloud:
- Select your project.
- Open the menu
Administration / Update Key
- Organization: is the name of your organization on SonarCloud. If your
https://sonarcloud.io/organizations/YOUR-ORGANIZATION/projects, then your Organization value is
- Exclusions: here you can define the wildcards to excluse some files fron Sonar scan, like sample, docs and test files.
Defining the tasks order
The last part of the
build.cake file define the order that tasks will run:
Running the build.cake
Now, every time you want to build, test and publish the results to SonarCloud you need to type this command on your project root folder:
When the build finish, you should see something like this:
Then open your project on SonarCloud:
That’s it, now your project is ready to using cake to publish results to SonarCloud.
If you are using git, you can add this lines to your .gitignore file: