gunk-dev/the-valley

nix.go

source535d69c9a69emain's published tip history
3.9 KiB
1package selfupdate
2
3import (
4 "bytes"
5 "context"
6 "encoding/json"
7 "errors"
8 "fmt"
9 "os"
10 "os/exec"
11 "runtime"
12 "slices"
13 "strings"
14 "time"
15)
16
17const (
18 buildTimeout = 30 * time.Minute
19 profileTimeout = 5 * time.Minute
20)
21
22// nixFeatures turns on what self-update uses of nix, whatever nix.conf
23// says: flake references, and the nix command itself.
24var nixFeatures = []string{"--extra-experimental-features", "nix-command flakes"}
25
26// Real is the nix on PATH, acting on the user's default profile.
27type Real struct{}
28
29// Build builds installable without a result link and returns its output's
30// store path. The git that fetches a git+ flake reference runs with gitEnv.
31func (Real) Build(ctx context.Context, installable string) (string, error) {
32 out, err := runNix(ctx, buildTimeout, gitEnv, "build", "--no-link", "--print-out-paths", installable)
33 if err != nil {
34 return "", err
35 }
36 paths := strings.Fields(out)
37 if len(paths) == 0 {
38 return "", errors.New("nix build printed no output path")
39 }
40 return paths[0], nil
41}
42
43// Elements returns the elements of the user's default nix profile, each
44// name with its store paths.
45func (Real) Elements(ctx context.Context) (map[string][]string, error) {
46 out, err := runNix(ctx, profileTimeout, nil, "profile", "list", "--json")
47 if err != nil {
48 return nil, err
49 }
50 var list struct {
51 Elements json.RawMessage `json:"elements"`
52 }
53 if err := json.Unmarshal([]byte(out), &list); err != nil {
54 return nil, fmt.Errorf("parsing nix profile list: %w", err)
55 }
56 var elements map[string]struct {
57 StorePaths []string `json:"storePaths"`
58 }
59 if len(list.Elements) > 0 {
60 if err := json.Unmarshal(list.Elements, &elements); err != nil {
61 return nil, fmt.Errorf("nix profile list has no named elements (needs Nix 2.20 or later): %w", err)
62 }
63 }
64 byName := make(map[string][]string, len(elements))
65 for name, e := range elements {
66 byName[name] = e.StorePaths
67 }
68 return byName, nil
69}
70
71// Remove removes the element called name from the default profile.
72func (Real) Remove(ctx context.Context, name string) error {
73 _, err := runNix(ctx, profileTimeout, nil, "profile", "remove", name)
74 return err
75}
76
77// Add adds storePath to the default profile.
78func (Real) Add(ctx context.Context, storePath string) error {
79 _, err := runNix(ctx, profileTimeout, nil, "profile", "add", storePath)
80 return err
81}
82
83// System returns nix's name for this machine's platform, e.g. x86_64-linux.
84func System() string {
85 arch := map[string]string{"amd64": "x86_64", "arm64": "aarch64", "386": "i686"}[runtime.GOARCH]
86 if arch == "" {
87 arch = runtime.GOARCH
88 }
89 return arch + "-" + runtime.GOOS
90}
91
92// runNix runs nix with env added to this process's environment, and
93// returns its trimmed stdout. An error carries nix's error line.
94func runNix(ctx context.Context, timeout time.Duration, env []string, args ...string) (string, error) {
95 ctx, cancel := context.WithTimeout(ctx, timeout)
96 defer cancel()
97 cmd := exec.CommandContext(ctx, "nix", slices.Concat(nixFeatures, args)...)
98 cmd.Env = append(os.Environ(), env...)
99 var stdout, stderr bytes.Buffer
100 cmd.Stdout, cmd.Stderr = &stdout, &stderr
101 if err := cmd.Run(); err != nil {
102 if ctx.Err() == context.DeadlineExceeded {
103 return "", fmt.Errorf("nix %s timed out after %s", args[0], timeout)
104 }
105 return "", fmt.Errorf("nix %s: %w: %s", strings.Join(args[:min(len(args), 2)], " "), err, ErrorLine(stderr.String()))
106 }
107 return strings.TrimSpace(stdout.String()), nil
108}
109
110// ErrorLine picks the line of a command's output that says what went wrong:
111// nix's first "error:" line or valley's first "valley:" line, else the last
112// non-empty line, capped in length.
113func ErrorLine(out string) string {
114 var last string
115 for _, l := range strings.Split(out, "\n") {
116 l = strings.TrimSpace(l)
117 if strings.HasPrefix(l, "error:") || strings.HasPrefix(l, "valley:") {
118 last = l
119 break
120 }
121 if l != "" {
122 last = l
123 }
124 }
125 if r := []rune(last); len(r) > 300 {
126 last = string(r[:299]) + "…"
127 }
128 return last
129}