Skip to content

Instantly share code, notes, and snippets.

@robmckinnon
Last active August 29, 2015 14:06
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save robmckinnon/19ca44feda320fcd3399 to your computer and use it in GitHub Desktop.
Save robmckinnon/19ca44feda320fcd3399 to your computer and use it in GitHub Desktop.
pre-commit
#!/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
@dotemacs
Copy link

@robmckinnon maybe also mention that once the file is saved as .git/hooks/pre-commit it should be made executable

chmod 755 .git/hooks/pre-commit

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment