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 23, 2022
1 parent 6c3a253 commit 3406e0c
Show file tree
Hide file tree
Showing 7 changed files with 521 additions and 10 deletions.
30 changes: 30 additions & 0 deletions context/context.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
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 {
// _, ok := ctx.Value(bodyActiveCountCtxKey{}).(bool)
// return ok
return ctx.Value(bodyActiveCountCtxKey{}) != nil
}
36 changes: 36 additions & 0 deletions decoder/body_candidates.go
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,18 @@ 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 {
countPresent := isAttributePresent(body, "count")
// check if Count is already used inside this body, so we don't
// suggest a duplicate
if !countPresent {
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 +147,27 @@ func isBlockDeclarable(body *hclsyntax.Body, blockType string, bSchema *schema.B
}
return true
}

func isAttributePresent(body *hclsyntax.Body, attributeName string) bool {
attributePresent := false
for attrName := range body.Attributes {
if attrName == attributeName {
attributePresent = true
}
}
return attributePresent
}

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 3406e0c

Please sign in to comment.