From 86ac4ee6736a21f11bbd94e6fb686b9c3a940ee1 Mon Sep 17 00:00:00 2001 From: c9s Date: Thu, 14 Nov 2024 12:06:18 +0800 Subject: [PATCH] slacknotifier: optimize object name for comparison summary --- pkg/notifier/slacknotifier/slack.go | 18 +++++++++++++++++- pkg/notifier/slacknotifier/slack_test.go | 22 ++++++++++++++++++++++ 2 files changed, 39 insertions(+), 1 deletion(-) create mode 100644 pkg/notifier/slacknotifier/slack_test.go diff --git a/pkg/notifier/slacknotifier/slack.go b/pkg/notifier/slacknotifier/slack.go index ba5f9d06c..b3d040243 100644 --- a/pkg/notifier/slacknotifier/slack.go +++ b/pkg/notifier/slacknotifier/slack.go @@ -521,7 +521,7 @@ func diffsToComment(obj any, diffs []dynamic.Diff) (text string) { return text } - text += fmt.Sprintf("%T updated\n", obj) + text += fmt.Sprintf("_%s_ updated\n", objectName(obj)) for _, diff := range diffs { text += fmt.Sprintf("- %s: `%s` transited to `%s`\n", diff.Field, diff.Before, diff.After) @@ -529,3 +529,19 @@ func diffsToComment(obj any, diffs []dynamic.Diff) (text string) { return text } + +var typeNamePrefixRE = regexp.MustCompile("^\\*?([a-zA-Z0-9_]+\\.)?") + +func objectName(obj any) string { + type labelInf interface { + Label() string + } + + if ll, ok := obj.(labelInf); ok { + return ll.Label() + } + + typeName := fmt.Sprintf("%T", obj) + typeName = typeNamePrefixRE.ReplaceAllString(typeName, "") + return typeName +} diff --git a/pkg/notifier/slacknotifier/slack_test.go b/pkg/notifier/slacknotifier/slack_test.go new file mode 100644 index 000000000..1528aa26d --- /dev/null +++ b/pkg/notifier/slacknotifier/slack_test.go @@ -0,0 +1,22 @@ +package slacknotifier + +import ( + "testing" + + "github.com/stretchr/testify/assert" + + "github.com/c9s/bbgo/pkg/types" +) + +func Test_objectName(t *testing.T) { + t.Run("deposit", func(t *testing.T) { + var deposit = &types.Deposit{} + assert.Equal(t, "Deposit", objectName(deposit)) + }) + + t.Run("local type", func(t *testing.T) { + type A struct{} + var obj = &A{} + assert.Equal(t, "A", objectName(obj)) + }) +}