aboutsummaryrefslogtreecommitdiffstats
path: root/ves-var-add.sh
blob: 01bc4571520294c335301bde6b42cdef2271edea (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
73
74
75
76
77
78
79
#!/bin/sh
#
# Prepend an entry to a path-like (:-delimited) variable within an sh-ves
# environment, or append it with --append. Values not beginning with / or
# ./ are expanded relative to the sh-ves data directories (see
# _shves_expand_path). If the target environment is currently active, the
# variable is also updated in the live shell.
#
ves_var_add() {
    env=""
    append=0

    while :; do
        case $1 in
            --env=*)
                env="${1#--env=}"
                shift
                ;;
            --append)
                append=1
                shift
                ;;
            *)
                break
                ;;
        esac
    done

    if [ "$#" -lt 2 ]; then
        printf "ERROR: Insufficient arguments. usage: ves var-add [--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")

    # Get the current value from the environment file and prepend the new
    # entry to it. If the variable is not stored in the environment at all,
    # seed it from the live shell value first, so that prepending to PATH
    # and friends never truncates them. An explicitly stored empty value
    # (as created by ves create --override) is respected, however.
    fname="$SHVES_ENV_DIR/$env"
    if _shves_has_var "$fname" "$var"; then
        var_value=$(_shves_get_var "$fname" "$var")
    else
        # Read the live shell value of the variable named in $var,
        # defaulting to empty if it is unset. For $var = PATH, this
        # expands to: var_value=${PATH:-}
        eval "var_value=\${$var:-}"
    fi

    if [ -z "$var_value" ]; then
        var_value="$value"
    elif [ "$append" -eq 1 ]; then
        var_value="$var_value:$value"
    else
        var_value="$value:$var_value"
    fi

    _shves_set_var "$fname" "$var" "$var_value"

    # If we are updating the currently active environment, export the
    # new value as well.
    if [ "$env" = "$SHVES_ENV_NM" ]; then
        _shves_live_export "$var" "$var_value"
    fi

    return 0
}