aboutsummaryrefslogtreecommitdiffstats
path: root/modules/by-name/di/direnv/pre-cache.sh
blob: 883689f156062a7d599569663fdd8df7d32175c2 (plain) (blame)
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
#! /usr/bin/env sh

_pre_cache_log() {
    printf "pre-cache: %s\n" "$1"
}
_pre_cache_preflight() {
    set -eu
    _nix_direnv_preflight

    REPO="%DEVSHELLS_REPO%"
    system="x86_64-linux"
    cache_dir="$XDG_CACHE_HOME/pre_cache"
    [ -d "$cache_dir" ] || mkdir --parents "$cache_dir"

    repo_ref="%DEVSHELLS_REPO_REF%"
    final_cache="$cache_dir/$repo_ref"

    if ! [ -d "$final_cache" ]; then
        _pre_cache_log "Cache dir invalidated"

        # There is not yet a final cache directory, so the ref must have changed.
        # Therefore we delete the whole cache directory, so we invalidate old cached shells.
        set -u
        rm --recursive "$cache_dir"

        mkdir --parents "$final_cache"
    fi
}

_pre_cache_load_shell() {
    lang="$1"
    lang_cache="$final_cache/$lang"

    if ! [ -f "$lang_cache" ]; then
        tmp_profile="$final_cache/__tmp_profile"
        profile="$final_cache/__profile"

        # It does not already exists, we need to evaluate it.
        _nix print-dev-env --profile "$tmp_profile" "$REPO#$lang" >"$lang_cache"

        _nix_add_gcroot "$tmp_profile" "$profile"
        rm "$tmp_profile" "$tmp_profile"*
    fi

    _pre_cache_log "Loaded dev-shell for $lang."
    _nix_import_env "$lang_cache"
}

_pre_cache_build_shells() {
    installables=""

    for lang in "$@"; do
        new_part="$REPO#devShells.$system.$lang"

        if [ -z "$installables" ]; then
            installables="$new_part"
        else
            installables="$installables $new_part"
        fi
    done

    # We want shell-spliting
    # shellcheck disable=SC2086
    _nix build --no-link $installables

}

pre_cache_load() {
    _pre_cache_preflight

    _pre_cache_build_shells "$@"

    for lan in "$@"; do
        _pre_cache_load_shell "$lan"
    done
}

# vim: ft=sh