gunk-dev/the-valley

naming_test.go

source4cbb5ec9c5dbmain's published tip history
11.6 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 // Snapshots a consult under bridge left, which a legacy host no longer
97 // allocates to.
98 snapshots := filepath.Join(home, ".valley", "flow", "consult-snapshots")
99 for _, d := range []string{filepath.Join(home, ".klaus", "memory"), filepath.Join(home, ".valley", "flow", "memory"), snapshots} {
100 if err := os.MkdirAll(d, 0o755); err != nil {
101 t.Fatal(err)
102 }
103 }
104
105 r := buildNamingReport(context.Background(), namingInputs{
106 layout: l,
107 tmux: run.TmuxDeps{
108 PaneExists: func(p string) bool { return live[p] },
109 PaneIsIdle: func(string) bool { return false },
110 PaneIsDead: func(string) bool { return false },
111 },
112 })
113
114 if r.Generation != location.Legacy || r.Next != location.Bridge || r.Allocates != location.Legacy {
115 t.Errorf("generation %q, next %q, allocates %q", r.Generation, r.Next, r.Allocates)
116 }
117 places := map[string]namingPlace{}
118 for _, p := range r.Places {
119 places[p.Kind] = p
120 }
121 if p := places["project registry"]; len(p.Paths) != 1 || p.Paths[0] != registry || !p.Exists {
122 t.Errorf("registry place %+v, want %s", p, registry)
123 }
124 if p := places["self-update state"]; len(p.Paths) != 1 || p.Paths[0] != statePath {
125 t.Errorf("self-update place %+v, want %s", p, statePath)
126 }
127 if p := places["sessions"]; len(p.Paths) != 2 {
128 t.Errorf("sessions place %+v, want both roots", p)
129 }
130 if p := places["shared memory"]; p.Error == "" || len(p.Paths) != 2 {
131 t.Errorf("memory under both names reported %+v, want a conflict naming both", p)
132 }
133 if p := places["consult snapshots"]; len(p.Paths) != 1 || p.Paths[0] != snapshots || !p.Exists {
134 t.Errorf("consult snapshots place %+v, want %s, where they are", p, snapshots)
135 }
136
137 if len(r.Sessions) != 2 || r.Sessions[0].ID != "session-a" || r.Sessions[0].CreatedBy != "" ||
138 r.Sessions[1].ID != "session-b" || r.Sessions[1].CreatedBy != "1.0-feedbee" {
139 t.Errorf("live sessions %+v, want session-a (unrecorded) and session-b", r.Sessions)
140 }
141 if len(r.Projects) != 2 || len(r.Projects[0].Hooks) != 1 || r.Projects[0].Hooks[0].Current || r.Projects[1].Error == "" {
142 t.Errorf("projects %+v, want app with one older hook and gone unreadable", r.Projects)
143 }
144 if r.SelfUpdate.Current == nil || r.SelfUpdate.Previous == nil || r.SelfUpdate.Previous.StorePath != previous {
145 t.Errorf("self-update %+v", r.SelfUpdate)
146 }
147 if _, err := os.Stat(ran); !errors.Is(err, os.ErrNotExist) {
148 t.Error("naming status ran the previous build")
149 }
150
151 blocked := map[string]bool{}
152 for _, b := range r.Blockers {
153 if b.Reason == "" {
154 t.Errorf("blocker %q has no reason", b.What)
155 }
156 blocked[b.What] = true
157 }
158 for _, want := range []string{"this build", "shared memory", "session session-a", "project app", "project gone", "self-update's previous build 2222222"} {
159 if !blocked[want] {
160 t.Errorf("no blocker for %s in %+v", want, r.Blockers)
161 }
162 }
163 if blocked["session session-b"] || blocked["session session-c"] {
164 t.Errorf("a recorded or finished session blocks: %+v", r.Blockers)
165 }
166
167 var out bytes.Buffer
168 printNamingReport(&out, r, home)
169 for _, want := range []string{"~/.valley/flow/projects.json", "session-a", "1.0-feedbee", r.Unseen} {
170 if !strings.Contains(out.String(), want) {
171 t.Errorf("report lacks %q:\n%s", want, out.String())
172 }
173 }
174
175 // It changed nothing: no session, registry or lock appeared.
176 for _, p := range []string{filepath.Join(home, ".klaus", "projects.json"), filepath.Join(home, ".klaus", "locks"), filepath.Join(newRoot, "session-a")} {
177 if _, err := os.Stat(p); !errors.Is(err, os.ErrNotExist) {
178 t.Errorf("naming status made %s", p)
179 }
180 }
181}
182
183// State that can't be read blocks: a registry is not taken for one with
184// no projects, a session for a finished one, whether its runs directory, a
185// record or a record's contents can't be read, nor self-update state for
186// one without a rollback target.
187func TestNamingReportUnreadableState(t *testing.T) {
188 home := t.TempDir()
189 t.Setenv("HOME", home)
190 for path, data := range map[string]string{
191 filepath.Join(home, ".klaus", "projects.json"): "{",
192 filepath.Join(home, "state", "klaus", "self-update.json"): "{",
193 filepath.Join(home, ".klaus", "sessions", "session-x", "runs"): "a file, not a directory",
194 filepath.Join(home, ".klaus", "sessions", "session-y", "runs", "run-1.json"): "{",
195 } {
196 if err := os.MkdirAll(filepath.Dir(path), 0o755); err != nil {
197 t.Fatal(err)
198 }
199 if err := os.WriteFile(path, []byte(data), 0o644); err != nil {
200 t.Fatal(err)
201 }
202 }
203 // A record no one can read, root included: a symlink to a directory.
204 runs := filepath.Join(home, ".klaus", "sessions", "session-z", "runs")
205 if err := os.MkdirAll(runs, 0o755); err != nil {
206 t.Fatal(err)
207 }
208 if err := os.Symlink(".", filepath.Join(runs, "run-1.json")); err != nil {
209 t.Fatal(err)
210 }
211 r := buildNamingReport(context.Background(), namingInputs{
212 layout: location.Layout{Home: home, StateHome: filepath.Join(home, "state"), Gen: location.Legacy},
213 tmux: run.TmuxDeps{PaneExists: func(string) bool { return false }, PaneIsIdle: func(string) bool { return true }, PaneIsDead: func(string) bool { return true }},
214 })
215 blocked := map[string]bool{}
216 for _, b := range r.Blockers {
217 blocked[b.What] = true
218 }
219 for _, want := range []string{"project registry", "self-update state", "session session-x", "session session-y", "session session-z"} {
220 if !blocked[want] {
221 t.Errorf("no blocker for an unreadable %s: %+v", want, r.Blockers)
222 }
223 }
224}
225
226// Under each generation the report says which names new state gets in
227// this build, and that this build keeps the host from flow: legacy gives
228// legacy names, bridge and flow bridge names, and only the state checks
229// block bridge.
230func TestNamingReportPerGeneration(t *testing.T) {
231 for _, tc := range []struct {
232 gen location.Generation
233 allocates location.Generation
234 glyph string // the verdict's: the head line's target is blocked or not
235 target location.Generation
236 sessions string // where new sessions go, under home
237 }{
238 {location.Legacy, location.Legacy, "โœ“", location.Bridge, ".klaus/sessions"},
239 {location.Bridge, location.Bridge, "โ—‡", location.Flow, ".valley/flow/sessions"},
240 {location.Flow, location.Bridge, "โ—‡", location.Flow, ".valley/flow/sessions"},
241 } {
242 t.Run(string(tc.gen), func(t *testing.T) {
243 home := t.TempDir()
244 t.Setenv("HOME", home)
245 r := buildNamingReport(context.Background(), namingInputs{
246 layout: location.Layout{Home: home, StateHome: filepath.Join(home, "state"), Gen: tc.gen},
247 tmux: run.TmuxDeps{PaneExists: func(string) bool { return false }, PaneIsIdle: func(string) bool { return true }, PaneIsDead: func(string) bool { return true }},
248 })
249 if r.Allocates != tc.allocates {
250 t.Errorf("allocates %q, want %q", r.Allocates, tc.allocates)
251 }
252 if len(r.Blockers) != 1 || r.Blockers[0].What != "this build" || r.Blockers[0].Blocks != location.Flow {
253 t.Errorf("blockers %+v, want this build alone, blocking flow", r.Blockers)
254 }
255 for _, p := range r.Places {
256 if p.Kind == "sessions" && (len(p.Paths) != 1 || p.Paths[0] != filepath.Join(home, tc.sessions)) {
257 t.Errorf("new sessions go to %v, want %s", p.Paths, filepath.Join(home, tc.sessions))
258 }
259 }
260 if got := namingTarget(r); got != tc.target {
261 t.Errorf("the report's target is %q, want %q", got, tc.target)
262 }
263 var out bytes.Buffer
264 printNamingReport(&out, r, home)
265 if first, _, _ := strings.Cut(out.String(), "\n"); !strings.HasPrefix(first, tc.glyph) ||
266 !strings.Contains(first, string(tc.allocates)) || !strings.Contains(first, string(tc.target)) {
267 t.Errorf("head line %q gives no %s verdict on %s with %s names", first, tc.glyph, tc.target, tc.allocates)
268 }
269 if !strings.Contains(out.String(), "this build") {
270 t.Errorf("report does not list this build's blocker:\n%s", out.String())
271 }
272 })
273 }
274}
275
276// An unknown session is an error and no store: a caller that checks the
277// store, not the error, must find nothing to use.
278func TestSessionStoreUnknownIsNil(t *testing.T) {
279 t.Setenv("HOME", t.TempDir())
280 t.Setenv(sessionIDEnv, "session-unknown")
281 store, err := sessionStore()
282 if err == nil || !errors.Is(err, location.ErrUnknownSession) {
283 t.Errorf("sessionStore() error = %v, want ErrUnknownSession", err)
284 }
285 if store != nil {
286 t.Errorf("sessionStore() = %#v, want a nil interface", store)
287 }
288}