Skip to content

Commit

Permalink
refactor(configio): Extension -> Format
Browse files Browse the repository at this point in the history
  • Loading branch information
GregoryAlbouy committed Nov 6, 2022
1 parent 1d5d50e commit 5d5465f
Show file tree
Hide file tree
Showing 2 changed files with 27 additions and 18 deletions.
27 changes: 13 additions & 14 deletions configio/decoder.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@ package configio

import (
"bytes"
"errors"
"fmt"

"github.com/benchttp/sdk/benchttp"
)
Expand All @@ -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))
}
}
18 changes: 14 additions & 4 deletions configio/file.go
Original file line number Diff line number Diff line change
Expand Up @@ -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}
}
Expand Down

0 comments on commit 5d5465f

Please sign in to comment.