Enforce .NET code style in CI with dotnet format
This post is part of the series 'Coding style'. Be sure to check out the rest of the blog posts of the series!
- How to enforce a consistent coding style in your projects
- Enforce .NET code style in CI with dotnet format (this post)
- Running GitHub Super-Linter in Azure Pipelines
In a previous post, I wrote about using an .editorfile
to define the coding style. Visual Studio understands this file and provides quick fixes to make your code match the coding style. You can easily rename symbols and add spaces where it's needed. However, it's easy to miss some warnings and commit a code that doesn't match the coding style. In this post, I'll show you how to enforce the coding style by using a step in the CI pipeline.
dotnet format
allows to format the files in a solution as shown in the previous post. But it can also check that your code matches the coding style defined in the file .editorconfig
. You can use --check
to prevent the tool from actually writing files and to make it return a non-zero exit code when a file doesn't match the coding style.
dotnet tool update -g dotnet-format
dotnet format --check
By using these 2 options you can check the coding style in your CI pipeline. For instance, in Azure Pipeline you can use the following code:
stages:
- stage: build
jobs:
- job: "lint"
pool:
vmImage: 'ubuntu-latest'
# Install the latest version of .NET Core SDK
- task: UseDotNet@2
inputs:
packageType: 'sdk'
version: '3.1.x'
# Install dotnet format as a global tool
- task: DotNetCoreCLI@2
displayName: 'Install dotnet format'
inputs:
command: 'custom'
custom: 'tool'
arguments: 'update -g dotnet-format'
# Run dotnet format --dry-run --check
# By default, the task ensure the exit code is 0
# If a file needs to be edited by dotnet format, the exit code will be a non-zero value
# So the task will fail
- task: DotNetCoreCLI@2
displayName: 'Lint dotnet'
inputs:
command: 'custom'
custom: 'format'
arguments: '--check --verbosity diagnostic'
If a file doesn't respect the coding style, this will print details and the build will fail:
If you don't want to use the DotNetCoreCLI@2
task, you can use the script task
stages:
- stage: build
jobs:
- job: "lint"
pool:
vmImage: 'ubuntu-latest'
- task: UseDotNet@2
inputs:
packageType: 'sdk'
version: '3.1.x'
- script: 'dotnet tool update -g dotnet-format && dotnet format --check --verbosity diagnostic'
displayName: 'Lint dotnet'
Do you have a question or a suggestion about this post? Contact me!