AfRApay/hooks/pre-commit.hook

49 lines
1.3 KiB
Plaintext
Raw Normal View History

2023-02-08 16:23:49 +01:00
#!/bin/bash
2023-02-08 16:36:42 +01:00
# Regexp for grep to only choose some file extensions for formatting
exts="\.\(cpp\|h\)$"
# The formatter to use
formatter=`which uncrustify`
# Check availability of the formatter
if [ -z "$formatter" ]
then
1>&2 echo "$formatter not found. Pre-commit formatting will not be done."
exit 0
fi
# Format staged files
for file in `git diff --cached --name-only --diff-filter=ACMR | grep $exts`
do
echo "Formatting $file"
2023-02-08 16:49:47 +01:00
# get tmpfile
tmpfile="${file//.cpp/.tmp.cpp}"
2023-02-08 17:34:18 +01:00
tmpfile="${tmpfile//.h/.tmp.h}"
2023-02-08 16:36:42 +01:00
# Get the file from index
2023-02-08 16:49:47 +01:00
git show ":$file" > "$tmpfile"
2023-02-08 16:36:42 +01:00
# Format it
2023-02-08 16:49:47 +01:00
"$formatter" --no-backup -c AfRApay.MateCard/.uncrustify.cfg "$tmpfile"
2023-02-08 23:31:06 +01:00
# Format the non-tmp file too, to prevent loops
"$formatter" --no-backup -c AfRApay.MateCard/.uncrustify.cfg "$file"
2023-02-08 16:36:42 +01:00
# Create a blob object from the formatted file
2023-02-08 16:49:47 +01:00
hash=`git hash-object -w "$tmpfile"`
2023-02-08 16:36:42 +01:00
# Add it back to index
git update-index --add --cacheinfo 100644 "$hash" "$file"
# Remove the tmp file
2023-02-08 16:49:47 +01:00
rm "$tmpfile"
2023-02-08 16:36:42 +01:00
done
2023-02-08 23:31:06 +01:00
# If amend - force succeed
IS_AMEND=$(ps -ocommand= -p $PPID | grep -e '--amend');
if [ -n "$IS_AMEND" ]; then
exit 0
fi
2023-02-08 16:36:42 +01:00
# If no files left in index after formatting - fail
ret=0
if [ ! "`git diff --cached --name-only`" ]; then
1>&2 echo "No files left after formatting"
exit 1
fi