#!/bin/sh
#
# Copyright 2017 The LazyJsonMapper Project
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
# ----------------------------------------------------------------------------
#
# Verifies that all files in the worktree follow our codestyle standards.
#
# Note that this script can't check that they're actually committing the nicely
# formatted code. It just checks that the worktree is clean. So if they've fixed
# all files but haven't added the codestyle fixes to their commit, they'll still
# pass this check. But it's still a great protection against most mistakes.
#
# To install this hook, just run the following in the project's root folder:
#   ln -fs "../../.pre-commit.hook" .git/hooks/pre-commit
#

# Redirect output to stderr.
exec 1>&2

# Git ensures that CWD is always the root of the project folder, so we can just
# run all tests without verifying what folder we are in...

failed="no"
echo "[pre-commit] Checking work-tree codestyle..."

# Check the general codestyle format.
echo "> Verifying php-cs-fixer..."
vendor/bin/php-cs-fixer fix --config=.php_cs.dist --allow-risky yes --dry-run
if [ $? -ne 0 ]; then
    failed="yes"
fi

# Look for specific problems with the style, related to our project.
echo "> Verifying checkStyle..."
/usr/bin/env php devtools/checkStyle.php x
if [ $? -ne 0 ]; then
    failed="yes"
fi

# Refuse to commit if there were problems. Instruct the user about solving it.
if [ "${failed}" = "yes" ]; then
    # Yes there are lots of "echo" commands, because "\n" is not cross-platform.
    echo "[commit failed] There are problems with your code..."
    echo ""
    echo "Run 'composer codestyle' to fix the code in your worktree."
    echo ""
    echo "But beware that the process is automatic, and that the result"
    echo "isn't always perfect and won't be automatically staged."
    echo ""
    echo "So remember to manually read through the changes, then further"
    echo "fix them if necessary, and finally stage the updated code"
    echo "afterwards so that the fixed code gets committed."
    exit 1
fi
