From d6a02d66b194138ceb44aed4ce13eec7d8cc272a Mon Sep 17 00:00:00 2001 From: Rupayon Haldar <80724680+rupayon123@users.noreply.github.com> Date: Fri, 2 Oct 2026 22:56:05 -0400 Subject: [PATCH] Ignore comment markers inside quoted values --- parser.go | 51 +++++++++++++++++++++++++++++++++++++------------- parser_test.go | 13 +++++++++++++ 2 files changed, 51 insertions(+), 13 deletions(-) diff --git a/parser.go b/parser.go index 513b19e..cd21cb3 100644 --- a/parser.go +++ b/parser.go @@ -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. @@ -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 diff --git a/parser_test.go b/parser_test.go index 7016d67..e308853 100644 --- a/parser_test.go +++ b/parser_test.go @@ -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) +}