-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathruntime.go
87 lines (65 loc) · 1.54 KB
/
runtime.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
75
76
77
78
79
80
81
82
83
84
85
86
87
package dbwrap
import (
"context"
"path"
"runtime"
"strings"
)
const (
skipCallers = 6
stackSize = 30
)
type callerCtxKey struct{}
// WithCaller overrides context with pre-defined caller value.
func WithCaller(ctx context.Context, caller string) context.Context {
return context.WithValue(ctx, callerCtxKey{}, caller)
}
// CallerCtx checks context for a pre-defined caller value or returns caller from runtime stack.
func CallerCtx(ctx context.Context, skipPackages ...string) string {
if caller, ok := ctx.Value(callerCtxKey{}).(string); ok {
return caller
}
return Caller(skipPackages...)
}
// Caller returns name and package of closest parent function
// that does not belong to skipped packages.
//
// For example the result could be
//
// pressly/goose.MySQLDialect.dbVersionQuery
func Caller(skipPackages ...string) string {
p := ""
pc := make([]uintptr, stackSize)
runtime.Callers(skipCallers, pc)
frames := runtime.CallersFrames(pc)
for {
frame, more := frames.Next()
if !more {
break
}
fn := frame.Function
// Skip unnamed literals.
if fn == "" || strings.Contains(fn, "{") {
continue
}
parts := strings.Split(fn, "/")
parts[len(parts)-1] = strings.Split(parts[len(parts)-1], ".")[0]
p = strings.Join(parts, "/")
if p == "database/sql" || p == "github.com/bool64/dbwrap" {
continue
}
skip := false
for _, sp := range skipPackages {
if p == sp {
skip = true
break
}
}
if skip {
continue
}
p = path.Base(path.Dir(fn)) + "/" + path.Base(fn)
break
}
return p
}