From 6098d4257e883d8cf846e9012bdd5b03811af4ce Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Carlos=20Henrique=20Guard=C3=A3o=20Gandarez?= <782854+gandarez@users.noreply.github.com> Date: Mon, 30 May 2022 20:13:15 -0300 Subject: [PATCH] parser: fix line skipping when key is empty (#323) --- error.go | 15 +++++++++++++++ ini_test.go | 2 ++ parser.go | 9 ++++++++- 3 files changed, 25 insertions(+), 1 deletion(-) diff --git a/error.go b/error.go index d88347c..f66bc94 100644 --- a/error.go +++ b/error.go @@ -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) +} diff --git a/ini_test.go b/ini_test.go index 12672e2..306a2a8 100644 --- a/ini_test.go +++ b/ini_test.go @@ -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) diff --git a/parser.go b/parser.go index ac1c980..44fc526 100644 --- a/parser.go +++ b/parser.go @@ -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 } @@ -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) @@ -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 }