// Package fetch resolves flake refs to pinned store paths. package fetch import ( "bytes" "context" "encoding/json" "fmt" "net/url" "os/exec" "strings" ) // Result is a source fetched into the Nix store. type Result struct { StorePath string // Locked holds the attrs to pass to builtins.fetchTree, including narHash. Locked map[string]any } // Rev returns the locked commit. func (r Result) Rev() string { rev, _ := r.Locked["rev"].(string) return rev } type Fetcher interface { Prefetch(ctx context.Context, flakeRef string) (Result, error) } // WithParam adds or replaces a query parameter on a flake ref, e.g. ref or rev. func WithParam(flakeRef, key, value string) string { return editQuery(flakeRef, func(q url.Values) { q.Set(key, value) }) } // AtRev pins a flake ref to a commit. Shorthand refs (github:, gitlab:, sourcehut:) // reject ref and rev together, so their ref is dropped; git refs keep it because // the rev must be reachable from it. func AtRev(flakeRef, rev string) string { base, _, _ := strings.Cut(flakeRef, "?") shorthand := !strings.Contains(base, "://") return editQuery(flakeRef, func(q url.Values) { if shorthand { q.Del("ref") } q.Set("rev", rev) }) } func editQuery(flakeRef string, edit func(url.Values)) string { base, query, _ := strings.Cut(flakeRef, "?") q, err := url.ParseQuery(query) if err != nil { q = url.Values{} } edit(q) if len(q) == 0 { return base } return base + "?" + q.Encode() } // Nix fetches with `nix flake prefetch`. type Nix struct { // Bin is the nix executable; empty means "nix" from PATH. Bin string } func (n Nix) Prefetch(ctx context.Context, flakeRef string) (Result, error) { bin := n.Bin if bin == "" { bin = "nix" } cmd := exec.CommandContext(ctx, bin, "--extra-experimental-features", "nix-command flakes", "flake", "prefetch", "--json", flakeRef) var stderr bytes.Buffer cmd.Stderr = &stderr out, err := cmd.Output() if err != nil { return Result{}, fmt.Errorf("nix flake prefetch %s: %w: %s", flakeRef, err, strings.TrimSpace(stderr.String())) } var raw struct { Hash string `json:"hash"` Locked map[string]any `json:"locked"` StorePath string `json:"storePath"` } if err := json.Unmarshal(out, &raw); err != nil { return Result{}, fmt.Errorf("parse prefetch output for %s: %w", flakeRef, err) } if raw.Hash == "" || raw.StorePath == "" || raw.Locked == nil { return Result{}, fmt.Errorf("incomplete prefetch output for %s: %s", flakeRef, out) } // prefetch reports the hash beside locked, but fetchTree needs it inside. raw.Locked["narHash"] = raw.Hash return Result{StorePath: raw.StorePath, Locked: raw.Locked}, nil }