diff options
author | Ryo Nihei <nihei.dev@gmail.com> | 2021-07-17 13:41:44 +0900 |
---|---|---|
committer | Ryo Nihei <nihei.dev@gmail.com> | 2021-07-17 13:41:44 +0900 |
commit | 2d3fed9f2992a11ab76601484a735d5500d84dba (patch) | |
tree | 643e1995e7b012af1fc0ff48e3bcb1b0ec95489b /error | |
parent | Add a line number to token error messages (diff) | |
download | cotia-2d3fed9f2992a11ab76601484a735d5500d84dba.tar.gz cotia-2d3fed9f2992a11ab76601484a735d5500d84dba.tar.xz |
Improve syntax error messages
- Add a source file name to error messages.
- Add a line that an error occurred at to error messages.
Diffstat (limited to 'error')
-rw-r--r-- | error/error.go | 52 |
1 files changed, 46 insertions, 6 deletions
diff --git a/error/error.go b/error/error.go index 1745c52..cc4fed5 100644 --- a/error/error.go +++ b/error/error.go @@ -1,15 +1,55 @@ package error -import "fmt" +import ( + "bufio" + "fmt" + "os" + "strings" +) type SpecError struct { - Cause error - Row int + Cause error + FilePath string + SourceName string + Row int } func (e *SpecError) Error() string { - if e.Row == 0 { - return fmt.Sprintf("error: %v", e.Cause) + var b strings.Builder + if e.SourceName != "" { + fmt.Fprintf(&b, "%v: ", e.SourceName) } - return fmt.Sprintf("%v: error: %v", e.Row, e.Cause) + if e.Row != 0 { + fmt.Fprintf(&b, "%v: ", e.Row) + } + fmt.Fprintf(&b, "error: %v", e.Cause) + + line := readLine(e.FilePath, e.Row) + if line != "" { + fmt.Fprintf(&b, "\n %v", line) + } + + return b.String() +} + +func readLine(filePath string, row int) string { + if filePath == "" || row <= 0 { + return "" + } + + f, err := os.Open(filePath) + if err != nil { + return "" + } + + i := 1 + s := bufio.NewScanner(f) + for s.Scan() { + if i == row { + return s.Text() + } + i++ + } + + return "" } |