Rasmus Olsson

Git client hooks for dotnet

September 12, 2021

I recently added some git hooks to my git hook folder for dotnet related work. Its a nice addition to my daily development which makes me more productive. Basically on every time I commit, I run the following:

  • dotnet build
  • dotnet test
  • dotnet format

I think the choices of what to run should vary depending on the repository you are working on. The problem that can occur is that if we don't run any checks locally before pushing the code, the CI server may fail. A good level might be to reflect the CI steps into your git client hooks.

I like to have small but fast running hooks on each commit, aiming at having every commit green. But for some scenarios like long running integration tests, I could see them fit better in pre-push hook.

Here is my general pre-commit hook for dotnet repositories:

#!/bin/bash RED='\033[0;31m' YELLOW='\033[1;33m' NC='\033[0m' # build echo -e "${YELLOW}Running pre-commit hook, dotnet build...${NC}" dotnet build rc=$? if [[ $rc != 0 ]] ; then echo -e "${RED}Failed to build the project, please fix this and commit again${NC}" exit $rc fi # test echo -e "${YELLOW}Running pre-commit hook, dotnet test...${NC}" dotnet test --no-build rc=$? if [[ $rc != 0 ]] ; then echo -e "${RED}Test failed, please fix this and commit again${NC}" exit $rc fi # format echo -e "${YELLOW}Running pre-commit hook, dotnet format...${NC}" dotnet format --no-restore --verbosity detailed rc=$? if [[ $rc != 0 ]] ; then echo -e "${RED}Failed to format project, please fix this and commit again${NC}" exit $rc fi exit 0

One thing that could be improved is to only run these on affected files for the repository.

Thats pretty much it!

Happy coding!

please share