DTynewydd
DTynewydd

Reputation: 426

Git pre-commit hook in Visual Studio 2022

I'm trying to do some linting with dotnet format in a pre-commit hook in VS2022. The problem is that the pre-commit hook does not seem to be called when I use the VS Git gui to commit changes, even though it works when I use the command line. So even though the command line correctly cancels the commit as shown below, the gui erroneously creates a commit.

How can I get VS to actually use the pre-commit hook? I've seen it correctly use the pre-push hook.

pre-commit:

#!/bin/sh
#
# An example hook script to verify what is about to be committed.
# Called by "git commit" with no arguments.  The hook should
# exit with non-zero status after issuing an appropriate message if
# it wants to stop the commit.
#
# To enable this hook, rename this file to "pre-commit".

echo >&2 "Running git format"
LC_ALL=C
# Select files to format
FILES=$(git diff --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 --files
# Add back the modified files to staging
echo "$FILES" | xargs git add
echo >&2 "Deliberate failure"
exit 1

command line output:

C:\Users\<username>\source\repos\WpfApp1>git commit -m "Test"
Running git format
xargs: dotnet-format: No such file or directory
Deliberate failure

Upvotes: 8

Views: 8698

Answers (2)

DTynewydd
DTynewydd

Reputation: 426

I recently came back to this and was able to get it working. It seems that VS updates mean that xargs is now supported and I was able to use dotnet format instead of dotnet-format

Upvotes: 1

Simon C
Simon C

Reputation: 419

I've recently found (with my own pre-commit issues with VS) that Visual Studio implements it's own internal version of git (including grep and sed). Within that, xargs isn't allowed. Visual studio won't tell you it's failed and will just commit. Try removing out any xargs references from your code. Also, dotnet-format is also a custom installed program, so won't work via VS.

If you want all your stated functionality, switching VS to use system-installed git will likely work much better: Configure Visual Studio to use system-installed Git.exe

To troubleshoot / get your code working I recommend testing out whether certain commands are even allowed in Visual Studio. Simply (temporarily) test out commands by putting code like the below in the top of your pre-commit file and try committing from Visual Studio:

xargs
echo "This outputs in VS git error window"
exit 1

Visual Studio example output

Upvotes: 3

Related Questions