Skip to content

Commit

Permalink
Faster utils.FileWithLineNum (#6981)
Browse files Browse the repository at this point in the history
* faster FileWithLineNum

* tweak caller skip count
  • Loading branch information
kkocdko committed Apr 22, 2024
1 parent d0b4ceb commit bc49365
Showing 1 changed file with 10 additions and 6 deletions.
16 changes: 10 additions & 6 deletions utils/utils.go
Original file line number Diff line number Diff line change
Expand Up @@ -32,12 +32,16 @@ func sourceDir(file string) string {

// FileWithLineNum return the file name and line number of the current file
func FileWithLineNum() string {
// the second caller usually from gorm internal, so set i start from 2
for i := 2; i < 15; i++ {
_, file, line, ok := runtime.Caller(i)
if ok && (!strings.HasPrefix(file, gormSourceDir) || strings.HasSuffix(file, "_test.go")) &&
!strings.HasSuffix(file, ".gen.go") {
return file + ":" + strconv.FormatInt(int64(line), 10)
pcs := [13]uintptr{}
// the third caller usually from gorm internal
len := runtime.Callers(3, pcs[:])
frames := runtime.CallersFrames(pcs[:len])
for i := 0; i < len; i++ {
// second return value is "more", not "ok"
frame, _ := frames.Next()
if (!strings.HasPrefix(frame.File, gormSourceDir) ||
strings.HasSuffix(frame.File, "_test.go")) && !strings.HasSuffix(frame.File, ".gen.go") {
return string(strconv.AppendInt(append([]byte(frame.File), ':'), int64(frame.Line), 10))
}
}

Expand Down

0 comments on commit bc49365

Please sign in to comment.