-
Notifications
You must be signed in to change notification settings - Fork 4
Expand file tree
/
Copy pathstack.go
More file actions
239 lines (209 loc) · 4.96 KB
/
stack.go
File metadata and controls
239 lines (209 loc) · 4.96 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
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
package goerr
import (
"fmt"
"io"
"path"
"runtime"
"strconv"
"strings"
)
// Stack represents function, file and line No of stack trace
type Stack struct {
Func string `json:"func"`
File string `json:"file"`
Line int `json:"line"`
}
// Stacks returns stack trace array generated by pkg/errors
func (x *Error) Stacks() []*Stack {
if x.st == nil {
return nil
}
stacks := make([]*Stack, 0, len(*x.st))
for _, pc := range *x.st {
f := newFrame(pc)
stacks = append(stacks, &Stack{
Func: f.getFunctionName(),
File: f.getFilePath(),
Line: f.getLineNumber(),
})
}
return stacks
}
// StackTrace returns stack trace that is compatible with pkg/errors
func (x *Error) StackTrace() StackTrace {
if x.st == nil {
return nil
}
return x.st.toStackTrace()
}
// frame represents a single stack frame
type frame uintptr
// stack represents a stack of program counters
type stack []uintptr
// StackTrace is array of frame. It's exported for compatibility with github.com/pkg/errors
type StackTrace []frame
// newFrame creates a new frame from program counter
func newFrame(pc uintptr) frame {
return frame(pc - 1)
}
// pc returns the program counter for this frame
func (f frame) pc() uintptr {
return uintptr(f)
}
// getFilePath returns the full path to the file that contains the function
func (f frame) getFilePath() string {
fn := runtime.FuncForPC(f.pc())
if fn == nil {
return "unknown"
}
file, _ := fn.FileLine(f.pc())
return file
}
// getLineNumber returns the line number of source code
func (f frame) getLineNumber() int {
fn := runtime.FuncForPC(f.pc())
if fn == nil {
return 0
}
_, line := fn.FileLine(f.pc())
return line
}
// getFunctionName returns the name of this function
func (f frame) getFunctionName() string {
fn := runtime.FuncForPC(f.pc())
if fn == nil {
return "unknown"
}
return fn.Name()
}
// Format implements fmt.Formatter interface
func (f frame) Format(s fmt.State, verb rune) {
switch verb {
case 's':
if s.Flag('+') {
f.formatWithFunctionName(s)
} else {
f.formatBaseFileName(s)
}
case 'd':
f.formatLineNumber(s)
case 'n':
f.formatShortFunctionName(s)
case 'v':
f.formatVerbose(s)
}
}
func (f frame) formatWithFunctionName(s fmt.State) {
_, _ = io.WriteString(s, f.getFunctionName())
_, _ = io.WriteString(s, "\n\t")
_, _ = io.WriteString(s, f.getFilePath())
}
func (f frame) formatBaseFileName(s fmt.State) {
_, _ = io.WriteString(s, path.Base(f.getFilePath()))
}
func (f frame) formatLineNumber(s fmt.State) {
_, _ = io.WriteString(s, strconv.Itoa(f.getLineNumber()))
}
func (f frame) formatShortFunctionName(s fmt.State) {
_, _ = io.WriteString(s, getShortFunctionName(f.getFunctionName()))
}
func (f frame) formatVerbose(s fmt.State) {
f.Format(s, 's')
_, _ = io.WriteString(s, ":")
f.Format(s, 'd')
}
// MarshalText implements encoding.TextMarshaler interface
func (f frame) MarshalText() ([]byte, error) {
name := f.getFunctionName()
if name == "unknown" {
return []byte(name), nil
}
return []byte(fmt.Sprintf("%s %s:%d", name, f.getFilePath(), f.getLineNumber())), nil
}
// Format implements fmt.Formatter interface for StackTrace
func (st StackTrace) Format(s fmt.State, verb rune) {
switch verb {
case 'v':
if s.Flag('+') {
st.formatVerbose(s)
} else if s.Flag('#') {
st.formatGoSyntax(s)
} else {
st.formatSlice(s, verb)
}
case 's':
st.formatSlice(s, verb)
}
}
func (st StackTrace) formatVerbose(s fmt.State) {
for _, f := range st {
_, _ = io.WriteString(s, "\n")
f.Format(s, 'v')
}
}
func (st StackTrace) formatGoSyntax(s fmt.State) {
fmt.Fprintf(s, "%#v", []frame(st))
}
func (st StackTrace) formatSlice(s fmt.State, verb rune) {
_, _ = io.WriteString(s, "[")
for i, f := range st {
if i > 0 {
_, _ = io.WriteString(s, " ")
}
f.Format(s, verb)
}
_, _ = io.WriteString(s, "]")
}
// Format implements fmt.Formatter interface for stack
func (s *stack) Format(st fmt.State, verb rune) {
if verb == 'v' && st.Flag('+') {
for _, pc := range *s {
f := newFrame(pc)
fmt.Fprintf(st, "\n%+v", f)
}
}
}
// toStackTrace converts stack to StackTrace
func (s *stack) toStackTrace() StackTrace {
if s == nil {
return nil
}
frames := make([]frame, len(*s))
for i, pc := range *s {
frames[i] = newFrame(pc)
}
return frames
}
// unstack trims the stack trace by n frames
func unstack(st *stack, n int) *stack {
if st == nil {
return &stack{}
}
switch {
case n <= 0:
return &stack{}
case n >= len(*st):
return st
default:
trimmed := (*st)[n:]
return &trimmed
}
}
// callers returns the stack of program counters
func callers() *stack {
const depth = 32
var pcs [depth]uintptr
n := runtime.Callers(4, pcs[:])
st := stack(pcs[:n])
return &st
}
// getShortFunctionName removes the path prefix component of a function's name
func getShortFunctionName(name string) string {
parts := strings.Split(name, "/")
lastPart := parts[len(parts)-1]
dotIndex := strings.Index(lastPart, ".")
if dotIndex == -1 {
return lastPart
}
return lastPart[dotIndex+1:]
}