Skip to content

Commit

Permalink
Do not print comments if they are all empty
Browse files Browse the repository at this point in the history
  • Loading branch information
magiconair committed Apr 10, 2015
1 parent 70f4111 commit 6dfa15a
Show file tree
Hide file tree
Showing 2 changed files with 30 additions and 16 deletions.
33 changes: 22 additions & 11 deletions properties.go
Original file line number Diff line number Diff line change
Expand Up @@ -539,21 +539,32 @@ func (p *Properties) WriteComment(w io.Writer, prefix string, enc Encoding) (n i

if prefix != "" {
if comments, ok := p.c[key]; ok {
// add a blank line between entries but not at the top
if len(comments) > 0 && n > 0 {
x, err = fmt.Fprintln(w)
if err != nil {
return
// don't print comments if they are all empty
allEmpty := true
for _, c := range comments {
if c != "" {
allEmpty = false
break
}
n += x
}

for _, c := range comments {
x, err = fmt.Fprintf(w, "%s%s\n", prefix, encode(c, "", enc))
if err != nil {
return
if !allEmpty {
// add a blank line between entries but not at the top
if len(comments) > 0 && n > 0 {
x, err = fmt.Fprintln(w)
if err != nil {
return
}
n += x
}

for _, c := range comments {
x, err = fmt.Fprintf(w, "%s%s\n", prefix, encode(c, "", enc))
if err != nil {
return
}
n += x
}
n += x
}
}
}
Expand Down
13 changes: 8 additions & 5 deletions properties_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -116,6 +116,7 @@ var commentTests = []struct {
comments []string
}{
{"key=value", "key", "value", nil},
{"#\nkey=value", "key", "value", []string{""}},
{"#comment\nkey=value", "key", "value", []string{"comment"}},
{"# comment\nkey=value", "key", "value", []string{"comment"}},
{"# comment\nkey=value", "key", "value", []string{"comment"}},
Expand Down Expand Up @@ -176,6 +177,8 @@ var writeCommentTests = []struct {
}{
// ISO-8859-1 tests
{"key = value", "key = value\n", "ISO-8859-1"},
{"#\nkey = value", "key = value\n", "ISO-8859-1"},
{"#\n#\n#\nkey = value", "key = value\n", "ISO-8859-1"},
{"# comment\nkey = value", "# comment\nkey = value\n", "ISO-8859-1"},
{"\n# comment\nkey = value", "# comment\nkey = value\n", "ISO-8859-1"},
{"# comment\n\nkey = value", "# comment\nkey = value\n", "ISO-8859-1"},
Expand Down Expand Up @@ -247,11 +250,11 @@ var parsedDurationTests = []struct {
def, value time.Duration
}{
// valid values
{"key = -1ns", "key", 999, -1*time.Nanosecond},
{"key = 300ms", "key", 999, 300*time.Millisecond},
{"key = 5s", "key", 999, 5*time.Second},
{"key = 3h", "key", 999, 3*time.Hour},
{"key = 2h45m", "key", 999, 2*time.Hour+45*time.Minute},
{"key = -1ns", "key", 999, -1 * time.Nanosecond},
{"key = 300ms", "key", 999, 300 * time.Millisecond},
{"key = 5s", "key", 999, 5 * time.Second},
{"key = 3h", "key", 999, 3 * time.Hour},
{"key = 2h45m", "key", 999, 2*time.Hour + 45*time.Minute},

// invalid values
{"key = 0xff", "key", 999, 999},
Expand Down

0 comments on commit 6dfa15a

Please sign in to comment.