gunk-dev/the-valley

profile.go

source6a6791929c36main's published tip history
4.4 KiB
1package nix
2
3import (
4 "bytes"
5 "context"
6 "encoding/json"
7 "errors"
8 "fmt"
9 "os"
10 "os/exec"
11 "runtime"
12 "strings"
13 "time"
14)
15
16const (
17 buildTimeout = 30 * time.Minute
18 profileTimeout = 5 * time.Minute
19)
20
21// Build builds installable without a result link and returns its output
22// store paths. env is added to nix's environment, and so to the git that
23// fetches a git+ flake.
24func Build(ctx context.Context, installable string, env ...string) ([]string, error) {
25 out, err := runNixEnv(ctx, buildTimeout, env, "build", "--no-link", "--print-out-paths", installable)
26 if err != nil {
27 return nil, err
28 }
29 paths := strings.Fields(out)
30 if len(paths) == 0 {
31 return nil, errors.New("nix build printed no output path")
32 }
33 return paths, nil
34}
35
36// HasPackage reports whether the flake at the locked reference flake offers
37// packages.<system>.<name> for this machine, reading only the names of its
38// packages, so nothing is built. flake must hold no ", \ or $, which would
39// end or interpolate the Nix string it is written into. env is added to
40// nix's environment, as for Build.
41func HasPackage(ctx context.Context, flake, name string, env ...string) (bool, error) {
42 expr := fmt.Sprintf(`builtins.hasAttr %q ((builtins.getFlake "%s").packages.%s or { })`, name, flake, System())
43 out, err := runNixEnv(ctx, buildTimeout, env, "eval", "--json", "--expr", expr)
44 if err != nil {
45 return false, err
46 }
47 switch out {
48 case "true":
49 return true, nil
50 case "false":
51 return false, nil
52 }
53 return false, fmt.Errorf("nix eval printed %q, not true or false", out)
54}
55
56// ProfileElements returns the elements of the user's default nix profile,
57// each name with its store paths.
58func ProfileElements(ctx context.Context) (map[string][]string, error) {
59 out, err := runNix(ctx, profileTimeout, "profile", "list", "--json")
60 if err != nil {
61 return nil, err
62 }
63 var list struct {
64 Elements json.RawMessage `json:"elements"`
65 }
66 if err := json.Unmarshal([]byte(out), &list); err != nil {
67 return nil, fmt.Errorf("parsing nix profile list: %w", err)
68 }
69 var elements map[string]struct {
70 StorePaths []string `json:"storePaths"`
71 }
72 if len(list.Elements) > 0 {
73 if err := json.Unmarshal(list.Elements, &elements); err != nil {
74 return nil, fmt.Errorf("nix profile list has no named elements (needs Nix 2.20 or later): %w", err)
75 }
76 }
77 byName := make(map[string][]string, len(elements))
78 for name, e := range elements {
79 byName[name] = e.StorePaths
80 }
81 return byName, nil
82}
83
84// ProfileRemove removes the element called name from the default profile.
85func ProfileRemove(ctx context.Context, name string) error {
86 _, err := runNix(ctx, profileTimeout, "profile", "remove", name)
87 return err
88}
89
90// ProfileAdd adds storePath to the default profile.
91func ProfileAdd(ctx context.Context, storePath string) error {
92 _, err := runNix(ctx, profileTimeout, "profile", "add", storePath)
93 return err
94}
95
96// System returns nix's name for this machine's platform, e.g. x86_64-linux.
97func System() string {
98 arch := map[string]string{"amd64": "x86_64", "arm64": "aarch64", "386": "i686"}[runtime.GOARCH]
99 if arch == "" {
100 arch = runtime.GOARCH
101 }
102 return arch + "-" + runtime.GOOS
103}
104
105// runNix runs nix and returns its trimmed stdout. An error carries nix's
106// error line.
107func runNix(ctx context.Context, timeout time.Duration, args ...string) (string, error) {
108 return runNixEnv(ctx, timeout, nil, args...)
109}
110
111func runNixEnv(ctx context.Context, timeout time.Duration, env []string, args ...string) (string, error) {
112 ctx, cancel := context.WithTimeout(ctx, timeout)
113 defer cancel()
114 cmd := exec.CommandContext(ctx, "nix", args...)
115 if len(env) > 0 {
116 cmd.Env = append(os.Environ(), env...)
117 }
118 var stdout, stderr bytes.Buffer
119 cmd.Stdout, cmd.Stderr = &stdout, &stderr
120 if err := cmd.Run(); err != nil {
121 if ctx.Err() == context.DeadlineExceeded {
122 return "", fmt.Errorf("nix %s timed out after %s", args[0], timeout)
123 }
124 return "", fmt.Errorf("nix %s: %w: %s", strings.Join(args[:min(len(args), 2)], " "), err, ErrorLine(stderr.String()))
125 }
126 return strings.TrimSpace(stdout.String()), nil
127}
128
129// ErrorLine picks the line of a command's output that says what went wrong:
130// nix's first "error:" line, else the last non-empty line, capped in length.
131func ErrorLine(out string) string {
132 var last string
133 for _, l := range strings.Split(out, "\n") {
134 l = strings.TrimSpace(l)
135 if strings.HasPrefix(l, "error:") {
136 last = l
137 break
138 }
139 if l != "" {
140 last = l
141 }
142 }
143 if r := []rune(last); len(r) > 300 {
144 last = string(r[:299]) + "…"
145 }
146 return last
147}