gunk-dev/the-valley

location_test.go

source6a6791929c36main's published tip history
12.8 KiB
1package location
2
3import (
4 "errors"
5 "os"
6 "path/filepath"
7 "reflect"
8 "strings"
9 "testing"
10)
11
12func testLayout(t *testing.T) Layout {
13 t.Helper()
14 home := t.TempDir()
15 return Layout{Home: home, StateHome: filepath.Join(home, ".local", "state")}
16}
17
18func write(t *testing.T, path, data string) {
19 t.Helper()
20 if err := os.MkdirAll(filepath.Dir(path), 0o755); err != nil {
21 t.Fatal(err)
22 }
23 if err := os.WriteFile(path, []byte(data), 0o644); err != nil {
24 t.Fatal(err)
25 }
26}
27
28func mkdir(t *testing.T, path string) {
29 t.Helper()
30 if err := os.MkdirAll(path, 0o755); err != nil {
31 t.Fatal(err)
32 }
33}
34
35func TestParseGeneration(t *testing.T) {
36 for in, want := range map[string]Generation{"": Legacy, "legacy": Legacy, "bridge": Bridge, "flow": Flow} {
37 if got, err := ParseGeneration(in); err != nil || got != want {
38 t.Errorf("ParseGeneration(%q) = %q, %v; want %q", in, got, err, want)
39 }
40 }
41 for _, in := range []string{"Legacy", "w1", " flow"} {
42 if _, err := ParseGeneration(in); err == nil {
43 t.Errorf("ParseGeneration(%q) accepted it", in)
44 }
45 }
46 if Legacy.Next() != Bridge || Bridge.Next() != Flow || Flow.Next() != "" {
47 t.Errorf("Next: %q %q %q", Legacy.Next(), Bridge.Next(), Flow.Next())
48 }
49}
50
51// A declaration is the file under the flow names when one is there, else
52// the legacy file, one file at a time.
53func TestDeclarationsFallBackPerFile(t *testing.T) {
54 l := testLayout(t)
55 legacy, flow := filepath.Join(l.Home, ".klaus", "config.json"), filepath.Join(l.Home, ".valley", "flow", "config.json")
56 check := func(want string) {
57 t.Helper()
58 if got, err := l.HostConfig(); err != nil || got != want {
59 t.Errorf("HostConfig() = %q, %v; want %q", got, err, want)
60 }
61 }
62 check(legacy)
63 write(t, legacy, "{}")
64 check(legacy)
65 write(t, flow, "{}")
66 check(flow)
67
68 repo := t.TempDir()
69 write(t, filepath.Join(repo, ".klaus", "config.json"), "{}")
70 write(t, filepath.Join(repo, ".klaus", "prompt.md"), "old")
71 write(t, filepath.Join(repo, ".valley", "flow", "prompt.md"), "new")
72 for name, want := range map[string]string{
73 ProjectConfig: filepath.Join(repo, ".klaus", "config.json"),
74 WorkerPrompt: filepath.Join(repo, ".valley", "flow", "prompt.md"),
75 Principles: filepath.Join(repo, ".klaus", "principles.md"),
76 } {
77 if got, err := ProjectFile(repo, name); err != nil || got != want {
78 t.Errorf("ProjectFile(%s) = %q, %v; want %q", name, got, err, want)
79 }
80 }
81}
82
83// A file under the flow names that can't be read is still the one: the
84// reader's error is never a fall back to the legacy file, and a symlink
85// to nothing, which a reader would take for no file, is an error.
86func TestDeclarationPresentButBroken(t *testing.T) {
87 repo := t.TempDir()
88 write(t, filepath.Join(repo, ".klaus", "prompt.md"), "old")
89 flow := filepath.Join(repo, ".valley", "flow", "prompt.md")
90 mkdir(t, flow) // a directory: present, and unreadable as a file
91 if got, err := ProjectFile(repo, WorkerPrompt); err != nil || got != flow {
92 t.Errorf("ProjectFile = %q, %v; want %q", got, err, flow)
93 }
94 if err := os.Remove(flow); err != nil {
95 t.Fatal(err)
96 }
97 if err := os.Symlink(filepath.Join(repo, "nowhere"), flow); err != nil {
98 t.Fatal(err)
99 }
100 if got, err := ProjectFile(repo, WorkerPrompt); err == nil {
101 t.Errorf("ProjectFile with a dangling symlink = %q, want an error", got)
102 }
103
104 // A flow root that is not a directory can't be checked: an error.
105 other := t.TempDir()
106 write(t, filepath.Join(other, ".valley"), "a file")
107 write(t, filepath.Join(other, ".klaus", "prompt.md"), "old")
108 if got, err := ProjectFile(other, WorkerPrompt); err == nil {
109 t.Errorf("ProjectFile under a .valley file = %q, want an error", got)
110 }
111}
112
113func TestSingleValuedState(t *testing.T) {
114 l := testLayout(t)
115 legacy, flow := filepath.Join(l.Home, ".klaus", "projects.json"), filepath.Join(l.Home, ".valley", "flow", "projects.json")
116
117 for _, g := range Generations {
118 gl := l
119 gl.Gen = g
120 if got, err := gl.Registry(); err != nil || got != legacy {
121 t.Errorf("%s: Registry() with none = %q, %v; want the legacy %q", g, got, err, legacy)
122 }
123 }
124
125 write(t, flow, "{}")
126 if got, err := l.Registry(); err != nil || got != flow {
127 t.Errorf("Registry() with the flow file = %q, %v; want %q", got, err, flow)
128 }
129
130 write(t, legacy, "{}")
131 _, err := l.Registry()
132 var conflict *ConflictError
133 if !errors.As(err, &conflict) || !reflect.DeepEqual(conflict.Paths, []string{legacy, flow}) {
134 t.Fatalf("Registry() with both = %v, want a ConflictError naming both", err)
135 }
136 if !strings.Contains(err.Error(), legacy) || !strings.Contains(err.Error(), flow) {
137 t.Errorf("conflict message names neither path: %v", err)
138 }
139
140 // One file under both names is one registry.
141 if err := os.Remove(flow); err != nil {
142 t.Fatal(err)
143 }
144 if err := os.Symlink(legacy, flow); err != nil {
145 t.Fatal(err)
146 }
147 if got, err := l.Registry(); err != nil || got != legacy {
148 t.Errorf("Registry() through a symlink = %q, %v; want %q", got, err, legacy)
149 }
150 // A symlink names the file it points at, so a save renames over the
151 // file rather than the link.
152 if err := os.Remove(legacy); err != nil {
153 t.Fatal(err)
154 }
155 write(t, filepath.Join(l.Home, "real.json"), "{}")
156 if err := os.Symlink(filepath.Join(l.Home, "real.json"), legacy); err != nil {
157 t.Fatal(err)
158 }
159 if err := os.Remove(flow); err != nil {
160 t.Fatal(err)
161 }
162 if err := os.Symlink(legacy, flow); err != nil {
163 t.Fatal(err)
164 }
165 if got, err := l.Registry(); err != nil || got != filepath.Join(l.Home, "real.json") {
166 t.Errorf("Registry() through symlinks = %q, %v; want the file itself", got, err)
167 }
168 if err := os.Remove(legacy); err != nil {
169 t.Fatal(err)
170 }
171 if err := os.Rename(filepath.Join(l.Home, "real.json"), legacy); err != nil {
172 t.Fatal(err)
173 }
174
175 // A hard link is two names a save would part: refused.
176 if err := os.Remove(flow); err != nil {
177 t.Fatal(err)
178 }
179 if err := os.Link(legacy, flow); err != nil {
180 t.Fatal(err)
181 }
182 if _, err := l.Registry(); !errors.As(err, &conflict) {
183 t.Errorf("Registry() through a hard link = %v, want a ConflictError", err)
184 }
185
186 // Self-update's legacy state is under the state directory.
187 state := filepath.Join(l.StateHome, "klaus", "self-update.json")
188 write(t, state, "{}")
189 if got, err := l.SelfUpdateState(); err != nil || got != state {
190 t.Errorf("SelfUpdateState() = %q, %v; want %q", got, err, state)
191 }
192 write(t, filepath.Join(l.Home, ".valley", "flow", "self-update.json"), "{}")
193 if _, err := l.SelfUpdateState(); !errors.As(err, &conflict) {
194 t.Errorf("SelfUpdateState() with both = %v, want a ConflictError", err)
195 }
196
197 mkdir(t, filepath.Join(l.Home, ".valley", "flow", "memory"))
198 if got, err := l.Memory(); err != nil || got != filepath.Join(l.Home, ".valley", "flow", "memory") {
199 t.Errorf("Memory() = %q, %v", got, err)
200 }
201}
202
203// Every generation allocates the legacy names; the host config decides the
204// generation when the layout doesn't, and a bad one allocates nothing.
205func TestAllocation(t *testing.T) {
206 l := testLayout(t)
207 for _, g := range Generations {
208 write(t, filepath.Join(l.Home, ".klaus", "config.json"), `{"naming_generation": "`+string(g)+`"}`)
209 if got, err := l.Generation(); err != nil || got != g {
210 t.Errorf("Generation() = %q, %v; want %q", got, err, g)
211 }
212 dir, err := l.NewSession("session-x")
213 if want := filepath.Join(l.Home, ".klaus", "sessions", "session-x"); err != nil || dir != want {
214 t.Errorf("%s: NewSession = %q, %v; want %q", g, dir, err, want)
215 }
216 if got, err := l.SyncLog(); err != nil || got != filepath.Join(l.Home, ".klaus", "sync.log") {
217 t.Errorf("%s: SyncLog = %q, %v", g, got, err)
218 }
219 if got, err := l.StandaloneStore("/repo/.git"); err != nil || got != filepath.Join("/repo/.git", "klaus") {
220 t.Errorf("%s: StandaloneStore = %q, %v", g, got, err)
221 }
222 }
223
224 write(t, filepath.Join(l.Home, ".valley", "flow", "config.json"), `{"naming_generation": "w2"}`)
225 if _, err := l.NewSession("session-y"); err == nil || !strings.Contains(err.Error(), "w2") {
226 t.Errorf("NewSession under a bad generation = %v, want its error", err)
227 }
228 write(t, filepath.Join(l.Home, ".valley", "flow", "config.json"), `{"naming_generation": `)
229 if _, err := l.ConsultSnapshots(); err == nil {
230 t.Error("ConsultSnapshots under a malformed host config succeeded")
231 }
232}
233
234func TestSessions(t *testing.T) {
235 l := testLayout(t)
236 oldRoot, newRoot := l.SessionRoots()[0], l.SessionRoots()[1]
237 mkdir(t, filepath.Join(oldRoot, "session-1"))
238 mkdir(t, filepath.Join(newRoot, "session-2"))
239 write(t, filepath.Join(newRoot, "stray.txt"), "")
240
241 got, err := l.Sessions()
242 want := []Session{{"session-1", filepath.Join(oldRoot, "session-1")}, {"session-2", filepath.Join(newRoot, "session-2")}}
243 if err != nil || !reflect.DeepEqual(got, want) {
244 t.Fatalf("Sessions() = %v, %v; want %v", got, err, want)
245 }
246 if dir, err := l.Session("session-2"); err != nil || dir != want[1].Dir {
247 t.Errorf("Session(session-2) = %q, %v", dir, err)
248 }
249
250 // An unknown ID fails, and creates nothing.
251 if _, err := l.Session("session-9"); !errors.Is(err, ErrUnknownSession) {
252 t.Errorf("Session(unknown) = %v, want ErrUnknownSession", err)
253 }
254 for _, root := range l.SessionRoots() {
255 if _, err := os.Stat(filepath.Join(root, "session-9")); !os.IsNotExist(err) {
256 t.Errorf("looking up an unknown session made %s", root)
257 }
258 }
259 for _, id := range []string{"", ".", "..", "../session-1", "a/b"} {
260 if _, err := l.Session(id); err == nil || errors.Is(err, ErrUnknownSession) {
261 t.Errorf("Session(%q) = %v, want it refused", id, err)
262 }
263 }
264 if _, err := l.NewSession("session-2"); err == nil {
265 t.Error("NewSession of an existing ID succeeded")
266 }
267
268 // The same ID under both roots names no session, and the error names both.
269 mkdir(t, filepath.Join(newRoot, "session-1"))
270 got, err = l.Sessions()
271 var conflict *ConflictError
272 if !errors.As(err, &conflict) || !reflect.DeepEqual(conflict.Paths, []string{filepath.Join(oldRoot, "session-1"), filepath.Join(newRoot, "session-1")}) {
273 t.Fatalf("Sessions() with a duplicate: err = %v", err)
274 }
275 if !reflect.DeepEqual(got, want[1:]) {
276 t.Errorf("Sessions() with a duplicate = %v, want the rest: %v", got, want[1:])
277 }
278 if _, err := l.Session("session-1"); !errors.As(err, &conflict) {
279 t.Errorf("Session(duplicate) = %v, want a ConflictError", err)
280 }
281
282 // One directory under both roots is one session.
283 if err := os.Remove(filepath.Join(newRoot, "session-1")); err != nil {
284 t.Fatal(err)
285 }
286 if err := os.Symlink(filepath.Join(oldRoot, "session-1"), filepath.Join(newRoot, "session-1")); err != nil {
287 t.Fatal(err)
288 }
289 if dir, err := l.Session("session-1"); err != nil || dir != filepath.Join(oldRoot, "session-1") {
290 t.Errorf("Session through a symlink = %q, %v", dir, err)
291 }
292 // A symlinked session is listed as it is looked up.
293 mkdir(t, filepath.Join(l.Home, "elsewhere", "session-3"))
294 if err := os.Symlink(filepath.Join(l.Home, "elsewhere", "session-3"), filepath.Join(newRoot, "session-3")); err != nil {
295 t.Fatal(err)
296 }
297 got, err = l.Sessions()
298 ids := map[string]int{}
299 for _, s := range got {
300 ids[s.ID]++
301 }
302 if err != nil || ids["session-1"] != 1 || ids["session-3"] != 1 {
303 t.Errorf("Sessions() = %v, %v; want session-1 once and the symlinked session-3", got, err)
304 }
305}
306
307func TestScaffoldWritesWhereItReads(t *testing.T) {
308 l := testLayout(t)
309 repo := t.TempDir()
310 if got, err := l.ScaffoldProjectFile(repo, ProjectConfig); err != nil || got != filepath.Join(repo, ".klaus", "config.json") {
311 t.Errorf("ScaffoldProjectFile with none = %q, %v", got, err)
312 }
313 write(t, filepath.Join(repo, ".valley", "flow", "config.json"), "{}")
314 if got, err := l.ScaffoldProjectFile(repo, ProjectConfig); err != nil || got != filepath.Join(repo, ".valley", "flow", "config.json") {
315 t.Errorf("ScaffoldProjectFile with the flow file = %q, %v", got, err)
316 }
317 write(t, filepath.Join(l.Home, ".valley", "flow", "config.json"), "{}")
318 if got, err := l.ScaffoldHostConfig(); err != nil || got != filepath.Join(l.Home, ".valley", "flow", "config.json") {
319 t.Errorf("ScaffoldHostConfig = %q, %v", got, err)
320 }
321}
322
323// New state needs only the generation: a legacy host config that can't be
324// read or parsed sets none, as flow never read it to allocate, while one
325// under the flow names that can't be is an error.
326func TestGenerationReadsLegacyHostConfigAsBefore(t *testing.T) {
327 l := testLayout(t)
328 legacy, flow := filepath.Join(l.Home, ".klaus", "config.json"), filepath.Join(l.Home, ".valley", "flow", "config.json")
329 write(t, legacy, "{")
330 if g, err := l.Generation(); err != nil || g != Legacy {
331 t.Errorf("Generation() with a malformed legacy host config = %q, %v; want legacy", g, err)
332 }
333 if _, err := l.NewSessionsRoot(); err != nil {
334 t.Errorf("NewSessionsRoot() with a malformed legacy host config: %v", err)
335 }
336 write(t, legacy, `{"naming_generation": "w1"}`)
337 if _, err := l.Generation(); err == nil {
338 t.Error("Generation() accepted naming_generation w1")
339 }
340 mkdir(t, flow)
341 if _, err := l.Generation(); err == nil {
342 t.Error("Generation() with an unreadable host config under the flow names fell back")
343 }
344 if !FlowNamed(flow) || FlowNamed(legacy) {
345 t.Errorf("FlowNamed: %s %v, %s %v", flow, FlowNamed(flow), legacy, FlowNamed(legacy))
346 }
347}