Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
15 changes: 15 additions & 0 deletions internal/langserver/handlers/code_action.go
Original file line number Diff line number Diff line change
Expand Up @@ -74,6 +74,21 @@ func (svc *service) textDocumentCodeAction(ctx context.Context, params lsp.CodeA
},
},
})
case ilsp.ExtractPropertyToOutput:
edits, err := svc.ExtractPropToOutput(ctx, params)
if err != nil {
return ca, err
}

ca = append(ca, lsp.CodeAction{
Title: "Extract Property to Output",
Kind: action,
Edit: lsp.WorkspaceEdit{
Changes: map[lsp.DocumentURI][]lsp.TextEdit{
lsp.DocumentURI(dh.FullURI()): edits,
},
},
})
}
}

Expand Down
78 changes: 78 additions & 0 deletions internal/langserver/handlers/extract_prop_to_output.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,78 @@
// Copyright (c) HashiCorp, Inc.
// SPDX-License-Identifier: MPL-2.0

package handlers

import (
"context"
"fmt"
"strings"

"github.com/hashicorp/hcl/v2/hclwrite"
ilsp "github.com/hashicorp/terraform-ls/internal/lsp"
lsp "github.com/hashicorp/terraform-ls/internal/protocol"
)

func (svc *service) ExtractPropToOutput(ctx context.Context, params lsp.CodeActionParams) ([]lsp.TextEdit, error) {
var edits []lsp.TextEdit

dh := ilsp.HandleFromDocumentURI(params.TextDocument.URI)

doc, err := svc.stateStore.DocumentStore.GetDocument(dh)
if err != nil {
return edits, err
}

mod, err := svc.stateStore.Modules.ModuleByPath(dh.Dir.Path())
if err != nil {
return edits, err
}

file, ok := mod.ParsedModuleFiles.AsMap()[dh.Filename]
if !ok {
return edits, err
}

pos, err := ilsp.HCLPositionFromLspPosition(params.Range.Start, doc)
if err != nil {
return edits, err
}

blocks := file.BlocksAtPos(pos)
if len(blocks) > 1 {
return edits, fmt.Errorf("found more than one block at pos: %v", pos)
}
if len(blocks) == 0 {
return edits, fmt.Errorf("can not find block at position %v", pos)
}

attr := file.AttributeAtPos(pos)
if attr == nil {
return edits, fmt.Errorf("can not find attribute at position %v", pos)
}

tfAddr := append(blocks[0].Labels, attr.Name)

insertPos := lsp.Position{
Line: uint32(len(doc.Lines)),
Character: uint32(len(doc.Lines)),
}

edits = append(edits, lsp.TextEdit{
Range: lsp.Range{
Start: insertPos,
End: insertPos,
},
NewText: outputBlock(strings.Join(tfAddr, "_"), strings.Join(tfAddr, ".")),
})
return edits, nil
}

func outputBlock(name, tfAddr string) string {
f := hclwrite.NewFile()
b := hclwrite.NewBlock("output", []string{name})
b.Body().SetAttributeRaw("value", hclwrite.TokensForIdentifier(tfAddr))
f.Body().AppendNewline()
f.Body().AppendBlock(b)
return string(f.Bytes())
}
Loading