feat(格式配置): 支持格式化配置

This commit is contained in:
2026-08-19 14:27:56 +08:00
parent ee27859f7e
commit 1f9d169cf1
2 changed files with 96 additions and 15 deletions
+39 -4
View File
@@ -36,14 +36,14 @@ type parsedKeyValue struct {
separator string
}
func (ini *GoINI) parse() {
func (ini *GoINI) parse(data string) {
ini.fileLines = nil
currentSection := ini.rootSection
if len(ini.data) == 0 {
if data == "" {
ini.rebuildIndexes()
return
}
for _, rawLine := range strings.Split(string(ini.data), "\n") {
for _, rawLine := range strings.Split(data, "\n") {
line, section := parseRawLine(rawLine, currentSection)
currentSection = section
ini.fileLines = append(ini.fileLines, line)
@@ -187,7 +187,7 @@ func (ini *GoINI) addSectionKey(sectionName string, keyName string, keyValue str
func (ini *GoINI) ensureParsed() {
if ini.sectionValues == nil {
ini.parse()
ini.parse("")
}
}
@@ -358,6 +358,41 @@ func renderLine(line iniLine) string {
}
}
func (ini *GoINI) formatString() string {
formattedLines := make([]string, 0, len(ini.fileLines))
pendingComments := make([]string, 0)
for _, line := range ini.fileLines {
switch line.kind {
case lineSection:
if len(formattedLines) > 0 {
formattedLines = append(formattedLines, "")
}
formattedLines = append(formattedLines, pendingComments...)
pendingComments = pendingComments[:0]
formattedLines = append(formattedLines, "["+line.sectionName+"]")
case lineKeyValue:
formattedLines = append(formattedLines, pendingComments...)
pendingComments = pendingComments[:0]
formattedLines = append(formattedLines, line.keyName+defaultSeparator+formatValue(line.keyValue))
case lineComment:
pendingComments = append(pendingComments, formatINIComment(line.text))
}
}
formattedLines = append(formattedLines, pendingComments...)
if len(formattedLines) == 0 {
return ""
}
return strings.Join(formattedLines, "\n") + "\n"
}
func formatINIComment(comment string) string {
comment = stripComment(comment)
if comment == "" {
return "#"
}
return "# " + comment
}
func renderKeyValue(line iniLine) string {
separator := line.separator
if separator == "" {