From f869cc44b34c8b24330b36aef1e4a8080c2f9385 Mon Sep 17 00:00:00 2001 From: Sergio Salvatore Date: Mon, 13 Feb 2023 17:21:28 -0500 Subject: [PATCH] Export the DecoderFromExtension Function This function is useful outside of the ez package, so we should export it. --- ez/ez.go | 35 ++++++++++++++++++++--------------- 1 file changed, 20 insertions(+), 15 deletions(-) diff --git a/ez/ez.go b/ez/ez.go index cf68bc5..8b3ff0b 100644 --- a/ez/ez.go +++ b/ez/ez.go @@ -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) }