Skip to content

Commit

Permalink
add a new line to the EOF in case of there is no at EOF
Browse files Browse the repository at this point in the history
  • Loading branch information
kurochan committed Dec 5, 2022
1 parent 4c7b830 commit cd484f0
Show file tree
Hide file tree
Showing 2 changed files with 11 additions and 24 deletions.
10 changes: 2 additions & 8 deletions pkg/yamlprocessor/yamlprocessor.go
Expand Up @@ -25,7 +25,6 @@ import (

type Processor struct {
file *ast.File
newLineAtEOF bool
}

func NewProcessor(data []byte) (*Processor, error) {
Expand All @@ -34,14 +33,8 @@ func NewProcessor(data []byte) (*Processor, error) {
return nil, err
}

nl := false
if len(data) > 0 && data[len(data)-1] == '\n' {
nl = true
}

return &Processor{
file: f,
newLineAtEOF: nl,
}, nil
}

Expand Down Expand Up @@ -112,7 +105,8 @@ func (p *Processor) ReplaceString(path, value string) error {

func (p *Processor) Bytes() []byte {
str := p.file.String()
if p.newLineAtEOF {

if len(str) > 0 && str[len(str)-1] != '\n' {
str += "\n"
}

Expand Down
25 changes: 9 additions & 16 deletions pkg/yamlprocessor/yamlprocessor_test.go
Expand Up @@ -190,15 +190,15 @@ func TestReplaceString(t *testing.T) {
yml: "foo: bar",
path: "$.foo",
value: "",
want: []byte("foo: "),
want: []byte("foo: \n"),
wantErr: false,
},
{
name: "valid value given",
yml: "foo: bar",
path: "$.foo",
value: "new-text",
want: []byte("foo: new-text"),
want: []byte("foo: new-text\n"),
wantErr: false,
},
{
Expand All @@ -208,7 +208,8 @@ foo: bar`,
path: "$.foo",
value: "new-text",
want: []byte(`# comments
foo: new-text`),
foo: new-text
`),
wantErr: false,
},
{
Expand All @@ -217,7 +218,7 @@ foo: new-text`),
`,
path: "$.foo",
value: "new-text",
want: []byte("foo: new-text # comments"),
want: []byte("foo: new-text # comments\n"),
wantErr: false,
},
{
Expand All @@ -229,15 +230,16 @@ foo: new-text`),
value: "new-text",
want: []byte(`foo:
- new-text
- baz`),
- baz
`),
wantErr: false,
},
{
name: "array in flow style",
yml: `foo: [bar, baz]`,
path: "$.foo[0]",
value: "new-text",
want: []byte(`foo: [new-text, baz]`),
want: []byte("foo: [new-text, baz]\n"),
wantErr: false,
},
{
Expand All @@ -250,16 +252,7 @@ foo:
value: "new-text",
want: []byte(`foo:
- new-text
- baz`),
wantErr: false,
},
{
name: "new line at end of yml given",
yml: `foo: bar
`,
path: "$.foo",
value: "new-text",
want: []byte(`foo: new-text
- baz
`),
wantErr: false,
},
Expand Down

0 comments on commit cd484f0

Please sign in to comment.