| 1 |
#!/bin/bash |
| 2 |
# |
| 3 |
# This pre-commit hook checks if any versions of clang-format |
| 4 |
# are installed, and if so, uses the installed version to format |
| 5 |
# the staged changes. |
| 6 |
|
| 7 |
export PATH=$PATH:/opt/rocm/llvm/bin:/opt/rocm/hcc/bin:/usr/bin:/bin |
| 8 |
|
| 9 |
set -x |
| 10 |
|
| 11 |
|
| 12 |
# Redirect stdout to stderr. |
| 13 |
exec >&2 |
| 14 |
|
| 15 |
# Do everything from top - level |
| 16 |
cd $(git rev-parse --show-toplevel) |
| 17 |
|
| 18 |
if git rev-parse --verify HEAD >/dev/null 2>&1; then |
| 19 |
against=HEAD |
| 20 |
else |
| 21 |
# Initial commit: diff against an empty tree object |
| 22 |
against=4b825dc642cb6eb9a060e54bf8d69288fbee4904 |
| 23 |
fi |
| 24 |
|
| 25 |
if [[ "$1" == "--reformat" ]]; then |
| 26 |
files=$(git ls-files --exclude-standard) |
| 27 |
else |
| 28 |
files=$(git diff-index --cached --name-only $against) |
| 29 |
fi |
| 30 |
|
| 31 |
[[ -z "$files" ]] && exit |
| 32 |
|
| 33 |
# Change the copyright date at the top of any text files |
| 34 |
for file in $files; do |
| 35 |
if [[ -e $file ]]; then |
| 36 |
/usr/bin/perl -pi -e 'INIT { exit 1 if !-f $ARGV[0] || -B $ARGV[0]; $year = (localtime)[5] + 1900 } |
| 37 |
s/^([*\/#[:space:]]*)Copyright\s+(?:\(C\)\s*)?(\d+)(?:\s*-\s*\d+)?/qq($1Copyright (C) $2@{[$year != $2 ? "-$year" : ""]})/ie |
| 38 |
if $. < 10' "$file" && git add -u "$file" |
| 39 |
fi |
| 40 |
done |
| 41 |
|
| 42 |
# do the formatting |
| 43 |
for file in $files; do |
| 44 |
if [[ -e $file ]] && echo $file | grep -Eq '\.c$|\.h$|\.hpp$|\.cpp$|\.cl$|\.in$|\.txt$|\.yaml$|\.sh$|\.py$|\.pl$|\.cmake$|\.md$|\.rst$|\.groovy$'; then |
| 45 |
sed -i -e 's/[[:space:]]*$//' "$file" # Remove whitespace at end of lines |
| 46 |
sed -i -e '$a\' "$file" # Add missing newline to end of file |
| 47 |
# Convert UTF8 non-ASCII to ASCII |
| 48 |
temp=$(mktemp) |
| 49 |
[[ -w $temp ]] || exit |
| 50 |
iconv -s -f utf-8 -t ascii//TRANSLIT "$file" > "$temp" || exit |
| 51 |
chmod --reference="$file" "$temp" || exit |
| 52 |
mv -f "$temp" "$file" || exit |
| 53 |
git add -u "$file" |
| 54 |
fi |
| 55 |
done |
| 56 |
|
| 57 |
# if clang-format exists, run it on C/C++ files |
| 58 |
if command -v clang-format >/dev/null; then |
| 59 |
for file in $files; do |
| 60 |
[[ -L $file ]] && continue |
| 61 |
if [[ -e $file ]] && echo $file | grep -Eq '\.c$|\.h$|\.hpp$|\.cpp$|\.cl$|\.h\.in$|\.hpp\.in$|\.cpp\.in$'; then |
| 62 |
echo "clang-format $file" |
| 63 |
clang-format -i -style=file "$file" |
| 64 |
git add -u "$file" |
| 65 |
fi |
| 66 |
done |
| 67 |
else |
| 68 |
echo "clang-format command not found, skipping file formatting." |
| 69 |
fi |