diff --git a/bash-folders-image-to-webp.sh b/bash-folders-image-to-webp.sh index 259be3c..53e8def 100755 --- a/bash-folders-image-to-webp.sh +++ b/bash-folders-image-to-webp.sh @@ -3,66 +3,79 @@ set -e usage() { - [[ -n "${*}" ]] && printf '%s\n' "Error: ${*}" >&2 - 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 OPTIONS: - --help Display this usage message and exit - --folder PATH PATH to be monitored + -h, --help Display this usage message and exit + -q, --quaity INT Specify the compression factor between 0-100 (default: 90) + +SEE ALSO: + cwebp(1), inotifywait(1) EOF exit 1 } -start() { - inotifywait -m -e create,moved_to --format '%f' "$FOLDER_ORIGIN" | while read -r filename; do - extension="${filename##*.}" - for ext in "${EXTENSIONS_TO_WATCH[@]}"; do - 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 +require() { + command -v "${1}" &>/dev/null && return + printf '%s\n' "Missing required application: '${1}'" >&2 + return 1 } -while [[ $# -gt 0 ]] -do - key="$1" - case $key in - --folder) - FOLDER_ORIGIN="$2" - shift 2 - ;; - --quality) - QUALITY="$2" - shift 2 - ;; - *) - usage "Unknown option: $1" - ;; - esac -done +run() { + local file extension -QUALITY="90" -MESSAGE_WAITING="converting_please_wait" -EXTENSIONS_TO_WATCH=("jpg" "jpeg" "png") + mkdir --parents "${1}" -if ! command -v cwebp > /dev/null; then - printf '%s\n' "Error: You must install WebP tooling" >&2 - exit 1 -fi + while read -r file; do + extension="${file##*.}" + [[ "${extension,,}" =~ ^(png|jpe?g)$ ]] || continue -# Check if the required --folder flag is provided -if [[ -z "$FOLDER_ORIGIN" ]]; then - printf '%s\n' "Error: The --folder flag is required" >&2 - exit 1 -fi + printf '%s\n' "Converting file '${file}'..." + if ! cwebp -q "${quality}" -o "${1}/${file%.*}.webp" "${1}/${file}"; then + printf '%s\n' "Failed to convert file: '${file}'" >&2 + fi + done < <(inotifywait --monitor --event "create" --event "moved_to" --format '%f' "${1}") +} -start +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 + shift + done + + if [[ -z "${1}" ]]; then + printf '%s\n' "No folder specified" >&2 + return 1 + fi + + require "inotifywait" || return + require "cwebp" || return + + run "${1}" +} + +main "${@}"