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.
5 // Package gen is used to generate command bindings from the gopls command
15 "golang.org/x/tools/internal/imports"
16 "golang.org/x/tools/internal/lsp/command/commandmeta"
19 const src = `// Copyright 2021 The Go Authors. All rights reserved.
20 // Use of this source code is governed by a BSD-style
21 // license that can be found in the LICENSE file.
23 // Don't include this file during code generation, or it will break the build
24 // if existing interface methods have been modified.
30 // Code generated by generate.go. DO NOT EDIT.
33 {{range $k, $v := .Imports -}}
40 {{.MethodName}} Command = "{{.Name}}"
44 var Commands = []Command {
50 func Dispatch(ctx context.Context, params *protocol.ExecuteCommandParams, s Interface) (interface{}, error) {
51 switch params.Command {
55 {{- range $i, $v := .Args}}
56 var a{{$i}} {{typeString $v.Type}}
58 if err := UnmarshalArgs(params.Arguments{{range $i, $v := .Args}}, &a{{$i}}{{end}}); err != nil {
62 return {{if not .Result}}nil, {{end}}s.{{.MethodName}}(ctx{{range $i, $v := .Args}}, a{{$i}}{{end}})
65 return nil, fmt.Errorf("unsupported command %q", params.Command)
69 func New{{.MethodName}}Command(title string, {{range $i, $v := .Args}}{{if $i}}, {{end}}a{{$i}} {{typeString $v.Type}}{{end}}) (protocol.Command, error) {
70 args, err := MarshalArgs({{range $i, $v := .Args}}{{if $i}}, {{end}}a{{$i}}{{end}})
72 return protocol.Command{}, err
74 return protocol.Command{
84 Imports map[string]bool
85 Commands []*commandmeta.Command
88 func Generate() ([]byte, error) {
89 pkg, cmds, err := commandmeta.Load()
91 return nil, fmt.Errorf("loading command data: %v", err)
93 qf := func(p *types.Package) string {
99 tmpl, err := template.New("").Funcs(template.FuncMap{
100 "typeString": func(t types.Type) string {
101 return types.TypeString(t, qf)
109 Imports: map[string]bool{
112 "golang.org/x/tools/internal/lsp/protocol": true,
115 const thispkg = "golang.org/x/tools/internal/lsp/command"
116 for _, c := range d.Commands {
117 for _, arg := range c.Args {
118 pth := pkgPath(arg.Type)
119 if pth != "" && pth != thispkg {
120 d.Imports[pth] = true
123 pth := pkgPath(c.Result)
124 if pth != "" && pth != thispkg {
125 d.Imports[pth] = true
130 if err := tmpl.Execute(&buf, d); err != nil {
131 return nil, fmt.Errorf("executing: %v", err)
134 opts := &imports.Options{
139 content, err := imports.Process("", buf.Bytes(), opts)
141 return nil, fmt.Errorf("goimports: %v", err)
146 func pkgPath(t types.Type) string {
147 if n, ok := t.(*types.Named); ok {
148 if pkg := n.Obj().Pkg(); pkg != nil {