Skip to content

Commit

Permalink
fix: fix DumpToFile() error on go1.15, add some tests
Browse files Browse the repository at this point in the history
  • Loading branch information
inhere committed Aug 9, 2022
1 parent adc55a9 commit 8021f6c
Show file tree
Hide file tree
Showing 3 changed files with 33 additions and 6 deletions.
18 changes: 18 additions & 0 deletions config_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -403,6 +403,24 @@ func TestJSONAllowComments(t *testing.T) {
JSONAllowComments = old
}

func TestSaveFileOnSet(t *testing.T) {
old := JSONMarshalIndent
JSONMarshalIndent = " "
defer func() {
JSONMarshalIndent = old
}()

is := assert.New(t)
c := New("test")
c.WithOptions(SaveFileOnSet("testdata/config.bak.json", JSON))

err := c.LoadStrings(JSON, jsonStr)
is.Nil(err)

is.NoError(c.Set("new-key", "new-value"))
is.Equal("new-value", c.Get("new-key"))
}

func TestMapStringStringParseEnv(t *testing.T) {
is := assert.New(t)
c := New("test")
Expand Down
14 changes: 11 additions & 3 deletions export.go
Original file line number Diff line number Diff line change
Expand Up @@ -155,7 +155,6 @@ func (c *Config) DumpToFile(fileName string, format string) (err error) {
return
}

// is empty
if len(c.data) == 0 {
return
}
Expand All @@ -167,6 +166,15 @@ func (c *Config) DumpToFile(fileName string, format string) (err error) {
}

// write content to out
//num, _ := fmt.Fprintln(out, string(encoded))
return os.WriteFile(fileName, encoded, os.ModePerm)
fsFlags := os.O_CREATE | os.O_WRONLY | os.O_TRUNC
f, err := os.OpenFile(fileName, fsFlags, os.ModePerm)
if err != nil {
return err
}

_, err = f.Write(encoded)
if err1 := f.Close(); err1 != nil && err == nil {
err = err1
}
return err
}
7 changes: 4 additions & 3 deletions options.go
Original file line number Diff line number Diff line change
@@ -1,8 +1,9 @@
package config

import (
"github.com/mitchellh/mapstructure"
"strings"

"github.com/mitchellh/mapstructure"
)

// there are some event names for config data changed.
Expand Down Expand Up @@ -91,8 +92,8 @@ func Delimiter(sep byte) func(*Options) {
}
}

// WithSetSaveFile set hook func
func WithSetSaveFile(fileName string, format string) func(options *Options) {
// SaveFileOnSet set hook func
func SaveFileOnSet(fileName string, format string) func(options *Options) {
return func(opts *Options) {
opts.HookFunc = func(event string, c *Config) {
if strings.HasPrefix(event, "set.") {
Expand Down

0 comments on commit 8021f6c

Please sign in to comment.