From 4be4c72cd4e5f3876d81c1be50799668fae7083b Mon Sep 17 00:00:00 2001 From: Juan <38849891+xoltia@users.noreply.github.com> Date: Fri, 22 Nov 2024 13:09:36 -0600 Subject: [PATCH] Fix ErrorWithPosition panic when less than two lines --- error.go | 17 ++++++++++++----- error_test.go | 13 +++++++++++++ 2 files changed, 25 insertions(+), 5 deletions(-) diff --git a/error.go b/error.go index 1dd5232..264abdc 100644 --- a/error.go +++ b/error.go @@ -124,17 +124,24 @@ func (pe ParseError) ErrorWithPosition() string { if pe.Position.Line > 2 { fmt.Fprintf(b, "% 7d | %s\n", pe.Position.Line-2, expandTab(lines[pe.Position.Line-3])) } - if pe.Position.Line > 1 { - fmt.Fprintf(b, "% 7d | %s\n", pe.Position.Line-1, expandTab(lines[pe.Position.Line-2])) - } /// Expand tabs, so that the ^^^s are at the correct position, but leave /// "column 10-13" intact. Adjusting this to the visual column would be /// better, but we don't know the tabsize of the user in their editor, which /// can be 8, 4, 2, or something else. We can't know. So leaving it as the /// character index is probably the "most correct". - expanded := expandTab(lines[pe.Position.Line-1]) - diff := len(expanded) - len(lines[pe.Position.Line-1]) + var ( + expanded string + diff int + ) + if pe.Position.Line > 1 { + fmt.Fprintf(b, "% 7d | %s\n", pe.Position.Line-1, expandTab(lines[pe.Position.Line-2])) + expanded = expandTab(lines[pe.Position.Line-1]) + diff = len(expanded) - len(lines[pe.Position.Line-1]) + } else { + expanded = expandTab(lines[0]) + diff = len(expanded) - len(lines[0]) + } fmt.Fprintf(b, "% 7d | %s\n", pe.Position.Line, expanded) fmt.Fprintf(b, "% 10s%s%s\n", "", strings.Repeat(" ", pe.Position.Col-1+diff), strings.Repeat("^", pe.Position.Len)) diff --git a/error_test.go b/error_test.go index d14283e..80cb0c0 100644 --- a/error_test.go +++ b/error_test.go @@ -245,6 +245,19 @@ func TestParseError(t *testing.T) { | 15:04:05.856018510 `, }, + + { + &struct{ String string }{}, + `string = "test`, + ` + | toml: error: unexpected EOF; expected '"' + | + | At line 0, column 14: + | + | 0 | string = "test + | ^ + `, + }, } prep := func(s string) string {