From eda9d559a2c919d66752910eec8cdd3a1bd07b2e Mon Sep 17 00:00:00 2001 From: lsytj0413 <511121939@qq.com> Date: Mon, 15 Jul 2024 19:06:22 +0800 Subject: [PATCH] fix(1007): return Sel.Name as FuncName when selector is an CallExpr Signed-off-by: lsytj0413 <511121939@qq.com> --- rule/add-constant.go | 9 +++++++-- test/add-constant_test.go | 2 +- testdata/add-constant.go | 15 +++++++++++++++ 3 files changed, 23 insertions(+), 3 deletions(-) diff --git a/rule/add-constant.go b/rule/add-constant.go index 86182623a..73dfa932c 100644 --- a/rule/add-constant.go +++ b/rule/add-constant.go @@ -53,7 +53,7 @@ func (r *AddConstantRule) Apply(file *lint.File, arguments lint.Arguments) []lin onFailure: onFailure, strLits: make(map[string]int), strLitLimit: r.strLitLimit, - allowList: r.allowList, + allowList: r.allowList, ignoreFunctions: r.ignoreFunctions, structTags: make(map[*ast.BasicLit]struct{}), } @@ -72,7 +72,7 @@ type lintAddConstantRule struct { onFailure func(lint.Failure) strLits map[string]int strLitLimit int - allowList allowList + allowList allowList ignoreFunctions []*regexp.Regexp structTags map[*ast.BasicLit]struct{} } @@ -127,6 +127,11 @@ func (*lintAddConstantRule) getFuncName(expr *ast.CallExpr) string { switch prefix := f.X.(type) { case *ast.Ident: return prefix.Name + "." + f.Sel.Name + case *ast.CallExpr: + // If the selector is an CallExpr, like `fn().Info`, we return `.Info` as function name + if f.Sel != nil { + return "." + f.Sel.Name + } } case *ast.Ident: return f.Name diff --git a/test/add-constant_test.go b/test/add-constant_test.go index a8b7d8595..45ce291a0 100644 --- a/test/add-constant_test.go +++ b/test/add-constant_test.go @@ -13,7 +13,7 @@ func TestAddConstant(t *testing.T) { "allowStrs": "\"\"", "allowInts": "0,1,2", "allowFloats": "0.0,1.0", - "ignoreFuncs": "os\\.(CreateFile|WriteFile|Chmod|FindProcess),\\.Println,ignoredFunc", + "ignoreFuncs": "os\\.(CreateFile|WriteFile|Chmod|FindProcess),\\.Println,ignoredFunc,\\.Info", }} testRule(t, "add-constant", &rule.AddConstantRule{}, &lint.RuleConfig{ diff --git a/testdata/add-constant.go b/testdata/add-constant.go index 53eba17a4..527b33c95 100644 --- a/testdata/add-constant.go +++ b/testdata/add-constant.go @@ -1,10 +1,25 @@ package fixtures import ( + "context" "fmt" "os" ) +type testLogger struct{} + +func (l *testLogger) Info(ctx context.Context, msg string) {} + +func getLogger() *testLogger { + return &testLogger{} +} + +func test1007() { + getLogger().Info(context.Background(), "test1007") + getLogger().Info(context.Background(), "test1007") + getLogger().Info(context.Background(), "test1007") +} + func foo(a float32, b string, c any, d int) { a = 1.0 // ignore b = "ignore"