]> CyberLeo.Net >> Repos - CDN/taggery.git/blob - lib/kvs.sh
What is this I don't even...
[CDN/taggery.git] / lib / kvs.sh
1 t="$(printf '\t')"
2
3 [ "${kvs}" ] || {
4   cat <<EOF
5 KVS v0.1
6 Copyright - http://wiki.cyberleo.net/wiki/CyberLeo/COPYRIGHT?version=4
7
8 Set the following variables before sourcing this library:
9
10  kvs  - Path and filename of the kvdb database file
11 EOF
12   kill $$
13   exit 1
14 }
15
16
17 [ -s "${kvs}" ] || echo "${t}${t}# KVSv0 id-key-value database" > "${kvs}"
18
19 # Add or replace a value stored for a given key and id in the kvs
20 kvs_set() {
21   [ "${1}" -a "${2}" ] || return 255
22   local id="${1}"
23   local var="${2}"
24   local val="${3}"
25   printf "%s\t%s\t%s\n" "${id}" "${var}" "${val}" >> "${kvs}"
26 }
27
28 # Fetch the most recent value stored for a given key and id from the kvs
29 kvs_get() {
30   [ "${1}" -a "${2}" ] || return 255
31   local id="${1}"
32   local var="${2}"
33   grep "^${id}${t}${var}${t}" "${kvs}" | tail -n 1 | cut -d"${t}" -f3-
34 }
35
36 # Does the kvs have any entries for a given ID?
37 kvs_has_id() {
38   [ "${1}" ] || return 255
39   local id="${1}"
40   grep -q "^${id}${t}" "${kvs}"
41 }
42
43 # Remove a given key with a given ID from the kvs
44 kvs_unset() {
45   [ "${1}" -a "${2}" ] || return 255
46   local id="${1}"
47   local var="${2}"
48   grep -v "^${id}${t}${var}${t}" "${kvs}" > "${kvs}.tmp" && mv -f "${kvs}.tmp" "${kvs}" || rm -f "${kvs}.tmp"
49 }
50
51 # Remove all keys with a given ID from the kvs
52 kvs_unset_all() {
53   [ "${1}" ] || return 255
54   local id="${1}"
55   grep -v "^${id}${t}" "${kvs}" > "${kvs}.tmp" && mv -f "${kvs}.tmp" "${kvs}" || rm -f "${kvs}.tmp"
56 }