From d6f1959da1bee7bc0f7911c198e6cffd4fb405a6 Mon Sep 17 00:00:00 2001 From: siddontang Date: Wed, 8 Oct 2014 16:02:00 +0800 Subject: [PATCH] config add dump support --- config/config.go | 19 +++++++++++++++++++ config/config_test.go | 14 +++++++++++++- 2 files changed, 32 insertions(+), 1 deletion(-) diff --git a/config/config.go b/config/config.go index 668b545..b90182e 100644 --- a/config/config.go +++ b/config/config.go @@ -1,7 +1,10 @@ package config import ( + "bytes" "github.com/BurntSushi/toml" + "github.com/siddontang/go/ioutil2" + "io" "io/ioutil" ) @@ -123,3 +126,19 @@ func (cfg *LevelDBConfig) Adjust() { cfg.MaxOpenFiles = 1024 } } + +func (cfg *Config) Dump(w io.Writer) error { + e := toml.NewEncoder(w) + e.Indent = "" + return e.Encode(cfg) +} + +func (cfg *Config) DumpFile(fileName string) error { + var b bytes.Buffer + + if err := cfg.Dump(&b); err != nil { + return err + } + + return ioutil2.WriteFileAtomic(fileName, b.Bytes(), 0644) +} diff --git a/config/config_test.go b/config/config_test.go index 47779aa..077451c 100644 --- a/config/config_test.go +++ b/config/config_test.go @@ -1,13 +1,25 @@ package config import ( + "os" + "reflect" "testing" ) func TestConfig(t *testing.T) { - _, err := NewConfigWithFile("./ledis.toml") + cfg, err := NewConfigWithFile("./config.toml") if err != nil { t.Fatal(err) } + defer os.Remove("./config.toml.bak") + if err := cfg.DumpFile("./config.toml.bak"); err != nil { + t.Fatal(err) + } + + if c, err := NewConfigWithFile("./config.toml.bak"); err != nil { + t.Fatal(err) + } else if !reflect.DeepEqual(cfg, c) { + t.Fatal("must equal") + } }