forked from srcshelton/stdlib.sh
-
Notifications
You must be signed in to change notification settings - Fork 0
/
stdlib.sh
2487 lines (2086 loc) · 68.5 KB
/
stdlib.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
# Copyright 2013-2016 Stuart Shelton
# Distributed under the terms of the GNU General Public License v2
#
# stdlib.sh standardised shared shell functions...
# Pull this file into external scripts as follows:
#
cat >/dev/null <<EOC
# --- CUT HERE ---
# stdlib.sh should be in /usr/local/lib/stdlib.sh, which can be found as
# follows by scripts located in /usr/local/{,s}bin/...
declare std_LIB="stdlib.sh"
for std_LIBPATH in \
"$( dirname -- "${BASH_SOURCE:-${0:-.}}" )" \
"." \
"$( dirname -- "$( type -pf "${std_LIB}" 2>/dev/null )" )" \
"$( dirname -- "${BASH_SOURCE:-${0:-.}}" )/../lib" \
"/usr/local/lib" \
${FPATH:+${FPATH//:/ }} \
${PATH:+${PATH//:/ }}
do
if [[ -r "${std_LIBPATH}/${std_LIB}" ]]; then
break
fi
done
[[ -r "${std_LIBPATH}/${std_LIB}" ]] && source "${std_LIBPATH}/${std_LIB}" || {
echo >&2 "FATAL: Unable to source ${std_LIB} functions"
exit 1
}
# --- CUT HERE ---
EOC
# Only load stdlib once, and provide support for loading stdlib from bashrc to
# reduce startup times...
#
if [[ "$( type -t std::sentinel 2>&1 )" == "function" ]]; then
# We've already initialised, and all funcions are (assumed to be)
# present.
:
else
if [[ -n "${STDLIB_HAVE_STDLIB:-}" ]]; then # {{{
if [[ -z "${NAME:-}" ]]; then
# shellcheck disable=SC2031
if [[ -z "${std_LIB:-}" ]]; then
std_LIB="${std_LIB:-stdlib.sh}"
fi
NAME="$( basename -- "${0:-${std_LIB}}" )"
[[ "${NAME:-}" == "$( basename -- "${SHELL:-bash}" )" ]] && \
NAME="${std_LIB}"
fi
echo >&2
echo >&2 "WARN: ${NAME} variables have been imported, but function definitions are"
echo >&2 "WARN: missing - parent shell may be running in restricted, setuid, or"
echo >&2 "WARN: in privileged mode."
echo >&2
echo >&2 "NOTICE: Re-executing ${NAME} to re-generate all functions."
echo >&2
fi # }}}
# {{{
# What API version are we exporting?
#export std_RELEASE="1.3" # Initial import
#export std_RELEASE="1.4" # Add std::parseargs
#export std_RELEASE="1.4.1" # Add std::define
#export std_RELEASE="1.4.2" # Add std::getfilesection, std::configure
#export std_RELEASE="1.4.4" # Re-load stdlib if functions aren't present due to
# bash privileged_mode changes
#export std_RELEASE="1.4.5" # Update exit-code and and add HTTP mapping
# functions
#export std_RELEASE="1.4.6" # Fix issues identified by shellcheck.net, and
# improve MacOS compatibility
#export std_RELEASE="1.4.7" # Fix warnings identified by shellcheck.net, add
# std::wordsplit
export std_RELEASE="1.5.0" # Add std::inherit, finally make errno functions
# work! Set std_ERRNO where appropriate
readonly std_RELEASE
declare std_DEBUG
# Standard usage is:
#
std_DEBUG="${DEBUG:-0}"
declare std_TRACE
# Standard usage is:
#
# shellcheck disable=SC2034
std_TRACE="${TRACE:-0}"
#
# ... and then include:
#
cat >/dev/null <<EOC
# --- CUT HERE ---
(( std_TRACE )) && set -o xtrace
# --- CUT HERE ---
EOC
#
# ... near the top of the calling script.
# If this is not overridden, then logging will be disabled:
#
declare std_LOGFILE="/dev/null"
#
# Note that std_LOGFILE may also be given the special value of "syslog" to use
# 'logger'(1) to send messages to local syslogd.
# All scripts should end with the lines:
#
cat >/dev/null <<EOC
# --- CUT HERE ---
function main() {
...
} # main
main "${@:-}"
exit 0
# vi: set syntax=sh colorcolumn=80 foldmethod=marker:
# --- CUT HERE ---
EOC
# }}}
#
# Externally set control-variables:
#
# STDLIB_WANT_MEMCACHED - Load native memcached functions;
# STDLIB_API - Specify the stdlib API to adhere to.
#
# Exported control-variables:
#
# STDLIB_HAVE_STDLIB - Set once stdlib functions have been loaded;
# STDLIB_HAVE_BASH_4 - Set if interpreter is bash-4 or above;
# STDLIB_HAVE_ERRNO - Set if errno functions have been initialised;
# STDLIB_HAVE_MEMCACHED - Set if bash memcached interace is available.
#
# Externally referenced variables:
#
# std_USAGE - Specify simple usage strings. For more complex
# requirements, instead override usage-message;
# std_ERRNO - Return an additional error-indication from a
# function.
#
###############################################################################
#
# stdlib.sh - Setup and standard functions
#
########################################################################### {{{
# Throw an error if parameter-expansion occurs with an unset variable.
#
# Gentleman, start your debuggers ;)
#
set -u
# Try to impose sane handling of the '!' character...
#
set +o histexpand
# Prevent non-matching shell globs from being literally interpreted...
#
#shopt -qs nullglob
# ... or abort when a glob fails to match anything:
shopt -qs failglob
# Use 'output' rather than 'echo' to clearly differentiate user-visible
# output from pipeline-intermediate commands.
#
function output() {
local flags="-e"
[[ " ${1:-} " == " -n " ]] && { flags+="n" ; shift ; }
[[ -n "${*:-}" ]] && echo ${flags} "${*}"
} # output
# Use 'respond' rather than 'echo' to clearly differentiate function results
# from pipeline-intermediate commands.
#
function respond() {
[[ -n "${*:-}" ]] && echo "${*}"
} # respond
# Use of aliases requires more investigation to ensure reliability.
#
## N.B.: Set this in order to have aliases interpreted by scripts...
##
##shopt -qs expand_aliases
##alias output='echo -e'
##alias respond='echo'
# }}}
###############################################################################
#
# stdlib.sh - Standard functions and variables
#
########################################################################### {{{
unalias cp >/dev/null 2>&1
unalias ls >/dev/null 2>&1
unalias mv >/dev/null 2>&1
unalias rm >/dev/null 2>&1
export std_PREFIX="${std_PREFIX:-/usr/local}"
export std_BINPATH="${std_PREFIX}/bin"
# N.B.: Earlier auto-discovered value for std_LIBPATH is replaced here:
export std_LIBPATH="${std_PREFIX}/lib"
# ${0} may equal '-bash' if invoked directly, in which case basename fails as
# it tries to interpret '-b ash'.
declare NAME
NAME="$( basename -- "${0:-${std_LIB:-stdlib.sh}}" )"
[[ "${NAME:-}" == "$( basename -- "${SHELL:-bash}" )" ]] && \
NAME="${std_LIB:-stdlib.sh}"
export NAME
# Ensure a sane sorting order...
export LC_ALL="C"
# These values should make certain code much clearer...
export std_TAB=' '
export std_NL='
'
# We don't want to rely on $SHELL so, as an alternative, this should work - but
# is also a little bit scary...
#
declare -i STDLIB_HAVE_BASH_4=0
export STDLIB_HAVE_ERRNO=0
export STDLIB_HAVE_STDLIB=0
export STDLIB_HAVE_MEMCACHED=0
export std_ERRNO=0
declare -a __STDLIB_OWNED_FILES
declare std_INTERNAL_DEBUG="${SLDEBUG:-0}"
# }}}
###############################################################################
#
# stdlib.sh - Shell detection
#
###############################################################################
# N.B.: In general, we don't want to reference ${0} as it may be unreliable if
# we're sourced from a script itself sourced from another script... but
# in this case the ultimate parent does impose the interpreter.
#
function __STDLIB_oneshot_get_bash_version() { # {{{
local parent="${0:-}"
local int shell version
if [[ -n "${BASH_VERSION:-}" ]]; then
if (( ${BASH_VERSION%%.*} >= 4 )); then
STDLIB_HAVE_BASH_4=1
else
STDLIB_HAVE_BASH_4=0
fi
export STDLIB_HAVE_BASH_4
std_ERRNO=0
return ${STDLIB_HAVE_BASH_4}
fi
# Please note - this function may have unintended consequences if
# invoked from a script which has an interpreter which causes a
# permanent state-change if executed with '--version' as a parameter.
if [[ -z "${parent:-}" || "$( basename -- "${parent#-}" )" == "bash" ]]; then
# If stdlib.sh is sourced directly, $0 will be 'bash' (or
# another shell name, which should be listed in /etc/shells)
#
if [[ -n "${SHELL:-}" ]]; then
shell="$( basename "${SHELL}" )"
else
shell="bash" # We'll assume...
fi
elif [[ -r "${parent}" ]]; then
# Our interpreter should be some valid shell...
int="$( head -n 1 "${parent}" )"
local sed="sed -r"
${sed} '' >/dev/null 2>&1 <<<'' || sed='sed -E' # ` # <- Syntax highlight fail
int="$( ${sed} 's|^#\! ?||' <<<"${int}" )"
unset sed
if [[ \
"${int:0:4}" == "env " || \
"${int:0:9}" == "/bin/env " || \
"${int:0:13}" == "/usr/bin/env " \
]]; then
shell="$( cut -d' ' -f 2 <<<"${int}" )"
else
shell="$( cut -d' ' -f 1 <<<"${int}" )"
fi
else
warn "Unknown interpretor"
fi
if [[ -n "${shell:-}" ]]; then
shell="$( readlink -e "$( type -pf "${shell:-bash}" 2>/dev/null )" )"
if [[ -n "${shell:-}" && -x "${shell}" ]]; then
version="$( "${shell}" --version 2>&1 | head -n 1 )" || \
die "Cannot determine version for" \
"interpreter '${shell}'"
#if grep -q "^GNU bash, version " >/dev/null 2>&1 <<<"${version}"; then
if echo "${version}" | grep -q "^GNU bash, version " >/dev/null 2>&1; then
#if ! grep -q " version [0-3]" >/dev/null 2>&1 <<<"${version}"; then
if ! echo "${version}" | grep -q " version [0-3]" >/dev/null 2>&1; then
STDLIB_HAVE_BASH_4=1
fi
# N.B.: Don't abort if we can't determine our
# interpretor's capabilities - simply don't set
# STDLIB_HAVE_BASH_4.
#
#else
# die "Cannot determine version for interpreter '${BASH}' (from '${version}')"
fi
#else
# die "Cannot execute interpreter '${int}'"
fi
unset version shell int
#else
# die "Cannot locate this script (tried '${0}')"
fi
export STDLIB_HAVE_BASH_4
std_ERRNO=0
return ${STDLIB_HAVE_BASH_4}
} # __STDLIB_oneshot_get_bash_version # }}}
###############################################################################
#
# stdlib.sh - Validate syntax
#
###############################################################################
function __STDLIB_oneshot_syntax_check() { # {{{
local script
local -Ai seen
if ! (( STDLIB_HAVE_BASH_4 )) || ! [[ -n "${SHELL:-}" && "${SHELL}" =~ bash$ ]]; then
std_ERRNO=$( errsymbol ENOEXE )
return 0
else
while read -r script; do
(( ${seen[${script}]:-0} )) && continue
seen[${script}]=1
if ! [[ -s "${script}" ]]; then
(( std_DEBUG )) && echo >&2 "DEBUG: Skipping syntax validation of unreadable script '${script}' ..."
else
(( std_DEBUG )) && echo >&2 "DEBUG: Syntax validating script '${script}' ..."
"${SHELL}" -n "${script}" || {
echo >&2 "FATAL: Syntax error detected in '${script}'"
std_ERRNO=5
return 1
}
fi
done < <( printf '%s\n' "${BASH_SOURCE[@]:-}" /usr/local/lib/stdlib.sh | sort | uniq )
fi
std_ERRNO=0
return 0
} # __STDLIB_oneshot_syntax_check # }}}
###############################################################################
#
# stdlib.sh - Standard overridable functions - Initialisation & clean-up
#
###############################################################################
# This function MUST be overridden, and contain all script code except for
# variable and function declarations.
#
# The code to include stdlib.sh may appear at top-level, within a separate
# function, or within main().
#
# N.B.: No API-version declaration here - this is fixed.
#
function main() {
die "No override main() function defined"
} # main
# This function may be overridden
#
function __STDLIB_API_1_std::cleanup() { # {{{
local -i rc=${?}
[[ -n "${1:-}" ]] && (( ${1:-0} )) && rc=${1}; shift
local file
# Remove any STDLIB-generated temporary files and exit.
for file in "${__STDLIB_OWNED_FILES[@]:-}"; do
(( std_INTERNAL_DEBUG )) && output >&2 "DEBUG: ${FUNCNAME[0]##*_} is removing file '${file}'"
[[ -n "${file:-}" && -e "${file}" ]] && \
rm -f "${file}" >/dev/null 2>&1
done
unset file
if [[ "${BASH_SOURCE:-${0:-}}" =~ ${std_LIB:-stdlib.sh}$ ]]; then
trap - EXIT QUIT TERM
else
trap - EXIT INT QUIT TERM
fi
[[ -n "${__STDLIB_SIGEXIT:-}" ]] && trap ${__STDLIB_SIGEXIT} EXIT
[[ -n "${__STDLIB_SIGINT:-}" ]] && trap ${__STDLIB_SIGINT} INT
[[ -n "${__STDLIB_SIGQUIT:-}" ]] && trap ${__STDLIB_SIGQUIT} QUIT
[[ -n "${__STDLIB_SIGTERM:-}" ]] && trap ${__STDLIB_SIGTERM} TERM
# 'rc' is numeric, and therefore not subject to word-splitting
# shellcheck disable=SC2086
exit ${rc}
} # __STDLIB_API_1_std::cleanup # }}}
# The 'std::cleanup' stub for the appropriate API should be in place by now...
#
declare __STDLIB_SIGINT __STDLIB_SIGTERM __STDLIB_SIGQUIT __STDLIB_SIGEXIT
__STDLIB_SIGEXIT="$( trap -p EXIT | cut -d"'" -f 2 )"
__STDLIB_SIGQUIT="$( trap -p QUIT | cut -d"'" -f 2 )"
__STDLIB_SIGTERM="$( trap -p TERM | cut -d"'" -f 2 )"
if [[ "${BASH_SOURCE:-${0:-}}" =~ ${std_LIB:-stdlib.sh}$ ]]; then
trap std::cleanup EXIT QUIT TERM
else
__STDLIB_SIGINT="$( trap -p INT | cut -d"'" -f 2 )"
trap std::cleanup EXIT INT QUIT TERM
fi
export __STDLIB_SIGINT __STDLIB_SIGTERM __STDLIB_SIGQUIT __STDLIB_SIGEXIT
# This function should be overridden, or the ${std_USAGE} variable define
#
function __STDLIB_API_1_usage-message() { # {{{
warn "${FUNCNAME[0]##*_} invoked - please use 'std::usage-message' instead"
std::usage-message "${@:-}"
} # __STDLIB_API_1_usage-message # }}}
# Heavyweight compatibility work-around:
declare __STDLIB_usage_message_definition
__STDLIB_usage_message_definition="$( typeset -f usage-message )"
export __STDLIB_usage_message_definition
# This function should be overridden, or the ${std_USAGE} variable defined
#
function __STDLIB_API_1_std::usage-message() { # {{{
die "No override std::usage-message() function defined"
# The following output will appear in-line after 'Usage: ${NAME} '...
output 'Command summary, e.g. "-f|--file <filename> [options]"'
output <<END
Further instructions here, e.g.
-f : Process the specified <filename>
-h : Show this help information
END
std_ERRNO=0
return 0
} # __STDLIB_API_1_std::usage-message # }}}
# This function may be overridden
#
function __STDLIB_API_1_std::usage() { # {{{
local rc="${1:-0}" ; shift
# Optional arguments should be denoted as '[parameter]', required
# arguments as '<parameter>'. Short and long options should be
# separated by a vertical-bar, e.g.
# showfiles [-l|--long] <directory>
output -n "Usage: ${NAME} "
if [[ -n "${std_USAGE:-}" ]]; then
output "${std_USAGE}"
else
if [[ "$( typeset -f usage-message )" == "${__STDLIB_usage_message_definition}" ]]; then
std::usage-message
else
usage-message
fi
fi
# 'rc' is numeric, and therefore not subject to word-splitting
# shellcheck disable=SC2086
exit ${rc}
} # __STDLIB_API_1_std::usage # }}}
###############################################################################
#
# stdlib.sh - Standard overridable functions - Logging functions
#
###############################################################################
function __STDLIB_API_1_std::wrap() { # {{{
local prefix="${1:-}" ; shift
local text="${*:-}"
[[ -n "${text:-}" ]] || {
std_ERRNO=$( errsymbol EARGS )
return 1
}
# N.B.: It may be necessary to 'export COLUMNS' before this
# works - this variable isn't exported to scripts by
# default, and is lost on invocation.
local -i columns=${COLUMNS:-$( tput cols )}
(( columns )) || columns=80
if [[ -n "${prefix:-}" ]]; then
if (( columns > ( ${#prefix} + 2 ) )); then
output "${text}" \
| fold -sw "$(( columns - ( ${#prefix} + 1 ) ))" \
| sed "s/^/${prefix} /"
else
output "${text}" \
| sed "s/^/${prefix} /"
fi
else
if (( columns > 1 )); then
output "${text}" \
| fold -sw "$(( columns - 1))"
else
output "${text}"
fi
fi
std_ERRNO=0
return 0
} # __STDLIB_API_1_std::wrap # }}}
function __STDLIB_API_1_std::log() { # {{{
local prefix="${1:-${std_LIB}}" ; shift
local data="${*:-}" message
# Assume that log messages should be written to a file (unless we're
# debugging) ... otherwise, use note(), warn(), or error() to output
# to screen.
if [[ -z "${data:-}" ]]; then
data="$( cat - )"
fi
[[ -n "${data:-}" ]] || {
std_ERRNO=$( errsymbol EARGS )
return 1
}
data="$( sed 's/\r//' <<<"${data}" )"
if [[ "${std_LOGFILE:-}" == "syslog" ]]; then
# We'll emulate 'logger -i' here, as we need to return and so
# can't use 'exec logger' to maintain PID...
message="[${$}]: ${prefix} ${data}"
type -pf logger >/dev/null 2>&1 && logger \
-t "${NAME}" -- "${message}" >/dev/null 2>&1
fi
#local date="$( date -u +'%Y%m%d %R.%S' )"
#message="${NAME}(${$}) ${date} ${prefix} ${data}"
message="${NAME}(${$}) $( date -u +'%Y%m%d %R.%S' ) ${prefix} ${data}"
# We don't care whether std_LOGFILE exists, but we do care whether it's
# set...
[[ -n "${std_LOGFILE:-}" && "${std_LOGFILE}" != "syslog" ]] \
&& output "${message}" >>"${std_LOGFILE}" 2>&1
if (( std_DEBUG )); then
__STDLIB_API_1_std::wrap "${prefix}" "${data}"
fi
# Don't stomp on std_ERRNO
return $(( ! std_DEBUG ))
} # __STDLIB_API_1_std::log # }}}
#
# N.B.: To prevent unnecessary indirection, call API-versioned functions below
#
# This function may be overridden
#
function __STDLIB_API_1_die() { # {{{
[[ -n "${*:-}" ]] && std_DEBUG=1 __STDLIB_API_1_std::log >&2 "FATAL: " "${*}"
__STDLIB_API_1_std::cleanup 1
# Don't stomp on std_ERRNO
return 1
} # __STDLIB_API_1_die # }}}
# This function may be overridden
#
function __STDLIB_API_1_error() { # {{{
std_DEBUG=1 __STDLIB_API_1_std::log >&2 "ERROR: " "${*:-Unspecified error}"
# Don't stomp on std_ERRNO
return 1
} # __STDLIB_API_1_error # }}}
# This function may be overridden
#
function __STDLIB_API_1_warn() { # {{{
std_DEBUG=1 __STDLIB_API_1_std::log >&2 "WARN: " "${*:-Unspecified warning}"
# Don't stomp on std_ERRNO
return 1
} # __STDLIB_API_1_warn # }}}
# This function may be overridden
#
function __STDLIB_API_1_note() { # {{{
std_DEBUG=1 __STDLIB_API_1_std::log "NOTICE:" "${*:-Unspecified notice}"
# Don't stomp on std_ERRNO
return 0
} # __STDLIB_API_1_note # }}}
function __STDLIB_API_1_notice() { # {{{
__STDLIB_API_1_note "${@:-}"
} # __STDLIB_API_1_notice # }}}
# This function may be overridden
#
function __STDLIB_API_1_info() { # {{{
std_DEBUG=1 __STDLIB_API_1_std::log "INFO: " "${*:-Unspecified message}"
# Don't stomp on std_ERRNO
return 0
} # __STDLIB_API_1_info # }}}
# This function may be overridden
#
function __STDLIB_API_1_debug() { # {{{
(( std_DEBUG )) && __STDLIB_API_1_std::log >&2 "DEBUG: " "${*:-Unspecified message}"
# Don't stomp on std_ERRNO
return $(( ! std_DEBUG ))
} # __STDLIB_API_1_debug # }}}
###############################################################################
#
# stdlib.sh - Standard functions - errno & friends
#
###############################################################################
function __STDLIB_oneshot_errno_init() { # {{{
local count=0
# This function must be called, once, before the errno functions can be
# used.
declare -agx __STDLIB_errsym __STDLIB_errstr
# As per http://tldp.org/LDP/abs/html/exitcodes.html, it would be
# advantageous if bash code could avoid return values 1, 2, 126-192,
# and 255. /usr/include/sysexits.h now defines values in the range 64
# to 78 - although, as referenced in a footnote, there is no reason to
# fit around these values since there is no intersection between the
# code these values apply to and bash scripts. Additionally, avoiding
# return codes 1 and 2 is problematic for interoperability with
# existing code. Avoiding return codes which are not positive integers
# appears to be problematic for Java prorgammers ;)
#
# It is reasonable to return 1 and set a descriptive/diagnostic
# std_ERRNO on failure.
# TODO: This should really be sourced from an external config file.
#
# 0 is not a real error code, but it is useful to have a placeholder
# here...
__STDLIB_errsym[0]="ENOERROR" ; __STDLIB_errstr[0]="Operation successful" ; (( count ++ )) ;
# Named error conditions - these should always be referred to by symbol
# rather than by number (other than in the internal errno functions,
# which can't rely on all values below being fully initialised).
__STDLIB_errsym[1]="ENOTFOUND" ; __STDLIB_errstr[1]="Parameter value not found" ; (( count ++ )) ;
__STDLIB_errsym[2]="EENV" ; __STDLIB_errstr[2]="Invalid environment" ; (( count ++ )) ;
__STDLIB_errsym[3]="EARGS" ; __STDLIB_errstr[3]="Invalid arguments" ; (( count ++ )) ;
__STDLIB_errsym[4]="ENOEXE" ; __STDLIB_errstr[4]="Required executable not found" ; (( count ++ )) ;
__STDLIB_errsym[5]="ESYNTAX" ; __STDLIB_errstr[5]="Syntax error" ; (( count ++ )) ;
__STDLIB_errsym[6]="EACCESS" ; __STDLIB_errstr[6]="File access denied" ; (( count ++ )) ;
# These should appear, in order, last:
__STDLIB_errsym[ ${count} ]="EERROR" ; __STDLIB_errstr[ ${count} ]="Undefined error" ; (( count ++ )) ;
__STDLIB_errsym[ ${count} ]="ENOTSET" ; __STDLIB_errstr[ ${count} ]="Logic failure: errno unset" ; # Final item, no increment
declare -gix __STDLIB_errtotal="${count}" std_ERRNO=0 STDLIB_HAVE_ERRNO=1
return 0
} # __STDLIB_oneshot_errno_init # }}}
function __STDLIB_API_1_symerror() { # {{{
local -i err="${1:-${std_ERRNO:-0}}"
# Given an error number, provide the associated symbolic error name.
if (( __STDLIB_errtotal < 1 || ! STDLIB_HAVE_ERRNO )); then
# FIXME: Obsolete
error "errno not initialised - please re-import ${std_LIB}" \
"with 'STDLIB_WANT_ERRNO' set"
return 1
fi
if (( err >= 0 && err <= ${__STDLIB_errtotal:-0} )) && [[ -n "${__STDLIB_errsym[ ${err} ]:-}" ]]; then
respond "${__STDLIB_errsym[ ${err} ]}"
return 0
fi
std_ERRNO=1 # instead use 'std_ERRNO="$( errsymbol ENOTFOUND )"'
return 1
} # __STDLIB_API_1_symerror # }}}
function __STDLIB_API_1_errsymbol() { # {{{
local symbol="${1:-}"
local -i n
# Given a symbolic error name, provide the error number (to set
# std_ERRNO, for example).
if (( __STDLIB_errtotal < 1 || ! STDLIB_HAVE_ERRNO )); then
# FIXME: Obsolete
error "errno not initialised - please re-import ${std_LIB}" \
"with 'STDLIB_WANT_ERRNO' set"
return 1
fi
if [[ -z "${symbol:-}" ]]; then
std_ERRNO=3 # instead use 'std_ERRNO="$( errsymbol EARGS )"'
return 1
fi
for n in $( seq 0 $(( ${__STDLIB_errtotal:-0} )) ); do
if [[ "${symbol}" == "${__STDLIB_errsym[ ${n} ]:-}" ]]; then
respond "${n}"
return 0
fi
done
std_ERRNO=1 # instead use 'std_ERRNO="$( errsymbol ENOTFOUND )"'
return 1
} # __STDLIB_API_1_errsymbol # }}}
function __STDLIB_API_1_strerror() { # {{{
local err="${1:-${std_ERRNO:-}}" ; shift
local msg="Unknown error number" rc=1
# Given an error number, provide the associated error string.
if (( __STDLIB_errtotal < 1 || ! STDLIB_HAVE_ERRNO )); then
# FIXME: Obsolete
error "errno not initialised - please re-import ${std_LIB}" \
"with 'STDLIB_WANT_ERRNO' set"
return 1
fi
if [[ "${err:-}" =~ ^[0-9]+$ ]] && [[ -n "${__STDLIB_errstr[ ${err} ]:-}" ]]; then
msg="${__STDLIB_errstr[ ${err} ]}"
rc=0
fi
respond "${msg}"
return ${rc}
} # __STDLIB_API_1_strerror # }}}
###############################################################################
#
# stdlib.sh - Standard functions - mktemp & friends
#
###############################################################################
function __STDLIB_API_1_std::garbagecollect() { # {{{
local file="" rc=0
# Add an additional file to the list of files to be removed when
# std::cleanup is invoked.
# This can be used to work-around the use of std::mktemp in a
# sub-shell.
std_ERRNO=0
for file in "${@:-}"; do
if [[ -e "${file}" ]]; then
__STDLIB_OWNED_FILES+=( "${file}" )
rc=${rc:-0}
else
std_ERRNO=$( errsymbol ENOTFOUND )
rc=1
fi
done
if (( std_INTERNAL_DEBUG )); then
output >&2 "DEBUG: ${FUNCNAME[0]##*_} updated '__STDLIB_OWNED_FILES' to:"
for file in "${__STDLIB_OWNED_FILES[@]}"; do
output >&2 "${std_TAB}${file}"
done
output >&2
fi
# std_ERRNO set above
return ${rc:-1}
} # __STDLIB_API_1_std::garbagecollect # }}}
function __STDLIB_API_1_std::mktemp() { # {{{
local tmpdir suffix files
local -i namedargs=1
# Usage: std::mktemp [-tmpdir <directory>] [-suffix <extension>] _
# [file ...]
local std_PARSEARGS_parsed=0
eval "$( std::parseargs --single --permissive --var files -- "${@:-}" )"
(( std_PARSEARGS_parsed )) || {
eval set -- "$( std::parseargs --strip -- "${@:-}" )"
files="${*:-}"
namedargs=0
}
local message standard opts
# Create a temporary file, which will be removed by cleanup() on
# program exit.
# N.B.: mktemp is commonly invoked in a sub-shell - if this is the case
# then std::garbagecollect() must be explicitly called on the
# returned file-names, as the parent process will not have seen
# them.
# If the first argument is a directory which already exists, then the
# temporary file(s) will be created in this directory.
# TODO:
# Add option-parsing of mktemp options, specifically '-d' to create a
# temporary directory.
# CentOS/Red Hat seem to ship a 'mktemp' utility which differs from
# that provided by GNU coreutils - presumably a legacy carry-over :(
#
# ... and in typical fashion, MacOS has a BSD mktemp which offers
# fewer features. In this case, no suffix is possible, and we can
# either specify a prefix (which will get 8 random characters appended)
# which will be placed into ${TMPDIR} with '-t', or provide a full path
# and template if no option is given.
#
# (Un)helpfully, the non-GNU mktemp returns an error if you try to find
# out what it is, which we can then take advantage of thusly:
#
local -i __std_mktemp_standard_gnu=1 __std_mktemp_standard_legacy=2 __std_mktemp_standard_bsd=4
readonly __std_mktemp_standard_gnu __std_mktemp_standard_legacy __std_mktemp_standard_bsd
mktemp --version >/dev/null 2>&1
case ${?} in
0)
message="GNU mktemp failed"
standard=$__std_mktemp_standard_gnu
;;
1)
[[ -n "${suffix:-}" ]] && debug "${FUNCNAME[0]##*_} Removing" \
"unsupported 'suffix' option with non-GNU system mktemp"
unset suffix
message="legacy/BSD mktemp failed"
case "$( uname -s )" in
Linux)
standard=$__std_mktemp_standard_legacy
;;
*)
standard=$__std_mktemp_standard_bsd
;;
esac
;;
*)
die "Cannot detect mktemp version: ${?}"
;;
esac
if (( 0 == namedargs )); then
if [[ -n "${1:-}" && -d "${1}" ]]; then
tmpdir="${1}"
shift
fi
fi
if [[ -d "${tmpdir:-}" ]]; then
case ${standard} in
$__std_mktemp_standard_gnu)
# Note trailing space and quote...
opts="--tmpdir=\"${tmpdir}\" \""
;;
$__std_mktemp_standard_legacy)
# Note lack of trailing space before quote...
opts="\"${tmpdir}\"/\""
;;
$__std_mktemp_standard_bsd)
# There are two options here:
# 'mktemp -t file' acts like
# 'mktemp "${TMPDIR}"/file.XXXXXXXX', but can't
# accept paths or templates;
# 'mktemp "${TMPDIR}"/file.XXXXXXXX' expands
# specified templates.
# Note lack of trailing space before quote...
opts="\"${tmpdir}\"/\""
;;
esac
else
tmpdir="${TMPDIR:-/tmp}"
case ${standard} in
$__std_mktemp_standard_bsd)
opts="\"${tmpdir}\"/\""
;;
*)
# Note trailing space and quote...
opts="-t \""
;;
esac
fi
local -a __std_NEWFILES
local file name
[[ -n "${files:-}" ]] || files="${NAME}"
for file in ${files}; do
name="${file}.XXXXXXXX${suffix:+.${suffix}}"
# Otherwise undocumented, **potentially dangerous**, configuration setting...
if [[ -n "${STDLIB_REUSE_TEMPFILES:-}" ]]; then
local filename
#filename="$( ls -1 "${tmpdir}"/"${NAME}.${file}."* 2>/dev/null | tail -n 1 )"
filename="$( find "${tmpdir}" -mindepth 1 -maxdepth 1 -name "${NAME}.${file}.*" -print 2>/dev/null | tail -n 1 )"
if [[ -n "${filename:-}" && -w "${filename}" ]]; then
# We're intentionally matching the literal quote characters here...
# shellcheck disable=SC2076
[[ " ${__STDLIB_OWNED_FILES[@]} " =~ " ${filename} " ]] || \
__STDLIB_OWNED_FILES+=( "${filename}" )
cat /dev/null > "${filename}" 2>/dev/null
respond "${filename}"
unset filename
continue
fi
fi
__std_NEWFILES+=(
"$( eval "mktemp ${opts}${name}\"" || {
error "${message}"
std_ERRNO=$( errsymbol EERROR )
return 1
} )"
)
done
if (( ${#__std_NEWFILES[@]} )); then
__STDLIB_OWNED_FILES+=( "${__std_NEWFILES[@]}" )
for file in "${__std_NEWFILES[@]}"; do
respond "${file}"
done
fi
if (( std_INTERNAL_DEBUG )); then
output >&2 "DEBUG: ${FUNCNAME[0]##*_} updated '__STDLIB_OWNED_FILES' to:"
for file in "${__STDLIB_OWNED_FILES[@]}"; do
output >&2 "${std_TAB}${file}"
done
output >&2
fi
std_ERRNO=0
return 0
} # __STDLIB_API_1_std::mktemp # }}}
function __STDLIB_API_1_std::emktemp() { # {{{
local var tmpdir suffix names