| 1 | // Package stack provides helpers for querying the callstack. |
| 2 | package stack |
| 3 | |
| 4 | import ( |
| 5 | "path" |
| 6 | "runtime" |
| 7 | "strings" |
| 8 | ) |
| 9 | |
| 10 | // Frames returns at most max callstack Frames, starting with its caller and |
| 11 | // skipping skip Frames. |
| 12 | func Frames(skip, max int) []runtime.Frame { |
| 13 | pc := make([]uintptr, max) |
| 14 | n := runtime.Callers(skip+2, pc) |
| 15 | if n == 0 { |
| 16 | return nil |
| 17 | } |
| 18 | pc = pc[:n] |
| 19 | frames := runtime.CallersFrames(pc) |
| 20 | var fs []runtime.Frame |
| 21 | for { |
| 22 | f, more := frames.Next() |
| 23 | fs = append(fs, f) |
| 24 | if !more { |
| 25 | break |
| 26 | } |
| 27 | } |
| 28 | return fs |
| 29 | } |
| 30 | |
| 31 | // Match returns the first stack frame for which the predicate function returns |
| 32 | // true. Returns nil if no match is found. Starts matching after skip frames, |
| 33 | // starting with its caller. |
| 34 | func Match(skip int, predicate func(runtime.Frame) bool) *runtime.Frame { |
| 35 | i, n := skip+1, 16 |
| 36 | for { |
| 37 | fs := Frames(i, n) |
| 38 | for j, f := range fs { |
| 39 | if predicate(f) { |
| 40 | return &fs[j] |
| 41 | } |
| 42 | } |
| 43 | if len(fs) < n { |
| 44 | break |
| 45 | } |
| 46 | i += n |
| 47 | } |
| 48 | return nil |
| 49 | } |
| 50 | |
| 51 | // Main returns the main() function Frame. |
| 52 | func Main() *runtime.Frame { |
| 53 | return Match(1, func(f runtime.Frame) bool { |
| 54 | return f.Function == "main.main" |
| 55 | }) |
| 56 | } |
| 57 | |
| 58 | // ExternalCaller returns the first frame outside the callers package. |
| 59 | func ExternalCaller() *runtime.Frame { |
| 60 | var first *runtime.Frame |
| 61 | return Match(1, func(f runtime.Frame) bool { |
| 62 | if first == nil { |
| 63 | first = &f |
| 64 | } |
| 65 | return pkg(first.Function) != pkg(f.Function) |
| 66 | }) |
| 67 | } |
| 68 | |
| 69 | func pkg(ident string) string { |
| 70 | dir, name := path.Split(ident) |
| 71 | parts := strings.Split(name, ".") |
| 72 | return dir + parts[0] |
| 73 | } |