Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Support comment for RawValues #127

Merged
merged 2 commits into from
Jul 23, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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
Loading