Skip to content

Instantly share code, notes, and snippets.

@dlovell
Last active May 10, 2024 18:05
Show Gist options
  • Save dlovell/e1dfe9fdf565b526fd0d6b836cf7a4d3 to your computer and use it in GitHub Desktop.
Save dlovell/e1dfe9fdf565b526fd0d6b836cf7a4d3 to your computer and use it in GitHub Desktop.
A helper function to `nix develop` on a package
# https://nixos.wiki/wiki/Nixpkgs/Create_and_debug_packages#Using_nix-shell_for_package_development
function debug_nix_package () {
set -u
packageName=${1:-default}
flakeDir=${2:-$(pwd)}
tmpdir=${3:-$(mktemp --directory --suffix=-nix-dbg)}
system=${4:-$(uname --machine)-$(uname --kernel-name | tr '[:upper:]' '[:lower:]')}
cd "$tmpdir" || exit
ln -s "$flakeDir" flakeDir
echo "$system" >system
echo "$packageName" >packageName
echo \
"try
source ./setup.sh
genericBuild >out 2>err
or
source ./setup.sh
runPhase unpackPhase
"
cat - > "$tmpdir/setup.sh" <<EOF
eval "\$(typeset -f genericBuild | grep 'phases=')"
echo "phases=${phases[@]}"
set -x
set +e
export NIX_ENFORCE_PURITY=0
# squelch direnv
unset PROMPT_COMMAND
EOF
nix develop "$flakeDir#packages.$system.$packageName"
}
script_content=$(cat <<'EOF'
set -x # Optional: it prints all commands, can be practical to debug
set +e # Optional: do not quit the shell on simple errors, Ctrl-C,...
export NIX_ENFORCE_PURITY=0
alias get-phases='eval echo $(typeset -f genericBuild | grep "phases=" | perl -pe "s/^\s+phases=//")'
alias set-phases='set $(get-phases); echo "$# phases: $@"'
alias run-next-phase='phaseName=$1; shift; realPhaseName="${!phaseName:-$phaseName}"; runPhase $phaseName; echo next phase: $1'
set-phases
echo next phase: $1
EOF
)
function debug_nix_drv() {
set -u
drvPath=$1
pname=$(nix-store --query --binding pname "$drvPath")
export out=$(mktemp -d -t "nix-debug-$pname.XXXXX")
pushd "$out" || exit
to_source=source-for-helpers.sh
echo "$script_content" >"$out/$to_source"
echo "#####################"
echo "run source ./$to_source"
echo "#####################"
nix-shell "$drvPath"
popd || exit
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment