github.com/camlistore/go4@v0.0.0-20200104003542-c7e774b10ea0/errorutil/highlight.go (about) 1 /* 2 Copyright 2011 Google Inc. 3 4 Licensed under the Apache License, Version 2.0 (the "License"); 5 you may not use this file except in compliance with the License. 6 You may obtain a copy of the License at 7 8 http://www.apache.org/licenses/LICENSE-2.0 9 10 Unless required by applicable law or agreed to in writing, software 11 distributed under the License is distributed on an "AS IS" BASIS, 12 WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 See the License for the specific language governing permissions and 14 limitations under the License. 15 */ 16 17 // Package errorutil helps make better error messages. 18 package errorutil // import "go4.org/errorutil" 19 20 import ( 21 "bufio" 22 "bytes" 23 "fmt" 24 "io" 25 "strings" 26 ) 27 28 // HighlightBytePosition takes a reader and the location in bytes of a parse 29 // error (for instance, from json.SyntaxError.Offset) and returns the line, column, 30 // and pretty-printed context around the error with an arrow indicating the exact 31 // position of the syntax error. 32 func HighlightBytePosition(f io.Reader, pos int64) (line, col int, highlight string) { 33 line = 1 34 br := bufio.NewReader(f) 35 lastLine := "" 36 thisLine := new(bytes.Buffer) 37 for n := int64(0); n < pos; n++ { 38 b, err := br.ReadByte() 39 if err != nil { 40 break 41 } 42 if b == '\n' { 43 lastLine = thisLine.String() 44 thisLine.Reset() 45 line++ 46 col = 1 47 } else { 48 col++ 49 thisLine.WriteByte(b) 50 } 51 } 52 if line > 1 { 53 highlight += fmt.Sprintf("%5d: %s\n", line-1, lastLine) 54 } 55 highlight += fmt.Sprintf("%5d: %s\n", line, thisLine.String()) 56 highlight += fmt.Sprintf("%s^\n", strings.Repeat(" ", col+5)) 57 return 58 }