forked from hashicorp/terraform-ls
-
Notifications
You must be signed in to change notification settings - Fork 2
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
(hashicorpGH-327) Format on save code action (hashicorp#625)
This enables in the language server to perform one or more code actions on a range of text or a full document. This adds a code action to format a file based on the `editor.codeActionsOnSave` setting or when a request has `source.formatAll` or `source.formatAll.terraform-ls`. This can either be a global setting or one specific to the terraform language.
- Loading branch information
Showing
8 changed files
with
317 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,75 @@ | ||
package handlers | ||
|
||
import ( | ||
"context" | ||
"fmt" | ||
|
||
lsctx "github.com/hashicorp/terraform-ls/internal/context" | ||
"github.com/hashicorp/terraform-ls/internal/langserver/errors" | ||
ilsp "github.com/hashicorp/terraform-ls/internal/lsp" | ||
lsp "github.com/hashicorp/terraform-ls/internal/protocol" | ||
"github.com/hashicorp/terraform-ls/internal/terraform/module" | ||
) | ||
|
||
func (h *logHandler) TextDocumentCodeAction(ctx context.Context, params lsp.CodeActionParams) []lsp.CodeAction { | ||
ca, err := h.textDocumentCodeAction(ctx, params) | ||
if err != nil { | ||
h.logger.Printf("code action failed: %s", err) | ||
} | ||
|
||
return ca | ||
} | ||
|
||
func (h *logHandler) textDocumentCodeAction(ctx context.Context, params lsp.CodeActionParams) ([]lsp.CodeAction, error) { | ||
var ca []lsp.CodeAction | ||
|
||
wantedCodeActions := ilsp.SupportedCodeActions.Only(params.Context.Only) | ||
if len(wantedCodeActions) == 0 { | ||
return nil, fmt.Errorf("could not find a supported code action to execute for %s, wanted %v", | ||
params.TextDocument.URI, params.Context.Only) | ||
} | ||
|
||
fh := ilsp.FileHandlerFromDocumentURI(params.TextDocument.URI) | ||
|
||
fs, err := lsctx.DocumentStorage(ctx) | ||
if err != nil { | ||
return ca, err | ||
} | ||
file, err := fs.GetDocument(fh) | ||
if err != nil { | ||
return ca, err | ||
} | ||
original, err := file.Text() | ||
if err != nil { | ||
return ca, err | ||
} | ||
|
||
for action := range wantedCodeActions { | ||
switch action { | ||
case lsp.Source, lsp.SourceFixAll, ilsp.SourceFormatAll, ilsp.SourceFormatAllTerraformLs: | ||
tfExec, err := module.TerraformExecutorForModule(ctx, fh.Dir()) | ||
if err != nil { | ||
return ca, errors.EnrichTfExecError(err) | ||
} | ||
|
||
h.logger.Printf("formatting document via %q", tfExec.GetExecPath()) | ||
|
||
edits, err := formatDocument(ctx, tfExec, original, file) | ||
if err != nil { | ||
return ca, err | ||
} | ||
|
||
ca = append(ca, lsp.CodeAction{ | ||
Title: "Format Document", | ||
Kind: lsp.SourceFixAll, | ||
Edit: lsp.WorkspaceEdit{ | ||
Changes: map[string][]lsp.TextEdit{ | ||
string(fh.URI()): edits, | ||
}, | ||
}, | ||
}) | ||
} | ||
} | ||
|
||
return ca, nil | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,147 @@ | ||
package handlers | ||
|
||
import ( | ||
"fmt" | ||
"testing" | ||
|
||
"github.com/hashicorp/go-version" | ||
"github.com/hashicorp/terraform-ls/internal/langserver" | ||
"github.com/hashicorp/terraform-ls/internal/langserver/session" | ||
"github.com/hashicorp/terraform-ls/internal/terraform/exec" | ||
"github.com/stretchr/testify/mock" | ||
) | ||
|
||
func TestLangServer_codeActionWithoutInitialization(t *testing.T) { | ||
ls := langserver.NewLangServerMock(t, NewMockSession(nil)) | ||
stop := ls.Start(t) | ||
defer stop() | ||
|
||
ls.CallAndExpectError(t, &langserver.CallRequest{ | ||
Method: "textDocument/codeAction", | ||
ReqParams: fmt.Sprintf(`{ | ||
"textDocument": { | ||
"version": 0, | ||
"languageId": "terraform", | ||
"text": "provider \"github\" {}", | ||
"uri": "%s/main.tf" | ||
} | ||
}`, TempDir(t).URI())}, session.SessionNotInitialized.Err()) | ||
} | ||
|
||
func TestLangServer_codeAction_basic(t *testing.T) { | ||
tmpDir := TempDir(t) | ||
|
||
ls := langserver.NewLangServerMock(t, NewMockSession(&MockSessionInput{ | ||
TerraformCalls: &exec.TerraformMockCalls{ | ||
PerWorkDir: map[string][]*mock.Call{ | ||
tmpDir.Dir(): { | ||
{ | ||
Method: "Version", | ||
Repeatability: 1, | ||
Arguments: []interface{}{ | ||
mock.AnythingOfType(""), | ||
}, | ||
ReturnArguments: []interface{}{ | ||
version.Must(version.NewVersion("0.12.0")), | ||
nil, | ||
nil, | ||
}, | ||
}, | ||
{ | ||
Method: "GetExecPath", | ||
Repeatability: 1, | ||
ReturnArguments: []interface{}{ | ||
"", | ||
}, | ||
}, | ||
{ | ||
Method: "Format", | ||
Repeatability: 1, | ||
Arguments: []interface{}{ | ||
mock.AnythingOfType(""), | ||
[]byte("provider \"test\" {\n\n }\n"), | ||
}, | ||
ReturnArguments: []interface{}{ | ||
[]byte("provider \"test\" {\n\n}\n"), | ||
nil, | ||
}, | ||
}}, | ||
}, | ||
}, | ||
})) | ||
stop := ls.Start(t) | ||
defer stop() | ||
|
||
ls.Call(t, &langserver.CallRequest{ | ||
Method: "initialize", | ||
ReqParams: fmt.Sprintf(`{ | ||
"capabilities": {}, | ||
"rootUri": %q, | ||
"processId": 12345 | ||
}`, tmpDir.URI())}) | ||
ls.Notify(t, &langserver.CallRequest{ | ||
Method: "initialized", | ||
ReqParams: "{}", | ||
}) | ||
ls.Call(t, &langserver.CallRequest{ | ||
Method: "textDocument/didOpen", | ||
ReqParams: fmt.Sprintf(`{ | ||
"textDocument": { | ||
"version": 0, | ||
"languageId": "terraform", | ||
"text": "provider \"test\" {\n\n }\n", | ||
"uri": "%s/main.tf" | ||
} | ||
}`, tmpDir.URI())}) | ||
ls.CallAndExpectResponse(t, &langserver.CallRequest{ | ||
Method: "textDocument/codeAction", | ||
ReqParams: fmt.Sprintf(`{ | ||
"textDocument": { "uri": "%s/main.tf" }, | ||
"range": { | ||
"start": { "line": 0, "character": 0 }, | ||
"end": { "line": 1, "character": 0 } | ||
}, | ||
"context": { "diagnostics": [], "only": ["source.fixAll"] } | ||
}`, tmpDir.URI())}, fmt.Sprintf(`{ | ||
"jsonrpc": "2.0", | ||
"id": 3, | ||
"result": [ | ||
{ | ||
"title": "Format Document", | ||
"kind": "source.fixAll", | ||
"edit":{ | ||
"changes":{ | ||
"%s/main.tf": [ | ||
{ | ||
"range": { | ||
"start": { | ||
"line": 0, | ||
"character": 0 | ||
}, | ||
"end": { | ||
"line": 1, | ||
"character": 0 | ||
} | ||
}, | ||
"newText": "provider \"test\" {\n" | ||
}, | ||
{ | ||
"range": { | ||
"start": { | ||
"line": 2, | ||
"character": 0 | ||
}, | ||
"end": { | ||
"line": 3, | ||
"character": 0 | ||
} | ||
}, | ||
"newText": "}\n" | ||
} | ||
] | ||
} | ||
} | ||
} | ||
] | ||
}`, tmpDir.URI())) | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,52 @@ | ||
package lsp | ||
|
||
import ( | ||
"sort" | ||
|
||
lsp "github.com/hashicorp/terraform-ls/internal/protocol" | ||
) | ||
|
||
const ( | ||
SourceFormatAll = "source.formatAll" | ||
SourceFormatAllTerraformLs = "source.formatAll.terraform-ls" | ||
) | ||
|
||
type CodeActions map[lsp.CodeActionKind]bool | ||
|
||
var ( | ||
SupportedCodeActions = CodeActions{ | ||
lsp.Source: true, | ||
lsp.SourceFixAll: true, | ||
SourceFormatAll: true, | ||
SourceFormatAllTerraformLs: true, | ||
} | ||
) | ||
|
||
func (c CodeActions) AsSlice() []lsp.CodeActionKind { | ||
s := make([]lsp.CodeActionKind, 0) | ||
for v := range c { | ||
s = append(s, v) | ||
} | ||
|
||
sort.SliceStable(s, func(i, j int) bool { | ||
return string(s[i]) < string(s[j]) | ||
}) | ||
return s | ||
} | ||
|
||
func (ca CodeActions) Only(only []lsp.CodeActionKind) CodeActions { | ||
// if only is empty, assume that the client wants all code actions | ||
// else build mapping of requested and determine if supported | ||
if len(only) == 0 { | ||
return ca | ||
} | ||
|
||
wanted := make(CodeActions, 0) | ||
for _, kind := range only { | ||
if v, ok := ca[kind]; ok { | ||
wanted[kind] = v | ||
} | ||
} | ||
|
||
return wanted | ||
} |