Created
February 20, 2013 16:55
-
-
Save drhayes/4997048 to your computer and use it in GitHub Desktop.
Pre-commit hook to remove trailing whitespace on lines you've actually changed
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
# | |
# Shamelessly copied from http://blog.yesmeck.com/archives/make-git-automatically-remove-trailing-whitespace-before-committing/ | |
# | |
# What's distinct about this version, as opposed to several I've seen, | |
# is that it only fixes the whitespace on lines you've actually changed, | |
# so avoids making you the blamee of code you didn't change. | |
# Find files with trailing whitespace | |
for file in `git diff --check --cached | grep '^[^+-]' | grep -o '^.*[0-9]\+:'` ; do | |
file_name=`echo ${file} | grep -o '^[^:]\+'` | |
line_number=`echo ${file} | grep -oP '(?<=:)[0-9]+(?=:)'` | |
# I think the reason there are two sed commands here | |
# is that 'sed -i' is different on different systems. | |
# shoot me. | |
(sed -i "${line_number}s/\s*$//" "${file_name}" > /dev/null 2>&1 \ | |
|| sed -i '' -E "${line_number}s/\s*$//" "${file_name}") | |
git add ${file_name} | |
echo "Re-wrote ${file_name} to trim whitespace." | |
done | |
# Now we can commit | |
exit |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment