gunk-dev/the-valley

selfupdate.go

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