Created
March 8, 2016 20:33
-
-
Save henriquemenezes/434d94f3e4a0a2a34dfd to your computer and use it in GitHub Desktop.
Git's pre-commit hook to remove trailing whitespaces/tabs Raw
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/bin/sh | |
# | |
# This will remove the trailing whitespaces from the files and add it again to be committed. | |
# | |
# Put this into ~/.git-templates/hooks/pre-commit, and chmod +x it. | |
# Detect platform | |
platform="win" | |
uname_result=`uname` | |
if [ "$uname_result" = "Linux" ]; then | |
platform="linux" | |
elif [ "$uname_result" = "Darwin" ]; then | |
platform="mac" | |
fi | |
if git rev-parse --verify HEAD >/dev/null 2>&1; then | |
against=HEAD | |
else | |
# Initial commit: diff against an empty tree object | |
against=4b825dc642cb6eb9a060e54bf8d69288fbee4904 | |
fi | |
# Remove trailing whitespaces | |
if test "$(git diff-index --check --cached $against --)"; then | |
echo "Removing trailing whitespaces..." | |
for FILE in `git diff-index --check --cached $against -- | sed '/^[+-]/d' | cut -d: -f1 | uniq`; do | |
echo "* $FILE" ; | |
# Replace trailing spaces | |
if [ "$platform" == "win" ]; then | |
# in windows, `sed -i` adds ready-only attribute to $file(I don't kown why), so we use temp file instead | |
sed 's/[[:space:]]*$//' "$FILE" > "${FILE}.tmp" | |
mv -f "${FILE}.tmp" "$FILE" | |
elif [ "$platform" == "mac" ]; then | |
sed -i "" 's/[[:space:]]*$//' "$FILE" | |
else | |
sed -i 's/[[:space:]]*$//' "$FILE" | |
fi | |
git add "$FILE" | |
done | |
fi | |
# Now we can commit | |
exit |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment