From 5d5465fd4acb5441c55c56de9cbab31258afb43a Mon Sep 17 00:00:00 2001 From: Gregory Albouy Date: Tue, 1 Nov 2022 11:43:11 +0100 Subject: [PATCH] refactor(configio): Extension -> Format --- configio/decoder.go | 27 +++++++++++++-------------- configio/file.go | 18 ++++++++++++++---- 2 files changed, 27 insertions(+), 18 deletions(-) diff --git a/configio/decoder.go b/configio/decoder.go index 0a93511..0014f70 100644 --- a/configio/decoder.go +++ b/configio/decoder.go @@ -2,7 +2,7 @@ package configio import ( "bytes" - "errors" + "fmt" "github.com/benchttp/sdk/benchttp" ) @@ -12,24 +12,23 @@ type Decoder interface { DecodeRunner(dst *benchttp.Runner) error } -type Extension string +type Format string const ( - ExtYML Extension = ".yml" - ExtYAML Extension = ".yaml" - ExtJSON Extension = ".json" + FormatJSON Format = "json" + FormatYAML Format = "yaml" ) -// DecoderOf returns the appropriate Decoder for the given extension, -// or a non-nil error if ext is not an expected extension. -func DecoderOf(ext Extension, in []byte) (Decoder, error) { +// DecoderOf returns the appropriate Decoder for the given Format. +// It panics if the format is not a Format declared in configio. +func DecoderOf(format Format, in []byte) Decoder { r := bytes.NewReader(in) - switch ext { - case ExtYML, ExtYAML: - return NewYAMLDecoder(r), nil - case ExtJSON: - return NewJSONDecoder(r), nil + switch format { + case FormatYAML: + return NewYAMLDecoder(r) + case FormatJSON: + return NewJSONDecoder(r) default: - return nil, errors.New("unsupported config format") + panic(fmt.Sprintf("configio.DecoderOf: unexpected format: %q", format)) } } diff --git a/configio/file.go b/configio/file.go index 6856ff7..f0aff7d 100644 --- a/configio/file.go +++ b/configio/file.go @@ -83,19 +83,29 @@ func (f *file) decode() (err error) { return errorutil.WithDetails(ErrFileRead, f.path, err) } - ext := Extension(filepath.Ext(f.path)) - dec, err := DecoderOf(ext, b) + ext, err := f.format() if err != nil { - return errorutil.WithDetails(ErrFileExt, ext, err) + return err } - if err = dec.Decode(&f.repr); err != nil { + if err := DecoderOf(ext, b).Decode(&f.repr); err != nil { return errorutil.WithDetails(ErrFileParse, f.path, err) } return nil } +func (f file) format() (Format, error) { + switch ext := filepath.Ext(f.path); ext { + case ".yml", ".yaml": + return FormatYAML, nil + case ".json": + return FormatJSON, nil + default: + return "", errorutil.WithDetails(ErrFileExt, ext, f.path) + } +} + func (f file) extend(nextPath string) file { return file{prev: &f, path: nextPath} }