Skip to content

Instantly share code, notes, and snippets.

@kylerippey
Created March 28, 2018 00:06
Show Gist options
  • Save kylerippey/8fb999c110e8dcc294d3256879dc104e to your computer and use it in GitHub Desktop.
Save kylerippey/8fb999c110e8dcc294d3256879dc104e to your computer and use it in GitHub Desktop.
Pre-commit git hook to optimize assets upon commit
#!/bin/sh
if git rev-parse --verify HEAD >/dev/null 2>&1
then
against=HEAD
else
# Initial commit: diff against an empty tree object
against=4b825dc642cb6eb9a060e54bf8d69288fbee4904
fi
# Redirect output to stderr.
exec 1>&2
# Check for changes to png or jpg assets
if test $(git diff --cached --name-only --diff-filter=ACMR $against | grep "\.\(png\|jpg\)$" | wc -l | tr -d ' ') != 0
then
cat <<\EOF
============================= Optimizing assets =============================
EOF
# TODO: Check if pngcrush is installed. If not, display a warning
# Optimize pngs
exec git diff --cached --name-only --diff-filter=ACMR $against | grep "\.png$" | xargs -I % pngcrush -q -brute -ow -noforce %
exec git diff --cached --name-only --diff-filter=ACMR $against | grep "\.png$" | xargs -I % git add %
# TODO: Check if jpegoptim is installed. If not, display a warning
# Optimize jpgs
exec git diff --cached --name-only --diff-filter=ACMR $against | grep "\.jpg$" | xargs -I % jpegoptim %
exec git diff --cached --name-only --diff-filter=ACMR $against | grep "\.jpg$" | xargs -I % git add %
cat <<\EOF
======================== Asset optimization complete ========================
EOF
fi
# If there are whitespace errors, print the offending file names and fail.
exec git diff-index --check --cached $against --
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment