Skip to content

Instantly share code, notes, and snippets.

@BjornFJohansson
Last active June 7, 2024 04:32
Show Gist options
  • Save BjornFJohansson/60fb8133a8043cc0573a97c06adfab8b to your computer and use it in GitHub Desktop.
Save BjornFJohansson/60fb8133a8043cc0573a97c06adfab8b to your computer and use it in GitHub Desktop.
#!/usr/bin/bash
#
# Git pre-commit hook for obsidian.ms or other collections of markdown files.
# This hook works with obsidian-git https://github.com/denolehov/obsidian-git
#
# An hook script to verify what is about to be committed.
# This script is 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:
# Removes empty lines at the end of the file, leaving one.
# Removes trailing empty space at the end of a lines.
#
# Information used to create this script:
# https://eng.wealthfront.com/2011/03/08/corrective-action-with-gits-pre-commit/
# http://stackoverflow.com/questions/13223868/how-to-stage-line-by-line-in-git-gui-although-no-newline-at-end-of-file-warnin
# https://unix.stackexchange.com/questions/552188/how-to-remove-empty-lines-from-beginning-and-end-of-file
git diff-index --name-only --cached HEAD -z |
while read -d $'\0' f
do
echo $f
# Only examine markdown text files
if [[ "$f" =~ [.](md)$ ]] # conf|css|erb|html|js|json|log|properties|rb|ru|txt|xml|yml|h|m
then
# Detect two trailing empty lines at the end of file
if [ -z $(tail -n2 "$f") ]
then
echo trailing empty lines: $f
# remove blank lines from the begin of file
# sed -i '/./,$!d' "$f"
# remove blank lines from the end of file:
sed -i -e :a -e '/^\n*$/{$d;N;ba' -e '}' "$f"
# remove blank lines from the begin and end of file
# sed -i -e '/./,$!d' -e :a -e '/^\n*$/{$d;N;ba' -e '}' "$f"
# echo >> $f
git add "$f"
fi
# Detect trailing whitespace at the end of lines
if grep -q "[[:blank:]]$" "$f"
then
echo trailing ws: $f
# Remove trailing whitespace from the end of lines
sed -i"" -e $'s/[ t]*$//g' "$f"
git add "$f"
fi
fi
done
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment