jetify-com / devbox

Instant, easy, and predictable development environments
https://www.jetify.com/devbox/
Apache License 2.0
7.83k stars 187 forks source link

internal/nix: improve command error handling #2125

Closed gcurtis closed 4 weeks ago

gcurtis commented 4 weeks ago

Add a new cmd type that wraps exec.Cmd and provides better error handling when a Nix command fails.

Calls to commandContext, exec.Command and exec.CommandContext are consolidated into the command function, which now returns a *cmd instead of an *exec.Cmd. The cmd.Run and related methods return an error that provides more detail about the command in the following format:

nix: command ("error"|"canceled"|"timed out"): <shell command>: <stderr>: <exec error>

The shell command in the error is a properly-escaped shell string that can be copy/pasted to re-run the command.

If Nix prints a line with the prefix "error: " to stderr, then the error will include that line in its message. If there are multiple lines with that prefix, it only includes the last one. Otherwise, it will include exec.ExitError.Stderr with control characters escaped.

When the command exits on its own, the error includes the exit code. If a signal (either from Devbox or the system) terminates the command, the error includes the signal name instead of a -1 exit code.

Below are some examples of how errors will look in logs and Sentry.

Missing package:

nix: command error: nix --extra-experimental-features ca-derivations --option experimental-features 'nix-command flakes fetch-closure' search 'flake:nixpkgs#torpalorp' ^ --json: flake 'flake:nixpkgs' does not provide attribute 'packages.aarch64-darwin.torpalorp', 'legacyPackages.aarch64-darwin.torpalorp' or 'torpalorp': exit code 1

Bad flake reference:

nix --extra-experimental-features ca-derivations --option experimental-features 'nix-command flakes fetch-closure' path-info github:blah/thisisnotarepo --json --impure: unable to download 'https://api.github.com/repos/blah/thisisnotarepo/commits/HEAD': HTTP error 404: exit code 1

Killed process:

nix: command error: nix --extra-experimental-features ca-derivations --option experimental-features 'nix-command flakes fetch-closure' build --impure --no-link /nix/store/vz0f0ydykljjji91a94sq8jskh3lpl4h-rustc-wrapper-1.77.2 /nix/store/0r6hm57fmlzhngn76v7vh7vzfp7qrsq8-rustc-wrapper-1.77.2-man: exit due to signal 9 (killed)