-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathutil.go
More file actions
97 lines (83 loc) · 1.89 KB
/
util.go
File metadata and controls
97 lines (83 loc) · 1.89 KB
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
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
package wraperr
import (
"bufio"
"go/ast"
"go/token"
"go/types"
"os"
"strings"
)
var (
genHdr = "// Code generated "
genFtr = " DO NOT EDIT."
errorType *types.Interface
)
func init() {
errorType = types.Universe.Lookup("error").Type().Underlying().(*types.Interface)
}
func isErrorType(t types.Type) bool {
return t != nil && types.Implements(t, errorType)
}
// https://golang.org/s/generatedcode
func isGeneratedFile(f *ast.File) bool {
for _, cg := range f.Comments {
for _, c := range cg.List {
src := c.Text
// from https://github.com/golang/lint/blob/06c8688daad7faa9da5a0c2f163a3d14aac986ca/lint.go#L129
if strings.HasPrefix(src, genHdr) && strings.HasSuffix(src, genFtr) && len(src) >= len(genHdr)+len(genFtr) {
return true
}
}
}
return false
}
func isTestFile(fset *token.FileSet, f *ast.File) bool {
return strings.HasSuffix(fset.File(f.Pos()).Name(), "_test.go")
}
func sprintInlineCode(s string) string {
cc := 1
c := cc
for _, r := range s {
if r == '`' {
cc++
if cc > c {
c = cc
}
} else {
cc = 1
}
}
q := strings.Repeat("`", c)
return q + s + q
}
type fileReader struct {
fset *token.FileSet
lines map[string][]string
}
func newFileReader(fset *token.FileSet) *fileReader {
return &fileReader{
fset: fset,
lines: make(map[string][]string),
}
}
// ref: https://github.com/kisielk/errcheck/blob/1787c4bee836470bf45018cfbc783650db3c6501/internal/errcheck/errcheck.go#L488-L498
func (r *fileReader) GetLine(tp token.Pos) string {
pos := r.fset.Position(tp)
foundLines, ok := r.lines[pos.Filename]
if !ok {
f, err := os.Open(pos.Filename)
if err == nil {
sc := bufio.NewScanner(f)
for sc.Scan() {
foundLines = append(foundLines, sc.Text())
}
r.lines[pos.Filename] = foundLines
f.Close()
}
}
line := "??"
if pos.Line-1 < len(foundLines) {
line = strings.TrimSpace(foundLines[pos.Line-1])
}
return line
}