package rustlang import ( "fmt" "os" "strings" "testing" "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 Rust writes are the one part of a project's // .turbo-rust directory that is about Rust, 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 TestTheCreatedToolsFileHoldsTheCargoCommandsAndTheExampleBesideThem(t *testing.T) { // These are what a Rust project runs before it commits, and they are the // reason the file exists at all. 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": "cargo fmt", "Lint": "cargo clippy --all-targets", "Build": "cargo build", "Test": "cargo test", "Run": "cargo run", "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 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) { // `cargo run` starts a program that may read the keyboard, and a popup // cannot answer one. Echo is a terminal too, as the worked example of a // tool in a menu of its own. 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, "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 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 TestTheCreatedToolsFileNamesTheRustMenuNotTheGoOne(t *testing.T) { // The comments explain which menu a tool lands in by naming it, and naming // the wrong editor's menu is the copy-and-paste mistake this catches. 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, "Rust menu") { t.Errorf("the created file never names the Rust menu:\n%s", contents) } if strings.Contains(contents, "Go menu") || strings.Contains(contents, "turbo-go") { t.Errorf("the created file still talks about Turbo Go:\n%s", contents) } } 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 TestTheCreatedSnippetsFileHoldsUsableRustSnippets(t *testing.T) { noUserSnippets(t) dir := t.TempDir() if _, err := snippets.Create(Profile(), dir); err != nil { t.Fatalf("snippets.Create() error = %v", err) } groups := loadSnippets(t, dir).Groups(string(Language)) if len(groups) == 0 { t.Fatal("the created file offers nothing at all in a Rust file") } for _, group := range groups { for _, snippet := range group.Snippets { if snippet.Name == "" || snippet.Body == "" { t.Errorf("the created file holds an unusable snippet %+v", snippet) } } } } func TestTheCreatedSnippetsIndentWithSpacesTheWayRustfmtDoes(t *testing.T) { // Rust indents with four spaces. A tab that crept in would land in // somebody's file and be reformatted out on the next `cargo fmt`, which is // a diff nobody asked for. 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(string(Language)) { for _, snippet := range group.Snippets { if strings.Contains(snippet.Body, "\t") { t.Errorf("%q indents with a tab:\n%q", snippet.Name, snippet.Body) } } } } 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{"theme", "autosave", "autosave_delay", "-list-themes"} { if !strings.Contains(contents, want) { t.Errorf("the created file never mentions %q:\n%s", want, contents) } } } func TestEveryTemplateNamesThisEditorAndNotTheOther(t *testing.T) { // The three templates started as Turbo Go's. A leftover "turbo-go" in a // file written into somebody's Rust project is the whole class of mistake // this catches, and it is invisible to every other test here. templates := map[string]string{ "settings": settingsTemplate, "snippets": snippetsTemplate, "tools": toolsTemplate, } for name, template := range templates { t.Run(name, func(t *testing.T) { if strings.Contains(template, "turbo-go") { t.Errorf("the %s template still says turbo-go:\n%s", name, template) } if !strings.Contains(template, Slug) { t.Errorf("the %s template never names %s:\n%s", name, Slug, template) } }) } } func TestTheSnippetsTemplateTakesExactlyTwoBlanks(t *testing.T) { // profile.Templates says Snippets is formatted with the ungrouped group's // name and the user's path, in that order. A third %s, or a stray one in a // comment, comes out as %!s(MISSING) in somebody's project. if got := strings.Count(snippetsTemplate, "%s"); got != 2 { t.Errorf("the snippets template has %d %%s, want 2", got) } if got := strings.Count(settingsTemplate, "%q"); got != 2 { t.Errorf("the settings template has %d %%q, want 2", got) } if strings.Contains(toolsTemplate, "%") { t.Errorf("the tools template takes no arguments but contains a %%:\n%s", toolsTemplate) } } 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}}", "cargo new --bin {{crate name}}", "{{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) { // The examples live in comments, so none of them may become a real tool — // and the loader must not trip over the braces in the prose either. 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 got := tool.Placeholders(); got != nil { t.Errorf("%q asks for %v; none of the five starter commands takes a value", tool.Name, got) } } } 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) } } }