diff options
| author | Shulhan <ms@kilabit.info> | 2019-06-02 10:10:57 +0700 |
|---|---|---|
| committer | Shulhan <ms@kilabit.info> | 2019-06-02 10:10:57 +0700 |
| commit | 3fe8a7ec4f8bb9a0ddbd941eb5af90cfc905b888 (patch) | |
| tree | c4e057d56e0e0b8abb5dd277a5d7d5421a8b8ee0 | |
| parent | e320c42fc3e29470fb5faad46f76cbd81520e749 (diff) | |
| download | pakakeh.go-3fe8a7ec4f8bb9a0ddbd941eb5af90cfc905b888.tar.xz | |
ini: add parameter section and subsection name
If section name is not empty, only the keys will be listed in the map.
| -rw-r--r-- | lib/ini/ini.go | 32 | ||||
| -rw-r--r-- | lib/ini/ini_example_test.go | 15 |
2 files changed, 32 insertions, 15 deletions
diff --git a/lib/ini/ini.go b/lib/ini/ini.go index 253d1e22..0ff3c1fa 100644 --- a/lib/ini/ini.go +++ b/lib/ini/ini.go @@ -150,27 +150,23 @@ func (in *Ini) addSection(sec *Section) { // AsMap return the INI contents as mapping of // (section-name ":" subsection-name ":" variable-name) as key // and the variable's values as slice of string. -// For example, given the following INI file, // -// [section1] -// key = value +// If section name is not empty, only the keys will be listed in the map. // -// [section2 "sub"] -// key2 = value2 -// key2 = value3 -// -// it will be mapped as, -// -// map["section1::key"] = []string{"value"} -// map["section2:sub:key2"] = []string{"value2", "value3"} -// -func (in *Ini) AsMap() (out map[string][]string) { +func (in *Ini) AsMap(sectionName, subName string) (out map[string][]string) { sep := ":" out = make(map[string][]string) for x := 0; x < len(in.secs); x++ { sec := in.secs[x] + if len(sectionName) > 0 && sectionName != sec.nameLower { + continue + } + if len(sectionName) > 0 && subName != sec.sub { + continue + } + for y := 0; y < len(sec.vars); y++ { v := sec.vars[y] @@ -181,7 +177,15 @@ func (in *Ini) AsMap() (out map[string][]string) { continue } - key := sec.nameLower + sep + sec.sub + sep + v.keyLower + var key string + + if len(sectionName) > 0 && len(subName) > 0 { + key += v.key + } else { + key += sec.nameLower + sep + key += sec.sub + sep + key += v.key + } vals, ok := out[key] if !ok { diff --git a/lib/ini/ini_example_test.go b/lib/ini/ini_example_test.go index 0fd4c31e..cf1e1c9c 100644 --- a/lib/ini/ini_example_test.go +++ b/lib/ini/ini_example_test.go @@ -71,6 +71,7 @@ key2= [section "sub"] key=value1 +key2= [section] key=value2 @@ -86,15 +87,27 @@ key=value3 log.Fatal(err) } - iniMap := inis.AsMap() + iniMap := inis.AsMap("", "") + + for k, v := range iniMap { + fmt.Println(k, "=", v) + } + + iniMap = inis.AsMap("section", "sub") + fmt.Println() for k, v := range iniMap { fmt.Println(k, "=", v) } + // Unordered output: // section::key = [value1 value2] // section::key2 = [true false] // section:sub:key = [value1 value2 value3] + // section:sub:key2 = [true] + // + // key = [value1 value2 value3] + // key2 = [true] } func ExampleIni_Prune() { |
