#! /bin/sh # # NAME # get - evaluate ./default.nix # # SYNOPSIS # get [-jlprs] [--show-trace] [attrPath] # # DESCRIPTION # The command nix evaluates the Nix expression in ./default.nix. # # OPTIONS # # -j Format output as JSON. Implies -s. # # -l List attrNames, one per line. If used in conjunction with -j, then # the list will be output as JSON value. # # -p Pretty-print output. (Only effectiv in conjunction with -j.) # # -r Disable the default filter and produce raw output. Normally, when # the result looks like a JSON or Nix string, i.e. begins with a double # quote, then the string itself gets printed. # Refs jq(1)'s --raw-output. # # -s Recursively evaluate list elements and attributes. # Refs nix-instantiate(1)'s --strict. # # --show-trace # Refs nix-instantiate(1)'s --show-trace. # set -efu args=$* has_lopt() { echo "$args" | grep -q '\(^\|\s\)--'"$1"'\(\s\|$\)' } has_sopt() { echo "$args" | grep -q '\(^\|\s\)-[a-z]*'"$1"'[a-z]*\(\s\|$\)' } filter() { set -- "$(cat)" if echo "$1" | grep -q ^\"; then echo "$1" | jq -e -r . else echo "$1" fi } if has_sopt j; then json=1 strict=1 fi if has_sopt l; then query='-E builtins.attrNames((import(./.)).&)' if ! has_sopt j; then json=1 filter() { jq -r .[]; } fi else query='-A &' fi if has_sopt p && has_sopt j; then filter() { jq .; } fi if has_sopt r; then filter() { cat; } fi if has_sopt s; then strict=1 fi if has_lopt show-trace; then show_trace=1 fi if x=$(nix-instantiate --json --eval -A NIX_PATH 2>/dev/null); then NIX_PATH=$(echo "$x" | jq -r .) export NIX_PATH unset x fi # Quote slashes so we can use query as replacement string for sed's s///. query=$(echo "$query" | sed 's:/:\\&:') result=$(nix-instantiate \ ${json+--json} \ ${show_trace+--show-trace} \ ${strict+--strict} \ --eval \ $( for i; do echo "$i" done | sed -n ' s/^[A-Za-z_][0-9A-Za-z_"./-]*$/'"$query"'/p s/^\([0-9A-Za-z-]\+\)=\([.0-9A-Za-z-]*\)$/--argstr \1 \2/p ' ) \ --argstr current-date "$(date -Is)" \ --argstr current-host-name "$HOSTNAME" \ --argstr current-user-name "$LOGNAME" \ ) echo "$result" | filter