file: fix incorrect multiline comment handling when write out (#157)

This commit is contained in:
Unknwon
2018-08-18 19:46:59 +08:00
parent d58d458bec
commit 5cf292cae4
3 changed files with 40 additions and 20 deletions
+18 -11
View File
@@ -237,15 +237,20 @@ func (f *File) writeToBuffer(indent string) (*bytes.Buffer, error) {
for i, sname := range f.sectionList {
sec := f.Section(sname)
if len(sec.Comment) > 0 {
if sec.Comment[0] != '#' && sec.Comment[0] != ';' {
sec.Comment = "; " + sec.Comment
// Support multiline comments
lines := strings.Split(sec.Comment, LineBreak)
for i := range lines {
if lines[i][0] != '#' && lines[i][0] != ';' {
lines[i] = "; " + lines[i]
} else {
sec.Comment = sec.Comment[:1] + " " + strings.TrimSpace(sec.Comment[1:])
lines[i] = lines[i][:1] + " " + strings.TrimSpace(lines[i][1:])
}
if _, err := buf.WriteString(sec.Comment + LineBreak); err != nil {
if _, err := buf.WriteString(lines[i] + LineBreak); err != nil {
return nil, err
}
}
}
if i > 0 || DefaultHeader {
if _, err := buf.WriteString("[" + sname + "]" + LineBreak); err != nil {
@@ -300,19 +305,21 @@ func (f *File) writeToBuffer(indent string) (*bytes.Buffer, error) {
if len(indent) > 0 && sname != DEFAULT_SECTION {
buf.WriteString(indent)
}
if key.Comment[0] != '#' && key.Comment[0] != ';' {
key.Comment = "; " + key.Comment
} else {
key.Comment = key.Comment[:1] + " " + strings.TrimSpace(key.Comment[1:])
}
// Support multiline comments
key.Comment = strings.Replace(key.Comment, "\n", "\n; ", -1)
lines := strings.Split(key.Comment, LineBreak)
for i := range lines {
if lines[i][0] != '#' && lines[i][0] != ';' {
lines[i] = "; " + lines[i]
} else {
lines[i] = lines[i][:1] + " " + strings.TrimSpace(lines[i][1:])
}
if _, err := buf.WriteString(key.Comment + LineBreak); err != nil {
if _, err := buf.WriteString(lines[i] + LineBreak); err != nil {
return nil, err
}
}
}
if len(indent) > 0 && sname != DEFAULT_SECTION {
buf.WriteString(indent)
+16 -3
View File
@@ -266,14 +266,27 @@ func TestFile_WriteTo(t *testing.T) {
})
Convey("Support multiline comments", t, func() {
f := ini.Empty()
f, err := ini.Load([]byte(`
#
# general.domain
#
# Domain name of XX system.
domain = mydomain.com
`))
So(err, ShouldBeNil)
f.Section("").Key("test").Comment = "Multiline\nComment"
var buf bytes.Buffer
_, err := f.WriteTo(&buf)
_, err = f.WriteTo(&buf)
So(err, ShouldBeNil)
So(buf.String(), ShouldEqual, `; Multiline
So(buf.String(), ShouldEqual, `#
# general.domain
#
# Domain name of XX system.
domain = mydomain.com
; Multiline
; Comment
test =
+1 -1
View File
@@ -34,7 +34,7 @@ const (
// Maximum allowed depth when recursively substituing variable names.
_DEPTH_VALUES = 99
_VERSION = "1.38.1"
_VERSION = "1.38.2"
)
// Version returns current package version literal.