1// Copyright 2021 The Go Authors. All rights reserved.
2// Use of this source code is governed by a BSD-style
3// license that can be found in the LICENSE file.
4
5package misc
6
7import (
8	"strings"
9	"testing"
10
11	"golang.org/x/tools/internal/lsp/protocol"
12	. "golang.org/x/tools/internal/lsp/regtest"
13)
14
15const filesA = `
16-- go.mod --
17module mod.com
18
19go 1.12
20-- b.gotmpl --
21{{define "A"}}goo{{end}}
22-- a.tmpl --
23{{template "A"}}
24`
25
26func TestSuffixes(t *testing.T) {
27	WithOptions(
28		EditorConfig{
29			AllExperiments: true,
30		},
31	).Run(t, filesA, func(t *testing.T, env *Env) {
32		env.OpenFile("a.tmpl")
33		x := env.RegexpSearch("a.tmpl", `A`)
34		file, pos := env.GoToDefinition("a.tmpl", x)
35		refs := env.References(file, pos)
36		if len(refs) != 2 {
37			t.Fatalf("got %v reference(s), want 2", len(refs))
38		}
39		// make sure we got one from b.gotmpl
40		want := env.Sandbox.Workdir.URI("b.gotmpl")
41		if refs[0].URI != want && refs[1].URI != want {
42			t.Errorf("failed to find reference to %s", shorten(want))
43			for i, r := range refs {
44				t.Logf("%d: URI:%s %v", i, shorten(r.URI), r.Range)
45			}
46		}
47
48		content, npos := env.Hover(file, pos)
49		if pos != npos {
50			t.Errorf("pos? got %v, wanted %v", npos, pos)
51		}
52		if content.Value != "template A defined" {
53			t.Errorf("got %s, wanted 'template A defined", content.Value)
54		}
55	})
56}
57
58// shorten long URIs
59func shorten(fn protocol.DocumentURI) string {
60	if len(fn) <= 20 {
61		return string(fn)
62	}
63	pieces := strings.Split(string(fn), "/")
64	if len(pieces) < 2 {
65		return string(fn)
66	}
67	j := len(pieces)
68	return pieces[j-2] + "/" + pieces[j-1]
69}
70
71// Hover,  SemTok, Diagnose with errors
72// and better coverage
73