gunk-dev/the-valley

selfupdate.go

sourcec14b0e68e9c3main's published tip history
26.8 KiB
1// Package selfupdate brings the installed agent-run client up to the tip of
2// a configured branch. It resolves the branch with git ls-remote, checks
3// that the flake there offers the client's package by name, builds exactly
4// that commit's packages.<system>.<attribute> with nix, smoke-tests the
5// build, and installs it into the user's default nix profile in place of
6// the element holding the client, klaus or valley-flow. Every step prints
7// one short line, so a journal of timer runs reads as a history.
8package selfupdate
9
10import (
11 "bytes"
12 "context"
13 "encoding/json"
14 "errors"
15 "fmt"
16 "io"
17 "net/url"
18 "os"
19 "os/exec"
20 "path/filepath"
21 "regexp"
22 "slices"
23 "strings"
24 "syscall"
25 "time"
26
27 "the-valley/flow/internal/git"
28 "the-valley/flow/internal/nix"
29)
30
31// The names the-valley's flake offers the client under. Each is a flake
32// attribute, packages.<system>.<name>; the name of that package, after
33// which nix names the profile element a store path of it installs as; and
34// the executable a build of it is smoke-tested as. Both packages hold the
35// same program under both executable names. A flake's default package is
36// never selected.
37const (
38 Klaus = "klaus"
39 ValleyFlow = "valley-flow"
40)
41
42// names are the profile elements that can hold the client.
43var names = []string{Klaus, ValleyFlow}
44
45const smokeTimeout = 2 * time.Minute
46
47// State is what self-update.json records between runs.
48type State struct {
49 // Current is the build self-update last put in the profile, and
50 // Previous the one it replaced, which --rollback reinstalls. A
51 // replacement that lost the client, its build not going in and the one
52 // it replaced not going back, records Current as none and Previous as
53 // the lost build.
54 Current *Install `json:"current,omitempty"`
55 Previous *Install `json:"previous,omitempty"`
56 Failed *Failure `json:"failed,omitempty"` // the last commit that failed to build or test
57 Pinned bool `json:"pinned,omitempty"` // --pin: leave Current alone until --unpin
58 // UpdatedAt is when a run last changed this state.
59 UpdatedAt time.Time `json:"updated_at"`
60}
61
62// Install is a build of the client in the profile.
63type Install struct {
64 Commit string `json:"commit,omitempty"` // full SHA; a short one when read from a store path's name
65 StorePath string `json:"store_path"`
66 // Element is the profile element holding it, Klaus or ValleyFlow, and
67 // Attribute the flake package it was built from. Load reads either as
68 // Klaus when the file has none.
69 Element string `json:"element"`
70 Attribute string `json:"attribute"`
71 At time.Time `json:"at"` // when it went into the profile
72}
73
74// Failure is a commit that failed to build, pass the smoke test, or go
75// into the profile.
76type Failure struct {
77 Commit string `json:"commit"`
78 Error string `json:"error"`
79 At time.Time `json:"at"`
80}
81
82// Updater runs self-update against one repo and branch.
83type Updater struct {
84 Repo string // git URL (or absolute path) of the klaus repository
85 Branch string // the branch to install, e.g. main
86 Dir string // state directory, holding the lock and self-update.json
87 Version string // the running klaus's version, e.g. 0.4.1-e949dba
88 Out io.Writer // where each step's line goes
89 Verbose bool // also report runs that find klaus up to date
90 // Attribute is the flake package Update builds and smoke-tests, Klaus
91 // or ValleyFlow; empty is Klaus. The self-update command leaves it
92 // empty.
93 Attribute string
94
95 nix nixTool // nil is the nix on PATH (systemNix)
96}
97
98// nixTool is what self-update runs nix for.
99type nixTool interface {
100 // HasPackage reports whether flake offers packages.<system>.<name>.
101 HasPackage(ctx context.Context, flake, name string) (bool, error)
102 // Build builds installable and returns its output's store path.
103 Build(ctx context.Context, installable string) (string, error)
104 // ProfileElements lists the default profile's elements, each name
105 // with its store paths.
106 ProfileElements(ctx context.Context) (map[string][]string, error)
107 // ProfileRemove removes the element called name from the profile.
108 ProfileRemove(ctx context.Context, name string) error
109 // ProfileAdd adds storePath to the profile, as the element nix names
110 // after its package.
111 ProfileAdd(ctx context.Context, storePath string) error
112}
113
114// systemNix is the nix on PATH, acting on the user's default profile. The
115// git it fetches a flake with runs with gitEnv.
116type systemNix struct{}
117
118func (systemNix) HasPackage(ctx context.Context, flake, name string) (bool, error) {
119 return nix.HasPackage(ctx, flake, name, gitEnv...)
120}
121
122func (systemNix) Build(ctx context.Context, installable string) (string, error) {
123 paths, err := nix.Build(ctx, installable, gitEnv...)
124 if err != nil {
125 return "", err
126 }
127 return paths[0], nil
128}
129
130func (systemNix) ProfileElements(ctx context.Context) (map[string][]string, error) {
131 return nix.ProfileElements(ctx)
132}
133
134func (systemNix) ProfileRemove(ctx context.Context, name string) error {
135 return nix.ProfileRemove(ctx, name)
136}
137
138func (systemNix) ProfileAdd(ctx context.Context, storePath string) error {
139 return nix.ProfileAdd(ctx, storePath)
140}
141
142func (u *Updater) tool() nixTool {
143 if u.nix != nil {
144 return u.nix
145 }
146 return systemNix{}
147}
148
149// attribute is the flake package Update builds.
150func (u *Updater) attribute() string {
151 if u.Attribute == "" {
152 return Klaus
153 }
154 return u.Attribute
155}
156
157// DefaultDir returns $XDG_STATE_HOME/klaus, or ~/.local/state/klaus.
158func DefaultDir() (string, error) {
159 if d := os.Getenv("XDG_STATE_HOME"); filepath.IsAbs(d) {
160 return filepath.Join(d, "klaus"), nil
161 }
162 home, err := os.UserHomeDir()
163 if err != nil {
164 return "", err
165 }
166 return filepath.Join(home, ".local", "state", "klaus"), nil
167}
168
169// StatePath is the state file in dir.
170func StatePath(dir string) string { return filepath.Join(dir, "self-update.json") }
171
172var safeBranch = regexp.MustCompile(`^[A-Za-z0-9._/-]+$`)
173
174// gitEnv restricts every git self-update starts, directly or through nix,
175// to the transports Validate accepts, and keeps it from prompting.
176var gitEnv = []string{"GIT_ALLOW_PROTOCOL=https:ssh:git:file", "GIT_TERMINAL_PROMPT=0"}
177
178// scpLike is user@host:path, git's shorthand for an ssh URL.
179var scpLike = regexp.MustCompile(`^[A-Za-z0-9_][A-Za-z0-9._-]*@[A-Za-z0-9][A-Za-z0-9.-]*:.`)
180
181// Validate checks the repo and branch before any of them reach git or nix.
182// The repo must be an https://, ssh://, git:// or file:// URL, an absolute
183// path, or scp-like user@host:path: no other git transport (ext::, fd::)
184// and only characters nix's flake-ref parser leaves as they are (urlSafe).
185func Validate(repo, branch string) error {
186 if err := validRepo(repo); err != nil {
187 return fmt.Errorf("self_update.repo %q is not a repo self-update accepts: %v; use an https://, ssh://, git:// or file:// URL, an absolute path, or user@host:path", repo, err)
188 }
189 if !safeBranch.MatchString(branch) || strings.HasPrefix(branch, "-") || strings.Contains(branch, "..") {
190 return fmt.Errorf("self_update.branch %q is not a branch name self-update accepts ([A-Za-z0-9._/-])", branch)
191 }
192 return nil
193}
194
195func validRepo(repo string) error {
196 switch {
197 case repo == "":
198 return errors.New("it is empty")
199 case strings.HasPrefix(repo, "-"):
200 return errors.New("it starts with -")
201 }
202 if scheme, _, ok := strings.Cut(repo, "://"); ok {
203 u, err := url.Parse(repo)
204 if err != nil {
205 return err
206 }
207 // An IPv6 host's brackets pass through nix unchanged.
208 if err := urlSafe(strings.Replace(repo, u.Host, strings.NewReplacer("[", "", "]", "").Replace(u.Host), 1)); err != nil {
209 return err
210 }
211 switch scheme {
212 case "https", "ssh", "git":
213 if u.Hostname() == "" || strings.HasPrefix(u.Hostname(), "-") {
214 return errors.New("it names no host")
215 }
216 case "file":
217 if u.Host != "" || !strings.HasPrefix(u.Path, "/") {
218 return errors.New("a file:// URL must be file:///<absolute path>")
219 }
220 default:
221 return fmt.Errorf("transport %s:// is not allowed", scheme)
222 }
223 return nil
224 }
225 if err := urlSafe(repo); err != nil {
226 return err
227 }
228 switch {
229 case filepath.IsAbs(repo):
230 return nil
231 case strings.Contains(repo, "::"):
232 return errors.New("transport-style <transport>::<address> is not allowed")
233 case scpLike.MatchString(repo):
234 return nil
235 }
236 return errors.New("it is not a URL, an absolute path or user@host:path")
237}
238
239// urlSafe refuses any character outside [A-Za-z0-9._~/:@-]: nix's flake-ref
240// parser keeps exactly these as they are (checked against Nix 2.34 with
241// builtins.parseFlakeRef and flakeRefToString), and re-encodes or rejects
242// the rest (+ becomes %2B), so with them git ls-remote and nix build could
243// name different URLs. ? and # it would read as flake-ref syntax.
244func urlSafe(s string) error {
245 for _, r := range s {
246 switch {
247 case r >= 'a' && r <= 'z', r >= 'A' && r <= 'Z', r >= '0' && r <= '9', strings.ContainsRune("._~/:@-", r):
248 default:
249 return fmt.Errorf("it has %q; only letters, digits and ._~/:@- are allowed, which nix leaves as they are", r)
250 }
251 }
252 return nil
253}
254
255// Update installs the branch's tip unless it is installed already, failed
256// before (unless retry), or the install is pinned. A run that finds another
257// in progress leaves it to finish and returns nil.
258func (u *Updater) Update(ctx context.Context, retry bool) error {
259 if err := Validate(u.Repo, u.Branch); err != nil {
260 return err
261 }
262 attr := u.attribute()
263 if !slices.Contains(names, attr) {
264 return fmt.Errorf("self-update builds packages.<system>.%s or packages.<system>.%s, not %q", Klaus, ValleyFlow, attr)
265 }
266 unlock, paths, err := u.begin(ctx, false)
267 if errors.Is(err, errBusy) {
268 u.say("another self-update is in progress; leaving it to finish")
269 return nil
270 }
271 if err != nil {
272 return err
273 }
274 defer unlock()
275 st, err := u.load()
276 if err != nil {
277 return err
278 }
279 if st.Pinned {
280 u.say("pinned at %s: leaving it alone until valley flow self-update --unpin", st.Current.label())
281 return nil
282 }
283
284 ref := "refs/heads/" + u.Branch
285 sha, err := git.LsRemote(ctx, RepoURL(u.Repo), ref, gitEnv...)
286 if err != nil {
287 return fmt.Errorf("resolving %s: %w", u.Branch, err)
288 }
289 if !isCommit(sha) {
290 return fmt.Errorf("%s has no branch %s", u.Repo, u.Branch)
291 }
292 short := sha[:7]
293 if u.upToDate(st, sha) && u.inProfile(st.Current, paths) {
294 if u.Verbose {
295 u.say("%s is at %s: flow is up to date", u.Branch, short)
296 }
297 return nil
298 }
299 // Before anything changes, and whenever the tip is not installed: a
300 // repository whose flake offers no package of the attribute by name is
301 // not one self-update installs from. It comes before a remembered
302 // failure of the same tip, which would otherwise hide the refusal until
303 // the tip moves. A failure to read the flake is not recorded, so the
304 // next run reads it again.
305 offers, err := u.tool().HasPackage(ctx, flakeSource(u.Repo, u.Branch, sha), attr)
306 if err != nil {
307 return fmt.Errorf("reading the packages %s offers at %s: %w", u.Repo, short, err)
308 }
309 if !offers {
310 return u.noPackage(short, attr)
311 }
312 if f := st.Failed; f != nil && f.Commit == sha && !retry {
313 u.say("skipping %s: it failed at %s: %s (it is retried when %s moves, or with --retry)",
314 short, f.At.Local().Format(time.DateTime), f.Error, u.Branch)
315 return nil
316 }
317 u.say("%s is at %s (installed: %s)", u.Branch, short, u.installedLabel(st))
318
319 out, err := u.build(ctx, sha, attr)
320 if err == nil {
321 err = u.smoke(ctx, out, sha, attr)
322 }
323 var element, old string
324 if err == nil {
325 element, old, err = u.replace(ctx, out)
326 }
327 var lost *restoreError
328 switch {
329 case errors.Is(err, errBothInstalled):
330 return err
331 case errors.As(err, &lost):
332 // The profile holds no client now. The state says so and holds no
333 // failure, so the next run installs the tip, whichever commit it
334 // is, rather than hold this one.
335 st.Previous = u.replaced(st, lost.element, lost.old)
336 st.Current, st.Failed = nil, nil
337 if serr := u.save(st); serr != nil {
338 return fmt.Errorf("%s: %w (and recording that the profile holds no flow: %v)", short, err, serr)
339 }
340 return fmt.Errorf("%s: %w\n"+
341 " the nix profile holds no flow now, and the next run installs the tip of %s;\n"+
342 " to put back the build it held by hand: nix profile add %s", short, err, u.Branch, lost.old)
343 case err != nil:
344 // A build that fails, fails its smoke test or does not go into
345 // the profile is held: running it again on every run would
346 // rebuild it, or remove and add the profile's element, each time.
347 st.Failed = &Failure{Commit: sha, Error: err.Error(), At: u.clock()}
348 if serr := u.save(st); serr != nil {
349 return fmt.Errorf("%s: %w (and recording the failure: %v)", short, err, serr)
350 }
351 u.say("%s failed; nothing installed", short)
352 return fmt.Errorf("%s: %w", short, err)
353 }
354 // The build replaced becomes the rollback target. With none in the
355 // profile, that is the recorded build, unless this reinstalls it; with
356 // none recorded either, before a first install or after a lost
357 // replacement, the target stays.
358 if old != "" || st.Current != nil && st.Current.Commit != sha {
359 st.Previous = u.replaced(st, element, old)
360 }
361 st.Current = &Install{Commit: sha, StorePath: out, Element: attr, Attribute: attr, At: u.clock()}
362 st.Failed = nil
363 if err := u.save(st); err != nil {
364 return err
365 }
366 u.say("installed %s into the nix profile, replacing %s", short, st.Previous.label())
367 return nil
368}
369
370// noPackage refuses a repository whose flake at short offers no package of
371// attribute attr. The way out is the updater's own: pointed at a repository
372// whose flake offers it, the next run builds, smoke-tests and installs it,
373// and puts the working build back if installing fails.
374func (u *Updater) noPackage(short, attr string) error {
375 pkg := "packages." + nix.System() + "." + attr
376 return fmt.Errorf("%s at %s offers no %s; nothing changed\n"+
377 " set self_update.repo in ~/.klaus/config.json to a repository whose flake offers %s,\n"+
378 " as the-valley's does, and run valley flow self-update again",
379 u.Repo, short, pkg, pkg)
380}
381
382// Rollback swaps the current install for the previous one, so a second
383// rollback returns to where the first started. It adds the store path
384// recorded as previous, which nix names as the element it was taken from,
385// in place of the element now holding the client.
386func (u *Updater) Rollback(ctx context.Context) error {
387 unlock, _, err := u.begin(ctx, true)
388 if err != nil {
389 return err
390 }
391 defer unlock()
392 st, err := u.load()
393 if err != nil {
394 return err
395 }
396 prev := st.Previous
397 if prev == nil || prev.StorePath == "" {
398 return errors.New("nothing to roll back to: self-update has not replaced a klaus yet")
399 }
400 if _, err := os.Stat(prev.StorePath); err != nil {
401 return fmt.Errorf("the previous klaus is gone from the store (garbage-collected?): %w", err)
402 }
403 element, old, err := u.replace(ctx, prev.StorePath)
404 if err != nil {
405 return err
406 }
407 st.Previous = u.replaced(st, element, old)
408 st.Current = &Install{Commit: prev.Commit, StorePath: prev.StorePath, Element: prev.Element, Attribute: prev.Attribute, At: u.clock()}
409 if err := u.save(st); err != nil {
410 return err
411 }
412 if st.Previous != nil {
413 u.say("rolled back to %s; --rollback again returns to %s", st.Current.label(), st.Previous.label())
414 } else { // from a lost replacement: nothing was in the profile
415 u.say("rolled back to %s", st.Current.label())
416 }
417 if !st.Pinned {
418 u.say("not pinned: the next run installs the tip of %s unless it is this one; valley flow self-update --pin keeps this one", u.Branch)
419 }
420 return nil
421}
422
423// Pin sets or clears the pin. While pinned, Update leaves the install alone.
424func (u *Updater) Pin(ctx context.Context, pinned bool) error {
425 unlock, _, err := u.begin(ctx, true)
426 if err != nil {
427 return err
428 }
429 defer unlock()
430 st, err := u.load()
431 if err != nil {
432 return err
433 }
434 st.Pinned = pinned
435 if err := u.save(st); err != nil {
436 return err
437 }
438 if pinned {
439 u.say("pinned at %s: self-update leaves it alone until valley flow self-update --unpin", st.Current.label())
440 } else {
441 u.say("unpinned: the next run installs the tip of %s if it is not installed", u.Branch)
442 }
443 return nil
444}
445
446// upToDate reports whether the installed client was built from sha. Once
447// self-update has installed a build, the state file says which, or that a
448// replacement lost it; before that, the running program's version stamp
449// does.
450func (u *Updater) upToDate(st State, sha string) bool {
451 if st.recorded() {
452 return st.Current != nil && st.Current.Commit == sha
453 }
454 c := versionCommit(u.Version)
455 return c != "" && strings.HasPrefix(sha, c)
456}
457
458// recorded reports whether self-update has put a build in the profile, so
459// that the state, not the running program, says what the profile holds.
460func (st State) recorded() bool { return st.Current != nil || st.Previous != nil }
461
462// inProfile reports whether the profile's client element, holding paths,
463// still holds inst, so a build removed or replaced by hand gets
464// reinstalled. With no install recorded, the version stamp upToDate read
465// stands.
466func (u *Updater) inProfile(inst *Install, paths []string) bool {
467 if inst == nil || slices.Contains(paths, inst.StorePath) {
468 return true
469 }
470 u.say("the nix profile's %s is no longer %s; reinstalling it", inst.Element, inst.label())
471 return false
472}
473
474// begin takes the state directory's lock, as lock does, and then lists the
475// profile, which every operation does before anything else: a profile
476// holding the client under both names, or one nix cannot list, is refused
477// with nothing changed, whatever the state would have the operation do. It
478// returns the store paths of the element holding the client, none when
479// the profile holds neither.
480func (u *Updater) begin(ctx context.Context, wait bool) (unlock func(), paths []string, err error) {
481 if unlock, err = u.lock(wait); err != nil {
482 return nil, nil, err
483 }
484 if _, paths, err = u.installed(ctx); err != nil {
485 unlock()
486 return nil, nil, err
487 }
488 return unlock, paths, nil
489}
490
491// errBothInstalled refuses a profile holding the client as both klaus and
492// valley-flow: which of them to replace would be a guess.
493var errBothInstalled = fmt.Errorf("the nix profile holds both %[1]s and %[2]s, and self-update replaces one; nothing changed\n"+
494 " remove the one not to keep (nix profile remove %[1]s, or %[2]s) and run valley flow self-update again", Klaus, ValleyFlow)
495
496// installed returns the profile element holding the client, klaus or
497// valley-flow, and its store paths; "" when the profile holds neither.
498func (u *Updater) installed(ctx context.Context) (string, []string, error) {
499 elems, err := u.tool().ProfileElements(ctx)
500 if err != nil {
501 return "", nil, err
502 }
503 var found string
504 for _, name := range names {
505 if _, ok := elems[name]; !ok {
506 continue
507 }
508 if found != "" {
509 return "", nil, errBothInstalled
510 }
511 found = name
512 }
513 return found, elems[found], nil
514}
515
516func (u *Updater) installedLabel(st State) string {
517 if st.recorded() {
518 return st.Current.label()
519 }
520 return "klaus " + u.Version
521}
522
523// build builds the flake's package attr at exactly sha.
524func (u *Updater) build(ctx context.Context, sha, attr string) (string, error) {
525 ref := FlakeRef(u.Repo, u.Branch, sha, attr)
526 u.say("building %s", ref)
527 out, err := u.tool().Build(ctx, ref)
528 if err != nil {
529 return "", err
530 }
531 u.say("built %s", out)
532 return out, nil
533}
534
535// smoke runs the build's executable named exe, the attribute it was built
536// from: --version must report sha's short form, and status must exit 0,
537// which shows the build reads the existing run state.
538func (u *Updater) smoke(ctx context.Context, out, sha, exe string) error {
539 bin := filepath.Join(out, "bin", exe)
540 v, err := runBin(ctx, bin, "--version")
541 if err != nil {
542 return fmt.Errorf("smoke test: %s --version: %w", exe, err)
543 }
544 v = firstLine(v)
545 if c := versionCommit(lastField(v)); len(c) < 7 || !strings.HasPrefix(sha, c) {
546 return fmt.Errorf("smoke test: %s --version reports %q, not commit %s", exe, v, sha[:7])
547 }
548 if _, err := runBin(ctx, bin, "status"); err != nil {
549 return fmt.Errorf("smoke test: %s status: %w", exe, err)
550 }
551 u.say("smoke test passed: %s; %s status exits 0", v, exe)
552 return nil
553}
554
555// replace puts storePath in the profile in place of the element holding
556// the client, klaus or valley-flow, and returns that element's name and
557// the store path it had, both "" if the profile had neither. Other
558// elements are left alone, and a profile holding both is refused with
559// nothing changed. If adding fails, it adds the old store path back, which
560// nix names as the element it was.
561func (u *Updater) replace(ctx context.Context, storePath string) (element, old string, err error) {
562 element, paths, err := u.installed(ctx)
563 if err != nil {
564 return "", "", err
565 }
566 if element != "" {
567 if len(paths) > 0 {
568 old = paths[0]
569 }
570 if err := u.tool().ProfileRemove(ctx, element); err != nil {
571 return "", "", err
572 }
573 }
574 if err := u.tool().ProfileAdd(ctx, storePath); err != nil {
575 if old != "" {
576 // Put it back even if ctx is what ended the add.
577 rctx, cancel := context.WithTimeout(context.WithoutCancel(ctx), time.Minute)
578 defer cancel()
579 if rerr := u.tool().ProfileAdd(rctx, old); rerr != nil {
580 return "", "", &restoreError{add: err, element: element, old: old, restore: rerr}
581 }
582 }
583 return "", "", err
584 }
585 return element, old, nil
586}
587
588// restoreError is an add that failed after replace removed element,
589// whose store path old then failed to go back too: the profile holds no
590// client.
591type restoreError struct {
592 add, restore error
593 element, old string
594}
595
596func (e *restoreError) Error() string {
597 return fmt.Sprintf("%v (and putting %s back: %v)", e.add, e.old, e.restore)
598}
599
600func (e *restoreError) Unwrap() error { return e.add }
601
602// replaced describes the build that replace took out of the profile's
603// element.
604func (u *Updater) replaced(st State, element, old string) *Install {
605 switch {
606 case old == "":
607 // Removed from the profile by hand: still the one to roll back to.
608 return st.Current
609 case st.Current != nil && st.Current.StorePath == old:
610 prev := *st.Current
611 prev.Element = element
612 return &prev
613 default:
614 // Installed by hand: its name carries the version stamp, and the
615 // element's name is its package's.
616 return &Install{Commit: versionCommit(filepath.Base(old)), StorePath: old, Element: element, Attribute: element}
617 }
618}
619
620// RepoURL is the one URL self-update reads repo by, for git ls-remote and
621// for nix alike, so both read the same repository. A path becomes a
622// file:// URL, and user@host:path becomes ssh://user@host/path: a relative
623// path counts from the server's root, as forges read it, so a path in your
624// home on a plain server is written user@host:~/path. repo must have passed
625// Validate, so it needs no escaping: it has no %, ?, # or whitespace.
626func RepoURL(repo string) string {
627 switch {
628 case strings.Contains(repo, "://"):
629 return repo
630 case filepath.IsAbs(repo):
631 return "file://" + repo
632 }
633 host, path, _ := strings.Cut(repo, ":")
634 return "ssh://" + host + "/" + strings.TrimPrefix(path, "/")
635}
636
637// FlakeRef names the flake's package attr at exactly sha on branch of
638// repo, read by RepoURL.
639func FlakeRef(repo, branch, sha, attr string) string {
640 return flakeSource(repo, branch, sha) + "#packages." + nix.System() + "." + attr
641}
642
643// flakeSource is the flake at exactly sha on branch of repo, read by
644// RepoURL. Validate keeps ", \ and $ out of it.
645func flakeSource(repo, branch, sha string) string {
646 return fmt.Sprintf("git+%s?ref=refs/heads/%s&rev=%s", RepoURL(repo), branch, sha)
647}
648
649var errBusy = errors.New("another self-update is in progress")
650
651// lock takes the state directory's lock. Without wait it returns errBusy
652// when another run holds it; with wait it says so and waits.
653func (u *Updater) lock(wait bool) (func(), error) {
654 if err := os.MkdirAll(u.Dir, 0o755); err != nil {
655 return nil, err
656 }
657 path := filepath.Join(u.Dir, "self-update.lock")
658 f, err := os.OpenFile(path, os.O_CREATE|os.O_RDWR, 0o644)
659 if err != nil {
660 return nil, err
661 }
662 err = syscall.Flock(int(f.Fd()), syscall.LOCK_EX|syscall.LOCK_NB)
663 if errors.Is(err, syscall.EWOULDBLOCK) {
664 if !wait {
665 f.Close()
666 return nil, errBusy
667 }
668 u.say("waiting for the self-update in progress to finish")
669 err = syscall.Flock(int(f.Fd()), syscall.LOCK_EX)
670 }
671 if err != nil {
672 f.Close()
673 return nil, fmt.Errorf("locking %s: %w", path, err)
674 }
675 return func() { f.Close() }, nil // close drops the flock
676}
677
678// Load reads the state file in dir; a missing file is the zero State. An
679// install recorded without an element or attribute, as an updater that
680// knows klaus alone records it, is klaus's.
681func Load(dir string) (State, error) {
682 var st State
683 data, err := os.ReadFile(StatePath(dir))
684 if errors.Is(err, os.ErrNotExist) {
685 return st, nil
686 }
687 if err != nil {
688 return st, err
689 }
690 if err := json.Unmarshal(data, &st); err != nil {
691 return st, fmt.Errorf("parsing %s: %w", StatePath(dir), err)
692 }
693 for _, i := range []*Install{st.Current, st.Previous} {
694 if i == nil {
695 continue
696 }
697 if i.Element == "" {
698 i.Element = Klaus
699 }
700 if i.Attribute == "" {
701 i.Attribute = Klaus
702 }
703 }
704 return st, nil
705}
706
707func (u *Updater) load() (State, error) { return Load(u.Dir) }
708
709// save writes the state file through a rename, so a reader never sees half.
710func (u *Updater) save(st State) error {
711 st.UpdatedAt = u.clock()
712 data, err := json.MarshalIndent(st, "", " ")
713 if err != nil {
714 return err
715 }
716 tmp, err := os.CreateTemp(u.Dir, "self-update-*.json")
717 if err != nil {
718 return err
719 }
720 defer os.Remove(tmp.Name())
721 if _, err := tmp.Write(append(data, '\n')); err != nil {
722 tmp.Close()
723 return err
724 }
725 if err := tmp.Close(); err != nil {
726 return err
727 }
728 return os.Rename(tmp.Name(), StatePath(u.Dir))
729}
730
731func (u *Updater) say(format string, args ...any) {
732 if u.Out != nil {
733 fmt.Fprintf(u.Out, format+"\n", args...)
734 }
735}
736
737func (u *Updater) clock() time.Time { return time.Now().UTC().Truncate(time.Second) }
738
739func (i *Install) label() string {
740 switch {
741 case i == nil:
742 return "nothing (the system klaus)"
743 case i.Commit != "":
744 return shortSHA(i.Commit)
745 }
746 return i.StorePath
747}
748
749// runBin runs a build's executable and returns its stdout; an error carries
750// its last line of output.
751func runBin(ctx context.Context, bin string, args ...string) (string, error) {
752 ctx, cancel := context.WithTimeout(ctx, smokeTimeout)
753 defer cancel()
754 cmd := exec.CommandContext(ctx, bin, args...)
755 var stdout, stderr bytes.Buffer
756 cmd.Stdout, cmd.Stderr = &stdout, &stderr
757 if err := cmd.Run(); err != nil {
758 if line := nix.ErrorLine(stderr.String() + "\n" + stdout.String()); line != "" {
759 return "", fmt.Errorf("%w: %s", err, line)
760 }
761 return "", err
762 }
763 return stdout.String(), nil
764}
765
766var hexRe = regexp.MustCompile(`^[0-9a-f]+$`)
767
768func isCommit(s string) bool { return len(s) >= 40 && hexRe.MatchString(s) }
769
770// versionCommit returns the commit stamped at the end of a klaus version or
771// store path name (0.4.1-e949dba gives e949dba), or "" if there is none.
772func versionCommit(v string) string {
773 i := strings.LastIndex(v, "-")
774 if i < 0 {
775 return ""
776 }
777 c := v[i+1:]
778 if len(c) < 7 || !hexRe.MatchString(c) {
779 return ""
780 }
781 return c
782}
783
784func shortSHA(s string) string { return s[:min(len(s), 7)] }
785
786func firstLine(s string) string {
787 l, _, _ := strings.Cut(strings.TrimSpace(s), "\n")
788 return strings.TrimSpace(l)
789}
790
791func lastField(s string) string {
792 f := strings.Fields(s)
793 if len(f) == 0 {
794 return ""
795 }
796 return f[len(f)-1]
797}