gunk-dev/the-valley

selfupdate.go

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