gunk-dev/the-valley

selfupdate_test.go

source6a7605f70901main's published tip history
23.1 KiB
1package selfupdate
2
3import (
4 "bytes"
5 "context"
6 "encoding/json"
7 "errors"
8 "fmt"
9 "maps"
10 "os"
11 "os/exec"
12 "path/filepath"
13 "slices"
14 "strings"
15 "testing"
16 "unicode"
17
18 "the-valley/flow/internal/nix"
19)
20
21// acceptedRepos covers every form Validate accepts.
22var acceptedRepos = []string{
23 "https://github.com/maintainer/klaus",
24 "https://github.com/maintainer/klaus.git",
25 "ssh://git@github.com/maintainer/klaus",
26 "ssh://git@[::1]:2222/srv/klaus.git",
27 "git://example.com/klaus.git",
28 "file:///srv/git/klaus.git",
29 "/srv/git/klaus.git",
30 "git@github.com:maintainer/klaus.git",
31 "me@host.example:~/klaus.git",
32 "https://example.com/a-b_c.d~e/f:g@h",
33}
34
35func TestValidateRepo(t *testing.T) {
36 for _, repo := range acceptedRepos {
37 if err := Validate(repo, "main"); err != nil {
38 t.Errorf("Validate(%q) refused: %v", repo, err)
39 }
40 }
41 for _, repo := range []string{
42 "",
43 "ext::sh -c touch% /tmp/pwned",
44 "ext::sh",
45 "fd::17",
46 "foo::bar",
47 "me@host::path",
48 "-uhttps://example.com/klaus",
49 "--upload-pack=touch /tmp/pwned",
50 "/srv/git/klaus.git?rev=0000000",
51 "/srv/git/klaus.git#packages.x86_64-linux.evil",
52 "https://example.com/klaus?ref=evil",
53 "/srv/git/my klaus.git",
54 "/srv/git/klaus%20repo.git",
55 "https://example.com/my%20klaus",
56 "https://example.com/repo+name",
57 "https://example.com/repo!",
58 "https://example.com/repo$x",
59 "https://example.com/repo'x",
60 "https://example.com/repo(x",
61 "https://example.com/repo,x",
62 "https://example.com/repo;x",
63 "https://example.com/repo=x",
64 "/srv/git/klaus+1.git",
65 "/srv/git/[klaus].git",
66 "/srv/git/klaus.git\n",
67 "http://example.com/klaus",
68 "ftp://example.com/klaus",
69 "file://relative/klaus",
70 "ssh://-oProxyCommand=touch/klaus",
71 "relative/klaus",
72 "host:klaus",
73 } {
74 err := Validate(repo, "main")
75 if err == nil {
76 t.Errorf("Validate(%q) accepted it", repo)
77 continue
78 }
79 if !strings.Contains(err.Error(), "self_update.repo") {
80 t.Errorf("Validate(%q) = %v; want the error to name self_update.repo", repo, err)
81 }
82 }
83}
84
85// TestRepoURL: ls-remote and nix read a repo by the same URL, the one the
86// flake ref carries.
87func TestRepoURL(t *testing.T) {
88 sha := strings.Repeat("a", 40)
89 for repo, want := range map[string]string{
90 "/srv/git/klaus.git": "file:///srv/git/klaus.git",
91 "file:///srv/git/klaus.git": "file:///srv/git/klaus.git",
92 "https://github.com/maintainer/klaus": "https://github.com/maintainer/klaus",
93 "git@github.com:maintainer/klaus.git": "ssh://git@github.com/maintainer/klaus.git",
94 "me@host.example:/srv/klaus.git": "ssh://me@host.example/srv/klaus.git",
95 "me@host.example:~/klaus.git": "ssh://me@host.example/~/klaus.git",
96 } {
97 if got := RepoURL(repo); got != want {
98 t.Errorf("RepoURL(%q) = %q, want %q", repo, got, want)
99 }
100 if got, ref := FlakeRef(repo, "main", sha, Klaus), "git+"+want+"?ref=refs/heads/main&rev="+sha+"#packages."; !strings.HasPrefix(got, ref) {
101 t.Errorf("FlakeRef(%q) = %q, want prefix %q", repo, got, ref)
102 }
103 }
104}
105
106// TestFlakeRefSurvivesNix: the installed nix parses each accepted repo's
107// flake ref and prints it back unchanged, so nix fetches the URL ls-remote
108// read.
109func TestFlakeRefSurvivesNix(t *testing.T) {
110 if _, err := exec.LookPath("nix"); err != nil {
111 if os.Getenv("KLAUS_TEST_TOOLS") == "required" {
112 t.Fatal("nix not installed")
113 }
114 t.Skip("nix not installed")
115 }
116 sha := strings.Repeat("a", 40)
117 for _, repo := range acceptedRepos {
118 ref, _, _ := strings.Cut(FlakeRef(repo, "main", sha, Klaus), "#")
119 // Only stdout is the reference: nix warns on stderr, as it does
120 // with no network.
121 var stderr strings.Builder
122 cmd := exec.Command("nix", "--extra-experimental-features", "nix-command flakes", "eval", "--raw", "--expr",
123 `builtins.flakeRefToString (builtins.parseFlakeRef "`+ref+`")`)
124 cmd.Stderr = &stderr
125 out, err := cmd.Output()
126 if err != nil {
127 t.Fatalf("nix eval of %q: %v\n%s", ref, err, stderr.String())
128 }
129 // nix prints git+git:// by its alias git://, the same URL.
130 if got := strings.Replace(ref, "git+git://", "git://", 1); string(out) != got {
131 t.Errorf("repo %q: nix turned %q into %q", repo, got, out)
132 }
133 }
134}
135
136// upstream is a bare repository standing for the-valley's, and a clone
137// that pushes commits to its main.
138type upstream struct {
139 t *testing.T
140 bare string
141 work string
142}
143
144func newUpstream(t *testing.T) *upstream {
145 dir := t.TempDir()
146 u := &upstream{t: t, bare: filepath.Join(dir, "the-valley.git"), work: filepath.Join(dir, "work")}
147 u.git(dir, "init", "--quiet", "--bare", u.bare)
148 u.git(dir, "init", "--quiet", u.work)
149 return u
150}
151
152// git runs git with no configuration but an identity of its own.
153func (u *upstream) git(dir string, args ...string) string {
154 u.t.Helper()
155 cmd := exec.Command("git", args...)
156 cmd.Dir = dir
157 cmd.Env = append(os.Environ(),
158 "GIT_CONFIG_NOSYSTEM=1", "GIT_CONFIG_GLOBAL=/dev/null",
159 "GIT_AUTHOR_NAME=test", "GIT_AUTHOR_EMAIL=test@localhost",
160 "GIT_COMMITTER_NAME=test", "GIT_COMMITTER_EMAIL=test@localhost")
161 out, err := cmd.CombinedOutput()
162 if err != nil {
163 u.t.Fatalf("git %s: %v\n%s", strings.Join(args, " "), err, out)
164 }
165 return strings.TrimSpace(string(out))
166}
167
168// push commits to main and pushes it, returning the commit.
169func (u *upstream) push(msg string) string {
170 u.git(u.work, "commit", "--quiet", "--allow-empty", "-m", msg)
171 u.git(u.work, "push", "--quiet", u.bare, "HEAD:refs/heads/main")
172 return u.git(u.work, "rev-parse", "HEAD")
173}
174
175// fakeNix offers both packages of the client and builds either for any
176// commit as a store path under store, holding bin/klaus and
177// bin/valley-flow. Each executable answers --version as the program does
178// under its name, and logs what it was run as to ran. The profile is a map
179// from element to store paths: an added store path becomes the element
180// nix would name after its package, and adding fails when the element is
181// there already, or when the other client element is, whose files would
182// collide. failAdds makes that many adds fail first.
183type fakeNix struct {
184 t *testing.T
185 store string
186 profile map[string][]string
187 asked []string // the packages HasPackage was asked for
188 builds []string // the installables built
189 ops []string // "remove <element>" and "add <store path>", in order
190 failAdds int
191}
192
193func newFakeNix(t *testing.T) *fakeNix {
194 return &fakeNix{t: t, store: t.TempDir(), profile: map[string][]string{}}
195}
196
197func (f *fakeNix) HasPackage(_ context.Context, flake, name string) (bool, error) {
198 f.asked = append(f.asked, name)
199 return slices.Contains(names, name), nil
200}
201
202func (f *fakeNix) Build(_ context.Context, ref string) (string, error) {
203 f.builds = append(f.builds, ref)
204 _, rest, _ := strings.Cut(ref, "&rev=")
205 sha, installable, _ := strings.Cut(rest, "#")
206 attr := strings.TrimPrefix(installable, "packages."+nix.System()+".")
207 out := filepath.Join(f.store, fmt.Sprintf("%d-%s-0.1.0-%s", len(f.builds), attr, sha[:7]))
208 for exe, program := range map[string]string{Klaus: "klaus", ValleyFlow: "valley flow"} {
209 script := fmt.Sprintf(`#!/bin/sh
210echo "%s $1" >> %q
211case "$1" in
212--version) echo "%s version 0.1.0-%s" ;;
213status) echo "No runs found." ;;
214*) exit 2 ;;
215esac
216`, exe, f.ranLog(), program, sha[:7])
217 if err := os.MkdirAll(filepath.Join(out, "bin"), 0o755); err != nil {
218 return "", err
219 }
220 if err := os.WriteFile(filepath.Join(out, "bin", exe), []byte(script), 0o755); err != nil {
221 return "", err
222 }
223 }
224 return out, nil
225}
226
227func (f *fakeNix) ranLog() string { return filepath.Join(f.store, "ran") }
228
229// ran is what the builds' executables were run as, in order.
230func (f *fakeNix) ran() []string {
231 data, _ := os.ReadFile(f.ranLog())
232 return strings.Split(strings.TrimSpace(string(data)), "\n")
233}
234
235func (f *fakeNix) ProfileElements(context.Context) (map[string][]string, error) {
236 return maps.Clone(f.profile), nil
237}
238
239func (f *fakeNix) ProfileRemove(_ context.Context, name string) error {
240 f.ops = append(f.ops, "remove "+name)
241 delete(f.profile, name)
242 return nil
243}
244
245func (f *fakeNix) ProfileAdd(_ context.Context, storePath string) error {
246 f.ops = append(f.ops, "add "+storePath)
247 if f.failAdds > 0 {
248 f.failAdds--
249 return errors.New("nix profile add: exit status 1: error: cannot write the profile")
250 }
251 name := packageName(storePath)
252 for _, held := range names {
253 if _, ok := f.profile[held]; ok && (held == name || slices.Contains(names, name)) {
254 return fmt.Errorf("nix profile add: exit status 1: error: %s is already provided by element %s", name, held)
255 }
256 }
257 f.profile[name] = []string{storePath}
258 return nil
259}
260
261// packageName is the name nix gives the element a store path installs as:
262// the path's name less the hash before it and the version after it, which
263// starts at the first dash followed by something other than a letter.
264func packageName(storePath string) string {
265 _, name, _ := strings.Cut(filepath.Base(storePath), "-")
266 parts := strings.Split(name, "-")
267 for i, p := range parts {
268 if i > 0 && p != "" && !unicode.IsLetter(rune(p[0])) {
269 return strings.Join(parts[:i], "-")
270 }
271 }
272 return name
273}
274
275// handInstalled puts a build of package name at commit short into the
276// profile the way a person would, as the element of that name.
277func (f *fakeNix) handInstalled(name, short string) string {
278 f.t.Helper()
279 path := filepath.Join(f.store, "hand-"+name+"-0.1.0-"+short)
280 if err := os.MkdirAll(path, 0o755); err != nil {
281 f.t.Fatal(err)
282 }
283 f.profile[name] = []string{path}
284 return path
285}
286
287// fixture is an updater over a fresh upstream, fake nix and state
288// directory, with output collected in out.
289type fixture struct {
290 t *testing.T
291 up *upstream
292 nix *fakeNix
293 u *Updater
294 out *bytes.Buffer
295}
296
297func newFixture(t *testing.T) *fixture {
298 up, fake, out := newUpstream(t), newFakeNix(t), &bytes.Buffer{}
299 return &fixture{t: t, up: up, nix: fake, out: out, u: &Updater{
300 Repo: up.bare, Branch: "main", Dir: t.TempDir(), Out: out, nix: fake,
301 }}
302}
303
304func (f *fixture) update(retry bool) (string, error) {
305 f.out.Reset()
306 err := f.u.Update(context.Background(), retry)
307 return f.out.String(), err
308}
309
310func (f *fixture) mustUpdate(retry bool) string {
311 f.t.Helper()
312 out, err := f.update(retry)
313 if err != nil {
314 f.t.Fatalf("Update: %v\n%s", err, out)
315 }
316 return out
317}
318
319func (f *fixture) mustRollback() string {
320 f.t.Helper()
321 f.out.Reset()
322 if err := f.u.Rollback(context.Background()); err != nil {
323 f.t.Fatalf("Rollback: %v\n%s", err, f.out.String())
324 }
325 return f.out.String()
326}
327
328func (f *fixture) state() State {
329 f.t.Helper()
330 st, err := Load(f.u.Dir)
331 if err != nil {
332 f.t.Fatal(err)
333 }
334 return st
335}
336
337func (f *fixture) stateFile() []byte {
338 data, _ := os.ReadFile(StatePath(f.u.Dir))
339 return data
340}
341
342// wantProfile fails unless the profile holds exactly the element name,
343// holding exactly storePath, besides elements other than the client's.
344func (f *fixture) wantProfile(name, storePath string) {
345 f.t.Helper()
346 want := map[string][]string{name: {storePath}}
347 got := map[string][]string{}
348 for _, n := range names {
349 if p, ok := f.nix.profile[n]; ok {
350 got[n] = p
351 }
352 }
353 if !maps.EqualFunc(got, want, slices.Equal) {
354 f.t.Errorf("profile's client elements = %v, want %v", got, want)
355 }
356}
357
358// wantInstall fails unless inst records commit, storePath and the element
359// and attribute name.
360func wantInstall(t *testing.T, what string, inst *Install, commit, storePath, element, attribute string) {
361 t.Helper()
362 if inst == nil {
363 t.Errorf("%s = nil, want %s in %s", what, shortSHA(commit), element)
364 return
365 }
366 if inst.Commit != commit || inst.StorePath != storePath || inst.Element != element || inst.Attribute != attribute {
367 t.Errorf("%s = %+v, want commit %s, store path %s, element %s, attribute %s",
368 what, *inst, commit, storePath, element, attribute)
369 }
370}
371
372// TestUpdateReplacesTheClientUnderEitherName: Update builds the attribute
373// it is given, klaus unless set, smoke-tests the executable of that name,
374// and puts the build in place of whichever client element the profile
375// holds, recording both. Rollback puts back exactly the store path it
376// replaced, as the element it was, and a second rollback returns.
377func TestUpdateReplacesTheClientUnderEitherName(t *testing.T) {
378 for _, c := range []struct {
379 installed, attribute string
380 }{
381 {Klaus, ""},
382 {ValleyFlow, ""},
383 {Klaus, ValleyFlow},
384 {ValleyFlow, ValleyFlow},
385 } {
386 t.Run(c.installed+" built as "+cmpOr(c.attribute, "default"), func(t *testing.T) {
387 f := newFixture(t)
388 f.u.Attribute = c.attribute
389 attr := cmpOr(c.attribute, Klaus)
390 old := f.nix.handInstalled(c.installed, "1111111")
391 sha := f.up.push("first")
392
393 out := f.mustUpdate(false)
394 if !slices.Equal(f.nix.asked, []string{attr}) {
395 t.Errorf("asked the flake for %v, want %s", f.nix.asked, attr)
396 }
397 if len(f.nix.builds) != 1 || !strings.HasSuffix(f.nix.builds[0], "&rev="+sha+"#packages."+nix.System()+"."+attr) {
398 t.Errorf("built %v, want packages.%s.%s at %s", f.nix.builds, nix.System(), attr, sha[:7])
399 }
400 if ran := f.nix.ran(); !slices.Equal(ran, []string{attr + " --version", attr + " status"}) {
401 t.Errorf("the smoke test ran %v, want bin/%s", ran, attr)
402 }
403 if !strings.Contains(out, "; "+attr+" status exits 0") {
404 t.Errorf("Update printed:\n%s", out)
405 }
406 built := f.nix.store + fmt.Sprintf("/1-%s-0.1.0-%s", attr, sha[:7])
407 f.wantProfile(attr, built)
408 if want := []string{"remove " + c.installed, "add " + built}; !slices.Equal(f.nix.ops, want) {
409 t.Errorf("profile operations %v, want %v", f.nix.ops, want)
410 }
411 st := f.state()
412 wantInstall(t, "current", st.Current, sha, built, attr, attr)
413 wantInstall(t, "previous", st.Previous, "1111111", old, c.installed, c.installed)
414
415 f.mustRollback()
416 f.wantProfile(c.installed, old)
417 st = f.state()
418 wantInstall(t, "current after rollback", st.Current, "1111111", old, c.installed, c.installed)
419 wantInstall(t, "previous after rollback", st.Previous, sha, built, attr, attr)
420
421 f.mustRollback()
422 f.wantProfile(attr, built)
423 st = f.state()
424 wantInstall(t, "current after a second rollback", st.Current, sha, built, attr, attr)
425 wantInstall(t, "previous after a second rollback", st.Previous, "1111111", old, c.installed, c.installed)
426 })
427 }
428}
429
430func cmpOr(s, or string) string {
431 if s == "" {
432 return or
433 }
434 return s
435}
436
437// TestEveryOperationRefusesAProfileHoldingBothNames: with klaus and
438// valley-flow both in the profile, every operation refuses before anything
439// else, whatever the state would have it do: Update with the tip
440// installed, moved, or running with nothing recorded, pinned, or held as
441// failed with and without --retry; --pin; --unpin; and --rollback with a
442// build to roll back to and without. None reads the flake, builds, or
443// changes the profile or the state.
444func TestEveryOperationRefusesAProfileHoldingBothNames(t *testing.T) {
445 update := func(retry bool) func(*fixture) error {
446 return func(f *fixture) error { _, err := f.update(retry); return err }
447 }
448 pin := func(pinned bool) func(*fixture) error {
449 return func(f *fixture) error { return f.u.Pin(context.Background(), pinned) }
450 }
451 rollback := func(f *fixture) error { return f.u.Rollback(context.Background()) }
452 // tip is the branch's tip, held by the profile's klaus element, and
453 // other an older build, still in the store.
454 for _, c := range []struct {
455 name string
456 state func(tip, other *Install) State
457 op func(*fixture) error
458 }{
459 {"update with the tip installed", func(tip, _ *Install) State { return State{Current: tip} }, update(false)},
460 {"update with the tip moved", func(_, other *Install) State { return State{Current: other} }, update(false)},
461 {"update running the tip with nothing recorded", func(_, _ *Install) State { return State{} }, update(false)},
462 {"update while pinned", func(_, other *Install) State { return State{Current: other, Pinned: true} }, update(false)},
463 {"update with the tip held as failed", func(tip, other *Install) State {
464 return State{Current: other, Failed: &Failure{Commit: tip.Commit, Error: "smoke test"}}
465 }, update(false)},
466 {"update --retry with the tip held as failed", func(tip, other *Install) State {
467 return State{Current: other, Failed: &Failure{Commit: tip.Commit, Error: "smoke test"}}
468 }, update(true)},
469 {"pin", func(tip, _ *Install) State { return State{Current: tip} }, pin(true)},
470 {"unpin", func(tip, _ *Install) State { return State{Current: tip, Pinned: true} }, pin(false)},
471 {"rollback", func(tip, other *Install) State { return State{Current: tip, Previous: other} }, rollback},
472 {"rollback with nothing to roll back to", func(tip, _ *Install) State { return State{Current: tip} }, rollback},
473 } {
474 t.Run(c.name, func(t *testing.T) {
475 f := newFixture(t)
476 sha := f.up.push("tip")
477 f.u.Version = "0.1.0-" + sha[:7] // the running program is the tip's build
478 tip := &Install{Commit: sha, StorePath: f.nix.handInstalled(Klaus, sha[:7]), Element: Klaus, Attribute: Klaus}
479 f.nix.handInstalled(ValleyFlow, "2222222")
480 other := &Install{Commit: "1111111", StorePath: filepath.Join(f.nix.store, "old-klaus-0.1.0-1111111"), Element: Klaus, Attribute: Klaus}
481 if err := os.MkdirAll(other.StorePath, 0o755); err != nil {
482 t.Fatal(err)
483 }
484 if err := f.u.save(c.state(tip, other)); err != nil {
485 t.Fatal(err)
486 }
487 profile, state := maps.Clone(f.nix.profile), f.stateFile()
488
489 f.out.Reset()
490 if err := c.op(f); !errors.Is(err, errBothInstalled) {
491 t.Errorf("%s = %v, want the refusal of both elements\n%s", c.name, err, f.out.String())
492 }
493 if len(f.nix.asked) != 0 || len(f.nix.builds) != 0 || len(f.nix.ops) != 0 || !maps.EqualFunc(f.nix.profile, profile, slices.Equal) {
494 t.Errorf("the refusal read the flake for %v, built %v or changed the profile: %v", f.nix.asked, f.nix.builds, f.nix.ops)
495 }
496 if !bytes.Equal(f.stateFile(), state) {
497 t.Errorf("the refusal changed the state:\nbefore %s\nafter %s", state, f.stateFile())
498 }
499 })
500 }
501}
502
503// TestUpdateRestoresTheElementWhenAddingFails: when the new build does not
504// go into the profile, the element that held the client gets its store
505// path back, and the state records the failure and keeps what is
506// installed. A later run holds that commit, as for a failed smoke test,
507// and --retry installs it, keeping the restored build as the rollback
508// target.
509func TestUpdateRestoresTheElementWhenAddingFails(t *testing.T) {
510 f := newFixture(t)
511 first := f.up.push("first")
512 f.mustUpdate(false)
513 installed := f.state().Current.StorePath
514
515 second := f.up.push("second")
516 f.nix.failAdds = 1
517 out, err := f.update(false)
518 if err == nil || !strings.Contains(err.Error(), "cannot write the profile") {
519 t.Fatalf("Update = %v, want the add's failure\n%s", err, out)
520 }
521 if !strings.Contains(out, second[:7]+" failed; nothing installed") {
522 t.Errorf("Update printed:\n%s", out)
523 }
524 built := f.nix.store + "/2-klaus-0.1.0-" + second[:7]
525 if want := []string{"add " + installed, "remove klaus", "add " + built, "add " + installed}; !slices.Equal(f.nix.ops, want) {
526 t.Errorf("profile operations %v, want %v", f.nix.ops, want)
527 }
528 f.wantProfile(Klaus, installed)
529 st := f.state()
530 wantInstall(t, "current", st.Current, first, installed, Klaus, Klaus)
531 if st.Previous != nil {
532 t.Errorf("previous = %+v, want none", *st.Previous)
533 }
534 if st.Failed == nil || st.Failed.Commit != second || !strings.Contains(st.Failed.Error, "cannot write the profile") {
535 t.Errorf("failed = %+v, want %s and the add's error", st.Failed, second[:7])
536 }
537
538 ops := len(f.nix.ops)
539 if out := f.mustUpdate(false); !strings.Contains(out, "skipping "+second[:7]+": it failed at") {
540 t.Errorf("the run after the failure printed:\n%s", out)
541 }
542 if len(f.nix.builds) != 2 || len(f.nix.ops) != ops {
543 t.Errorf("the run after the failure built %v or changed the profile: %v", f.nix.builds, f.nix.ops[ops:])
544 }
545
546 f.mustUpdate(true)
547 built = f.nix.store + "/3-klaus-0.1.0-" + second[:7]
548 f.wantProfile(Klaus, built)
549 st = f.state()
550 wantInstall(t, "current after --retry", st.Current, second, built, Klaus, Klaus)
551 wantInstall(t, "previous after --retry", st.Previous, first, installed, Klaus, Klaus)
552 if st.Failed != nil {
553 t.Errorf("failed after --retry = %+v, want none", *st.Failed)
554 }
555}
556
557// TestARetryThatLosesTheClientRecordsNone: a commit held after its add
558// failed is retried, and adding it and putting the element's store path
559// back both fail. The state records no install and no failure, keeping the
560// lost build as the rollback target, and the error says the profile holds
561// no client and how to add that build back. The next ordinary run then
562// installs the tip, though the running program reports that commit.
563func TestARetryThatLosesTheClientRecordsNone(t *testing.T) {
564 f := newFixture(t)
565 first := f.up.push("first")
566 f.mustUpdate(false)
567 installed := f.state().Current.StorePath
568
569 second := f.up.push("second")
570 f.nix.failAdds = 1
571 if out, err := f.update(false); err == nil {
572 t.Fatalf("Update with a failing add succeeded\n%s", out)
573 }
574 if st := f.state(); st.Failed == nil || st.Failed.Commit != second {
575 t.Fatalf("failed = %+v, want %s held", st.Failed, second[:7])
576 }
577
578 f.nix.failAdds = 2
579 out, err := f.update(true)
580 if err == nil || !strings.Contains(err.Error(), "holds no flow") || !strings.Contains(err.Error(), "nix profile add "+installed) {
581 t.Fatalf("Update --retry = %v, want what is left and the command that adds %s back\n%s", err, installed, out)
582 }
583 if len(f.nix.profile) != 0 {
584 t.Errorf("profile = %v, want no client: both adds failed", f.nix.profile)
585 }
586 st := f.state()
587 if st.Current != nil || st.Failed != nil {
588 t.Errorf("current = %+v, failed = %+v, want neither: the profile holds no client", st.Current, st.Failed)
589 }
590 wantInstall(t, "previous", st.Previous, first, installed, Klaus, Klaus)
591
592 f.u.Version = "0.1.0-" + second[:7]
593 f.mustUpdate(false)
594 built := f.nix.store + "/4-klaus-0.1.0-" + second[:7]
595 f.wantProfile(Klaus, built)
596 st = f.state()
597 wantInstall(t, "current", st.Current, second, built, Klaus, Klaus)
598 wantInstall(t, "previous", st.Previous, first, installed, Klaus, Klaus)
599}
600
601// TestStateAcrossUpdaters: a state file an updater that knows klaus alone
602// wrote reads as klaus's, and one this updater writes keeps the keys that
603// updater reads.
604func TestStateAcrossUpdaters(t *testing.T) {
605 dir := t.TempDir()
606 older := `{
607 "current": {"commit": "` + strings.Repeat("a", 40) + `", "store_path": "/nix/store/a-klaus-0.1.0-aaaaaaa", "at": "2026-01-02T03:04:05Z"},
608 "previous": {"commit": "bbbbbbb", "store_path": "/nix/store/b-klaus-0.1.0-bbbbbbb", "at": "2026-01-01T03:04:05Z"},
609 "updated_at": "2026-01-02T03:04:05Z"
610}
611`
612 if err := os.WriteFile(StatePath(dir), []byte(older), 0o644); err != nil {
613 t.Fatal(err)
614 }
615 st, err := Load(dir)
616 if err != nil {
617 t.Fatal(err)
618 }
619 wantInstall(t, "current", st.Current, strings.Repeat("a", 40), "/nix/store/a-klaus-0.1.0-aaaaaaa", Klaus, Klaus)
620 wantInstall(t, "previous", st.Previous, "bbbbbbb", "/nix/store/b-klaus-0.1.0-bbbbbbb", Klaus, Klaus)
621
622 st.Current.Element, st.Current.Attribute = ValleyFlow, ValleyFlow
623 u := &Updater{Dir: dir}
624 if err := u.save(st); err != nil {
625 t.Fatal(err)
626 }
627 var read struct {
628 Current, Previous struct {
629 Commit string `json:"commit"`
630 StorePath string `json:"store_path"`
631 }
632 }
633 data, _ := os.ReadFile(StatePath(dir))
634 if err := json.Unmarshal(data, &read); err != nil {
635 t.Fatal(err)
636 }
637 if read.Current.Commit != st.Current.Commit || read.Current.StorePath != st.Current.StorePath ||
638 read.Previous.Commit != st.Previous.Commit || read.Previous.StorePath != st.Previous.StorePath {
639 t.Errorf("an older updater reads %+v from:\n%s", read, data)
640 }
641}