Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
102 changes: 99 additions & 3 deletions file.go
Original file line number Diff line number Diff line change
Expand Up @@ -103,9 +103,7 @@ func (f *File) addSection(name string) (*Section, error) {
return nil, errors.New("empty section name")
}

if (f.options.Insensitive || f.options.InsensitiveSections) && name != f.options.DefaultSection {
name = strings.ToLower(name)
}
name = f.storedSectionName(name)

if secs := f.byName[name]; len(secs) > 0 && !f.options.AllowNonUniqueSections {
return secs[0], nil
Expand Down Expand Up @@ -338,6 +336,104 @@ func (f *File) SectionNames() []string {
return names
}

// storedSectionName returns name as the file stores a new section's name:
// lower-cased when loaded with CaseInsensitive or CaseInsensitiveSections,
// unless it is the default section's.
func (f *File) storedSectionName(name string) string {
if (f.options.Insensitive || f.options.InsensitiveSections) && name != f.options.DefaultSection {
return strings.ToLower(name)
}
return name
}

// checkNewSectionName returns an error if a section can't be copied or
// renamed to name: it is empty, the default section's, or another
// section's, unless the file allows non-unique sections. The caller holds
// the lock.
func (f *File) checkNewSectionName(name string) error {
switch {
case name == "":
return errors.New("empty section name")
case f.isDefaultSection(name):
return errors.New("the default section already exists")
case len(f.byName[name]) > 0 && !f.options.AllowNonUniqueSections:
return fmt.Errorf("section %q already exists", name)
}
return nil
}

// CopySection adds a copy of the section name, with its comment, keys,
// values and key comments, or its raw body, as a section newName after the
// last section, and returns the copy. With AllowNonUniqueSections, it
// copies the first section of the name, and newName may be taken. Child
// sections of name aren't copied.
func (f *File) CopySection(name, newName string) (*Section, error) {
f.maybeLock()
defer f.maybeUnlock()
secs, err := f.sectionsByName(name)
if err != nil {
return nil, err
}
newName = f.storedSectionName(newName)
if err := f.checkNewSectionName(newName); err != nil {
return nil, err
}

src, dst := secs[0], newSection(f, newName)
dst.comment, dst.isRawSection, dst.rawBody = src.comment, src.isRawSection, src.rawBody
for _, k := range src.keys {
c := *k
c.s = dst
c.shadows = slices.Clone(k.shadows)
c.nestedValues = slices.Clone(k.nestedValues)
dst.keys = append(dst.keys, &c)
dst.byName[c.name] = &c
}
f.sections = append(f.sections, dst)
f.byName[newName] = append(f.byName[newName], dst)
return dst, nil
}

// RenameSection renames the section name to newName, in its place among
// the sections. *Section and *Key values held for it see the new name.
// With AllowNonUniqueSections, it renames the first section of the name,
// and newName may be taken. Child sections of name keep their names. The
// default section can't be renamed.
func (f *File) RenameSection(name, newName string) error {
f.maybeLock()
defer f.maybeUnlock()
secs, err := f.sectionsByName(name)
if err != nil {
return err
}
sec := secs[0]
if f.isDefaultSection(sec.name) {
return errors.New("cannot rename the default section")
}
newName = f.storedSectionName(newName)
if newName == sec.name {
return nil
}
if err := f.checkNewSectionName(newName); err != nil {
return err
}

if len(secs) == 1 {
delete(f.byName, sec.name)
} else {
f.byName[sec.name] = secs[1:]
}
sec.name = newName
// Sections of a name are indexed in the order of f.sections.
f.byName[newName] = nil
for _, s := range f.sections {
if s.name == newName {
f.byName[newName] = append(f.byName[newName], s)
}
}
return nil
}

// DeleteSection deletes a section or all sections with given name.
func (f *File) DeleteSection(name string) {
secs, err := f.SectionsByName(name)
Expand Down
114 changes: 114 additions & 0 deletions file_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -549,6 +549,120 @@ func TestFile_SectionStrings(t *testing.T) {
assert.Equal(t, []string{DefaultSection, "author", "package", "package.sub", "features", "types", "array", "note", "comments", "string escapes", "advance"}, f.SectionNames())
}

// https://github.com/go-ini/ini/issues/280
func TestFile_CopyRenameSection(t *testing.T) {
const data = `; mysql
[mysqld]
port = 3306 ; default
include = a
include = b
[mysqld.extra]
x = 1
[client]
user = root
`
load := func(t *testing.T, opts ...LoadOption) *File {
f, err := Load([]byte(data), append([]LoadOption{AllowShadows(true)}, opts...)...)
require.NoError(t, err)
return f
}
write := func(t *testing.T, f *File) string {
var buf bytes.Buffer
_, err := f.WriteTo(&buf)
require.NoError(t, err)
return buf.String()
}

t.Run("copy", func(t *testing.T) {
f := load(t)
sec, err := f.CopySection("mysqld", "mysqld2")
require.NoError(t, err)
sec.Key("port").SetValue("3307")
require.NoError(t, sec.Key("include").AddShadow("c"))

// The copy is independent of the original and comes last.
assert.Equal(t, []string{"a", "b"}, f.Section("mysqld").Key("include").Values())
assert.Equal(t, `; mysql
[mysqld]
; default
port = 3306
include = a
include = b

[mysqld.extra]
x = 1

[client]
user = root

; mysql
[mysqld2]
; default
port = 3307
include = a
include = b
include = c
`, write(t, f))
})

t.Run("rename", func(t *testing.T) {
f := load(t)
heldSec := f.Section("mysqld")
held := heldSec.Key("port")
require.NoError(t, f.RenameSection("mysqld", "server"))

assert.Equal(t, []string{DefaultSection, "server", "mysqld.extra", "client"}, f.SectionNames())
assert.False(t, f.HasSection("mysqld"))
assert.Equal(t, "server", heldSec.Name())
assert.Equal(t, "3306", f.Section("server").Key("port").String())
// Reads through a held key see the renamed section.
f.Section("server").Key("port").SetValue("1")
assert.Equal(t, "1", held.String())
require.NoError(t, f.RenameSection("server", "server"))
})

t.Run("errors", func(t *testing.T) {
f := load(t)
_, err := f.CopySection("missing", "x")
assert.Error(t, err)
_, err = f.CopySection("mysqld", "client")
assert.Error(t, err)
_, err = f.CopySection("mysqld", "")
assert.Error(t, err)
_, err = f.CopySection("mysqld", DefaultSection)
assert.Error(t, err)
assert.Error(t, f.RenameSection("mysqld", "client"))
assert.Error(t, f.RenameSection("", "x"))
assert.Error(t, f.RenameSection("missing", "x"))
assert.Equal(t, []string{DefaultSection, "mysqld", "mysqld.extra", "client"}, f.SectionNames())
})

t.Run("case insensitive", func(t *testing.T) {
f := load(t, CaseInsensitive(true))
require.NoError(t, f.RenameSection("MySQLd", "Server"))
assert.Equal(t, "3306", f.Section("SERVER").Key("port").String())
_, err := f.CopySection("client", "MYSQLD.EXTRA")
assert.Error(t, err)
})

t.Run("non-unique sections", func(t *testing.T) {
f, err := Load([]byte("[peer]\nip = 1\n[peer]\nip = 2\n[other]\nip = 3\n"), AllowNonUniqueSections(true))
require.NoError(t, err)
// Renaming the first peer after other keeps the file order.
require.NoError(t, f.RenameSection("other", "peer"))
require.NoError(t, f.RenameSection("peer", "other"))
peers, err := f.SectionsByName("peer")
require.NoError(t, err)
require.Len(t, peers, 2)
assert.Equal(t, "2", peers[0].Key("ip").String())
assert.Equal(t, "3", peers[1].Key("ip").String())

_, err = f.CopySection("peer", "peer")
require.NoError(t, err)
assert.Equal(t, []string{DefaultSection, "other", "peer", "peer", "peer"}, f.SectionNames())
})
}

func TestFile_DeleteSection(t *testing.T) {
t.Run("delete a section", func(t *testing.T) {
f := Empty()
Expand Down
2 changes: 2 additions & 0 deletions section.go
Original file line number Diff line number Diff line change
Expand Up @@ -70,6 +70,8 @@ func (s *Section) attach() *Section {

// Name returns name of Section.
func (s *Section) Name() string {
s.f.maybeRLock()
defer s.f.maybeRUnlock()
return s.name
}

Expand Down
Loading