Allow marshal to bytes buffer

This commit is contained in:
Nobi 2022-03-26 03:20:24 +00:00
parent c5102bdba0
commit b210eb7dcd
No known key found for this signature in database
GPG Key ID: 6BEC04F94F08661F
2 changed files with 18 additions and 0 deletions

View File

@ -1704,6 +1704,15 @@ func (v *Viper) SafeWriteConfigAs(filename string) error {
return v.writeConfig(filename, false) 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 { func (v *Viper) writeConfig(filename string, force bool) error {
v.logger.Info("attempting to write configuration to file") v.logger.Info("attempting to write configuration to file")

View File

@ -1979,6 +1979,15 @@ func TestSafeWriteConfigAsWithExistingFile(t *testing.T) {
assert.True(t, ok, "Expected ConfigFileAlreadyExistsError") 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) { func TestWriteHiddenFile(t *testing.T) {
v := New() v := New()
fs := afero.NewMemMapFs() fs := afero.NewMemMapFs()