Moved everything into functions for scoping; added option to specify quality at runtime

This commit is contained in:
Alex Paarfus
2023-06-27 13:07:36 -04:00
parent 57026af5d9
commit d59edb33dd

View File

@@ -3,66 +3,79 @@
set -e set -e
usage() { usage() {
[[ -n "${*}" ]] && printf '%s\n' "Error: ${*}" >&2
cat << EOF cat << EOF
USAGE: ${0##*/} [OPTION] --folder PATH USAGE: ${0##*/} [OPTIONS] PATH
Watches when new image (PNG or JPEG) are added and transform to WebP format Watches when new image (PNG or JPEG) are added and transform to WebP format
OPTIONS: OPTIONS:
--help Display this usage message and exit -h, --help Display this usage message and exit
--folder PATH PATH to be monitored -q, --quaity INT Specify the compression factor between 0-100 (default: 90)
SEE ALSO:
cwebp(1), inotifywait(1)
EOF EOF
exit 1 exit 1
} }
start() { require() {
inotifywait -m -e create,moved_to --format '%f' "$FOLDER_ORIGIN" | while read -r filename; do command -v "${1}" &>/dev/null && return
extension="${filename##*.}" printf '%s\n' "Missing required application: '${1}'" >&2
for ext in "${EXTENSIONS_TO_WATCH[@]}"; do return 1
if [[ "$ext" == "$extension" ]]; then
filename_output="${filename%.*}.webp"
touch "$FOLDER_ORIGIN/$MESSAGE_WAITING"
cwebp -q "$QUALITY" "$FOLDER_ORIGIN/$filename" -o "$FOLDER_ORIGIN/$filename_output"
rm "$FOLDER_ORIGIN/$MESSAGE_WAITING"
fi
done
done
} }
while [[ $# -gt 0 ]] run() {
do local file extension
key="$1"
case $key in mkdir --parents "${1}"
--folder)
FOLDER_ORIGIN="$2" while read -r file; do
shift 2 extension="${file##*.}"
;; [[ "${extension,,}" =~ ^(png|jpe?g)$ ]] || continue
--quality)
QUALITY="$2" printf '%s\n' "Converting file '${file}'..."
shift 2 if ! cwebp -q "${quality}" -o "${1}/${file%.*}.webp" "${1}/${file}"; then
;; printf '%s\n' "Failed to convert file: '${file}'" >&2
*) fi
usage "Unknown option: $1" done < <(inotifywait --monitor --event "create" --event "moved_to" --format '%f' "${1}")
}
main() {
local opts quality
quality="90"
opts="$(getopt \
--options hq: \
--longoptions help,quality: \
--name "${0##*/}" \
-- "${@}" \
)"
eval set -- "${opts}"
while true; do
case "${1}" in
-h | --help ) usage; return 0;;
-q | --quality ) quality="${2}"; shift;;
-- ) shift; break;;
* )
printf '%s\n' "Unknown option: '${1}'" >&2
usage
return 1
;; ;;
esac esac
done shift
done
QUALITY="90" if [[ -z "${1}" ]]; then
MESSAGE_WAITING="converting_please_wait" printf '%s\n' "No folder specified" >&2
EXTENSIONS_TO_WATCH=("jpg" "jpeg" "png") return 1
fi
if ! command -v cwebp > /dev/null; then require "inotifywait" || return
printf '%s\n' "Error: You must install WebP tooling" >&2 require "cwebp" || return
exit 1
fi
# Check if the required --folder flag is provided run "${1}"
if [[ -z "$FOLDER_ORIGIN" ]]; then }
printf '%s\n' "Error: The --folder flag is required" >&2
exit 1
fi
start main "${@}"