Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
#!/bin/bash
version=$(astyle --version 2>/dev/null)
if test "x$version" = "x"; then
echo "astyle can't be found"
exit 1
fi
# @parm $1 - input file
# @parm $2 - output file (optional)
function beautify_code {
input=$1
if [ ! -f "$input" ]; then
echo "File $input not found!"
exit 1
fi
if [ -z "$2" ]; then
output=$input
else
output=$2
cp $input $output
fi
astyle --style=allman \
--indent=tab \
--indent-col1-comments \
--pad-oper \
--pad-header \
--align-pointer=type \
--add-brackets \
--mode=c \
--suffix=none \
--unpad-paren \
$output
}
# @parm $1 - input file
# @return: 0 if style is correct; othrewise, returns value not equal to 0
function generate_diff {
input=$1
output=$(mktemp --dry-run /tmp/$input.XXXXXXXXX)
beautify_code $input $output
diff -u -p "${input}" "${output}"
isdiff=$?
rm "${output}"
return $isdiff
}
if [ "$1" == "-h" ] || [ -z "$1" ]; then
echo "Usage: $(basename $0) (OPTION | FILE)
With no OPTION, prints a diff betwen FILE and formatted FILE to a standard output
-h display this help and exit
-g git pre-commit hook mode (checks style of all stagged files)
-f FILE format the FILE
"
exit 0
elif [ "$1" == "-f" ]; then
beautify_code $2
exit $?
elif [ "$1" == "-g" ]; then
extensions=("\.cc" "\.cpp")
grep_extensions=$(IFS="|" ; echo "${extensions[*]}")
invalid_files=()
for file in $(git diff-index --cached --name-only HEAD --diff-filter=ACMR | grep -P "(${grep_extensions})");
do
input=$(git checkout-index --temp $file | cut -f 1)
echo " ==== Checking $file ===="
generate_diff $input
if [ $? -eq 1 ]; then
invalid_files+=($file)
fi
rm "${input}"
done
if [ ${#invalid_files[@]} -gt 0 ]; then
echo ""
echo "========= SUMMARY =========="
echo " Invalid style in following files:"
printf " * %s\n" "${invalid_files[@]}"
echo " Run"
echo " $(basename "$0") -f <FILE>"
echo " to fix the issues."
exit 1
fi
exit 0
else
generate_diff $1
exit $?
fi
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.