File size: 2,095 Bytes
c4f8e4a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
{ lib, pkgs }:

let
  exportEnv = env:
    lib.concatStringsSep "\n" (
      lib.mapAttrsToList (name: value: "export ${name}=${lib.escapeShellArg value}") env
    );

  prependEnv = env:
    lib.concatStringsSep "\n" (
      lib.mapAttrsToList (
        name: value:
          ''
            _runtime_current_value="$(printenv ${name} || true)"
            if [ -n "$_runtime_current_value" ]; then
              export ${name}=${lib.escapeShellArg value}:"$_runtime_current_value"
            else
              export ${name}=${lib.escapeShellArg value}
            fi
            unset _runtime_current_value
          ''
      ) env
    );

  mergeStringAttrs = runtimes: key:
    lib.foldl' (
      acc: runtime:
        let current = runtime.${key} or { };
        in acc // lib.mapAttrs (
          name: value:
            if builtins.hasAttr name acc
            then "${value}:${builtins.getAttr name acc}"
            else value
        ) current
    ) { } runtimes;

  mergeRuntimes = runtimes: {
    packages = lib.unique (lib.concatMap (runtime: runtime.packages or [ ]) runtimes);
    env = lib.foldl' (acc: runtime: acc // (runtime.env or { })) { } runtimes;
    prependEnv = mergeStringAttrs runtimes "prependEnv";
    shellHook = lib.concatStringsSep "\n\n" (
      lib.filter (chunk: chunk != "") (map (runtime: runtime.shellHook or "") runtimes)
    );
  };

  mkRuntimeShell = {
    name,
    runtimes,
    extraPackages ? [ ],
    extraShellHook ? "",
    stdenv ? null,
  }:
    let
      runtime = mergeRuntimes runtimes;
      shellHook = lib.concatStringsSep "\n\n" (
        [
          (exportEnv (runtime.env or { }))
          (prependEnv (runtime.prependEnv or { }))
          (runtime.shellHook or "")
          extraShellHook
          ''
            echo "${name} shell ready"
          ''
        ]
      );
    in
    pkgs.mkShell ({
      packages = lib.unique (extraPackages ++ runtime.packages);
      inherit shellHook;
    } // lib.optionalAttrs (stdenv != null) { inherit stdenv; });
in
{
  inherit exportEnv prependEnv mergeRuntimes mkRuntimeShell;
}