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

Props: Add encoding func for DOM's container #36

Merged
merged 1 commit into from
Jun 17, 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
18 changes: 17 additions & 1 deletion props/codec.go
Original file line number Diff line number Diff line change
Expand Up @@ -19,13 +19,29 @@ package props
import (
"fmt"
"github.com/magiconair/properties"
"github.com/rkosegi/yaml-toolkit/dom"
"github.com/rkosegi/yaml-toolkit/utils"
"io"
)

func encodeKv(k string, v interface{}, w io.Writer) error {
_, err := w.Write([]byte(fmt.Sprintf("%s=%v\n", k, v)))
return err
}

func EncoderFn(w io.Writer, x interface{}) error {
for k, v := range x.(map[string]interface{}) {
_, err := w.Write([]byte(fmt.Sprintf("%s=%v\n", k, v)))
err := encodeKv(k, v, w)
if err != nil {
return err
}
}
return nil
}

func DomEncoderFn(w io.Writer, x interface{}) error {
for k, v := range x.(dom.Container).Children() {
err := encodeKv(k, v.(dom.Leaf).Value(), w)
if err != nil {
return err
}
Expand Down
15 changes: 15 additions & 0 deletions props/codec_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@ package props

import (
"bytes"
"github.com/rkosegi/yaml-toolkit/dom"
"github.com/rkosegi/yaml-toolkit/utils"
"github.com/stretchr/testify/assert"
"strings"
Expand All @@ -38,6 +39,20 @@ func TestEncoderFn(t *testing.T) {
assert.Error(t, EncoderFn(utils.FailingWriter(), m))
}

func TestDomEncoderFn(t *testing.T) {
m := map[string]interface{}{
"a.b.c": 1,
"x.y.z": "Hi!",
}
var buff bytes.Buffer
c := dom.Builder().FromMap(m)
err := DomEncoderFn(&buff, c)
assert.NoError(t, err)
assert.Contains(t, buff.String(), "a.b.c=1\n")
assert.Contains(t, buff.String(), "x.y.z=Hi!\n")
assert.Error(t, DomEncoderFn(utils.FailingWriter(), c))
}

func TestDecoderFn(t *testing.T) {
m := make(map[string]interface{})
err := DecoderFn(strings.NewReader("a.b=1\nx.y=Hi!\n"), &m)
Expand Down
Loading