mcfg: implement Sources

This commit is contained in:
Brian Picciano 2018-08-13 20:15:54 -04:00
parent be17ee942a
commit 8ff2abf02c
2 changed files with 37 additions and 0 deletions

View File

@ -51,3 +51,21 @@ func (cfg *Cfg) allParamValues() []ParamValue {
type Source interface { type Source interface {
Parse(*Cfg) ([]ParamValue, error) Parse(*Cfg) ([]ParamValue, error)
} }
// Sources combines together multiple Source instances into one. It will call
// Parse on each element individually. Later Sources take precedence over
// previous ones in the slice.
type Sources []Source
// Parse implements the method for the Source interface.
func (ss Sources) Parse(c *Cfg) ([]ParamValue, error) {
var pvs []ParamValue
for _, s := range ss {
innerPVs, err := s.Parse(c)
if err != nil {
return nil, err
}
pvs = append(pvs, innerPVs...)
}
return pvs, nil
}

View File

@ -3,6 +3,7 @@ package mcfg
import ( import (
"encoding/json" "encoding/json"
"fmt" "fmt"
. "testing"
"time" "time"
"github.com/mediocregopher/mediocre-go-lib/mrand" "github.com/mediocregopher/mediocre-go-lib/mrand"
@ -140,3 +141,21 @@ func (scs srcCommonState) assert(s Source) error {
massert.Subset(scs.expPVs, gotPVs), massert.Subset(scs.expPVs, gotPVs),
).Assert() ).Assert()
} }
func TestSources(t *T) {
cfg := New()
a := cfg.ParamRequiredInt("a", "")
b := cfg.ParamRequiredInt("b", "")
c := cfg.ParamRequiredInt("c", "")
err := cfg.populateParams(Sources{
SourceCLI{Args: []string{"--a=1", "--b=666"}},
SourceEnv{Env: []string{"B=2", "C=3"}},
})
massert.Fatal(t, massert.All(
massert.Nil(err),
massert.Equal(1, *a),
massert.Equal(2, *b),
massert.Equal(3, *c),
))
}