Skip to content

Commit

Permalink
Support count and count.index completion in blocks
Browse files Browse the repository at this point in the history
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.
  • Loading branch information
jpogran committed Sep 27, 2022
1 parent 6c3a253 commit 9da56b1
Show file tree
Hide file tree
Showing 7 changed files with 508 additions and 10 deletions.
28 changes: 28 additions & 0 deletions context/context.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
package context

import (
"context"

"github.com/hashicorp/hcl-lang/schema"
)

type bodyExtCtxKey struct{}

type bodyActiveCountCtxKey struct{}

func WithExtensions(ctx context.Context, ext *schema.BodyExtensions) context.Context {
return context.WithValue(ctx, bodyExtCtxKey{}, ext)
}

func WithActiveCount(ctx context.Context) context.Context {
return context.WithValue(ctx, bodyActiveCountCtxKey{}, true)
}

func ExtensionsFromContext(ctx context.Context) (*schema.BodyExtensions, bool) {
ext, ok := ctx.Value(bodyExtCtxKey{}).(*schema.BodyExtensions)
return ext, ok
}

func ActiveCountFromContext(ctx context.Context) bool {
return ctx.Value(bodyActiveCountCtxKey{}) != nil
}
25 changes: 25 additions & 0 deletions decoder/body_candidates.go
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,17 @@ func (d *PathDecoder) bodySchemaCandidates(body *hclsyntax.Body, schema *schema.
candidates := lang.NewCandidates()
count := 0

if schema.Extensions != nil {
// check if this schema supports Count attribute
if schema.Extensions.Count {
// check if Count is already used inside this body, so we don't
// suggest a duplicate
if _, ok := body.Attributes["count"]; !ok {
candidates.List = append(candidates.List, countAttributeCandidate(editRng))
}
}
}

if len(schema.Attributes) > 0 {
attrNames := sortedAttributeNames(schema.Attributes)
for _, name := range attrNames {
Expand Down Expand Up @@ -135,3 +146,17 @@ func isBlockDeclarable(body *hclsyntax.Body, blockType string, bSchema *schema.B
}
return true
}

func countAttributeCandidate(editRng hcl.Range) lang.Candidate {
return lang.Candidate{
Label: "count",
Detail: "optional, number",
Description: lang.PlainText("The distinct index number (starting with 0) corresponding to the instance"),
Kind: lang.AttributeCandidateKind,
TextEdit: lang.TextEdit{
NewText: "count",
Snippet: "count = ${1:1}",
Range: editRng,
},
}
}
Loading

0 comments on commit 9da56b1

Please sign in to comment.