check-png-sizes.sh 1.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546
  1. #!/usr/bin/env bash
  2. set -eo pipefail
  3. # How many bytes optipng has to be able to strip out of the file for the optimization to be worth it. The default is 1 KiB.
  4. : "${MINIMUM_OPTIMIZATION_BYTES:=1024}"
  5. script_path=$(cd -P -- "$(dirname -- "$0")" && pwd -P)
  6. cd "${script_path}/.."
  7. if ! command -v optipng >/dev/null ; then
  8. if [[ "$GITHUB_ACTIONS" == "true" ]]; then
  9. echo 'optipng is not installed, failing check because running in CI.'
  10. exit 1
  11. fi
  12. echo 'optipng is not installed, skipping png size check.'
  13. echo 'Please install optipng for your system to run this check.'
  14. exit 0
  15. fi
  16. files=()
  17. for file in "$@"; do
  18. if [[ "${file}" == *".png" ]]; then
  19. files+=("${file}")
  20. fi
  21. done
  22. if (( ${#files[@]} )); then
  23. # We need to allow optipng to write output so we can check what it actually did. We use a dummy file that's discarded afterwards.
  24. optimizations=$( printf '%s\0' "${files[@]}" |\
  25. xargs -0 -n1 optipng -strip all -out dummy-optipng-output.png -clobber 2>&1 |\
  26. grep -i -e 'Output IDAT size =' |\
  27. sed -E 's/Output IDAT size = [0-9]+ byte(s?) \(([0-9]+) byte(s?) decrease\)/\2/g;s/Output IDAT size = [0-9]+ byte(s?) \(no change\)/0/g' |\
  28. awk "{ if (\$1 >= $MINIMUM_OPTIMIZATION_BYTES) { S+=\$1 } } END { print S }")
  29. rm -f dummy-optipng-output.png dummy-optipng-output.png.bak
  30. optimizations="${optimizations:-0}"
  31. if [[ "$optimizations" -ne 0 ]] ; then
  32. echo "There are non-optimized PNG images in Base/. It is possible to reduce file sizes by at least $optimizations byte(s)."
  33. # shellcheck disable=SC2016 # we're not trying to expand expressions here
  34. echo 'Please run optipng with `-strip all` on modified PNG images and try again.'
  35. exit 1
  36. fi
  37. else
  38. echo 'No PNG images to check.'
  39. fi