From 2626ac2e4800c035d38ef3cf2e58cfb061df5f6e Mon Sep 17 00:00:00 2001 From: Steffen Vogel Date: Thu, 7 Sep 2023 12:26:36 +0200 Subject: [PATCH] Add pre-commit hook for clang-format Signed-off-by: Steffen Vogel --- tools/git-pre-commit-hook.sh | 43 ++++++++++++++++++++++++++++++++++++ 1 file changed, 43 insertions(+) create mode 100644 tools/git-pre-commit-hook.sh diff --git a/tools/git-pre-commit-hook.sh b/tools/git-pre-commit-hook.sh new file mode 100644 index 000000000..f6237b56a --- /dev/null +++ b/tools/git-pre-commit-hook.sh @@ -0,0 +1,43 @@ +#!/usr/bin/env bash +# +# Install / run pre-commit hook in repo +# +# Author: Steffen Vogel +# SPDX-FileCopyrightText: 2014-2023 Institute for Automation of Complex Power Systems, RWTH Aachen University +# SPDX-License-Identifier: Apache-2.0 + +format_file() { + FILE="${1}" + if [ -f ${FILE} ]; then + if ! clang-format --Werror --dry-run ${FILE}; then + clang-format -i ${FILE} + return 1 + fi + fi +} + +case "${1}" in + help) + echo "Run ${0} install to install the git commit hooks" + ;; + + install) + TOP_DIR=$(git rev-parse --show-toplevel) + cp "${BASH_SOURCE[0]}" "${TOP_DIR}/.git/hooks/pre-commit" + ;; + + *) + FILES=$(git diff-index --cached --name-only HEAD | grep -iE '\.(cpp|hpp|c|h)$') + CHANGES=0 + for FILE in ${FILES}; do + if ! format_file "${FILE}"; then + CHANGES=$((CHANGES+1)) + fi + done + + if (( ${CHANGES} > 0 )); then + echo "Formatting of ${CHANGES} files has been fixed. Please stage and commit again." + exit -1 + fi + ;; +esac