package mention import ( "os" "path/filepath" "strings" "testing" ) // A workspace with a file, a nested file and a directory, to mention. func workspace(t *testing.T) string { t.Helper() dir := t.TempDir() for _, p := range []string{"main.go", "internal/acp/acp.go"} { if err := os.MkdirAll(filepath.Dir(filepath.Join(dir, p)), 0o755); err != nil { t.Fatal(err) } if err := os.WriteFile(filepath.Join(dir, p), []byte("package x"), 0o644); err != nil { t.Fatal(err) } } return dir } // The text is kept as typed and each existing path becomes one attachment // line, in order, once — the shape an ACP resource_link takes. func TestExpandAttachesExistingPathsOnce(t *testing.T) { dir := workspace(t) in := "compare @main.go with @internal/acp/acp.go, then @main.go again; and @internal too" got, att := Expand(in, dir) want := in + "\n[attached file: " + filepath.Join(dir, "main.go") + "]" + "\n[attached file: " + filepath.Join(dir, "internal/acp/acp.go") + "]" + "\n[attached directory: " + filepath.Join(dir, "internal") + "]" if got != want { t.Errorf("Expand:\n got %q\nwant %q", got, want) } if len(att) != 3 || att[0].Mention != "main.go" || att[2].Dir != true || att[1].Dir { t.Errorf("attachments %+v", att) } } // What is NOT a mention: a path that does not exist (a name, a handle), an // e-mail address (@ glued to a word), a lone @, and the input untouched when // nothing matches. func TestExpandLeavesNonPathsAlone(t *testing.T) { dir := workspace(t) for _, in := range []string{ "ask @bob about it", "mail k33g@example.com", "a lone @ sign", "@does/not/exist.go", "", } { got, att := Expand(in, dir) if got != in || len(att) != 0 { t.Errorf("Expand(%q) = %q, %+v; want the input unchanged and no attachment", in, got, att) } } } // Absolute paths, ~ paths, and mentions wrapped in brackets or quotes or // glued to punctuation all resolve to the same clean absolute path. func TestExpandResolvesAbsoluteHomeAndPunctuated(t *testing.T) { dir := workspace(t) t.Setenv("HOME", dir) abs := filepath.Join(dir, "main.go") for _, in := range []string{ "see @" + abs + ".", "see @~/main.go!", "see (@main.go)", "see \"@./main.go\"", "see @" + dir + "/internal/../main.go", "@main.go", } { _, att := Expand(in, dir) if len(att) != 1 || att[0].Path != abs { t.Errorf("Expand(%q) attachments = %+v, want one at %s", in, att, abs) } } } // A mention is resolved against cwd, not the process directory: the ACP // front end passes the session's cwd, the terminal the directory mm runs in. func TestExpandIsRelativeToCwd(t *testing.T) { dir := workspace(t) _, att := Expand("@acp.go", filepath.Join(dir, "internal", "acp")) if len(att) != 1 || !strings.HasSuffix(att[0].Path, filepath.Join("internal", "acp", "acp.go")) { t.Errorf("attachments %+v", att) } if _, att := Expand("@acp.go", dir); len(att) != 0 { t.Errorf("acp.go does not exist at the root, yet %+v", att) } }