mirror of
https://github.com/spf13/viper
synced 2024-11-16 18:07:02 +00:00
Merge e648540a6a
into ea35b92596
This commit is contained in:
commit
ce295d9315
3 changed files with 58 additions and 0 deletions
19
viper.go
19
viper.go
|
@ -1753,6 +1753,25 @@ func (v *Viper) SafeWriteConfigAs(filename string) error {
|
|||
return v.writeConfig(filename, false)
|
||||
}
|
||||
|
||||
// Encode will load the rawVal into config, then you can write to file
|
||||
func (v *Viper) Encode(rawVal interface{}, opts ...DecoderConfigOption) error {
|
||||
var cfg map[string]interface{}
|
||||
err := decode(rawVal, defaultDecoderConfig(&cfg, opts...))
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
return v.MergeConfigMap(cfg)
|
||||
}
|
||||
|
||||
// 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")
|
||||
|
||||
|
|
|
@ -2037,6 +2037,41 @@ func TestSafeWriteConfigAsWithExistingFile(t *testing.T) {
|
|||
assert.True(t, ok, "Expected ConfigFileAlreadyExistsError")
|
||||
}
|
||||
|
||||
func TestEncode(t *testing.T) {
|
||||
type config struct {
|
||||
Age int
|
||||
Beard bool
|
||||
}
|
||||
C := &config{35, true}
|
||||
v := New()
|
||||
require.NoError(t, v.Encode(C))
|
||||
expected := map[string]interface{}{"age": 35, "beard": true}
|
||||
assert.Equal(t, v.config, expected)
|
||||
}
|
||||
|
||||
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 TestEncodeAndMarshal(t *testing.T) {
|
||||
type config struct {
|
||||
Age int
|
||||
Beard bool
|
||||
}
|
||||
C := &config{35, true}
|
||||
v := New()
|
||||
require.NoError(t, v.Encode(C))
|
||||
v.SetConfigType("yaml")
|
||||
c, err := v.Marshal()
|
||||
require.NoError(t, err)
|
||||
assert.Equal(t, c.Bytes(), yamlEncodeWriteExpected)
|
||||
}
|
||||
|
||||
func TestWriteHiddenFile(t *testing.T) {
|
||||
v := New()
|
||||
fs := afero.NewMemMapFs()
|
||||
|
|
|
@ -51,3 +51,7 @@ emails:
|
|||
created: 01/02/03
|
||||
active: true
|
||||
`)
|
||||
|
||||
var yamlEncodeWriteExpected = []byte(`age: 35
|
||||
beard: true
|
||||
`)
|
||||
|
|
Loading…
Reference in a new issue