Skip to content

Wrong section may be written if section name contains dot #247

@csquire

Description

@csquire

Describe the bug
If a section name being written contains a dot, the wrong section can be written in the ini file. If section foo exists and you attempt to write section foo.bar the data will incorrectly be written to section foo. I included an example test below that reproduces the problem.

Example below when section foo exists and section foo.bar is written:

Expected output:

[foo]
fruit = apple

[foo.bar]
fruit = orange

Actual output:

[foo]
fruit = orange

[foo.bar]

To Reproduce

package ini

import (
	"os"
	"testing"

	"github.com/stretchr/testify/assert"

	"github.com/go-ini/ini"
)

func TestIni(t *testing.T) {
	type Profile struct {
		Fruit string `ini:"fruit"`
	}

	configFile := "config.ini"
	apple := &Profile{
		Fruit: "apple",
	}
	orange := &Profile{
		Fruit: "orange",
	}

	_, err := os.OpenFile(configFile, os.O_RDONLY|os.O_CREATE, 0666)
	assert.Nil(t, err)
	conf, err := ini.LoadSources(ini.LoadOptions{}, configFile)
	assert.Nil(t, err)

	// Writes to section 'foo' with apple and 'foo.bar' with orange
	err = conf.Section("foo").ReflectFrom(&apple)
	assert.Nil(t, err)
	err = conf.Section("foo.bar").ReflectFrom(&orange)
	assert.Nil(t, err)
	err = conf.SaveTo(configFile)
	assert.Nil(t, err)

        // This will fail
	assert.Equal(t,
		"apple",
		conf.Section("foo").Key("fruit").Value(),
		"Section foo should be apple")
	assert.Equal(t,
		"orange",
		conf.Section("foo.bar").Key("fruit").Value(),
		"Section foo.bar should be orange")
}

Expected behavior
I expect the correct section to be written

Metadata

Metadata

Assignees

No one assigned

    Labels

    bugSomething isn't working

    Type

    No type
    No fields configured for issues without a type.

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions