-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathincl.sh
More file actions
1398 lines (1229 loc) · 42.5 KB
/
incl.sh
File metadata and controls
1398 lines (1229 loc) · 42.5 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
# shellcheck disable=SC1083,SC2001,SC2015,SC2016,SC2028,SC2034,SC2046,SC2059,SC2119,SC2120,SC2128,SC2154,SC2162,SC2178,SC2183,SC2206,SC2207,SC2317
# SC1083: "This } is literal. Check expression (missing ;/\\n?) or quote it.",
# SC2001: "See if you can use ${variable//search/replace} instead.",
# SC2015: "Note that A && B || C is not if-then-else. C may run when A is true.",
# SC2016: "Expressions don't expand in single quotes, use double quotes for that.",
# SC2028: "echo may not expand escape sequences. Use printf.",
# SC2034: "bBlack appears unused. Verify use (or export if used externally).",
# SC2046: "Quote this to prevent word splitting.",
# SC2059: "Don't use variables in the printf format string. Use printf '..%s..' \"$foo\".",
# SC2119: "Use get_fmtdate \"$@\" if function's $1 should mean script's $1.",
# SC2120: "list_funcs references arguments, but none are ever passed.",
# SC2128: "Expanding an array without an index only gives the first element.",
# SC2154: "Ciyan is referenced but not assigned (did you mean 'Cyan'?).",
# SC2162: "read without -r will mangle backslashes.",
# SC2178: "Variable was used as an array but is now assigned a string.",
# SC2183: "This format string has 3 variables, but is passed 1 argument.",
# SC2206: "Quote to prevent word splitting/globbing, or split robustly with mapfile or read -a.",
# SC2207: "Prefer mapfile or read -a to split command output (or quote to avoid splitting).",
# SC2317: "Command appears to be unreachable. Check usage (or ignore if invoked indirectly).",
# Usage: source in target script as shown below - assuming both have the same path
# myDir="$( dirname "$0" )"
# source "${myDir}/incl.sh"
# Unittest:
# bash incl.sh
MY_SRC="${BASH_SOURCE[0]}"
[ -n "$(which python3)" ] && PY="$(which python3)"
[ -z "$PY" ] && PY="$(which python)"
function log() {
# usage: export LOGLEVEL=TRACE|DEBUG|INFO|SUCCESS|WARNING|ERROR|CRITICAL ###
# Local log - colored
[ "$LOGLEVEL" == "TRACE" ] && LV=0
[ "$LOGLEVEL" == "DEBUG" ] && LV=1
[ "$LOGLEVEL" == "INFO" ] && LV=10
[ "$LOGLEVEL" == "SUCCESS" ] && LV=20
[ "$LOGLEVEL" == "WARNING" ] && LV=30
[ "$LOGLEVEL" == "ERROR" ] && LV=40
[ "$LOGLEVEL" == "CRITICAL" ] && LV=50
# Default: INFO level 10
[ -z "$LOGLEVEL" ] && LOGLEVEL='INFO' && LV=10
lv=$1; lv=$(( lv )); shift
[[ 0 -eq "$lv" && "$lv" -ge "$LV" ]] && echo -e "${Gray}TRACE${NC}: $*" >&2
[[ 1 -eq "$lv" && "$lv" -ge "$LV" ]] && echo -e "${Yellow}DEBUG${NC}: $*" >&2
[[ 10 -eq "$lv" && "$lv" -ge "$LV" ]] && echo -e "${Green}INFO${NC}: $*" >&2
[[ 20 -eq "$lv" && "$lv" -ge "$LV" ]] && echo -e "${Green}SUCCESS${NC}: $*" >&2
[[ 30 -eq "$lv" && "$lv" -ge "$LV" ]] && echo -e "${Red}WARNING${NC}: $*" >&2
[[ 40 -eq "$lv" && "$lv" -ge "$LV" ]] && echo -e "${Red}ERROR${NC}: $*" >&2 && exit 1
[[ 50 -eq "$lv" && "$lv" -ge "$LV" ]] && echo -e "${Red}CRITICAL${NC}: $*" >&2 && exit 1
true
return
}
function sLog() {
# usage: export LOGLEVEL=TRACE|DEBUG|INFO|SUCCESS|WARNING|ERROR|CRITICAL ###
# Sys log - no color
[ "$LOGLEVEL" == "TRACE" ] && LV=0
[ "$LOGLEVEL" == "DEBUG" ] && LV=1
[ "$LOGLEVEL" == "INFO" ] && LV=10
[ "$LOGLEVEL" == "SUCCESS" ] && LV=20
[ "$LOGLEVEL" == "WARNING" ] && LV=30
[ "$LOGLEVEL" == "ERROR" ] && LV=40
[ "$LOGLEVEL" == "CRITICAL" ] && LV=50
# Default: INFO level 10
[ -z "$LOGLEVEL" ] && LOGLEVEL='INFO' && LV=10
lv=$1; lv=$(( lv )); shift
[[ 0 -eq "$lv" && "$lv" -ge "$LV" ]] && echo -e "TRACE: $*" >&2
[[ 1 -eq "$lv" && "$lv" -ge "$LV" ]] && echo -e "DEBUG: $*" >&2
[[ 10 -eq "$lv" && "$lv" -ge "$LV" ]] && echo -e "INFO: $*" >&2
[[ 20 -eq "$lv" && "$lv" -ge "$LV" ]] && echo -e "SUCCESS: $*" >&2
[[ 30 -eq "$lv" && "$lv" -ge "$LV" ]] && echo -e "WARNING: $*" >&2
[[ 40 -eq "$lv" && "$lv" -ge "$LV" ]] && echo -e "ERROR: $*" >&2
[[ 50 -eq "$lv" && "$lv" -ge "$LV" ]] && echo -e "CRITICAL: $*" >&2 && exit 1
true
return
}
## Log Local - Color
function iTrace() { log 0 "$*"; }
function iDebug() { log 1 "$*"; }
function iInfo() { log 10 "$*"; }
function iSuccess() { log 20 "$*"; }
function iWarning() { log 30 "$*"; }
function iError() { log 40 "$*"; }
function iCritical() { log 50 "$*"; } # exit 1
## Log Sys - No Color
function sTrace() { sLog 0 "$*"; }
function sDebug() { sLog 1 "$*"; }
function sInfo() { sLog 10 "$*"; }
function sSuccess() { sLog 20 "$*"; }
function sWarning() { sLog 30 "$*"; }
function sError() { sLog 40 "$*"; }
function sCritical() { sLog 50 "$*"; } # exit 1
function getExitCode() {
local ec
ec="$?"
if [ 0 -eq "$ec" ]; then
iDebug "ExitCode: ${Green}${ec}${NC}"
else
iWarning "ExitCode: ${Red}${ec}${NC}"
fi
}
function getDir() {
# usage: returns current filr & folder data ###
SOURCE=${BASH_SOURCE[-1]}
while [ -L "$SOURCE" ]; do
DIR=$( cd -P "$( dirname "$SOURCE" )" >/dev/null 2>&1 && pwd )
SOURCE=$(readlink "$SOURCE")
[[ $SOURCE != /* ]] && SOURCE=$DIR/$SOURCE # resolve symlink
done
DIR=$( cd -P "$( dirname "$SOURCE" )" >/dev/null 2>&1 && pwd )
FileName=$(echo "$SOURCE" | tr '/' ' ' | awk '{print $NF}' )
Name=$( echo "$FileName" | tr '.' ' ' | awk '{print $1}' )
name=$(echo "$Name" | tr '\_' '-')
TITLES=$(echo "$Name" | tr '\-\_' ' ')
for r in $TITLES; do
Title+="${r^} "
done
echo "CWD': $(pwd)"
echo "Path': $( realpath -e -- "$DIR")"
echo "File': $SOURCE"
echo "FileName': $FileName"
echo "Name': $Name"
echo "Title: ${Title}"
}
function isCodeBuild() {
# usage: [ 0 -eq "$( isCodeBuild ) $?" ] && echo "True" || echo "False" ###
if [ -n "$CODEBUILD_BUILD_NUMBER" ]; then
true
return
else
false
return
fi
}
function isDebug() {
# usage: [ 0 -eq "$( isDebug ) $?" ] && echo "True" || echo "False" ###
if [[ -n "$LOGLEVEL" && "$LOGLEVEL" = "DEBUG" ]]; then
true
return
else
false
return
fi
}
function isTrace() {
# usage: [ 0 -eq "$( isTrace ) $?" ] && echo "True" || echo "False" ###
if [[ -n "$LOGLEVEL" && "$LOGLEVEL" = "TRACE" ]]; then
true
return
else
false
return
fi
}
## Print
function wline() {
# usage: wline ['-' 90 | 90] # print '-' 90 chars lenght ###
iTrace "L#$(( LINENO - 2 )) :: ${iYellow}${FUNCNAME[0]}()${NC} ${iCyan}${*}${NC}"
local i len char res
char='-'
len=90
res=''
# char len
if [ -n "$2" ]; then
char="$1"
len="$2"
# char or len
elif [ -n "$1" ]; then
if [ 0 -eq "$( isInt "$1" ) $?" ]; then
iDebug "$1 is an integer"
len="$1"
else
iDebug "$1 is not an integer"
char="$1"
fi
fi
for (( i=0; i<len; i++ )); do
res="${res}${char}"
done
echo "$res"
}
function spc() {
# usage: spc lenght # returns space to lenght ###
iTrace "L#$(( LINENO - 2 )) :: ${BASH_LINENO[*]}, ${iYellow}${FUNCNAME[0]}()${NC} ${iCyan}${*}${NC}"
local len res
len="$1"
[ 1 -eq "$(isInt "$len") $?" ] && iTrace "${len} is not an integer!" && return
while [ ${#res} -lt "${len}" ]; do res=" ${res}"; done
echo "$res"
}
function print_table() {
# Usage: [-t "$title"] [-i "$file"] [-l "$lines"] # prints file or lines as tabular data ###
iTrace "Line: $(( LINENO - 2 )), ${iYellow}${FUNCNAME[0]}()${NC} ${iCyan}${*}${NC}"
local WIDTH MAX_LINE_WIDTH COUNTER_WIDTH i TITLE FILE LINES MSG line
WIDTH=132 # Min wline WIdth
MAX_LINE_WIDTH="$WIDTH"
COUNTER_WIDTH=5 # row number width
EXTRA_WIDTH=4 # 4 = +2 for a dot and a space +2 extra
i=0
while [ $# -gt 0 ]; do
case $1 in
# kwqrgs
-t|--title)
TITLE="$2"
shift;shift;;
-f|--file)
FILE="$2"
shift;shift;;
-l|--lines)
LINES="$2"
shift;shift;;
*)
MSG="$1"
shift
;;
esac
done
[ -n "${TITLE}" ] && echo -e "${TITLE}"
# --file
if [[ -n "${FILE}" || -f "${FILE}" ]]; then
MAX_LINE_WIDTH=$( wc -L ${FILE} | awk '{print $1}' )
MAX_LINE_WIDTH=$(( MAX_LINE_WIDTH + COUNTER_WIDTH + EXTRA_WIDTH ))
[ "$MAX_LINE_WIDTH" -gt "$WIDTH" ] && WIDTH="$MAX_LINE_WIDTH"
wline $WIDTH
i=0
while read -r line; do
if [ '#' = "${line:0:1}" ]; then
echo -e "$( jstr -w $COUNTER_WIDTH -r "") ${Green}${line}${NC}"
continue
fi
i=$(( i + 1 ))
echo "$( jstr -w $COUNTER_WIDTH -r "$i"). ${line}"
done < "$FILE"
wline $WIDTH
fi
# --lines
if [ -n "${LINES}" ]; then
# get MAX_LINE_WIDTH
while read -r line; do
[ "${#line}" -gt "$WIDTH" ] && WIDTH="${#line}"
done < <( echo -e "$LINES" )
WIDTH=$(( WIDTH + COUNTER_WIDTH + EXTRA_WIDTH ))
wline $WIDTH
i=0
while read -r line; do
if [ '#' = "${line:0:1}" ]; then
echo -e "$( jstr -w $COUNTER_WIDTH -r "") ${Green}${line}${NC}"
continue
fi
i=$(( i + 1 ))
echo "$( jstr -w $COUNTER_WIDTH -r "$i"). ${line}"
done < <( echo -e "$LINES" )
wline $WIDTH
fi
[[ -n "${TITLE}" && "$i" -gt 50 ]] && echo -e "${TITLE}"
}
function ppwide() {
# Usage: [-b '-'] [-a '-'] [-w int] ['Message'] # prints bbb 'Message' aaa... # to w chars wide ###
iTrace "L#$(( LINENO - 2 )) :: ${iYellow}${FUNCNAME[0]}()${NC} ${iCyan}${*}${NC}"
local str before after color width message oneChar sStr
before=''
after=''
str='#'
width=90
while [ $# -gt 0 ]; do
case $1 in
# options
-b|--before)
before="$2"
shift;shift;;
-a|--after)
after="$2"
shift;shift;;
-c|--color)
color="$2"
shift;shift;;
-w|--width)
width="$2"
shift;shift;;
*)
message="$1"
shift
;;
esac
done
width=$(( width - 1 ))
rep="$(wline '#' "$width")"
[ -n "$message" ] && str="### $message"
[ -n "$before" ] && str=${str//#/$before}
[[ -n "$before" && -z "$after" ]] && after="${before}"
if [[ -n "$message" && 1 -eq "${#message}" ]]; then
oneChar=1
str="$message"
rep="#${rep}"
rep="$( echo "$rep" | tr "#" "$str" )"
elif [ -z "$message" ]; then
oneChar=1
rep="#${rep}"
str='#'
fi
[ -n "$before" ] && str=${str//#/$before}
[ -n "$after" ] && rep=${rep//#/$after}
sStr=$( echo -e "$str" | sed 's/\x1b\[[0-9;]*[a-zA-Z]//g' )
iTrace "--before '$before' --after '$after' --color '$color' --width ${width} '${sStr}'"
if [ -n "${!color}" ]; then
[ -n "$oneChar" ] && echo -e "${!color}${str}${!color}${rep:${#sStr}}${NC}" || echo -e "${!color}${str} ${!color}${rep:${#sStr}}${NC}"
else
[ -n "$oneChar" ] && echo -e "${str}${rep:${#sStr}}" || echo -e "${str} ${rep:${#sStr}}"
fi
}
function ppwider() {
ppwide -w 140 "$*"
}
function pyg_lexers() {
pygmentize -L "lexers" | grep ':' | tr -d '*:,' | tr -d '\n'
}
function pyg_styles() {
local CMD
CMD="
from pygments.styles import get_all_styles
for style in list(get_all_styles()):
print(style)
"
# shellcheck disable=SC2046,SC2005
echo $( $PY -c "$CMD" | tr '\n' ' ' )
}
function pyg_out() {
local lang code
lang='bash'
# args & kwargs parser
if [ -n "$2" ]; then
code="$2"
lang="$1"
else
code="$1"
fi
echo "$code" | pygmentize -l "$lang" -O style=monokai
}
# shellcheck disable=SC2304,SC2181,SC2034
AWSV=$( aws --version | grep 'aws-cli/2' )
# shellcheck disable=SC2304,SC2181,SC2034
[ 0 -eq $? ] && AWS_VERSION=2 || AWS_VERSION=1
# which shell
# zsh colors: \033, bash colors: \e
[ -n "$ZSH_VERSION" ] && Esc='\033' || Esc='\e'
# Color Usage:
# echo -e "${Green}Green Test${NC}"
# echo -e "${bGreen}Bold Green Test${NC}"
# echo -e "${iGreen}Italic GreenTest${NC}"
# echo -e "${uGreen}Underline Green Test${NC}"
# Reset
function set_color() {
# ussage: set colors for echo -e "..." & printf ###
# printf colors
# A hack fix to avoid codebuild terminal error:
# tput: No value for $TERM and no -T specified
if [ -z "$CODEBUILD_BUILD_NUMBER" ]; then
NORMAL=$(tput sgr0)
BLACK=$(tput setaf 0)
RED=$(tput setaf 1)
GREEN=$(tput setaf 2)
YELLOW=$(tput setaf 3)
LIME_YELLOW=$(tput setaf 190)
POWDER_BLUE=$(tput setaf 153)
BLUE=$(tput setaf 4)
MAGENTA=$(tput setaf 5)
CYAN=$(tput setaf 6)
WHITE=$(tput setaf 7)
BRIGHT=$(tput bold)
BLINK=$(tput blink)
REVERSE=$(tput smso)
UNDERLINE=$(tput smul)
fi
# which shell
# zsh colors: \033, bash colors: \e
[ -n "$ZSH_VERSION" ] && Esc='\033' || Esc='\e'
# Color Usage:
# echo -e "${Green}Green Test${NC}"
# echo -e "${bGreen}Bold Green Test${NC}"
# echo -e "${iGreen}Italic GreenTest${NC}"
# echo -e "${uGreen}Underline Green Test${NC}"
NC="${Esc}[0m" # Text Reset
# 0: Normal Colors
Black="${Esc}[0;30m" # Black
Gray="${Esc}[0;90m" # Gray
Red="${Esc}[0;91m" # Red
Green="${Esc}[0;92m" # Green
Yellow="${Esc}[0;93m" # Yellow
Blue="${Esc}[0;94m" # Blue
Magenta="${Esc}[0;95m" # Magenta
Cyan="${Esc}[0;96m" # Cyan
White="${Esc}[0;97m" # White
# Extended Normal Colors
Brown="${Esc}[38;5;136m" # Brown
Orange="${Esc}[38;5;208m" # Orange
Lemon="${Esc}[38;5;48m" # Lemon
Rose="${Esc}[38;5;160m" # Rose
Pink="${Esc}[38;5;200m" # Pink
# 1: Bold Colors
bBlack="${Esc}[1;30m" # Black
bGray="${Esc}[1;90m" # Gray
bRed="${Esc}[1;91m" # Red
bGreen="${Esc}[1;92m" # Green
bYellow="${Esc}[1;93m" # Yellow
bBlue="${Esc}[1;94m" # Blue
bMagenta="${Esc}[1;95m" # Magenta
bCyan="${Esc}[1;96m" # Cyan
bWhite="${Esc}[1;97m" # White
# 3: Italic Colors
iBlack="${Esc}[3;30m" # Black
iGray="${Esc}[3;90m" # Gray
iRed="${Esc}[3;91m" # Red
iGreen="${Esc}[3;92m" # Green
iYellow="${Esc}[3;93m" # Yellow
iBlue="${Esc}[3;94m" # Blue
iMagenta="${Esc}[3;95m" # Magenta
iCyan="${Esc}[3;96m" # Cyan
iWhite="${Esc}[3;97m" # White
# 4: Underline Colors
uBlack="${Esc}[4;30m" # Black
uGray="${Esc}[4;90m" # Gray
uRed="${Esc}[4;91m" # Red
uGreen="${Esc}[4;92m" # Green
uYellow="${Esc}[4;93m" # Yellow
uBlue="${Esc}[4;94m" # Blue
uMagenta="${Esc}[4;95m" # Magenta
uCyan="${Esc}[4;96m" # Cyan
uWhite="${Esc}[4;97m" # White
}
set_color
function list_colors() {
local COLORS bCOLORS iCOLORS uiCOLORS
COLORS=( Black Gray Red Green Yellow Blue Magenta Cyan White )
eCOLORS=( Brown Orange Lemon Rose Pink )
bCOLORS=( bBlack bGray bRed bGreen bYellow bBlue bMagenta bCyan bWhite )
iCOLORS=( iBlack iGray iRed iGreen iYellow iBlue iMagenta iCyan iWhite )
uCOLORS=( uBlack uGray uRed uGreen uYellow uBlue uMagenta uCyan uWhite )
ppwide -b '-' "Colors & Styles / ${Yellow}echo${NC} ${Blue}-e${NC}"
# shellcheck disable=SC2016
echo -e 'Usage: echo -e "${Blue}Message${NC} ${bBlue}Message${NC} ${iBlue}Message${NC} ${uBlue}Message${NC}"'
wline
w=8
echo;echo -e -n "Normal : "
for COLOR in "${COLORS[@]}"; do
COLOR_ID=$(jstr -w "${w}" "${COLOR}")
echo -e -n "${!COLOR}${COLOR_ID}${NC} "
done
echo;echo -e -n "Extended : "
for COLOR in "${eCOLORS[@]}"; do
COLOR_ID=$(jstr -w "${w}" "${COLOR}")
echo -e -n "${!COLOR}${COLOR_ID}${NC} "
done
echo;echo -e -n "Bold : "
for COLOR in "${bCOLORS[@]}"; do
COLOR_ID=$(jstr -w "${w}" "${COLOR}")
echo -e -n "${!COLOR}${COLOR_ID}${NC} "
done
echo;echo -e -n "Italic : "
for COLOR in "${iCOLORS[@]}"; do
COLOR_ID=$(jstr -w "${w}" "${COLOR}")
echo -e -n "${!COLOR}${COLOR_ID}${NC} "
done
echo;echo -e -n "Underline : "
for COLOR in "${uCOLORS[@]}"; do
COLOR_ID=$(jstr -w "${w}" "${COLOR}")
echo -e -n "${!COLOR}${COLOR_ID}${NC} "
done
echo
echo -e "Reset : NC"
# printf
echo
ppwide -b '-' "Colors & Styles / ${Yellow}printf${NC}"
# shellcheck disable=SC2016,SC2028
echo 'Usage: printf '%s\\n' ${STYLE}${COLOR}Message${NORMAL}'
# shellcheck disable=SC2016,SC2028
echo 'Usage: printf '%s\\n' ${COLOR}Message${NORMAL} # if no STYLE given defaults to NORMAL'
wline
local PCOLORS PSTYLES COL_WIDTH SPC COL_DATA
PSTYLES=( NORMAL BRIGHT BLINK REVERSE UNDERLINE )
PCOLORS=( BLACK RED GREEN YELLOW LIME_YELLOW POWDER_BLUE BLUE MAGENTA CYAN WHITE )
COL_WIDTH="%-9s : %s\n"
printf "$COL_WIDTH" "Style" "Colors for printf"
wline
SPC=' '
for STYLE in "${PSTYLES[@]}"; do
COL_DATA=''
for COLOR in "${PCOLORS[@]}"; do
COLOR_ID="${COLOR}"
COL_DATA="${COL_DATA}${SPC}${!STYLE}${!COLOR}${COLOR_ID}${NORMAL}"
done
printf "$COL_WIDTH" "$STYLE" "$COL_DATA"
done
echo -e "Reset : NORMAL"
}
function ansi_colors() {
local i iStr
for i in {0..255}; do
iStr=$(ndigits "$i")
echo -e -n "${Esc}[38;5;${i}m ${iStr}. Test ${NC}"
[[ 0 -eq $(( i % 8 )) ]] && echo
done
echo
}
### Str, Int & Array
function clean_path() {
# usage: returns removed '../' from middle of given absolute path###
path="$1"
$PY -c "
path = '$1'
paths = path.split('/')
while '..' in paths:
if paths[0] == '..': break
for i, path in enumerate(paths):
if path == '..' and i > 0:
try:
paths.pop( i )
paths.pop( i - 1 )
except Exception:
pass
res = '/'.join(paths)
print(res)
"
}
function fmtInt() {
# usage: int [decimal] returns thousands comma separated int [with given decimal] ###
local num decimal
num="$1"
[ -n "$2" ] && decimal="$2" || decimal=0
$PY -c "num=$num;decimal=$decimal;print(f'{num:,.{decimal}f}')"
}
function dedent() {
# usage: returns remove leading spaces of input lines ###
echo "$1" | sed 's/^[[:space:]]*//'
}
function int_fmt() {
# usage: print $int with thousands separator ###
[ 0 -eq "$(isInt "$1") $?" ] && $PY -c "num=$1;print(f'{num:,}')"
}
function s2n() {
# usage: returns one char per line for ascii value of all chars input ###
printf '%s' "$1" | awk -l ordchar -v RS='.{1}' '{s+ord(RT)} END{print s+0}'
}
function inarr() {
# usage: [ 0 -eq "$( inarr "needle" "${arr[@]}" ) $?" ] && echo "True" || echo "False" ###
local ne arr
ne=$1; shift
# shellcheck disable=SC2206
arr=( $* )
for k in "${arr[@]}";do
if [ "$k" = "$ne" ]; then
true
return
fi
done
false
return
}
function isInt() {
# usage: [ 0 -eq "$(isInt "$chk") $?" ] && echo true || echo false ###
iTrace "L#$(( LINENO - 2 )) :: ${iYellow}${FUNCNAME[0]}()${NC} ${iCyan}${*}${NC}"
if [[ "$1" =~ ^[0-9]+$ ]]; then
iTrace "$1 is an integer"
true
return
else
iTrace "$1 is not an integer!"
false
return
fi
}
function title_case() {
# usage: "$text" # returns Title Case ###
iTrace "L#$(( LINENO - 2 )) :: ${iYellow}${FUNCNAME[0]}()${NC} ${iCyan}${*}${NC}"
"$PY" -c "print('$*'.title())"
}
function ltrim() {
# usage: returns right trimed ###
# shellcheck disable=SC2317
echo "$*" | sed 's/^ *//'
}
function ltrim() {
# usage: returns left trimed ###
echo "$*" | sed 's/ *$//'
}
function trim() {
# usage: returns left & right trimed whitespace ###
# echo "$*" | sed 's/^ *//' | sed 's/ *$//'
echo "$*" | awk '{$1=$1};1'
}
function strip() {
# usage: returns left & right trimed whitespace ###
echo "$*" | awk '{$1=$1};1'
}
function prcnt() {
# usage: percent 5.2 10 # returns 52.00% ###
local chk total res
chk="$1"
total="$2"
$PY -c "print(float(format($chk/$total*100, '.2f')))"
}
function get_maxlen() {
# usage: get_maxlen "abc "abc abcdf abcdef" # returns 6 ###
local maxLen ele
maxLen=0
for ele in $1; do
[[ "${#ele}" -ge "$maxLen" ]] && maxLen=${#ele}
done
return "$maxLen"
}
function camel2() {
# usage: [-|_] "$CamelCase" # - returns spinal case, _ returns snake case ###
local r="$1"
local str="$2"
local CMD="
res = ''
str = '$str'
for i in str:
if i.isupper(): res += '$r'
res += i.lower()
print(res[1:])
"
"$PY" -c "$CMD"
}
function snake2camel() {
# usage: snake_text_to_test # returns SnakeTextToTest ###
"$PY" -c "print('$1'.replace('-',' ').replace('_',' ').title().replace(' ',''))"
}
function spinal2camel() {
# usage: spinal-text-to-test # returns SpinalTextToTest ###
"$PY" -c "print('$1'.replace('-',' ').replace('_',' ').title().replace(' ',''))"
}
function camel2snake() {
# usage: SnakeTextToTest # returns snake_text_to_test ###
camel2 '_' "$1"
}
function camel2spinal() {
# usage: SpinalTextToTest # returns spinal-text-to-test ###
camel2 '-' "$1"
}
function snake2title() {
# usage: snake_text_to_test # returns Snake Text To Test ###
"$PY" -c "print('$1'.replace('-',' ').replace('_',' ').title())"
}
function spinal2title() {
# usage: spinal-text-to-test # returns Spinal Text To Test ###
"$PY" -c "print('$1'.replace('-',' ').replace('_',' ').title())"
}
function ndigits() {
# usage: ndigits "int" [digits] # echo left zero str ###
iTrace "L#$(( LINENO - 2 )) :: ${iYellow}${FUNCNAME[0]}()${NC} ${iCyan}${*}${NC}"
local int digits
int="$1"
digits=3
[ -n "$2" ] && digits="$2" && shift;
[ "${#int}" -gt "$digits" ] && echo "$int" && return
for (( i=${#int};i<$digits; i++ )); do
int="0${int}"
done
echo "$int"
}
function press_any_key() {
read -n 1 -s -r -p "Press any key to continue ... "
}
function goNoGoCheck() {
# usage: [$message] # shows a message and waits for user y/n input then retunes 0 for go ###
local message key
message='Do you want to proceed'
[ -n "$1" ] && message="$1"
read -n 1 -s -r -p "${message}? Y/n " key
if [ 'y' = "$key" ] || [ 'Y' = "$key" ]; then
echo 0
else
echo 1
fi
}
function goNoGo() {
# usage: shows Go/no-go message and waits for user y/n input ###
local key
read -n 1 -s -r -p "Do you want to proceed? Y/n " key
echo
if [ 'y' = "$key" ] || [ 'Y' = "$key" ]; then
true
return
else
exit 1
fi
}
function is_int() {
# usage: [ 0 -eq "$( is_int ) $?" ] && echo "True" || echo "False" ###
isInt "$*"
}
function jstr-help() {
echo "Justify String"
wline
echo "args:"
echo " -h show this help and exit"
echo " -c --center center align"
echo " -l --left left align, default"
echo " -r --right right align"
echo " -w --width final width"
}
function jstr() {
# usage [-l|-c|-r] -w "int" "Message" # return justified to -w lenght ###
local args align width str
iTrace "Given: $*"
args=()
align='left'
while [ $# -gt 0 ]; do
case "$1" in
### start custom parameter checks
-l|--left)
align='left'
shift;;
-c|--center)
align='center'
shift;;
-r|--right)
align='right'
shift;;
-w|--width)
width="$2"
shift;shift;;
### end custom parameter checks
-h|--help)
jstr-help
return;;
-|--)
while [ $# -gt 0 ]; do args+=("$1"); shift; done;
break;;
--*)
echo "**Bad parameter: $1**" >&2
jstr-help
exit 1
;;
*)
str="$1"
args+=("$1");
shift;;
esac
done
iTrace "Print: ${Green}--width ${width}${NC} ${Blue}--${align}${NC} ${Yellow}${str}${NC}"
[ -z "$width" ] && iTrace "Missing required arg -w or --width" && exit 1
# process
if [ 'left' = "$align" ]; then
while [ ${#str} -lt "$width" ]; do str="$str "; done
iTrace "${Blue}'${str}'${NC}"
elif [ 'center' = "$align" ]; then
while [ "${#str}" -lt "$width" ]; do str=" $str "; done
iTrace "${Green}'${str}'${NC}"
elif [ 'right' = "$align" ]; then
while [ ${#str} -lt "$width" ]; do str=" $str"; done
iTrace "${Red}'${str}'${NC}"
fi
echo "${str}"
}
## Date, Time
function get_dt() {
date +%FT%R:%S.%6N
}
function get_ts() {
# Formats: +%s.%3N +%s.%6N +%s.%9N +%s.%12N or +%s.%N
date +%s.%6N
}
function iso_dt() {
date +%Y-%m-%dT%H:%M:%S%:z
}
function took_ts() {
if [ -n "$1" ]; then
local ts now took
ts=$1
now="$( date +%s.%6N )"
$PY -c "print(float(format($now - $ts, '.6f')))"
fi
}
function demo_ts() {
local ts took
ts=$( get_ts )
sleep 0.234567
took=$( took_ts "${ts}" )
echo "${took}"
}
function get_fmtdate() {
# usage: [-f] # returns full human readable date with -f, or prints brief data ###
[ -n "$1" ] && date '+%A %d %B %Y %H:%M:%S.%3N %z %Z' || date '+%a %d-%b-%Y %H:%M:%S'
}
function dt2ts() {
date --date="${1}" +"%s"
}
function ts2dt() {
date -d "@${1}" +%FT%R:%S%:z
}
function timeit() {
echo "$( get_ts ) ${1}"
}
function timedelta_mhsm() {
secs="${1}"
# shellcheck disable=SC2046,SC2183
printf '%02d:%02d:%06.3f\n' $($PY -c "print(int($secs/3600));print(int($secs%3600/60));print(float(format($secs%60,'.6f')))")
}
function set_timer() {
[ ! -r "$TIMER_FILE" ] && TIMER_FILE=$( mktemp )
echo "$( get_ts ) ${1}" >> "${TIMER_FILE}"
}
function rm_timer() {
rm -rf "${TIMER_FILE}"
}
function get_timer() {
# usage: [width] # int of table width, default 90 ###
[ ! -r "${TIMER_FILE}" ] && return
local tsArr=()
local width=132
[ -n "$1" ] && width="$1"
while read -r line; do
tsArr+=( "${line}" )
done < "${TIMER_FILE}"
local total=0
local i=0
local HEAD_COLS="%3s %-15s %-12s %-s\n"
local ROWS_COLS="%3s %-15s %-12s %-s\n"
local FOOT_COLS="%3s %-15s %-12s %-s\n"
local old_ts=0
local t=''
local cur_ts=0
local desc=''
local took=0
local total=0
local took_str=''
local total_str=''
# shellcheck disable=SC2059
printf "$HEAD_COLS" " " "Took" "Total Time" "Description"
wline "$width"
for t in "${tsArr[@]}"; do
# shellcheck disable=SC2004
i=$(( $i+1 ))
cur_ts=$( echo "${t}" | awk '{ print $1 }' )
desc=$( echo "${t}" | awk '{$1=""; print $0}' )
[ 1 -eq "$i" ] && old_ts="${cur_ts}" # for first is init with 0 time elapsed
took=$( $PY -c "print($cur_ts - $old_ts)" )
total=$( $PY -c "print($total + $took)" )
took_str=$( timedelta_mhsm "$took" )
total_str=$( timedelta_mhsm "$total" )
# shellcheck disable=SC2059
printf "$ROWS_COLS" "${i}." "$took_str" "$total_str" "${desc}"
old_ts=$( echo "${t}" | awk '{ print $1 }') # last ts woud be start of next duration
done
# shellcheck disable=SC2059
wline "$width"
printf "$HEAD_COLS" " " "Took" "Total Time" "Description"
wline "$width"
printf "$FOOT_COLS" " " "$total_str" "$total_str" " "
}
### AWS
function boto2cli() {
# boto2cli [securityhub] get_administrator_account -> [securityhub] get-administrator-account
[ -n "$2" ] && echo -n "${1,,} " && shift
echo "$1" | tr '_' '-'
}
function boto2iam() {
# boto2iam [securityhub] get_administrator_account -> [securityhub:]GetAministratorAccount
[ -n "$2" ] && echo -n "${1,,}:" && shift
snake2camel "$1"
}
function cli2boto() {
# cli2boto get-administrator-account -> get_administrator_account
[ -n "$2" ] && shift
echo "$1" | tr '-' '_'
}
function cli2iam() {
# cli2iam [securityhub] get-administrator-account -> [securityhub:]GetAministratorAccount
[ -n "$2" ] && echo -n "${1,,}:" && shift
spinal2camel "$1"
}
function iam2boto() {
# iam2boto [securityhub:]GetAministratorAccount -> [securityhub ]get_administrator_account
local arg svc
arg="$1"
if [[ "$1" == *":"* ]]; then
svc=$( echo "${1,,}" | tr ':' ' ' | awk '{print $1}' )
arg=$( echo "$1" | tr ':' ' ' | awk '{print $2}' )
iTrace "svc: $svc"
iTrace "arg: $arg"
echo -n "$svc "
fi
camel2snake "$arg"
}