gunk-dev/the-valley

selfupdate.go

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