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