Skip to content

Commit

Permalink
feat: add function to write config to writer
Browse files Browse the repository at this point in the history
Signed-off-by: Mark Sagi-Kazar <mark.sagikazar@gmail.com>
  • Loading branch information
sagikazarmark committed Jul 23, 2024
1 parent 3268cbd commit ae564f0
Showing 1 changed file with 15 additions and 2 deletions.
17 changes: 15 additions & 2 deletions viper.go
Original file line number Diff line number Diff line change
Expand Up @@ -1591,6 +1591,19 @@ func (v *Viper) WriteConfigAs(filename string) error {
return v.writeConfig(filename, true)
}

// WriteConfigTo writes current configuration to an [io.Writer].
func WriteConfigTo(w io.Writer) error { return v.WriteConfigTo(w) }

func (v *Viper) WriteConfigTo(w io.Writer) error {
format := strings.ToLower(v.getConfigType())

if !slices.Contains(SupportedExts, format) {
return UnsupportedConfigError(format)
}

return v.marshalWriter(w, format)
}

// SafeWriteConfigAs writes current configuration to a given filename if it does not exist.
func SafeWriteConfigAs(filename string) error { return v.SafeWriteConfigAs(filename) }

Expand Down Expand Up @@ -1665,7 +1678,7 @@ func (v *Viper) unmarshalReader(in io.Reader, c map[string]any) error {
}

// Marshal a map into Writer.
func (v *Viper) marshalWriter(f afero.File, configType string) error {
func (v *Viper) marshalWriter(w io.Writer, configType string) error {
c := v.AllSettings()

encoder, err := v.encoderRegistry.Encoder(configType)
Expand All @@ -1678,7 +1691,7 @@ func (v *Viper) marshalWriter(f afero.File, configType string) error {
return ConfigMarshalError{err}
}

_, err = f.WriteString(string(b))
_, err = w.Write(b)
if err != nil {
return ConfigMarshalError{err}
}
Expand Down

0 comments on commit ae564f0

Please sign in to comment.