gunk-dev/the-valley

naming_test.go

source6a6791929c36main's published tip history
9.5 KiB
1package cmd
2
3import (
4 "bytes"
5 "context"
6 "encoding/json"
7 "errors"
8 "os"
9 "os/exec"
10 "path/filepath"
11 "strings"
12 "testing"
13
14 "the-valley/flow/internal/git"
15 "the-valley/flow/internal/location"
16 "the-valley/flow/internal/run"
17 "the-valley/flow/internal/selfupdate"
18)
19
20func writeJSON(t *testing.T, path string, v any) {
21 t.Helper()
22 data, err := json.Marshal(v)
23 if err != nil {
24 t.Fatal(err)
25 }
26 if err := os.MkdirAll(filepath.Dir(path), 0o755); err != nil {
27 t.Fatal(err)
28 }
29 if err := os.WriteFile(path, data, 0o644); err != nil {
30 t.Fatal(err)
31 }
32}
33
34// naming status reads state under either name: sessions in both roots, the
35// registry and self-update state under the flow names, and reports what
36// keeps the host from advancing, each with its reason.
37func TestNamingReport(t *testing.T) {
38 home := t.TempDir()
39 t.Setenv("HOME", home)
40 l := location.Layout{Home: home, StateHome: filepath.Join(home, ".local", "state"), Gen: location.Legacy}
41 oldRoot, newRoot := l.SessionRoots()[0], l.SessionRoots()[1]
42
43 live := map[string]bool{"%1": true, "%2": true}
44 seed := func(dir string, st *run.State) {
45 t.Helper()
46 store := run.NewHomeDirStoreFromPath(dir)
47 if err := store.Save(st); err != nil {
48 t.Fatal(err)
49 }
50 }
51 p1, p2, p3 := "%1", "%2", "%3"
52 seed(filepath.Join(oldRoot, "session-a"), &run.State{ID: "session-a", Type: "session", CoordinatorPane: &p1})
53 seed(filepath.Join(newRoot, "session-b"), &run.State{ID: "session-b", Type: "session", CoordinatorPane: &p2, CreatedBy: "1.0-feedbee", NamingGeneration: "legacy"})
54 seed(filepath.Join(oldRoot, "session-c"), &run.State{ID: "session-c", Type: "session", CoordinatorPane: &p3})
55
56 // A registered project whose one worktree has an older hook.
57 clone := filepath.Join(home, "src", "app")
58 for _, args := range [][]string{
59 {"init", "-q", "-b", "main", clone},
60 {"-C", clone, "-c", "user.name=t", "-c", "user.email=t@example.org", "commit", "-q", "--allow-empty", "-m", "init"},
61 {"-C", clone, "worktree", "add", "-q", "-b", "run", filepath.Join(home, "wt")},
62 } {
63 if out, err := exec.Command("git", args...).CombinedOutput(); err != nil {
64 t.Fatalf("git %v: %v: %s", args, err, out)
65 }
66 }
67 wt := filepath.Join(home, "wt")
68 if err := git.InstallHooks(context.Background(), wt, git.Provenance{}, nil); err != nil {
69 t.Fatal(err)
70 }
71 gitDir, err := exec.Command("git", "-C", wt, "rev-parse", "--absolute-git-dir").Output()
72 if err != nil {
73 t.Fatal(err)
74 }
75 if err := os.WriteFile(filepath.Join(strings.TrimSpace(string(gitDir)), "hooks", "commit-msg"), []byte("#!/bin/sh\n"), 0o755); err != nil {
76 t.Fatal(err)
77 }
78 registry := filepath.Join(home, ".valley", "flow", "projects.json")
79 // Saved registries hold paths under HOME as ~/...
80 writeJSON(t, registry, map[string]any{"projects": map[string]string{"app": "~/src/app", "gone": filepath.Join(home, "gone")}})
81
82 // The previous build is a program that leaves a mark if run: the
83 // report must not run it.
84 previous, ran := filepath.Join(home, "previous"), filepath.Join(home, "ran")
85 if err := os.MkdirAll(filepath.Join(previous, "bin"), 0o755); err != nil {
86 t.Fatal(err)
87 }
88 if err := os.WriteFile(filepath.Join(previous, "bin", "klaus"), []byte("#!/bin/sh\n: > "+ran+"\n"), 0o755); err != nil {
89 t.Fatal(err)
90 }
91 statePath := filepath.Join(home, ".valley", "flow", "self-update.json")
92 writeJSON(t, statePath, selfupdate.State{
93 Current: &selfupdate.Install{Commit: "1111111111", StorePath: "/nix/store/new"},
94 Previous: &selfupdate.Install{Commit: "2222222222", StorePath: previous},
95 })
96 for _, d := range []string{filepath.Join(home, ".klaus", "memory"), filepath.Join(home, ".valley", "flow", "memory")} {
97 if err := os.MkdirAll(d, 0o755); err != nil {
98 t.Fatal(err)
99 }
100 }
101
102 r := buildNamingReport(context.Background(), namingInputs{
103 layout: l,
104 tmux: run.TmuxDeps{
105 PaneExists: func(p string) bool { return live[p] },
106 PaneIsIdle: func(string) bool { return false },
107 PaneIsDead: func(string) bool { return false },
108 },
109 })
110
111 if r.Generation != location.Legacy || r.Next != location.Bridge || r.Allocates != location.Legacy {
112 t.Errorf("generation %q, next %q, allocates %q", r.Generation, r.Next, r.Allocates)
113 }
114 places := map[string]namingPlace{}
115 for _, p := range r.Places {
116 places[p.Kind] = p
117 }
118 if p := places["project registry"]; len(p.Paths) != 1 || p.Paths[0] != registry || !p.Exists {
119 t.Errorf("registry place %+v, want %s", p, registry)
120 }
121 if p := places["self-update state"]; len(p.Paths) != 1 || p.Paths[0] != statePath {
122 t.Errorf("self-update place %+v, want %s", p, statePath)
123 }
124 if p := places["sessions"]; len(p.Paths) != 2 {
125 t.Errorf("sessions place %+v, want both roots", p)
126 }
127 if p := places["shared memory"]; p.Error == "" || len(p.Paths) != 2 {
128 t.Errorf("memory under both names reported %+v, want a conflict naming both", p)
129 }
130
131 if len(r.Sessions) != 2 || r.Sessions[0].ID != "session-a" || r.Sessions[0].CreatedBy != "" ||
132 r.Sessions[1].ID != "session-b" || r.Sessions[1].CreatedBy != "1.0-feedbee" {
133 t.Errorf("live sessions %+v, want session-a (unrecorded) and session-b", r.Sessions)
134 }
135 if len(r.Projects) != 2 || len(r.Projects[0].Hooks) != 1 || r.Projects[0].Hooks[0].Current || r.Projects[1].Error == "" {
136 t.Errorf("projects %+v, want app with one older hook and gone unreadable", r.Projects)
137 }
138 if r.SelfUpdate.Current == nil || r.SelfUpdate.Previous == nil || r.SelfUpdate.Previous.StorePath != previous {
139 t.Errorf("self-update %+v", r.SelfUpdate)
140 }
141 if _, err := os.Stat(ran); !errors.Is(err, os.ErrNotExist) {
142 t.Error("naming status ran the previous build")
143 }
144
145 blocked := map[string]bool{}
146 for _, b := range r.Blockers {
147 if b.Reason == "" {
148 t.Errorf("blocker %q has no reason", b.What)
149 }
150 blocked[b.What] = true
151 }
152 for _, want := range []string{"this build", "shared memory", "session session-a", "project app", "project gone", "self-update's previous build 2222222"} {
153 if !blocked[want] {
154 t.Errorf("no blocker for %s in %+v", want, r.Blockers)
155 }
156 }
157 if blocked["session session-b"] || blocked["session session-c"] {
158 t.Errorf("a recorded or finished session blocks: %+v", r.Blockers)
159 }
160
161 var out bytes.Buffer
162 printNamingReport(&out, r, home)
163 for _, want := range []string{"~/.valley/flow/projects.json", "session-a", "1.0-feedbee", r.Unseen} {
164 if !strings.Contains(out.String(), want) {
165 t.Errorf("report lacks %q:\n%s", want, out.String())
166 }
167 }
168
169 // It changed nothing: no session, registry or lock appeared.
170 for _, p := range []string{filepath.Join(home, ".klaus", "projects.json"), filepath.Join(home, ".klaus", "locks"), filepath.Join(newRoot, "session-a")} {
171 if _, err := os.Stat(p); !errors.Is(err, os.ErrNotExist) {
172 t.Errorf("naming status made %s", p)
173 }
174 }
175}
176
177// State that can't be read blocks: a registry is not taken for one with
178// no projects, a session for a finished one, whether its runs directory, a
179// record or a record's contents can't be read, nor self-update state for
180// one without a rollback target.
181func TestNamingReportUnreadableState(t *testing.T) {
182 home := t.TempDir()
183 t.Setenv("HOME", home)
184 for path, data := range map[string]string{
185 filepath.Join(home, ".klaus", "projects.json"): "{",
186 filepath.Join(home, "state", "klaus", "self-update.json"): "{",
187 filepath.Join(home, ".klaus", "sessions", "session-x", "runs"): "a file, not a directory",
188 filepath.Join(home, ".klaus", "sessions", "session-y", "runs", "run-1.json"): "{",
189 } {
190 if err := os.MkdirAll(filepath.Dir(path), 0o755); err != nil {
191 t.Fatal(err)
192 }
193 if err := os.WriteFile(path, []byte(data), 0o644); err != nil {
194 t.Fatal(err)
195 }
196 }
197 // A record no one can read, root included: a symlink to a directory.
198 runs := filepath.Join(home, ".klaus", "sessions", "session-z", "runs")
199 if err := os.MkdirAll(runs, 0o755); err != nil {
200 t.Fatal(err)
201 }
202 if err := os.Symlink(".", filepath.Join(runs, "run-1.json")); err != nil {
203 t.Fatal(err)
204 }
205 r := buildNamingReport(context.Background(), namingInputs{
206 layout: location.Layout{Home: home, StateHome: filepath.Join(home, "state"), Gen: location.Legacy},
207 tmux: run.TmuxDeps{PaneExists: func(string) bool { return false }, PaneIsIdle: func(string) bool { return true }, PaneIsDead: func(string) bool { return true }},
208 })
209 blocked := map[string]bool{}
210 for _, b := range r.Blockers {
211 blocked[b.What] = true
212 }
213 for _, want := range []string{"project registry", "self-update state", "session session-x", "session session-y", "session session-z"} {
214 if !blocked[want] {
215 t.Errorf("no blocker for an unreadable %s: %+v", want, r.Blockers)
216 }
217 }
218}
219
220// At flow, the last generation, nothing is left to advance to.
221func TestNamingReportAtFlow(t *testing.T) {
222 home := t.TempDir()
223 t.Setenv("HOME", home)
224 r := buildNamingReport(context.Background(), namingInputs{
225 layout: location.Layout{Home: home, StateHome: filepath.Join(home, "state"), Gen: location.Flow},
226 tmux: run.TmuxDeps{PaneExists: func(string) bool { return false }, PaneIsIdle: func(string) bool { return true }, PaneIsDead: func(string) bool { return true }},
227 })
228 if r.Next != "" || len(r.Blockers) != 0 {
229 t.Errorf("at flow: next %q, blockers %+v", r.Next, r.Blockers)
230 }
231}
232
233// An unknown session is an error and no store: a caller that checks the
234// store, not the error, must find nothing to use.
235func TestSessionStoreUnknownIsNil(t *testing.T) {
236 t.Setenv("HOME", t.TempDir())
237 t.Setenv(sessionIDEnv, "session-unknown")
238 store, err := sessionStore()
239 if err == nil || !errors.Is(err, location.ErrUnknownSession) {
240 t.Errorf("sessionStore() error = %v, want ErrUnknownSession", err)
241 }
242 if store != nil {
243 t.Errorf("sessionStore() = %#v, want a nil interface", store)
244 }
245}