Skip to content

Git Hook

David Grochocki edited this page Feb 5, 2016 · 7 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 Magic 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 Magic - xmagic.exe pre-commit Git Hook
# Documentation: https://github.com/grochocki/XamlMagic/wiki

# Define path to xmagic.exe
XMAGIC_PATH=

# Define path to XAML Magic configuration
XMAGIC_CONFIG=

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

echo "Running XAML Magic 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 xmagic.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 "$XMAGIC_CONFIG" ] && configParam="" || configParam="-c $XMAGIC_CONFIG"

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

    exit 0
}