This repository has been archived by the owner on May 4, 2023. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 1
/
qwerty.sh
executable file
·1743 lines (1427 loc) · 47.4 KB
/
qwerty.sh
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
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/bin/sh
# qwerty.sh: download, verify, and unpack files in a single command.
#
# Copyright (c) 2018-2022, R. DuPlain. All rights reserved.
# README: https://github.com/rduplain/qwerty.sh#readme
# Contact: community@qwerty.sh -- See footer for BSD 2-Clause License.
VERSION=v0.8.1-dev
usage() {
stderr "usage: curl -sSL qwerty.sh | sh -s - [OPTION...] URL [...]"
stderr " curl -sSL qwerty.sh/v0.8 | sh -s - [OPTION...] URL [...]"
stderr
stderr "harden usage with:"
stderr
stderr " curl --proto '=https' --tlsv1.2 -sSf https://qwerty.sh | sh -s -"
stderr
stderr "using a checksum:"
stderr
stderr " URL A file to download."
stderr
stderr " --sha224=..."
stderr " --sha256=..."
stderr " --sha384=..."
stderr " --sha512=..."
stderr
stderr " --md5=... (weak)"
stderr " --sha1=... (weak)"
stderr
stderr " --skip-rej Skip writing .rej file on failure."
stderr
stderr "using git:"
stderr
stderr " ... URL"
stderr " ... URL <file>..."
stderr " ... URL <repo_file>:<local_file>..."
stderr
stderr " URL A repository."
stderr " file Download file within repository."
stderr " repo_file:local_file Download file to this local path."
stderr
stderr " -b, --ref=REF, --tag=TAG Clone repository at this reference."
stderr " Option --ref is useful when a ref is"
stderr " untagged and not HEAD of a branch;"
stderr " --ref clones the full repo history"
stderr " and is more download-intensive."
stderr " -f, --force Force overwriting files."
stderr " --when-missing When used with --force, only clone"
stderr " repository when one or more files"
stderr " are missing on the local system."
stderr " -k, --keep Keep the .git directory after clone."
stderr " Note: -b, --tag have shallow clones."
stderr
stderr "using a run-command (rc) file:"
stderr
stderr " --rc=FILE File containing qwerty.sh arguments."
stderr " Each line in the file is treated as"
stderr " arguments to a qwerty.sh call;"
stderr " multiple rc files supported."
stderr " --cd-on-rc Change directories to that of rc file"
stderr " when processing its commands."
stderr
stderr "output options:"
stderr
stderr " -o, --output=FILEPATH Download to this location."
stderr " --chmod=MODE Change mode of downloaded file(s)."
stderr
stderr "general options:"
stderr
stderr " -h, --help Display this help message."
stderr " -V, --version Display '$PROG $VERSION' to stdout."
stderr
stderr "event hooks:"
stderr
stderr " --on-start=COMMAND Run command on start."
stderr " --on-match=COMMAND Run command after conditions match."
stderr " --on-download=COMMAND Run command after downloading."
stderr " --on-output=COMMAND Run command after writing output."
stderr " --on-finish=COMMAND Run command on finish."
stderr
stderr "conditional execution:"
stderr
stderr ' --arch=ARCHITECTURE Run only if `uname -m` matches.'
stderr ' --sys=OPERATING_SYSTEM Run only if `uname -s` matches.'
stderr " --when=COMMAND Run only if COMMAND is successful."
stderr
stderr " --all-sub-arch Support partial --arch matches."
stderr
stderr '`sh -s -` sends all arguments which follow to the stdin script.'
}
main() {
reset
set_traps
determine_program_name "$@"
parse_arguments "$@"
on_start
if ! platform_matches; then
clear_traps
return
fi
on_match
if using_rc; then
run_commands
elif using_checksum; then
if ! valid_download_exists; then
given curl openssl
create_temp_dir
download
checksums_or_rej
on_download
write_download_output
on_output
fi
else
given git
create_temp_dir
if validate_filepaths_before_clone; then
clone
on_download
validate_filepaths_after_clone
prepare_clone_output
write_clone_output
on_output
fi
fi
remove_temp_dir
clear_traps
on_finish
}
### Global variables ###
# Exit immediately if a command error or non-zero return occurs.
set -e
# Ensure execution continues if variables are unset.
set +u
reset() {
# Reset global variables.
# Global runtime configuration variables:
PROG=qwerty.sh # Name of program.
BASEPROG="$PROG" # Static identifier for use in temporary names.
TEMP_DIR= # Path to program's temporary directory.
WORKING_DIR="$PWD" # Path to program's working directory.
# Checksum runtime configuration variable:
DOWNLOAD= # Temporary path of downloaded file.
# Clone runtime configuration variables:
CLONE_FILEPATH= # Temporary path of cloned repository.
CLONE_FULL= # Clone full repository (when needed by revision).
CLONE_PREPARED= # Temporary path of output prepared from clone.
CLONE_STDOUT= # Temporary path of file to send to stdout.
# Variables parsed from command line:
ALL_SUB_ARCH= # Support partial --arch matches.
ARCH= # Run only if `uname -m` matches one of these.
ARGUMENTS= # Additional positional arguments.
CD_ON_RC= # Change directories to rc file when processing it.
CHMOD= # Mode invocation for chmod of downloaded file.
CLONE_REVISION= # Branch, reference, or tag to clone.
FORCE= # Force overwriting files (default in checksum mode).
KEEP= # Keep the .git directory after clone.
ON_DOWNLOAD= # Event hook commands to run on download.
ON_FINISH= # Event hook commands to run on finish.
ON_MATCH= # Event hook commands to run on match.
ON_OUTPUT= # Event hook commands to run on output.
ON_START= # Event hook commands to run on start.
OUTPUT= # Destination of downloaded file(s) once verified.
RC= # Run-command (rc) file(s) for batch-style qwerty.sh.
SKIP_REJ= # Skip writing .rej file on failure.
SYS= # Run only if `uname -s` matches one of these.
URL= # URL of target download.
WHEN= # Run only if one of these commands is successful.
WHEN_MISSING= # With FORCE, only clone when missing local files.
# Checksum values, parsed from command line:
MD5=
SHA1=
SHA224=
SHA256=
SHA384=
SHA512=
# Behavior overrides:
QWERTY_SH_USE_REF="${QWERTY_SH_USE_REF-}"
# Dynamic global variable to support white-label qwerty.sh invocation:
QWERTY_SH_PROG="${QWERTY_SH_PROG-}"
# Path of working directory at program start.
QWERTY_SH_PWD="${QWERTY_SH_PWD-$PWD}"
}
pack_arguments() {
# Print packed data of values parsed from command line, for validation.
#
# Keep in sync with list (above) of variables parsed from command line.
# Note that conditional execution options are omitted; they always apply.
printf %s \
"$URL$ARGUMENTS" \
"$MD5$SHA1$SHA224$SHA256$SHA384$SHA512" \
"$CD_ON_RC$CHMOD$CLONE_REVISION$FORCE$KEEP$OUTPUT$RC$SKIP_REJ" \
"$WHEN_MISSING" \
"$ON_DOWNLOAD$ON_FINISH$ON_MATCH$ON_OUTPUT$ON_START"
}
### Shell Cookbook: General utilities without global variables ###
## Utilities to verify external dependencies ##
given() {
# Check that the given commands exist.
for command in "$@"; do
if ! which "$command" > /dev/null; then
if exists "$PROG"; then
stderr "$PROG: cannot find required program: $command"
else
stderr "cannot find required program: $command"
fi
return 3
fi
done
}
## Checksum ##
checksum() {
# Verify checksum of file, exiting non-zero if hash does not match.
if [ $# -ne 3 ]; then
stderr "usage: checksum FILENAME sha1|sha256|... HASH"
return 2
fi
filepath="$1"
hash_algorithm="$2"
hash_value="$3"
shift 3
case "$hash_algorithm" in
"md5" | "sha1" | "sha224" | "sha256" | "sha384" | "sha512")
dgst_value=$(openssl_dgst "$filepath" $hash_algorithm) || return $?
# Print a legible standalone section of checksum values to stderr.
case "$hash_algorithm" in
"md5")
pad="----"
;;
"sha1")
pad="---"
;;
*)
pad="-"
;;
esac
stderr "--- $hash_algorithm $pad$(repleat "-" $dgst_value)"
stderr "Expected: $hash_value"
if [ "$hash_value" = "$dgst_value" ]; then
stderr "$(green Downloaded): $dgst_value"
else
stderr "$(red Downloaded): $dgst_value"
fi
stderr "------------$(repleat "-" $dgst_value)"
if [ "$hash_value" != "$dgst_value" ]; then
stderr "Error: $hash_algorithm mismatch."
return 1
fi
# Success. Provide suggestion to upgrade on weaker algorithms.
case "$hash_algorithm" in
"md5" | "sha1")
stderr "$(yellow "Using $hash_algorithm. Next time use:")"
stderr
stderr " --sha256=$(openssl_dgst "$filepath" sha256)"
stderr
stderr "... assuming no $hash_algorithm collision."
;;
esac
;;
* )
stderr "checksum: unknown hash algorithm: $hash_algorithm"
return 2
;;
esac
}
openssl_dgst() {
# Print openssl digest value of file checksum to stdout.
#
# Unlike `checksum`, this does not validate selection of given algorithm.
given openssl
if [ $# -ne 2 ]; then
stderr "usage: openssl_dgst FILENAME sha1|sha256|..."
return 2
fi
filepath="$1"
hash_algorithm="$2"
shift 2
dgst_output=$(openssl dgst -$hash_algorithm "$filepath")
dgst_exit=$?
if [ $dgst_exit -ne 0 ]; then
stderr "openssl dgst failed with non-zero status: $dgst_exit"
return $dgst_exit
fi
# Parse checksum output and trim spaces.
dgst_value=$(printf %s "$dgst_output" | awk -F= '{ print $2 }')
dgst_value=$(printf %s "$dgst_value" | tr -d "[:space:]")
if ! exists "$dgst_value"; then
stderr "Unable to parse hash value from openssl dgst call."
return 3
fi
printf %s $dgst_value
}
## Shell language improvements ##
contains() {
# Check whether first argument exists in remaining arguments.
#
# Example:
#
# contains "/" "foo/bar/"
match="$1"
shift
case "$*" in *"$match"*) return 0;; esac; return 1
}
endswith() {
# Check whether first argument exists at the end of remaining arguments.
#
# Example:
#
# endswith "bar/" "/foo/bar/"
substr="$1"
shift
case "$*" in *"$substr") return 0;; esac; return 1
}
exists() {
# Check whether argument is not empty, i.e. test whether a variable exists.
#
# Example:
#
# exists "$VAR"
[ _"$*" != _ ]
}
lower() {
# Print argument to stdout, converting uppercase letters to lowercase.
echo "$@" | tr "[:upper:]" "[:lower:]"
}
quote_arguments() {
# Output argument array to stdout in a format for saving.
#
# The argument array can include newlines and ' quotes.
# This:
#
# foo
# bar'baz
# one two
#
# ... is saved as:
#
# 'foo' \
# 'bar'\''baz' \
# 'one two' \
#
#
# ... where the final line above has whitespace to continue the
# previous/final backslash without effect (according to sh grammar).
#
# Formatting a string with these quoted arguments allows that string to be
# saved as a variable which can then be passed to shell's builtin `set`
# which parses the variable as though its contents were passed on the
# command line verbatim.
#
# Example:
#
# ARGUMENTS=$(quote_arguments "$@") # Save "$@".
# eval "set -- $ARGUMENTS" # Load "$@".
for arg in "$@"; do
quote_argument "$arg"
done
# Close array. See function comment block above.
echo " "
}
quote_argument() {
# Output argument within array to stdout in a format for saving.
#
# See `quote_arguments`.
# Quoted argument.
# | Output line continuation \, escaped twice.
# | | Newline, escaped twice.
printf "%s \\\\\\n" "$(quote "$@")"
}
quote() {
# Output argument wrapped in ' quotes, to stdout.
printf %s\\n "$@" | \
# Replace ' characters with '\''.
# | Output \ (for \'), escaped twice.
# | Insert leading '.
# | | Append trailing '.
sed "s/'/'\\\\''/g; 1s/^/'/; \$s/\$/'/"
}
startswith() {
# Check whether first argument exists at the start of remaining arguments.
#
# Example:
#
# startswith "/foo" "/foo/bar/"
substr="$1"
shift
case "$*" in "$substr"*) return 0;; esac; return 1
}
## Utilities for standard I/O ##
stdout() {
# Echo all arguments to stdout.
#
# Provided for parity with stderr function.
echo "$@"
}
stderr() {
# Echo all arguments to stderr.
#
# Be sure to return/exit with an error code if applicable, after calling.
echo "$@" >&2
}
stdout_isatty() {
# Check whether stdout is open and refers to a terminal.
[ "$ISATTY" = "true" ] || [ -t 1 ]
}
stderr_isatty() {
# Check whether stderr is open and refers to a terminal.
[ "$ISATTY" = "true" ] || [ -t 2 ]
}
repleat() {
# Echo repeat replacement character for the width of given value.
replacement="$1"
shift
echo "$@" | tr "[:print:]" "$replacement"
}
colorize() {
# Print bold line to stdout with given color code if stdout is a terminal.
color="$1"
shift
if stderr_isatty; then
printf "\033[1;${color}m%s\033[0m\n" "$*"
else
echo "$*"
fi
}
blue() {
# Print line to stdout, in blue, if stderr is a terminal.
colorize 34 "$@"
}
green() {
# Print line to stdout, in green, if stderr is a terminal.
colorize 32 "$@"
}
yellow() {
# Print line to stdout, in yellow, if stderr is a terminal.
colorize 33 "$@"
}
red() {
# Print line to stdout, in red, if stderr is a terminal.
colorize 31 "$@"
}
## Utilities for file I/O ##
files_exist() {
# Check whether given directory contains files or directories.
exists "$(find "$@" -mindepth 1 -maxdepth 1)"
}
isabs() {
# Check whether a path is absolute.
case "$*" in /*) return 0;; esac; return 1
}
iterate_files() {
# Iterate all files at given location, including subdirectories.
#
# Load filepaths into an argument array as in `quote_arguments` as to allow
# shell functions to access files without having to handle quoting or
# escaping of filepaths.
#
# Example:
#
# eval "set -- $(iterate_files /tmp/foo)" # Access files with "$@".
path="$1"
exists "$path" || path=.
# Find all files (-type f) or (-o) symlinks (-type l) found within $path.
#
# The `find` command allows `-exec` to execute a subprocess on each found
# result, and allows for arbitrarily many -exec calls (delimited with \;),
# which `find` calls in order.
#
# Format an output in the `quote_arguments` format (see its docstring and
# example) using printf and sed.
#
# Three execs, 1 2 3,
# through comments, one can see,
# which inline, cannot be.
#
# Use a `sh -c` subprocess to support inner printf|sed pipeline.
# | Output leading '.
# -exec 2 | Terminate -exec with \;.
# | -exec 1 | Continue find invocation to next line.
# | | 1 | Path {} from find, wrapped in escaped " quotes.
# | | | 1 | Start sed command.
# | | | | 2 | Replace ' characters with '\''.
# | | | | | 2 | Output \ (for \'),
# | | | | | | 2 escaped three times.
# | | | | | | | | End sed command.
# | 1 1 1 | | | | |
# 2 | | | 2 2 2 2 2
# | | | | | | | | |
find "$path" \( -type l -o -type f \) \
-exec printf "'" \; \
-exec sh -c "printf %s \"{}\" | sed \"s/'/'\\\\\\''/g;\"" \; \
-exec printf "' \\\\\\n" \;
# | | |
# -exec 3 3 3
# | | |
# | | Newline, escaped twice.
# | Output line continuation \, escaped twice.
# Output trailing '.
# Close array. Continue final backslash without effect, using whitespace.
echo " "
}
join_path() {
# Join two paths, inserting '/' as needed, and output to stdout.
#
# Use only the second path if it is absolute.
if [ $# -ne 2 ]; then
stderr "usage: join_path PATH1 PATH2"
return 2
fi
if isabs "$2"; then
echo "$2"
else
if endswith "/" "$1"; then
echo "$1$2"
else
echo "$1/$2"
fi
fi
}
merge_directories() {
# Merge directories by moving files from source to destination directory.
#
# This operation retains the tree structure of the source directory,
# writing files to their matching directory in the destination, while
# retaining files and directories in the destination which do not exist in
# the source directory.
if [ $# -ne 2 ]; then
stderr "usage: merge_directories SOURCE DESTINATION"
return 2
fi
src="$1"
dst="$2"
shift 2
pwd="$PWD"
src_abs="$(cd "$src" && pwd)"
dst_abs="$(cd "$dst" && pwd)"
cd "$src_abs"
eval "set -- $(iterate_files .)"
cd "$dst_abs"
for file in "$@"; do
file="$(strip_rel "$file")"
src_file="$(join_path "$src_abs" "$file")"
dst_file="$(join_path "$dst" "$file")"
dst_file="$(strip_rel "$dst_file")"
stderr "$dst_file"
mkdirs "$(dirname "$dst_file")"
mv "$src_file" "$dst_file"
done
cd "$pwd"
}
mkdirs() {
# Make a directory, making all parent directories in the process.
#
# While `mkdir -p` is useful, this allows invocation with variables which
# may result in empty invocation.
#
# Example:
#
# mkdirs "$(dirname "$VAR")"
for dir in "$@"; do
mkdir -p "$dir"
done
}
strip_rel() {
# Output given path, stripped of leading './' if found.
if startswith "./" "$*"; then
printf %s "$*" | cut -c 3-
else
echo "$@"
fi
}
### Tasks and utilities which use global variables ###
## Tasks in determining whether system matches conditions for execution ##
platform_matches() {
# Check whether local system matches given execution conditions.
if ! exists "$ARCH$SYS$WHEN"; then
# No conditions given.
return
fi
platform_matches_fail=
# Begin composing status line to stderr with each condition tested.
printf %s "$PROG: conditional execution: " >&2
if exists "$ALL_SUB_ARCH"; then
printf %s "--all-sub-arch " >&2
fi
eval "set -- $ARCH"
arch_match=
arch_hint=
for arch in $@; do
match=$(lower "$arch")
found=$(lower "$(uname -m)")
if exists "$ALL_SUB_ARCH" && startswith "$match" "$found"; then
arch_match="$arch"
arch_hint="$(uname -m)"
printf %s "$(green --arch=$arch) " >&2
elif [ "$match" = "$found" ]; then
arch_match="$arch"
printf %s "$(green --arch=$arch) " >&2
else
printf %s "--arch=$arch " >&2
fi
done
eval "set -- $SYS"
sys_match=
for sys in $@; do
match=$(lower "$sys")
found=$(lower "$(uname -s)")
if [ "$match" = "$found" ]; then
sys_match="$sys"
printf %s "$(green --sys=$sys) " >&2
else
printf %s "--sys=$sys " >&2
fi
done
eval "set -- $WHEN"
when_match=
for when in "$@"; do
if ! exists "$when_match" && eval "$when" > /dev/null 2>&1; then
when_match="$when"
printf %s "$(green --when=\'$when\') " >&2
else
printf %s "--when='$when' " >&2
fi
done
stderr
if exists "$ARCH"; then
if exists "$arch_match"; then
if exists "$arch_hint"; then
stderr "Architecture matches $arch_match: $(green $arch_hint)."
else
stderr "Architecture matches $(green $arch_match)."
fi
else
stderr "Architecture does not match."
platform_matches_fail=true
fi
fi
if exists "$SYS"; then
if exists "$sys_match"; then
stderr "System matches $(green $sys_match)."
else
stderr "System does not match."
platform_matches_fail=true
fi
fi
if exists "$WHEN"; then
if exists "$when_match"; then
stderr "Matches 'when' condition: '$(green "$when_match")'."
else
stderr "Does not match a 'when' command."
platform_matches_fail=true
fi
fi
if exists "$platform_matches_fail"; then
stderr "Platform does not match. Skipping ..."
return 1
else
stderr "$(green Platform matches. Proceeding ...)"
fi
}
## Tasks when using run-command (rc) files ##
read_run_command_file() {
# Print preprocessed lines to stdout for `while read line`.
if [ $# -ne 1 ]; then
stderr "usage: read_run_command_file FILENAME"
return 2
fi
file="$1"
shift
if [ ! -e "$file" ]; then
stderr "$PROG: no such run-command file: $file"
return 1
fi
# Ultimately, each line in the run-command file is sent to the
# shell-builtin `read` in order to parse as shell arguments while
# supporting comments and line continuations.
#
# Preprocess lines to preserve backslashes, '\' to '\\'.
# This is especially important in supporting arguments with spaces.
#
# Then, revert any line-continuation so that `read` correctly constructs a
# single line from the continuation.
sed 's,\\,\\\\,g' "$file" | \
sed 's,\\\\[[:space:]]*$,\\,g'
}
run_commands() {
# Run commands listed in run-command (rc) file(s).
eval "set -- $RC"
if exists "$cd_on_rc$CD_ON_RC"; then
cd_on_rc=true
fi
for rc_file in $@; do
cd "$QWERTY_SH_PWD"
rc_filepath="$PWD"/"$rc_file"
if exists "$cd_on_rc"; then
cd "$(dirname "$rc_file")"
rc_filepath="$PWD"/"$(basename "$rc_file")"
WORKING_DIR="$PWD"
fi
if [ ! -e "$rc_filepath" ]; then
stderr "$PROG: no such run-command file: $rc_file"
return 1
fi
read_run_command_file "$rc_filepath" | while read line; do
eval "set -- $line"
if [ $# -gt 0 ]; then
stderr "--- $(blue "$rc_file"): $line"
main "$@"
fi
done
done
}
## Tasks when using checksum ##
valid_download_exists() {
# Check whether the download output exists and has a valid checksum.
! exists "$OUTPUT" && return 1 # No output specified.
[ -e "$OUTPUT" ] || return 1 # No output file exists.
if checksums "$OUTPUT"; then
stderr "Output already exists and is valid: $(green $OUTPUT)"
return 0
else
status=$?
stderr "Output already exists but is not valid: $(red $OUTPUT)"
return $status
fi
}
download() {
# Download file at URL to DOWNLOAD.
DOWNLOAD="$TEMP_DIR"/$BASEPROG.download
if [ -d "$URL" ]; then
stderr "error: $PROG cannot target directories."
return 2
elif [ -e "$URL" ]; then
download_file
else
download_url
fi
}
download_file() {
# "Download" a file.
stderr "Copying file at $URL ..."
cp -p "$URL" "$DOWNLOAD"
}
download_url() {
# Download a URL, passing optional QWERTY_CURL_FLAGS from environment.
#
# Example usage from command line:
#
# curl ... qwerty.sh | QWERTY_CURL_FLAGS="-v" sh -s - ...
given curl
report="--- $(blue $PROG)\n"
report="${report}Location:\t%{url_effective}\n"
report="${report}Content-Type:\t%{content_type}\n"
report="${report}Content-Length:\t%{size_download}\n"
curl -SL -o "$DOWNLOAD" -w "$report" $QWERTY_CURL_FLAGS "$URL" >&2
}
checksums_or_rej() {
# Check all specified checksum values, or write .rej file.
if checksums; then
return 0
else
status=$?
fi
if ! exists "$SKIP_REJ"; then
if ! exists "$OUTPUT"; then
output_rej="stdout.rej"
else
output_rej="$OUTPUT.rej"
fi
stderr "Rejecting download: $(red $output_rej)"
mkdirs "$(dirname "$output_rej")"
mv "$DOWNLOAD" "$output_rej"
fi
return $status
}
checksums() {
# Check all specified checksum values.
if exists "$MD5"; then
checksum "${1:-$DOWNLOAD}" md5 "$MD5" || return $?
fi
if exists "$SHA1"; then
checksum "${1:-$DOWNLOAD}" sha1 "$SHA1" || return $?
fi
if exists "$SHA224"; then
checksum "${1:-$DOWNLOAD}" sha224 "$SHA224" || return $?
fi
if exists "$SHA256"; then
checksum "${1:-$DOWNLOAD}" sha256 "$SHA256" || return $?
fi
if exists "$SHA384"; then
checksum "${1:-$DOWNLOAD}" sha384 "$SHA384" || return $?
fi
if exists "$SHA512"; then
checksum "${1:-$DOWNLOAD}" sha512 "$SHA512" || return $?
fi
}
write_download_output() {
# Write download to output file according to context.
cd "$QWERTY_SH_PWD"
if exists "$OUTPUT"; then
stderr "Download is valid. Writing to $(green $OUTPUT)."
mkdirs "$(dirname "$OUTPUT")"
cp -p "$DOWNLOAD" "$OUTPUT"
if exists "$CHMOD"; then
chmod "$CHMOD" "$OUTPUT"
fi
elif ! stdout_isatty; then
stderr "Download is valid. Writing to pipeline on $(green stdout)."
stderr
cat "$DOWNLOAD"
else
stderr "No command pipeline or output specified. Waiting for Godot."
fi
}
## Tasks when cloning a repository ##
local_filepath() {
# Output the full filepath a target local file, according to context.