aboutsummaryrefslogtreecommitdiffstats
path: root/ves-activate.sh
blob: 5199f5b54dd54b6513b843279106eb3e008c4f78 (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
80
81
82
#!/bin/sh
#
# Activate an sh-ves environment in the current shell. The prior values of
# all variables the environment overrides are saved in SHVES_SAVED_<var>
# shell variables (with SHVES_SAVEDSET_<var> recording whether the variable
# existed at all), so that ves_deactivate can restore them exactly.
#
ves_activate() {
    if [ "$#" -lt 1 ]; then
        printf "ERROR: No environment name specified.\n" >&2
        return 1
    fi

    if [ -n "$SHVES_ENV_NM" ]; then
        printf "ERROR: Environment [%s] is already active. Deactivate it first.\n" "$SHVES_ENV_NM" >&2
        return 1
    fi

    env_name="$1"
    if ! _shves_check_env_name "$env_name"; then
        return 1
    fi

    if ! _shves_check_env_exists "$env_name"; then
        return 1
    fi

    SHVES_SAVED_VARS=""

    while IFS= read -r line; do
        case $line in
            export_var:*)
                ;;
            *)
                continue
                ;;
        esac

        entry="${line#export_var:}"
        var="${entry%%=*}"
        value="${entry#*=}"

        if ! _shves_check_var_name "$var"; then
            continue
        fi

        # save the prior value (and whether the variable was set at all)
        # so that deactivation can restore the environment exactly
        _shves_live_export "$var" "$value"
    done < "$SHVES_ENV_DIR/$env_name"

    SHVES_ENV_NM="$env_name"
    export SHVES_ENV_NM

    return 0
}

#
# Switch to another environment: deactivate the current one (if any) and
# activate the named one. Pure convenience; environments still do not
# compose.
#
ves_switch() {
    if [ "$#" -lt 1 ]; then
        printf "ERROR: No environment name specified.\n" >&2
        return 1
    fi

    if ! _shves_check_env_name "$1"; then
        return 1
    fi

    if ! _shves_check_env_exists "$1"; then
        return 1
    fi

    if [ -n "$SHVES_ENV_NM" ]; then
        ves_deactivate || return 1
    fi

    ves_activate "$1"
}