git-subtree-dir: 3dp/nix-zsh-completions git-subtree-split: ad4477be7c63af2167f1e2bc2857127700321341
7TOUKKDEFYRNQZ5UG32B7EK2YCTYACHXMWWNK46LVJ2LMKDSDHKQC
# Nix Install
alias ni='nix-env -iA'
# Nix Search
alias ns='nix-env -qaP'
function prompt_nix_shell_precmd {
if [[ ${IN_NIX_SHELL} -eq 1 ]] then
if [[ -n ${IN_WHICH_NIX_SHELL} ]] then
NIX_SHELL_NAME=": ${IN_WHICH_NIX_SHELL}"
fi
NIX_PROMPT="%F{8}[%F{3}nix-shell${NIX_SHELL_NAME}%F{8}]%f"
if [[ $PROMPT != *"$NIX_PROMPT"* ]] then
PROMPT="$NIX_PROMPT $PROMPT"
fi
fi
}
function prompt_nix_shell_setup {
autoload -Uz add-zsh-hook
add-zsh-hook precmd prompt_nix_shell_precmd
}
prompt_nix_shell_setup "$@"
# Source module files.
source "${0:h}/nix.plugin.zsh" || return 1
#compdef nixos-version
#autoload
_nix-common-options
_arguments \
'(- *)'{--hash,--revision}'[Print only the git hash of the channel]'\
#compdef nixos-rebuild
#autoload
_nix-common-options
local -a _1st_arguments
_1st_arguments=(
'switch:Build, activate, and update boot default'\
'boot:Build and update boot default without activating'\
'test:Build and activate without updating boot default'\
'build:Build without activating or updating boot default'\
'dry-build:Show what store paths would be built or downloaded without building'\
'dry-activate:Build and show what changes would be performed by the activation'\
'build-vm:Create a script which starts a VM with the built configuration'\
'build-vm-with-bootloader:Like build-vm, but boot using regular boot loader'
)
_arguments \
$_nix_common_nixos_rebuild \
'--upgrade[Fetch the latest version of NixOS from the NixOS channel]'\
'--install-grub[(Re)install grub on the configured device]'\
"--no-build-nix[Don't build Nix package manager]"\
'--fast[Equivalent to --no-build-nix --show-trace]'\
'--rollback[Roll back to the previous configuration]'\
'(--profile-name -p)'{--profile-name,-p}'[Profile to use to track current and previous system configurations]:Profile:_nix_profiles'\
'1:: :->subcmds' && return 0
case $state in
subcmds)
_describe -t commands "nixos-rebuild subcommands" _1st_arguments
;;
esac
#compdef nixos-install
#autoload
_nix-common-options
_arguments \
$_nix_search_path_args \
'--root[Treat the given directory as the root of the NixOS installation]:Installation Root:_files -/'\
'--show-trace[Print a stack trace in case of evaluation errors]'\
'--chroot[Chroot into given installation]'
#compdef nixos-generate-config
#autoload
_nix-common-options
_arguments \
'--force[Overwrite /etc/nixos/configuration.nix if it exists]:'\
'--root[Directory to treat as root of filesystem]:Root directory:_files -/'\
'--dir[Directory to write configuration files to (Default /etc/nixos)]:Output directory:_files -/'\
'--no-filesystems[Omit file system information from hardware configuration]'\
'--show-hardware-config[Print hardware configuration to stdout without writing anything to disk]'
#compdef nixos-container
#autoload
_nix-common-options
_containers () {
containers=($(nixos-container list))
_wanted containers expl 'containers' compadd -a containers
}
local -a _1st_arguments
_1st_arguments=(
'list:Show list of containers'\
'create:Create a container'\
'destroy:Destroy a container'\
'start:Start a container'\
'stop:Stop a container'\
'status:Get status of a container'\
'update:Update container'\
'login:Login to a container'\
'root-login:Login to a container as root (no password needed)'\
'run:Run a container'\
'show-ip:Display the IP of a container'\
'show-host-key:Display the host key of a container'
)
_arguments \
'(- 1 *)--help[Display help]'\
'*:: :->subcmds' && return 0
if (( CURRENT==1 )); then
_describe -t commands "nixos-container subcommands" _1st_arguments
return
fi
local _container_name='1:Container Name:_containers';
local _container_config='--config[Config]:Config:( )';
case "$words[1]" in
create)
_arguments\
$_container_name\
$_container_config\
'--system-path[System path]:Path:_files'\
'--ensure-unique-name[Avoid name conflicts with other containers]'\
'--auto-start[Start the container immediately]'
;;
run)
# TODO: There are a few more arguments in this case
_arguments\
$_container_name\
;;
update)
_arguments\
$_container_name\
$_container_config
;;
destroy|start|stop|status|login|root-login|show-ip|show-host-key)
_arguments\
$_container_name
;;
esac
#compdef nixos-build-vms
#autoload
_nix-common-options
_arguments \
'--show-trace[Show a trace of the output]'\
"--no-out-link[Do not create a 'result' symlink]"\
'1:Network Nix Expression:_nix_complete_dotnix_files'
#compdef nixops
#autoload
_nix-common-options
# List of valid commands
local -a _1st_arguments
_1st_arguments=(
"list:list all known deployments"\
"create:create a new deployment"\
"modify:modify an existing deployment"\
"clone:clone an existing deployment"\
"delete:delete a deployment"\
"info:show the state of the deployment"\
"check:check the state of the machines in the network"\
"set-args:persistently set arguments to the deployment specification"\
"deploy:deploy the network configuration"\
"send-keys:send encryption keys"\
"destroy:destroy all resources in the specified deployment"\
"stop:stop all virtual machines in the network"\
"start:start all virtual machines in the network"\
"reboot:reboot all virtual machines in the network"\
"show-physical:print the physical network expression"\
"ssh:login on the specified machine via SSH"\
"ssh-for-each:execute a command on each machine via SSH"\
"scp:copy files to or from the specified machine via scp"\
"rename:rename machine in network"\
"backup:make snapshots of persistent disks in network (EC2-only)"\
"backup-status:get status of backups"\
"remove-backup:remove a given backup"\
"clean-backups:remove old backups"\
"restore:restore machines based on snapshots of persistent disks in network (EC2-only)"\
"show-option:print the value of a configuration option"\
"list-generations:list previous configurations to which you can roll back"\
"rollback:roll back to a previous configuration"\
"delete-generation:remove a previous configuration"\
"show-console-output:print the machines console output on stdout"\
"dump-nix-paths:dump Nix paths referenced in deployments"\
"export:export the state of a deployment"\
"import:import deployments into the state file"\
"edit:open the deployment specification in \$EDITOR"\
)
# Options valid for every command
local -a _nixops_common_arguments
_nixops_common_arguments=(
'(--state -s)'{--state,-s}'[Path to state file that contains the deployments]:Statefile:_files -g \*.nixops'\
'(--deployment -d)'{--deployment,-d}'[UUID or symbolic name of deployment on which to operate]'\
'--confirm[Automatically confirm "dangerous" actions]'\
'--debug[Turn on debugging output]'\
)
local -a _nixops_include_exclude
_nixops_include_exclude=(
'--include[Only operate on the specified machines]:Machine Names:_hosts' \
'--exclude[Do not operate on the specified machines]:Machine Names:_hosts' \
)
local -a _nixops_search_path_args
_nixops_search_path_args=(
'-I[Add path to the Nix expression search path for all future evaluations]:Path:_files -/' \
)
_arguments \
$_nix_boilerplate_opts \
'*:: :->subcmds' && return 0
if (( CURRENT==1 )); then
_describe -t commands "nixos-container subcommands" _1st_arguments
return
fi
case "$words[1]" in
create)
_arguments \
$_nixops_common_arguments\
$_nixops_search_path_args \
'*:Nix Expressions:_nix_complete_dotnix_files'
;;
modify)
_arguments \
$_nixops_common_arguments\
$_nixops_search_path_args \
'(--name -n)'{--name,-n}'[Change the symbolic name]:New Name:( )'\
;;
clone)
_arguments \
$_nixops_common_arguments\
'(--name -n)'{--name,-n}'[Symbolic name for the new deployment]'\
;;
delete)
_arguments \
$_nixops_common_arguments\
'--all[Delete all deployments in the state file]'\
'--force[]'
;;
deploy)
_arguments \
$_nixops_common_arguments\
'(--kill-obsolete -k)'{--kill-obsolete,-k}'[Destroy machines no longer listed in the deployment specification]'\
$_nix_dry_run \
$_nix_repair \
'--create-only[Create missing machines only: build nothing and do not touch existing machines]'\
'--build-only[Build the configuration without creating or deploying machines]'\
'--copy-only[Do everything except activate the new configuration]'\
'--check[Check that deployed machines are correctly configured]'\
'--allow-reboot[Allow NixOps to reboot the instance if necessary]'\
'--force-reboot[Reboot the machine to activate the new configuration]'\
'--allow-recreate[Recreate resources that have disappeared]'\
$_nixops_include_exclude \
$_nixops_search_path_args \
'--max-concurrent-copy[Set the maximum concurrent nix-copy-closure processes (Default 5)]:Number:( )'
;;
destroy)
_arguments \
$_nixops_common_arguments\
'--all[Destroy all deployments]'\
$_nixops_include_exclude \
;;
stop)
_arguments \
$_nixops_common_arguments\
$_nixops_include_exclude \
;;
start)
_arguments \
$_nixops_common_arguments\
$_nixops_include_exclude \
;;
info)
_arguments \
$_nixops_common_arguments\
'--all[Print information about all resources in all known deployments]'\
'--plain[Print in a more easily parsed format]'\
'--no-eval[Do not evaluate the deployment specification]'
;;
check)
_arguments \
$_nixops_common_arguments\
'--all[Check all machines in all known deployments]'
;;
ssh)
_arguments \
$_nixops_common_arguments\
'--include-keys[]'
;;
ssh-for-each)
_arguments \
$_nixops_common_arguments\
'(--parallel -p)'{--parallel -p}'[Execute the command on each machine in parallel]'\
$_nixops_include_exclude \
;;
reboot)
_arguments \
$_nixops_common_arguments\
$_nixops_include_exclude \
'--no-wait[Do not wait until the machines have finished rebooting]'
;;
backup)
_arguments \
$_nixops_common_arguments\
$_nixops_include_exclude \
;;
restore)
_arguments \
$_nixops_common_arguments\
$_nixops_include_exclude \
'--devices[Restore only the persistent disks which are mapped to the specified device names]:Device names:( )'\
'--backup-id[Restore the persistent disks of all machines to a given backup except the ones listed here.]:Backup ids:( )'
;;
show-option)
_arguments \
$_nixops_common_arguments\
'--xml[Format output as XML]'\
'1:machine:_hosts'\
'2:option:( )'
;;
set-args)
_arguments \
$_nixops_common_arguments\
'--arg[Set the function argument]:Name:( ):Value:( )'\
'--argstr[Like --arg but the value is a string]:Name:( ):Value:( )'\
'--unset[Remove a previously set function argument]:Name:( )'
;;
show-console-output)
_arguments \
$_nixops_common_arguments\
'1:machine:_hosts'
;;
export)
_arguments \
$_nixops_common_arguments\
'--all[Apply to all deployments]'
;;
import)
_arguments \
$_nixops_common_arguments\
'--include-keys[]'
;;
*)
_arguments \
$_nixops_common_arguments\
;;
esac
#compdef nix-store
#autoload
_nix-common-options
local -a _1st_arguments
_1st_arguments=(
{--realise,-r}':Build the specified store paths' \
'--gc:Perform garbage collection on the Nix store' \
'--delete:Delete store paths from the Nix store if it is safe to do so' \
{--query,-q}':Display information about store paths' \
'--add:Add paths to the Nix store' \
'--verify:Verify the consistency of the Nix database and store' \
'--verify-path:Compare the contents of each store path to the hashes stored in the database' \
'--repair-path:Attempt to repair the specified paths by redownloading them' \
'--dump:Produce a NAR file containing the contents of the given path' \
'--restore:Unpack a NAR archive, read from stdin, to the given path' \
'--export:Serialize the specified store paths to stdout in a format which can be imported' \
'--import:Read searialized store paths from stdin and add them to the Nix store' \
'--optimise:Find identical files in the Nix store and hardlink them together to reduce disk usage'\
{--read-log,-l}':Print the build log of the specified store paths' \
'--dump-db:Dump Nix database to stdout' \
'--load-db:Read a dump of the Nix database' \
'--print-env:Print the environment of a derivation as shell code' \
'--query-failed-paths:Print out store paths which failed to build' \
'--clear-failed-paths:Clear the "failed" state of the given store path' \
)
_arguments \
'*:: :->subcmds' && return 0
if (( CURRENT==1 )); then
_describe -t commands "nix-store subcommands" _1st_arguments
return
fi
case "$words[1]" in
--realise|-r)
_arguments \
$_nix_dry_run \
'--ignore-unknown[Silently ignore non-derivation paths with no substitute]' \
'*:Store Paths:_files'
;;
--gc)
_arguments \
$_nix_gc_common \
'--max-freed[Stop garbage collection once this many bytes has been freed]:Bytes:( )'
;;
--delete)
_arguments \
'--ignore-liveness[Ignore reachability from roots]'
;;
--query|-q)
local -a _queries
_queries=(
'--outputs:Print the output paths of the given store derivations' \
{--requisites,-R}':Print the closure of the given store paths' \
'--references:Print immediate dependencies of the given store paths' \
'--referrers:Print store paths which refer to these paths' \
'--referrers-closure:Print the closure under the referrers relation' \
'--deriver:Print the deriver of the store paths' \
'--graph:Print the references graph of the store paths in Graphviz format' \
'--tree:Print the references graph of the store paths as an ASCII tree' \
'--binding:Print the value of an attribute of the store derivations' \
'--hash:Print the SHA-256 hash of the contents of the store paths' \
'--size:Print the size in bytes of the contents of the store paths' \
'--roots:Print the garbage collector roots that point to the store paths' \
)
local -a _query_common
_query_common=(
'(--use-output -u)'{--use-output,-u}'[Apply the query to the output path of any store derivations]' \
'(--force-realise -f)'{--force-realise,-f}'[Realise each argument to the query first]' \
)
if (( CURRENT == 2 )); then
_describe -t commands "Query subcommands" _queries
return
fi
case "$words[2]" in
--requisites|-R)
_arguments $_query_common \
'--include-outputs[Also include the output paths of store derivations]' \
'*: :_files'
;;
*)
_arguments $_query_common \
'*: :_files'
;;
esac
;;
--verify)
_arguments \
'--check-contents[Compute and validate the SHA-256 hash of each store item]' \
'--repair[Attempt to repair invalid or missing paths by redownloading them]'
;;
--dump-db|--load-db|--query-failed-paths)
# Nothing to complete
;;
*)
_arguments \
'*: :_files'
;;
esac
#compdef nix-shell
#autoload
local command_name=nix-shell
_nix-common-options
local -a _nix_shell_opts
_nix_shell_opts=(
'--command[Run a command instead of starting an interactive shell]:Command:_command_names' \
'--exclude[Do not build any dependencies which match this regex]:Regex:( )' \
'--pure[Clear the environment before starting the interactive shell]' \
'(--packages -p)'{--packages,-p}'[Set up an environment where the given packages are present]:*:Packages: _nix_attr_paths "<nixpkgs>"' \
)
_arguments \
$_nix_boilerplate_opts \
$_nix_common_opts \
$_nix_shell_opts \
'*:Paths:_nix_path' \
#compdef nix-push
#autoload
_nix-common-options
_arguments \
'--dest[Set the destination directory]:Destination directory:_files -/'\
'(--none)--bzip2[Compress NARs using bzip2 instead of xz -9]'\
'(--bzip2)--none[Do not compress NARs]'\
'--force[Overwrite .narinfo files if they already exist]'\
'--link[Hard link files into the destination directory rather than copying]'\
'(--manifest-path)--manifest[Force the generation of a manifest suitable for use by nix-pull]'\
'(--manifest)--manifest-path[Like --manifest, but specify the manifest filename]:Manifest filename:_files'\
'--url-prefix[Specify the prefix URL used in the Manifest]:Prefix URL:_urls'\
'*:Derivation Paths:_files'
#compdef nix-prefetch-url
#autoload
_nix-common-options
_arguments \
'--type[Use the specified cryptographic hash algorithm]:Hash Algorithm:(md5 sha1 sha256)'\
'1:URL:_urls'\
'2::Hash:( )'
#compdef nix-instantiate
#autoload
local command_name=nix-instantiate
_nix-common-options
# --no-location: undocumented arg
# --repair: undocumented arg
_arguments \
$_nix_boilerplate_opts \
$_nix_common_opts \
'--xml[Print output from --eval as XML]'\
'--json[Print output from --eval as JSON]'\
'--add-root[Register result as a root of the garbage collector]::Path (Hint /nix/var/nix/gcroots):_files -/'\
'--indirect[Allow roots to be stored outside of the GC roots directory]'\
'--parse[Just parse the input files and print their abstract syntax trees]'\
'--eval[Just parse and evaluate the input files, and print the resulting values]'\
"(- *)--find-file[Look up the given files on Nix's search path]:*:Files:_files"\
'--strict[Cause --eval to recursively evaluate list elements and attributes]'\
'--read-write-mode[Perform evaluation in read/write mode]'\
#compdef nix-install-package
#autoload
_nix-common-options
_arguments \
'--non-interactive[Do not open a terminal window and do not ask for confirmation]' \
'(--profile -p)'{--profile,-p}'[Profile to install the package into]:Profile:_nix_profiles' \
'--set[Install the package as the profile so that the profile contains nothing else]' \
'(1)--url[URL to download the package file from]:URL:_urls' \
'(--url)1:Package File:_files -g \*.nixpkg'
#compdef nix-hash
#autoload
_nix-common-options
local -a ig
ig=( '--to-base16' '--to-base32' )
_arguments \
'(- *)--to-base16[Convert a base 32 hash to hexadecimal]:Hash:( )' \
'(- *)--to-base32[Convert a hexadecimal hash to base 32]:Hash:( )' \
"($ig)--flat[Print hash of regular files rather than their NAR dump]" \
"($ig)--base32[Print hash in base 32 rather than hexadecimal]" \
"($ig)--truncate[Truncate hashes to 160 bits]" \
"($ig)--type[Hash algorithm to use]:hashAlgo:(md5 sha1 sha256)" \
"($ig)*:Store Paths:_files" && return 0
#compdef nix-env
#autoload
emulate -L zsh
setopt extendedglob
local command_name=nix-env
_nix-common-options
local -a _1st_arguments
_1st_arguments=(
{--install,-i}":Install package"\
{--upgrade,-u}":Upgrade package"\
{--uninstall,-e}":Uninstall package"\
"--set-flag:Modify meta attribute of installed package"\
{--query,-q}":List information about derivations"\
{--switch-profile,-S}":Set the current profile path"\
"--list-generations:Print a list of all generations in the active profile"\
"--delete-generations:Delete specified generations"\
{--switch-generation,-G}":Activate specified generation"\
"--rollback:Switch to the previous generation of active profile"
)
local -a _nix_env_common_opts
_nix_env_common_opts=(
$_nix_common_opts \
'(--file -f)'{--file,-f}'[Specify Nix expression used to obtain derivations]:Path to file:_nix_path'\
'(--profile -p)'{--profile,-p}'[Specify the profile to use]:Path:_nix_profiles'\
$_nix_dry_run \
'--system-filter[Only show derivations matching the specified platform]:system:_nix_systems'\
)
local -a _nix_env_b
_nix_env_b=('(--prebuilt-only -b)'{--prebuilt-only,-b}'[Fail if there is no pre-built binary available]')
local _nix_env_from_profile
_nix_env_from_profile='--from-profile[Fetch store paths from another profile]:Profile:_nix_profiles'
_arguments \
'*:: :->subcmds' && return 0
# TODO: For some reason boilerplate opts hide all other opts
#$_nix_boilerplate_opts \
if (( CURRENT==1 )); then
_describe -t commands "nix-env subcommands" _1st_arguments
return
fi
# Workaround:
# opt_args doesn't contain the first option
# so can't detect stacked options like '-iA'
local expect_attr_paths=false
for opt in $words; do
case $opt in
--attr|-[^-]#A[^-]#)
expect_attr_paths=true
;;
esac
done
case "$words[1]" in
--install|-[^-]#i[^-]#)
_arguments -s \
$_nix_env_common_opts \
$_nix_env_b \
$_nix_env_from_profile \
'(--preserve-installed -P)'{--preserve-installed,-P}'[Do not remove derivations with the same name]' \
'(--remove-all -r)'{--remove-all,-r}'[Remove all previously installed packages prior to installing]' \
'*:Package:{if $expect_attr_paths; then _nix_attr_paths ; fi}'\
;;
--upgrade|-[^-]#u[^-]#)
_arguments -s $_nix_env_common_opts \
$_nix_env_b \
$_nix_env_from_profile \
'(-lt -leq -eq --always)--lt[Upgrade derivations with newer versions (default)]' \
'(-lt -leq -eq --always)--leq[Upgrade derivations with the same or newer version]' \
'(-lt -leq -eq --always)--eq[Upgrade derivations with equivalent versions]' \
'(-lt -leq -eq --always)--always[Upgrade even if version number decreases]' \
'*:Packages:_nix_installed_packages'
;;
--uninstall|-[^-]#e[^-]#)
_arguments -s '*::Packages:_nix_installed_packages'
;;
--set-flag)
_set_flag_attrs=(
'priority:Resolve package name conflicts' \
'keep:Prevent package from being upgraded' \
'active:Package is symlinked to profile' \
)
if (( CURRENT==2 )); then
_describe -t commands "nix-env subcommands" _set_flag_attrs
return
fi
if (( CURRENT==3 )); then
case "$words[2]" in
priority)
;;
keep)
_values "TF" true false
;;
active)
_values "TF" true false
;;
esac
else
_nix_installed_packages
fi
;;
--query|-[^-]#q[^-]#)
_arguments -s -O options $_nix_env_common_opts \
'(--available -a)'{--available,-a}'[Display all installable derivations]' \
$_nix_output_opts \
$_nix_env_b \
'(--status -s)'{--status,-s}'[Print status of derivation]' \
'(--attr-path -P)'{--attr-path,-P}'[Print attribute path of derivations]' \
'--no-name[Suppress printing of name attribute]' \
'(--compare-versions -c)'{--compare-versions,-c}'[Compare installed and available version]' \
'--system[Print system attribute]' \
'--drv-path[Print store derivation path]' \
'--out-path[Print output path]' \
'--description[Print description]' \
'--xml[Print output as XML]'\
'--json[Print output as JSON]'\
'--meta[Print all meta attributes: only available with --xml]'\
;;
--switch-profile|-[^-]#S[^-]#)
_arguments ':Profile:_nix_profiles'
;;
--delete-generations)
_arguments \
'*::Generations:_nix_generations'
;;
--switch-generation|-[^-]#G[^-]#)
_arguments '::Generations:_nix_generations'
;;
esac
#compdef nix-copy-closure
#autoload
_nix-common-options
_arguments \
'(--from)--to[Copy the closure to the remote machine (default)]'\
'(--to)--from[Copy the closure from the remote machine]'\
'--sign[Cryptographically sign to allow sharing between untrusted users on trusted machines]'\
'--gzip[Enable compression of the SSH connection]'\
'--include-outputs[Also copy outputs of store derivations included in the closure]'\
'(--use-substitutes -s)'{--use-substitutes,-s}'[Download files from the binary cache if possible]'\
'1:user@machine:_user_at_host'\
'2:paths:_files'
#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_generations () {
# List of package names with version numbers stripped
local generations=($(nix-env --list-generations | awk '{print $1":"$2}'))
_describe "Nix Generations" generations
}
_nix_installed_packages () {
# List of package names with version numbers stripped
local -a packages
packages=($(nix-env -q | perl -pe 's/-[0-9.-].*$//'))
_values "Nix Packages" $packages
}
# 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
}
# Prints the attribute names (whitespace separated) of the given path
# Arguments: attribute_path [top_level_expr_path]
# top_level_expr is interpreted as 'nix-env --file'
# if top_level_expr is omitted it defaults to what 'nix-env -iA' uses
# Eg. _nix_attr_names nixos.python2Packages mypkgs.nix
_nix_attr_names () {
setopt local_options pipefail
local attr_path=top${1:+.$1}
local defexpr_path=$2
local defexpr
if [[ -n $defexpr_path ]]; then
if [[ -e $defexpr_path ]]; then
# If the path exist use the absolute path to make sure import will
# accept it.
# (Otherwise the path is likely a <nixpkgs> notation)
defexpr_path=${defexpr_path:a}
fi
defexpr="import $defexpr_path"
elif [[ $command_name == nix-env ]]; then
defexpr=$(_nix_gen_defexpr ~/.nix-defexpr)
fi
nix-instantiate --eval - \
<<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 $attr_path
NIX_FILE
return $?
}
# Complete attribute paths
# NB: this function expects an optional argument so the user must make sure
# zsh completion functions doesn't supply arguments. eg. when used in a
# action spec to _arguments the function should be prefixed with a space:
# `: _nix_attr_paths`
# Without the space prefix _arguments will inject lots of arguments. These
# are available(?) in the `expl` array anyway
_nix_attr_paths () {
local attr_path=""
if [[ $words[CURRENT] == *.* ]]; then
attr_path=${words[CURRENT]%.*}
fi
local defexpr_path=$1
if [[ -z $defexpr_path ]]; then
if [[ $command_name == nix-env ]]; then
defexpr_path=$opt_args[-f]
if [[ -z $defexpr_path ]]; then
defexpr_path=$opt_args[--file]
fi
else
if [[ $line ]]; then
defexpr_path=$line[1]
elif [[ -e shell.nix && $command_name == nix-shell ]]; then
defexpr_path=shell.nix
elif [[ -e default.nix ]]; then
defexpr_path=default.nix
fi
fi
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>`)
defexpr_path=${(Q)defexpr_path}
local -a result # must be on separate line to capture error code..
result=( $(_nix_attr_names "$attr_path" $defexpr_path) ) 2>/dev/null
if [[ $? > 0 ]]; then
# Probably because of invalid attribute path or error in top-level expr
return 1
fi
local prefix
if [[ -n $attr_path ]]; then
prefix=${attr_path}.
fi
_values -s . "Packages" ${prefix}${^result}
}
_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_dotnix_files'\
)
# 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=(
'(--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 \
$_nix_search_path_args \
'(--attr -A)'{--attr,-A}'[Select an attribute from the top-level Nix expression being evaluated]:Packages: _nix_attr_paths'\
'(--expr -E)'{--expr,-E}'[Interpret command line args as Nix expressions]:*:Files:_files'\
'*--arg[Argument to pass to the Nix function]:Name:( ):Value:( )'\
'--argstr[Like --arg, but the value is a 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
#compdef nix-collect-garbage
#autoload
_nix-common-options
_arguments \
'(--delete-old -d)'{--delete-old,-d}'[Delete all old generations of all profiles]'\
'--delete-older-than[Delete generations older than the given time]:Time such as 30d:( )'\
$_nix_dry_run \
#compdef nix-channel
#autoload
_nix-common-options
# TODO: Handle case where nix-channel --list is empty
_nix_channels() {
_values 'Nix Channels' $(nix-channel --list | awk '{ print $1 }' ORS=' ')
}
_arguments \
'(- *)--add[Subscribe to a channel]:Channel URL:_urls::Channel Name:( )'\
'(- *)--remove[Unsubscribe from a channel]:Channel Name:_nix_channels'\
'(- *)--list[List subscribed channels]'\
'(- *)--update[Update and activate channels]:Channel Name:_nix_channels'\
'(- *)--rollback[Revert the previous nix-channel --update]'
#compdef nix-build
#autoload
local command_name=nix-build
_nix-common-options
local -a _nix_build_opts
_nix_build_opts=(
'--drv-link[Add a symlink to the store derivation]:Symlink Name:( )' \
'--add-drv-link[Shorthand for --drv-link ./derivation]' \
'--no-out-link[Do not create a symlink to the output path]' \
{--out-link,-o}'[Name of the output symlink]:Output Symlink Name:( )' \
)
# TODO: Undocumented args to possibly add
# --add-root
# --dry-run
# --check
# --quiet
# --command
# --exclude
# --pure
# --impure
# --packages,-p
_arguments \
$_nix_boilerplate_opts \
$_nix_common_opts \
$_nix_build_opts \
'*:Paths:_files'
ZSH Completions for Nix and NixOS
=================================
This project aims to provide a highly complete set of ZSH completions for [Nix](https://nixos.org/nix/),
[NixOS](https://nixos.org/), [NixOps](http://nixos.org/nixops/), and the surrounding ecosystem.
NixOS
----------------------
Set `programs.zsh.enableCompletion = true` in `/etc/nix/configuration.nix` and either add `nix-zsh-completions` to `systemPackages` or install it locally: `nix-env -iA nixos.nix-zsh-completions`
Oh-My-ZSH Installation
----------------------
```zsh
git clone git@github.com:spwhitt/nix-zsh-completions.git ~/.oh-my-zsh/custom/plugins/nix
```
Then add `nix` to the plugins list in `~/.zshrc`
Antigen Installation
--------------------
Add the following to `~/.zshrc`
```zsh
antigen bundle git@github.com:spwhitt/nix-zsh-completions.git
```
Plain ZSH Installation
----------------------
Clone this repository and add the following to `~/.zshrc` with the path to
`nix-zsh-completions` updated as necessary.
```zsh
source $HOME/nix-zsh-completions/nix.plugin.zsh
fpath=($HOME/nix-zsh-completions $fpath)
autoload -U compinit && compinit
```
ZSH Completions Tutorial
------------------------
[zsh-completions-howto](https://github.com/zsh-users/zsh-completions/blob/master/zsh-completions-howto.org)
Copyright (c) 2015, Spencer Whitt
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright notice, this
list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.
* Neither the name of Spencer Whitt nor the names of other
contributors may be used to endorse or promote products derived from
this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
_* linguist-language=Shell