-
Notifications
You must be signed in to change notification settings - Fork 137
/
Copy pathinitialize.go
285 lines (245 loc) · 9.19 KB
/
initialize.go
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
package handlers
import (
"context"
"fmt"
"path/filepath"
"strings"
"github.com/creachadair/jrpc2"
lsctx "github.com/hashicorp/terraform-ls/internal/context"
"github.com/hashicorp/terraform-ls/internal/document"
ilsp "github.com/hashicorp/terraform-ls/internal/lsp"
lsp "github.com/hashicorp/terraform-ls/internal/protocol"
"github.com/hashicorp/terraform-ls/internal/settings"
"github.com/hashicorp/terraform-ls/internal/uri"
"github.com/mitchellh/go-homedir"
)
func (svc *service) Initialize(ctx context.Context, params lsp.InitializeParams) (lsp.InitializeResult, error) {
serverCaps := lsp.InitializeResult{
Capabilities: lsp.ServerCapabilities{
TextDocumentSync: lsp.TextDocumentSyncOptions{
OpenClose: true,
Change: lsp.Incremental,
},
CompletionProvider: lsp.CompletionOptions{
ResolveProvider: false,
TriggerCharacters: []string{".", "["},
},
CodeActionProvider: lsp.CodeActionOptions{
CodeActionKinds: ilsp.SupportedCodeActions.AsSlice(),
ResolveProvider: false,
},
DeclarationProvider: lsp.DeclarationOptions{},
DefinitionProvider: true,
CodeLensProvider: lsp.CodeLensOptions{},
ReferencesProvider: true,
HoverProvider: true,
DocumentFormattingProvider: true,
DocumentSymbolProvider: true,
WorkspaceSymbolProvider: true,
Workspace: lsp.Workspace5Gn{
WorkspaceFolders: lsp.WorkspaceFolders4Gn{
Supported: true,
ChangeNotifications: "workspace/didChangeWorkspaceFolders",
},
},
},
}
serverCaps.ServerInfo.Name = "terraform-ls"
version, ok := lsctx.LanguageServerVersion(ctx)
if ok {
serverCaps.ServerInfo.Version = version
}
clientCaps := params.Capabilities
properties := map[string]interface{}{
"experimentalCapabilities.referenceCountCodeLens": false,
"options.rootModulePaths": false,
"options.excludeModulePaths": false,
"options.commandPrefix": false,
"options.ignoreDirectoryNames": false,
"options.experimentalFeatures.validateOnSave": false,
"options.terraformExecPath": false,
"options.terraformExecTimeout": "",
"options.terraformLogFilePath": false,
"root_uri": "dir",
"lsVersion": serverCaps.ServerInfo.Version,
}
expClientCaps := lsp.ExperimentalClientCapabilities(clientCaps.Experimental)
svc.server = jrpc2.ServerFromContext(ctx)
if tv, ok := expClientCaps.TelemetryVersion(); ok {
svc.logger.Printf("enabling telemetry (version: %d)", tv)
err := svc.setupTelemetry(tv, svc.server)
if err != nil {
svc.logger.Printf("failed to setup telemetry: %s", err)
}
svc.logger.Printf("telemetry enabled (version: %d)", tv)
}
defer svc.telemetry.SendEvent(ctx, "initialize", properties)
if params.RootURI == "" {
properties["root_uri"] = "file"
return serverCaps, fmt.Errorf("Editing a single file is not yet supported." +
" Please open a directory.")
}
if !uri.IsURIValid(string(params.RootURI)) {
properties["root_uri"] = "invalid"
return serverCaps, fmt.Errorf("URI %q is not valid", params.RootURI)
}
root := document.DirHandleFromURI(string(params.RootURI))
err := lsctx.SetRootDirectory(ctx, root.Path())
if err != nil {
return serverCaps, err
}
if params.ClientInfo.Name != "" {
err = ilsp.SetClientName(ctx, params.ClientInfo.Name)
if err != nil {
return serverCaps, err
}
}
if _, ok = expClientCaps.ShowReferencesCommandId(); ok {
serverCaps.Capabilities.Experimental = lsp.ExperimentalServerCapabilities{
ReferenceCountCodeLens: true,
}
properties["experimentalCapabilities.referenceCountCodeLens"] = true
}
err = ilsp.SetClientCapabilities(ctx, &clientCaps)
if err != nil {
return serverCaps, err
}
out, err := settings.DecodeOptions(params.InitializationOptions)
if err != nil {
return serverCaps, err
}
properties["options.rootModulePaths"] = len(out.Options.ModulePaths) > 0
properties["options.excludeModulePaths"] = len(out.Options.ExcludeModulePaths) > 0
properties["options.commandPrefix"] = len(out.Options.CommandPrefix) > 0
properties["options.ignoreDirectoryNames"] = len(out.Options.IgnoreDirectoryNames) > 0
properties["options.experimentalFeatures.prefillRequiredFields"] = out.Options.ExperimentalFeatures.PrefillRequiredFields
properties["options.experimentalFeatures.validateOnSave"] = out.Options.ExperimentalFeatures.ValidateOnSave
properties["options.terraformExecPath"] = len(out.Options.TerraformExecPath) > 0
properties["options.terraformExecTimeout"] = out.Options.TerraformExecTimeout
properties["options.terraformLogFilePath"] = len(out.Options.TerraformLogFilePath) > 0
err = out.Options.Validate()
if err != nil {
return serverCaps, err
}
err = svc.configureSessionDependencies(ctx, out.Options)
if err != nil {
return serverCaps, err
}
stCaps := clientCaps.TextDocument.SemanticTokens
caps := ilsp.SemanticTokensClientCapabilities{
SemanticTokensClientCapabilities: clientCaps.TextDocument.SemanticTokens,
}
semanticTokensOpts := lsp.SemanticTokensOptions{
Legend: lsp.SemanticTokensLegend{
TokenTypes: ilsp.TokenTypesLegend(stCaps.TokenTypes).AsStrings(),
TokenModifiers: ilsp.TokenModifiersLegend(stCaps.TokenModifiers).AsStrings(),
},
Full: caps.FullRequest(),
}
serverCaps.Capabilities.SemanticTokensProvider = semanticTokensOpts
// set commandPrefix for session
lsctx.SetCommandPrefix(ctx, out.Options.CommandPrefix)
// apply prefix to executeCommand handler names
serverCaps.Capabilities.ExecuteCommandProvider = lsp.ExecuteCommandOptions{
Commands: cmdHandlers(svc).Names(out.Options.CommandPrefix),
WorkDoneProgressOptions: lsp.WorkDoneProgressOptions{
WorkDoneProgress: true,
},
}
// set experimental feature flags
lsctx.SetExperimentalFeatures(ctx, out.Options.ExperimentalFeatures)
if len(out.UnusedKeys) > 0 {
jrpc2.ServerFromContext(ctx).Notify(ctx, "window/showMessage", &lsp.ShowMessageParams{
Type: lsp.Warning,
Message: fmt.Sprintf("Unknown configuration options: %q", out.UnusedKeys),
})
}
cfgOpts := out.Options
if !clientCaps.Workspace.WorkspaceFolders && len(params.WorkspaceFolders) > 0 {
jrpc2.ServerFromContext(ctx).Notify(ctx, "window/showMessage", &lsp.ShowMessageParams{
Type: lsp.Warning,
Message: "Client sent workspace folders despite not declaring support. " +
"Please report this as a bug.",
})
}
var excludeModulePaths []string
for _, rawPath := range cfgOpts.ExcludeModulePaths {
modPath, err := resolvePath(root.Path(), rawPath)
if err != nil {
svc.logger.Printf("Ignoring excluded module path %s: %s", rawPath, err)
continue
}
excludeModulePaths = append(excludeModulePaths, modPath)
}
err = svc.stateStore.WalkerPaths.EnqueueDir(root)
if err != nil {
return serverCaps, err
}
if len(params.WorkspaceFolders) > 0 {
for _, folderPath := range params.WorkspaceFolders {
modPath := document.DirHandleFromURI(folderPath.URI)
err := svc.stateStore.WalkerPaths.EnqueueDir(modPath)
if err != nil {
jrpc2.ServerFromContext(ctx).Notify(ctx, "window/showMessage", &lsp.ShowMessageParams{
Type: lsp.Warning,
Message: fmt.Sprintf("Ignoring workspace folder %s: %s."+
" This is most likely bug, please report it.", folderPath.URI, err),
})
continue
}
}
}
svc.closedDirWalker.SetIgnoreDirectoryNames(cfgOpts.IgnoreDirectoryNames)
svc.closedDirWalker.SetExcludeModulePaths(excludeModulePaths)
svc.openDirWalker.SetIgnoreDirectoryNames(cfgOpts.IgnoreDirectoryNames)
svc.openDirWalker.SetExcludeModulePaths(excludeModulePaths)
// Walkers run asynchronously so we're intentionally *not*
// passing the request context here
walkerCtx := context.Background()
err = svc.closedDirWalker.StartWalking(walkerCtx)
if err != nil {
return serverCaps, fmt.Errorf("failed to start closedDirWalker: %w", err)
}
err = svc.openDirWalker.StartWalking(walkerCtx)
if err != nil {
return serverCaps, fmt.Errorf("failed to start openDirWalker: %w", err)
}
// Static user-provided paths take precedence over dynamic discovery
if len(cfgOpts.ModulePaths) > 0 {
svc.logger.Printf("Attempting to add %d static module paths", len(cfgOpts.ModulePaths))
for _, rawPath := range cfgOpts.ModulePaths {
modPath, err := resolvePath(root.Path(), rawPath)
if err != nil {
jrpc2.ServerFromContext(ctx).Notify(ctx, "window/showMessage", &lsp.ShowMessageParams{
Type: lsp.Warning,
Message: fmt.Sprintf("Ignoring module path %s: %s", rawPath, err),
})
continue
}
err = svc.watcher.AddModule(modPath)
if err != nil {
return serverCaps, err
}
}
return serverCaps, nil
}
return serverCaps, nil
}
func resolvePath(rootDir, rawPath string) (string, error) {
path, err := homedir.Expand(rawPath)
if err != nil {
return "", err
}
if !filepath.IsAbs(path) {
path = filepath.Join(rootDir, rawPath)
}
return cleanupPath(path)
}
func cleanupPath(path string) (string, error) {
absPath, err := filepath.Abs(path)
return toLowerVolumePath(absPath), err
}
func toLowerVolumePath(path string) string {
volume := filepath.VolumeName(path)
return strings.ToLower(volume) + path[len(volume):]
}