From b2742c2b187bc5dbcdf57d8356c7ad9f231aa893 Mon Sep 17 00:00:00 2001 From: daheige Date: Mon, 31 May 2021 21:16:52 +0800 Subject: [PATCH] fix FileWithLineNum func and add gormSourceDir unit test --- utils/utils.go | 10 ++++++++-- utils_filenum_test.go | 12 ++++++++++++ 2 files changed, 20 insertions(+), 2 deletions(-) create mode 100644 utils_filenum_test.go diff --git a/utils/utils.go b/utils/utils.go index f1fb8734..5da42f61 100644 --- a/utils/utils.go +++ b/utils/utils.go @@ -3,6 +3,7 @@ package utils import ( "database/sql/driver" "fmt" + "path/filepath" "reflect" "runtime" "strconv" @@ -14,17 +15,22 @@ var gormSourceDir string func init() { _, file, _, _ := runtime.Caller(0) - gormSourceDir = strings.Replace(file, `utils.utils.go`, "", -1) + // Here is the directory to get the gorm source code. Here, the filepath.Dir mode is enough, + // and the filepath is compatible with various operating systems + gormSourceDir = filepath.Dir(filepath.Dir(file)) } +// FileWithLineNum return the file name and line number of the current file func FileWithLineNum() string { - for i := 2; i < 15; i++ { + for i := 1; i < 15; i++ { _, file, line, ok := runtime.Caller(i) + // fmt.Println("file:", file, " line: ", line, "ok: ", ok) if ok && (!strings.HasPrefix(file, gormSourceDir) || strings.HasSuffix(file, "_test.go")) { return file + ":" + strconv.FormatInt(int64(line), 10) } } + return "" } diff --git a/utils_filenum_test.go b/utils_filenum_test.go new file mode 100644 index 00000000..20e5ec88 --- /dev/null +++ b/utils_filenum_test.go @@ -0,0 +1,12 @@ +package gorm + +import ( + "log" + "testing" + + "gorm.io/gorm/utils" +) + +func TestFileWithLineNum(t *testing.T) { + log.Println("FileWithLineNum: ", utils.FileWithLineNum()) +}