Skip to content

Commit

Permalink
Export the DecoderFromExtension Function
Browse files Browse the repository at this point in the history
This function is useful outside of the ez package, so we should
export it.
  • Loading branch information
sergiosalvatore committed Feb 13, 2023
1 parent d4368fc commit f869cc4
Showing 1 changed file with 20 additions and 15 deletions.
35 changes: 20 additions & 15 deletions ez/ez.go
Original file line number Diff line number Diff line change
Expand Up @@ -293,25 +293,30 @@ func TOMLConfigEnvFlag[T any, TP ConfigWithConfigPath[T]](ctx context.Context, c
return ConfigFileEnvFlag(ctx, cfg, func(string) dials.Decoder { return &toml.Decoder{} }, params)
}

// DecoderFromExtension is a DecoderFactory that returns an appropriate decoder
// based on the extension of the filename or nil if there is not an appropriate
// mapping.
func DecoderFromExtension(path string) dials.Decoder {
ext := filepath.Ext(path)
switch strings.ToLower(ext) {
case ".yaml", ".yml":
return &yaml.Decoder{}
case ".json":
return &json.Decoder{}
case ".toml":
return &toml.Decoder{}
case ".cue":
return &cue.Decoder{}
default:
return nil
}
}

// FileExtensionDecoderConfigEnvFlag takes advantage of the
// ConfigWithConfigPath cfg and thinly wraps ConfigFileEnvFlag and and thinly
// wraps ConfigFileEnvFlag choosing the dials.Decoder used when handling the
// file contents based on the file extension (from the limited set of JSON,
// Cue, YAML and TOML).
func FileExtensionDecoderConfigEnvFlag[T any, TP ConfigWithConfigPath[T]](ctx context.Context, cfg TP, params Params[T]) (*dials.Dials[T], error) {
return ConfigFileEnvFlag(ctx, cfg, func(fp string) dials.Decoder {
ext := filepath.Ext(fp)
switch strings.ToLower(ext) {
case ".yaml", ".yml":
return &yaml.Decoder{}
case ".json":
return &json.Decoder{}
case ".toml":
return &toml.Decoder{}
case ".cue":
return &cue.Decoder{}
default:
return nil
}
}, params)
return ConfigFileEnvFlag(ctx, cfg, DecoderFromExtension, params)
}

0 comments on commit f869cc4

Please sign in to comment.