Avoid creating temp files until necessary

For instance, if one ran "optipdf --help" it would create and delete an
empty directory in /tmp.
This commit is contained in:
Dan Church 2023-03-27 11:02:50 -05:00
parent 18515e5794
commit 2497e27b04
Signed by: h3xx
GPG Key ID: EA2BF379CD2CDBD0
1 changed files with 13 additions and 6 deletions

19
optipdf
View File

@ -42,12 +42,6 @@ KEEP_BACKUP_SUFFIX=
FORCE_OVERWRITE=0
ENCODE_THRU_WARNINGS=0
TEMP_DIR=$(mktemp -d -t "${0##*/}.XXXXXX")
cleanup() {
rm -fr -- "$TEMP_DIR"
}
trap 'cleanup' EXIT
FILES=()
NO_MORE_FLAGS=0
for ARG; do
@ -104,6 +98,8 @@ for ARG; do
fi
done
TEMP_DIR=
if [[ ${#FILES[@]} -eq 0 ]]; then
USAGE >&2
exit 1
@ -159,6 +155,16 @@ hr_size() (
printf '%g %s\n' "$HR_VAL" "$HR_UNIT"
)
setup_tempdir() {
if [[ -z $TEMP_DIR ]]; then
TEMP_DIR=$(mktemp -d -t "${0##*/}.XXXXXX")
cleanup() {
rm -fr -- "$TEMP_DIR"
}
trap 'cleanup' EXIT
fi
}
# 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',
@ -250,6 +256,7 @@ fi
ERRORS=0
FREED_TOTAL=0
for FILE in "${FILES[@]}"; do
setup_tempdir
TEMP=$(mktemp -p "$TEMP_DIR" -t 'file.XXXXXX')
rm -f -- "$TEMP"
BEGIN_FILESIZE=$(file_size "$FILE")