mcfg: add some helper methods to Cfg related to its Path

This commit is contained in:
Brian Picciano 2018-05-28 03:10:57 +00:00
parent 4e0d440d09
commit 7db5197a1e
3 changed files with 45 additions and 1 deletions

View File

@ -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

View File

@ -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

View File

@ -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())
}