diff --git a/README.md b/README.md index d09a79c..d5cd4e7 100644 --- a/README.md +++ b/README.md @@ -28,7 +28,7 @@ if !ok { Iterate through values in a section: ```go -for key, value := range file.Section("mysection") { +for key, value := range file["mysection"] { fmt.Printf("%s => %s\n", key, value) } ``` @@ -36,12 +36,10 @@ for key, value := range file.Section("mysection") { Iterate through sections in a file: ```go -for sectionName, section := range file { - fmt.Printf("Section name: %s", sectionName) +for name, section := range file { + fmt.Printf("Section name: %s\n", name) } ``` -Note that the current implementation always includes the empty section -when iterating. File Format ----------- diff --git a/ini.go b/ini.go index 1d4d202..095fde4 100644 --- a/ini.go +++ b/ini.go @@ -68,7 +68,7 @@ func (f File) LoadFile(file string) (err error) { } func parseFile(in *bufio.Reader, file File) (err error) { - section := file.Section("") + section := "" lineNum := 0 for done := false; !done; { var line string @@ -93,10 +93,12 @@ func parseFile(in *bufio.Reader, file File) (err error) { if groups := assignRegex.FindStringSubmatch(line); groups != nil { key, val := groups[1], groups[2] key, val = strings.TrimSpace(key), strings.TrimSpace(val) - section[key] = val + file.Section(section)[key] = val } else if groups := sectionRegex.FindStringSubmatch(line); groups != nil { name := strings.TrimSpace(groups[1]) - section = file.Section(name) + section = name + // Create the section if it does not exist + file.Section(section) } else { return ErrSyntax{lineNum, line} } diff --git a/ini_test.go b/ini_test.go index 7ac6c00..06a4d05 100644 --- a/ini_test.go +++ b/ini_test.go @@ -1,6 +1,7 @@ package ini import ( + "reflect" "strings" "testing" ) @@ -61,3 +62,28 @@ func TestSyntaxError(t *testing.T) { t.Fatal("incorrect source") } } + +func TestDefinedSectionBehaviour(t *testing.T) { + check := func(src string, expect File) { + file, err := Load(strings.NewReader(src)) + if err != nil { + t.Fatal(err) + } + if !reflect.DeepEqual(file, expect) { + t.Errorf("expected %v, got %v", expect, file) + } + } + // No sections for an empty file + check("", File{}) + // Default section only if there are actually values for it + check("foo=bar", File{"": {"foo": "bar"}}) + // User-defined sections should always be present, even if empty + check("[a]\n[b]\nfoo=bar", File{ + "a": {}, + "b": {"foo": "bar"}, + }) + check("foo=bar\n[a]\nthis=that", File{ + "": {"foo": "bar"}, + "a": {"this": "that"}, + }) +}