Collection of advice how to auto check/format. Every sample expects dotnet format installed as local tool, unless otherwise noted.
Create file .git/hooks/pre-commit
with following contents:
#!/bin/sh
LC_ALL=C
# Select files to format
FILES=$(git diff --cached --name-only --diff-filter=ACM "*.cs" | sed 's| |\\ |g')
[ -z "$FILES" ] && exit 0
# Format all selected files
echo "$FILES" | cat | xargs | sed -e 's/ /,/g' | xargs dotnet format --include
# Add back the modified files to staging
echo "$FILES" | xargs git add
exit 0
These instructions originally authored by randulakoralage82.
Add following to your build file:
- task: UseDotNet@2
displayName: 'Use .NET 6 sdk'
inputs:
packageType: 'sdk'
version: '6.0.x'
includePreviewVersions: true
- task: DotNetCoreCLI@2
displayName: 'dotnet-format'
inputs:
command: 'custom'
custom: 'format'
arguments: '--verify-no-changes'
These instructions originally authored by leotsarev.
pre-commit.com hook to reformat
Add the following block to the repos
section of your .pre-commit-config.yaml
file:
- repo: https://github.com/dotnet/format
rev: "" # Specify a tag or sha here, or run "pre-commit autoupdate"
hooks:
- id: dotnet-format
Note that this will compile and install dotnet format to an isolated environment, using the system installation of the dotnet CLI. See the pre-commit.com documentation for more details. The problem is that dotnet format is using preview SDK (even for 5.x versions), and you have to install preview SDK on your machine for compiling it. Another option is to use local feature of pre-commit, as follows:
- repo: local
hooks:
#Use dotnet format already installed on your machine
- id: dotnet-format
name: dotnet-format
language: system
entry: dotnet format --include
types_or: ["c#", "vb"]
These instructions originally authored by rkm & leotsarev.
- Open Settings -> Tools -> File Watchers
- Press The “Plus Sign” to Add a Custom watcher
- Set the name to i.e. “dotnet format on save”
- FileType: C#
- Scope: Open Files
- Program: Write dotnet-format
- Arguments:
$SolutionPath$ --verbosity diagnostic --include$FileRelativePath$ - (Optionally) Append --fix-style warning to fix any style issues automatically on save.
- (Optionally) Append --fix-analyzers warning to fix any analyzer warnings on save.
- Disable all advanced option checkboxes.
- All other values were left default
These instructions originally authored by Nils Henrik Hals.