From 8ff2abf02ce28b19aa3b175781bd2fb7c6923e14 Mon Sep 17 00:00:00 2001 From: Brian Picciano Date: Mon, 13 Aug 2018 20:15:54 -0400 Subject: [PATCH] mcfg: implement Sources --- mcfg/source.go | 18 ++++++++++++++++++ mcfg/source_test.go | 19 +++++++++++++++++++ 2 files changed, 37 insertions(+) diff --git a/mcfg/source.go b/mcfg/source.go index 8f334e0..972e7a1 100644 --- a/mcfg/source.go +++ b/mcfg/source.go @@ -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 +} diff --git a/mcfg/source_test.go b/mcfg/source_test.go index 9aa9b79..c26e532 100644 --- a/mcfg/source_test.go +++ b/mcfg/source_test.go @@ -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), + )) +}