diff --git a/mcfg/cli.go b/mcfg/cli.go index 658ed1d..c6a3047 100644 --- a/mcfg/cli.go +++ b/mcfg/cli.go @@ -124,7 +124,7 @@ func (cli SourceCLI) cliParamVals(cfg *Cfg) (map[string]ParamValue, error) { m := map[string]ParamValue{} for _, param := range cfg.Params { key := cliKeyPrefix - if len(cfg.Path) > 0 { + if !cfg.IsRoot() { key += strings.Join(cfg.Path, cliKeyJoin) + cliKeyJoin } key += param.Name diff --git a/mcfg/mcfg.go b/mcfg/mcfg.go index facca66..f64266d 100644 --- a/mcfg/mcfg.go +++ b/mcfg/mcfg.go @@ -6,6 +6,7 @@ import ( "context" "encoding/json" "fmt" + "strings" ) // TODO Sources: @@ -120,6 +121,27 @@ func New() *Cfg { } } +// IsRoot returns true if this is the root instance of a Cfg (i.e. the one +// returned by New) +func (c *Cfg) IsRoot() bool { + return len(c.Path) == 0 +} + +// Name returns the name given to this instance when it was created via Child. +// if this instance was created via New (i.e. it is the root instance) then +// empty string is returned. +func (c *Cfg) Name() string { + if c.IsRoot() { + return "" + } + return c.Path[len(c.Path)-1] +} + +// FullName returns a string representing the full path of the instance. +func (c *Cfg) FullName() string { + return "/" + strings.Join(c.Path, "/") +} + func (c *Cfg) populateParams(src Source) error { // we allow for nil Source here for tests // TODO make Source stub type which tests could use here instead diff --git a/mcfg/mcfg_test.go b/mcfg/mcfg_test.go index 179d495..2b49e85 100644 --- a/mcfg/mcfg_test.go +++ b/mcfg/mcfg_test.go @@ -120,3 +120,25 @@ func TestPopulateParams(t *T) { assert.Equal(t, 3, *c) } } + +func TestChild(t *T) { + cfg := New() + assert.True(t, cfg.IsRoot()) + assert.Equal(t, "", cfg.Name()) + assert.Equal(t, "/", cfg.FullName()) + + foo := cfg.Child("foo") + assert.False(t, foo.IsRoot()) + assert.Equal(t, "foo", foo.Name()) + assert.Equal(t, "/foo", foo.FullName()) + + bar := cfg.Child("bar") + assert.False(t, bar.IsRoot()) + assert.Equal(t, "bar", bar.Name()) + assert.Equal(t, "/bar", bar.FullName()) + + foo2 := foo.Child("foo2") + assert.False(t, foo2.IsRoot()) + assert.Equal(t, "foo2", foo2.Name()) + assert.Equal(t, "/foo/foo2", foo2.FullName()) +}