-
Notifications
You must be signed in to change notification settings - Fork 8
/
start
executable file
·93 lines (74 loc) · 1.8 KB
/
start
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
#!/usr/bin/env bash
# ensure third party tools are installed
requirements_check() {
local which_bin="jq python"
local ret=0
which ${which_bin} &>/dev/null
ret=$?
if [ $ret -ne 0 ]; then
echo >&2 "binaries missing in [${which_bin}]"
else
# ensure python modules are installed
python -c 'import sys, yaml, json' 2>/dev/null
ret=$?
if [ $ret -ne 0 ]; then
echo >&2 "python modules missing in [yaml, json]"
fi
fi
return $ret
}
show_usage() {
echo "Usage: "$0" [get <jq_filter> | set <jq_filter> <new_value>]"
echo ""
exit 1
}
y2j() {
python -c 'import sys, yaml, json; json.dump(yaml.load(sys.stdin), sys.stdout, indent=4)'
}
j2y() {
python -c 'import sys, yaml, json; yaml.safe_dump(json.load(sys.stdin), sys.stdout, indent=2, default_flow_style=False)'
}
yq() {
local jq_response=$(y2j | jq "$@")
if is_json "$jq_response"; then
echo "$jq_response" | j2y
else
echo "$jq_response"
fi
}
is_json() {
echo "$1" | jq -e 'if type=="array" or type=="object" then true else false end' &>/dev/null
}
set_value() {
[ $# -ne 3 ] && show_usage
if is_json $1; then
echo "$1" | jq "$2 |= $3"
else
echo "$1" | y2j | jq "$2 |= $3" | j2y
fi
}
read_value() {
[ $# -lt 2 ] && show_usage
local input="$1"
shift
if is_json "$input"; then
echo "$input" | jq "$@"
else
echo "$input" | yq "$@"
fi
}
main() {
# on demand requirements check
if [ "$1" == "req" ]; then
requirements_check; exit $?
fi
# ensure requirements are completed at each run
requirements_check || exit $?
[ $# -ge 1 -a -f "$1" ] && input="$(cat $1)" && shift || input="$(cat)"
case "$1" in
set) shift; set_value "$input" "$@";;
get) shift; read_value "$input" "$@";;
*) show_usage;;
esac
}
main "$@"