Skip to content

Instantly share code, notes, and snippets.

@matthieuprat
Last active January 14, 2016 18:06
Show Gist options
  • Select an option

  • Save matthieuprat/21419a5057252c4d7def to your computer and use it in GitHub Desktop.

Select an option

Save matthieuprat/21419a5057252c4d7def to your computer and use it in GitHub Desktop.
Ensure that a file has one and only one final new line
fix_eof() {
for f; do
: Add a final new line if needed.
[ "$(tail -c1 $f)" = "" ] || echo >> $f
: Remove extra final new lines.
while [ "$(tail -c2 $f)" = "" ] && [ $(wc -l < $f) -gt 1 ]; do
sed -i '' '$ d' $f
done
done
}
: Fix EOF of all non-binary tracked files.
fix_eof $(git grep --cached --name-only -I '')
fix_eof() {
for f; do
: Add a final new line if needed.
[ "$(tail -c1 $f)" = "" ] || echo >> $f
: Remove extra final new lines.
while [ "$(tail -c2 $f)" = "" ] && [ $(wc -l < $f) -gt 1 ]; do
sed -i '' '$ d' $f
done
done
}
test() {
f=$(mktemp)
printf "$1" > $f
fix_eof $f
d=$(diff $f <(printf "$2"))
[ -z "$d" ] && echo OK || echo -e "Failure:\n$f"
rm $f
}
test '' ''
test '\n' '\n'
test '\n\n' '\n'
test 'foo' 'foo\n'
test 'foo\n' 'foo\n'
test 'foo\nbar' 'foo\nbar\n'
test 'foo\nbar\n\n' 'foo\nbar\n'
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment