-
Notifications
You must be signed in to change notification settings - Fork 23
/
quinedb
executable file
·148 lines (128 loc) · 2.52 KB
/
quinedb
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
#!/usr/bin/env bash
if [[ "$BASH_VERSION" =~ ^3 ]]; then
echo 'quinedb requires bash 4!'
exit 1
fi
declare -A db
db=(
)
PREAMBLE=$(cat <<'EOF'
#!/usr/bin/env bash
if [[ "$BASH_VERSION" =~ ^3 ]]; then
echo 'quinedb requires bash 4!'
exit 1
fi
declare -A db
EOF
)
POSTAMBLE=$(cat <<'EOF'
pr_str () {
printf "%q" "$1"
}
case "$1" in
"get")
if [ ${db["$2"]+_} ]; then
v=${db["$2"]}
echo "$(pr_str "$v")" >&2
fi
;;
"set")
db["$2"]="$3"
echo 'OK' >&2
;;
"delete")
unset db["$2"]
echo 'OK' >&2
;;
"keys")
for k in "${!db[@]}"; do echo "$(pr_str "$k")"; done >&2
;;
*)
echo "USAGE: quinedb [get k | set k v | delete k | keys]" >&2
;;
esac
# print self
print_db(){
echo "db=("
i=0
for k in "${!db[@]}"; do
escaped_keys[$i]=$(pr_str "$k")
i=$((i+1))
done
# sort the keys for deterministic printing
IFS=$'\n' sorted=($(for l in ${escaped_keys[@]}; do echo $l; done | sort))
unset IFS
for k in "${sorted[@]}"; do
unescaped=$(eval "echo $k")
v=${db["$unescaped"]}
echo " [$k]=$(pr_str "$v")"
done
echo ")"
}
echo "$PREAMBLE"; echo
print_db; echo
echo 'PREAMBLE=$(cat <<'\'EOF\'
echo "$PREAMBLE"
echo EOF
echo \); echo
echo 'POSTAMBLE=$(cat <<'\'EOF\'
echo "$POSTAMBLE"
echo EOF
echo \); echo
echo "$POSTAMBLE"
EOF
)
pr_str () {
printf "%q" "$1"
}
case "$1" in
"get")
if [ ${db["$2"]+_} ]; then
v=${db["$2"]}
echo "$(pr_str "$v")" >&2
fi
;;
"set")
db["$2"]="$3"
echo 'OK' >&2
;;
"delete")
unset db["$2"]
echo 'OK' >&2
;;
"keys")
for k in "${!db[@]}"; do echo "$(pr_str "$k")"; done >&2
;;
*)
echo "USAGE: quinedb [get k | set k v | delete k | keys]" >&2
;;
esac
# print self
print_db(){
echo "db=("
i=0
for k in "${!db[@]}"; do
escaped_keys[$i]=$(pr_str "$k")
i=$((i+1))
done
# sort the keys for deterministic printing
IFS=$'\n' sorted=($(for l in ${escaped_keys[@]}; do echo $l; done | sort))
unset IFS
for k in "${sorted[@]}"; do
unescaped=$(eval "echo $k")
v=${db["$unescaped"]}
echo " [$k]=$(pr_str "$v")"
done
echo ")"
}
echo "$PREAMBLE"; echo
print_db; echo
echo 'PREAMBLE=$(cat <<'\'EOF\'
echo "$PREAMBLE"
echo EOF
echo \); echo
echo 'POSTAMBLE=$(cat <<'\'EOF\'
echo "$POSTAMBLE"
echo EOF
echo \); echo
echo "$POSTAMBLE"