Repository navigation
Expand file tree
/
Copy pathshell-api-core.sh
More file actions
8462 lines (7334 loc) · 250 KB
/
Copy pathshell-api-core.sh
File metadata and controls
8462 lines (7334 loc) · 250 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
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/bash
###############################################################################
#
# Copyright (c) 2024-2026 Michel Mehl. All rights reserved.
#
# -----------------------------------------------------------------------------
#
# A Shell API gathering a set of basic useful functions. This file
# also provides a framework for setting up easily and quickly high quality
# shell applications (BASH).
#
# -----------------------------------------------------------------------------
#
# Report bugs to michel.mehl@slashetc.fr
#
###############################################################################
__SHELL_API_CORE_DIR__=$(readlink -f $(dirname ${BASH_SOURCE[0]}))
if [[ -v "__SHELL_API_CORE__" ]]; then
return 0
fi
# 0 EXIT
# 1 SIGHUP
# 2 SIGINT
# 3 SIGQUIT
# 6 SIGABRT
# 9 SIGKILL
# 14 SIGALRM
# 15 SIGTERM
#__ALL_SIGNALS__=(EXIT SIGHUP SIGINT SIGTERM SIGQUIT SIGABRT)
for __SIGNAL__ in 1 2 3 6 9 14 15 ; do
trap "_cleanup ${__SIGNAL__}" ${__SIGNAL__}
done
#trap _cleanup EXIT SIGHUP SIGINT SIGTERM SIGQUIT SIGABRT
__SHELL_API_CORE__=0
__CALLER_APP__="$1"
export __SUDO__=""
__SHELL_API_CORE_LOADED__=0
__SHELL_CURRENT_APPNAME__=""
__SHELL_CURRENT_APP_JOB_ID__=""
__SHELL_TEST_GEN_EXAMPLES__=1
declare -A SHELL_API_DEP_LOADED
# --------------------------------------------------------------------------------------
# Color Palette API
# --------------------------------------------------------------------------------------
Term__text_mode=""
# Term__text_color is set as the concanetation of Term__text_fgcolor and Term__text_bgcolor
Term__text_color=""
Term__text_fgcolor=""
Term__text_bgcolor=""
Term__reset_color='\033[0m'
Term__colorFormatString='\033[%s1%s2m'
Term__colorList=$(tput colors 2>/dev/null || echo "0")
declare -A _pal
declare -A Term__colorName2colorCodeMap
Term__colorName2colorCodeMap["black"]=0
Term__colorName2colorCodeMap["red"]=1
Term__colorName2colorCodeMap["green"]=2
Term__colorName2colorCodeMap["yellow"]=3
Term__colorName2colorCodeMap["blue"]=4
Term__colorName2colorCodeMap["purple"]=5
Term__colorName2colorCodeMap["cyan"]=6
Term__colorName2colorCodeMap["white"]=7
Term__setTextMode()
{
Term__text_mode="$1"
}
declare -A Term__textMode2TextModeCode
Term__textMode2TextModeCode["normal"]=0;
Term__textMode2TextModeCode["bold"]=1;
Term__textMode2TextModeCode["italic"]=3;
Term__textMode2TextModeCode["underline"]=4;
Term__textMode2TextModeCode["blinking"]=5;
Term__textMode2TextModeCode["blinkingfast"]=6;
Term__textMode2TextModeCode["reverse"]=7;
Term__textMode2TextModeCode["hide"]=8;
Term__textMode2TextModeCode["cross"]=9;
Term__resetColorData() {
Term__text_fgcolor=""
Term__text_bgcolor=""
}
Term__resetColor() {
Term__text_fgcolor=""
Term__text_bgcolor=""
echo -n -e "${Term__reset_color}"
}
Term__setColorOn()
{
Term__setColor "$@"
echo -n -e "${Term__text_color}"
}
Term__setBgColorOn()
{
Term__setColor "$@" true
echo -n -e "${Term__text_color}"
}
:<<'EOF'
Sets either the foreground or the background color
To change the background color, 'true' must be passed as second argument.
@return this sets Term__text_fgcolor and Term__text_bgcolor, and sets Term__text_color from these latter values
EOF
Term__setColor()
{
if ! test -n "${Term__colorList}" || test ${Term__colorList} -lt 8 ; then
Term__text_color=""
return 0
fi
local cname="$1"
local isBackground=false
local tmcode
local _ccode
local realccode
local _ccodeOffset=30
local _textmode="${Term__text_mode}"
if [ $# -eq 1 ]; then
isBackground=false
fi
if [ $# -ge 2 ]; then
isBackground=$2
fi
if [ $# -eq 3 ] && ! $isBackground; then
_textmode="$3"
fi
if $isBackground; then
_ccodeOffset=40
_textmode=""
tmcode=""
if [ -z "$cname" ] ; then
Term__text_bgcolor=""
return 0
fi
else
if [ -z "$cname" ] ; then
Term__text_color="${Term__reset_color}"
return 0
fi
if [ -z "$_textmode" ] ; then
_textmode="normal"
fi
tmcode="${Term__textMode2TextModeCode["${_textmode}"]}"
fi
if [ ! -z "$tmcode" ] ; then tmcode="${tmcode};" ; fi
_ccode=${Term__colorName2colorCodeMap["$cname"]}
local _text_color="${Term__colorFormatString}"
_text_color="${_text_color//%s1/$tmcode}"
realccode=$((${_ccodeOffset} + ${_ccode}))
_text_color="${_text_color//%s2/$realccode}"
if $isBackground ; then
Term__text_bgcolor="${_text_color}"
else
Term__text_fgcolor="${_text_color}"
fi
Term__text_color="${Term__text_bgcolor}${Term__text_fgcolor}"
}
:<<'EOF'
Feed the mal _pal which maps readable colors to the terminal escaped char
Readable colors are of the form:
[bg_]<color name>[_<text_mode>]
If the text mode is not specified , it refers to the default normal text color
If 'bg_' is specified, then the color refers to the background color.
Otherwise, it is foreground color
EOF
Term__buildPalette()
{
local allcolNames=(${!Term__colorName2colorCodeMap[@]})
local alltextModes=(${!Term__textMode2TextModeCode[@]})
local col
Term__text_bgcolor=""
for col in "${allcolNames[@]}" ; do
local txtmode
for txtmode in "${alltextModes[@]}" ; do
# Add entry which is only the text mode, assuming
# names are unique across color names and text modes
local textModeEntry="${Term__colorFormatString}"
local textModeNumVal="${Term__textMode2TextModeCode["$txtmode"]}"
textModeEntry="${textModeEntry//%s1/$textModeNumVal}"
textModeEntry="${textModeEntry//%s2/}"
_pal["${txtmode}"]="$textModeEntry"
#printf "%s %s\n" "$txtmode" "$textModeEntry" # DEBUG
# Add foreground color palette entry
Term__setColor "$col" false "$txtmode"
_pal["${col}_${txtmode}"]="${Term__text_fgcolor}"
# When mode is normal, also add an entry which is just the color itself
if [ "$txtmode" = "normal" ] ; then
_pal["${col}"]="${Term__text_fgcolor}"
fi
# Add background color palette entry
Term__setColor "$col" true
_pal["bg_${col}_${txtmode}"]="${Term__text_bgcolor}"
# When mode is normal, also add an entry which is just the color itself
if [ "$txtmode" = "normal" ] ; then
_pal["bg_${col}"]="${Term__text_bgcolor}"
fi
done
done
# Term__resetColor prints an unprintable char on terminal
# to actual reset the color => this impacts man pages and help
# Actually, here only the internal data needs to be reset
#Term__resetColor
Term__resetColorData
}
Term__showPalette()
{
local all=(${!_pal[@]})
local col
for col in "${all[@]}" ; do
printf "$col: %s\n" "${_pal[$col]}"
done
}
Term__testColors()
{
local allcolNames=(${!Term__colorName2colorCodeMap[@]})
local alltextModes=(${!Term__textMode2TextModeCode[@]})
local col
for col in "${allcolNames[@]}" ; do
local txtmode
for txtmode in "${alltextModes[@]}" ; do
Term__setColor "$col" false "$txtmode"
echo -e "${Term__text_color}$col $txtmode${Term__reset_color}"
#printf "$col $txtmode:%s\n" "${Term__text_color}" >> log.txt # DEBUG
Term__setColor "$col" true "$txtmode"
Term__setColor "white" false "$txtmode"
echo -e "${Term__text_color}$col $txtmode with BACKGROUND${Term__reset_color}"
#printf "$col $txtmode:%s\n" "${Term__text_color}" >> log.txt # DEBUG
Term__resetColor
done
done
Term__resetColor
}
_colorprint() {
echo -n -e "${Term__text_color}$1"
Term__resetColor
}
:<<'EOF'
Print the passed text with the specified color without
impacting the current terminal setting (resets to normal)
The background color name of the palette shall be specified without the "bg_" prefix
@param[1] text to print
@param[2] text foreground color
@param[3] text background color
EOF
_colorText() {
local __outText=""
if [ $# -ge 2 ] ; then
__outText="${_pal["$2"]}${__outText}"
fi
if [ $# -ge 3 ] ; then
__outText="${__outText}${_pal["bg_$3"]}"
fi
if [ $# -ge 1 ] ; then
__outText="${__outText}$1"
fi
if [ $# -ge 2 ] ; then
__outText="${__outText}${Term__reset_color}"
fi
echo -n -e "${__outText}"
}
:<<'EOF'
Updates the passed text by adding the specified fore and background colors
The background color name of the palette shall be specified without the "bg_" prefix
@param[1] text to print
@param[2] text foreground color
@param[3] text background color
EOF
_setColored() {
local -n __inoutText=$1
local __inText="${__inoutText}"
__inoutText=""
if [ $# -ge 2 ] ; then
__inoutText="${_pal["$2"]}${__inoutText}"
fi
if [ $# -ge 3 ] ; then
__inoutText="${_pal["bg_$3"]}${__inoutText}"
fi
__inoutText="${__inoutText}${__inText}"
if [ $# -ge 2 ] ; then
__inoutText="${__inoutText}${Term__reset_color}"
fi
}
#Term__testColors
Term__buildPalette
#Term__showPalette
#exit 0
# --------------------------------------------------------------------------------------
# Shell API framework API
# --------------------------------------------------------------------------------------
:<<'EOF'
Loads another script file by sourcing it (if not loaded yet before).
Prior to sourcing, the global var __SHELL_SOURCE_NAME__ is set to
hold the basename of the sourced script. __SHELL_SOURCE_NAME__ is restored
to previous value after the sourcing.
@param [1] name of the script without extension
@param [2] parent dir path of the script, relatively to this.
@return 1 on error (invalid args), 0 otherwise.
EOF
_load() {
if [ $# -ge 1 ] ; then
local scriptName="$1"
local parentDir="$2"
local fileCorename
File__corename "${scriptName}" fileCorename
local import_define="__${fileCorename}__"
Str__toUpper import_define
Str__replace import_define "-" "_"
# _log_dbg "CHECK: '$import_define'"
if [[ ! -v "${import_define}" ]]; then
_log_dbg "sourcing '${__SHELL_API_CORE_DIR__}/${parentDir}/${scriptName}.sh'"
local cur_SRC_NAME="${__SHELL_SRC_NAME__}"
__SHELL_SRC_NAME__="$fileCorename"
#_log_dbg "_LOAD SHELL SRC NAME : '${__SHELL_SRC_NAME__}'"
source "${__SHELL_API_CORE_DIR__}/${parentDir}/${scriptName}.sh"
__SHELL_SRC_NAME__="${cur_SRC_NAME}" # restore value prior to sourcing
fi
return 0
else
_log_err "${FUNCNAME[0]}: invalid use. 1 or 2 arg(s) expected, $# passed ($*)"
echo -n "" >&2
return 1
fi
}
loadm='read _load_mod
echo "!!!! -$_load_mod-"
'
_loadm='read _load_mod &&
__shell_api_fileCorename="" && File__corename "${_load_mod}" __shell_api_fileCorename &&
__shell_api_import_define="__${__shell_api_fileCorename}__" && Str__toUpper __shell_api_import_define && Str__replace __shell_api_import_define "-" "_" &&
if [[ ! -v "${__shell_api_import_define}" ]]; then _log_dbg "sourcing ${__SHELL_API_CORE_DIR__}/${_load_mod}.sh"; __shell_api_cur_SRC_NAME="${__SHELL_SRC_NAME__}"; __SHELL_SRC_NAME__="${__shell_api_fileCorename}"; source "${__SHELL_API_CORE_DIR__}/${_load_mod}.sh";__SHELL_SRC_NAME__="${__shell_api_cur_SRC_NAME}" ;fi
'
_loada='read _load_app &&
appDirVar="\${${__SHELL_CURRENT_UPCASE_APPNAME__}__VARS[\"MYDIR\"]}" &&
eval source "${appDirVar}/${_load_app}"
'
:<<'EOF'
Tells whether the cache indicates that the dependency was already loaded
EOF
_isLoadDepCached() {
[ ! -z "${SHELL_API_DEP_LOADED["$1"]}" ]
}
:<<'EOF'
Loads a possible dependency bound with a given distro version
EOF
_loadVDep() {
if ! _isLoadDepCached "$1" ; then
if DPKG__exists "$1" ; then
_loadDep "$1"
else
SHELL_API_DEP_LOADED["$1"]=0
fi
fi
}
:<<'EOF'
Standard/generic end-user wrapper for dealing with package dependencies.
EOF
_loadDep() {
local dep # a dependency can be formatted like lsblk@util-linux
local depApp
local depPkg
local allargs=("$@")
local allActualArgs=()
# Check first if not yet cached
for dep in "${allargs[@]}"
do
Str__split "$1" depApp "@" depPkg 0
if [ -z "${SHELL_API_DEP_LOADED["$depPkg"]}" ] ; then
allActualArgs+=("$depPkg")
#DEBUG
#else
# _log_high "Dependency $depPkg already loaded according to cache"
fi
done
if [ ${#allActualArgs[@]} -eq 0 ] ; then
return 0
fi
_invokeCallback loadDep "${allActualArgs[@]}"
if [ $? -eq 0 ] ; then
for dep in "${allActualArgs[@]}"
do
#_log_dbg "_loadDep: raw dep string: $dep"
local alternativesString=""
local expectedProgForAlternatives=""
Str__split "$1" expectedProgForAlternatives "@" alternativesString 0
readarray -t -d'|' alternatives <<< "$alternativesString"
local alternCnt=0
while [ $alternCnt -lt ${#alternatives[@]} ] ; do
local aPkg="${alternatives[$alternCnt]}"
Str__trimEnd "$aPkg" aPkg
#_log_dbg "_loadDep: dep string: $aPkg"
SHELL_API_DEP_LOADED["$aPkg"]=0
alternCnt=$(($alternCnt + 1))
done
done
fi
}
:<<'EOF'
Function to be called by any script API to check whether it has been already sourced or not.
When not loaded yet, it defines a global variable which existence means script file had been
sourced yet before.
Typical use:
if _loaded "${BASH_SOURCE[0]}" ; then
return 0
fi
@param [1] path to the source file of the calling script
@return 0 if already loaded, 1 otherwise.
EOF
_loaded() {
local filePath="$1"
Str__toTail filePath "/"
local import_define="__${filePath%.*}__" # take only the core filename without extension, avoiding using subshells
Str__toUpper import_define
Str__replace import_define "-" "_"
#_log_dbg "CHECK: '$import_define'"
if [[ ! -v "${import_define}" ]]; then
#echo "defining ${import_define}"
_log_dbg "defining ${import_define}"
eval "${import_define}=0"
:<<'EOF'
local ftype=`type -t ${import_define}init`
if [ "$ftype" == 'function' ] ; then
eval "${import_define}init"
eval "declare -A Dev__fstype2PartUUID"
fi
EOF
return 1
else
return 0
fi
}
:<<'EOF'
Standard/generic end-user wrapper for handling usage errors by doing the following:
- display of a script usage. The calling script-specific usage is displayed by
invoking a callback function formatted <appname>__usage where <appname> is
given by first parameter
- display any error specified by second parameter on standard error
- exit process with code - 1
Optionally displays an error message if second argument is specified
@param [1] optional error message to be displayed
EOF
_usage() {
local msg="$1"
if [ ! -z "$msg" ] ; then
echo
_log_err "$msg"
fi
_invokeCallback usage "$msg"
exit -1
}
:<<'EOF'
Short usage function.
Standard/generic end-user wrapper for handling usage errors by doing the following:
- display of a script usage. The calling script-specific usage is displayed by
invoking a callback function formatted <appname>__susage where <appname> is
given by first parameter
- display any error specified by second parameter on standard error
- exit process with code - 1
Optionally displays an error message if second argument is specified
@param [1] optional error message to be displayed
EOF
_susage() {
local msg="$*"
_invokeCallback susage "$msg"
if [ ! -z "$msg" ] ; then
echo "" 1>&2
_log_err "$msg"
echo "" 1>&2
fi
exit -1
}
:<<'EOF'
Invokes safely an application callback, displaying
a warning if the callback does not exist.
@param [1] callback function name
EOF
_invokeCallback() {
local callback="$1"
shift
local argc=$#
local appName="${__SHELL_CURRENT_APPNAME__}"
if Env__fn_exists "${appName}__${callback}" ; then
if [ $argc -eq 0 ] ; then
${appName}__${callback}
else
local argv=("$@")
${appName}__${callback} "${argv[@]}"
fi
else
_log_warn "expected function '${appName}__${callback}' is not defined."
fi
}
:<<'EOF'
Standard/generic end-user wrapper for handling help doc by doing the following:
- display of a script app help. The calling script-specific help is displayed by
invoking a callback function formatted <appname>__help
where <appname> is __SHELL_CURRENT_APPNAME__
If any argument is specified, the call back is <appname>__fullhelp
- exit process with code 0
Optionally displays an error message if second argument is specified
@param [1] any string
EOF
_help() {
local callback=""
if [ $# -ge 1 ] ; then
callback=fullhelp
else
callback=help
fi
_invokeCallback "$callback"
exit 0
}
:<<'EOF'
This does the same as _options() except that it accepts the additional parameters
OPTION_LIST_ARGS_TYPE so that the argument description
can reflect the argument types defined. _options() is kept for compatibility.
EOF
_optionsN() {
local -n OPTION_LIST_DESC=$1
local -n OPTION_LIST_ARGS=$2
local -n OPTION_LIST_ARGS_TYPE=$3
local -n OPTION_LIST_INTERN=$4
local filter=$5
if [ "$filter" = "0" ] ; then
cat << EOF
*COMMAND DETAILS*
EOF
else
cat << EOF
*OPTIONS DETAILS*
EOF
fi
local k=0
local found=1
declare -A displayOptionList
local maxOptionListLength=0
local maxAllowedOptionListLength=50
# First constructs the list of actual relevant keys
local sortedKeys=()
local keys=()
for k in ${!OPTION_LIST_DESC[@]}
do
local opt1=${k%%|*}
local opt2=${k##*|}
if [ ! -z "$filter" ] ; then
if [ "$filter" = "0" ] && Str__startsWith "$opt1" "-" ; then
continue
fi
if [ "$filter" = "1" ] && ! Str__startsWith "$opt1" "-" ; then
continue
fi
fi
if [ ! -v OPTION_LIST_INTERN["$k"] ] ; then
keys+=("$k")
fi
done
Array__getSortedArray keys sortedKeys
for k in ${sortedKeys[@]}
do
local opt1=${k%%|*}
local opt2=${k##*|}
if [ ! -z "$filter" ] ; then
if [ "$filter" = "0" ] && Str__startsWith "$opt1" "-" ; then
continue
fi
if [ "$filter" = "1" ] && ! Str__startsWith "$opt1" "-" ; then
continue
fi
fi
if [ ! -v OPTION_LIST_INTERN["$k"] ] ; then
displayOptionList["$k"]=$(printf "%s" "${k//|/, }")
if [ "${OPTION_LIST_ARGS["$k"]}" == "0" ] ; then # one mandatory argument
if [ -v OPTION_LIST_ARGS_TYPE["$k"] ] ; then
#echo "=${OPTION_LIST_ARGS_TYPE["$k"]}"
displayOptionList["$k"]="${displayOptionList["$k"]} $(echo -n "${assignChar}${OPTION_LIST_ARGS_TYPE["$k"]}")"
else
#echo "=<arg>"
displayOptionList["$k"]="${displayOptionList["$k"]} $(echo -n "${assignChar}<arg>")"
fi
elif [ "${OPTION_LIST_ARGS["$k"]}" == "2" ] ; then # one optional argument
if [ -v OPTION_LIST_ARGS_TYPE["$k"] ] ; then
#echo "=[${OPTION_LIST_ARGS_TYPE["$k"]}]"
displayOptionList["$k"]="${displayOptionList["$k"]} $(echo -n "${assignChar}[${OPTION_LIST_ARGS_TYPE["$k"]}]")"
else
displayOptionList["$k"]="${displayOptionList["$k"]} $(echo -n "${assignChar}<arg>")"
fi
#else
#echo
#displayOptionList["$k"]="${displayOptionList["$k"]} $(echo)"
fi
printf "%s" "${displayOptionList[$k]}"
printf "\n"
# With optionsN, always display the option description on
# on the next line with a default indent of 10
# NOTE: the indent must not be too great (e.g. 30), otherwise
# it messes up man page generation by helpman
local optionListDescription=""
optionListDescription="${OPTION_LIST_DESC["$k"]}"
Str__fitToLineWidth optionListDescription 80
Str__indent 10 optionListDescription
printf "%s\n" "$optionListDescription"
fi
done
}
:<<'EOF'
Displays script options according to the description list of all options
as stored in global variable <APPNAME>__OPTION_LIST_DESC to be passed on as first argument
and <APPNAME>__OPTION_LIST_ARGS to be passed on as second argument
EOF
_options() {
local -n OPTION_LIST_DESC=$1
local -n OPTION_LIST_ARGS=$2
local -n OPTION_LIST_INTERN=$3
local filter=$4
if [ "$filter" = "0" ] ; then
cat << EOF
COMMAND DETAILS
EOF
else
cat << EOF
OPTIONS DETAILS
EOF
fi
local k=0
local found=1
# First constructs the list of actual relevant keys
local sortedKeys=()
local keys=()
for k in ${!OPTION_LIST_DESC[@]}
do
local opt1=${k%%|*}
local opt2=${k##*|}
if [ ! -z "$filter" ] ; then
if [ "$filter" = "0" ] && Str__startsWith "$opt1" "-" ; then
continue
fi
if [ "$filter" = "1" ] && ! Str__startsWith "$opt1" "-" ; then
continue
fi
fi
if [ ! -v OPTION_LIST_INTERN["$k"] ] ; then
keys+=("$k")
fi
done
Array__getSortedArray keys sortedKeys
for k in ${sortedKeys[@]}
do
local opt1=${k%%|*}
local opt2=${k##*|}
if [ ! -z "$filter" ] ; then
if [ "$filter" = "0" ] && Str__startsWith "$opt1" "-" ; then
continue
fi
if [ "$filter" = "1" ] && ! Str__startsWith "$opt1" "-" ; then
continue
fi
fi
if [ ! -v OPTION_LIST_INTERN["$k"] ] ; then
printf "%s" "${k//|/, }"
if [ "${OPTION_LIST_ARGS["$k"]}" == "0" ] ; then
printf "%s" " <arg>"
elif [ "${OPTION_LIST_ARGS["$k"]}" == "2" ] ; then
printf "%s" " [<arg>]"
fi
echo
local optionListDescription=""
optionListDescription="${OPTION_LIST_DESC["$k"]}"
Str__fitToLineWidth optionListDescription 80
Str__indent 10 optionListDescription
printf "%s\n" "$optionListDescription"
fi
done
}
:<<'EOF'
Displays a short synopsis of the options according to the description list of all options
as stored in global variable <APPNAME>__OPTION_LIST_DESC.
EOF
_soptions() {
local -n OPTION_LIST_DESC=$1
local -n OPTION_LIST_SDESC=$2
local -n OPTION_LIST_ARGS=$3
local -n OPTION_LIST_ARGS_TYPE=$4
local -n OPTION_LIST_INTERN=$5
local filter=$6
cat << EOF
EOF
local k=0
local found=1
declare -A displayOptionList
local maxOptionListLength=0
local maxAllowedOptionListLength=30
local manMode=false
if [ $# -ge 7 ] && [ "$7" = "man" ] ; then
manMode=true
fi
# First constructs the list of actual relevant keys
local sortedKeys=()
local keys=()
for k in ${!OPTION_LIST_DESC[@]}
do
local opt1=${k%%|*}
local opt2=${k##*|}
if [ ! -z "$filter" ] ; then
if [ "$filter" = "0" ] && Str__startsWith "$opt1" "-" ; then
continue
fi
if [ "$filter" = "1" ] && ! Str__startsWith "$opt1" "-" ; then
continue
fi
fi
if [ ! -v OPTION_LIST_INTERN["$k"] ] ; then
keys+=("$k")
fi
done
Array__getSortedArray keys sortedKeys
for k in ${sortedKeys[@]}
do
local opt1=${k%%|*}
local opt2=${k##*|}
if [ ! -z "$filter" ] ; then
if [ "$filter" = "0" ] && Str__startsWith "$opt1" "-" ; then
continue
fi
if [ "$filter" = "1" ] && ! Str__startsWith "$opt1" "-" ; then
continue
fi
fi
local assignChar=" "
if Str__startsWith "$opt1" "-" ; then
assignChar="="
fi
if [ ! -v OPTION_LIST_INTERN["$k"] ] ; then
#echo -n " ${k//|/, }"
displayOptionList["$k"]=$(printf "%s" "${k//|/, }")
if [ "${OPTION_LIST_ARGS["$k"]}" == "0" ] ; then # one mandatory argument
if [ -v OPTION_LIST_ARGS_TYPE["$k"] ] ; then
#echo "=${OPTION_LIST_ARGS_TYPE["$k"]}"
displayOptionList["$k"]="${displayOptionList["$k"]} $(echo -n "${assignChar}${OPTION_LIST_ARGS_TYPE["$k"]}")"
else
#echo "=<arg>"
displayOptionList["$k"]="${displayOptionList["$k"]} $(echo -n "${assignChar}<arg>")"
fi
elif [ "${OPTION_LIST_ARGS["$k"]}" == "2" ] ; then # one optional argument
if [ -v OPTION_LIST_ARGS_TYPE["$k"] ] ; then
#echo "=[${OPTION_LIST_ARGS_TYPE["$k"]}]"
displayOptionList["$k"]="${displayOptionList["$k"]} $(echo -n "${assignChar}[${OPTION_LIST_ARGS_TYPE["$k"]}]")"
else
displayOptionList["$k"]="${displayOptionList["$k"]} $(echo -n "${assignChar}<arg>")"
fi
else
if $manMode ; then
displayOptionList["$k"]="${displayOptionList["$k"]} " # Need to add the space as separation with description
fi
fi
fi
local len=${#displayOptionList["$k"]}
if [ $len -lt $maxAllowedOptionListLength ] && [ $len -gt $maxOptionListLength ] ; then maxOptionListLength=$len; fi
done
#echo "MAX LEN=$maxOptionListLength"
Int__max $maxOptionListLength $maxAllowedOptionListLength maxOptionListLength
#for k in ${!displayOptionList[@]}
for k in ${sortedKeys[@]}
do
local len=${#displayOptionList["$k"]}
printf "%s" "${displayOptionList[$k]}"
local optionListDescription=""
if [ -v OPTION_LIST_SDESC["$k"] ] ; then
optionListDescription="${OPTION_LIST_SDESC["$k"]}"
else
optionListDescription="${OPTION_LIST_DESC["$k"]}"
fi
local originalOptionListDescription="${optionListDescription}"
Str__fitToLineWidth optionListDescription 60
#Str__justify optionListDescription 60
# In normal mode (not man), display the description opposite
# the option if it holds on a 1 single line and its length
# is not greater than maxAllowedOptionListLength
# Otherwise, display it on the next line with an indent
# equal to maxOptionListLength - len
#
# In man mode, always display the option description on
# on the next line with a default indent of 10
# NOTE: the indent must not be too great (e.g. 30), otherwise
# it messes up man page generation by helpman
#
if $manMode ; then
printf "\n"
Str__indent 10 optionListDescription #maxOptionListLength
#Str__spaces $maxOptionListLength
else
local lc=0
Str__lineCount "$optionListDescription" lc
if [ $len -lt $maxAllowedOptionListLength ] && [ $lc -eq 1 ] ; then
Str__indent $(($maxOptionListLength - $len)) optionListDescription
#Str__spaces $(($maxOptionListLength - $len))
#:<<'EOF'
else
printf "\n"
Str__indent $maxOptionListLength optionListDescription
#Str__spaces $maxOptionListLength
#EOF
fi
fi
printf "%s\n" "${optionListDescription}"
if $manMode ; then
printf "\n"
fi
done
}
:<<'EOF'
Standard/generic end-user wrapper for parsing argument.
It handles the -h/--help argument
invoking a callback function formatted <appname>__help
where <appname> is __SHELL_CURRENT_APPNAME__,
ending calling _quit
It handles the --man argument
invoking a callback function formatted <appname>__man
where <appname> is __SHELL_CURRENT_APPNAME__
ending calling _quit
EOF
_parseArgs() {
local argv=("$@")
local argc=${#argv[@]}
local new_argv=()
local arg=""
for arg in "${argv[@]}"
do
case "$arg" in
--man)
_invokeCallback man
__quit
;;
-h|--help)
_invokeCallback help
__quit
;;
-v|--version)
_invokeCallback version
__quit
;;
--revision)
_invokeCallback revision
__quit
;;
--hash)
_invokeCallback hash
__quit
;;
--version-num)
_invokeCallback versionnum
__quit
;;
*)
new_argv+=("$arg")
;;
esac
done
# Handle the default app options if any
local appName="${__SHELL_CURRENT_APPNAME__}"
local upperAppName="${__SHELL_CURRENT_UPCASE_APPNAME__}"
local globVar="\${${upperAppName}__VARS[\"DEFAULT_APP_OPTIONS\"]}"
local dfltAppOptions="$(eval echo "$globVar")"
#_log_dbg "$globVar: DEFAULT_APP_OPTIONS= '$dfltAppOptions'"
Str__trim "$dfltAppOptions" dfltAppOptions
if [ ! -z "${dfltAppOptions}" ] ; then
local dfltAppOptionsAsArray=($dfltAppOptions)
local dftOpt
for dftOpt in "${dfltAppOptionsAsArray[@]}" ; do
#_log "ADDING DEFUALT OPT $dftOpt"