-
Notifications
You must be signed in to change notification settings - Fork 0
/
traceutil.go
59 lines (52 loc) · 1.62 KB
/
traceutil.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
package traceutil
import (
"path/filepath"
"runtime"
"strings"
)
var wharfCoreDir string
func init() {
// file: /some/path/to/repo/wharf-core/internal/traceutil/traceutil.go
_, file, _, ok := runtime.Caller(0)
if ok {
// filepath.Dir(file)^1: /some/path/to/repo/wharf-core/internal/traceutil
// filepath.Dir(file)^2: /some/path/to/repo/wharf-core/internal
// filepath.Dir(file)^3: /some/path/to/repo/wharf-core
wharfCoreDir = filepath.Dir(filepath.Dir(filepath.Dir(file)))
} else {
// no file will start with null char
wharfCoreDir = "\x00"
}
}
// CallerFileWithLineNum returns the filename with its direct parent directory,
// as well as the line number.
//
// This is done by traversing the call stack up from the caller of the caller of
// this function and ignoring all paths from inside this repository
// (wharf-core). unless it's also a test file ("*_test.go")
func CallerFileWithLineNum() (string, int) {
const (
// start on 2 to disregard this func and caller of this func
startDepth = 2
// the max is mostly arbitrary, but we don't want an infinite loop
maxDepth = 15
)
for i := startDepth; i <= maxDepth; i++ {
_, path, line, ok := runtime.Caller(i)
if ok && isValidCallerFile(path) {
return fileAndLastDir(path), line
}
}
return "", 0
}
func isValidCallerFile(path string) bool {
return strings.HasSuffix(path, "_test.go") || !strings.HasPrefix(path, wharfCoreDir)
}
func fileAndLastDir(path string) string {
const unknownDir = "???" + string(filepath.Separator)
dir, file := filepath.Split(path)
if dir == "" {
return unknownDir + file
}
return filepath.Join(filepath.Base(dir), file)
}