Skip to content

Commit

Permalink
parser: fix line skipping when key is empty (#323)
Browse files Browse the repository at this point in the history
  • Loading branch information
gandarez authored May 30, 2022
1 parent 7c569cc commit 6098d42
Show file tree
Hide file tree
Showing 3 changed files with 25 additions and 1 deletion.
15 changes: 15 additions & 0 deletions error.go
Original file line number Diff line number Diff line change
Expand Up @@ -32,3 +32,18 @@ func IsErrDelimiterNotFound(err error) bool {
func (err ErrDelimiterNotFound) Error() string {
return fmt.Sprintf("key-value delimiter not found: %s", err.Line)
}

// ErrEmptyKeyName indicates the error type of no key name is found which there should be one.
type ErrEmptyKeyName struct {
Line string
}

// IsErrEmptyKeyName returns true if the given error is an instance of ErrEmptyKeyName.
func IsErrEmptyKeyName(err error) bool {
_, ok := err.(ErrEmptyKeyName)
return ok
}

func (err ErrEmptyKeyName) Error() string {
return fmt.Sprintf("empty key name: %s", err.Line)
}
2 changes: 2 additions & 0 deletions ini_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -441,6 +441,8 @@ BiomeRarityScale: 100
BiomeGroup(NormalBiomes, 3, 99, RoofedForestEnchanted, ForestSakura, FloatingJungle
BiomeGroup(IceBiomes, 4, 85, Ice Plains)
= RainForest
`))
require.NoError(t, err)
require.NotNil(t, f)
Expand Down
9 changes: 8 additions & 1 deletion parser.go
Original file line number Diff line number Diff line change
Expand Up @@ -164,6 +164,10 @@ func readKeyName(delimiters string, in []byte) (string, int, error) {
if endIdx < 0 {
return "", -1, ErrDelimiterNotFound{line}
}
if endIdx == 0 {
return "", -1, ErrEmptyKeyName{line}
}

return strings.TrimSpace(line[0:endIdx]), endIdx + 1, nil
}

Expand Down Expand Up @@ -463,8 +467,9 @@ func (f *File) parse(reader io.Reader) (err error) {

kname, offset, err := readKeyName(f.options.KeyValueDelimiters, line)
if err != nil {
switch {
// Treat as boolean key when desired, and whole line is key name.
if IsErrDelimiterNotFound(err) {
case IsErrDelimiterNotFound(err):
switch {
case f.options.AllowBooleanKeys:
kname, err := p.readValue(line, parserBufferSize)
Expand All @@ -482,6 +487,8 @@ func (f *File) parse(reader io.Reader) (err error) {
case f.options.SkipUnrecognizableLines:
continue
}
case IsErrEmptyKeyName(err) && f.options.SkipUnrecognizableLines:
continue
}
return err
}
Expand Down

0 comments on commit 6098d42

Please sign in to comment.