aboutsummaryrefslogtreecommitdiffstats
path: root/ves-var-rm.sh
blob: cc0a1e1ecc2721008719f8249e3e9a98f223ea14 (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
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
#!/bin/sh
#
# Remove an entry from a path-like (:-delimited) variable within an sh-ves
# environment. The value is expanded with the same rules as ves var-add, so
# entries can be removed using the same form they were added with. If the
# target environment is currently active, the variable is also updated in
# the live shell.
#
ves_var_rm() {
    env=""
    case $1 in
        --env=*)
            env="${1#--env=}"
            shift
            ;;
    esac

    if [ "$#" -lt 2 ]; then
        printf "ERROR: Insufficient arguments. usage: ves var-rm [--env=<name>] <variable> <value>\n" >&2
        return 2
    fi

    var="$1"
    value="$2"

    if ! env=$(_shves_resolve_env "$env"); then
        return 1
    fi

    if ! _shves_check_var_name "$var"; then
        return 1
    fi

    value=$(_shves_expand_path "$var" "$value")

    fname="$SHVES_ENV_DIR/$env"
    if ! _shves_has_var "$fname" "$var"; then
        printf "ERROR: Variable [%s] does not exist in environment [%s].\n" "$var" "$env" >&2
        return 1
    fi

    var_value=$(_shves_get_var "$fname" "$var")

    # Rebuild the :-delimited list, dropping every element matching the
    # value to remove.
    new_value=""
    found=0
    _shves_split_begin
    for entry in $var_value; do
        if [ "$entry" = "$value" ]; then
            found=1
        elif [ -z "$new_value" ]; then
            new_value="$entry"
        else
            new_value="$new_value:$entry"
        fi
    done
    _shves_split_end

    if [ "$found" -eq 0 ]; then
        printf "ERROR: Entry [%s] not present in variable [%s].\n" "$value" "$var" >&2
        return 1
    fi

    _shves_set_var "$fname" "$var" "$new_value"

    if [ "$env" = "$SHVES_ENV_NM" ]; then
        _shves_live_export "$var" "$new_value"
    fi

    return 0
}