From 07e894344345653587fda9fa5ce5ae85bc581657 Mon Sep 17 00:00:00 2001 From: daheige Date: Fri, 11 Jun 2021 21:20:19 +0800 Subject: [PATCH] fix FileWithLineNum compatible with various platforms --- utils/utils.go | 8 +++++--- utils/utils_test.go | 4 ++++ 2 files changed, 9 insertions(+), 3 deletions(-) diff --git a/utils/utils.go b/utils/utils.go index 3261138f..6a1e3ade 100644 --- a/utils/utils.go +++ b/utils/utils.go @@ -15,8 +15,9 @@ var gormSourceDir string func init() { _, file, _, _ := runtime.Caller(0) - // 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 + // the separator in the path returned by runtime.Caller is /, + // which is a known problem with go, but for compatibility with the path, + // the filepath.Dir mode is used here gormSourceDir = filepath.Dir(filepath.Dir(file)) } @@ -24,7 +25,8 @@ func init() { func FileWithLineNum() string { for i := 1; i < 15; i++ { _, file, line, ok := runtime.Caller(i) - if ok && (!strings.HasPrefix(file, gormSourceDir) || strings.HasSuffix(file, "_test.go")) { + // compatible with various platforms + if ok && (!strings.HasPrefix(filepath.Dir(file), gormSourceDir) || strings.HasSuffix(file, "_test.go")) { return file + ":" + strconv.FormatInt(int64(line), 10) } } diff --git a/utils/utils_test.go b/utils/utils_test.go index 5737c511..3f0f31d5 100644 --- a/utils/utils_test.go +++ b/utils/utils_test.go @@ -12,3 +12,7 @@ func TestIsValidDBNameChar(t *testing.T) { } } } + +func TestFileWithLineNum(t *testing.T) { + t.Log("file line with num: ", FileWithLineNum()) +}