From 6bb1cbca63b1961c0682902731a98cf0896223f5 Mon Sep 17 00:00:00 2001 From: Claudio Costa Date: Thu, 17 Jun 2021 09:22:16 +0200 Subject: [PATCH] Patch bot only if changed (#17766) --- app/bot.go | 4 ++++ model/bot.go | 19 +++++++++++++++++++ model/bot_test.go | 34 ++++++++++++++++++++++++++++++++++ 3 files changed, 57 insertions(+) diff --git a/app/bot.go b/app/bot.go index 6df5db4568..b36c34d86a 100644 --- a/app/bot.go +++ b/app/bot.go @@ -216,6 +216,10 @@ func (a *App) PatchBot(botUserId string, botPatch *model.BotPatch) (*model.Bot, return nil, err } + if !bot.WouldPatch(botPatch) { + return bot, nil + } + bot.Patch(botPatch) user, nErr := a.Srv().Store.User().Get(context.Background(), botUserId) diff --git a/model/bot.go b/model/bot.go index b193fc3d55..e58fc0bea0 100644 --- a/model/bot.go +++ b/model/bot.go @@ -129,6 +129,8 @@ func BotFromJson(data io.Reader) *Bot { } // Patch modifies an existing bot with optional fields from the given patch. +// TODO 6.0: consider returning a boolean to indicate whether or not the patch +// applied any changes. func (b *Bot) Patch(patch *BotPatch) { if patch.Username != nil { b.Username = *patch.Username @@ -143,6 +145,23 @@ func (b *Bot) Patch(patch *BotPatch) { } } +// WouldPatch returns whether or not the given patch would be applied or not. +func (b *Bot) WouldPatch(patch *BotPatch) bool { + if patch == nil { + return false + } + if patch.Username != nil && *patch.Username != b.Username { + return true + } + if patch.DisplayName != nil && *patch.DisplayName != b.DisplayName { + return true + } + if patch.Description != nil && *patch.Description != b.Description { + return true + } + return false +} + // ToJson serializes the bot patch to json. func (b *BotPatch) ToJson() []byte { data, err := json.Marshal(b) diff --git a/model/bot_test.go b/model/bot_test.go index 50dd1e1a32..dbd921674b 100644 --- a/model/bot_test.go +++ b/model/bot_test.go @@ -491,6 +491,40 @@ func TestBotPatch(t *testing.T) { } } +func TestBotWouldPatch(t *testing.T) { + b := &Bot{ + UserId: NewId(), + } + + t.Run("nil patch", func(t *testing.T) { + ok := b.WouldPatch(nil) + require.False(t, ok) + }) + + t.Run("nil patch fields", func(t *testing.T) { + patch := &BotPatch{} + ok := b.WouldPatch(patch) + require.False(t, ok) + }) + + t.Run("patch", func(t *testing.T) { + patch := &BotPatch{ + DisplayName: NewString("BotName"), + } + ok := b.WouldPatch(patch) + require.True(t, ok) + }) + + t.Run("no patch", func(t *testing.T) { + patch := &BotPatch{ + DisplayName: NewString("BotName"), + } + b.Patch(patch) + ok := b.WouldPatch(patch) + require.False(t, ok) + }) +} + func TestBotPatchToAndFromJson(t *testing.T) { botPatch1 := &BotPatch{ Username: sToP("username"),