From e7fea39b01aea8d5671f6858f0532f56e8bff3a5 Mon Sep 17 00:00:00 2001 From: Unknwon Date: Tue, 28 Mar 2017 11:39:02 -0400 Subject: [PATCH] section: add ChildSections (#95) Also added (*File).ChildSecions. --- ini.go | 7 ++++++- ini_test.go | 25 +++++++++++++++++++++++++ section.go | 14 ++++++++++++++ 3 files changed, 45 insertions(+), 1 deletion(-) diff --git a/ini.go b/ini.go index 1c5a1f8..5211d5a 100644 --- a/ini.go +++ b/ini.go @@ -37,7 +37,7 @@ const ( // Maximum allowed depth when recursively substituing variable names. _DEPTH_VALUES = 99 - _VERSION = "1.26.0" + _VERSION = "1.27.0" ) // Version returns current package version literal. @@ -321,6 +321,11 @@ func (f *File) Sections() []*Section { return sections } +// ChildSections returns a list of child sections of given section name. +func (f *File) ChildSections(name string) []*Section { + return f.Section(name).ChildSections() +} + // SectionStrings returns list of section names. func (f *File) SectionStrings() []string { list := make([]string, len(f.sectionList)) diff --git a/ini_test.go b/ini_test.go index 91b3b9a..4ed6ab0 100644 --- a/ini_test.go +++ b/ini_test.go @@ -241,6 +241,31 @@ key5 }) } +func Test_File_ChildSections(t *testing.T) { + Convey("Find child sections by parent name", t, func() { + cfg, err := Load([]byte(` +[node] + +[node.biz1] + +[node.biz2] + +[node.biz3] + +[node.bizN] +`)) + So(err, ShouldBeNil) + So(cfg, ShouldNotBeNil) + + children := cfg.ChildSections("node") + names := make([]string, len(children)) + for i := range children { + names[i] = children[i].name + } + So(strings.Join(names, ","), ShouldEqual, "node.biz1,node.biz2,node.biz3,node.bizN") + }) +} + func Test_LooseLoad(t *testing.T) { Convey("Loose load from data sources", t, func() { Convey("Loose load mixed with nonexistent file", func() { diff --git a/section.go b/section.go index c9fa27e..94f7375 100644 --- a/section.go +++ b/section.go @@ -232,3 +232,17 @@ func (s *Section) DeleteKey(name string) { } } } + +// ChildSections returns a list of child sections of current section. +// For example, "[parent.child1]" and "[parent.child12]" are child sections +// of section "[parent]". +func (s *Section) ChildSections() []*Section { + prefix := s.name + "." + children := make([]*Section, 0, 3) + for _, name := range s.f.sectionList { + if strings.HasPrefix(name, prefix) { + children = append(children, s.f.sections[name]) + } + } + return children +}