Skip to content

Commit

Permalink
sort
Browse files Browse the repository at this point in the history
  • Loading branch information
jpogran committed Oct 4, 2021
1 parent 7fc091d commit 4606715
Show file tree
Hide file tree
Showing 2 changed files with 25 additions and 2 deletions.
8 changes: 6 additions & 2 deletions decoder/label_candidates.go
Original file line number Diff line number Diff line change
Expand Up @@ -115,15 +115,19 @@ func generateRequiredFieldsSnippet(label string, bodySchema *schema.BodySchema,
snippetText += " {\n"
}

for attrName, attr := range bodySchema.Attributes {
attrNames := bodySchema.SortAttributes()
for _, attrName := range attrNames {
attr := bodySchema.Attributes[attrName]
if attr.IsRequired {
valueSnippet := snippetForExprContraint(uint(placeholder), attr.Expr)
snippetText += fmt.Sprintf("%s%s = %s\n", indent, attrName, valueSnippet)
placeholder++
}
}

for blockName, blockSchema := range bodySchema.Blocks {
blockNames := bodySchema.SortBlocks()
for _, blockName := range blockNames {
blockSchema := bodySchema.Blocks[blockName]
if blockSchema.MinItems > 0 {
snippetText += fmt.Sprintf("%s%s {\n", indent, blockName)
snippetText += generateRequiredFieldsSnippet("", blockSchema.Body, blockSchema.Labels, placeholder, indentCount+1)
Expand Down
19 changes: 19 additions & 0 deletions schema/body_schema.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ package schema

import (
"fmt"
"sort"

"github.com/hashicorp/go-multierror"
"github.com/hashicorp/hcl-lang/lang"
Expand Down Expand Up @@ -50,6 +51,24 @@ func NewBodySchema() *BodySchema {
}
}

func (as *BodySchema) SortAttributes() []string {
keys := make([]string, 0, len(as.Attributes))
for k := range as.Attributes {
keys = append(keys, k)
}
sort.Strings(keys)
return keys
}

func (as *BodySchema) SortBlocks() []string {
keys := make([]string, 0, len(as.Blocks))
for k := range as.Blocks {
keys = append(keys, k)
}
sort.Strings(keys)
return keys
}

func (bs *BodySchema) Validate() error {
if len(bs.Attributes) > 0 && bs.AnyAttribute != nil {
return fmt.Errorf("one of Attributes or AnyAttribute must be set, not both")
Expand Down

0 comments on commit 4606715

Please sign in to comment.