-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathfileWithLineNum.go
56 lines (44 loc) · 970 Bytes
/
fileWithLineNum.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
package timber
import (
"fmt"
"os"
"path/filepath"
"runtime"
"strings"
)
const github = "github.com/designsbysm"
func fileWithLineNum(flag int) string {
if flag == 0 {
return ""
}
file, line := getCaller()
if file == "" {
return ""
}
if flag&FlagFileName != 0 {
file = filepath.Base(file)
} else if flag&FlagFileProject != 0 {
current, err := os.Getwd()
if err != nil {
return ""
}
file = strings.TrimPrefix(file, current)
if strings.Contains(file, github) {
parts := strings.Split(file, github)
file = parts[1]
}
}
file = strings.TrimPrefix(file, "/")
return fmt.Sprintf("%s:%d", file, line)
}
func getCaller() (string, int) {
for i := 0; i < 15; i++ {
_, file, line, ok := runtime.Caller(i)
if ok && !strings.HasSuffix(file, "fileWithLineNum.go") && !strings.HasSuffix(file, "write.go") && !strings.HasSuffix(file, "helpers.go") {
return file, line
} else if !ok {
return "", 0
}
}
return "", 0
}