-
Notifications
You must be signed in to change notification settings - Fork 0
/
install
executable file
·1821 lines (1569 loc) · 60.3 KB
/
install
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
#!/usr/bin/env bash
###############################################################################
# GENERATED FROM https://github.com/fchastanet/bash-tools-framework/tree/master/src/_binaries/build/install/install-binary.yaml
# DO NOT EDIT IT
# @generated
###############################################################################
# shellcheck disable=SC2288,SC2034
# ensure that no user aliases could interfere with
# commands used in this script
unalias -a || true
shopt -u expand_aliases
# shellcheck disable=SC2034
((failures = 0)) || true
# Bash will remember & return the highest exit code in a chain of pipes.
# This way you can catch the error inside pipes, e.g. mysqldump | gzip
set -o pipefail
set -o errexit
# Command Substitution can inherit errexit option since bash v4.4
shopt -s inherit_errexit || true
# if set, and job control is not active, the shell runs the last command
# of a pipeline not executed in the background in the current shell
# environment.
shopt -s lastpipe
# a log is generated when a command fails
set -o errtrace
# use nullglob so that (file*.php) will return an empty array if no file
# matches the wildcard
shopt -s nullglob
# ensure regexp are interpreted without accentuated characters
export LC_ALL=POSIX
export TERM=xterm-256color
# avoid interactive install
export DEBIAN_FRONTEND=noninteractive
export DEBCONF_NONINTERACTIVE_SEEN=true
# store command arguments for later usage
# shellcheck disable=SC2034
declare -a BASH_FRAMEWORK_ARGV=("$@")
# shellcheck disable=SC2034
declare -a ORIGINAL_BASH_FRAMEWORK_ARGV=("$@")
# @see https://unix.stackexchange.com/a/386856
# shellcheck disable=SC2317
interruptManagement() {
# restore SIGINT handler
trap - INT
# ensure that Ctrl-C is trapped by this script and not by sub process
# report to the parent that we have indeed been interrupted
kill -s INT "$$"
}
trap interruptManagement INT
################################################
# Temp dir management
################################################
KEEP_TEMP_FILES="${KEEP_TEMP_FILES:-0}"
export KEEP_TEMP_FILES
# PERSISTENT_TMPDIR is not deleted by traps
PERSISTENT_TMPDIR="${TMPDIR:-/tmp}/bash-framework"
export PERSISTENT_TMPDIR
if [[ ! -d "${PERSISTENT_TMPDIR}" ]]; then
mkdir -p "${PERSISTENT_TMPDIR}"
fi
# shellcheck disable=SC2034
TMPDIR="$(mktemp -d -p "${PERSISTENT_TMPDIR:-/tmp}" -t bash-framework-$$-XXXXXX)"
export TMPDIR
# temp dir cleaning
# shellcheck disable=SC2317
cleanOnExit() {
local rc=$?
if [[ "${KEEP_TEMP_FILES:-0}" = "1" ]]; then
Log::displayInfo "KEEP_TEMP_FILES=1 temp files kept here '${TMPDIR}'"
elif [[ -n "${TMPDIR+xxx}" ]]; then
Log::displayDebug "KEEP_TEMP_FILES=0 removing temp files '${TMPDIR}'"
rm -Rf "${TMPDIR:-/tmp/fake}" >/dev/null 2>&1
fi
exit "${rc}"
}
trap cleanOnExit EXIT HUP QUIT ABRT TERM
SCRIPT_NAME=${0##*/}
REAL_SCRIPT_FILE="$(readlink -e "$(realpath "${BASH_SOURCE[0]}")")"
if [[ -n "${EMBED_CURRENT_DIR}" ]]; then
CURRENT_DIR="${EMBED_CURRENT_DIR}"
else
CURRENT_DIR="${REAL_SCRIPT_FILE%/*}"
fi
FRAMEWORK_ROOT_DIR="$(cd "${CURRENT_DIR}/." && pwd -P)"
FRAMEWORK_SRC_DIR="${FRAMEWORK_ROOT_DIR}/src"
FRAMEWORK_BIN_DIR="${FRAMEWORK_ROOT_DIR}/bin"
FRAMEWORK_VENDOR_DIR="${FRAMEWORK_ROOT_DIR}/vendor"
FRAMEWORK_VENDOR_BIN_DIR="${FRAMEWORK_ROOT_DIR}/vendor/bin"
# @description Log namespace provides 2 kind of functions
# - Log::display* allows to display given message with
# given display level
# - Log::log* allows to log given message with
# given log level
# Log::display* functions automatically log the message too
# @see Env::requireLoad to load the display and log level from .env file
# @description log level off
export __LEVEL_OFF=0
# @description log level error
export __LEVEL_ERROR=1
# @description log level warning
export __LEVEL_WARNING=2
# @description log level info
export __LEVEL_INFO=3
# @description log level success
export __LEVEL_SUCCESS=3
# @description log level debug
export __LEVEL_DEBUG=4
# @description verbose level off
export __VERBOSE_LEVEL_OFF=0
# @description verbose level info
export __VERBOSE_LEVEL_INFO=1
# @description verbose level info
export __VERBOSE_LEVEL_DEBUG=2
# @description verbose level info
export __VERBOSE_LEVEL_TRACE=3
# @description concatenate each element of an array with a separator
# but wrapping text when line length is more than provided argument
# The algorithm will try not to cut the array element if it can.
# - if an arg can be placed on current line it will be,
# otherwise current line is printed and arg is added to the new
# current line
# - Empty arg is interpreted as a new line.
# - Add \r to arg in order to force break line and avoid following
# arg to be concatenated with current arg.
#
# @arg $1 glue:String
# @arg $2 maxLineLength:int
# @arg $3 indentNextLine:int
# @arg $@ array:String[]
Array::wrap2() {
local glue="${1-}"
local -i glueLength="${#glue}"
shift || true
local -i maxLineLength=$1
shift || true
local -i indentNextLine=$1
shift || true
local indentStr=""
if ((indentNextLine > 0)); then
indentStr="$(head -c "${indentNextLine}" </dev/zero | tr '\0' " ")"
fi
if (($# == 0)); then
return 0
fi
printCurrentLine() {
if ((isNewline == 0)) || ((previousLineEmpty == 1)); then
echo
fi
((isNewline = 1))
echo -en "${indentStr}"
((currentLineLength = indentNextLine)) || true
}
appendToCurrentLine() {
local text="$1"
local -i length=$2
((currentLineLength += length)) || true
((isNewline = 0)) || true
if [[ "${text: -1}" = $'\r' ]]; then
text="${text:0:-1}"
echo -en "${text%%+([[:blank:]])}"
printCurrentLine
else
echo -en "${text%%+([[:blank:]])}"
fi
}
(
local currentLine
local -i currentLineLength=0 isNewline=1 argLength=0
local -a additionalLines
local -i previousLineEmpty=0
local arg=""
while (($# > 0)); do
arg="$1"
shift || true
# replace tab by 2 spaces
arg="${arg//$'\t'/ }"
# remove trailing spaces
arg="${arg%[[:blank:]]}"
if [[ "${arg}" = $'\n' || -z "${arg}" ]]; then
printCurrentLine
((previousLineEmpty = 1))
continue
else
if ((previousLineEmpty == 1)); then
printCurrentLine
fi
((previousLineEmpty = 0)) || true
fi
# convert eol to args
mapfile -t additionalLines <<<"${arg}"
if ((${#additionalLines[@]} > 1)); then
set -- "${additionalLines[@]}" "$@"
continue
fi
((argLength = ${#arg})) || true
# empty arg
if ((argLength == 0)); then
if ((isNewline == 0)); then
# isNewline = 0 means currentLine is not empty
printCurrentLine
fi
continue
fi
if ((isNewline == 0)); then
glueLength="${#glue}"
else
glueLength="0"
fi
if ((currentLineLength + argLength + glueLength > maxLineLength)); then
if ((argLength + glueLength > maxLineLength)); then
# arg is too long to even fit on one line
# we have to split the arg on current and next line
local -i remainingLineLength
((remainingLineLength = maxLineLength - currentLineLength - glueLength))
appendToCurrentLine "${glue:0:${glueLength}}${arg:0:${remainingLineLength}}" "$((glueLength + remainingLineLength))"
printCurrentLine
arg="${arg:${remainingLineLength}}"
# remove leading spaces
arg="${arg##[[:blank:]]}"
set -- "${arg}" "$@"
else
# the arg can fit on next line
printCurrentLine
appendToCurrentLine "${arg}" "${argLength}"
fi
else
appendToCurrentLine "${glue:0:${glueLength}}${arg}" "$((glueLength + argLength))"
fi
done
if [[ "${currentLine}" != "" ]] && [[ ! "${currentLine}" =~ ^[\ \t]+$ ]]; then
printCurrentLine
fi
) | sed -E -e 's/[[:blank:]]+$//'
}
# @description check if command specified exists or return 1
# with error and message if not
#
# @arg $1 commandName:String on which existence must be checked
# @arg $2 helpIfNotExists:String a help command to display if the command does not exist
#
# @exitcode 1 if the command specified does not exist
# @stderr diagnostic information + help if second argument is provided
Assert::commandExists() {
local commandName="$1"
local helpIfNotExists="$2"
"${BASH_FRAMEWORK_COMMAND:-command}" -v "${commandName}" >/dev/null 2>/dev/null || {
Log::displayError "${commandName} is not installed, please install it"
if [[ -n "${helpIfNotExists}" ]]; then
Log::displayInfo "${helpIfNotExists}"
fi
return 1
}
return 0
}
# @description check if tty (interactive mode) is active
# @noargs
# @exitcode 1 if tty not active
# @env NON_INTERACTIVE if 1 consider as not interactive even if environment is interactive
# @env INTERACTIVE if 1 consider as interactive even if environment is not interactive
Assert::tty() {
if [[ "${NON_INTERACTIVE:-0}" = "1" ]]; then
return 1
fi
if [[ "${INTERACTIVE:-0}" = "1" ]]; then
return 0
fi
tty -s
}
# @description Backup given directory in the base directory or in BACKUP_DIR directory
# backup directory name is composed by following fields separated by _:
# - if BACKUP_DIR is not empty then escaped full dir name separated by @
# - date with format %Y%m%d_%H:%M:%S (Eg: 20240326_14:45:08)
# - .tgz extension
#
# @arg $1 string the base directory
# @arg $2 string the directory to backup from base directory
#
# @env BACKUP_DIR String variable referencing backup directory
# @env FRAMEWORK_ROOT_DIR String used to remove this project directory from displayed backup path
# @env SUDO String allows to use custom sudo prefix command
#
# @exitcode 1 if directory to backup does not exist, 0 if everything is OK
# @exitcode 2 on backup failure
#
# @stderr message about where the directory is backed up
Backup::dir() {
if [[ "${REQUIRE_FUNCTION_LINUX_REQUIRE_TAR_COMMAND_LOADED:-0}" != 1 ]]; then
echo >&2 "Requirement Linux::requireTarCommand has not been loaded"
exit 1
fi
local escapedDirname backupFile
local fromDir="$1"
local dirname="$2"
if [[ ! -d "${fromDir}/${dirname}" ]]; then
Log::displayError "Backup::dir - directory '${fromDir}/${dirname}' doesn't exist"
return 1
fi
if [[ -z "${BACKUP_DIR:-}" ]]; then
escapedDirname="$(sed -e 's#^/##; s#/#@#g' <<<"${dirname}")"
backupFile="${fromDir}/${escapedDirname}-$(date +"%Y%m%d_%H:%M:%S").tgz"
else
escapedDirname="$(sed -e 's#^/##; s#/#@#g' <<<"${fromDir}/${dirname}")"
backupFile="${BACKUP_DIR}/${escapedDirname}-$(date +"%Y%m%d_%H:%M:%S").tgz"
fi
Log::displayInfo "Backup directory '${fromDir}/${dirname}' to ${backupFile}"
if ! ${SUDO:-} tar --same-owner -czf "${backupFile}" "${fromDir}/${dirname}" 2>/dev/null; then
Log::displayError "cannot backup '${fromDir}/${dirname}'"
return 2
fi
}
read -r -d '\0' bashToolsDefaultConfigTemplate <<-EOM || true
##!/usr/bin/env bash
# shellcheck disable=SC2034
# Default settings
# you can override these settings by creating ${HOME}/.bash-tools/.env file
###
### DISPLAY Level
### minimum level of the messages that will be displayed on screen
###
### 0: NO LOG
### 1: ERROR
### 2: WARNING
### 3: INFO
### 4: DEBUG
###
BASH_FRAMEWORK_DISPLAY_LEVEL=${BASH_FRAMEWORK_DISPLAY_LEVEL:-3}
###
### DISPLAY duration
### 0: no duration is displayed on the messages
### 1: duration between previous message and current is displayed
### with the message
###
DISPLAY_DURATION=${DISPLAY_DURATION:0}
###
### Log to file
###
### all log messages will be redirected to log file specified
### this same path will be used inside and outside of the container
###
BASH_FRAMEWORK_LOG_FILE=${BASH_FRAMEWORK_LOG_FILE:-${BASH_TOOLS_ROOT_DIR}/logs/bash.log}
###
### LOG Level
### minimum level of the messages that will be logged into LOG_FILE
###
### 0: NO LOG
### 1: ERROR
### 2: WARNING
### 3: INFO
### 4: DEBUG
###
BASH_FRAMEWORK_LOG_LEVEL=${BASH_FRAMEWORK_LOG_LEVEL:-0}
# absolute directory containing db import sql dumps
DB_IMPORT_DUMP_DIR=${DB_IMPORT_DUMP_DIR:-${HOME}/.bash-tools/dbImportDumps}
# garbage collect all files for which modification is greater than eg: 30 days (+30)
# each time an existing file is used by dbImport/dbImportTable
# the file modification time is set to now
DB_IMPORT_GARBAGE_COLLECT_DAYS=${DB_IMPORT_GARBAGE_COLLECT_DAYS:-+30}
# absolute directory containing dbScripts used by dbScriptAllDatabases
SCRIPTS_FOLDER=${SCRIPTS_FOLDER:-${HOME}/.bash-tools/conf/dbScripts}
# -----------------------------------------------------
# AWS Parameters
# -----------------------------------------------------
S3_BASE_URL=${S3_BASE_URL:-}
# -----------------------------------------------------
# Postman Parameters
# -----------------------------------------------------
POSTMAN_API_KEY=
EOM
# @description loads ~/.bash-tools/.env if available
# if not creates it from a default template
# else check if new options need to be added
BashTools::Conf::requireLoad() {
BASH_TOOLS_ROOT_DIR="$(cd "${CURRENT_DIR}/${RELATIVE_FRAMEWORK_DIR_TO_CURRENT_DIR}" && pwd -P)"
if [[ -d "${BASH_TOOLS_ROOT_DIR}/vendor/bash-tools-framework/" ]]; then
FRAMEWORK_ROOT_DIR="$(cd "${BASH_TOOLS_ROOT_DIR}/vendor/bash-tools-framework" && pwd -P)"
else
# if the directory does not exist yet, give a value to FRAMEWORK_ROOT_DIR
FRAMEWORK_ROOT_DIR="${BASH_TOOLS_ROOT_DIR}/vendor/bash-tools-framework"
fi
# shellcheck disable=SC2034
FRAMEWORK_SRC_DIR="${FRAMEWORK_ROOT_DIR}/src"
# shellcheck disable=SC2034
FRAMEWORK_BIN_DIR="${FRAMEWORK_ROOT_DIR}/bin"
# shellcheck disable=SC2034
FRAMEWORK_VENDOR_DIR="${FRAMEWORK_ROOT_DIR}/vendor"
# shellcheck disable=SC2034
FRAMEWORK_VENDOR_BIN_DIR="${FRAMEWORK_ROOT_DIR}/vendor/bin"
if [[ -f "${HOME}/.bash-tools/.env" ]]; then
# shellcheck disable=SC2034
BASH_FRAMEWORK_ENV_FILES=("${HOME}/.bash-tools/.env")
fi
local envFile="${HOME}/.bash-tools/.env"
if [[ ! -f "${envFile}" ]]; then
mkdir -p "${HOME}/.bash-tools"
(
echo "#!/usr/bin/env bash"
# shellcheck disable=SC2154
echo "${bashToolsDefaultConfigTemplate}"
) >"${envFile}"
Log::displayInfo "Configuration file '${envFile}' created"
else
if ! grep -q '^POSTMAN_API_KEY=' "${envFile}"; then
(
echo '# -----------------------------------------------------'
echo '# Postman Parameters'
echo '# -----------------------------------------------------'
echo 'POSTMAN_API_KEY='
) >>"${envFile}"
fi
fi
# shellcheck source=/conf/defaultEnv/.env
source "${envFile}" || {
Log::displayError "impossible to load '${envFile}'"
exit 1
}
}
# @description ensure env files are loaded
# @arg $@ list of default files to load at the end
# @exitcode 1 if one of env files fails to load
# @stderr diagnostics information is displayed
# shellcheck disable=SC2120
Env::requireLoad() {
export REQUIRE_FUNCTION_ENV_REQUIRE_LOAD_LOADED=1
local -a defaultFiles=("$@")
# get list of possible config files
local -a configFiles=()
if [[ -n "${BASH_FRAMEWORK_ENV_FILES[0]+1}" ]]; then
# BASH_FRAMEWORK_ENV_FILES is an array
configFiles+=("${BASH_FRAMEWORK_ENV_FILES[@]}")
fi
local localFrameworkConfigFile
localFrameworkConfigFile="$(pwd)/.framework-config"
if [[ -f "${localFrameworkConfigFile}" ]]; then
configFiles+=("${localFrameworkConfigFile}")
fi
if [[ -f "${FRAMEWORK_ROOT_DIR}/.framework-config" ]]; then
configFiles+=("${FRAMEWORK_ROOT_DIR}/.framework-config")
fi
configFiles+=("${optionEnvFiles[@]}")
configFiles+=("${defaultFiles[@]}")
for file in "${configFiles[@]}"; do
# shellcheck source=/.framework-config
CURRENT_LOADED_ENV_FILE="${file}" source "${file}" || {
Log::displayError "while loading config file: ${file}"
return 1
}
done
}
# @description create a temp file using default TMPDIR variable
# @env TMPDIR String (default value /tmp)
# @arg $1 templateName:String template name to use(optional)
Framework::createTempFile() {
mktemp -p "${TMPDIR:-/tmp}" -t "${1:-}.XXXXXXXXXXXX"
}
# @description ensure running user is not root
# @exitcode 1 if current user is root
# @stderr diagnostics information is displayed
Linux::requireExecutedAsUser() {
if [[ "$(id -u)" = "0" ]]; then
Log::fatal "this script should be executed as normal user"
fi
}
# @description ensure command tar is available
# @exitcode 1 if tar command not available
# @stderr diagnostics information is displayed
Linux::requireTarCommand() {
export REQUIRE_FUNCTION_LINUX_REQUIRE_TAR_COMMAND_LOADED=1
Assert::commandExists tar
}
declare -g FIRST_LOG_DATE LOG_LAST_LOG_DATE LOG_LAST_LOG_DATE_INIT LOG_LAST_DURATION_STR
FIRST_LOG_DATE="${EPOCHREALTIME/[^0-9]/}"
LOG_LAST_LOG_DATE="${FIRST_LOG_DATE}"
LOG_LAST_LOG_DATE_INIT=1
LOG_LAST_DURATION_STR=""
# @description compute duration since last call to this function
# the result is set in following env variables.
# in ss.sss (seconds followed by milliseconds precision 3 decimals)
# @noargs
# @env DISPLAY_DURATION int (default 0) if 1 display elapsed time information between 2 info logs
# @set LOG_LAST_LOG_DATE_INIT int (default 1) set to 0 at first call, allows to detect reference log
# @set LOG_LAST_DURATION_STR String the last duration displayed
# @set LOG_LAST_LOG_DATE String the last log date that will be used to compute next diff
Log::computeDuration() {
if ((${DISPLAY_DURATION:-0} == 1)); then
local -i duration=0
local -i delta=0
local durationStr deltaStr
local -i currentLogDate
currentLogDate="${EPOCHREALTIME/[^0-9]/}"
if ((LOG_LAST_LOG_DATE_INIT == 1)); then
LOG_LAST_LOG_DATE_INIT=0
LOG_LAST_DURATION_STR="Ref"
else
duration=$(((currentLogDate - FIRST_LOG_DATE) / 1000000))
delta=$(((currentLogDate - LOG_LAST_LOG_DATE) / 1000000))
if ((duration > 59)); then
durationStr=$(date -ud "@${duration}" +'%H:%M:%S')
else
durationStr="${duration}s"
fi
if ((delta > 59)); then
deltaStr=$(date -ud "@${delta}" +'%H:%M:%S')
else
deltaStr="${delta}s"
fi
LOG_LAST_DURATION_STR="${durationStr}/+${deltaStr}"
fi
LOG_LAST_LOG_DATE="${currentLogDate}"
# shellcheck disable=SC2034
local microSeconds="${EPOCHREALTIME#*.}"
LOG_LAST_DURATION_STR="$(printf '%(%T)T.%03.0f\n' "${EPOCHSECONDS}" "${microSeconds:0:3}")(${LOG_LAST_DURATION_STR}) - "
else
# shellcheck disable=SC2034
LOG_LAST_DURATION_STR=""
fi
}
# @description Display message using debug color (gray)
# @arg $1 message:String the message to display
# @env DISPLAY_DURATION int (default 0) if 1 display elapsed time information between 2 info logs
# @env LOG_CONTEXT String allows to contextualize the log
Log::displayDebug() {
if ((BASH_FRAMEWORK_DISPLAY_LEVEL >= __LEVEL_DEBUG)); then
Log::computeDuration
echo -e "${__DEBUG_COLOR}DEBUG - ${LOG_CONTEXT:-}${LOG_LAST_DURATION_STR:-}${1}${__RESET_COLOR}" >&2
fi
Log::logDebug "$1"
}
# @description Display message using error color (red)
# @arg $1 message:String the message to display
# @env DISPLAY_DURATION int (default 0) if 1 display elapsed time information between 2 info logs
# @env LOG_CONTEXT String allows to contextualize the log
Log::displayError() {
if ((BASH_FRAMEWORK_DISPLAY_LEVEL >= __LEVEL_ERROR)); then
Log::computeDuration
echo -e "${__ERROR_COLOR}ERROR - ${LOG_CONTEXT:-}${LOG_LAST_DURATION_STR:-}${1}${__RESET_COLOR}" >&2
fi
Log::logError "$1"
}
# @description Display message using info color (bg light blue/fg white)
# @arg $1 message:String the message to display
# @env DISPLAY_DURATION int (default 0) if 1 display elapsed time information between 2 info logs
# @env LOG_CONTEXT String allows to contextualize the log
Log::displayInfo() {
local type="${2:-INFO}"
if ((BASH_FRAMEWORK_DISPLAY_LEVEL >= __LEVEL_INFO)); then
Log::computeDuration
echo -e "${__INFO_COLOR}${type} - ${LOG_CONTEXT:-}${LOG_LAST_DURATION_STR:-}${1}${__RESET_COLOR}" >&2
fi
Log::logInfo "$1" "${type}"
}
# @description Display message using skip color (yellow)
# @arg $1 message:String the message to display
# @env DISPLAY_DURATION int (default 0) if 1 display elapsed time information between 2 info logs
# @env LOG_CONTEXT String allows to contextualize the log
Log::displaySkipped() {
if ((BASH_FRAMEWORK_DISPLAY_LEVEL >= __LEVEL_INFO)); then
Log::computeDuration
echo -e "${__SKIPPED_COLOR}SKIPPED - ${LOG_CONTEXT:-}${LOG_LAST_DURATION_STR:-}${1}${__RESET_COLOR}" >&2
fi
Log::logSkipped "$1"
}
# @description Display message using warning color (yellow)
# @arg $1 message:String the message to display
# @env DISPLAY_DURATION int (default 0) if 1 display elapsed time information between 2 info logs
# @env LOG_CONTEXT String allows to contextualize the log
Log::displayWarning() {
if ((BASH_FRAMEWORK_DISPLAY_LEVEL >= __LEVEL_WARNING)); then
Log::computeDuration
echo -e "${__WARNING_COLOR}WARN - ${LOG_CONTEXT:-}${LOG_LAST_DURATION_STR:-}${1}${__RESET_COLOR}" >&2
fi
Log::logWarning "$1"
}
# @description Display message using error color (red) and exit immediately with error status 1
# @arg $1 message:String the message to display
# @env DISPLAY_DURATION int (default 0) if 1 display elapsed time information between 2 info logs
# @env LOG_CONTEXT String allows to contextualize the log
Log::fatal() {
Log::computeDuration
echo -e "${__ERROR_COLOR}FATAL - ${LOG_CONTEXT:-}${LOG_LAST_DURATION_STR:-}${1}${__RESET_COLOR}" >&2
Log::logFatal "$1"
exit 1
}
# @description log message to file
# @arg $1 message:String the message to display
Log::logDebug() {
if ((BASH_FRAMEWORK_LOG_LEVEL >= __LEVEL_DEBUG)); then
Log::logMessage "${2:-DEBUG}" "$1"
fi
}
# @description log message to file
# @arg $1 message:String the message to display
Log::logError() {
if ((BASH_FRAMEWORK_LOG_LEVEL >= __LEVEL_ERROR)); then
Log::logMessage "${2:-ERROR}" "$1"
fi
}
# @description log message to file
# @arg $1 message:String the message to display
Log::logFatal() {
Log::logMessage "${2:-FATAL}" "$1"
}
# @description log message to file
# @arg $1 message:String the message to display
Log::logInfo() {
if ((BASH_FRAMEWORK_LOG_LEVEL >= __LEVEL_INFO)); then
Log::logMessage "${2:-INFO}" "$1"
fi
}
# @description Internal: common log message
# @example text
# [date]|[levelMsg]|message
#
# @example text
# 2020-01-19 19:20:21|ERROR |log error
# 2020-01-19 19:20:21|SKIPPED|log skipped
#
# @arg $1 levelMsg:String message's level description (eg: STATUS, ERROR, ...)
# @arg $2 msg:String the message to display
# @env BASH_FRAMEWORK_LOG_FILE String log file to use, do nothing if empty
# @env BASH_FRAMEWORK_LOG_LEVEL int log level log only if > OFF or fatal messages
# @stderr diagnostics information is displayed
Log::logMessage() {
if [[ "${REQUIRE_FUNCTION_ENV_REQUIRE_LOAD_LOADED:-0}" != 1 ]]; then
echo >&2 "Requirement Env::requireLoad has not been loaded"
exit 1
fi
if [[ "${REQUIRE_FUNCTION_LOG_REQUIRE_LOAD_LOADED:-0}" != 1 ]]; then
echo >&2 "Requirement Log::requireLoad has not been loaded"
exit 1
fi
local levelMsg="$1"
local msg="$2"
local date
if [[ -n "${BASH_FRAMEWORK_LOG_FILE}" ]] && ((BASH_FRAMEWORK_LOG_LEVEL > __LEVEL_OFF)); then
date="$(date '+%Y-%m-%d %H:%M:%S')"
touch "${BASH_FRAMEWORK_LOG_FILE}"
printf "%s|%7s|%s\n" "${date}" "${levelMsg}" "${msg}" >>"${BASH_FRAMEWORK_LOG_FILE}"
fi
}
# @description log message to file
# @arg $1 message:String the message to display
Log::logSkipped() {
if ((BASH_FRAMEWORK_LOG_LEVEL >= __LEVEL_INFO)); then
Log::logMessage "${2:-SKIPPED}" "$1"
fi
}
# @description log message to file
# @arg $1 message:String the message to display
Log::logWarning() {
if ((BASH_FRAMEWORK_LOG_LEVEL >= __LEVEL_WARNING)); then
Log::logMessage "${2:-WARNING}" "$1"
fi
}
# @description activate or not Log::display* and Log::log* functions
# based on BASH_FRAMEWORK_DISPLAY_LEVEL and BASH_FRAMEWORK_LOG_LEVEL
# environment variables loaded by Env::requireLoad
# try to create log file and rotate it if necessary
# @noargs
# @set BASH_FRAMEWORK_LOG_LEVEL int to OFF level if BASH_FRAMEWORK_LOG_FILE is empty or not writable
# @env BASH_FRAMEWORK_DISPLAY_LEVEL int
# @env BASH_FRAMEWORK_LOG_LEVEL int
# @env BASH_FRAMEWORK_LOG_FILE String
# @env BASH_FRAMEWORK_LOG_FILE_MAX_ROTATION int do log rotation if > 0
# @exitcode 0 always successful
# @stderr diagnostics information about log file is displayed
Log::requireLoad() {
export REQUIRE_FUNCTION_LOG_REQUIRE_LOAD_LOADED=1
if [[ "${REQUIRE_FUNCTION_ENV_REQUIRE_LOAD_LOADED:-0}" != 1 ]]; then
echo >&2 "Requirement Env::requireLoad has not been loaded"
exit 1
fi
if [[ "${REQUIRE_FUNCTION_UI_REQUIRE_THEME_LOADED:-0}" != 1 ]]; then
echo >&2 "Requirement UI::requireTheme has not been loaded"
exit 1
fi
if [[ -z "${BASH_FRAMEWORK_LOG_FILE:-}" ]]; then
BASH_FRAMEWORK_LOG_LEVEL=${__LEVEL_OFF}
export BASH_FRAMEWORK_LOG_LEVEL
fi
if ((BASH_FRAMEWORK_LOG_LEVEL > __LEVEL_OFF)); then
if [[ ! -f "${BASH_FRAMEWORK_LOG_FILE}" ]]; then
if [[ ! -d "${BASH_FRAMEWORK_LOG_FILE%/*}" ]]; then
if ! mkdir -p "${BASH_FRAMEWORK_LOG_FILE%/*}" 2>/dev/null; then
BASH_FRAMEWORK_LOG_LEVEL=${__LEVEL_OFF}
echo -e "${__ERROR_COLOR}ERROR - directory ${BASH_FRAMEWORK_LOG_FILE%/*} is not writable${__RESET_COLOR}" >&2
fi
elif ! touch --no-create "${BASH_FRAMEWORK_LOG_FILE}" 2>/dev/null; then
BASH_FRAMEWORK_LOG_LEVEL=${__LEVEL_OFF}
echo -e "${__ERROR_COLOR}ERROR - File ${BASH_FRAMEWORK_LOG_FILE} is not writable${__RESET_COLOR}" >&2
fi
elif [[ ! -w "${BASH_FRAMEWORK_LOG_FILE}" ]]; then
BASH_FRAMEWORK_LOG_LEVEL=${__LEVEL_OFF}
echo -e "${__ERROR_COLOR}ERROR - File ${BASH_FRAMEWORK_LOG_FILE} is not writable${__RESET_COLOR}" >&2
fi
fi
if ((BASH_FRAMEWORK_LOG_LEVEL > __LEVEL_OFF)); then
# will always be created even if not in info level
Log::logMessage "INFO" "Logging to file ${BASH_FRAMEWORK_LOG_FILE} - Log level ${BASH_FRAMEWORK_LOG_LEVEL}"
if ((BASH_FRAMEWORK_LOG_FILE_MAX_ROTATION > 0)); then
Log::rotate "${BASH_FRAMEWORK_LOG_FILE}" "${BASH_FRAMEWORK_LOG_FILE_MAX_ROTATION}"
fi
fi
}
# @description To be called before logging in the log file
# @arg $1 file:string log file name
# @arg $2 maxLogFilesCount:int maximum number of log files
Log::rotate() {
local file="$1"
local maxLogFilesCount="${2:-5}"
if [[ ! -f "${file}" ]]; then
Log::displayDebug "Log file ${file} doesn't exist yet"
return 0
fi
local i
for ((i = maxLogFilesCount - 1; i > 0; i--)); do
Log::displayInfo "Log rotation ${file}.${i} to ${file}.$((i + 1))"
mv "${file}."{"${i}","$((i + 1))"} &>/dev/null || true
done
if cp "${file}" "${file}.1" &>/dev/null; then
echo >"${file}" # reset log file
Log::displayInfo "Log rotation ${file} to ${file}.1"
fi
}
# @description draw a line with the character passed in parameter repeated depending on terminal width
# @arg $1 character:String character to use as separator (default value #)
UI::drawLine() {
local character="${1:-#}"
local -i width=${COLUMNS:-0}
if ((width == 0)) && [[ -t 1 ]]; then
width=$(tput cols)
fi
if ((width == 0)); then
width=80
fi
printf -- "${character}%.0s" $(seq "${COLUMNS:-$([[ -t 1 ]] && tput cols || echo '80')}")
echo
}
# @description load color theme
# @noargs
# @env BASH_FRAMEWORK_THEME String theme to use
# @env LOAD_THEME int 0 to avoid loading theme
# @exitcode 0 always successful
UI::requireTheme() {
export REQUIRE_FUNCTION_UI_REQUIRE_THEME_LOADED=1
if [[ "${LOAD_THEME:-1}" = "1" ]]; then
UI::theme "${BASH_FRAMEWORK_THEME-default}"
fi
}
# @description load colors theme constants
# @warning if tty not opened, noColor theme will be chosen
# @arg $1 theme:String the theme to use (default, noColor)
# @arg $@ args:String[]
# @set __ERROR_COLOR String indicate error status
# @set __INFO_COLOR String indicate info status
# @set __SUCCESS_COLOR String indicate success status
# @set __WARNING_COLOR String indicate warning status
# @set __SKIPPED_COLOR String indicate skipped status
# @set __DEBUG_COLOR String indicate debug status
# @set __HELP_COLOR String indicate help status
# @set __TEST_COLOR String not used
# @set __TEST_ERROR_COLOR String not used
# @set __HELP_TITLE_COLOR String used to display help title in help strings
# @set __HELP_OPTION_COLOR String used to display highlight options in help strings
#
# @set __RESET_COLOR String reset default color
#
# @set __HELP_EXAMPLE String to remove
# @set __HELP_TITLE String to remove
# @set __HELP_NORMAL String to remove
# shellcheck disable=SC2034
UI::theme() {
local theme="${1-default}"
if [[ ! "${theme}" =~ -force$ ]] && ! Assert::tty; then
theme="noColor"
fi
case "${theme}" in
default | default-force)
theme="default"
;;
noColor) ;;
*)
Log::fatal "invalid theme provided"
;;
esac
if [[ "${theme}" = "default" ]]; then
BASH_FRAMEWORK_THEME="default"
# check colors applicable https://misc.flogisoft.com/bash/tip_colors_and_formatting
__ERROR_COLOR='\e[31m' # Red
__INFO_COLOR='\e[44m' # white on lightBlue
__SUCCESS_COLOR='\e[32m' # Green
__WARNING_COLOR='\e[33m' # Yellow
__SKIPPED_COLOR='\e[33m' # Yellow
__DEBUG_COLOR='\e[37m' # Gray
__HELP_COLOR='\e[7;49;33m' # Black on Gold
__TEST_COLOR='\e[100m' # Light magenta
__TEST_ERROR_COLOR='\e[41m' # white on red
__HELP_TITLE_COLOR="\e[1;37m" # Bold
__HELP_OPTION_COLOR="\e[1;34m" # Blue
# Internal: reset color
__RESET_COLOR='\e[0m' # Reset Color
# shellcheck disable=SC2155,SC2034
__HELP_EXAMPLE="$(echo -e "\e[2;97m")"
# shellcheck disable=SC2155,SC2034
__HELP_TITLE="$(echo -e "\e[1;37m")"
# shellcheck disable=SC2155,SC2034
__HELP_NORMAL="$(echo -e "\033[0m")"
else
BASH_FRAMEWORK_THEME="noColor"
# check colors applicable https://misc.flogisoft.com/bash/tip_colors_and_formatting
__ERROR_COLOR=''
__INFO_COLOR=''
__SUCCESS_COLOR=''
__WARNING_COLOR=''
__SKIPPED_COLOR=''
__DEBUG_COLOR=''
__HELP_COLOR=''
__TEST_COLOR=''
__TEST_ERROR_COLOR=''
__HELP_TITLE_COLOR=''
__HELP_OPTION_COLOR=''
# Internal: reset color
__RESET_COLOR=''
__HELP_EXAMPLE=''
__HELP_TITLE=''
__HELP_NORMAL=''
fi
}
# FUNCTIONS
declare -a BASH_FRAMEWORK_ARGV_FILTERED=()
beforeParseCallback() {
Env::requireLoad
UI::requireTheme
Log::requireLoad
}
copyrightCallback() {
#
# shellcheck disable=SC2155,SC2154,SC2250
echo "Copyright (c) 2022-now François Chastanet"
}
# shellcheck disable=SC2317 # if function is overridden
updateArgListInfoVerboseCallback() {
BASH_FRAMEWORK_ARGV_FILTERED+=(--verbose)
}
# shellcheck disable=SC2317 # if function is overridden
updateArgListDebugVerboseCallback() {
BASH_FRAMEWORK_ARGV_FILTERED+=(-vv)
}
# shellcheck disable=SC2317 # if function is overridden
updateArgListTraceVerboseCallback() {
BASH_FRAMEWORK_ARGV_FILTERED+=(-vvv)
}
# shellcheck disable=SC2317 # if function is overridden
updateArgListEnvFileCallback() { :; }
# shellcheck disable=SC2317 # if function is overridden
updateArgListLogLevelCallback() { :; }
# shellcheck disable=SC2317 # if function is overridden
updateArgListDisplayLevelCallback() { :; }
# shellcheck disable=SC2317 # if function is overridden
updateArgListNoColorCallback() {
BASH_FRAMEWORK_ARGV_FILTERED+=(--no-color)
}
# shellcheck disable=SC2317 # if function is overridden
updateArgListThemeCallback() { :; }
# shellcheck disable=SC2317 # if function is overridden
updateArgListQuietCallback() { :; }
# shellcheck disable=SC2317 # if function is overridden
optionHelpCallback() {
Log::displayError "optionHelpCallback needs to be overridden"
exit 0
}
# shellcheck disable=SC2317 # if function is overridden
optionVersionCallback() {