How to call/run fxcop analyzer from pre-commit git hook? C#

921 Views Asked by At

I'm Fxcop Analyzer style checker. I want to run/call Fxcop from pre-commit, so if Fxcop finds any error or fields so Git Hook pre-commit should stop commit process.
I had never programmer in Bash and it is the first time I am working with git hook.

Any suggestions that I could use to set this up would be great.

1

There are 1 best solutions below

0
Dusklight On

For running FxCop as a pre-commit hook, you'll need to install FxCop as nuget package and then build the project with MSBuild as you would from the command-line. When MSBuild detects any errors, it will exit with a non-zero exit code. When git detects that the pre-commit hook exited with a non-zero exit code, it will prevent the commit from going through.

As per Microsoft's documentation, this is the command-line you can use:

msbuild myproject.csproj /target:rebuild /verbosity:minimal

Git uses bash for executing hook files even on Windows, so the command-line syntax will be a bit different than the regular cmd. You can try the following as the pre-commit hook file:

#!/bin/sh

'/c/Program Files (x86)/Microsoft Visual Studio/2019/Professional/MSBuild/Current/Bin/MSBuild.exe' ConsoleApp1.csproj /target:rebuild /verbosity:minimal

That's assuming ConsoleApp1.csproj is located at the root of your local git repository folder, and I'm using Visual Studio 2019 (16.4.5), so you may need to adjust it based on your environment.

It should work for either .Net or .Net Core projects.

Note that if there are just warnings, then MSBuild will not exit with a non-zero exit code. You can configure FxCop severity if you want some rules to fail as error, or use MSBuild with warnAsError switch.

Also, depending on how long the build takes, you may want to consider using a pull-request build pipeline, instead of the pre-commit hook.