mcfg: implement Sources
This commit is contained in:
parent
be17ee942a
commit
8ff2abf02c
@ -51,3 +51,21 @@ func (cfg *Cfg) allParamValues() []ParamValue {
|
||||
type Source interface {
|
||||
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
|
||||
}
|
||||
|
@ -3,6 +3,7 @@ package mcfg
|
||||
import (
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
. "testing"
|
||||
"time"
|
||||
|
||||
"github.com/mediocregopher/mediocre-go-lib/mrand"
|
||||
@ -140,3 +141,21 @@ func (scs srcCommonState) assert(s Source) error {
|
||||
massert.Subset(scs.expPVs, gotPVs),
|
||||
).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),
|
||||
))
|
||||
}
|
||||
|
Loading…
Reference in New Issue
Block a user