Last active
June 8, 2022 14:10
-
-
Save MarcoPriebe/9365054 to your computer and use it in GitHub Desktop.
pre-commit git hook to remove trailing whitespace
This file contains hidden or 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/bash | |
| # | |
| # A git hook script to find and fix trailing whitespace | |
| # in your commits. Bypass it with the --no-verify option | |
| # to git-commit | |
| # | |
| # Logic: | |
| # | |
| # The 'git stash save' fails if the tree is clean (instead of | |
| # creating an empty stash :P). So, we only 'stash' and 'pop' if | |
| # the tree is dirty. | |
| # | |
| # The 'git rebase --whitespace=fix HEAD~' throws away the commit | |
| # if it's empty, and adding '--keep-empty' prevents the whitespace | |
| # from being fixed. So, we first check that the index is dirty. | |
| # | |
| # Also: | |
| # - '(! git diff-index --quiet --cached HEAD)' is true (zero) if | |
| # the index is dirty | |
| # - '(! git diff-files --quiet .)' is true if the tree is dirty | |
| # | |
| # The 'rebase --whitespace=fix' trick is from here: | |
| # http://stackoverflow.com/a/19156679/470844 | |
| # | |
| if (! git diff-files --quiet .) && \ | |
| (! git diff-index --quiet --cached HEAD) ; then | |
| git commit --quiet --no-verify -m FIXWS_SAVE_INDEX && \ | |
| git stash save --quiet FIXWS_SAVE_TREE && \ | |
| git rebase --quiet --whitespace=fix HEAD~ && \ | |
| git reset --quiet --soft HEAD~ && \ | |
| git stash pop --quiet | |
| elif (! git diff-index --quiet --cached HEAD) ; then | |
| git commit --quiet --no-verify -m FIXWS_SAVE_INDEX && \ | |
| git rebase --quiet --whitespace=fix HEAD~ && \ | |
| git reset --quiet --soft HEAD~ | |
| fi |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment