-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathstacktrace.go
More file actions
92 lines (78 loc) · 2.43 KB
/
stacktrace.go
File metadata and controls
92 lines (78 loc) · 2.43 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
package errx
import (
"fmt"
"os"
"path/filepath"
"runtime"
"sort"
"strings"
)
type stacktrace struct {
file string
function string
line int
}
func newStacktrace() *stacktrace {
// Caller of newStacktrace is newError, New or Wrap, so user's code is 3 up.
pc, file, line, ok := runtime.Caller(3)
if !ok {
return nil
}
file = removeGoPath(file)
st := &stacktrace{
file: file,
line: line,
}
f := runtime.FuncForPC(pc)
if f == nil {
return nil
}
st.function = shortFuncName(f)
return st
}
func (s *stacktrace) String() string {
if s.function != "" {
return fmt.Sprintf(" --- at %v:%v %v()", s.file, s.line, s.function)
} else {
return fmt.Sprintf(" --- at %v:%v", s.file, s.line)
}
}
func shortFuncName(f *runtime.Func) string {
// f.Name() is like one of these:
// - "github.com/palantir/shield/package.FuncName"
// - "github.com/palantir/shield/package.Receiver.MethodName"
// - "github.com/palantir/shield/package.(*PtrReceiver).MethodName"
longName := f.Name()
withoutPath := longName[strings.LastIndex(longName, "/")+1:]
withoutPackage := withoutPath[strings.Index(withoutPath, ".")+1:]
shortName := withoutPackage
shortName = strings.Replace(shortName, "(", "", 1)
shortName = strings.Replace(shortName, "*", "", 1)
shortName = strings.Replace(shortName, ")", "", 1)
return shortName
}
/*
RemoveGoPath makes a path relative to one of the src directories in the $GOPATH
environment variable. If $GOPATH is empty or the input path is not contained
within any of the src directories in $GOPATH, the original path is returned. If
the input path is contained within multiple of the src directories in $GOPATH,
it is made relative to the longest one of them.
*/
func removeGoPath(path string) string {
dirs := filepath.SplitList(os.Getenv("GOPATH"))
// Sort in decreasing order by length so the longest matching prefix is removed
sort.Stable(longestFirst(dirs))
for _, dir := range dirs {
srcdir := filepath.Join(dir, "src")
rel, err := filepath.Rel(srcdir, path)
// filepath.Rel can traverse parent directories, don't want those
if err == nil && !strings.HasPrefix(rel, ".."+string(filepath.Separator)) {
return rel
}
}
return path
}
type longestFirst []string
func (strs longestFirst) Len() int { return len(strs) }
func (strs longestFirst) Less(i, j int) bool { return len(strs[i]) > len(strs[j]) }
func (strs longestFirst) Swap(i, j int) { strs[i], strs[j] = strs[j], strs[i] }