-
-
Notifications
You must be signed in to change notification settings - Fork 25
/
Copy pathdown
executable file
Β·416 lines (377 loc) Β· 11.8 KB
/
down
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
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
#!/usr/bin/env bash
# @todo support these:
# https://github.com/rs/curlie
# https://github.com/ducaale/xh
# https://github.com/mihaigalos/aim
function down_() (
source "$DOROTHY/sources/bash.bash"
source "$(type -P eval-helper)"
# supported tools
# @todo probably won't require shapeshifter if [eval-helper] is wrote to make more use of [eval_capture]
local tool available_tools=() all_tools=(
wget # nice progress bar without shapeshifter
curl # nice progress bar with shapeshifter
got # nice progress bar with shapeshifter
aria2c # no useful progress bar
# httpie # writes to stdout with [eval-helper], shapeshifter doesn't fix it, [eval-helper --no-quiet] solves it, but isn't what we want
) shapeshifter_tools=(
curl
got
)
# determine which tools are available
for tool in "${all_tools[@]}"; do
if __command_exists -- "$tool"; then
available_tools+=("$tool")
fi
done
tool=''
# if no tools are available, install preference
if [[ ${#available_tools[@]} -eq 0 ]]; then
get-installer --first-success --invoke --quiet -- "${all_tools[@]}"
down "$@"
return
fi
# =====================================
# Arguments
function help {
cat <<-EOF >/dev/stderr
ABOUT:
Download a file, using the best available tool, and with the best available options.
USAGE:
down [...options] <url>
OUTPUTS:
Progress to tty.
Errors to stderr.
Downloaded filepath to stdout.
OPTIONS:
--tool=<tool>
Enforce the usage of <tool> to download the file.
If omitted, the first available preferred tool will be used.
--archive-format=<format>
Treat the download as an archive file, and enforce <format> as the extraction format.
This option is handled by the [unziptar] command.
--archive-glob=<glob>
Treat the download as an archive file, and only extract files that match the glob pattern <glob>.
This option is handled by the [unziptar] command.
--bearer-token=<token>
If provided, include this in a bearer token header.
--directory=<directory>
Place downloaded file(s) inside <directory>.
If omitted, the current working directory will be used.
--file=<file>
If only a single file was downloaded, rename it to <file>.
If multiple files were downloaded, then fail.
--filepath=<directory>/<file>
If only a single file was downloaded, rename it to <file>, and place it inside <directory>.
If multiple files were downloaded, then fail.
--retry=<retries>
How many times to retry the download.
Defaults to 2.
--[no-]quiet
Whether or not output should be simplified, defaults to enabled.
TOOLS:
The following download tools, sorted by order of preference, were determined to be available on your system:
${available_tools[*]}
EOF
if [[ $# -ne 0 ]]; then
echo-error "$@"
fi
return 22 # EINVAL 22 Invalid argument
}
# process
local item option_quiet='' url='' tool='' archive_format='' archive_glob='' directory='' file='' filepath='' retry='2' option_bearer_token='' option_progress=''
while [[ $# -ne 0 ]]; do
item="$1"
shift
case "$item" in
'--help' | '-h') help ;;
'--no-verbose'* | '--verbose'*)
option_quiet="$(get-flag-value --non-affirmative --fallback="$option_quiet" -- "$item")"
;;
'--no-quiet'* | '--quiet'*)
option_quiet="$(get-flag-value --affirmative --fallback="$option_quiet" -- "$item")"
;;
'--bearer-token='*) option_bearer_token="${item#*=}" ;;
'--tool='*) tool="${item#*=}" ;;
'--archive-format='* | '--unzip-format='*) archive_format="${item#*=}" ;;
'--archive-glob='* | '--archive-filter='* | '--unzip-glob='* | '--unzip-filter='*) archive_glob="${item#*=}" ;;
'--directory='*) directory="${item#*=}" ;;
'--file='*) file="${item#*=}" ;;
'--filepath='*) filepath="${item#*=}" ;;
'--retry='*) retry="${item#*=}" ;;
'--url='*) url="${item#*=}" ;;
'--no-progress'* | '--progress'*)
option_progress="$(get-flag-value --affirmative --fallback="$option_progress" -- "$item")"
;;
'--'*) help "An unrecognised flag was provided: $item" ;;
*)
if [[ -z $url ]]; then
url="$item"
else
help "An unrecognised argument was provided: $item"
fi
;;
esac
done
# disable progress bars if CI
if [[ -z $option_progress ]] && is-ci; then
option_progress='no'
fi
# assert url
if [[ -z $url ]]; then
help "No URL was provided."
fi
# ensure tool
if [[ -z $tool ]]; then
tool="${available_tools[0]}"
elif ! is-needle --needle="$tool" -- "${available_tools[@]}"; then
help "The specified tool is not available: $tool"
fi
# some tools need shapeshifter
local shapeshifter='no'
if is-needle --needle="$tool" -- "${shapeshifter_tools[@]}"; then
shapeshifter='yes'
fi
# ensure filepath, directory, file
if [[ -n $filepath ]]; then
# filepath is a directory + file combination
filepath="$(fs-absolute -- "$filepath")"
directory="$(dirname -- "$filepath")"
file="$(basename -- "$filepath")"
elif [[ -n $directory && -n $file ]]; then
# directory + file
filepath="$(fs-absolute -- "$directory/$file")"
directory="$(dirname -- "$filepath")"
file="$(basename -- "$filepath")"
elif [[ -z $directory && -n $file ]]; then
# file, without directory
filepath="$(pwd)/$file"
directory="$(dirname -- "$filepath")"
file="$(basename -- "$filepath")"
elif [[ -n $directory && -z $file ]]; then
# directory, without file
directory="$(fs-absolute -- "$directory")"
filepath='' # it is for dir+file combos only
else
directory="$(pwd)"
filepath='' # it is for dir+file combos only
fi
__mkdirp "$directory"
# =====================================
# Action
function act {
# if zip, then download to a temporary/random directory first, filename must be valid but keep extension for unziptar (so trim special)
local download_directory download_file
if [[ -n $archive_format || -n $archive_glob ]]; then
local url_basename
url_basename="$(basename -- "$url" | echo-trim-special --stdin)"
download_directory="$(fs-temp --directory='down' --directory --touch)"
download_file="$url_basename"
else
download_directory="$directory"
download_file="$file" # can be empty
__mkdirp "$download_directory" # fs-temp makes directory
fi
# tool helpers
function do_aria2c {
local aria2c_options=(
--dir="$download_directory"
--file-allocation=none
--allow-overwrite=true
--always-resume=true
--auto-file-renaming=false
--show-console-readout=false
--quiet # its multiline bar doesn't reset itself, just dumps more bars to stdout
--no-conf
)
if [[ -n $option_bearer_token ]]; then
aria2c_options+=(
"--header=Authorization: Bearer $option_bearer_token"
)
fi
if [[ -n $download_file ]]; then
aria2c_options+=(
--out="$download_file"
)
fi
aria2c_options+=("$url")
aria2c "${aria2c_options[@]}"
}
function do_curl {
# [--progress-bar] not as nice as default table
local curl_options=(
'-L'
)
if [[ -n $option_bearer_token ]]; then
curl_options+=(
'--header'
"Authorization: Bearer $option_bearer_token"
)
fi
if [[ -n $download_file ]]; then
curl_options+=(-o "$download_file")
else
curl_options+=(-O)
fi
curl_options+=("$url")
(
cd "$download_directory"
curl "${curl_options[@]}"
)
}
function do_got {
# https://github.com/melbahja/got#command-line-tool-usage
local got_options=()
if [[ -n $option_bearer_token ]]; then
got_options+=(
'--header'
"Authorization: Bearer $option_bearer_token"
)
fi
if [[ -n $download_file ]]; then
got_options+=(-o "$download_file")
fi
got_options+=("$url")
(
cd "$download_directory"
got "${got_options[@]}"
)
}
function do_httpie {
# https://httpie.io/docs/cli/download-mode
local http_options=(
'--download'
)
if [[ -n $option_bearer_token ]]; then
http_options+=(
'--auth'
"Bearer $option_bearer_token"
)
fi
if [[ -n $download_file ]]; then
http_options+=(
'--continue' # --continue only works with --output
'--output' "$download_file"
)
fi
http_options+=("$url")
(
cd "$download_directory"
http "${http_options[@]}"
)
}
function do_wget {
# -O, --output-document=FILE write documents to FILE
# -o, --output-file=FILE log messages to FILE
# -N, --timestamping don't re-retrieve files unless newer than local
# -c, --continue resume getting a partially-downloaded file
# -q, --quiet quiet (no output)
# -v, --verbose be verbose (this is the default)
# -nv, --no-verbose turn off verboseness, without being quiet
# --show-progress display the progress bar in any verbosity mode
# WARNING: timestamping does nothing in combination with -O. See the manual for details.
local wget_options=()
# wget on apk doesn't have the --progress option:
# https://github.com/bevry/dorothy/actions/runs/7498226466/job/20414036419#step:4:64
if [[ $option_progress == 'no' ]] || is-apk; then
wget_options+=('--no-verbose') # wget doesn't have a --progress=off or equivalent, instead this is it
else
# bar is nicer than dot, and noscroll prevents issues with our clearing
wget_options+=('--progress=bar:noscroll')
fi
if [[ -n $option_bearer_token ]]; then
wget_options+=(
"--header=Authorization: Bearer $option_bearer_token"
)
fi
if [[ -n $download_file ]]; then
wget_options+=(
"--output-document=$download_file"
)
else
wget_options+=(
'--timestamping'
)
fi
wget_options+=("$url")
(
cd "$download_directory"
wget "${wget_options[@]}"
)
}
function do_download {
if [[ "$(type -t "do_$tool")" == 'function' ]]; then
"do_$tool"
else
help "Unrecognised tool: $tool"
fi
}
# invoke the download with retry support, capturing exit codes
local download_status
while [[ $retry -ge 0 ]]; do
eval_capture --statusvar=download_status -- do_download
if [[ $download_status -eq 0 ]]; then
break
fi
retry=$((retry - 1))
done
# double confirm it was created, in case exit code passed but it still was not created
if [[ -n $download_file ]]; then
if is-missing -- "$download_directory/$download_file"; then
echo-error "Failed to download " --code="$url" ' to ' --code="$download_directory/$download_file"
return 1
fi
fi
# log
echo-style --success="Downloaded with $tool successfully!"
# if desired, perform extraction of the temporary file
if [[ -n $archive_format || -n $archive_glob ]]; then
echo-style --notice='Unzipping...'
unziptar "$download_directory/$download_file" \
--prune \
--directory="$directory" \
--file="$file" \
--filepath="$filepath" \
--format="$archive_format" \
--glob="$archive_glob"
# check extraction
if [[ -n $file ]]; then
# assert it was created
if is-missing -- "$filepath"; then
echo-error 'Failed to extract ' --code="$url" ' to ' --code="$filepath"
return 1
fi
fi
fi
# log
echo-style --success='Extracted!'
}
# messages
local pending='Downloading'
local success='Downloaded'
local failure='Failed to download'
if [[ -n $archive_format || -n $archive_glob ]]; then
pending='Downloading and extracting'
success='Downloaded and extracted'
failure='Failed to download and extract'
fi
# act
eval_helper --quiet="$option_quiet" --no-wrap --shapeshifter="$shapeshifter" \
--pending="$(
echo-style --bold="$pending " \
--code="$url" ' to ' --code="$directory/$file"
)" \
--success="$(
echo-style --success="$success " \
--code="$url" ' to ' --code="$directory/$file"
)" \
--failure="$(
echo-style --error="$failure " \
--code="$url" ' to ' --code="$directory/$file"
)" \
-- act
)
# fire if invoked standalone
if [[ $0 == "${BASH_SOURCE[0]}" ]]; then
down_ "$@"
fi