Skip to content

Commit 17d582c

Browse files
committed
Support count and count.index completion in blocks
This provides completion hints inside blocks for `count.index` references within resource, data and module blocks anywhere the `count` meta-argument is supported. It detects if count is used already and does not suggest duplicates.
1 parent 369f0e2 commit 17d582c

File tree

7 files changed

+508
-10
lines changed

7 files changed

+508
-10
lines changed

context/context.go

Lines changed: 28 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,28 @@
1+
package context
2+
3+
import (
4+
"context"
5+
6+
"github.com/hashicorp/hcl-lang/schema"
7+
)
8+
9+
type bodyExtCtxKey struct{}
10+
11+
type bodyActiveCountCtxKey struct{}
12+
13+
func WithExtensions(ctx context.Context, ext *schema.BodyExtensions) context.Context {
14+
return context.WithValue(ctx, bodyExtCtxKey{}, ext)
15+
}
16+
17+
func WithActiveCount(ctx context.Context) context.Context {
18+
return context.WithValue(ctx, bodyActiveCountCtxKey{}, true)
19+
}
20+
21+
func ExtensionsFromContext(ctx context.Context) (*schema.BodyExtensions, bool) {
22+
ext, ok := ctx.Value(bodyExtCtxKey{}).(*schema.BodyExtensions)
23+
return ext, ok
24+
}
25+
26+
func ActiveCountFromContext(ctx context.Context) bool {
27+
return ctx.Value(bodyActiveCountCtxKey{}) != nil
28+
}

decoder/body_candidates.go

Lines changed: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -17,6 +17,17 @@ func (d *PathDecoder) bodySchemaCandidates(body *hclsyntax.Body, schema *schema.
1717
candidates := lang.NewCandidates()
1818
count := 0
1919

20+
if schema.Extensions != nil {
21+
// check if this schema supports Count attribute
22+
if schema.Extensions.Count {
23+
// check if Count is already used inside this body, so we don't
24+
// suggest a duplicate
25+
if _, ok := body.Attributes["count"]; !ok {
26+
candidates.List = append(candidates.List, countAttributeCandidate(editRng))
27+
}
28+
}
29+
}
30+
2031
if len(schema.Attributes) > 0 {
2132
attrNames := sortedAttributeNames(schema.Attributes)
2233
for _, name := range attrNames {
@@ -135,3 +146,17 @@ func isBlockDeclarable(body *hclsyntax.Body, blockType string, bSchema *schema.B
135146
}
136147
return true
137148
}
149+
150+
func countAttributeCandidate(editRng hcl.Range) lang.Candidate {
151+
return lang.Candidate{
152+
Label: "count",
153+
Detail: "optional, number",
154+
Description: lang.PlainText("The distinct index number (starting with 0) corresponding to the instance"),
155+
Kind: lang.AttributeCandidateKind,
156+
TextEdit: lang.TextEdit{
157+
NewText: "count",
158+
Snippet: "count = ${1:1}",
159+
Range: editRng,
160+
},
161+
}
162+
}

0 commit comments

Comments
 (0)