-
Notifications
You must be signed in to change notification settings - Fork 40
/
code_hunk.go
74 lines (61 loc) · 1.15 KB
/
code_hunk.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
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
package gobrake
import (
"bufio"
"fmt"
"os"
"strconv"
"github.com/airbrake/gobrake/v5/internal/lrucache"
)
var cache = lrucache.New(1000)
func getCode(file string, line int) (map[int]string, error) {
cacheKey := file + strconv.Itoa(line)
v, ok := cache.Get(cacheKey)
if ok {
switch v := v.(type) {
case error:
return nil, v
case map[int]string:
return v, nil
default:
return nil, fmt.Errorf("unsupported type=%T", v)
}
}
lines, err := _getCode(file, line)
if err != nil {
cache.Set(cacheKey, err)
return nil, err
}
return lines, nil
}
func _getCode(file string, line int) (map[int]string, error) {
const nlines = 2
const maxLineLen = 512
fd, err := os.Open(file)
if err != nil {
return nil, err
}
defer fd.Close()
start := line - nlines
end := line + nlines
scanner := bufio.NewScanner(fd)
var i int
lines := make(map[int]string, nlines)
for scanner.Scan() {
i++
if i < start {
continue
}
if i > end {
break
}
line := scanner.Text()
if len(line) > maxLineLen {
line = line[:maxLineLen]
}
lines[i] = line
}
if err := scanner.Err(); err != nil {
return nil, err
}
return lines, nil
}