Skip to content

Commit

Permalink
[feat]: BlockVal should reflects WithNewLine option
Browse files Browse the repository at this point in the history
  • Loading branch information
ryotafuwa-dev committed Jul 22, 2024
1 parent 2234f28 commit 4c8f4fc
Show file tree
Hide file tree
Showing 3 changed files with 25 additions and 7 deletions.
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, in order to archive 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

0 comments on commit 4c8f4fc

Please sign in to comment.