Codebase list golang-github-spf13-viper / 04d3a0c
feat(encoding): integrate dotenv codec into Viper Signed-off-by: Mark Sagi-Kazar <mark.sagikazar@gmail.com> Mark Sagi-Kazar authored 2 years ago Márk Sági-Kazár committed 2 years ago
1 changed file(s) with 13 addition(s) and 24 deletion(s). Raw diff Collapse all Expand all
3838 "github.com/spf13/afero"
3939 "github.com/spf13/cast"
4040 "github.com/spf13/pflag"
41 "github.com/subosito/gotenv"
4241
4342 "github.com/spf13/viper/internal/encoding"
43 "github.com/spf13/viper/internal/encoding/dotenv"
4444 "github.com/spf13/viper/internal/encoding/hcl"
4545 "github.com/spf13/viper/internal/encoding/ini"
4646 "github.com/spf13/viper/internal/encoding/javaproperties"
366366 decoderRegistry.RegisterDecoder("prop", codec)
367367 }
368368
369 {
370 codec := &dotenv.Codec{}
371
372 encoderRegistry.RegisterEncoder("dotenv", codec)
373 decoderRegistry.RegisterDecoder("dotenv", codec)
374
375 encoderRegistry.RegisterEncoder("env", codec)
376 decoderRegistry.RegisterDecoder("env", codec)
377 }
378
369379 v.encoderRegistry = encoderRegistry
370380 v.decoderRegistry = decoderRegistry
371381 }
16661676 buf.ReadFrom(in)
16671677
16681678 switch format := strings.ToLower(v.getConfigType()); format {
1669 case "yaml", "yml", "json", "toml", "hcl", "tfvars", "ini", "properties", "props", "prop":
1679 case "yaml", "yml", "json", "toml", "hcl", "tfvars", "ini", "properties", "props", "prop", "dotenv", "env":
16701680 err := v.decoderRegistry.Decode(format, buf.Bytes(), c)
16711681 if err != nil {
16721682 return ConfigParseError{err}
1673 }
1674
1675 case "dotenv", "env":
1676 env, err := gotenv.StrictParse(buf)
1677 if err != nil {
1678 return ConfigParseError{err}
1679 }
1680 for k, v := range env {
1681 c[k] = v
16821683 }
16831684 }
16841685
16901691 func (v *Viper) marshalWriter(f afero.File, configType string) error {
16911692 c := v.AllSettings()
16921693 switch configType {
1693 case "yaml", "yml", "json", "toml", "hcl", "tfvars", "ini", "prop", "props", "properties":
1694 case "yaml", "yml", "json", "toml", "hcl", "tfvars", "ini", "prop", "props", "properties", "dotenv", "env":
16941695 b, err := v.encoderRegistry.Encode(configType, c)
16951696 if err != nil {
16961697 return ConfigMarshalError{err}
16981699
16991700 _, err = f.WriteString(string(b))
17001701 if err != nil {
1701 return ConfigMarshalError{err}
1702 }
1703
1704 case "dotenv", "env":
1705 lines := []string{}
1706 for _, key := range v.AllKeys() {
1707 envName := strings.ToUpper(strings.Replace(key, ".", "_", -1))
1708 val := v.Get(key)
1709 lines = append(lines, fmt.Sprintf("%v=%v", envName, val))
1710 }
1711 s := strings.Join(lines, "\n")
1712 if _, err := f.WriteString(s); err != nil {
17131702 return ConfigMarshalError{err}
17141703 }
17151704 }