-
Notifications
You must be signed in to change notification settings - Fork 93
Expand file tree
/
Copy pathdefault.nix
More file actions
313 lines (270 loc) · 8.78 KB
/
default.nix
File metadata and controls
313 lines (270 loc) · 8.78 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
{ lib
, bashInteractive
, buildEnv
, coreutils
, pkgs
, system
, writeText
, writeTextFile
, writeShellScriptBin
}:
let
bashBin = "${bashInteractive}/bin";
bashPath = "${bashInteractive}/bin/bash";
# Transform the env vars into bash exports
envToBash = env:
builtins.concatStringsSep "\n"
(lib.mapAttrsToList
(k: v: "export ${k}=${lib.escapeShellArg (toString v)}")
env
)
;
# A developer shell that works in all scenarios
#
# * nix-build
# * nix-shell
# * flake app
# * direnv integration
mkDevShell = module:
let
config = (lib.evalModules {
modules = [ ./options.nix module ];
args = {
inherit pkgs;
};
}).config;
inherit (config)
bash
commands
services
env
motd
name
packages
;
envDrv = buildEnv {
# TODO: support passing more arguments here
name = "${name}-env";
paths =
let
op =
{ name, command, ... }:
if command == null || command == "" then [ ]
else [
(writeShellScriptBin name (toString command))
];
in
(builtins.concatMap op commands) ++ packages ++ [ serviceViewer ];
};
sessionName = "${name}-sessions";
serviceRunner = let
makeService = service: ''
echo "Starting service ${service.name}"
${pkgs.tmux}/bin/tmux new-window -n '${service.name}' -t '${sessionName}' '${service.command}'
'';
in pkgs.writeShellScript "service-runner" ''
# In case user is running multiple terminals with the same devshell
${pkgs.tmux}/bin/tmux list-sessions | grep '^${sessionName}: ' && exit 0
${pkgs.tmux}/bin/tmux new-session -d -s '${sessionName}'
${lib.strings.concatStringsSep
"\n"
(map
makeService
services
)
}
'';
serviceViewer = writeShellScriptBin "service-viewer" ''
serviceName="$1"
case "$serviceName" in
${lib.strings.concatStrings (map (service: "${service.name})\n;;\n") services)}
*)
echo "Invalid service name. Choose one of ${lib.strings.concatStringsSep "\n" (map (service: service.name) services)}"
exit 1
;;
esac
${pkgs.tmux}/bin/tmux select-window -t '${sessionName}':"$serviceName" \; a -t '${sessionName}'
'';
# write a bash profile to load
bashrc = writeText "${name}-bashrc" ''
# Set all the passed environment variables
${envToBash env}
# Prepend the PATH with the devshell dir and bash
PATH=''${PATH#/path-not-set:}
PATH=''${PATH#${bashBin}:}
export PATH=$DEVSHELL_DIR/bin:${bashBin}:$PATH
# Expose the path to nixpkgs
export NIXPKGS_PATH=${toString pkgs.path}
function stopServices {
echo "Cleaning up services"
${pkgs.tmux}/bin/tmux kill-session -t '${sessionName}'
}
trap stopServices EXIT
${serviceRunner}
# 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
# Use this to set even more things with bash
${bash.extra or ""}
__devshell-motd() {
cat <<DEVSHELL_PROMPT
${motd}
DEVSHELL_PROMPT
}
# Print the motd in direnv
if [[ ''${DIRENV_IN_ENVRC:-} = 1 ]]; then
__devshell-motd
fi
# Interactive sessions
if [[ $- == *i* ]]; then
# Print information if the prompt is every 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}
# Set a cool PS1
if [[ -n "$PS1" ]]; then
# Print the path relative to $DEVSHELL_ROOT
rel_root() {
local path
path=$(${coreutils}/bin/realpath --relative-to "$DEVSHELL_ROOT" "$PWD")
if [[ $path != . ]]; then
echo " $path "
fi
}
PS1='\[\033[38;5;202m\][${name}]$(rel_root)\$\[\033[0m\] '
fi
# Load bash completions
for file in "$DEVSHELL_DIR/share/bash-completion/completions/"* ; do
[[ -f "$file" ]] && source "$file"
done
${bash.interactive or ""}
fi # Interactive session
'';
# This is our entry-point for everything!
devShellBin = derivation {
inherit system;
name = "${name}-bin";
# Define our own minimal builder.
builder = bashPath;
args = [
"-ec"
''
${coreutils}/bin/cp $envScriptPath $out &&
${coreutils}/bin/chmod +x $out;
exit 0
''
];
# The actual devshell wrapper script
envScript = ''
#!${bashPath}
# Script that sets-up the environment. Can be both sourced or invoked.
# This is the directory that contains our dependencies
export DEVSHELL_DIR=${envDrv}
# It assums that the shell is always loaded from the root of the project
# Store that for later usage.
export DEVSHELL_ROOT=$PWD
# If the file is sourced, skip all of the rest and just source the
# bashrc
if [[ $0 != "''${BASH_SOURCE[0]}" ]]; then
source "${bashrc}"
return
fi
# Be strict!
set -euo pipefail
if [[ $# = 0 ]]; then
# Start an interactive shell
exec "${bashPath}" --rcfile "${bashrc}" --noprofile
elif [[ $1 == "-h" || $1 == "--help" ]]; then
cat <<USAGE
Usage: ${name}
source $0 # load the environment in the current bash
$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 -c "$0" "$@"
else
# Start a script
source "${bashrc}"
exec -- "$@"
fi
'';
passAsFile = [ "envScript" ];
};
# Use this to define a flake app for the environment.
flakeApp = {
type = "app";
program = "${devShellBin}";
};
# Use a naked derivation to limit the amount of noise passed to nix-shell.
devShell = derivation {
inherit name system;
# `nix develop` actually checks and uses builder. And it must be bash.
builder = bashPath;
# Bring in the dependencies on `nix-build`
args = [ "-ec" "${coreutils}/bin/ln -s ${devShellBin} $out; exit 0" ];
# $stdenv/setup is loaded by nix-shell during startup.
# https://github.com/nixos/nix/blob/377345e26f1ac4bbc87bb21debcc52a1d03230aa/src/nix-build/nix-build.cc#L429-L432
stdenv = writeTextFile {
name = "devshell-stdenv";
destination = "/setup";
text = ''
# Fix for `nix develop`
: ''${outputs:=out}
runHook() {
eval "$shellHook"
unset runHook
}
'';
};
# The shellHook is loaded directly by `nix develop`. But nix-shell
# requires that other trampoline.
shellHook = ''
# Remove all the unnecessary noise that is set by the build env
unset NIX_BUILD_TOP NIX_BUILD_CORES NIX_BUILD_TOP NIX_STORE
unset TEMP TEMPDIR TMP TMPDIR
unset builder name out shellHook stdenv system
# Flakes stuff
unset dontAddDisableDepTrack outputs
# For `nix develop`
if [[ "$SHELL" == "/noshell" ]]; then
export SHELL=${bashPath}
fi
# Load the dev shell environment
source "${devShellBin}"
'';
};
out = devShell // {
inherit flakeApp;
};
in
out
;
# Build the devshell from pure JSON-like data
fromData = data: mkDevShell data;
importTOML = path: builtins.fromTOML (builtins.readFile path);
# Build the devshell from a TOML declaration
fromTOML = path: fromData (importTOML path);
in
{
inherit
fromData
fromTOML
importTOML
mkDevShell
;
__functor = _: mkDevShell;
}