Skip to content

Git Hook

David Grochocki edited this page Oct 27, 2016 · 4 revisions

Git Hooks allow you to execute scripts when certain actions occur. The pre-commit hook is run first, before you even type in a commit message.

The pre-commit hook below will format all XAML files in a commit. It can be configured with an external XAML Styler configuration and a backup location for original XAML files before formatting.

You can bypass execution of this hook with git commit --no-verify.

#!/bin/sh
# XAML Styler - xstyler.exe pre-commit Git Hook
# Documentation: https://github.com/Xavalon/XamlStyler/wiki

# Define path to xstyler.exe
XSTYLER_PATH=

# Define path to XAML Styler configuration
XSTYLER_CONFIG=

# Define path to copy original XAML files as backup
BACKUP_PATH=~/Documents/XamlStyler/Backup

echo "Running XAML Styler on committed XAML files"
git diff --cached --name-only --diff-filter=ACM  | grep -e '\.xaml$' | \
# Wrap in brackets to preserve variable through loop
{
    # Setup XAML file backup
    if [ -n "$BACKUP_PATH" ]; then
        echo "Backing up XAML files to: $BACKUP_PATH"
        BACKUP_PATH="$BACKUP_PATH/$(date +"%Y-%m-%d_%H-%M-%S")/"
    fi

    files=""
    # Build list of files to pass to xstyler.exe
    while read FILE; do
        if [ "$files" == "" ]; then
            files="$FILE";
            mkdir -p $BACKUP_PATH
        else
            files="$files,$FILE";
        fi

        if [ -n "$BACKUP_PATH" ]; then
            cp -r --parents $FILE $BACKUP_PATH
        fi
    done

    if [ "$files" != "" ]; then
        # Check if external configuration is specified
        [ -z "$XSTYLER_CONFIG" ] && configParam="" || configParam="-c $XSTYLER_CONFIG"

        # Format XAML files
        $XSTYLER_PATH -f "$files" $configParam
        git add -u
    else
        echo "No XAML files detected in commit"
    fi

    exit 0
}

Have a useful recipe? Let us know, and we will add it to the Wiki for others to use in their projects.