Skip to content

Add File.CopySection and File.RenameSection - #444

Open
unknwon wants to merge 1 commit into
mainfrom
copy-rename-section
Open

unknwon wants to merge 1 commit into
mainfrom
copy-rename-section

Conversation

@unknwon

@unknwon unknwon commented Nov 15, 2026

Copy link
Copy Markdown
Member

Describe the pull request

Adds two File methods next to NewSection and DeleteSection, for editing files such as my.cnf where a new instance starts from an existing one:

sec, err := f.CopySection("mysqld", "mysqld2")
sec.Key("port").SetValue("3307")

err = f.RenameSection("mysqld", "server")
  • CopySection(name, newName) adds an independent copy after the last section: its comment, keys, values, shadow and nested values, key comments, or its raw body. The trailing comments of the file aren't copied.
  • RenameSection(name, newName) renames the section where it is. *Section and *Key values held for it see the new name.
  • Child sections such as [mysqld.extra] are neither copied nor renamed; callers can loop over ChildSections().
  • Errors: a missing source, an empty name, the default section's name, or a name that's taken, unless the file allows non-unique sections. Then they act on the first section of the name, like GetSection, and keep sections of a name indexed in file order. The default section can't be renamed.
  • Case-insensitive files store newName lower-cased, as NewSection does, now through a shared helper.

Clone was considered as a name, but in Go it usually means a detached copy (maps.Clone, bytes.Clone), and this one gets a name inside the file.

Section.Name() now takes the read lock, since a rename changes it. Nothing in the package calls it.

Link to the issue: closes #280

Checklist

  • I agree to follow the Code of Conduct by submitting this pull request.
  • I have read and acknowledge the Contributing guide.
  • I have added test cases to cover the new code.

AI usage

Written by Amp (an AI coding agent) at the maintainer's request. Validation: go test ./..., go vet, 20 s of FuzzWriteRoundTrip, and a scratch -race run of Name and SectionNames against concurrent renames and copies. TestFile_CopyRenameSection checks the written copy, that it's independent of the original, held values after a rename, every error case, case-insensitive names and non-unique section order.

CopySection adds a copy of a section with its keys, values and
comments under a new name, and RenameSection renames a section in
place. Section.Name now takes the read lock, since a rename changes it
(#280).

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Methods for Copy Section & Rename Section

1 participant