Created
November 6, 2012 11:48
-
-
Save johnjohndoe/4024222 to your computer and use it in GitHub Desktop.
Git pre-commit hook to add a new line at the end of a file and remove trailing whitespaces
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 | |
# | |
# An example hook script to verify what is about to be committed. | |
# Called by "git commit" with no arguments. The hook should | |
# exit with non-zero status after issuing an appropriate message if | |
# it wants to stop the commit. | |
# | |
# Usage: | |
# Remove the .sh file extension when you put the script in your hooks folder! | |
# | |
# Purposes: | |
# Add an empty line at the end of the file. | |
# Remove trailing spaces at the end of a line. | |
# | |
# Source: http://eng.wealthfront.com/2011/03/corrective-action-with-gits-pre-commit.html | |
# Version: 2011-03-08 | |
# Related: http://stackoverflow.com/questions/13223868/how-to-stage-line-by-line-in-git-gui-although-no-newline-at-end-of-file-warnin | |
# Files (not deleted) in the index | |
files=$(git diff-index --name-status --cached HEAD | grep -v ^D | cut -c3-) | |
if [ "$files" != "" ] | |
then | |
for f in $files | |
do | |
# Only examine known text files | |
if [[ "$f" =~ [.](conf|css|erb|html|js|json|log|properties|rb|ru|txt|xml|yml|h|m)$ ]] | |
then | |
# Add a linebreak to the file if it doesn't have one | |
if [ "$(tail -c1 $f)" != '\n' ] | |
then | |
echo >> $f | |
git add $f | |
fi | |
# Remove trailing whitespace if it exists | |
if grep -q "[[:blank:]]$" $f | |
then | |
sed -i "" -e $'s/[ \t]*$//g' $f | |
git add $f | |
fi | |
fi | |
done | |
fi |
@jugaldb I am not maintaining the code snippet. I recommend you do some research, create a first script and ask specific questions on Stackoverflow to solve your problem.
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
I want to add stuff in the beginning of the file, lets say in each file I want to add, 'Hello this was added at - time'