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
51 changes: 38 additions & 13 deletions parser.go
Original file line number Diff line number Diff line change
Expand Up @@ -225,6 +225,42 @@ func (p *parser) readContinuationLines(val string) (string, error) {
return val, nil
}

func inlineCommentIndex(line string, spaceBefore bool) int {
var quote byte
escaped := false
for i := 0; i < len(line); i++ {
ch := line[i]
if quote != 0 {
if escaped {
escaped = false
continue
}
if quote == '"' && ch == '\\' {
escaped = true
continue
}
if ch == quote {
quote = 0
}
continue
}
if i == 0 && (ch == '\'' || ch == '"') {
quote = ch
continue
}
if ch != '#' && ch != ';' {
continue
}
if !spaceBefore {
return i
}
if i > 0 && line[i-1] == ' ' {
return i - 1
}
}
return -1
}

// hasSurroundedQuote check if and only if the first and last characters
// are quotes \" or \'.
// It returns false if any other parts also contain same kind of quotes.
Expand Down Expand Up @@ -276,24 +312,13 @@ func (p *parser) readValue(in []byte, bufferSize int) (string, error) {
return p.readContinuationLines(line[:len(line)-1])
}

// Check if ignore inline comment
// Check for inline comments only outside a value's surrounding quotes.
if !p.options.IgnoreInlineComment {
var i int
if p.options.SpaceBeforeInlineComment {
i = strings.Index(line, " #")
if i == -1 {
i = strings.Index(line, " ;")
}

} else {
i = strings.IndexAny(line, "#;")
}

i := inlineCommentIndex(line, p.options.SpaceBeforeInlineComment)
if i > -1 {
p.comment.WriteString(line[i:])
line = strings.TrimSpace(line[:i])
}

}

// Trim single and double quotes
Expand Down
13 changes: 13 additions & 0 deletions parser_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -75,3 +75,16 @@ func TestBadLoad(t *testing.T) {
})
})
}

func TestInlineCommentMarkersInQuotedValues(t *testing.T) {
f, err := Load([]byte(`[background]
primary-color = '#e18477'
secondary-color = "#000000"
accent-color = '#ffffff' # trailing comment
`))
require.NoError(t, err)
assert.Equal(t, "#e18477", f.Section("background").Key("primary-color").String())
assert.Equal(t, "#000000", f.Section("background").Key("secondary-color").String())
assert.Equal(t, "#ffffff", f.Section("background").Key("accent-color").String())
assert.Equal(t, "# trailing comment", f.Section("background").Key("accent-color").Comment)
}