/
imageOptimBashLib
349 lines (296 loc) · 10.9 KB
/
imageOptimBashLib
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
#!/bin/bash
# Copyright © 2013 Jamie Mason, @GotNoSugarBaby,
# https://github.com/JamieMason
# Permission is hereby granted, free of charge, to any person
# obtaining a copy of this software and associated documentation files
# (the "Software"), to deal in the Software without restriction,
# including without limitation the rights to use, copy, modify, merge,
# publish, distribute, sublicense, and/or sell copies of the Software,
# and to permit persons to whom the Software is furnished to do so,
# subject to the following conditions:
# The above copyright notice and this permission notice shall be
# included in all copies or substantial portions of the Software.
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
# EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
# MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
# NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS
# BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN
# ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
# CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
# SOFTWARE.
# ------------------------------------
# DEFAULT / ENVIRONMENT VARIABLES
# ------------------------------------
# current version of ImageOptim-CLI from package.json
VERSION="{{version}}"
# {DirectoryPath} Absolute file system path to this shell script.
CLI_PATH="$( cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd )"
# {DirectoryPath} Absolute file system path to where this shell script was invoked from.
EXEC_PATH="$PWD"
# {FilePath} The location of our Applescript library file.
APPLESCRIPT_BIN="$CLI_PATH/imageOptimAppleScriptLib"
# {DirectoryPath} Where we'll copy all images to be processed, compared, then returned to their
# original locations.
TEMP_PATH="${TMPDIR}imageoptim-cli"
# {FilePath} A list of all images we'll be operating on.
INDEX_FILE="${TEMP_PATH}/index.txt"
# {FilePath[]} The original locations of every image to be processed.
INDEX_ARRAY=[]
# {Number} How many images in total being processed.
TOTAL_IMAGES=0
# {DirectoryPath|String} The optionally provided -d or --directory command line argument.
DIRECTORY_OPTION="false"
# {BooleanString} Optionally overridden with -a or --image-alpha.
USE_IMAGE_ALPHA="false"
# {BooleanString} Optionally overridden with -j or --jpeg-mini.
USE_JPEGMINI="false"
# {BooleanString} Optionally overridden with -q or --quit.
QUIT_ON_COMPLETE="false"
# {RegEx} Supported file extensions for each application.
FILE_TYPES_REGEX_IMAGE_ALPHA=".*(png)$"
FILE_TYPES_REGEX_IMAGE_OPTIM=".*(bmp|gif|jpeg|jpg|pcx|png|pnm|tga|tiff)$"
FILE_TYPES_REGEX_JPEGMINI=".*(jpg|jpeg)$"
# {FilePath} Location of pngquant executable within ImageAlpha.
PNGQUANT_PATH="/Applications/ImageAlpha.app/Contents/Resources/pngquant"
# {FilePath} Location of executable within ImageOptim.
IMAGEOPTIM_BIN_PATH="/Applications/ImageOptim.app/Contents/MacOS/ImageOptim"
# {String} The OS X file names for each Application.
APP_FILENAME_IMAGE_ALPHA="ImageAlpha.app"
APP_FILENAME_IMAGE_OPTIM="ImageOptim.app"
APP_FILENAME_JPEGMINI="JPEGmini.app"
# {String} The OS X Bundle IDs for each Application.
APP_BUNDLE_ID_IMAGE_ALPHA="net.pornel.ImageAlpha"
APP_BUNDLE_ID_IMAGE_OPTIM="net.pornel.ImageOptim"
APP_BUNDLE_ID_JPEGMINI="com.icvt.JPEGmini"
APP_BUNDLE_ID_JPEGMINI_LITE="com.icvt.JPEGmini-lite"
APP_BUNDLE_ID_JPEGMINI_RETAIL="com.icvt.JPEGmini-retail"
# {BooleanString} Whether each Application is installed, these will be set to true accordingly
# during initialisation.
HAS_IMAGE_ALPHA="false"
HAS_IMAGE_OPTIM="false"
HAS_JPEGMINI="false"
HAS_JPEGMINI_LITE="false"
HAS_JPEGMINI_RETAIL="false"
# {BooleanString} Whether GUI Scripting is enabled, which is needed to robotically control OS X in
# order to automate JPEGmini, which offers no command line access. This will be set to true
# accordingly during initialisation.
HAS_GUI_SCRIPT="false"
# ------------------------------------
# LOGGING UTILS
# ------------------------------------
# Display a red error message and quit
# param {String} $1 message
function fatal {
printf "\e[31m✘ $1"
echo "\033[0m"
exit 1
}
# Display a message in green with a tick by it
# param {String} $1 message
function success {
printf "\e[32m✔ $1"
echo "\033[0m"
}
# Display usage information
function usage {
{{usage}}
}
# Display usage examples
function examples {
{{examples}}
}
# ------------------------------------
# DETERMINE WHAT EXISTS AT A GIVEN LOCATION
# ------------------------------------
# State whether the entity at path is a "file", "directory", or "other".
# param {EntityPath} $1 entity
# return {String} file_type
function get_entity_type {
if [ -f "$1" ]; then
echo "file"
elif [ -d "$1" ]; then
echo "directory"
else
echo "other"
fi
}
# State whether the entity at path is a "png", "jpg", "other", or "unsupported" image file.
# param {EntityPath} $1 entity
# return {String} image_type
function get_image_type {
shopt -s nocasematch
if [[ "$1" =~ $FILE_TYPES_REGEX_IMAGE_ALPHA ]]; then
echo "png"
elif [[ "$1" =~ $FILE_TYPES_REGEX_JPEGMINI ]]; then
echo "jpg"
elif [[ "$1" =~ $FILE_TYPES_REGEX_IMAGE_OPTIM ]]; then
echo "other"
else
echo "unsupported"
fi
shopt -u nocasematch
}
# ------------------------------------
# GATHER PATHS TO IMAGES
# ------------------------------------
# Add file received via stdin to our index file.
# param {FilePath} $1 file
function add_file_to_index {
local image_type=$(get_image_type "$1")
if [ $image_type != "unsupported" ]; then
echo "$1" >> $INDEX_FILE
else
echo "Ignored as an unsupported file type: $LINE"
fi
}
# Add all files in a directory to our index file.
# param {DirectoryPath} $1 directory
function add_directory_to_index {
find -E "$1" -iregex $FILE_TYPES_REGEX_IMAGE_OPTIM -type f -print0 | while read -d '' -r file; do
add_file_to_index "$file"
done
}
# Read files received via stdin into an index which will outlive the LINE variable.
function add_stdin_to_index {
if ! [ -t 0 ]; then
while read LINE; do
echo 33
local entity_type=$(get_entity_type "$LINE")
if [ $entity_type == "file" ]; then
add_file_to_index "$LINE"
elif [ $entity_type == "directory" ]; then
add_directory_to_index "$LINE"
else
echo "Ignored as neither file or directory: $LINE"
fi
done
fi
}
# If -d or --directory were supplied, add the contents of that directory to our processing index.
function add_directory_option_to_index {
if [ "$DIRECTORY_OPTION" != "false" ]; then
if [ -d "$DIRECTORY_OPTION" ]; then
add_directory_to_index "$DIRECTORY_OPTION"
else
echo "Value for --directory is not a directory: $LINE"
fi
fi
}
# Remove any duplicate files in our index, which may have occurred when importing directories whose
# images have already been gathered by other means.
function remove_duplicate_indexes {
sort -f "$INDEX_FILE" | uniq > "$INDEX_FILE.uniq.txt"
mv "$INDEX_FILE.uniq.txt" "$INDEX_FILE"
}
# Read our index file into an Array.
function parse_index {
IFS=$'\n' read -d '' -r -a INDEX_ARRAY < "$INDEX_FILE"
TOTAL_IMAGES=${#INDEX_ARRAY[@]}
}
# Construct a clean Array containing sorted, unique paths to every image we should process.
function gather_paths_to_images {
add_stdin_to_index
add_directory_option_to_index
remove_duplicate_indexes
parse_index
}
# ------------------------------------
# PREPARE A TEMPORARY DIRECTORY
# ------------------------------------
# Automating JPEGmini is particularily difficult and unusably slow when working with arbitrary sets
# of files. Instead, we create a temporary directory and pass that once to JPEGmini rather than
# each file individually.
function init_temp_directory {
rm -rf "$TEMP_PATH"
mkdir -p "$TEMP_PATH"
chmod 777 "$TEMP_PATH"
}
# Determine the location in our temp directory a given file should be held at.
# param {FilePath} $1 file
# return {FilePath} temp_file
function get_temp_path_for_file {
local image_type=$(get_image_type "$1")
echo "${TEMP_PATH}/${image_type}$1"
}
# Copy all files received over stdin to a temp directory, grouped by file extension.
function populate_temp_directories {
local image_type
local temp_file
for source_file in "${INDEX_ARRAY[@]}"; do
image_type=$(get_image_type "$source_file")
temp_file=$(get_temp_path_for_file "$source_file")
if [[ $image_type != "unsupported" ]]; then
ditto "$source_file" "$temp_file"
fi
done
}
# Gather paths to all images we should process and prepare a temporary directory containing copies.
function prepare_images {
gather_paths_to_images
if [ $TOTAL_IMAGES -gt 0 ]; then
populate_temp_directories
fi
}
# ------------------------------------
# INSPECT IMAGE APPLICATIONS
# ------------------------------------
# Use an Application's bundle id to locate the path to the installed Application.
# param {String} $1 app_bundle_id
# return {String} $1 path_to_app
function get_path_to_app_by_bundle_id {
echo `osascript "$APPLESCRIPT_BIN" has_app_installed "$1"`
}
# Is an Application at path_to_app with the expected app_bundle_id installed on this machine?
# param {String} $1 path_to_app
# param {String} $2 app_bundle_id
# return {BooleanString}
function has_app {
local expected_app_name="$1"
local actual_app_name=$(get_path_to_app_by_bundle_id "$2")
if [ $actual_app_name == $expected_app_name ]; then
echo "true"
else
echo "false"
fi
}
# Determine whether GUI Scripting is enabled, which is needed to automate JPEGmini.
function has_gui_script {
echo `osascript "$APPLESCRIPT_BIN" has_gui_script`
}
# ------------------------------------
# INVOKE IMAGE APPLICATIONS
# ------------------------------------
function run_image_alpha {
if [ "true" == $USE_IMAGE_ALPHA ]; then
if [ "true" == $HAS_IMAGE_ALPHA ]; then
find "${TEMP_PATH}/png" -type f -print0 | xargs -n10 -P8 -0 \
$PNGQUANT_PATH --ext=.png --force --speed=1 --quality=75-100 --
else
fatal "ImageAlpha is not installed (http://pngmini.com)"
fi
fi
}
function run_jpegmini {
if [ "true" == $USE_JPEGMINI ]; then
if [ "true" == $HAS_JPEGMINI ] || [ "true" == $HAS_JPEGMINI_RETAIL ]; then
if [ "true" == $HAS_GUI_SCRIPT ]; then
`osascript "$APPLESCRIPT_BIN" run_jpegmini "${TEMP_PATH}/jpg" JPEGmini` > /dev/null 2>&1
sleep 1
`osascript "$APPLESCRIPT_BIN" wait_for JPEGmini` > /dev/null 2>&1
if [ "true" == $QUIT_ON_COMPLETE ]; then
osascript -e 'tell application "JPEGmini" to quit'
fi
else
fatal "To automate JPEGmini we need to enable GUI Scripting. Check 'Enable access for \
assistive devices' under Accessibility in System Preferences, then run ImageOptim-CLI again"
fi
else
fatal "JPEGmini is not installed (https://itunes.apple.com/us/app/jpegmini/id498944723)"
fi
fi
}
function run_image_optim {
if [ "true" == $HAS_IMAGE_OPTIM ]; then
$IMAGEOPTIM_BIN_PATH 2>/dev/null "$TEMP_PATH"
fi
}