forked from nix-community/nix-zsh-completions
-
Notifications
You must be signed in to change notification settings - Fork 1
/
_nix-common-options
445 lines (396 loc) · 14.5 KB
/
_nix-common-options
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
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
#autoload
if [[ $_NIX_SHELL_COMPLETION_LOADED ]]; then
# No point in re-defining these functions each time we do a completion
return 0
fi
# Simple completion function to select a system
# List gathered from: https://github.com/NixOS/nixpkgs/blob/master/lib/platforms.nix
_nix_systems () {
_values 'Systems' \
i686-linux x86_64-linux \
armv5tel-linux armv6l-linux armv7l-linux mips64el-linux \
x86_64-darwin \
i686-freebsd x86_64-freebsd \
i686-openbsd x86_64-openbsd \
i686-netbsd x86_64-netbsd \
i686-cygwin x86_64-cygwin
}
# Completion function to select an angle-bracket expression from the nix path
# Assumptions: No '=' in the actual path components in NIX_PATH
# TODO: Complete files in /some/path for expressions like <nixpkgs/pkgs/...>
# IMPROVEMENT: Remove '<nixos-config>' since that seems rather useless(?)
_nix_shortcuts () {
local nix_path=(${(s.:.)NIX_PATH})
local named=(${(M)nix_path:#*=*})
local dirs=(${nix_path:#*=*})
local valid_dir_globs=($^dirs"/*/default.nix(N:h:t)")
local valid_dirs=(${~valid_dir_globs})
local names=(${named%%=*})
_values shortcuts "<"${^valid_dirs}">" "<"${^names}">"
}
_nix_path() {
_alternative \
'nixpkgs:Nixpkgs:_nix_shortcuts' \
'path:File Path:_nix_complete_dotnix_files'
}
_nix_complete_dotnix_files () {
_path_files '-g' '*.nix(N) *(N-/)'
}
_nix_complete_includes () {
local cur=${words[$CURRENT]}
local -a nixpath=(${(s.:.)NIX_PATH})
local -a path_names
local p
for p in ${nixpath[*]}; do
[[ "$p" == *=* ]] && \
path_names+=(${p%=*}:Path:_nix_complete_dotnix_files)
done
if [[ $cur == *=* ]]; then
path_names+=(${cur%=*}:Path:_nix_complete_dotnix_files)
fi
_alternative \
"nixpath:nixpath:_values -s = 'Nix path name' $path_names" \
'file:Path:_files -/'
return
}
_nix_generations () {
# List of package names with version numbers stripped
setopt extendedglob
local -a generations=(${${${(f)"$(nix-env --list-generations)"}## #}/ /:})
_describe -V "Nix Generations" generations
}
_nix_installed_packages () {
# List of package names with version numbers stripped
# with the alternative to specify store paths
local extra_help=$1
local prefix='-P ./'
local current_word=$words[$CURRENT]
# When referencing an absolute path we can't prefix with ./
if [[ -z ${current_word:##(/*|\~/*)} && -n $current_word ]]; then
prefix=""
fi
local -a packages=(${${(f)"$(nix-env -q)"}%%-[0-9]*})
_alternative \
"package:packages:_values 'Installed package $extra_help' $packages" \
"file:Store path to package:_files ${prefix}"
}
# Generate nix code creating the default expression used by 'nix-env -iA'
_nix_gen_defexpr () {
setopt local_options null_glob
local -a result
local -a queue=($1)
while [[ ${#queue} > 0 ]]; do
local current=$queue[1]
shift queue
if [[ -e $current/default.nix ]]; then
result+=($current)
else
queue+=($current/*)
fi
done
local nix_expr="{\n"
for p in $result; do
nix_expr+="$(basename $p) = import $p {};"
nix_expr+="\n"
done
nix_expr+="}"
echo $nix_expr
}
# Complete attribute names using $1 as the toplevel expression NB: If calling
# this function from an action spec you need to prefix it with a space so that
# eg. _arguments won't pass it options which it doesn't expect, ie:
# `: _nix_attr_paths`
_nix_attr_paths () {
setopt local_options pipefail
local defexpr=$1
if [[ "$2" == false ]]; then
_message "The URL isn't cached, download to get completion"
return
fi
local attr_path=""
if [[ $words[CURRENT] == *.* ]]; then
attr_path=${words[CURRENT]%.*}
fi
local prefixed_path=top${attr_path:+.$attr_path}
# Build up a modified NIX_PATH using -I and --include
local i override=""
for ((i=1; i < ${#words[*]}; i++)); do
case "${words[i]}" in
-I|--include)
override+=${override:+:}${words[$((i+1))]}
;;
esac
done
override+=${override:+:}${NIX_PATH}
# Resolve channel: syntax
while [[ "$override" == *(=|:)channel:* ]]; do
local channel=${override#*channel:}
channel="channel:"${channel%%:*}
local url="https://nixos.org/channels/"${channel:8}"/nixexprs.tar.xz"
# Replace the channel with its url
override=${override/"$channel"/"$url"}
done
local cache_help=""
# Resolve any url to a cache, else we might trigger a blocking download
while [[ "$override" == *https://* ]]; do
# Find the first url
local url=${override#*https://}
# Strip everything starting with the first colon
url="https://"${url%%:*}
local cache=$(_nix_resolve_url "$url")
[[ -z "$cache" ]] \
&& cache_help=" (an URL in the NIX_PATH isn't cached, completion might not work)"
# Replace the url with the cache
override=${override/"$url"/"$cache"}
done
local -a result=($(
NIX_PATH=$override nix-instantiate --eval - 2> /dev/null \
<<NIX_FILE | tr '[]"' ' '
let
top_gen = $defexpr;
# --file arguments can be a lambda producing a record too
top = if builtins.typeOf top_gen == "lambda" then top_gen {} else top_gen ;
in
builtins.attrNames $prefixed_path
NIX_FILE
))
if [[ $? > 0 ]]; then
# Probably because of invalid attribute path or error in top-level expr
return 1
fi
local -a prefix=()
if [[ -n $attr_path ]]; then
for i in ${=attr_path//./ }; do
prefix+=("($i)" .)
done
fi
_wanted package package "Attribute path$cache_help" \
_sep_parts $prefix result \.
return $?
}
# Generate the top level expression in all the various ways the different
# commands expects it to be built. Then generate completions by calling
# _nix_attr_paths $defexpr
_nix_complete_attr_paths () {
local defexpr="" cached=true
local file=$(_nix_get_file_arg)
if [[ "$file" ]]; then
# Extract --arg and --argstr into $args
local i=1 args="" name="" value=""
for ((i=1; i < ${#words[*]}; i++)); do
case "${words[$i]}" in
--arg)
name=${(Q)words[$((i+1))]}
value=${(Q)words[$((i+2))]}
args+="$name = $value;"
i=$((i+2))
;;
--argstr)
name=${(Q)words[$((i+1))]}
value=${(Q)words[$((i+2))]}
args+="$name = \"$value\";"
i=$((i+2))
;;
esac
done
defexpr="import $file {$args}"
else
if [[ $service == nix-env ]]; then
defexpr=$(_nix_gen_defexpr ~/.nix-defexpr)
elif [[ $service == nix ]]; then
# Extract the channels from NIX_PATH and -I/--include
local -a channels=(${(s.:.)NIX_PATH})
# Add -I/--include afterwards, so they will shadow the NIX_PATH
channels+=(${(s.:.)opt_args[-I]})
channels+=(${(s.:.)opt_args[--include]})
# Add the names in an associative array to avoid duplicates
local -A names
local channel name
for channel in $channels; do
name=${channel%%=*}
nix_path=${channel#*=}
if [[ $name != $channel ]]; then
# Only add paths with a name, not sure how they work
names[$name]=1
fi
done
defexpr=$'{ '
for name in ${(@k)names}; do
# nixos-config isn't useful or possible to complete
[[ $name == nixos-config ]] && continue
defexpr+="$name = import <${name}> {}; "
done
defexpr+=' }'
fi
fi
_nix_attr_paths $defexpr $cached 2>/dev/null
}
function _nix_resolve_url () {
local -a sha
local url=$1
local version="$($service --version)"
if [[ "${version##* }" == 1.11.* ]]; then
# works for nix 1.11
sha=($(printf "$url" | sha256sum -))
else
# works for nix 1.12
local name="${url##*/}"
sha=($(printf "$name\0$url" | sha256sum -))
fi
local base=$(nix-hash --to-base32 --type sha256 \
${sha[*]:0:1})
local cache=${XDG_CACHE_HOME:-~/.cache}/nix/tarballs
local link="$cache"/"$base"-file
if [[ -e "$link" ]]; then
echo "$cache/$(basename $(readlink $link))-unpacked"
fi
}
function _nix_get_file_arg () {
local file=""
if [[ "$service" == (nix-env|nix) ]]; then
local i
# Extract the last seen -f/--file argument
for ((i=1; i < ${#words[*]}; i++)); do
case "${words[i]}" in
--file|-f)
file=${words[$((i+1))]}
;;
esac
done
elif [[ $line ]]; then
file=$line[1]
elif [[ -e shell.nix && $service == nix-shell ]]; then
file=shell.nix
elif [[ -e default.nix ]]; then
file=default.nix
fi
# Remove one level of shell quoting to make sure we see the same value as
# the nix-* program will see.
# ($opt_args and $line contain the verbatim string:
# eg. given `nix-shell '<nixpkgs>' -A ` $line[1] will be `'<nixpkgs>'` while
# nix-shell will see `<nixpkgs>`)
file=${(Q)file}
if [[ "file" ]]; then
# Expand channel: syntax
if [[ "$file" == channel:* ]]; then
file="https://nixos.org/channels/"${file:8}"/nixexprs.tar.xz"
fi
if [[ -e $file ]]; then
# If the path exist use the absolute path to make sure import will
# accept it.
# (Otherwise the path is likely a <nixpkgs> notation)
file=${file:a}
elif [[ "$file" == https://* ]]; then
file=$(_nix_resolve_url $file)
[[ -z "$file" ]] && cached=false
fi
fi
print -n -- $file
}
function _nix_complete_function_arg () {
local file=$(_nix_get_file_arg)
local -a names=($(nix-instantiate --eval - <<NIX_FILE 2> /dev/null \
| tr '"[]' ' '
let
args = builtins.functionArgs (import $file);
in
builtins.attrNames args
NIX_FILE
))
_values "Argument name" $names
}
_nix_profiles () {
local -a profiles
profiles=($(find /nix/var/nix/profiles))
_values "Nix Profiles" $profiles
}
# Used in: nix-build, nix-env, nix-instantiate, nix-shell, nixops
_nix_boilerplate_opts=(
'(- *)--help[Print help message and exit]' \
'(- *)--version[Print version number and exit]'
)
# Used in: nix-collect-garbage, nix-env, nix-store, nixops
_nix_dry_run='--dry-run[Show what would be done without doing it]'
# Used in: nix-collect-garbage, nix-store
_nix_gc_common=(
'(- --print* --delete)--print-roots[Print roots used by garbage collector]' \
'(- --print* --delete)--print-live[Print store paths reachable from roots]' \
'(- --print* --delete)--print-dead[Print store paths not reachable from roots]' \
'(- --print* --delete)--delete[Garbage collect all dead paths from the store]' \
)
# Used in: nixos-install, nix_common_opts
_nix_search_path_args=(
'*-I+[Add path to Nix expression search path]:Include path:_nix_complete_includes'\
)
# Either true or false: useful for completing many Nix options
_nix_options_bool () {
_values true false
}
# List gathered from: https://nixos.org/nix/manual/#sec-conf-file
# TODO: Complete the value as well, not just the key
_nix_options () {
_values \
'gc-keep-outputs' \
'gc-keep-derivations' \
'env-keep-derivations' \
'build-max-jobs' \
'build-cores' \
'build-max-silent-time' \
'build-timeout' \
'build-max-log-size' \
'build-users-group' \
'build-use-chroot' \
'build-chroot-dirs' \
'build-extra-chroot-dirs' \
'build-use-substitutes' \
'build-fallback' \
'build-cache-failure' \
'build-keep-log' \
'build-compress-log' \
'use-binary-caches' \
'binary-caches' \
'binary-caches-files' \
'trusted-binary-caches' \
'extra-binary-caches' \
'signed-binary-caches' \
'binary-cache-public-keys' \
'binary-caches-parallel-connections' \
'verify-https-binary-caches' \
'force-manifest' \
'system' \
'fsync-metadata' \
'auto-optimise-store' \
'connect-timeout' \
'log-servers' \
'trusted-users' \
'allowed-users' \
'restrict-eval' \
'pre-build-hook'
}
_nix_repair='--repair[Fix corrupted or missing store paths by redownloading or rebuilding]';
# Misc Nix options accepted by nixos-rebuild
_nix_common_nixos_rebuild=(
$_nix_search_path_args \
'(--verbose -v)*'{--verbose,-v}'[Increase verbosity of diagnostic messages]'\
'(--no-build-output -Q)'{--no-build-output,-Q}'[Silence output to stdout and stderr]'\
'(--max-jobs -j)'{--max-jobs,-j}'[Set the maximum number of build jobs that Nix will perform in parallel]'\
'--cores[Set the parallelism of the individual builders (e.g. -j argument to make)]'\
'(--keep-going -k)'{--keep-going,-k}'[Keep going in case of failed builds, to the greatest extent possible]'\
'(--keep-failed -K)'{--keep-failed,-K}'[Do not delete the build directory if build fails]'\
'--fallback[If binary download fails, fall back on building from source]'\
'--show-trace[Print stack trace of evaluation errors]'\
'--option[Set Nix configuration option]:Options:_nix_options:Value:( )'\
$_nix_repair
)
# Used in: nix-build, nix-env, nix-instantiate, nix-shell
_nix_common_opts=(
$_nix_common_nixos_rebuild \
'(--attr -A)'{--attr,-A}'[Select an attribute from the top-level Nix expression being evaluated]:Packages: _nix_complete_attr_paths'\
'*--arg[Argument to pass to the Nix function]:Name:_nix_complete_function_arg:Value: '\
'*--argstr[Like --arg, but the value is a string]:Name:_nix_complete_function_arg:String: '\
'--max-silent-time[Builder times out after not producing stdout/stderr for x seconds]:Seconds:( )'\
'--timeout[Timeout builder after given number of seconds]:Seconds:( )'\
'--readonly-mode[Do not open Nix database]'\
'--log-type[Configure how output is formatted]:Output format:((pretty\:"Default" escapes\:"Indicate nesting with escape codes" flat\:"Remove all nesting"))'\
)
_NIX_SHELL_COMPLETION_LOADED=1