Skip to content

Commit

Permalink
Support comment for RawValues (#127)
Browse files Browse the repository at this point in the history
* adding comment support for rawValues handler

Signed-off-by: GitHub <[email protected]>

* fix vendor

Signed-off-by: GitHub <[email protected]>

---------

Signed-off-by: GitHub <[email protected]>
  • Loading branch information
piggybankwang authored Jul 23, 2024
1 parent fd745ac commit ec532a0
Show file tree
Hide file tree
Showing 3 changed files with 29 additions and 2 deletions.
20 changes: 20 additions & 0 deletions hcledit_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -176,6 +176,26 @@ object1 = {
attribute1 = "str1"
}
}
`,
},

"Raw with Comment": {
input: `
`,
query: "object1",
opts: []hcledit.Option{hcledit.WithComment("# test comment for raw")},
value: hcledit.RawVal(`{
object2 = {
attribute1 = "str1"
}
}`),
want: `
# test comment for raw
object1 = {
object2 = {
attribute1 = "str1"
}
}
`,
},
}
Expand Down
2 changes: 1 addition & 1 deletion internal/handler/handler.go
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,7 @@ func New(input interface{}, comment, afterKey string, beforeNewline bool) (Handl
case *BlockVal:
return newBlockHandler(v.Labels, comment)
case *RawVal:
return newRawHandler(v.RawString)
return newRawHandler(v.RawString, comment, beforeNewline)
}

ctyType, err := gocty.ImpliedType(input)
Expand Down
9 changes: 8 additions & 1 deletion internal/handler/raw.go
Original file line number Diff line number Diff line change
Expand Up @@ -13,9 +13,10 @@ type RawVal struct {

type rawHandler struct {
rawTokens hclwrite.Tokens
beforeTokens hclwrite.Tokens
}

func newRawHandler(rawString string) (Handler, error) {
func newRawHandler(rawString, comment string, beforeNewline bool) (Handler, error) {
return &rawHandler{
// NOTE(tcnksm):
rawTokens: hclwrite.Tokens{
Expand All @@ -24,11 +25,17 @@ func newRawHandler(rawString string) (Handler, error) {
Bytes: []byte(rawString),
},
},
beforeTokens: beforeTokens(comment, beforeNewline),
}, nil
}

func (h *rawHandler) HandleBody(body *hclwrite.Body, name string, _ []string) error {
body.SetAttributeRaw(name, h.rawTokens)
if len(h.beforeTokens) > 0 {
tokens := body.GetAttribute(name).BuildTokens(h.beforeTokens)
body.RemoveAttribute(name)
body.AppendUnstructuredTokens(tokens)
}
return nil
}

Expand Down

0 comments on commit ec532a0

Please sign in to comment.