bin/imgoptim: refactor + dependency checks

This commit is contained in:
Henrik Lissner 2017-12-18 01:29:37 -05:00
parent 6b50f0f4e7
commit 4fb5501fd2
No known key found for this signature in database
GPG key ID: 5F6C0EA160557395

View file

@ -1,6 +1,6 @@
#!/usr/bin/env zsh #!/usr/bin/env zsh
# A simple script that losslessly optimizes image files given to it. # Optimize image files (losslessly by default)
# #
# Examples: # Examples:
# imgoptim image.jpg image.png image.gif # imgoptim image.jpg image.png image.gif
@ -11,13 +11,14 @@
# PNGs: optipng, pngquant (lossy) # PNGs: optipng, pngquant (lossy)
# JPGs: jpegtran, jpegoptim (lossy) # JPGs: jpegtran, jpegoptim (lossy)
# GIFs: gifsicle # GIFs: gifsicle
#
# Packages (same name on homebrew & arch linux)
# optipng [pngquant] libjpeg-turbo [jpegoptim] gifsicle
set -e set -e
unset CDPATH unset CDPATH
LOSSY= _usage() {
usage() {
cat <<EOL cat <<EOL
Usage: ${0:A:t} [-lh] IMAGE [IMAGE2 [IMAGE3 [...]]] Usage: ${0:A:t} [-lh] IMAGE [IMAGE2 [IMAGE3 [...]]]
@ -26,16 +27,6 @@ Usage: ${0:A:t} [-lh] IMAGE [IMAGE2 [IMAGE3 [...]]]
EOL EOL
} }
while getopts hl opt; do
case $opt in
h) usage; exit;;
l) LOSSY=1;;
:) >&2 echo "$OPTARG requires an argument"; usage; exit 1;;
*) >&2 echo "Not a valid arg: $opt"; usage; exit 1;;
esac
done
shift $((OPTIND-1))
_filesize() { _filesize() {
case $OSTYPE in case $OSTYPE in
darwin*) stat -c%s "$1" ;; darwin*) stat -c%s "$1" ;;
@ -43,6 +34,30 @@ _filesize() {
esac esac
} }
#
while getopts hl opt; do
case $opt in
h) _usage; exit;;
l) lossy=1;;
:) >&2 echo "$OPTARG requires an argument"; _usage; exit 1;;
*) >&2 echo "Not a valid arg: $opt"; _usage; exit 1;;
esac
done
shift $((OPTIND-1))
cmds=( optipng jpegtran gifsicle )
[[ $lossy ]] && cmds=( $cmds pngquant jpegoptim )
for cmd in "optipng jpegtran gifsicle"; do
if ! command -v $cmd >/dev/null; then
>&2 echo "$cmd isn't installed"
error=1
fi
done
if [[ $error ]]; then
>&2 echo "There were errors, aborting"
exit 1
fi
for file in $@; do for file in $@; do
if [[ -d $file ]]; then if [[ -d $file ]]; then
imgoptim $file/* imgoptim $file/*
@ -50,14 +65,14 @@ for file in $@; do
pre_size=$(_filesize "$file") pre_size=$(_filesize "$file")
case ${file##*.} in case ${file##*.} in
png) png)
[[ $LOSSY ]] && pngquant $file [[ $lossy ]] && pngquant $file
optipng -nc -nb -o7 $file optipng -nc -nb -o7 $file
;; ;;
gif) gif)
gifsicle --batch --optimize=3 "$file" gifsicle --batch --optimize=3 "$file"
;; ;;
jpg|jpeg) jpg|jpeg)
[[ $LOSSY ]] && jpegoptim --max=90 "$file" [[ $lossy ]] && jpegoptim --max=90 "$file"
jpegtran -copy none -optimize -progressive -outfile "$file" "$file" jpegtran -copy none -optimize -progressive -outfile "$file" "$file"
;; ;;
*) *)