-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathsumdir
More file actions
executable file
·717 lines (657 loc) · 22.7 KB
/
Copy pathsumdir
File metadata and controls
executable file
·717 lines (657 loc) · 22.7 KB
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
#!/bin/bash
# Author: Christopher Lovejoy <c@lovejoy.io>
# Sections:
# + DOCUMENTATION
# + APPLICATION
# + PLUMBING
# + CONFIGURATION
# + EXECUTION
## DOCUMENTATION:
{
SCRIPT_NAME=sumdir
SCRIPT_VERSION=0.3.6
SCRIPT_MODIFIED=2026-09-10
SCRIPT_USAGE="${0##*/} [OPTIONS] [PATH...]"
SCRIPT_EXAMPLE_COLUMNS=(script description)
SCRIPT_EXAMPLES=()
SCRIPT_EXAMPLES+=("${SCRIPT_NAME} -r -o ./externalDrive-%d /mnt/externalDrive" "Sum files from a different location, and save output in the current directory.")
SCRIPT_PURPOSE="Coordinates the generation and output of many checksums."
HEADER_IGNORE_STATEMENT="Metadata follows file paths, separated by: "
HEADER_IGNORE_TAB_LABEL='Tab character "\t"'
showHelp() {
echo "USAGE: $SCRIPT_USAGE";
echo "PURPOSE: $SCRIPT_PURPOSE";
echo
echo "OPTIONS:";
SCRIPT_OPTIONS=(
"-h, --help, help"
" Show this help"
""
"-a CMD"
" Hashing algorithm to use. Currently supported:"
" 'sha256', 'b2', 'sha256e' (alias 'annex')."
" env: SUMDIR_ALGORITHM."
""
"-r "
" Recurse into directory. env: SUMDIR_SHOULD_RECURSE"
""
"-L "
" Dereference (follow) symlinks. env: SUMDIR_SHOULD_DEREFERENCE"
""
"-1, --single"
" Remove existing *SUM* SUMFILEs in this directory"
" (trash-cli, falls back to rm). Only this directory, even"
" with -r. env: SUMDIR_SHOULD_SINGLE_HASH_FILE"
""
"-o, --out TEMPLATE"
" Output file name template."
" See 'TEMPLATES' below for substitution patterns."
" env: SUMDIR_OUTPUT_FILE_TEMPLATE"
""
"-l "
" hostname and PWD in output SUMFILE."
" Affected by -L."
" env: SUMDIR_SHOULD_INCLUDE_LOCATION_IN_OUTPUT"
""
"-z, --tz TZ"
" Set timezone for timestamp; default 'UTC'."
" env: SUMDIR_TIMEZONE"
""
"-f, --dateformat"
" Set format for timestamp (per GNU coreutils date)."
" env: SUMDIR_DATE_FORMAT"
""
"-v, --verbose[=N] "
" Increase the detail of the info output to STDERR."
" env: SUMDIR_VERBOSE"
""
"-x, --exclude PATTERN"
" Exclude files by name, via \`find \\! -name PATTERN\`."
" env: SUMDIR_LIST_EXCLUDE_NAME"
""
"-X, --exclude-path PATTERN"
" Exclude files by name, per \`find \\! -path PATTERN\`;"
" usually of form '*PATTERN*'."
" env: SUMDIR_LIST_EXCLUDE_PATH"
""
"--length N "
" (b2sum only) Set the length of the digest hash in bits."
" Hashes appear 1/4 this length in hexadecimal"
" (e.g --length 128 yields a has 32 characters long)."
" Default and maximum is 512 (for an output 128 chars long)."
" This is the same as setting the env var SUMDIR_LIST_B2_OPTS='--length:N'."
""
"--time"
" (Only with -a sha256e) Add modified time after filename after DELIM."
""
"-d DELIM"
" (Only with -a sha256e) Set metadata separator string to DELIM."
" Defaults to '\\t' Tab character."
""
"--no-key-ref"
" (Only with -a sha256e) Treat all files the same;"
" don't look for SHA256E keys in small files."
" By default, small files containing keys have their"
" keys printed with a '*' prefix."
" Handled in ${SCRIPT_NAME} and checkdir versions +0.3.0."
""
"--"
" After this, all further arguments are passed directly to 'find'."
""
"--bk"
" Same as -f '${OPT_OUTPUT_FILE_TEMPLATE_BK}'"
""
"--version"
" Output version information"
);
local opt;
for opt in "${SCRIPT_OPTIONS[@]}"; do
echo " ${opt}"
done
echo
echo "DESCRIPTION:";
SCRIPT_DESCRIPTION_LINES=(
"If no PATH is specified, the current directory (\$PWD) is used."
""
"If no SUMFILE is specified, \$PWD/${DEFAULT_OUTPUT_FILE_TEMPLATE} is used (see TEMPLATES)."
""
"TEMPLATES"
" The following strings are substituted for dynamic values:"
" '%d' or '{}' => Datetime as formatted by -f"
" '%a' => Algorithm ('sha256', 'b2', …)"
" '%A' => Algorithm uppercase ('SHA256', 'B2', …)"
" "
""
"ENVIRONMENT VARIABLES"
" *_SHOULD_* options expect 'true' or 'false' values."
" *_LIST_* options must be colon-separated like PATH."
""
" You may set any of the options above by using the following environment variables."
" They are shown here with their default values, if available."
);
for line in "${SCRIPT_DESCRIPTION_LINES[@]}"; do
echo " ${line}"
done
for opt in "${OPT_VAR_NAMES[@]}"; do
echo -n " $(getEnvOptName "$opt")";
defaultValue="$(getValueIfDefined $(getDefaultOptName "$opt"))" \
&& echo -n "='${defaultValue}'";
echo; # newline
done
echo
echo "EXAMPLES:";
local exampleIndex=0;
local exampleColumnCount=${#SCRIPT_EXAMPLE_COLUMNS[@]};
local exampleColumnIndex=;
local exampleColumnName=;
for example in "${SCRIPT_EXAMPLES[@]}"; do
let 'exampleColumnIndex = exampleIndex % exampleColumnCount';
exampleColumnName="${SCRIPT_EXAMPLE_COLUMNS[$exampleColumnIndex]}";
if [[ 'script' == $exampleColumnName ]]; then
echo " \$ ${example}";
elif [[ 'description' == $exampleColumnName ]]; then
echo " # ${example}";
fi
let 'exampleIndex++';
done
echo
echo "${SCRIPT_NAME} version ${SCRIPT_VERSION} (${SCRIPT_MODIFIED})"
}
}
## APPLICATION:
{
main() {
local inputDirectories=() userArg;
setOptsFromEnvAndDefaults;
while [[ $# -gt 0 ]]; do
case "$1" in
--) shift; inputDirectories+=("$@"); shift $#; break;;
--bk) opt_output_file_template="$OPT_OUTPUT_FILE_TEMPLATE_BK";;
--length) opt_list_b2_opts+=(--length $2); shift;;
--no-key-refs) opt_should_handle_key_refs=false;;
--time) opt_include_time=true;;
--verbose=*) opt_verbose=${1#*=};;
-1|--single) opt_should_single_hash_file=true;;
-a) opt_algorithm="$2"; shift;;
-d) opt_column_sep="$2"; shift;;
-f|--dateformat) opt_date_format="$2"; shift;;
-h|--help|help) showHelp | less; exit;;
-L) opt_should_dereference=true;;
-l) opt_should_include_location_in_output=true;;
-o|--out) opt_output_file_template="$2"; shift;;
-r) opt_should_recurse=true;;
-vv) let opt_verbose+=2;;
-vvv) let opt_verbose+=3;;
-v|--verbose) let opt_verbose++;;
-x|--exclude) opt_list_exclude_name+=("$2"); shift;;
-X|--exclude-path) opt_list_exclude_path+=("$2"); shift;;
-z|--tz) opt_timezone="$2"; shift;;
--version)
if loglevel 1; then
echo "$(basename "$0") version ${SCRIPT_VERSION} (${SCRIPT_MODIFIED})"
else
echo "${SCRIPT_VERSION}"
fi
exit;;
*) inputDirectories+=("$1");;
esac
shift;
done
feedback 1 "(Verbose output level: ${opt_verbose})";
export opt_verbose;
initializeSumCommand;
initializeJobExecutor;
export opt_column_sep; # after initializeSumCommand, where it may be reset to empty
[[ ${#inputDirectories[@]} -eq 0 ]] && inputDirectories=("$PWD");
## LOOP THROUGH INPUT DIRECTORIES
local dStackHeight=0
local cwd="$PWD";
local outputPath;
for dir in "${inputDirectories[@]}"; do
dir="${dir%/}" # Remove trailing slash from directory paths.
while [[ $dStackHeight -gt 0 ]]; do
popd &>/dev/null \
&& let dStackHeight--;
done
if pushd "$dir" &>/dev/null; then
let dStackHeight++;
else
feedback 0 "Unable to access directory '$dir'. Skipping.";
continue;
fi
if [[ $opt_should_single_hash_file == true ]]; then
removeFilesByTemplate "$opt_output_file_template";
fi
local date="$(TZ="$opt_timezone" date "$opt_date_format")";
local outputPath="${opt_output_file_template/\{\}/$date}";
outputPath="${outputPath/\%d/$date}";
outputPath="${outputPath/\%a/$opt_algorithm}";
outputPath="${outputPath/\%A/${algoUpper}}";
if [[ $outputPath =~ / ]]; then
if [[ ${outputPath:0:1} != '/' ]]; then
outputPath="${cwd}/${outputPath}";
fi
else
outputPath="${PWD}/${outputPath}";
fi
outputFilename="$(basename "$outputPath")"
feedback 0 "Outputting to: ${outputPath}";
local findArgs=();
if [[ $opt_should_dereference == true ]]; then
findArgs+=(-L);
fi
findArgs+=(.);
if [[ $opt_should_recurse != true ]]; then
findArgs+=(-maxdepth 1);
fi
findArgs+=(-type f);
findArgs+=(\! -name "$outputFilename");
if [[ ${#opt_list_exclude_path[@]} -gt 0 ]]; then
for pattern in "${opt_list_exclude_path[@]}"; do
findArgs+=(\! -path "$pattern");
done
fi
if [[ ${#opt_list_exclude_name[@]} -gt 0 ]]; then
for pattern in "${opt_list_exclude_name[@]}"; do
findArgs+=(\! -name "$pattern");
done
fi
if [[ $opt_include_time == true ]]; then
if [[ -n $opt_column_sep ]]; then
findArgs+=(-printf '%p'"$opt_column_sep"'%TFT%TT %TZ\0');
else
findArgs+=(-printf '%p\t%TFT%TT %TZ\0');
fi
else
findArgs+=(-print0);
fi
loglevel 1 && declare -p findArgs outputPath PWD
{
echo "# Generated ${date} by ${SCRIPT_NAME} ${SCRIPT_VERSION} (called as \`${SCRIPT_NAME} $(escapeArgs "${CALL_ARGS[@]}")\`)";
if [[ -n $opt_column_sep ]]; then
local colHeader=""
colHeader+="# ${HEADER_IGNORE_STATEMENT}";
if [[ $opt_column_sep == '\t' || $opt_column_sep == $'\t' ]]; then
colHeader+="${HEADER_IGNORE_TAB_LABEL}";
else
colHeader+="$(printf %q "$opt_column_sep")";
fi
echo "$colHeader";
fi
echo "# Same as: ${sumCommand[*]} FILENAMES";
echo "# To check file integrity, run: ${checkCommand[*]} ${outputFilename}";
local dirPath;
if [[ $opt_should_include_location_in_output == true ]]; then
dirPath="${PWD}"
if [[ $opt_should_dereference == true ]]; then
dirPath="$(dereferenceSymlink "${PWD}")";
else
dirPath="${PWD}"
fi
echo "# Location: $(hostname):${dirPath}";
fi
## Removing leading `./` in paths.
#| sed -z 's/^\.\///' \ # BSD sed doesn't have `-z` (sed --version)
#| perl -pe 's/^\.\///' \ # untested @1666202382 # Pulling this convenience out for now, since it breaks compatibility.
#| perl -pe 's/(^|\x00)\.\//\1/g' \
must find "${findArgs[@]}" \
| sed -E 's/(^|\x00)\.\//\1/g' \
| "${jobExecutor[@]}" "${sumCommand[@]}";
# LATER Sort file list by path (`sort -k2`). todo.sumdir.txt#a0a942a5-d08d-469c-b572-ee8b3e8ae4ec
} > "${outputPath}";
local sumStatus=$?;
loglevel 0 && {
>&2 echo -n "Generated: ";
echo "${outputPath}"; # Output path, for scripting
}
if [[ $sumStatus != 0 ]]; then
die $sumStatus "Sum failed."$'\n'"$(declare -p sumCommand)";
fi
done
}
removeFilesByTemplate() {
local template="$1";
feedback 2 "Output filename template: ${template}";
local templateStar="${template//\{\}/*}";
templateStar="${templateStar//%d/*}";
templateStar="${templateStar//%a/$opt_algorithm}";
templateStar="${templateStar//%A/${algoUpper}}";
feedback 2 "Pattern for files to remove: ${templateStar}";
local IFS='*';
local templateParts=($templateStar);
local idxLastTemplatePart=$(( ${#templateParts[@]} - 1 )); # For Bash 3.2.x compatibility, rather than using index -1.
if [[ -n ${templateParts[$idxLastTemplatePart]} && $templateStar =~ \*$ ]]; then
templateParts+=("");
fi
IFS="$g_IFS";
local removeCommand=trash;
command -v "$removeCommand" &>/dev/null || removeCommand=rm;
feedback 1 "$ $removeCommand $templateStar";
case ${#templateParts[@]} in
0) feedback 1 "No non-wildcard part of name template to glob by, for removing previous output sum files."; return 1;;
1) feedback 2 "No wildcards in template. Searching for literal name"; $removeCommand "${templateParts[0]}";;
2) $removeCommand "${templateParts[0]}"*"${templateParts[1]}";;
3) $removeCommand "${templateParts[0]}"*"${templateParts[1]}"*"${templateParts[2]}";;
4) $removeCommand "${templateParts[0]}"*"${templateParts[1]}"*"${templateParts[2]}"*"${templateParts[3]}";;
esac
}
initializeSumCommand() {
# Not `local`: setting in caller context.
sumCommand=();
checkCommand=();
jobExecutor=();
algoUpper='';
case "$(echo -n "$opt_algorithm" | toLowerCase)" in
sha256e|*annex) opt_algorithm=sha256e;
if ! command -v sha256sum &>/dev/null; then
die 1 "Missing checksum software: sha256sum or shasum.";
fi
sumCommand=(sumSHA256E);
[[ $opt_should_handle_key_refs == false ]] && sumCommand+=(--no-key-refs);
checkCommand=(checkdir);
;;
sha*) opt_algorithm=sha256;
if ! command -v sha256sum &>/dev/null; then
die 1 "Missing checksum software: sha256sum or shasum.";
fi
sumCommand=(sha256sum);
checkCommand=("${sumCommand[@]}" -c);
if [[ ${#opt_list_sha_opts[@]} -gt 0 ]]; then
sumCommand+=("${opt_list_sha_opts[@]}");
fi
;;
b2*|blake*) opt_algorithm=b2;
sumCommand=(b2sum);
checkCommand=("${sumCommand[@]}" -c);
if [[ ${#opt_list_b2_opts[@]} -gt 0 ]]; then
sumCommand+=("${opt_list_b2_opts[@]}");
fi
;;
*) die 1 "Unknown sum algorithm '${opt_algorithm}'. Aborting for safety.";;
esac
sumCommand+=(--); # no more options, in case filenames/paths begin with `-`.
if [[ $opt_include_time == true ]]; then
checkCommand=(checkdir) # Count on checkdir ^0.2.3 to detect separator header.
fi
if command -v "${sumCommand[0]}" &>/dev/null; then
feedback 1 "Using $(command -v "${sumCommand[0]}")";
else
die 1 "Missing selected checksum software: ${sumCommand[0]}.";
fi
algoUpper="$(echo "$opt_algorithm" | toUpperCase)";
if [[ $opt_algorithm != sha256e ]]; then
opt_column_sep= # Not warning, as it is non-empty by default.
if [[ $opt_include_time != false ]]; then
feedback 0 "WARNING: Time metadata is only available with -a sha256e"
opt_include_time=false
fi
elif [[ $opt_include_time != true ]]; then
# If no metadata (currently time is the only metadata available), avoid adding metadata descriptive header.
opt_column_sep= # Not warning, as it is non-empty by default.
fi
}
initializeJobExecutor() {
if command -v parallel &>/dev/null; then
jobExecutor=(parallel -0 --bar);
elif command -v xargs &>/dev/null; then
jobExecutor=(xargsNulWrapper);
else
die 1 "Missing parallel and xargs.";
return 1
fi;
if [[ $opt_include_time == true ]]; then
jobExecutor+=(jobWithMetadata);
fi
return 0
}
xargsNulWrapper() {
# Invoking bash in order to access exported functions.
local bashCommandQuoted=()
while [[ $# -gt 0 ]]; do
bashCommandQuoted+=("$(printf %q "$1")");
shift;
done
xargs -i -0 bash -c "${bashCommandQuoted[*]} {}";
}
sumSHA256E() {
local parseArgs=true path basename size sum ext extWIP getKeyReferenceContents=true
local PATTERN_SHA256E='^SHA256E-s[0-9]+--[0-9a-f]{64}(\.[^.]{1,8}){0,2}$'
local MAX_KEY_LENGTH=300
local MAX_EXTENSION_LENGTH=10
local KEY_REF_PREFIX='*'
while [[ $# -gt 0 ]]; do
if [[ $parseArgs == true ]]; then
case $1 in
--no-key-refs) getKeyReferenceContents=false; shift; continue;;
--) parseArgs=false; shift; continue;;
esac
fi
path="$1"
shift
[[ -n $path ]] || continue
basename="$(basename "$path")"
size=($(du -L -b "$path")) || continue # LATER Honor opt_should_dereference uuid: 23d2b673-c60b-4476-80eb-302869e8fedd
if [[ -n $path && $getKeyReferenceContents == true && $size -lt $MAX_KEY_LENGTH ]]
then
# LATER Also handle symlink key references uuid:c79db6fa-5d82-4459-9011-c02f1274d7b4
key="$(cat "$path" | sed 's/^.*\///' | grep '^SHA256E')" # grepping to avoid wacky values
if [[ $key =~ $PATTERN_SHA256E ]]
then
key="${KEY_REF_PREFIX}${key}"
loglevel 3 && >&2 echo "# $(declare -p key path)"
else
key=
fi
fi
if [[ -z $key ]]
then
sum=($(sha256sum "$path")) || continue
ext="${basename##*.}"
if [[ $ext == $basename ]]
then
ext=''
else
while [[ ${#ext} -gt $MAX_EXTENSION_LENGTH ]]; do
extWIP="${ext#*.}"
if [[ $extWIP != $ext ]]
then
ext="$extWIP"
else
ext=
fi
done
[[ -n $ext ]] && ext=".${ext}"
fi
key="SHA256E-s${size[0]}--${sum[0]}${ext}"
fi
echo "${key} ${path}"
done
}
export -f sumSHA256E
jobWithMetadata() {
local command=("$1" "$2"); # Assuming $2 is '--'
shift 2;
local remainder="$*";
local buffer= arg=;
while [[ ${#remainder} -gt 0 ]]; do
buffer+="${remainder:0:1}";
remainder="${remainder:1}";
if [[ $buffer == $opt_column_sep ]]; then
break;
elif [[ $buffer != ${opt_column_sep:0:${#buffer}} ]]; then
arg+="$buffer";
buffer=;
fi
done
if [[ -n $arg ]]; then
command+=("$arg");
fi
local output;
output="$("${command[@]}")";
local status=$?;
loglevel 1 && >&2 declare -p command output opt_column_sep arg buffer remainder;
if [[ -n $remainder ]]; then
output+="${opt_column_sep}${remainder}";
fi
echo "$output";
return $status;
}
export -f jobWithMetadata
}
## PLUMBING:
{
g_IFS="$IFS"
export g_IFS
die() { local status=$1; shift; feedback 0 "$@"; exit $status; }; export -f die;
must() { "$@" || die $? "cannot $*"; }; export -f must;
loglevel() { [[ $opt_verbose -ge $1 ]]; }; export -f loglevel;
feedback() { loglevel $1 || return; shift; >&2 echo "$@"; }; export -f feedback;
getValueIfDefined() {
varName="$1";
eval "[ -n \"\${${varName}+v}\" ] && echo -en \"\$${varName}\"";
local status=$?;
return $status;
}
toLowerCase() {
#perl -C -lne 'print uc';
tr '[:upper:]' '[:lower:]';
}
toUpperCase() {
#perl -C -lne 'print uc';
tr '[:lower:]' '[:upper:]';
}
getArrayFromColonList() {
local varName="$1";
local colonValue="$2";
local listValue=();
local singleValue='';
while [[ "$colonValue" =~ : ]]; do
singleValue="${colonValue%%:*}";
colonValue="${colonValue#*:}"; # Remove first segment from colon-delimited list.
if [[ -z "$singleValue" ]]; then
continue;
fi
listValue+=("$singleValue");
done
listValue+=("${colonValue}");
eval "${opt}=(\"\${listValue[@]}\")"
}
fullPath() {
local inputPath="$1";
echo "$(cd "${inputPath%/*}" &>/dev/null && echo -n "${PWD}/${inputPath##*/}")";
}
dereferenceSymlink() {
local linkPath="$1";
local realPath;
while [ -L "$linkPath" ]; do
realPath="$(readlink -- "${linkPath}")";
if [ ${realPath:0:1} != '/' ]; then
realPath="$(dirname "${linkPath}")/${realPath}";
fi
linkPath="${realPath}";
done
fullPath "${linkPath}";
}
escapeArgs() {
local output=;
while [[ $# -gt 0 ]]; do
[[ -n $output ]] && output+=' ';
output+="$(printf %q "$1")"
shift;
done
echo "$output";
}
export -f escapeArgs
if ! command -v sha256sum &>/dev/null && command -v shasum &>/dev/null; then
sha256sum() { shasum -a 256 "$@"; }
export -f sha256sum;
fi
}
## CONFIGURATION:
{
# NOTE: DEFAULT_EXAMPLE_NAME and opt_example_name must agree for getDefaultOptName and getEnvOptName to work.
DEFAULT_ALGORITHM='sha256';
DEFAULT_COLUMN_SEP='\t';
DEFAULT_DATE_FORMAT='+%Y%m%dT%H%M%SZ';
DEFAULT_SHOULD_HANDLE_KEY_REFS=true;
DEFAULT_INCLUDE_TIME=false;
DEFAULT_LIST_EXCLUDE_NAME='.DS_Store:.thumbnails';
DEFAULT_LIST_EXCLUDE_PATH='*/.git/*:*/node_modules/*';
DEFAULT_OUTPUT_FILE_TEMPLATE='.SUM%A--%d'; # previously '.SHA256SUM--{}'
DEFAULT_SHOULD_DEREFERENCE=false;
DEFAULT_SHOULD_INCLUDE_LOCATION_IN_OUTPUT=false;
DEFAULT_SHOULD_RECURSE=false;
DEFAULT_SHOULD_SINGLE_HASH_FILE=false;
DEFAULT_TIMEZONE=UTC;
DEFAULT_VERBOSE=0;
SCRIPT_NAME="${0##*/}";
CALL_ARGS=("$@");
OPT_OUTPUT_FILE_TEMPLATE_BK='%d..%ASUM';
OPT_VAR_NAMES=(
opt_algorithm
opt_column_sep
opt_date_format
opt_should_handle_key_refs
opt_include_time
opt_list_b2_opts
opt_list_exclude_name
opt_list_exclude_path
opt_list_sha_opts
opt_output_file_template
opt_should_dereference
opt_should_include_location_in_output
opt_should_recurse
opt_should_single_hash_file
opt_timezone
opt_verbose # check verbose first
);
getDefaultOptName() {
local opt="$1";
echo -n "DEFAULT${opt#opt}" | toUpperCase;
}
getEnvOptName() {
local opt="$1";
echo -n "SUMDIR${opt#opt}" | toUpperCase;
}
setOptsFromEnvAndDefaults() {
local missingEnv=();
for opt in "${OPT_VAR_NAMES[@]}"; do
## Get environment variable.
fromVarName="$(getEnvOptName "$opt")";
if ! newValue="$(getValueIfDefined "$fromVarName")"; then
missingEnv+=("${fromVarName}");
## Get default.
fromVarName="$(getDefaultOptName "$opt")";
if ! newValue="$(getValueIfDefined "$fromVarName")"; then
feedback 2 "✗ Missing env and default values for '${opt}'";
continue;
fi
fi
if [[ $opt =~ ^opt_list_ ]]; then
if getArrayFromColonList $opt "$newValue"; then
feedback 1 "✓ ${opt}: (${#listValue[@]})[${listValue[*]}] # from ${fromVarName}";
else
feedback 0 "✗ Unable to parse colon-separated list from env var '${fromVarName}'.";
fi
else
eval "${opt}=\"\$newValue\"";
feedback 1 "✓ ${opt}: \"${newValue}\" # from ${fromVarName}";
fi
done
[[ ${#missingEnv[@]} -gt 0 ]] && feedback 2 "✗ No env vars for options: ${missingEnv[*]}";
}
}
## EXECUTION:
mainArgs=();
if [[ -L "$0" ]]
then
linkName="$(basename "$0")"
suffix="${linkName#sumdir}"
case ${suffix,,} in
*annex*|*sha256e*) mainArgs+=(-a sha256e);;
*sha256*) mainArgs+=(-a sha256);;
*b2*) mainArgs+=(-a b2);;
esac
fi
mainArgs+=("$@");
main "${mainArgs[@]}";