From d7a4fc9b8e5b301399a4c2cf5fffd954412ba0b4 Mon Sep 17 00:00:00 2001 From: Dan Church Date: Tue, 29 Jun 2021 11:51:50 -0500 Subject: [PATCH] Output number of freed bytes instead of success --- optipdf | 78 ++++++++++++++++++++++++++++++++++++++++++++++----------- 1 file changed, 64 insertions(+), 14 deletions(-) diff --git a/optipdf b/optipdf index f7235e8..440254a 100755 --- a/optipdf +++ b/optipdf @@ -18,6 +18,47 @@ file_size() { 2>/dev/null } +# produces a human-readable size from the byte count passed to it +hr_size() ( + declare -i BYTES=$1 + + #UNITS=(B KB MB GB TB PB EB ZB YB) # shell math can only go so far... + UNITS=(B KB MB GB TB) + FACT=1024 + THRESH=9/10 + DECIMALS=1 + DECIMALS_FACTOR=$(( 10 ** DECIMALS )) + + # cycle through units from largest to smallest, exiting when it finds the + # largest applicable unit + for (( EXP = ${#UNITS[@]} - 1; EXP > -1; --EXP )); do + # check if the unit is close enough to the unit's size, within the + # threshold + if [[ $BYTES -gt $((FACT ** EXP * $THRESH)) ]]; then + # we found the applicable unit + + # must multiply by a factor of 10 here to not truncate + # the given number of decimal places after the point + HR_VAL=$(( BYTES * DECIMALS_FACTOR / FACT ** EXP )) + + # put the decimal point in + if [[ $DECIMALS -gt 0 ]]; then + HR_VAL=$(( HR_VAL / DECIMALS_FACTOR )).$(( HR_VAL % DECIMALS_FACTOR )) + fi + + HR_UNIT=${UNITS[$EXP]} + break + fi + done + + if [[ -z $HR_UNIT ]]; then + HR_VAL=$BYTES + HR_UNIT=${UNITS[0]} + fi + + printf '%g %s\n' "$HR_VAL" "$HR_UNIT" +) + # copies $2 over to $1 if $2 is smaller than $1 use_smaller() { # if `$TEMP' isn't empty and it's of a smaller size than `$FILE', @@ -64,19 +105,11 @@ use_smaller() { "$TEMP" \ "$FILE" - local ERR=$? - case "$ERR" in - '0') - printf 'Optimized "%s"\n' \ - "$FILE" \ - >&2 - ;; - *) - printf 'Failed to optimize "%s"!\n' \ - "$FILE" \ - >&2 - ;; - esac + if [[ $? -ne 0 ]]; then + printf 'Failed to optimize "%s"!\n' \ + "$FILE" \ + >&2 + fi fi @@ -90,16 +123,33 @@ TEMP1=$(mktemp -t "${0##*/}.XXXXXX") TEMP_FILES+=("$TEMP0" "$TEMP0") ERRORS=0 +FREED_TOTAL=0 for FILE; do rm -f -- "$TEMP0" "$TEMP1" - if ! + BEGIN_FILESIZE=$(file_size "$FILE") + + if qpdf --stream-data=uncompress -- "$FILE" "$TEMP0" && qpdf --stream-data=compress -- "$TEMP0" "$TEMP1" && use_smaller "$FILE" "$TEMP1"; then + + END_FILESIZE=$(file_size "$FILE") + FREED=$(( BEGIN_FILESIZE - END_FILESIZE )) + FREED_HR=$(hr_size "$FREED") + (( FREED_TOTAL += FREED )) + + printf '%s: freed %d bytes (%s)\n' \ + "$FILE" \ + "$FREED" \ + "$FREED_HR" + else (( ++ERRORS )) fi done +FREED_TOTAL_HR=$(hr_size "$FREED_TOTAL") +printf 'all: freed %d bytes (%s)\n' "$FREED_TOTAL" "$FREED_TOTAL_HR" + if [[ $ERRORS -gt 0 ]]; then exit 1 fi