-
Notifications
You must be signed in to change notification settings - Fork 92
Expand file tree
/
Copy pathdevshell.nix
More file actions
332 lines (285 loc) · 8.99 KB
/
devshell.nix
File metadata and controls
332 lines (285 loc) · 8.99 KB
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
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
{ config, lib, pkgs, ... }:
with lib;
let
cfg = config.devshell;
ansi = import ../nix/ansi.nix;
bashBin = "${cfg.bashPackage}/bin";
bashPath = "${cfg.bashPackage}/bin/bash";
# Because we want to be able to push pure JSON-like data into the
# environment.
strOrPackage = import ../nix/strOrPackage.nix { inherit lib pkgs; };
# Use this to define a flake app for the environment.
mkFlakeApp = bin: {
type = "app";
program = "${bin}";
};
mkSetupHook = entrypoint:
pkgs.stdenvNoCC.mkDerivation {
name = "devshell-setup-hook";
setupHook = pkgs.writeText "devshell-setup-hook.sh" ''
source ${devshell_dir}/env.bash
'';
dontUnpack = true;
dontBuild = true;
dontInstall = true;
};
mkNakedShell = pkgs.callPackage ../nix/mkNakedShell.nix { };
addAttributeName = prefix:
mapAttrs (k: v: v // {
text = ''
#### ${prefix}.${k}
${v.text}
'';
});
entryOptions = {
text = mkOption {
type = types.str;
description = ''
Script to run.
'';
};
deps = mkOption {
type = types.listOf types.str;
default = [ ];
description = ''
A list of other steps that this one depends on.
'';
};
};
# Write a bash profile to load
envBash = pkgs.writeText "devshell-env.bash" ''
if [[ -n ''${IN_NIX_SHELL:-} || ''${DIRENV_IN_ENVRC:-} = 1 ]]; then
# We know that PWD is always the current directory in these contexts
export PRJ_ROOT=$PWD
elif [[ -z ''${PRJ_ROOT:-} ]]; then
echo "ERROR: please set the PRJ_ROOT env var to point to the project root" >&2
return 1
fi
# Expose the folder that contains the assembled environment.
export DEVSHELL_DIR=@DEVSHELL_DIR@
# Prepend the PATH with the devshell dir and bash
PATH=''${PATH%:/path-not-set}
PATH=''${PATH#${bashBin}:}
export PATH=$DEVSHELL_DIR/bin:${bashBin}:$PATH
${cfg.startup_env}
${textClosureMap id (addAttributeName "startup" cfg.startup) (attrNames cfg.startup)}
# Interactive sessions
if [[ $- == *i* ]]; then
${textClosureMap id (addAttributeName "interactive" cfg.interactive) (attrNames cfg.interactive)}
fi # Interactive session
'';
# This is our entrypoint script.
entrypoint = pkgs.writeScript "${cfg.name}-entrypoint" ''
#!${bashPath}
# Script that sets-up the environment. Can be both sourced or invoked.
export DEVSHELL_DIR=@DEVSHELL_DIR@
# If the file is sourced, skip all of the rest and just source the env
# script.
if [[ $0 != "''${BASH_SOURCE[0]}" ]]; then
source "$DEVSHELL_DIR/env.bash"
return
fi
# Be strict!
set -euo pipefail
if [[ $# = 0 ]]; then
# Start an interactive shell
exec "${bashPath}" --rcfile "$DEVSHELL_DIR/env.bash" --noprofile
elif [[ $1 == "-h" || $1 == "--help" ]]; then
cat <<USAGE
Usage: ${cfg.name}
$0 -h | --help # show this help
$0 [--pure] # start a bash sub-shell
$0 [--pure] <cmd> [...] # run a command in the environment
Options:
* --pure : execute the script in a clean environment
USAGE
exit
elif [[ $1 == "--pure" ]]; then
# re-execute the script in a clean environment
shift
exec /usr/bin/env -i -- "HOME=$HOME" "PRJ_ROOT=$PRJ_ROOT" "$0" "$@"
else
# Start a script
source "$DEVSHELL_DIR/env.bash"
exec -- "$@"
fi
'';
# Builds the DEVSHELL_DIR with all the dependencies
devshell_dir = pkgs.buildEnv {
name = "devshell-dir";
paths = cfg.packages;
postBuild = ''
substitute ${envBash} $out/env.bash --subst-var-by DEVSHELL_DIR $out
substitute ${entrypoint} $out/entrypoint --subst-var-by DEVSHELL_DIR $out
chmod +x $out/entrypoint
'';
};
# Returns a list of all the input derivation ... for a derivation.
inputsOf = drv:
(drv.buildInputs or [ ]) ++
(drv.nativeBuildInputs or [ ]) ++
(drv.propagatedBuildInputs or [ ]) ++
(drv.propagatedNativeBuildInputs or [ ])
;
in
{
options.devshell = {
bashPackage = mkOption {
internal = true;
type = strOrPackage;
default = pkgs.bashInteractive;
defaultText = "pkgs.bashInteractive";
description = "Version of bash to use in the project";
};
package = mkOption {
internal = true;
type = types.package;
description = ''
This package contains the DEVSHELL_DIR
'';
};
startup = mkOption {
type = types.attrsOf (types.submodule { options = entryOptions; });
default = { };
internal = true;
description = ''
A list of scripts to execute on startup.
'';
};
startup_env = mkOption {
type = types.str;
default = "";
internal = true;
description = ''
Please ignore. Used by the env module.
'';
};
interactive = mkOption {
type = types.attrsOf (types.submodule { options = entryOptions; });
default = { };
internal = true;
description = ''
A list of scripts to execute on interactive startups.
'';
};
# TODO: rename motd to something better.
motd = mkOption {
type = types.str;
default = ''
{202}🔨 Welcome to ${cfg.name}{reset}
$(type -p menu &>/dev/null && menu)
'';
apply = replaceStrings
(map (key: "{${key}}") (attrNames ansi))
(attrValues ansi);
description = ''
Message Of The Day.
This is the welcome message that is being printed when the user opens
the shell.
You may use any valid ansi color from the 8-bit ansi color table. For example, to use a green color you would use something like {106}. You may also use {bold}, {italic}, {underline}. Use {reset} to turn off all attributes.
'';
};
load_profiles = mkEnableOption "load etc/profiles.d/*.sh in the shell";
name = mkOption {
type = types.str;
default = "devshell";
description = ''
Name of the shell environment. It usually maps to the project name.
'';
};
packages = mkOption {
type = types.listOf strOrPackage;
default = [ ];
description = ''
The set of packages to appear in the project environment.
Those packages come from <https://nixos.org/NixOS/nixpkgs> and can be
searched by going to <https://search.nixos.org/packages>
'';
};
packagesFrom = mkOption {
type = types.listOf strOrPackage;
default = [ ];
description = ''
Add all the build dependencies from the listed packages to the
environment.
'';
};
shell = mkOption {
internal = true;
type = types.package;
description = "TODO";
};
};
config.devshell = {
package = devshell_dir;
packages = foldl' (sum: drv: sum ++ (inputsOf drv)) [ ] cfg.packagesFrom;
startup = {
motd = noDepEntry ''
__devshell-motd() {
cat <<DEVSHELL_PROMPT
${cfg.motd}
DEVSHELL_PROMPT
}
if [[ ''${DEVSHELL_NO_MOTD:-} = 1 ]]; then
# Skip if that env var is set
:
elif [[ ''${DIRENV_IN_ENVRC:-} = 1 ]]; then
# Print the motd in direnv
__devshell-motd
else
# Print information if the prompt is displayed. We have to make
# that distinction because `nix-shell -c "cmd"` is running in
# interactive mode.
__devshell-prompt() {
__devshell-motd
# Make it a noop
__devshell-prompt() { :; }
}
PROMPT_COMMAND=__devshell-prompt''${PROMPT_COMMAND+;$PROMPT_COMMAND}
fi
'';
} // (optionalAttrs cfg.load_profiles {
load_profiles = lib.noDepEntry ''
# Load installed profiles
for file in "$DEVSHELL_DIR/etc/profile.d/"*.sh; do
# If that folder doesn't exist, bash loves to return the whole glob
[[ -f "$file" ]] && source "$file"
done
'';
});
interactive = {
PS1_util = noDepEntry ''
if [[ -n "''${PRJ_ROOT:-}" ]]; then
# Print the path relative to $PRJ_ROOT
rel_root() {
local path
path=$(${pkgs.coreutils}/bin/realpath --relative-to "$PRJ_ROOT" "$PWD")
if [[ $path != . ]]; then
echo " $path "
fi
}
else
# If PRJ_ROOT is unset, print only the current directory name
rel_root() {
echo " \W "
}
fi
'';
# Set a cool PS1
PS1 = stringAfter [ "PS1_util" ] (lib.mkDefault ''
PS1='\[\033[38;5;202m\][${cfg.name}]$(rel_root)\$\[\033[0m\] '
'');
};
# Use a naked derivation to limit the amount of noise passed to nix-shell.
shell = mkNakedShell {
name = strings.sanitizeDerivationName cfg.name;
profile = cfg.package;
passthru = {
inherit config;
flakeApp = mkFlakeApp entrypoint;
hook = mkSetupHook entrypoint;
inherit (config._module.args) pkgs;
};
};
};
}