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

[feat]: BlockVal should reflects WithNewLine option #130

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
13 changes: 13 additions & 0 deletions hcledit_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -155,6 +155,19 @@ prev {}`,
want: `
prev {}
// test comment
block "label1" "label2" {
}
`,
},

"Block with new line": {
input: `
`,
query: "block",
opts: []hcledit.Option{hcledit.WithNewLine()},
value: hcledit.BlockVal("label1", "label2"),
want: `

block "label1" "label2" {
}
`,
Expand Down
17 changes: 11 additions & 6 deletions internal/handler/block.go
Original file line number Diff line number Diff line change
Expand Up @@ -14,27 +14,32 @@ type BlockVal struct {
}

type blockHandler struct {
labels []string
comment string
labels []string
comment string
beforeNewLine bool
}

func newBlockHandler(labels []string, comment string) (Handler, error) {
func newBlockHandler(labels []string, comment string, beforeNewLine bool) (Handler, error) {
return &blockHandler{
labels: labels,
comment: comment,
labels: labels,
comment: comment,
beforeNewLine: beforeNewLine,
}, nil
}

func (h *blockHandler) HandleBody(body *hclwrite.Body, name string, _ []string) error {
if h.comment != "" {
// Note: intuitively, adding a new line should be determined by `h.beforeNewLine`.
// However, for the backward compatibility, we add a new line whenever comment is set to a non empty string.
body.AppendUnstructuredTokens(
beforeTokens(
fmt.Sprintf("// %s", strings.TrimSpace(strings.TrimPrefix(h.comment, "//"))),
true,
),
)
} else {
body.AppendUnstructuredTokens(beforeTokens(h.comment, h.beforeNewLine))
}

body.AppendNewBlock(name, h.labels)
return nil
}
Expand Down
2 changes: 1 addition & 1 deletion internal/handler/handler.go
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,7 @@ type Handler interface {
func New(input interface{}, comment, afterKey string, beforeNewline bool) (Handler, error) {
switch v := input.(type) {
case *BlockVal:
return newBlockHandler(v.Labels, comment)
return newBlockHandler(v.Labels, comment, beforeNewline)
case *RawVal:
return newRawHandler(v.RawString)
}
Expand Down
Loading