Last active
August 29, 2015 14:03
-
-
Save contivero/d67fa603a0913e13ab10 to your computer and use it in GitHub Desktop.
pre-commit git hook for validation and minification of staged html files
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/sh | |
# Script to validate htmls, minify them, and minify css before commiting | |
# Exits on validation failure. Minified files, and any other website resource | |
# needed is copied into $DIR_TO_COPY | |
readonly HTML_COMPRESSOR_PATH="$(git config hooks.htmlcompressor)" | |
readonly YUI_COMPRESSOR_PATH="$(git config hooks.yuicompressor)" | |
readonly DIR_TO_COPY=minified-site #path into which to copy files | |
readonly VALIDATOR="tidy" | |
# ============================================================================= | |
echo "Starting git pre-commit hook..." | |
echo | |
set -e #exit on error | |
set -u #exit script if there is any uninitialized variable | |
err() { | |
echo "[$(date +'%Y-%m-%dT%H:%M:%S%z')]: $@" >&2 | |
} | |
if [ ! -f "$HTML_COMPRESSOR_PATH" ]; then | |
err "Unable to find htmlcompressor.jar on the configuration." | |
err "Please configure it with:" | |
err " git config hooks.htmlcompressor /path/to/jar" | |
exit 1 | |
fi | |
if [ ! -f "$YUI_COMPRESSOR_PATH" ]; then | |
err "Unable to find yuicompressor-x.y.z.jar on the configuration." | |
err "Please configure it with:" | |
err " git config hooks.yuicompressor /path/to/jar" | |
exit 2 | |
fi | |
validate_html(){ | |
echo "Validating: $1" | |
echo "‾‾‾‾‾‾‾‾‾‾‾" | |
$VALIDATOR -e $1 | |
echo #For some reason tidyhtml5 is eating the first echo | |
echo | |
} | |
minify_html(){ | |
echo -n "Minifying: $1... " | |
java -jar $HTML_COMPRESSOR_PATH --remove-input-attr \ | |
--remove-intertag-spaces --remove-quotes \ | |
--remove-style-attr --remove-link-attr --remove-script-attr \ | |
--remove-form-attr --simple-bool-attr --remove-js-protocol \ | |
--remove-http-protocol --remove-https-protocol \ | |
--remove-surrounding-spaces all $1 -o $DIR_TO_COPY/$1 | |
echo "done" | |
echo "‾‾‾‾‾‾‾‾‾‾" | |
} | |
minify_css(){ | |
echo -n "Minifying: $1... " | |
java -jar $YUI_COMPRESSOR_PATH $1 -o $DIR_TO_COPY/$1 | |
echo "done" | |
echo "‾‾‾‾‾‾‾‾‾‾" | |
} | |
#for every file staged | |
git diff --cached --name-only | while read file; do | |
extension=${file: -5} | |
case $extension in | |
.html) | |
validate_html $file | |
minify_html $file | |
;; | |
*.css) | |
minify_css $file | |
;; | |
*) | |
echo -n "copying: $file... " | |
cp -u --parent $file $DIR_TO_COPY | |
echo "done" | |
;; | |
esac | |
done |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment