Skip to content

Instantly share code, notes, and snippets.

@lysanntranvouez
Last active October 7, 2023 22:11
Show Gist options
  • Select an option

  • Save lysanntranvouez/65cb7633458ab29ca6ad2fd3a3c06dcb to your computer and use it in GitHub Desktop.

Select an option

Save lysanntranvouez/65cb7633458ab29ca6ad2fd3a3c06dcb to your computer and use it in GitHub Desktop.
git pre-commit hook: XamlStyler + git-format-staged
#!/usr/bin/env bash
# Git pre-commit hook that uses git-format-staged and XamlStyler to format xaml files on commit.
#
# See also:
# https://github.com/hallettj/git-format-staged
# https://github.com/Xavalon/XamlStyler
#
# This assumes that XamlStyler was installed as a local tool in the repository.
# See https://github.com/Xavalon/XamlStyler/wiki/Script-Integration for setup instructions.
set -e
XAML_STYLER_CONFIG="tools/xaml-styler/config.json"
GIT_FORMAT_STAGED_PATH="tools/git-format-staged.py"
files=$( ( git diff --cached --name-only --diff-filter=ACM || true ) \
| ( grep -i -E '\.xaml$' || true ) )
if [ -z "$files" ]; then
exit 0
fi
formatter="dotnet xstyler --config \"${XAML_STYLER_CONFIG}\" --file \"{}\" --write-to-stdout"
# At the time of writing XamlStyler.Console targets .NET 6
if ! command -v "dotnet" >/dev/null || ! dotnet --list-runtimes | grep -q "Microsoft.NETCore.App 6."; then
>&2 echo "Must install .NET 6 (https://dotnet.microsoft.com/en-us/download/dotnet/6.0)"
exit 1
fi
dotnet tool restore > /dev/null
if ! dotnet tool list --local | grep -q xamlstyler.console; then
>&2 echo "Failed to install xamlstyler.console"
exit 1
fi
if [ ! -f "${GIT_FORMAT_STAGED_PATH}" ]; then
>&2 echo "pre-commit-xaml-styler.sh: Missing git-format-staged.py"
exit 1
fi
python_exe='python3'
if ! command -v "${python_exe}" >/dev/null 2>&1; then
python_exe='python'
fi
"${python_exe}" "${GIT_FORMAT_STAGED_PATH}" --formatter "${formatter}" $files
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment