|
1 | 1 | package nix
|
2 | 2 |
|
3 | 3 | import (
|
| 4 | + "bytes" |
4 | 5 | "context"
|
| 6 | + "errors" |
| 7 | + "fmt" |
| 8 | + "io" |
| 9 | + "os" |
5 | 10 | "os/exec"
|
| 11 | + "slices" |
| 12 | + "strconv" |
| 13 | + "strings" |
| 14 | + "sync" |
| 15 | + "syscall" |
| 16 | + "time" |
6 | 17 | )
|
7 | 18 |
|
8 |
| -func command(args ...string) *exec.Cmd { |
9 |
| - return commandContext(context.Background(), args...) |
| 19 | +type cmd struct { |
| 20 | + Args cmdArgs |
| 21 | + Env []string |
| 22 | + |
| 23 | + Stdin io.Reader |
| 24 | + Stdout io.Writer |
| 25 | + Stderr io.Writer |
| 26 | + |
| 27 | + execCmd *exec.Cmd |
| 28 | + execCmdOnce sync.Once |
10 | 29 | }
|
11 | 30 |
|
12 |
| -func commandContext(ctx context.Context, args ...string) *exec.Cmd { |
13 |
| - cmd := exec.CommandContext(ctx, "nix", args...) |
14 |
| - cmd.Args = append(cmd.Args, ExperimentalFlags()...) |
| 31 | +func command(args ...any) *cmd { |
| 32 | + cmd := &cmd{ |
| 33 | + Args: append(cmdArgs{ |
| 34 | + "nix", |
| 35 | + "--extra-experimental-features", "ca-derivations", |
| 36 | + "--option", "experimental-features", "nix-command flakes fetch-closure", |
| 37 | + }, args...), |
| 38 | + } |
15 | 39 | return cmd
|
16 | 40 | }
|
17 | 41 |
|
| 42 | +func (c *cmd) CombinedOutput(ctx context.Context) ([]byte, error) { |
| 43 | + out, err := c.initExecCommand(ctx).CombinedOutput() |
| 44 | + return out, c.error(ctx, err) |
| 45 | +} |
| 46 | + |
| 47 | +func (c *cmd) Output(ctx context.Context) ([]byte, error) { |
| 48 | + out, err := c.initExecCommand(ctx).Output() |
| 49 | + return out, c.error(ctx, err) |
| 50 | +} |
| 51 | + |
| 52 | +func (c *cmd) Run(ctx context.Context) error { |
| 53 | + return c.error(ctx, c.initExecCommand(ctx).Run()) |
| 54 | +} |
| 55 | + |
| 56 | +func (c *cmd) String() string { |
| 57 | + return c.Args.String() |
| 58 | +} |
| 59 | + |
| 60 | +func (c *cmd) initExecCommand(ctx context.Context) *exec.Cmd { |
| 61 | + c.execCmdOnce.Do(func() { |
| 62 | + args := c.Args.StringSlice() |
| 63 | + c.execCmd = exec.CommandContext(ctx, args[0], args[1:]...) |
| 64 | + c.execCmd.Env = c.Env |
| 65 | + c.execCmd.Stdin = c.Stdin |
| 66 | + c.execCmd.Stdout = c.Stdout |
| 67 | + c.execCmd.Stderr = c.Stderr |
| 68 | + |
| 69 | + c.execCmd.Cancel = func() error { |
| 70 | + // Try to let Nix exit gracefully by sending an |
| 71 | + // interrupt instead of the default behavior of killing |
| 72 | + // it. |
| 73 | + err := c.execCmd.Process.Signal(os.Interrupt) |
| 74 | + if errors.Is(err, os.ErrProcessDone) { |
| 75 | + // Nix already exited; execCmd.Wait will use the |
| 76 | + // exit code. |
| 77 | + return err |
| 78 | + } |
| 79 | + if err != nil { |
| 80 | + // We failed to send SIGINT, so kill the process |
| 81 | + // instead. |
| 82 | + // |
| 83 | + // - If Nix already exited, Kill will return |
| 84 | + // os.ErrProcessDone and execCmd.Wait will use |
| 85 | + // the exit code. |
| 86 | + // - Otherwise, execCmd.Wait will always return |
| 87 | + // an error. |
| 88 | + return c.execCmd.Process.Kill() |
| 89 | + } |
| 90 | + |
| 91 | + // We sent the SIGINT successfully. It's still possible |
| 92 | + // for Nix to exit successfully, so return |
| 93 | + // os.ErrProcessDone so that execCmd.Wait uses the exit |
| 94 | + // code instead of ctx.Err. |
| 95 | + return os.ErrProcessDone |
| 96 | + } |
| 97 | + // Kill Nix if it doesn't exit within 15 seconds of Devbox |
| 98 | + // sending an interrupt. |
| 99 | + c.execCmd.WaitDelay = 15 * time.Second |
| 100 | + }) |
| 101 | + return c.execCmd |
| 102 | +} |
| 103 | + |
| 104 | +func (c *cmd) error(ctx context.Context, err error) error { |
| 105 | + if err == nil { |
| 106 | + return nil |
| 107 | + } |
| 108 | + |
| 109 | + cmdErr := &cmdError{err: err} |
| 110 | + if errors.Is(err, exec.ErrNotFound) { |
| 111 | + cmdErr.msg = fmt.Sprintf("nix: %s not found in $PATH", c.Args[0]) |
| 112 | + } |
| 113 | + |
| 114 | + switch { |
| 115 | + case errors.Is(ctx.Err(), context.Canceled): |
| 116 | + cmdErr.msg = "nix: command canceled" |
| 117 | + case errors.Is(ctx.Err(), context.DeadlineExceeded): |
| 118 | + cmdErr.msg = "nix: command timed out" |
| 119 | + default: |
| 120 | + cmdErr.msg = "nix: command error" |
| 121 | + } |
| 122 | + cmdErr.msg += ": " + c.String() |
| 123 | + |
| 124 | + var exitErr *exec.ExitError |
| 125 | + if errors.As(err, &exitErr) { |
| 126 | + if stderr := c.stderrExcerpt(exitErr.Stderr); len(stderr) != 0 { |
| 127 | + cmdErr.msg += ": " + stderr |
| 128 | + } |
| 129 | + if exitErr.Exited() { |
| 130 | + cmdErr.msg += fmt.Sprintf(": exit code %d", exitErr.ExitCode()) |
| 131 | + return cmdErr |
| 132 | + } |
| 133 | + if stat, ok := exitErr.Sys().(syscall.WaitStatus); ok && stat.Signaled() { |
| 134 | + cmdErr.msg += fmt.Sprintf(": exit due to signal %d (%[1]s)", stat.Signal()) |
| 135 | + return cmdErr |
| 136 | + } |
| 137 | + } |
| 138 | + |
| 139 | + if !errors.Is(err, ctx.Err()) { |
| 140 | + cmdErr.msg += ": " + err.Error() |
| 141 | + } |
| 142 | + return cmdErr |
| 143 | +} |
| 144 | + |
| 145 | +func (*cmd) stderrExcerpt(stderr []byte) string { |
| 146 | + stderr = bytes.TrimSpace(stderr) |
| 147 | + if len(stderr) == 0 { |
| 148 | + return "" |
| 149 | + } |
| 150 | + |
| 151 | + lines := bytes.Split(stderr, []byte("\n")) |
| 152 | + slices.Reverse(lines) |
| 153 | + for _, line := range lines { |
| 154 | + line = bytes.TrimSpace(line) |
| 155 | + after, found := bytes.CutPrefix(line, []byte("error: ")) |
| 156 | + if !found { |
| 157 | + continue |
| 158 | + } |
| 159 | + after = bytes.TrimSpace(after) |
| 160 | + if len(after) == 0 { |
| 161 | + continue |
| 162 | + } |
| 163 | + stderr = after |
| 164 | + break |
| 165 | + |
| 166 | + } |
| 167 | + |
| 168 | + excerpt := string(stderr) |
| 169 | + if !strconv.CanBackquote(excerpt) { |
| 170 | + quoted := strconv.Quote(excerpt) |
| 171 | + excerpt = quoted[1 : len(quoted)-1] |
| 172 | + } |
| 173 | + return excerpt |
| 174 | +} |
| 175 | + |
| 176 | +type cmdArgs []any |
| 177 | + |
| 178 | +func appendArgs[E any](args cmdArgs, new []E) cmdArgs { |
| 179 | + for _, elem := range new { |
| 180 | + args = append(args, elem) |
| 181 | + } |
| 182 | + return args |
| 183 | +} |
| 184 | + |
| 185 | +func (c cmdArgs) StringSlice() []string { |
| 186 | + s := make([]string, len(c)) |
| 187 | + for i := range c { |
| 188 | + s[i] = fmt.Sprint(c[i]) |
| 189 | + } |
| 190 | + return s |
| 191 | +} |
| 192 | + |
| 193 | +func (c cmdArgs) String() string { |
| 194 | + if len(c) == 0 { |
| 195 | + return "" |
| 196 | + } |
| 197 | + |
| 198 | + sb := &strings.Builder{} |
| 199 | + c.writeQuoted(sb, fmt.Sprint(c[0])) |
| 200 | + if len(c) == 1 { |
| 201 | + return sb.String() |
| 202 | + } |
| 203 | + |
| 204 | + for _, arg := range c[1:] { |
| 205 | + sb.WriteByte(' ') |
| 206 | + c.writeQuoted(sb, fmt.Sprint(arg)) |
| 207 | + } |
| 208 | + return sb.String() |
| 209 | +} |
| 210 | + |
| 211 | +func (cmdArgs) writeQuoted(dst *strings.Builder, str string) { |
| 212 | + needsQuote := strings.ContainsAny(str, ";\"'()$|&><` \t\r\n\\#{~*?[=") |
| 213 | + if !needsQuote { |
| 214 | + dst.WriteString(str) |
| 215 | + return |
| 216 | + } |
| 217 | + |
| 218 | + canSingleQuote := !strings.Contains(str, "'") |
| 219 | + if canSingleQuote { |
| 220 | + dst.WriteByte('\'') |
| 221 | + dst.WriteString(str) |
| 222 | + dst.WriteByte('\'') |
| 223 | + return |
| 224 | + } |
| 225 | + |
| 226 | + dst.WriteByte('"') |
| 227 | + for _, r := range str { |
| 228 | + switch r { |
| 229 | + // Special characters inside double quotes: |
| 230 | + // https://pubs.opengroup.org/onlinepubs/009604499/utilities/xcu_chap02.html#tag_02_02_03 |
| 231 | + case '$', '`', '"', '\\': |
| 232 | + dst.WriteRune('\\') |
| 233 | + } |
| 234 | + dst.WriteRune(r) |
| 235 | + } |
| 236 | + dst.WriteByte('"') |
| 237 | +} |
| 238 | + |
| 239 | +type cmdError struct { |
| 240 | + msg string |
| 241 | + err error |
| 242 | +} |
| 243 | + |
| 244 | +func (c *cmdError) Redact() string { |
| 245 | + return c.Error() |
| 246 | +} |
| 247 | + |
| 248 | +func (c *cmdError) Error() string { |
| 249 | + return c.msg |
| 250 | +} |
| 251 | + |
| 252 | +func (c *cmdError) Unwrap() error { |
| 253 | + return c.err |
| 254 | +} |
| 255 | + |
18 | 256 | func allowUnfreeEnv(curEnv []string) []string {
|
19 | 257 | return append(curEnv, "NIXPKGS_ALLOW_UNFREE=1")
|
20 | 258 | }
|
|
0 commit comments