-
Notifications
You must be signed in to change notification settings - Fork 7
/
snippets.go
112 lines (101 loc) · 2.06 KB
/
snippets.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
package snippets
import (
"fmt"
"log"
"strings"
lsp "github.com/Azure/azapi-lsp/internal/protocol"
"github.com/hashicorp/hcl/v2/hclsyntax"
)
type Snippet struct {
AzureResourceType string
Fields []Field
}
type Field struct {
Name string
Value string
}
func (field Field) Order() int {
switch field.Name {
case "type":
return -1
case "parent_id":
return 0
case "name":
return 1
case "resource_id":
return 2
case "location":
return 3
case "identity":
return 4
case "body":
return 5
case "tags":
return 6
case "schema_validation_enabled":
return 7
case "response_export_values":
return 8
default:
return 9
}
}
func CodeSampleCandidates(block *hclsyntax.Block, editRange lsp.Range) []lsp.CompletionItem {
if block == nil || block.Type == "data" {
return nil
}
if len(block.Labels) != 2 || block.Labels[0] != "azapi_resource" {
return nil
}
typeValue := ""
for _, attr := range block.Body.Attributes {
if attr.Name == "type" {
v, diags := attr.Expr.Value(nil)
if diags.HasErrors() {
log.Printf("[ERROR] %s", diags)
return nil
}
typeValue = v.AsString()
break
}
}
azureResourceType := parseResourceType(typeValue)
if snippet, ok := snippetMap[strings.ToLower(azureResourceType)]; ok {
newText := ""
for _, field := range snippet.Fields {
if _, ok := block.Body.Attributes[field.Name]; ok {
continue
}
newText += field.Value + "\n"
}
if newText == "" {
return nil
}
return []lsp.CompletionItem{
{
Label: "code sample",
Kind: lsp.SnippetCompletion,
Detail: "Code Sample",
Documentation: lsp.MarkupContent{
Kind: "markdown",
Value: fmt.Sprintf("```\n%s\n```\n", newText),
},
SortText: "0",
InsertTextFormat: lsp.SnippetTextFormat,
InsertTextMode: lsp.AdjustIndentation,
TextEdit: &lsp.TextEdit{
Range: editRange,
NewText: newText,
},
},
}
}
return nil
}
func parseResourceType(typeValue string) string {
parts := strings.Split(typeValue, "@")
if len(parts) == 2 {
return parts[0]
}
return ""
}