From 2c6e3ea2e988c33925e5e91c3a01e2acdae453ff Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?kleines=20Filmr=C3=B6llchen?= Date: Sat, 18 Jun 2022 13:17:52 +0200 Subject: [PATCH] Meta: Add a PNG size check to CI and pre-commit checks This uses optipng to check how much size can be reduced on PNG files. If that's more than 2 KiB for at least one file, the check fails. As with other checks, it doesn't run if optipng is not installed. --- Meta/check-png-sizes.sh | 42 +++++++++++++++++++++++++++++++++++++++++ Meta/lint-ci.sh | 1 + 2 files changed, 43 insertions(+) create mode 100755 Meta/check-png-sizes.sh diff --git a/Meta/check-png-sizes.sh b/Meta/check-png-sizes.sh new file mode 100755 index 0000000000..2512171d1f --- /dev/null +++ b/Meta/check-png-sizes.sh @@ -0,0 +1,42 @@ +#!/usr/bin/env bash + +set -eo pipefail + +# 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. +: "${MINIMUM_OPTIMIZATION_BYTES:=1024}" + +script_path=$(cd -P -- "$(dirname -- "$0")" && pwd -P) +cd "${script_path}/.." + +if ! command -v optipng >/dev/null ; then + echo 'optipng is not installed, skipping png size check.' + echo 'Please install optipng for your system to run this check.' + exit 0 +fi + +files=() +for file in "$@"; do + if [[ "${file}" == *".png" ]]; then + files+=("${file}") + fi +done + +if (( ${#files[@]} )); then + # 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. + optimizations=$( printf '%s\0' "${files[@]}" |\ + xargs -0 -n1 optipng -strip all -out dummy-optipng-output.png -clobber 2>&1 |\ + grep -i -e 'Output IDAT size =' |\ + 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' |\ + awk "{ if (\$1 >= $MINIMUM_OPTIMIZATION_BYTES) { S+=\$1 } } END { print S }") + rm -f dummy-optipng-output.png dummy-optipng-output.png.bak + optimizations="${optimizations:-0}" + + if [[ "$optimizations" -ne 0 ]] ; then + echo "There are non-optimized PNG images in Base/. It is possible to reduce file sizes by at least $optimizations byte(s)." + # shellcheck disable=SC2016 # we're not trying to expand expressions here + echo 'Please run optipng with `-strip all` on modified PNG images and try again.' + exit 1 + fi +else + echo 'No PNG images to check.' +fi diff --git a/Meta/lint-ci.sh b/Meta/lint-ci.sh index 84dc27328a..10ef401cb6 100755 --- a/Meta/lint-ci.sh +++ b/Meta/lint-ci.sh @@ -24,6 +24,7 @@ for cmd in \ Meta/check-debug-flags.sh \ Meta/check-markdown.sh \ Meta/check-newlines-at-eof.py \ + Meta/check-png-sizes.sh \ Meta/check-style.py \ Meta/lint-executable-resources.sh \ Meta/lint-keymaps.py \