This repository has been archived by the owner on Oct 17, 2020. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathshttp
3731 lines (3484 loc) · 102 KB
/
shttp
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
# Simple HTTP API development environment.
# -author Giovanni Farfan B.
set -euo pipefail
IFS=$'\n\t'
# Help content.
_shttp_help_content=(
""
" Simple HTTP API development environment by command line."
""
" Usage: ./<file>[.sh] <command> [<manage-option>]* [<request-option>]*"
""
" [--help] [<add-on-option>]*"
""
" Manage options:"
" --list: Displays the <command> list (all functions defined into main script)"
" --envs: Displays all environments based on configuration files"
" --copy <env-from> <env-to>: Copies the environment configuration and credentials files. Must exist the 'from'"
" configuration files. If already exist the 'to' files those will be replaced."
" If is required to copy from 'default' environment, the first parameters must"
" contain 'default'"
" --del <env>: Removes the selected environment: configuration and credentials files. If is"
" required to remove 'default' environment, the parameter must contain 'default'"
" --get <key-name>: Displays the config value by key from 'ws/config[.<env>].json'"
" --add <key-name> <value> <sec>: Adds new key-value to 'ws/config[.<env>].json'"
" <sec>:"
" -h: hidden mode, in 'ws/.vlt'"
" -s: public mode, in 'ws/config[.<env>].json'"
" --remove <key-name>: Removes the key-value from 'ws/config[.<env>].json'"
" --keys: Displays all keys from 'ws/config[.<env>].json' file"
" --part <part> <value> <desc>: Adds new credential part to 'ws/credentials[.<env>].json' and 'ws/.vlt' (hidden)."
" Credential option is required ('--cred') to execute correctly."
" <part>:"
" -u: 'username' alias"
" -p: 'password' alias"
" -e: 'type' alias"
" -t: 'token' alias"
" -k: 'key' alias"
" -c: 'client' alias"
" -s: 'secret' alias"
" -i: 'pin' alias"
" <desc>: (optional) Description of the credential part"
" --creds: Displays all credentials ids from 'ws/credentials[.<env>].json'"
" --cred-keys <credential>: Displays all keys from 'ws/credentials[.<env>].json' file for a specific credential"
" --clean: Cleans up all output files 'output/*'"
""
" Request options:"
" --env <env>: Sets the environment for script by changing configuration and credentials files:"
" 'ws/config[.<env>].json' and 'ws/credentials[.<env>].json'"
" --cred <credential>: Set the credential for script by updating '_shttp_auth_credential"
" --curl <body-opt> Displays the related cURL command for the input <command>"
" <body-opt>:"
" -f: show the body as filename only"
" -c: show the body as content"
" --set <key-name> <value>: Sets a temporal key-value config. This won't saved to 'ws/config[.<env>].json'"
" --local <port>: Sets variables to local execution:"
" '_shttp_protocol=http'"
" '_shttp_domain=localhost:<port>' (default 80)"
" --port <port>: Sets value to port variable"
" --auth-basic <credential>: Sets mode to '_shttp_auth_mode=BASIC' and assign the credential"
" --auth-token <credential>: Sets mode to '_shttp_auth_mode=TOKEN' and assign the credential"
" --auth-skip: Sets mode to '_shttp_auth_mode=SKIP' when authorization mode is not required"
" --times <value>: Sets the number of executions required for the request in '_shttp_request_times'"
" --open: Sets '_shttp_editor_command' with value defined on 'editorCommand'"
" from 'ws/settings.json'. This causes to execute '_shttp_editor_command'"
" --mock: Sets to enable the mock flag '_shttp_mock_enabled'"
" Manual options:"
" --help: Displays this help message"
""
" Environment variables:"
" SAVED_LOGS: 'true' for saved logs on '/tmp/_shttp_basename.yyyy-mm-dd.log'"
" otherwise logs only will print by 'echo' function"
" DEBUG_MODE: 'true' for show default debug logs for internal functions"
" otherwise debug log is skipped"
" CHECK_DEPENDENCIES: 'true' for check if 'cURL' or 'jq' are already installed"
" otherwise check is skipped"
" Add-on options: "
)
# Script filename.
readonly _shttp_basename=$( basename "$0" )
# ---------- External configuration
SAVED_LOGS=${SAVED_LOGS:-"false"}
DEBUG_MODE=${DEBUG_MODE:-"false"}
CHECK_DEPENDENCIES=${CHECK_DEPENDENCIES:-"false"}
# ---------- Logging functions
if [ "$SAVED_LOGS" == "true" ]; then
# Log filename.
readonly _shttp_log_file="/tmp/shTTP_${_shttp_basename%.*}.$( date '+%Y-%m-%d' ).log"
# Logs a message with the INFO level.
# No test required.
#
# -param $* Log message
# shellcheck disable=SC2086
info() { echo "$( date '+%Y-%m-%d %T.%N' ) INFO $*" | tee -a "$_shttp_log_file" >&2 ; }
# Logs a message with the WARNING level.
# No test required.
#
# -param $* Log message
# shellcheck disable=SC2086
warn() { echo "$( date '+%Y-%m-%d %T.%N' ) WARNING $*" | tee -a "$_shttp_log_file" >&2 ; }
# Logs a message with the ERROR level.
# No test required.
#
# -param $* Log message
# shellcheck disable=SC2086
error() { echo "$( date '+%Y-%m-%d %T.%N' ) ERROR $*" | tee -a "$_shttp_log_file" >&2 ; }
# Logs a message with the FATAL level,
#+ exit execution with 1.
# No test required.
#
# -param $* Log message
# shellcheck disable=SC2086
fatal() { echo "$( date '+%Y-%m-%d %T.%N' ) FATAL $*" | tee -a "$_shttp_log_file" >&2 ; exit 1 ; }
if [ "$DEBUG_MODE" == "true" ]; then
# Logs a message with the DEBUG level.
# No test required.
#
# -param $* Log message
# shellcheck disable=SC2086
debug() { echo "$( date '+%Y-%m-%d %T.%N' ) DEBUG $*" | tee -a "$_shttp_log_file" >&2 ; }
else
debug() { :; }
fi
else
info() { echo "$( date '+%Y-%m-%d %T.%N' ) INFO $*" ; }
warn() { echo "$( date '+%Y-%m-%d %T.%N' ) WARNING $*" ; }
error() { echo "$( date '+%Y-%m-%d %T.%N' ) ERROR $*" ; }
fatal() { echo "$( date '+%Y-%m-%d %T.%N' ) FATAL $*" ; exit 1 ; }
if [ "$DEBUG_MODE" == "true" ]; then
debug() { echo "$( date '+%Y-%m-%d %T.%N' ) DEBUG $*" ; }
else
debug() { :; }
fi
fi
# ---------- Initialization
if [ "$CHECK_DEPENDENCIES" == "true" ]; then
# 'cURL' is required
readonly _curl_version=$( curl --version )
if [ -z "$_curl_version" ]; then
fatal "'curl' is not installed yet"
else
info "Installed 'curl': $_curl_version"
fi
# 'jq' (command-line JSON processor)
#+ is required
#+ https://github.com/stedolan/jq
readonly _jq_version=$( jq --version )
if [ -z "$_jq_version" ]; then
warn "'jq' is not installed yet, JSON processing will not work"
else
info "Installed 'jq': $_jq_version"
fi
fi
# Output directory for trace and
#+ results files
if ! [ -d output ]; then
mkdir output || fatal "Imposible to create 'output' directory"
fi
# Output directory for execution
#+ history.
if ! [ -d hist ]; then
mkdir hist || fatal "Imposible to create 'hist' directory"
fi
# Workspace directory for data
#+ execution
if ! [ -d ws ]; then
mkdir ws || fatal "Imposible to create 'ws' directory"
fi
# Default configuration JSON file
if ! [ -f "ws/config.json" ]; then
echo '{ }' > "ws/config.json"
fi
# Default settings JSON file
if ! [ -f "ws/settings.json" ]; then
echo '{ "editorCommand": null }' > "ws/settings.json"
fi
# Default credentials JSON file
if ! [ -f "ws/credentials.json" ]; then
echo '[{
"id": "credential-identifier",
"username": "Field for credential [username]",
"password": "Field for credential [password]",
"type": "Field for credential [type], possible values: Basic, token, Bearer, HMAC, ...",
"token": "Field for credential [token]",
"key": "Field for credential [key]",
"client": "Field for credential [client]",
"secret": "Field for credential [secret]",
"pin": "Field for credential [pin]"
}]' > "ws/credentials.json"
fi
# Override JSON file
if [ -f "ws/.override.json.tmp" ]; then
rm -f "ws/.override.json.tmp"
fi
echo '{ }' > "ws/.override.json.tmp"
# ---------- Util functions
# Reverses the string input.
#
# -param $1 String input
# -return Reversed string
str_rev() {
local _input=${1:-}
local _rev=""
# shellcheck disable=SC2145
debug "[str_rev] ${*}"
for (( _input_idx=${#_input}-1; _input_idx>=0; _input_idx-- )); do
_rev="$_rev${_input:$_input_idx:1}"
done
debug "[str_rev] $_rev"
echo "$_rev"
}
# Generates a random string
#+ value with specified length.
#
# -param $1 Required string
#+ length
# -return Random string
str_rnd() {
local _length=${1:-10}
local _val=""
debug "[str_rnd] ${*}"
_val=$( < /dev/urandom tr -dc 'a-zA-Z0-9' \
| fold -w "$_length" \
| head -n 1 )
debug "[str_rnd] $_val"
echo "$_val"
}
# Joins the elements of the
#+ array in a single string.
#
# -param $1 Delimiter
# -param $* Elements
# -return Single string
arr_join() {
debug "[arr_join] ${*}"
local d=$1; shift; echo -n "$1"; shift; printf "%s" "${@/#/$d}"
}
# Returns 1 if the argument string is
#+ contained in the array. The evaluation
#+ is by the pattern: '*string*'.
# The evaluation ignores case sensitivity.
#
# -param $1 Search input
# -param $* Elements
# -return 1 if string exists
#+ otherwise 0
arr_like() {
local _string="$1"
debug "[arr_like] ${*}"
shift
local _arr=( $@ )
local _found=0
shopt -s nocasematch
case "${_arr[@]}" in *"$_string"*) _found=1 ;; esac
shopt -u nocasematch
debug "[arr_like] $_found"
echo "$_found"
}
# Gets a random value from
#+ an array.
#
# -param $* Elements
# -return Random element
arr_rnd() {
local _arr=( $@ )
local _length=${#_arr[@]}
local _val=""
debug "[arr_rnd] ${*}"
_val="${_arr[$((0 + RANDOM % _length))]}"
debug "[arr_rnd] $_val"
echo "$_val"
}
# Gets a random boolean.
#
# -return true or false
bool_rnd() {
local _values=( true false )
local _val=""
debug "[bool_rnd] ${*}"
_val="${_values[$((0 + RANDOM % 2))]}"
debug "[bool_rnd] $_val"
echo "$_val"
}
# Generates a random number.
#
# -param $1 Max digits
# -param $2 Max decimals
# -param $3 Negatives flag
# 0: only positives
# 1: only negatives
# otherwise: positives and
#+ negatives
# -return Random number
num_rnd() {
local _digits=${1:-1}
local _decimals=${2:-0}
local _negatives=${3:-0}
local _sign=""
local _val=""
debug "[num_rnd] ${*}"
case "$_negatives" in
0) ;;
1) _sign="-" ;;
*) (( $((0 + RANDOM % 2)) == 1 )) && _sign="-" ;;
esac
if (( _decimals > 0 )); then
_val="$_sign${RANDOM:0:$_digits}.${RANDOM:0:$_decimals}"
else
_val="$_sign${RANDOM:0:$_digits}"
fi
debug "[num_rnd] $_val"
echo "$_val"
}
# Addition arithmetic operation.
#
# -param $1 Number A
# -param $2 Number B
# -return Addition result
num_add() {
local _val=""
debug "[num_add] ${*}"
_val=$( echo "[${1:-0}, ${2:-0}]" | jq ".[0] + .[1]" )
debug "[num_add] $_val"
echo "$_val"
}
# Subtraction arithmetic operation.
#
# -param $1 Minuend
# -param $2 Subtrahend
# -return Difference result
num_subtract() {
local _val=""
debug "[num_subtract] ${*}"
_val=$( echo "[${1:-0}, ${2:-0}]" | jq ".[0] - .[1]" )
debug "[num_subtract] $_val"
echo "$_val"
}
# Multiplication arithmetic operation.
#
# -param $1 Multiplicand
# -param $2 Multiplier
# -return Multiplication result
num_multiply() {
local _val=""
debug "[num_multiply] ${*}"
_val=$( echo "[${1:-0}, ${2:-0}]" | jq ".[0] * .[1]" )
debug "[num_multiply] $_val"
echo "$_val"
}
# Division arithmetic operation.
#
# -param $1 Dividend
# -param $2 Divisor
# -return Division result
num_divide() {
local _val=""
debug "[num_divide] ${*}"
_val=$( echo "[${1:-0}, ${2:-0}]" | jq ".[0] / .[1]" )
debug "[num_divide] $_val"
echo "$_val"
}
# Modulo operation.
#
# -param $1 Dividend
# -param $2 Divisor
# -return Reminder of division
num_modulo() {
local _val=""
debug "[num_modulo] ${*}"
_val=$( echo "[${1:-0}, ${2:-0}]" | jq ".[0] % .[1]" )
debug "[num_modulo] $_val"
echo "$_val"
}
# Gets a now timestamp in milliseconds.
#+ It is possible the timestamp by using
#+ terms tags, e.g.: +5D (adds 5 days)
#
# -param $1 Addition/Subtraction term '[+|-]<num>[s|m|h|D|W|M|Y]':
# s: seconds
# m: minutes
# h: hours
# D: days
# W: weeks
# M: months
# Y: years
# -return Milliseconds timestamp
now_ms() {
local _term=${1:-"0s"}
local _is_subtract=0
local _extra=0
local _now=0
debug "[now_ms] ${*}"
if [[ "$_term" == "-*" ]]; then
_term=${_term:1:${#_term}-1}
_is_subtract=1
elif [[ "$_term" == "+*" ]]; then
_term=${_term:1:${#_term}-1}
fi
case "$_term" in
*s) _extra=$( num_multiply "${_term::-1}" 1000 );;
*m) _extra=$( num_multiply "${_term::-1}" 60000 );;
*h) _extra=$( num_multiply "${_term::-1}" 3600000 );;
*D) _extra=$( num_multiply "${_term::-1}" 86400000 );;
*W) _extra=$( num_multiply "${_term::-1}" 604800000 );;
*M) _extra=$( num_multiply "${_term::-1}" 2629800000 );;
*Y) _extra=$( num_multiply "${_term::-1}" 31557600000 );;
esac
_now=$( date '+%s%N' | cut -b1-13 )
if (( _is_subtract == 0 )); then
_now=$( num_add "$_now" "$_extra" )
else
_now=$( num_subtract "$_now" "$_extra" )
fi
debug "[now_ms] $_now"
echo "$_now"
}
# Less than (<) operator.
#
# -param $1 Value A
# -param $2 Value B
# -return true if A is less than B
#+ otherwise false
lt() {
local _val=""
debug "[lt] ${*}"
_val=$( echo "[${1:-}, ${2:-}]" | jq ".[0] < .[1]" )
debug "[lt] $_val"
echo "$_val"
}
# Less than (<) operator for strings.
#
# -param $1 Value A
# -param $2 Value B
# -return true if A is less than B
#+ otherwise false
lt_str() {
local _val=""
debug "[lt_str] ${*}"
_val=$( echo "[\"${1:-}\", \"${2:-}\"]" | jq ".[0] < .[1]" )
debug "[lt_str] $_val"
echo "$_val"
}
# Less than or equals to (<=) operator.
#
# -param $1 Value A
# -param $2 Value B
# -return true if A is less than or equals to B
#+ otherwise false
lte() {
local _val=""
debug "[lte] ${*}"
_val=$( echo "[${1:-}, ${2:-}]" | jq ".[0] <= .[1]" )
debug "[lte] $_val"
echo "$_val"
}
# Less than or equals to (<=) operator for strings.
#
# -param $1 Value A
# -param $2 Value B
# -return true if A is less than or equals to B
#+ otherwise false
lte_str() {
local _val=""
debug "[lte_str] ${*}"
_val=$( echo "[\"${1:-}\", \"${2:-}\"]" | jq ".[0] <= .[1]" )
debug "[lte_str] $_val"
echo "$_val"
}
# Greater than (>) operator.
#
# -param $1 Value A
# -param $2 Value B
# -return true if A is greater than B
#+ otherwise false
gt() {
local _val=""
debug "[gt] ${*}"
_val=$( echo "[${1:-}, ${2:-}]" | jq ".[0] > .[1]" )
debug "[gt] $_val"
echo "$_val"
}
# Greater than (>) operator for strings.
#
# -param $1 Value A
# -param $2 Value B
# -return true if A is greater than B
#+ otherwise false
gt_str() {
local _val=""
debug "[gt_str] ${*}"
_val=$( echo "[\"${1:-}\", \"${2:-}\"]" | jq ".[0] > .[1]" )
debug "[gt_str] $_val"
echo "$_val"
}
# Greater than or equals to (>=) operator.
#
# -param $1 Value A
# -param $2 Value B
# -return true if A is greater than or equals to B
#+ otherwise false
gte() {
local _val=""
debug "[gte] ${*}"
_val=$( echo "[${1:-}, ${2:-}]" | jq ".[0] >= .[1]" )
debug "[gte] $_val"
echo "$_val"
}
# Greater than or equals to (>=) operator for strings.
#
# -param $1 Value A
# -param $2 Value B
# -return true if A is greater than or equals to B
#+ otherwise false
gte_str() {
local _val=""
debug "[gte_str] ${*}"
_val=$( echo "[\"${1:-}\", \"${2:-}\"]" | jq ".[0] >= .[1]" )
debug "[gte_str] $_val"
echo "$_val"
}
# Equals to (==) operator.
#
# -param $1 Value A
# -param $2 Value B
# -return true if A is equals to B
#+ otherwise false
eq() {
local _val=""
debug "[eq] ${*}"
_val=$( echo "[${1:-}, ${2:-}]" | jq ".[0] == .[1]" )
debug "[eq] $_val"
echo "$_val"
}
# Equals to (==) operator for strings.
#
# -param $1 Value A
# -param $2 Value B
# -return true if A is equals to B
#+ otherwise false
eq_str() {
local _val=""
debug "[eq_str] ${*}"
_val=$( echo "[\"${1:-}\", \"${2:-}\"]" | jq ".[0] == .[1]" )
debug "[eq_str] $_val"
echo "$_val"
}
# Not equals to (!=) operator.
#
# -param $1 Value A
# -param $2 Value B
# -return true if A is not equals to B
#+ otherwise false
neq() {
local _val=""
debug "[neq] ${*}"
_val=$( echo "[${1:-}, ${2:-}]" | jq ".[0] != .[1]" )
debug "[neq] $_val"
echo "$_val"
}
# Not equals to (!=) operator for strings.
#
# -param $1 Value A
# -param $2 Value B
# -return true if A is not equals to B
#+ otherwise false
neq_str() {
local _val=""
debug "[neq_str] ${*}"
_val=$( echo "[\"${1:-}\", \"${2:-}\"]" | jq ".[0] != .[1]" )
debug "[neq_str] $_val"
echo "$_val"
}
# Removes an array element by key (start-with
#+ of the value). The original array is passed
#+ by the name of the array, so the function
#+ is able to evaluate that name as a variable.
#
# -param $1 Key (start-with) of the map (case sensitive)
# -param $2 Name of the array variable
remove_map() {
local _key=${1:-}
local _map_name=${2:-}
debug "[remove_map] ${*}"
# shellcheck disable=SC1087
eval "local _map_length=\${#$_map_name[@]}"
# shellcheck disable=SC2154
if (( _map_length > 0 )); then
# shellcheck disable=SC1087
eval "local _map_src=( \${$_map_name[@]} )"
eval "$_map_name=()"
# shellcheck disable=SC2154
for i in "${!_map_src[@]}"; do
if ! [[ "${_map_src[$i]}" == "${_key}"* ]]; then
eval "$_map_name+=( \"\${_map_src[\$i]}\" )"
fi
done
fi
}
# Puts an array element by key-value. The original array
#+ is passed by the name of the array, so the function
#+ is able to evaluate that name as a variable. There
#+ is no separator for key-value because a concatenated
#+ string ('key'+'value') is saved as an array element.
#
# -param $1 Key (start-with) of the map
# -param $2 Value (string part) of the map
# -param $3 Name of the array variable
put_map() {
local _key=${1:-}
local _value=${2:-}
local _map_name=${3:-}
debug "[put_map] ${*}"
remove_map "$_key" "$_map_name"
# shellcheck disable=SC1087
eval "$_map_name+=( \"$_key$_value\" )"
}
# Gets an element from an array. The original array
#+ is passed by the name of the array, so the function
#+ is able to evaluate that name as a variable.
#
# -param $1 Key (start-with) of the map
# -param $2 Name of the array variable
# -return Value (string part) of the map
get_map() {
local _key=${1:-}
local _map_name=${2:-}
local _element=""
debug "[get_map] ${*}"
# shellcheck disable=SC1087
eval "local _map_length=\${#$_map_name[@]}"
# shellcheck disable=SC2154
if (( _map_length > 0 )); then
# shellcheck disable=SC1087
eval "local _map_src=( \${$_map_name[@]} )"
shopt -s nocasematch
for _element in "${_map_src[@]}"; do
if [[ "$_element" == "$_key"* ]]; then
_element=${_element:${#_key}}
break
fi
done
shopt -u nocasematch
fi
debug "[get_map] $_element"
echo "$_element"
}
# ---------- Public functions
# In request flow step this is
#+ an external request call:
#+ input parameters processing,
#+ and request execution.
# In a flow execution context
#+ the '--times' option
#+ does not work for steps
#+ because it is used for repeat
#+ flow execution.
# It is recommended to use
#+ inside a flow function.
# This is the step process:
# 1. Execute option functions
#+ based on input parameters
# 2. Log executed step
# 3. Execute request command
# 4. Reset request variables
#
# -param $1 Request command
# -param $@ Request options
step() {
local _command=${1:-}
# Get the user input params
local _last_params="$_shttp_input_params"
debug "[step] ${*}"
debug "[step] Input params: $_shttp_input_params"
shift
# User input params have the priority
# If there are no user input params set the step params
mainOpts "$@"
# Look for the '--times' rule
# Only valid if there are step params
local _length=0
local _times_rule=""
_length=${#}
if(( _length > 0 )); then
local _contains_times=0
_contains_times=$( arr_like "--times" "${@}" )
_times_rule=$( (( _contains_times > 0 )) && echo "ALLOW_TIMES" || echo "BLOCK_TIMES" )
else
_times_rule="BLOCK_TIMES"
fi
debug "[step] Times-rule: $_times_rule"
_execute_request_opt "$_times_rule"
echo "$_command" | tee -a "$_shttp_output_flow.steps" > /dev/null
_execute "$_command" "$_shttp_request_times" STEP
# Set again the user input params
_shttp_input_params="$_last_params"
}
# Updates a JSON file using 'jq'.
#
# -param $1 JSON file
# -param $2 Change by 'jq' syntax
update() {
local _json=${1:-}
local _jq=${2:-}
local _temp=""
debug "[update] ${*}"
_temp="ws/.pivot.$( date '+%s.%N' ).json.tmp"
debug "[update] $_jq $_temp"
( < "$_json" jq -r "$_jq" ) > "$_temp"
mv "$_temp" "$_json"
info "Updated [$_json] file"
}
# Saves key-value config to 'ws/config[.<env>].json'.
# This function has three different forms:
# 1. Only 'jq' query: put '.jq'
# 2. Name and 'jq' query: put 'name' '.jq'
# 3. Name and value: put 'name' 'value'
# If 'jq' query is found, the function will
#+ use JSON result to take the value.
#
# -param $1 Name of the entry or 'jq' for value
# -param $2 Value of the entry or 'jq' for value
# -param $3 Secure type: [PRIVATE | PUBLIC]
put() {
local _name=${1:-}
local _val=${2:-}
local _sec=${3:-"PUBLIC"}
local _jq=""
debug "[put] ${*}"
if [ -z "$_val" ]; then
_jq="$_name"
_name=${_name//[0-9^\[\]]/}
_name=$( str_rev "$_name" )
_name=$( echo "$_name" | cut -d '.' -f 1 )
_name=$( str_rev "$_name" )
elif [[ "$_val" = \.* ]]; then
_jq="$_val"
fi
if [ -n "$_jq" ]; then
_val=$( < "$_shttp_output.output" jq "try $_jq catch null" )
fi
if [ "$_sec" = "PRIVATE" ]; then
local _entry="$_shttp_suffix->$_name:="
local _desc=""
_desc=$( < "$_shttp_env" jq ".$_name")
_entry=$( echo "$_entry" | base64 )
_val=$( echo "$_val" | sed -e 's/^"//' -e 's/"$//' )
_val=$( echo "$_val" | base64 )
if [ -a "ws/.vlt" ]; then
sed -i "/^$_entry/d" "ws/.vlt"
fi
echo "$_entry!$_val" | tee -a "ws/.vlt" > /dev/null
_val="$_desc"
fi
debug "[update] $_shttp_env . + { \"$_name\": $_val }"
update "$_shttp_env" ". + { \"$_name\": $_val }"
info "Saved [$_name] with value [$_val] to workspace config"
}
# Gets key-value config in the following
#+ order:
#+ 1. script variables and
#+ 2. from 'ws/config[.<env>].json'.
#
# -param $1 Name of the entry or 'jq'
#+ query (without '.' at the
#+ beginning of the query)
# -param $2 Default value if required
#+ is not found
# -return Config value
get() {
local _name=${1:-}
local _default=${2:-'null'}
local _entry=""
local _val=""
debug "[get] ${*}"
if [ -a "ws/.vlt" ]; then
_entry="$_shttp_suffix->$_name:="
_entry=$( echo "$_entry" | base64 )
_val=$( grep -e "^$_entry" "ws/.vlt" )
fi
if [ -n "$_val" ]; then
_val="${_val/"$_entry!"/}"
_val=$( echo "$_val" | base64 --decode )
else
_val=$( < "ws/.override.json.tmp" jq ".$_name | tostring" )
_val=$( echo "$_val" | sed -e 's/^"//' -e 's/"$//' )
if [ "$_val" = "null" ]; then
_val=""
fi
if [ -z "$_val" ]; then
_val=$( jq ".$_name | tostring" "$_shttp_env" )
_val=$( echo "$_val" | sed -e 's/^"//' -e 's/"$//' )
if [ "$_val" = "null" ]; then
_val="$_default"
fi
fi
fi
debug "[get] $_val"
echo "$_val"
}
# Removes key-value from 'ws/config[.<env>].json'.
# This function has two different forms:
# 1. 'jq' query: remove '.jq'
# 2. Field name: remove 'name'
#
# -param $1 Name of the entry
remove() {
local _name=${1:-}
debug "[remove] ${*}"
if [[ "$_name" = \.* ]]; then
local _val=""
_val=$( jq "try $_name catch null" "$_shttp_env" )
if [ "$_val" != "null" ]; then
update "$_shttp_env" "del($_name)"
info "Removed [$_name] from workspace config"
fi
else
local _found=""
_found=$( jq "has(\"$_name\")" "$_shttp_env" )
if [ "$_found" = "true" ]; then
update "$_shttp_env" "del(.$_name)"
info "Removed [$_name] from workspace config"
fi
fi
}
# Gets the method setted in '_shttp_method'. This value
#+ is only available after processing any 'before'
#+ function like 'before_api' and 'before_[command]'
#+ besides after '[command]' function execution. It is
#+ recomendable use this method only in the context
#+ of the 'request': 'before_[command]' and
#+ 'after_[command]'.
#
# -return Request method
getRequestMethod() {
local _method="$_shttp_method"
debug "[getRequestMethod] $_method"
echo "$_method"
}
# Gets the body setted in '_shttp_body' (file) as
#+ string value. This value is only available after
#+ processing any 'before' function like 'before_api'
#+ and 'before_[command]' besides after '[command]'
#+ function execution. It is recomendable use this
#+ method only in the context of the 'request':
#+ 'before_[command]' and 'after_[command]'.
#
# -return Request body (as string)
getRequestBody() {
local _body=""
if [ -f "$_shttp_body" ]; then
_body="$( cat "$_shttp_body" )"
fi
debug "[getRequestBody] $_body"
echo "$_body"
}
# Gets a header value setted in '_shttp_headers'.
#+ This value is only available after processing any
#+ 'before' function like 'before_api' and 'before_[command]'
#+ besides after '[command]' function execution. It is
#+ recomendable use this method only in the context
#+ of the 'request': 'before_[command]' and 'after_[command]'.
#
# -param $1 Header key
# -return Request header value
getRequestHeader() {
local _header=${1:-}
local _value=""
_value=$( get_map "$_header: " "_shttp_headers" )
debug "[getRequestHeader] ${*}"
debug "[getRequestHeader] $_value"
echo "$_value"
}
# Gets the path built with '_shttp_endpoint' and
#+ '_shttp_query_params'. This value is only available
#+ after processing any 'before' function like 'before_api'
#+ and 'before_[command]' besides after '[command]'
#+ function execution. It is recomendable use this
#+ method only in the context of the 'request':
#+ 'before_[command]' and 'after_[command]'.
#
# -return Request path
getRequestPath() {
local _length=0
local _path="$_shttp_endpoint"
_length=${#_shttp_query_params[@]}
if (( _length > 0 )); then
_path+="?"
_path+=$( arr_join "&" "${_shttp_query_params[@]}" )
fi
debug "[getRequestPath] $_path"
echo "$_path"
}
# Gets the URL built with '_shttp_url' and
#+ '_shttp_query_params'. This value is only available
#+ after processing any 'before' function like 'before_api'
#+ and 'before_[command]' besides after '[command]'
#+ function execution. It is recomendable use this
#+ method only in the context of the 'request':
#+ 'before_[command]' and 'after_[command]'.
#
# -return Request URL
getRequestUrl() {
local _length=0
local _url="$_shttp_url"
_length=${#_shttp_query_params[@]}
if (( _length > 0 )); then
_url+="?"
_url+=$( arr_join "&" "${_shttp_query_params[@]}" )
fi
debug "[getRequestUrl] $_url"
echo "$_url"
}
# Saves credential part for '_shttp_auth_credential'
#+ so this variable have to be set preiously.
#
# -param $1 Part name
# -param $2 Part value
# -param $3 Secure type:
#+ [PRIVATE | PUBLIC]
# -param $4 Part description