turbo-editors/turbo-gopublic Fork 0
v1.0.2
Commits
Clone
git clone https://git.rickub.com/turbo-editors/turbo-go.git
git clone ssh://git@rickub.com/turbo-editors/turbo-go.git

Host key fingerprint (ed25519): SHA256:iycHnxEyq0Q7uyVpB7JlznP0G7JrTPXLYRcAU5CSLhc — verify it before your first connect.

📦 Turbo Go 3d7798b · on v1.0.2 · k33g · 10h ago
templates_test.go · 507 lines · 17.1 KBGo Blame HistoryRaw
  1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
package golang

import (
	"errors"
	"fmt"
	"os"
	"slices"
	"strings"
	"testing"

	"rickub.com/turbo-editors/turbo-core/acp"
	"rickub.com/turbo-editors/turbo-core/settings"
	"rickub.com/turbo-editors/turbo-core/snippets"
	"rickub.com/turbo-editors/turbo-core/syntax"
	"rickub.com/turbo-editors/turbo-core/tools"
)

// The starter files Turbo Go writes are the one part of a project's .turbo-go
// directory that is about Go, so this is where what is *in* them is checked.
// That the file written is the profile's template at all is turbo-core's test.

// noUserSnippets points the user's own snippets at an empty directory, so a
// test never reads whoever is running it.
func noUserSnippets(t *testing.T) {
	t.Helper()
	t.Setenv(Profile().SnippetDirEnvVar(), t.TempDir())
}

// loadTools reads a project's tools, failing the test if it cannot.
func loadTools(t *testing.T, dir string) tools.List {
	t.Helper()

	list, err := tools.Load(Profile(), dir)
	if err != nil {
		t.Fatalf("tools.Load(%q) error = %v", dir, err)
	}
	return list
}

// loadSnippets reads a project's snippets, failing the test if it cannot.
func loadSnippets(t *testing.T, dir string) snippets.List {
	t.Helper()

	list, err := snippets.Load(Profile(), dir)
	if err != nil {
		t.Fatalf("snippets.Load(%q) error = %v", dir, err)
	}
	return list
}

// readFile returns a file's contents.
func readFile(t *testing.T, path string) string {
	t.Helper()

	data, err := os.ReadFile(path)
	if err != nil {
		t.Fatalf("reading %s: %v", path, err)
	}
	return string(data)
}

// plain strips the tilde hot-key markers from a label.
func plain(label string) string { return strings.ReplaceAll(label, "~", "") }

// hotKey returns the character between the tildes, or 0 when there is none.
func hotKey(label string) rune {
	first := strings.IndexByte(label, '~')
	if first < 0 || first+1 >= len(label) {
		return 0
	}
	return rune(label[first+1])
}

func TestTheCreatedToolsFileHoldsTheGoCommandsAndTheExamplesThatTeachTheFormat(t *testing.T) {
	// The first five are what a Go project runs before it commits, and they are
	// the reason the file exists at all. The three after them are there to
	// teach the format itself — a value the editor asks for, a menu of the
	// tool's own, an output that is not the default — and a starter file that
	// only listed the five would leave all three undiscoverable.
	dir := t.TempDir()
	if _, err := tools.Create(Profile(), dir); err != nil {
		t.Fatalf("tools.Create() error = %v", err)
	}

	byName := map[string]string{}
	for _, tool := range loadTools(t, dir).Tools() {
		byName[plain(tool.Name)] = tool.Command
	}

	want := map[string]string{
		"Format":      "gofmt -l -w .",
		"Lint":        "go vet ./...",
		"Build":       "go build ./...",
		"Test":        "go test ./...",
		"Run":         "go run .",
		"Grep":        "grep -rn {{pattern}} --include='*.go' .",
		"Init module": "go mod init {{module path}}",
		"Echo":        "echo 🎉 tada!",
	}
	for name, command := range want {
		if got := byName[name]; got != command {
			t.Errorf("%s runs %q, want %q", name, got, command)
		}
	}
	for name := range byName {
		if _, ok := want[name]; !ok {
			t.Errorf("the created file holds a tool this test does not know about: %q", name)
		}
	}
}

func TestTheCreatedToolsCarryHotKeys(t *testing.T) {
	// Five items in a menu are worth reaching with one keystroke each.
	dir := t.TempDir()
	if _, err := tools.Create(Profile(), dir); err != nil {
		t.Fatalf("tools.Create() error = %v", err)
	}

	seen := map[rune]string{}
	for _, tool := range loadTools(t, dir).Tools() {
		key := hotKey(tool.Name)
		if key == 0 {
			t.Errorf("%q has no hot key", tool.Name)
			continue
		}
		if other, clash := seen[key]; clash {
			t.Errorf("%q and %q both answer to %c", other, tool.Name, key)
		}
		seen[key] = tool.Name
	}
}

func TestTheCreatedToolsFileDoesNotClaimEverythingRunsInATerminal(t *testing.T) {
	// The header said so before output existed, and left the file contradicting
	// itself two lines above the key that says otherwise.
	dir := t.TempDir()
	if _, err := tools.Create(Profile(), dir); err != nil {
		t.Fatalf("tools.Create() error = %v", err)
	}

	contents := readFile(t, tools.Path(Profile(), dir))
	if strings.Contains(contents, "runs it in a terminal window of its own") {
		t.Errorf("the header still claims every tool runs in a terminal:\n%s", contents)
	}
}

func TestTheCreatedToolsFileExplainsItself(t *testing.T) {
	dir := t.TempDir()
	if _, err := tools.Create(Profile(), dir); err != nil {
		t.Fatalf("tools.Create() error = %v", err)
	}

	contents := readFile(t, tools.Path(Profile(), dir))
	for _, want := range []string{"[[tool]]", "sh -c", "hot key", "popup", "terminal", "editor", "./..."} {
		if !strings.Contains(contents, want) {
			t.Errorf("the created file never mentions %q:\n%s", want, contents)
		}
	}
}

func TestTheCreatedToolsFileNamesAnOutputForEveryTool(t *testing.T) {
	// The key is the interesting part of the format, and a file where it only
	// appears once is a file where nobody notices it exists.
	dir := t.TempDir()
	if _, err := tools.Create(Profile(), dir); err != nil {
		t.Fatalf("tools.Create() error = %v", err)
	}

	for _, tool := range loadTools(t, dir).Tools() {
		if tool.Output == "" {
			t.Errorf("%q leaves its output to the default rather than saying it", tool.Name)
		}
	}
}

func TestEachToolGoesWhereItsOwnOutputBelongs(t *testing.T) {
	// All three destinations appear, because a starter file is where somebody
	// finds out that the key has more than one value. Run and Echo are
	// terminals: a program that reads the keyboard has to be able to be
	// answered, and a popup cannot do that. Grep prints a list worth keeping
	// beside the code and searching with Ctrl-F, which is what an editing
	// window is for. The rest say something short and are read once.
	dir := t.TempDir()
	if _, err := tools.Create(Profile(), dir); err != nil {
		t.Fatalf("tools.Create() error = %v", err)
	}

	want := map[string]tools.Output{
		"Format":      tools.OutputPopup,
		"Lint":        tools.OutputPopup,
		"Build":       tools.OutputPopup,
		"Test":        tools.OutputPopup,
		"Run":         tools.OutputTerminal,
		"Grep":        tools.OutputEditor,
		"Init module": tools.OutputPopup,
		"Echo":        tools.OutputTerminal,
	}
	for _, tool := range loadTools(t, dir).Tools() {
		name := plain(tool.Name)
		if got := tool.Where(); got != want[name] {
			t.Errorf("%s goes to %q, want %q", name, got, want[name])
		}
	}
}

func TestTheCreatedToolsFileShowsHowToUseAnotherMenu(t *testing.T) {
	dir := t.TempDir()
	if _, err := tools.Create(Profile(), dir); err != nil {
		t.Fatalf("tools.Create() error = %v", err)
	}

	contents := readFile(t, tools.Path(Profile(), dir))
	for _, want := range []string{"menu says which menu", `menu = "Tools"`} {
		if !strings.Contains(contents, want) {
			t.Errorf("the created file never shows %q:\n%s", want, contents)
		}
	}
}

func TestTheCreatedSnippetsFilesTabsSurviveTOML(t *testing.T) {
	// A Go snippet is indented with tabs, and every step between the template
	// and the editor is somewhere one can be lost: the multi-line TOML string,
	// the decoder, and the editor's own re-indentation on insertion. Asserting
	// on a tab the body is known to contain is what catches that.
	noUserSnippets(t)
	dir := t.TempDir()
	if _, err := snippets.Create(Profile(), dir); err != nil {
		t.Fatalf("snippets.Create() error = %v", err)
	}

	for _, group := range loadSnippets(t, dir).Groups("go") {
		for _, snippet := range group.Snippets {
			if snippet.Name != "main" {
				continue
			}
			if !strings.Contains(snippet.Body, "\tfmt.Println") {
				t.Errorf("the body is %q; the tab did not survive", snippet.Body)
			}
			return
		}
	}
	t.Fatal("the created file has no \"main\" snippet")
}

func TestTheCreatedSnippetsFileExplainsItself(t *testing.T) {
	noUserSnippets(t)
	dir := t.TempDir()
	if _, err := snippets.Create(Profile(), dir); err != nil {
		t.Fatalf("snippets.Create() error = %v", err)
	}

	contents := readFile(t, snippets.ProjectPath(Profile(), dir))
	for _, want := range []string{"[[snippet]]", "languages", "group", "General", snippets.UserPath(Profile())} {
		if !strings.Contains(contents, want) {
			t.Errorf("the created file never mentions %q:\n%s", want, contents)
		}
	}
}

func TestTheCreatedSettingsFileExplainsItself(t *testing.T) {
	project := t.TempDir()
	if _, err := settings.Create(Profile(), project, "turbo-classic"); err != nil {
		t.Fatalf("settings.Create() error = %v", err)
	}

	contents := readFile(t, settings.Path(Profile(), project))
	for _, want := range []string{"-list-themes", "autosave_delay", "-theme flag"} {
		if !strings.Contains(contents, want) {
			t.Errorf("the created file never mentions %q:\n%s", want, contents)
		}
	}
}

func TestTheCreatedToolsFileExplainsHowToAskForAValue(t *testing.T) {
	// A parameterised tool is only discoverable if the file people get says the
	// syntax exists. The double-brace warning is here too, because somebody
	// reading this file may well have an awk one-liner in mind.
	dir := t.TempDir()
	if _, err := tools.Create(Profile(), dir); err != nil {
		t.Fatalf("tools.Create() error = %v", err)
	}

	contents := readFile(t, tools.Path(Profile(), dir))
	for _, want := range []string{
		"{{label}}",
		"go mod init {{module path}}",
		"{{extra flags...}}",
		"Double braces, not single",
	} {
		if !strings.Contains(contents, want) {
			t.Errorf("the created file never mentions %q:\n%s", want, contents)
		}
	}
}

func TestTheCreatedToolsFileStillLoadsWithItsPlaceholderExamples(t *testing.T) {
	// Two of the starter tools ask for a value, on purpose: a syntax explained
	// only in a comment is a syntax nobody tries. What they ask for is checked
	// here rather than left to the prose, because the braces also appear in the
	// file's *comments* — `{{label}}`, `{{extra flags...}}`, and an awk
	// one-liner warning against single ones — and a loader that read those as
	// tools would ask for something nobody wrote a command for.
	dir := t.TempDir()
	if _, err := tools.Create(Profile(), dir); err != nil {
		t.Fatalf("tools.Create() error = %v", err)
	}

	want := map[string][]tools.Placeholder{
		"Grep":        {{Label: "pattern"}},
		"Init module": {{Label: "module path"}},
	}
	for _, tool := range loadTools(t, dir).Tools() {
		name := plain(tool.Name)
		got := tool.Placeholders()
		if !slices.Equal(got, want[name]) {
			t.Errorf("%q asks for %v, want %v", name, got, want[name])
		}
	}
}

func TestTheCreatedSnippetsFileListsEveryLanguageTheEditorKnows(t *testing.T) {
	// The comment is where a user finds out what they may write in a languages
	// key. One that omits a language the editor colours sends them looking for
	// a feature that is already there.
	noUserSnippets(t)
	dir := t.TempDir()
	if _, err := snippets.Create(Profile(), dir); err != nil {
		t.Fatalf("snippets.Create() error = %v", err)
	}

	contents := readFile(t, snippets.ProjectPath(Profile(), dir))
	for _, language := range syntax.Registered() {
		if !strings.Contains(contents, string(language)) {
			t.Errorf("the created file never mentions the %q language:\n%s", language, contents)
		}
	}
}

func TestTheCreatedSettingsFileTurnsAutosaveOn(t *testing.T) {
	// A project that has gone to the trouble of creating a settings file has
	// said what it wants. The file is the visible, editable place to say
	// otherwise, which is why the default lives here and not in the library.
	project := t.TempDir()
	if _, err := settings.Create(Profile(), project, "turbo-classic"); err != nil {
		t.Fatalf("settings.Create() error = %v", err)
	}

	loaded, err := settings.Load(Profile(), project)
	if err != nil {
		t.Fatalf("settings.Load() error = %v", err)
	}
	if !loaded.Autosave {
		t.Errorf("the created settings file leaves autosave off:\n%s", readFile(t, settings.Path(Profile(), project)))
	}
	if loaded.AutosaveDelay != settings.DefaultAutosaveDelay {
		t.Errorf("AutosaveDelay = %v, want the library default %v", loaded.AutosaveDelay, settings.DefaultAutosaveDelay)
	}
}

func TestAProjectWithNoSettingsFileStillDoesNotAutosave(t *testing.T) {
	// The other half of the decision. Turning autosave on for a project that
	// never opted in would mean the editor writing to disk in any directory it
	// is started in, which is a different and much larger claim.
	if settings.Default().Autosave {
		t.Error("settings.Default() autosaves; a project with no settings file never opted in")
	}
}

// The three embedded templates and the blanks profile.Templates says each one
// takes. Kept together so that adding a verb to a .tmpl file without saying so
// here fails, which is the guard the constants used to get for free by sitting
// next to the contract.
var embeddedTemplates = []struct {
	name     string
	body     string
	verb     string
	blanks   int
	filledBy []any
}{
	{"settings.toml.tmpl", settingsTemplate, "%q", 2, []any{"turbo-classic", "2s"}},
	{"snippets.toml.tmpl", snippetsTemplate, "%s", 2, []any{"General", "/tmp/snippets.toml"}},
	{"tools.toml.tmpl", toolsTemplate, "%", 0, nil},
}

func TestEveryTemplateIsEmbeddedAndNotEmpty(t *testing.T) {
	// go:embed fails to compile when a file is missing, but an empty file
	// compiles happily and writes an empty starter file into somebody's
	// project.
	for _, template := range embeddedTemplates {
		if len(template.body) == 0 {
			t.Errorf("%s embedded as nothing", template.name)
		}
	}
}

func TestEveryTemplateTakesTheBlanksItsContractPromises(t *testing.T) {
	// profile.Templates documents the count and the verb of each. The
	// templates now live in files of their own, so nothing but this notices a
	// verb added, removed, or changed.
	for _, template := range embeddedTemplates {
		if got := strings.Count(template.body, template.verb); got != template.blanks {
			t.Errorf("%s holds %d %q, want %d", template.name, got, template.verb, template.blanks)
		}
	}
}

func TestFillingATemplateLeavesNoFormattingMarker(t *testing.T) {
	// Go writes %!q(MISSING) or %!(EXTRA …) into the output rather than
	// failing, so a template with the wrong number of blanks produces a file
	// that is written, opened, and wrong.
	for _, template := range embeddedTemplates {
		filled := template.body
		if template.filledBy != nil {
			filled = fmt.Sprintf(template.body, template.filledBy...)
		}
		if strings.Contains(filled, "%!") {
			t.Errorf("%s filled to:\n%s", template.name, filled)
		}
	}
}

func TestTheCreatedAgentsFileFillsBothOfItsBlanks(t *testing.T) {
	// The template takes two different values — the project directory, which
	// the example agent's arguments point into, and the user's own file, which
	// a comment names. Go writes %!s(MISSING) into the output rather than
	// failing, so a miscounted verb produces a starter file that is written,
	// opened, and wrong.
	dir := t.TempDir()
	if _, err := acp.Create(Profile(), dir); err != nil {
		t.Fatalf("acp.Create() error = %v", err)
	}

	contents := readFile(t, acp.ProjectPath(Profile(), dir))
	if strings.Contains(contents, "%!") {
		t.Errorf("the created file has an unfilled verb in it:\n%s", contents)
	}
	if want := Profile().ProjectDir() + "/agent.yaml"; !strings.Contains(contents, want) {
		t.Errorf("the example agent does not point at %q:\n%s", want, contents)
	}
	if want := acp.UserPath(Profile()); want != "" && !strings.Contains(contents, want) {
		t.Errorf("the created file never names the user's own file %q:\n%s", want, contents)
	}
}

func TestTheCreatedAgentsFileLoadsBackAsOneAgent(t *testing.T) {
	// The file is mostly comments, and a comment carrying a [[agent]] example
	// that the loader read as real would put an agent nobody configured into
	// the menu.
	dir := t.TempDir()
	if _, err := acp.Create(Profile(), dir); err != nil {
		t.Fatalf("acp.Create() error = %v", err)
	}

	list, err := acp.Load(Profile(), dir)
	if err != nil {
		t.Fatalf("acp.Load() error = %v", err)
	}
	if list.Len() != 1 {
		t.Fatalf("the created file holds %d agents, want 1: %v", list.Len(), list.Agents())
	}

	agent := list.Agents()[0]
	if agent.Command != "docker" {
		t.Errorf("the example agent runs %q, want docker", agent.Command)
	}
	if want := "agent serve acp"; !strings.Contains(agent.CommandLine(), want) {
		t.Errorf("the example command line is %q, want %q in it", agent.CommandLine(), want)
	}
}

func TestTheCreatedAgentsFileExplainsItself(t *testing.T) {
	// The keys and the window's keyboard are both invisible otherwise: this is
	// the only document a user is handed by the editor itself.
	dir := t.TempDir()
	if _, err := acp.Create(Profile(), dir); err != nil {
		t.Fatalf("acp.Create() error = %v", err)
	}

	contents := readFile(t, acp.ProjectPath(Profile(), dir))
	for _, want := range []string{
		"[[agent]]", "name", "command", "args", "env", "cwd",
		"agentclientprotocol.com",
		"Alt-Enter", "Ctrl-W", "Esc",
	} {
		if !strings.Contains(contents, want) {
			t.Errorf("the created file never mentions %q:\n%s", want, contents)
		}
	}
}

func TestCreatingAgentsTwiceLeavesTheFirstAlone(t *testing.T) {
	dir := t.TempDir()
	path, err := acp.Create(Profile(), dir)
	if err != nil {
		t.Fatalf("acp.Create() error = %v", err)
	}
	if err := os.WriteFile(path, []byte("# mine\n"), 0o644); err != nil {
		t.Fatalf("writing over it: %v", err)
	}

	if _, err := acp.Create(Profile(), dir); !errors.Is(err, acp.ErrExists) {
		t.Errorf("acp.Create() error = %v, want ErrExists", err)
	}
	if got := readFile(t, path); got != "# mine\n" {
		t.Errorf("the file was overwritten: %q", got)
	}
}