-
Notifications
You must be signed in to change notification settings - Fork 0
/
errors.go
57 lines (46 loc) · 954 Bytes
/
errors.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
package codegen
import (
"bufio"
"bytes"
"fmt"
"math"
)
type CodeFormatError struct {
src []byte
err error
}
func codeFormatError(err error, src []byte) error {
if err == nil {
panic("invalid code format error: nil error passed")
}
if src == nil {
panic("invalid code format error: nil src passed")
}
return CodeFormatError {
err: err,
src: src,
}
}
func (err CodeFormatError) Error() string {
return err.err.Error()
}
// Returns the source code with line numbers
func (err CodeFormatError) Source() string {
n := bytes.Count(err.src, []byte{'\n'})
if n == 0 {
if len(err.src) > 0 {
n = 1
}
}
lineDigits := int(math.Log10(float64(n))) + 1
prefix := fmt.Sprintf("%%0%dd", lineDigits)
var dst bytes.Buffer
scanner := bufio.NewScanner(bytes.NewReader(err.src))
lineno := 1
for scanner.Scan() {
line := scanner.Text()
fmt.Fprintf(&dst, prefix + ": %s\n", lineno, line)
lineno++
}
return dst.String()
}