From b210eb7dcdcb1b5c79d22ee07298b8ffb647c337 Mon Sep 17 00:00:00 2001 From: Nobi Date: Sat, 26 Mar 2022 03:20:24 +0000 Subject: [PATCH] Allow marshal to bytes buffer --- viper.go | 9 +++++++++ viper_test.go | 9 +++++++++ 2 files changed, 18 insertions(+) diff --git a/viper.go b/viper.go index 0158a7f..571ea52 100644 --- a/viper.go +++ b/viper.go @@ -1704,6 +1704,15 @@ func (v *Viper) SafeWriteConfigAs(filename string) error { return v.writeConfig(filename, false) } +// Marshal will return a Buffer containing the content that should have been written to the file +func (v *Viper) Marshal() (*bytes.Buffer, error) { + data, err := v.encoderRegistry.Encode(v.getConfigType(), v.AllSettings()) + if err != nil { + return nil, err + } + return bytes.NewBuffer(data), nil +} + func (v *Viper) writeConfig(filename string, force bool) error { v.logger.Info("attempting to write configuration to file") diff --git a/viper_test.go b/viper_test.go index e0bfc57..ffcd5fe 100644 --- a/viper_test.go +++ b/viper_test.go @@ -1979,6 +1979,15 @@ func TestSafeWriteConfigAsWithExistingFile(t *testing.T) { assert.True(t, ok, "Expected ConfigFileAlreadyExistsError") } +func TestMarshal(t *testing.T) { + v := New() + v.SetConfigType("yaml") + require.NoError(t, v.ReadConfig(bytes.NewBuffer(yamlExample))) + c, err := v.Marshal() + require.NoError(t, err) + assert.Equal(t, c.Bytes(), yamlWriteExpected) +} + func TestWriteHiddenFile(t *testing.T) { v := New() fs := afero.NewMemMapFs()