Last active
August 29, 2015 14:06
-
-
Save robmckinnon/19ca44feda320fcd3399 to your computer and use it in GitHub Desktop.
pre-commit
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 | |
# | |
# In your git repo: | |
# 1. save this file as: .git/hooks/pre-commit | |
# 2. chmod 755 .git/hooks/pre-commit | |
# | |
# An hook script to normalize what is about to be committed. | |
# Called by "git commit" with no arguments. | |
# Removes trailing whitespace if it exists from files. | |
# Replaces multiple blank lines with single blank line in files. | |
# For files (not deleted) in the index | |
files=$(git diff-index --name-status --cached HEAD | grep -v ^D | cut -c3-) | |
echo "running .git/hooks/pre-commit" | |
if [ "$files" != "" ] | |
then | |
for f in $files | |
do | |
# Only examine known text files | |
if [[ "$f" =~ [.](coffee|rb)$ ]] | |
then | |
# Remove trailing whitespace if it exists | |
if grep -q "[[:blank:]]$" $f | |
then | |
echo "stripped trailing whitespace in: $f" | |
sed -i "" -e $'s/[ \t]*$//g' $f | |
git add $f | |
fi | |
# Replace multiple blank lines with single blank line | |
cat -s $f > "$f.tmp" | |
diff --brief $f "$f.tmp" >/dev/null | |
comp_value=$? | |
if [ $comp_value -eq 1 ] | |
then | |
echo "squeezed multiple blank lines in: $f" | |
mv "$f.tmp" $f | |
git add $f | |
else | |
rm "$f.tmp" | |
fi | |
fi | |
done | |
fi |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
@robmckinnon maybe also mention that once the file is saved as .git/hooks/pre-commit it should be made executable