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
4 changes: 4 additions & 0 deletions file.go
Original file line number Diff line number Diff line change
Expand Up @@ -570,6 +570,10 @@ func (f *File) writeToBuffer(opts []WriteOption) (*bytes.Buffer, error) {
if !f.options.AllowBooleanKeys {
return line, nil
}
case f.options.AllowHeredocMultilineValues && key.heredoc != "":
// keeps the original heredoc delimiter
delim := key.heredoc
line = form + eq + "<<" + delim + lineBreak + val + delim + lineBreak
case strings.Contains(val, "\n") || (val != "" && val[0] == '`'):
line = form + eq + `"""` + val + `"""` + lineBreak
case !f.options.IgnoreInlineComment && strings.ContainsAny(val, symbols):
Expand Down
20 changes: 10 additions & 10 deletions file_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -709,7 +709,7 @@ func TestFile_WriteTo(t *testing.T) {

golden := "testdata/TestFile_WriteTo.golden"
if *update {
require.NoError(t, os.WriteFile(golden, buf.Bytes(), 0644))
require.NoError(t, os.WriteFile(golden, buf.Bytes(), 0o644))
}

expected, err := os.ReadFile(golden)
Expand Down Expand Up @@ -742,7 +742,6 @@ domain = mydomain.com
; Comment
test =
`, buf.String())

})

t.Run("keep leading and trailing spaces in value", func(t *testing.T) {
Expand Down Expand Up @@ -788,7 +787,7 @@ Note = Hello world!`))
require.NotNil(t, f)

var actual bytes.Buffer
var expected = []byte(`[Others]
expected := []byte(`[Others]
Cities -> HangZhou|Boston
Visits -> 1993-10-07T20:17:05Z, 1993-10-07T20:17:05Z
Years -> 1993,1994
Expand Down Expand Up @@ -1114,13 +1113,14 @@ func TestWriteReadsBack(t *testing.T) {
{"k =\n n\nk\n", []LoadOption{AllowNestedValues(true), AllowBooleanKeys(true)}},
{"k = \"\"\n n\n", []LoadOption{AllowNestedValues(true), AllowPythonMultilineValues(true)}},
{"NAME = x\n[DEFAULT]\nk1 = v1\n", []LoadOption{CaseInsensitive(true), AllowNonUniqueSections(true)}},
{"[DEFAULT] ; c\n[s]\nk = v\n", nil}, // comment of an empty default section
{"# BEGIN\n[p]\nk = v\n# END\n", nil}, // comment after the last key
{"# only a comment\n", nil}, // comment of an empty file
{"[raw]\nbody\n# c\n", []LoadOption{RawSections("raw")}}, // comment after a raw body
{"[custom]\n", []LoadOption{RawSections("custom")}}, // empty raw section
{"k = v\n[DEFAULT]\n", []LoadOption{RawSections("DEFAULT")}}, // empty raw header of a section with keys
{"k = a\n\n b\nn = 1\n", []LoadOption{AllowPythonMultilineValues(true)}}, // empty line in a multiline value
{"[DEFAULT] ; c\n[s]\nk = v\n", nil}, // comment of an empty default section
{"# BEGIN\n[p]\nk = v\n# END\n", nil}, // comment after the last key
{"# only a comment\n", nil}, // comment of an empty file
{"[raw]\nbody\n# c\n", []LoadOption{RawSections("raw")}}, // comment after a raw body
{"[custom]\n", []LoadOption{RawSections("custom")}}, // empty raw section
{"k = v\n[DEFAULT]\n", []LoadOption{RawSections("DEFAULT")}}, // empty raw header of a section with keys
{"k = a\n\n b\nn = 1\n", []LoadOption{AllowPythonMultilineValues(true)}}, // empty line in a multiline value
{"NAME = <<EOT\nblabla\nEOT\n", []LoadOption{AllowHeredocMultilineValues(true)}}, // multiline heredoc
} {
f, err := Load([]byte(tc.data), tc.opts...)
require.NoError(t, err)
Expand Down
65 changes: 65 additions & 0 deletions ini_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -1569,6 +1569,71 @@ func TestPythonMultiline_EOF(t *testing.T) {
assert.Equal(t, "some text here\n\tsome more text here 2", testData.Value1)
}

type testHeredocData struct {
Value1 string `ini:"value1"`
Value2 string `ini:"value2"`
Value3 string `ini:"value3"`
Value4 string `ini:"value4"`
Value5 string `ini:"value5"`
Value6 string `ini:"value6"`
}

func TestHeredocMultiline(t *testing.T) {
if runtime.GOOS == "windows" {
t.Skip("Skipping testing on Windows")
}

path := filepath.Join("testdata", "multiline_heredoc.ini")
f, err := Load(path, AllowHeredocMultilineValues(true))
require.NoError(t, err)
require.NotNil(t, f)
assert.Len(t, f.Sections(), 1)

defaultSection := f.Section("")
assert.NotNil(t, f.Section(""))

var testData testHeredocData
err = defaultSection.MapTo(&testData)
require.NoError(t, err)
assert.Equal(t, "", testData.Value1)
assert.Equal(t, "line 1\n\tline 2\nline 3\n", testData.Value2)
assert.Equal(t, "regular value", testData.Value3)
assert.Equal(t, "line 1\n\n", testData.Value4)
assert.Equal(t, "line\n'\n", testData.Value6)
// multiline heredoc should store text as is, no transformation
assert.Equal(t, "\t%(value3)\n\\\n\t'\"\\\"\\'\\\\\\\n EOF\n", testData.Value5)
t.Run("write out", func(t *testing.T) {
var buf bytes.Buffer
_, err := f.WriteTo(&buf)
require.NoError(t, err)
assert.Equal(t, `value1 = <<EOT
EOT
value2 = <<ABC
line 1
line 2
line 3
ABC
value3 = regular value
value4 = <<LONG_STRING_HEREDOC
line 1

LONG_STRING_HEREDOC
value5 = <<EOF
%(value3)
\
'"\"\'\\\
EOF
EOF
value6 = <<\|$
line
'
\|$
`,
buf.String(),
)
})
}

func Test_NestedValuesSpanningSections(t *testing.T) {
t.Run("basic nested value", func(t *testing.T) {
f, err := Load([]byte(`
Expand Down
3 changes: 3 additions & 0 deletions key.go
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,9 @@ type Key struct {
shadows []string
isAutoIncrement bool
isBooleanType bool
// heredoc is the multiline <<DELIMITER the value was read with, kept to
// write it back with the same one.
heredoc string
// missing is set on a key Section.Key returned for a name its section
// doesn't have. The key isn't in the section until a change adds it.
// If the section gains a key of its name first, it reads and changes
Expand Down
36 changes: 31 additions & 5 deletions lexer.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ package ini
import (
"errors"
"fmt"
"regexp"
"strconv"
"strings"
"unicode"
Expand All @@ -24,6 +25,7 @@ type token struct {
kind tokenKind
name string
value string
heredoc string // for tokKey, the delimiter of a heredoc value
comment string // for tokEOF, the comment lines after the last key
raw bool // for tokSection, the section is unparseable
line, column int // where the token starts, both from 1
Expand All @@ -45,6 +47,7 @@ type lexer struct {
line int // number of the last line read, from 1

comment []string // comment pieces for the next section or key
heredoc string // delimiter of the heredoc value just read, if any
lastValueEmpty bool // the last key had an empty value, so indented lines are nested values
inRaw bool // inside an unparseable section
raw strings.Builder
Expand Down Expand Up @@ -234,12 +237,14 @@ func (l *lexer) key(line string, tok *token) (ok bool, _ error) {
name, offset, err := readKeyName(&l.opts.delimiterSet, line)
switch {
case err == nil:
l.heredoc = ""
value, err := l.readValue(line[offset:])
if err != nil {
return false, err
}
l.lastValueEmpty = value == ""
tok.kind, tok.name, tok.value, tok.comment = tokKey, name, value, l.takeComment()
tok.heredoc = l.heredoc
return true, nil

case errors.Is(err, ErrDelimiterNotFound) && l.opts.AllowBooleanKeys:
Expand Down Expand Up @@ -302,6 +307,9 @@ func (l *lexer) readValue(in string) (string, error) {
return line, nil
}

// at least: '<<X', must end with '\n'
var reg = regexp.MustCompile(`^(<<[A-Za-z0-9!#$%&(\)*+,\-./:;=?@[\\\]^_{|}~]+)[\t ]*\n$`)

// valueQuote returns the quote that opens line as a quoted value: `"""`, "`",
// or `"` with UnescapeValueDoubleQuotes. Single quotes and plain double
// quotes are handled later, as surrounding quotes.
Expand All @@ -313,6 +321,13 @@ func (l *lexer) valueQuote(line string) string {
return "`"
case l.opts.UnescapeValueDoubleQuotes && line[0] == '"':
return `"`
case l.opts.AllowHeredocMultilineValues && len(line) > 3 && line[:2] == `<<`:
data := reg.FindStringSubmatch(line)
if len(data) == 0 || len(data[1]) < 3 {
// bad heredoc
return ""
}
return data[1] // '<<XXX' trimmed without ending \n
}
return ""
}
Expand All @@ -321,13 +336,20 @@ func (l *lexer) valueQuote(line string) string {
// the same line or, failing that, the first later line containing q.
func (l *lexer) readQuoted(line, q string) (string, error) {
rest := line[len(q):]
if i := strings.LastIndex(rest, q); i > -1 {
if q == `"` {
return strings.ReplaceAll(rest[:i], `\"`, `"`), nil
inHeredoc := false
if l.opts.AllowHeredocMultilineValues && strings.HasPrefix(q, "<<") {
q = q[2:] // strip << to get the heredoc token
rest = "" // skip, whole line is and heredoc delimiter
inHeredoc = true
l.heredoc = q
} else {
if i := strings.LastIndex(rest, q); i > -1 {
if q == `"` {
return strings.ReplaceAll(rest[:i], `\"`, `"`), nil
}
return rest[:i], nil
}
return rest[:i], nil
}

var b strings.Builder
b.WriteString(rest)
for {
Expand All @@ -342,6 +364,9 @@ func (l *lexer) readQuoted(line, q string) (string, error) {
case !l.opts.IgnoreContinuation && strings.HasSuffix(strings.TrimSpace(next[i+len(q):]), `\`):
// A backslash after the closing quote continues the value.
b.WriteString(next)
case inHeredoc && i != 0:
// heredoc must start the line, no space allowed before
b.WriteString(next)
default:
b.WriteString(next[:i])
if j := l.opts.commentSet.index(next[i:]); j > -1 {
Expand Down Expand Up @@ -520,6 +545,7 @@ func (f *File) parse(src string) error {
return tok.errorf(err)
}
key.isAutoIncrement = isAutoIncr
key.heredoc = tok.heredoc
key.comment = tok.comment
lastRegularKey = key
}
Expand Down
8 changes: 8 additions & 0 deletions options.go
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,7 @@ type loadOptions struct {
AllowShadows bool
AllowNestedValues bool
AllowPythonMultilineValues bool
AllowHeredocMultilineValues bool
SpaceBeforeInlineComment bool
UnescapeValueDoubleQuotes bool
UnescapeValueCommentSymbols bool
Expand Down Expand Up @@ -133,6 +134,13 @@ func AllowPythonMultilineValues(v bool) LoadOption {
return func(o *loadOptions) { o.AllowPythonMultilineValues = v }
}

// AllowHeredocMultilineValues continues a value on the following lines that
// start with a heredoc string (like <<EOT ... EOT).
// Accepted characters for the delimiter: A-Za-z0-9!#$%&()*+,-./:;=?@[]^_{|}~\
func AllowHeredocMultilineValues(v bool) LoadOption {
return func(o *loadOptions) { o.AllowHeredocMultilineValues = v }
}

// SpaceBeforeInlineComment starts an inline comment only at a comment symbol
// that follows a space, so values can contain comment symbols.
func SpaceBeforeInlineComment(v bool) LoadOption {
Expand Down
22 changes: 22 additions & 0 deletions testdata/multiline_heredoc.ini
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
value1 = <<EOT
EOT

value2 = <<ABC
line 1
line 2
line 3
ABC

value3 = regular value

value4 =<<LONG_STRING_HEREDOC
line 1

LONG_STRING_HEREDOC

value5 =<<EOF
%(value3)
\
'"\"\'\\\
EOF
EOF