aboutsummaryrefslogtreecommitdiff
path: root/shell_utils.sh
blob: 51361f534c2940ca13833492d5768aa30d1a471e (plain)
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
# This file is part of Haketilo
#
# Copyright (C) 2021, Wojtek Kosior
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the CC0 1.0 Universal License as published by
# the Creative Commons Corporation.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# CC0 1.0 Universal License for more details.

map_set_instr() {
    printf "%s__%s='%s'" "$1" "$2" "$3"
}

map_set() {
    eval "$(map_set_instr "$@")"
}

map_set_export() {
    eval "export $(map_set_instr "$@")"
}

map_get() {
    eval "printf %s \"\$$1__$2\""
}

map_del_instr() {
    printf 'unset %s__%s' "$1" "$2"
}

map_del() {
    eval "$(map_del_instr "$@")"
}

sanitize() {
    printf %s "$1" | tr /.- _
}

escape_regex_special() {
    printf %s "$1" | sed 's/\([]\.*?{},()[-]\)/\\\1/g'
}

# Note: We don't actually parse JSON. We extract needed keys with sed regexes
# which does not work in the general case but is sufficient for now.
get_json_key() {
    local KEY_REG="$(escape_regex_special "$1")"
    printf %s "$2" |
	sed 's/\(.*"'"$KEY_REG"'"[[:space:]]*:[[:space:]]*"\([^"]*\)"\)\?.*/\2/' |
	grep . | head -1
}