From 4a5ae9e81e09e3cc5197fccde9105e9fa5ff65b9 Mon Sep 17 00:00:00 2001 From: Thomas Pelletier Date: Tue, 7 Sep 2021 10:21:14 -0400 Subject: [PATCH] errors: fix context generation with only one line --- errors.go | 11 ++++++++++- errors_test.go | 7 +++++++ 2 files changed, 17 insertions(+), 1 deletion(-) diff --git a/errors.go b/errors.go index a00924b..d9a6ee7 100644 --- a/errors.go +++ b/errors.go @@ -116,6 +116,7 @@ func wrapDecodeError(document []byte, de *decodeError) *DecodeError { maxLine := errLine + len(after) - 1 lineColumnWidth := len(strconv.Itoa(maxLine)) + // Write the lines of context strictly before the error. for i := len(before) - 1; i > 0; i-- { line := errLine - i buf.WriteString(formatLineNumber(line, lineColumnWidth)) @@ -129,6 +130,8 @@ func wrapDecodeError(document []byte, de *decodeError) *DecodeError { buf.WriteRune('\n') } + // Write the document line that contains the error. + buf.WriteString(formatLineNumber(errLine, lineColumnWidth)) buf.WriteString("| ") @@ -143,6 +146,10 @@ func wrapDecodeError(document []byte, de *decodeError) *DecodeError { } buf.WriteRune('\n') + + // Write the line with the error message itself (so it does not have a line + // number). + buf.WriteString(strings.Repeat(" ", lineColumnWidth)) buf.WriteString("| ") @@ -157,6 +164,8 @@ func wrapDecodeError(document []byte, de *decodeError) *DecodeError { buf.WriteString(errMessage) } + // Write the lines of context strictly after the error. + for i := 1; i < len(after); i++ { buf.WriteRune('\n') line := errLine + i @@ -230,7 +239,7 @@ forward: rest = rest[o+1:] o = 0 - case o == len(rest)-1 && o > 0: + case o == len(rest)-1: // add last line only if it's non-empty afterLines = append(afterLines, rest) diff --git a/errors_test.go b/errors_test.go index d098647..1c02595 100644 --- a/errors_test.go +++ b/errors_test.go @@ -148,6 +148,13 @@ line 5`, 6| 7| line 4`, }, + { + desc: "handle remainder of the error line when there is only one line", + doc: [3]string{`P=`, `[`, `#`}, + msg: "array is incomplete", + expected: `1| P=[# + | ~ array is incomplete`, + }, } for _, e := range examples {