From 717a4d04a925d4969fa3a35fbf633c33e0ad308c Mon Sep 17 00:00:00 2001 From: Ibrahim Serdar Acikgoz Date: Tue, 5 Jul 2022 09:46:50 +0300 Subject: [PATCH] Use any instead of interface{} (#20577) * replace interface{} with any --- api4/apitestlib.go | 2 +- api4/channel.go | 6 +- api4/channel_local.go | 2 +- api4/command_test.go | 12 +-- api4/config.go | 8 +- api4/config_test.go | 2 +- api4/file.go | 6 +- api4/graphql.go | 6 +- api4/integration_action_test.go | 10 +- api4/openGraph_test.go | 2 +- api4/plugin_test.go | 2 +- api4/post.go | 2 +- api4/post_test.go | 16 +-- api4/resolver_channel_member_test.go | 20 ++-- api4/resolver_channel_test.go | 28 ++--- api4/resolver_sidebar_categories_test.go | 6 +- api4/resolver_team_member_test.go | 10 +- api4/resolver_test.go | 2 +- api4/resolver_user_test.go | 4 +- api4/saml.go | 2 +- api4/system.go | 12 +-- api4/team.go | 6 +- api4/team_local.go | 6 +- api4/team_test.go | 10 +- api4/user.go | 6 +- api4/websocket_test.go | 2 +- app/admin.go | 4 +- app/admin_advisor.go | 8 +- app/app_iface.go | 6 +- app/authentication.go | 4 +- app/bot.go | 4 +- app/channel.go | 22 ++-- app/channel_test.go | 52 ++++----- app/channels.go | 4 +- app/cloud.go | 2 +- app/cluster.go | 4 +- app/command.go | 28 ++--- app/config.go | 6 +- app/email/email.go | 80 +++++++------- app/email/email_batching.go | 6 +- app/email/notification_email.go | 2 +- app/emoji.go | 4 +- app/expirynotify.go | 2 +- app/export_test.go | 8 +- app/feature_flags.go | 2 +- app/featureflag/feature_flags_sync.go | 4 +- app/featureflag/split_logger.go | 10 +- app/file.go | 10 +- app/import.go | 2 +- app/import_functions.go | 20 ++-- app/import_validators.go | 4 +- app/integration_action.go | 16 +-- app/integration_action_test.go | 2 +- app/integrations.go | 2 +- app/layer_generators/main.go | 2 +- app/ldap.go | 4 +- app/license.go | 2 +- app/notification.go | 16 +-- app/notification_email.go | 30 +++--- app/notification_push.go | 2 +- app/notification_push_test.go | 4 +- app/notification_test.go | 6 +- app/oauth.go | 16 +-- app/opentracing/opentracing_layer.go | 6 +- app/options.go | 2 +- app/permissions_test.go | 2 +- app/plugin_api.go | 20 ++-- app/plugin_api_test.go | 14 +-- app/plugin_api_tests/basic_config.go | 2 +- .../main.go | 2 +- app/plugin_commands.go | 4 +- app/plugin_commands_test.go | 10 +- app/plugin_db_driver.go | 10 +- app/plugin_deadlock_test.go | 6 +- app/plugin_hooks_test.go | 2 +- app/plugin_install.go | 2 +- app/post.go | 16 +-- app/post_metadata.go | 2 +- app/post_metadata_test.go | 48 ++++----- app/post_test.go | 20 ++-- app/product.go | 4 +- app/product_notices.go | 4 +- app/product_notices_test.go | 12 +-- app/product_test.go | 10 +- app/request/context.go | 2 +- app/saml.go | 2 +- app/server.go | 2 +- app/server_inactivity.go | 2 +- app/session.go | 12 +-- app/slashcommands/command_channel_header.go | 2 +- .../command_channel_header_test.go | 16 +-- app/slashcommands/command_channel_purpose.go | 2 +- .../command_channel_purpose_test.go | 12 +-- app/slashcommands/command_channel_rename.go | 4 +- .../command_channel_rename_test.go | 12 +-- app/slashcommands/command_code_test.go | 2 +- app/slashcommands/command_custom_status.go | 2 +- app/slashcommands/command_groupmsg.go | 6 +- app/slashcommands/command_invite.go | 14 +-- .../command_invite_people_test.go | 2 +- app/slashcommands/command_invite_test.go | 4 +- app/slashcommands/command_leave.go | 2 +- app/slashcommands/command_leave_test.go | 14 +-- app/slashcommands/command_mute.go | 8 +- app/slashcommands/command_remote.go | 40 +++---- app/slashcommands/command_remove.go | 4 +- app/slashcommands/command_remove_test.go | 14 +-- app/slashcommands/command_share.go | 40 +++---- app/slashcommands/command_share_test.go | 4 +- app/slashcommands/command_test.go | 6 +- app/slashcommands/util.go | 2 +- app/status.go | 6 +- app/syncables.go | 2 +- app/team.go | 14 +-- app/upload.go | 12 +-- app/user.go | 12 +-- app/users/helper_test.go | 2 +- app/users/service.go | 2 +- app/web_conn.go | 2 +- app/webhook.go | 12 +-- app/webhook_test.go | 12 +-- app/webhub_fuzz.go | 4 +- audit/record.go | 6 +- audit/record_test.go | 4 +- cmd/mattermost/commands/main_test.go | 2 +- cmd/mattermost/commands/output.go | 6 +- cmd/mattermost/commands/utils.go | 2 +- cmd/mattermost/commands/utils_test.go | 8 +- config/database.go | 14 +-- config/database_test.go | 36 +++---- config/diff.go | 6 +- config/diff_test.go | 14 +-- config/emitter.go | 4 +- config/environment.go | 20 ++-- config/file_test.go | 28 ++--- config/logger_test.go | 4 +- config/store.go | 4 +- config/utils.go | 4 +- einterfaces/mocks/AppContextInterface.go | 6 +- .../advanced_permissions_phase_2.go | 2 +- jobs/migrations/worker.go | 2 +- jobs/resend_invitation_email/worker.go | 2 +- model/auditconv.go | 2 +- model/auditconv_test.go | 4 +- model/bot.go | 6 +- model/bot_test.go | 2 +- model/channel.go | 48 ++++----- model/channel_member.go | 2 +- model/channel_sidebar.go | 4 +- model/client4.go | 28 ++--- model/client4_test.go | 6 +- model/cloud.go | 14 +-- model/command_autocomplete.go | 14 +-- model/config.go | 54 +++++----- model/config_test.go | 4 +- model/group.go | 8 +- model/group_syncable.go | 2 +- model/integration_action.go | 50 ++++----- model/integration_action_test.go | 18 ++-- model/integrity.go | 12 +-- model/license.go | 4 +- model/link_metadata.go | 4 +- model/manifest.go | 4 +- model/message_export.go | 2 +- model/plugin_key_value.go | 4 +- model/post.go | 16 +-- model/post_embed.go | 2 +- model/post_test.go | 34 +++--- model/product_notices.go | 26 ++--- model/remote_cluster.go | 2 +- model/session.go | 2 +- model/slack_attachment.go | 4 +- model/slack_attachment_test.go | 4 +- model/status.go | 4 +- model/status_test.go | 2 +- model/team_member.go | 2 +- model/terms_of_service.go | 2 +- model/user.go | 2 +- model/utils.go | 30 +++--- model/utils_test.go | 4 +- model/websocket_client.go | 14 +-- model/websocket_client_test.go | 6 +- model/websocket_message.go | 36 +++---- model/websocket_message_test.go | 6 +- model/websocket_request.go | 6 +- plugin/api.go | 16 +-- plugin/api_timer_layer_generated.go | 16 +-- plugin/client.go | 2 +- plugin/client_rpc.go | 42 ++++---- plugin/client_rpc_generated.go | 18 ++-- plugin/environment.go | 10 +- plugin/example_help_test.go | 2 +- plugin/hclog_adapter.go | 18 ++-- plugin/interface_generator/main.go | 6 +- plugin/plugintest/mock/mock.go | 4 +- plugin/stringifier.go | 8 +- plugin/stringifier_test.go | 8 +- product/api.go | 2 +- services/cache/cache.go | 8 +- services/cache/lru.go | 12 +-- services/cache/lru_striped.go | 8 +- services/cache/lru_test.go | 8 +- services/cache/mocks/Cache.go | 16 +-- services/marketplace/client.go | 2 +- services/remotecluster/response.go | 2 +- services/remotecluster/send.go | 2 +- services/remotecluster/service.go | 6 +- services/searchengine/bleveengine/bleve.go | 2 +- services/sharedchannel/mock_AppIface_test.go | 4 +- services/sharedchannel/service.go | 2 +- services/sharedchannel/sync_send.go | 2 +- services/slackimport/slackimport.go | 38 +++---- services/telemetry/telemetry.go | 102 +++++++++--------- services/telemetry/telemetry_test.go | 12 +-- services/tracing/tracing.go | 2 +- shared/i18n/i18n.go | 14 +-- shared/i18n/i18n_test.go | 12 +-- shared/markdown/inspect.go | 2 +- shared/markdown/inspect_test.go | 4 +- shared/markdown/text_range_test.go | 2 +- shared/mlog/graphql.go | 2 +- shared/templates/templates.go | 2 +- shared/templates/templates_test.go | 2 +- store/errors.go | 10 +- store/localcachelayer/layer.go | 4 +- store/sqlstore/adapters.go | 2 +- store/sqlstore/bot_store.go | 2 +- .../sqlstore/channel_member_history_store.go | 2 +- store/sqlstore/channel_store.go | 28 ++--- store/sqlstore/channel_store_categories.go | 10 +- store/sqlstore/compliance_store.go | 10 +- store/sqlstore/file_info_store.go | 2 +- store/sqlstore/group_store.go | 10 +- store/sqlstore/integrity.go | 2 +- store/sqlstore/post_store.go | 32 +++--- store/sqlstore/reaction_store.go | 6 +- store/sqlstore/retention_policy_store.go | 20 ++-- store/sqlstore/sqlx_wrapper.go | 68 ++++++------ store/sqlstore/team_store.go | 12 +-- store/sqlstore/thread_store.go | 4 +- store/sqlstore/user_access_token_store.go | 2 +- store/sqlstore/user_store.go | 12 +-- store/sqlstore/utils.go | 16 +-- store/sqlstore/utils_test.go | 6 +- store/store.go | 2 +- store/storetest/channel_store.go | 20 ++-- store/storetest/compliance_store.go | 4 +- store/storetest/reaction_store.go | 2 +- testlib/helper.go | 2 +- utils/api.go | 2 +- utils/merge.go | 2 +- utils/merge_test.go | 56 +++++----- web/context.go | 6 +- web/unsupported_browser.go | 2 +- wsapi/status.go | 4 +- wsapi/system.go | 4 +- wsapi/user.go | 4 +- wsapi/websocket_handler.go | 8 +- 258 files changed, 1286 insertions(+), 1286 deletions(-) diff --git a/api4/apitestlib.go b/api4/apitestlib.go index ac0c6f4a3b..1caa897a55 100644 --- a/api4/apitestlib.go +++ b/api4/apitestlib.go @@ -999,7 +999,7 @@ func CheckUserSanitization(tb testing.TB, user *model.User) { require.Equal(tb, "", user.MfaSecret, "mfa secret wasn't blank") } -func CheckEtag(tb testing.TB, data interface{}, resp *model.Response) { +func CheckEtag(tb testing.TB, data any, resp *model.Response) { tb.Helper() require.Empty(tb, data) diff --git a/api4/channel.go b/api4/channel.go index b8064e5e8b..34ec2e058a 100644 --- a/api4/channel.go +++ b/api4/channel.go @@ -184,7 +184,7 @@ func updateChannel(c *Context, w http.ResponseWriter, r *http.Request) { if oldChannel.Name == model.DefaultChannelName { if channel.Name != "" && channel.Name != oldChannel.Name { - c.Err = model.NewAppError("updateChannel", "api.channel.update_channel.tried.app_error", map[string]interface{}{"Channel": model.DefaultChannelName}, "", http.StatusBadRequest) + c.Err = model.NewAppError("updateChannel", "api.channel.update_channel.tried.app_error", map[string]any{"Channel": model.DefaultChannelName}, "", http.StatusBadRequest) return } } @@ -340,7 +340,7 @@ func patchChannel(c *Context, w http.ResponseWriter, r *http.Request) { if oldChannel.Name == model.DefaultChannelName { if patch.Name != nil && *patch.Name != oldChannel.Name { - c.Err = model.NewAppError("patchChannel", "api.channel.update_channel.tried.app_error", map[string]interface{}{"Channel": model.DefaultChannelName}, "", http.StatusBadRequest) + c.Err = model.NewAppError("patchChannel", "api.channel.update_channel.tried.app_error", map[string]any{"Channel": model.DefaultChannelName}, "", http.StatusBadRequest) return } } @@ -1694,7 +1694,7 @@ func addChannelMember(c *Context, w http.ResponseWriter, r *http.Request) { return } if len(nonMembers) > 0 { - c.Err = model.NewAppError("addChannelMember", "api.channel.add_members.user_denied", map[string]interface{}{"UserIDs": nonMembers}, "", http.StatusBadRequest) + c.Err = model.NewAppError("addChannelMember", "api.channel.add_members.user_denied", map[string]any{"UserIDs": nonMembers}, "", http.StatusBadRequest) return } } diff --git a/api4/channel_local.go b/api4/channel_local.go index d51e169f6d..8119d956b7 100644 --- a/api4/channel_local.go +++ b/api4/channel_local.go @@ -201,7 +201,7 @@ func localAddChannelMember(c *Context, w http.ResponseWriter, r *http.Request) { return } if len(nonMembers) > 0 { - c.Err = model.NewAppError("localAddChannelMember", "api.channel.add_members.user_denied", map[string]interface{}{"UserIDs": nonMembers}, "", http.StatusBadRequest) + c.Err = model.NewAppError("localAddChannelMember", "api.channel.add_members.user_denied", map[string]any{"UserIDs": nonMembers}, "", http.StatusBadRequest) return } } diff --git a/api4/command_test.go b/api4/command_test.go index f8a5eb12e9..3f493607ff 100644 --- a/api4/command_test.go +++ b/api4/command_test.go @@ -717,7 +717,7 @@ func TestExecuteGetCommand(t *testing.T) { Text: "test get command response", ResponseType: model.CommandResponseTypeInChannel, Type: "custom_test", - Props: map[string]interface{}{"someprop": "somevalue"}, + Props: map[string]any{"someprop": "somevalue"}, } ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { @@ -779,7 +779,7 @@ func TestExecutePostCommand(t *testing.T) { Text: "test post command response", ResponseType: model.CommandResponseTypeInChannel, Type: "custom_test", - Props: map[string]interface{}{"someprop": "somevalue"}, + Props: map[string]any{"someprop": "somevalue"}, } ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { @@ -840,7 +840,7 @@ func TestExecuteCommandAgainstChannelOnAnotherTeam(t *testing.T) { Text: "test post command response", ResponseType: model.CommandResponseTypeInChannel, Type: "custom_test", - Props: map[string]interface{}{"someprop": "somevalue"}, + Props: map[string]any{"someprop": "somevalue"}, } ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { @@ -892,7 +892,7 @@ func TestExecuteCommandAgainstChannelUserIsNotIn(t *testing.T) { Text: "test post command response", ResponseType: model.CommandResponseTypeInChannel, Type: "custom_test", - Props: map[string]interface{}{"someprop": "somevalue"}, + Props: map[string]any{"someprop": "somevalue"}, } ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { @@ -951,7 +951,7 @@ func TestExecuteCommandInDirectMessageChannel(t *testing.T) { Text: "test post command response", ResponseType: model.CommandResponseTypeInChannel, Type: "custom_test", - Props: map[string]interface{}{"someprop": "somevalue"}, + Props: map[string]any{"someprop": "somevalue"}, } ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { @@ -1015,7 +1015,7 @@ func TestExecuteCommandInTeamUserIsNotOn(t *testing.T) { Text: "test post command response", ResponseType: model.CommandResponseTypeInChannel, Type: "custom_test", - Props: map[string]interface{}{"someprop": "somevalue"}, + Props: map[string]any{"someprop": "somevalue"}, } ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { diff --git a/api4/config.go b/api4/config.go index 613df65507..6412c06e43 100644 --- a/api4/config.go +++ b/api4/config.go @@ -164,7 +164,7 @@ func updateConfig(c *Context, w http.ResponseWriter, r *http.Request) { // Both of them cannot be nil since cfg.SetDefaults is called earlier for cfg, // and appCfg is the existing earlier config and if it's nil, server sets a default value. if *appCfg.ComplianceSettings.Directory != *cfg.ComplianceSettings.Directory { - c.Err = model.NewAppError("updateConfig", "api.config.update_config.not_allowed_security.app_error", map[string]interface{}{"Name": "ComplianceSettings.Directory"}, "", http.StatusForbidden) + c.Err = model.NewAppError("updateConfig", "api.config.update_config.not_allowed_security.app_error", map[string]any{"Name": "ComplianceSettings.Directory"}, "", http.StatusForbidden) return } } @@ -281,7 +281,7 @@ func patchConfig(c *Context, w http.ResponseWriter, r *http.Request) { // Do not allow plugin uploads to be toggled through the API if cfg.PluginSettings.EnableUploads != nil && *cfg.PluginSettings.EnableUploads != *appCfg.PluginSettings.EnableUploads { - c.Err = model.NewAppError("patchConfig", "api.config.update_config.not_allowed_security.app_error", map[string]interface{}{"Name": "PluginSettings.EnableUploads"}, "", http.StatusForbidden) + c.Err = model.NewAppError("patchConfig", "api.config.update_config.not_allowed_security.app_error", map[string]any{"Name": "PluginSettings.EnableUploads"}, "", http.StatusForbidden) return } @@ -289,7 +289,7 @@ func patchConfig(c *Context, w http.ResponseWriter, r *http.Request) { if cfg.PluginSettings.MarketplaceURL != nil && cfg.PluginSettings.EnableUploads != nil { // Breaking it down to 2 conditions to make it simple. if *cfg.PluginSettings.MarketplaceURL != *appCfg.PluginSettings.MarketplaceURL && !*cfg.PluginSettings.EnableUploads { - c.Err = model.NewAppError("patchConfig", "api.config.update_config.not_allowed_security.app_error", map[string]interface{}{"Name": "PluginSettings.MarketplaceURL"}, "", http.StatusForbidden) + c.Err = model.NewAppError("patchConfig", "api.config.update_config.not_allowed_security.app_error", map[string]any{"Name": "PluginSettings.MarketplaceURL"}, "", http.StatusForbidden) return } } @@ -302,7 +302,7 @@ func patchConfig(c *Context, w http.ResponseWriter, r *http.Request) { // There are some settings that cannot be changed in a cloud env if c.App.Channels().License() != nil && *c.App.Channels().License().Features.Cloud { if cfg.ComplianceSettings.Directory != nil && *appCfg.ComplianceSettings.Directory != *cfg.ComplianceSettings.Directory { - c.Err = model.NewAppError("patchConfig", "api.config.update_config.not_allowed_security.app_error", map[string]interface{}{"Name": "ComplianceSettings.Directory"}, "", http.StatusForbidden) + c.Err = model.NewAppError("patchConfig", "api.config.update_config.not_allowed_security.app_error", map[string]any{"Name": "ComplianceSettings.Directory"}, "", http.StatusForbidden) return } } diff --git a/api4/config_test.go b/api4/config_test.go index ff3054cc41..7ed50894cc 100644 --- a/api4/config_test.go +++ b/api4/config_test.go @@ -595,7 +595,7 @@ func TestGetEnvironmentConfig(t *testing.T) { serviceSettings, ok := envConfig["ServiceSettings"] require.True(t, ok, "should've returned ServiceSettings") - serviceSettingsAsMap, ok := serviceSettings.(map[string]interface{}) + serviceSettingsAsMap, ok := serviceSettings.(map[string]any) require.True(t, ok, "should've returned ServiceSettings as a map") siteURL, ok := serviceSettingsAsMap["SiteURL"] diff --git a/api4/file.go b/api4/file.go index 17b0de4820..365dd48d09 100644 --- a/api4/file.go +++ b/api4/file.go @@ -254,7 +254,7 @@ NextPart: if err != nil && err != io.EOF { c.Err = model.NewAppError("uploadFileMultipart", "api.file.upload_file.read_form_value.app_error", - map[string]interface{}{"Formname": formname}, + map[string]any{"Formname": formname}, err.Error(), http.StatusBadRequest) return nil } @@ -367,7 +367,7 @@ NextPart: if expectClientIds && len(clientIds) != nFiles { c.Err = model.NewAppError("uploadFileMultipart", "api.file.upload_file.incorrect_number_of_client_ids.app_error", - map[string]interface{}{"NumClientIds": len(clientIds), "NumFiles": nFiles}, + map[string]any{"NumClientIds": len(clientIds), "NumFiles": nFiles}, "", http.StatusBadRequest) return nil } @@ -412,7 +412,7 @@ func uploadFileMultipartLegacy(c *Context, mr *multipart.Reader, if len(clientIds) != 0 && len(clientIds) != len(fileHeaders) { c.Err = model.NewAppError("uploadFilesMultipartBuffered", "api.file.upload_file.incorrect_number_of_client_ids.app_error", - map[string]interface{}{"NumClientIds": len(clientIds), "NumFiles": len(fileHeaders)}, + map[string]any{"NumClientIds": len(clientIds), "NumFiles": len(fileHeaders)}, "", http.StatusBadRequest) return nil } diff --git a/api4/graphql.go b/api4/graphql.go index 9838f64ac4..19d4208227 100644 --- a/api4/graphql.go +++ b/api4/graphql.go @@ -18,9 +18,9 @@ import ( ) type graphQLInput struct { - Query string `json:"query"` - OperationName string `json:"operationName"` - Variables map[string]interface{} `json:"variables"` + Query string `json:"query"` + OperationName string `json:"operationName"` + Variables map[string]any `json:"variables"` } // Unique type to hold our context. diff --git a/api4/integration_action_test.go b/api4/integration_action_test.go index a7c0714b86..975e90ee90 100644 --- a/api4/integration_action_test.go +++ b/api4/integration_action_test.go @@ -65,7 +65,7 @@ func TestPostActionCookies(t *testing.T) { Type: model.PostActionTypeButton, Integration: &model.PostActionIntegration{ URL: server.URL, - Context: map[string]interface{}{ + Context: map[string]any{ "test-key": "test-value", }, }, @@ -80,7 +80,7 @@ func TestPostActionCookies(t *testing.T) { Type: model.PostActionTypeButton, Integration: &model.PostActionIntegration{ URL: server.URL, - Context: map[string]interface{}{ + Context: map[string]any{ "test-key": "test-value", }, }, @@ -95,7 +95,7 @@ func TestPostActionCookies(t *testing.T) { Type: model.PostActionTypeButton, Integration: &model.PostActionIntegration{ URL: server.URL, - Context: map[string]interface{}{ + Context: map[string]any{ "test-key": "test-value", }, }, @@ -112,7 +112,7 @@ func TestPostActionCookies(t *testing.T) { ChannelId: th.BasicChannel.Id, CreateAt: model.GetMillis(), UpdateAt: model.GetMillis(), - Props: map[string]interface{}{ + Props: map[string]any{ "attachments": []*model.SlackAttachment{ { Title: "some-title", @@ -226,7 +226,7 @@ func TestSubmitDialog(t *testing.T) { UserId: th.BasicUser.Id, ChannelId: th.BasicChannel.Id, TeamId: th.BasicTeam.Id, - Submission: map[string]interface{}{"somename": "somevalue"}, + Submission: map[string]any{"somename": "somevalue"}, } ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { diff --git a/api4/openGraph_test.go b/api4/openGraph_test.go index 41d8a3ae55..5faedfc9ae 100644 --- a/api4/openGraph_test.go +++ b/api4/openGraph_test.go @@ -50,7 +50,7 @@ func TestGetOpenGraphMetadata(t *testing.T) { } })) - for _, data := range [](map[string]interface{}){ + for _, data := range [](map[string]any){ {"path": "/og-data/", "title": "Test Title", "cacheMissCount": 1}, {"path": "/no-og-data/", "title": "", "cacheMissCount": 2}, diff --git a/api4/plugin_test.go b/api4/plugin_test.go index 5381be4704..a6382ce32a 100644 --- a/api4/plugin_test.go +++ b/api4/plugin_test.go @@ -342,7 +342,7 @@ func TestNotifyClusterPluginEvent(t *testing.T) { for { select { case resp := <-webSocketClient.EventChannel: - if resp.EventType() == model.WebsocketEventPluginStatusesChanged && len(resp.GetData()["plugin_statuses"].([]interface{})) == 0 { + if resp.EventType() == model.WebsocketEventPluginStatusesChanged && len(resp.GetData()["plugin_statuses"].([]any)) == 0 { done <- true return } diff --git a/api4/post.go b/api4/post.go index 8070055f30..4e63b1b087 100644 --- a/api4/post.go +++ b/api4/post.go @@ -425,7 +425,7 @@ func getPostsByIds(c *Context, w http.ResponseWriter, r *http.Request) { } if len(postIDs) > 1000 { - c.Err = model.NewAppError("getPostsByIds", "api.post.posts_by_ids.invalid_body.request_error", map[string]interface{}{"MaxLength": 1000}, "", http.StatusBadRequest) + c.Err = model.NewAppError("getPostsByIds", "api.post.posts_by_ids.invalid_body.request_error", map[string]any{"MaxLength": 1000}, "", http.StatusBadRequest) return } diff --git a/api4/post_test.go b/api4/post_test.go index 738a89ab95..cd536c11db 100644 --- a/api4/post_test.go +++ b/api4/post_test.go @@ -586,7 +586,7 @@ func TestCreatePostSendOutOfChannelMentions(t *testing.T) { err := json.Unmarshal([]byte(event.GetData()["post"].(string)), &wpost) require.NoError(t, err) - acm, ok := wpost.GetProp(model.PropsAddChannelMember).(map[string]interface{}) + acm, ok := wpost.GetProp(model.PropsAddChannelMember).(map[string]any) require.True(t, ok, "should have received ephemeral post with 'add_channel_member' in props") require.True(t, acm["post_id"] != nil, "should not be nil") require.True(t, acm["user_ids"] != nil, "should not be nil") @@ -2120,7 +2120,7 @@ func TestDeletePostMessage(t *testing.T) { testCases := []struct { description string client *model.Client4 - delete_by interface{} + delete_by any }{ {"Do not send delete_by to regular user", th.Client, nil}, {"Send delete_by to system admin user", th.SystemAdminClient, th.SystemAdminUser.Id}, @@ -2857,7 +2857,7 @@ func TestSetPostUnreadWithoutCollapsedThreads(t *testing.T) { // test websocket event for marking post as unread var caught bool var exit bool - var data map[string]interface{} + var data map[string]any for { select { case ev := <-userWSClient.EventChannel: @@ -3105,7 +3105,7 @@ func TestGetPostStripActionIntegrations(t *testing.T) { Name: "test-name", Integration: &model.PostActionIntegration{ URL: "https://test.test/action", - Context: map[string]interface{}{ + Context: map[string]any{ "test-ctx": "some-value", }, }, @@ -3120,13 +3120,13 @@ func TestGetPostStripActionIntegrations(t *testing.T) { actualPost, _, err := client.GetPost(rpost.Id, "") require.NoError(t, err) - attachments, _ := actualPost.Props["attachments"].([]interface{}) + attachments, _ := actualPost.Props["attachments"].([]any) require.Equal(t, 1, len(attachments)) - att, _ := attachments[0].(map[string]interface{}) + att, _ := attachments[0].(map[string]any) require.NotNil(t, att) - actions, _ := att["actions"].([]interface{}) + actions, _ := att["actions"].([]any) require.Equal(t, 1, len(actions)) - action, _ := actions[0].(map[string]interface{}) + action, _ := actions[0].(map[string]any) require.NotNil(t, action) // integration must be omitted require.Nil(t, action["integration"]) diff --git a/api4/resolver_channel_member_test.go b/api4/resolver_channel_member_test.go index a4b622d5e2..cc6b6778f2 100644 --- a/api4/resolver_channel_member_test.go +++ b/api4/resolver_channel_member_test.go @@ -182,7 +182,7 @@ func TestGraphQLChannelMembers(t *testing.T) { } } `, - Variables: map[string]interface{}{ + Variables: map[string]any{ "user": model.NewId(), }, } @@ -211,7 +211,7 @@ func TestGraphQLChannelMembers(t *testing.T) { input := graphQLInput{ OperationName: "channelMembers", Query: query, - Variables: map[string]interface{}{ + Variables: map[string]any{ "first": 4, }, } @@ -225,7 +225,7 @@ func TestGraphQLChannelMembers(t *testing.T) { input = graphQLInput{ OperationName: "channelMembers", Query: query, - Variables: map[string]interface{}{ + Variables: map[string]any{ "first": 4, "after": q.ChannelMembers[3].Cursor, }, @@ -240,7 +240,7 @@ func TestGraphQLChannelMembers(t *testing.T) { input = graphQLInput{ OperationName: "channelMembers", Query: query, - Variables: map[string]interface{}{ + Variables: map[string]any{ "first": 4, "after": q.ChannelMembers[3].Cursor, }, @@ -265,7 +265,7 @@ func TestGraphQLChannelMembers(t *testing.T) { input := graphQLInput{ OperationName: "channelMembers", Query: query, - Variables: map[string]interface{}{ + Variables: map[string]any{ "channelId": ch1.Id, "first": 4, }, @@ -281,7 +281,7 @@ func TestGraphQLChannelMembers(t *testing.T) { input = graphQLInput{ OperationName: "channelMembers", Query: query, - Variables: map[string]interface{}{ + Variables: map[string]any{ "channelId": model.NewId(), "first": 3, }, @@ -304,7 +304,7 @@ func TestGraphQLChannelMembers(t *testing.T) { input := graphQLInput{ OperationName: "channelMembers", Query: query, - Variables: map[string]interface{}{ + Variables: map[string]any{ "teamId": th.BasicTeam.Id, }, } @@ -318,7 +318,7 @@ func TestGraphQLChannelMembers(t *testing.T) { input = graphQLInput{ OperationName: "channelMembers", Query: query, - Variables: map[string]interface{}{ + Variables: map[string]any{ "teamId": th.BasicTeam.Id, "excludeTeam": true, }, @@ -347,7 +347,7 @@ func TestGraphQLChannelMembers(t *testing.T) { input := graphQLInput{ OperationName: "channelMembers", Query: query, - Variables: map[string]interface{}{ + Variables: map[string]any{ "first": 4, "lastUpdateAt": float64(now), }, @@ -365,7 +365,7 @@ func TestGraphQLChannelMembers(t *testing.T) { input = graphQLInput{ OperationName: "channelMembers", Query: query, - Variables: map[string]interface{}{ + Variables: map[string]any{ "first": 4, "lastUpdateAt": float64(now), }, diff --git a/api4/resolver_channel_test.go b/api4/resolver_channel_test.go index 323cae156f..f5e7b458cf 100644 --- a/api4/resolver_channel_test.go +++ b/api4/resolver_channel_test.go @@ -128,7 +128,7 @@ func TestGraphQLChannels(t *testing.T) { input := graphQLInput{ OperationName: "channels", Query: query, - Variables: map[string]interface{}{ + Variables: map[string]any{ "userId": u1.Id, }, } @@ -157,7 +157,7 @@ func TestGraphQLChannels(t *testing.T) { input := graphQLInput{ OperationName: "channels", Query: query, - Variables: map[string]interface{}{ + Variables: map[string]any{ "first": 4, }, } @@ -171,7 +171,7 @@ func TestGraphQLChannels(t *testing.T) { input = graphQLInput{ OperationName: "channels", Query: query, - Variables: map[string]interface{}{ + Variables: map[string]any{ "first": 4, "after": q.Channels[3].Cursor, }, @@ -186,7 +186,7 @@ func TestGraphQLChannels(t *testing.T) { input = graphQLInput{ OperationName: "channels", Query: query, - Variables: map[string]interface{}{ + Variables: map[string]any{ "first": 4, "after": q.Channels[3].Cursor, }, @@ -209,7 +209,7 @@ func TestGraphQLChannels(t *testing.T) { input := graphQLInput{ OperationName: "channels", Query: query, - Variables: map[string]interface{}{ + Variables: map[string]any{ "first": 10, "teamId": myTeam.Id, }, @@ -224,7 +224,7 @@ func TestGraphQLChannels(t *testing.T) { input = graphQLInput{ OperationName: "channels", Query: query, - Variables: map[string]interface{}{ + Variables: map[string]any{ "first": 2, "teamId": myTeam.Id, }, @@ -251,7 +251,7 @@ func TestGraphQLChannels(t *testing.T) { input := graphQLInput{ OperationName: "channels", Query: query, - Variables: map[string]interface{}{ + Variables: map[string]any{ "first": 2, "teamId": myTeam.Id, }, @@ -286,7 +286,7 @@ func TestGraphQLChannels(t *testing.T) { input := graphQLInput{ OperationName: "channels", Query: query, - Variables: map[string]interface{}{ + Variables: map[string]any{ "includeDeleted": false, }, } @@ -301,7 +301,7 @@ func TestGraphQLChannels(t *testing.T) { input = graphQLInput{ OperationName: "channels", Query: query, - Variables: map[string]interface{}{ + Variables: map[string]any{ "includeDeleted": true, "lastUpdateAt": float64(now), }, @@ -318,7 +318,7 @@ func TestGraphQLChannels(t *testing.T) { input = graphQLInput{ OperationName: "channels", Query: query, - Variables: map[string]interface{}{ + Variables: map[string]any{ "includeDeleted": true, "lastUpdateAt": float64(now), }, @@ -339,7 +339,7 @@ func TestGraphQLChannels(t *testing.T) { input = graphQLInput{ OperationName: "channels", Query: query, - Variables: map[string]interface{}{ + Variables: map[string]any{ "includeDeleted": false, }, } @@ -353,7 +353,7 @@ func TestGraphQLChannels(t *testing.T) { input = graphQLInput{ OperationName: "channels", Query: query, - Variables: map[string]interface{}{ + Variables: map[string]any{ "includeDeleted": true, "lastDeleteAt": float64(model.GetMillis()), }, @@ -368,7 +368,7 @@ func TestGraphQLChannels(t *testing.T) { input = graphQLInput{ OperationName: "channels", Query: query, - Variables: map[string]interface{}{ + Variables: map[string]any{ "includeDeleted": true, "lastDeleteAt": float64(model.GetMillis()), "first": 5, @@ -396,7 +396,7 @@ func TestGraphQLChannels(t *testing.T) { input := graphQLInput{ OperationName: "channels", Query: query, - Variables: map[string]interface{}{ + Variables: map[string]any{ "first": 10, "teamId": myTeam.Id, }, diff --git a/api4/resolver_sidebar_categories_test.go b/api4/resolver_sidebar_categories_test.go index b53cef4284..2c8b68252c 100644 --- a/api4/resolver_sidebar_categories_test.go +++ b/api4/resolver_sidebar_categories_test.go @@ -42,7 +42,7 @@ func TestGraphQLSidebarCategories(t *testing.T) { } } `, - Variables: map[string]interface{}{ + Variables: map[string]any{ "userId": "me", "teamId": th.BasicTeam.Id, }, @@ -83,7 +83,7 @@ func TestGraphQLSidebarCategories(t *testing.T) { } } `, - Variables: map[string]interface{}{ + Variables: map[string]any{ "userId": "me", "teamId": th.BasicTeam.Id, "excludeTeam": true, @@ -117,7 +117,7 @@ func TestGraphQLSidebarCategories(t *testing.T) { } } `, - Variables: map[string]interface{}{ + Variables: map[string]any{ "userId": "me", "teamId": th.BasicTeam.Id, "excludeTeam": true, diff --git a/api4/resolver_team_member_test.go b/api4/resolver_team_member_test.go index 701f29fba0..45aa49d23b 100644 --- a/api4/resolver_team_member_test.go +++ b/api4/resolver_team_member_test.go @@ -75,7 +75,7 @@ func TestGraphQLTeamMembers(t *testing.T) { } } `, - Variables: map[string]interface{}{ + Variables: map[string]any{ "userId": "me", }, } @@ -128,7 +128,7 @@ func TestGraphQLTeamMembers(t *testing.T) { } } `, - Variables: map[string]interface{}{ + Variables: map[string]any{ "userId": "me", "teamId": th.BasicTeam.Id, }, @@ -180,7 +180,7 @@ func TestGraphQLTeamMembers(t *testing.T) { } } `, - Variables: map[string]interface{}{ + Variables: map[string]any{ "userId": "me", }, } @@ -233,7 +233,7 @@ func TestGraphQLTeamMembers(t *testing.T) { } } `, - Variables: map[string]interface{}{ + Variables: map[string]any{ "userId": "me", "teamId": th.BasicTeam.Id, }, @@ -257,7 +257,7 @@ func TestGraphQLTeamMembers(t *testing.T) { } } `, - Variables: map[string]interface{}{ + Variables: map[string]any{ "userId": "me", }, } diff --git a/api4/resolver_test.go b/api4/resolver_test.go index c28a60f1be..831ae69a53 100644 --- a/api4/resolver_test.go +++ b/api4/resolver_test.go @@ -131,7 +131,7 @@ func TestGraphQLChannelsLeft(t *testing.T) { channelsLeft(userId: $userId, since: $since) } `, - Variables: map[string]interface{}{ + Variables: map[string]any{ "since": model.GetMillis(), }, } diff --git a/api4/resolver_user_test.go b/api4/resolver_user_test.go index 1788da4152..fd65a6c88f 100644 --- a/api4/resolver_user_test.go +++ b/api4/resolver_user_test.go @@ -178,7 +178,7 @@ func TestGraphQLUser(t *testing.T) { } } `, - Variables: map[string]interface{}{ + Variables: map[string]any{ "id": th.BasicUser2.Id, }, } @@ -203,7 +203,7 @@ func TestGraphQLUser(t *testing.T) { } } `, - Variables: map[string]interface{}{ + Variables: map[string]any{ "id": id, }, } diff --git a/api4/saml.go b/api4/saml.go index 27a313e45d..03345a1516 100644 --- a/api4/saml.go +++ b/api4/saml.go @@ -281,6 +281,6 @@ func resetAuthDataToEmail(c *Context, w http.ResponseWriter, r *http.Request) { c.Err = appErr return } - b, _ := json.Marshal(map[string]interface{}{"num_affected": numAffected}) + b, _ := json.Marshal(map[string]any{"num_affected": numAffected}) w.Write(b) } diff --git a/api4/system.go b/api4/system.go index c510286d1f..700f4b8e06 100644 --- a/api4/system.go +++ b/api4/system.go @@ -693,7 +693,7 @@ func upgradeToEnterprise(c *Context, w http.ResponseWriter, r *http.Request) { var iaErr *upgrader.InvalidArch switch { case errors.As(err, &ipErr): - params := map[string]interface{}{ + params := map[string]any{ "MattermostUsername": ipErr.MattermostUsername, "FileUsername": ipErr.FileUsername, "Path": ipErr.Path, @@ -729,19 +729,19 @@ func upgradeToEnterpriseStatus(c *Context, w http.ResponseWriter, r *http.Reques } percentage, err := c.App.Srv().UpgradeToE0Status() - var s map[string]interface{} + var s map[string]any if err != nil { var isErr *upgrader.InvalidSignature switch { case errors.As(err, &isErr): appErr := model.NewAppError("upgradeToEnterpriseStatus", "api.upgrade_to_enterprise_status.app_error", nil, err.Error(), http.StatusBadRequest) - s = map[string]interface{}{"percentage": 0, "error": appErr.Message} + s = map[string]any{"percentage": 0, "error": appErr.Message} default: appErr := model.NewAppError("upgradeToEnterpriseStatus", "api.upgrade_to_enterprise_status.signature.app_error", nil, err.Error(), http.StatusBadRequest) - s = map[string]interface{}{"percentage": 0, "error": appErr.Message} + s = map[string]any{"percentage": 0, "error": appErr.Message} } } else { - s = map[string]interface{}{"percentage": percentage, "error": nil} + s = map[string]any{"percentage": percentage, "error": nil} } w.Write([]byte(model.StringInterfaceToJSON(s))) @@ -974,7 +974,7 @@ func getAppliedSchemaMigrations(c *Context, w http.ResponseWriter, r *http.Reque // returns true if the data has nil fields // this is being used for testS3 and testEmail methods -func checkHasNilFields(value interface{}) bool { +func checkHasNilFields(value any) bool { v := reflect.Indirect(reflect.ValueOf(value)) if v.Kind() != reflect.Struct { return false diff --git a/api4/team.go b/api4/team.go index afb7e72999..ae7ffdeb65 100644 --- a/api4/team.go +++ b/api4/team.go @@ -738,7 +738,7 @@ func addTeamMember(c *Context, w http.ResponseWriter, r *http.Request) { return } if len(nonMembers) > 0 { - c.Err = model.NewAppError("addTeamMember", "api.team.add_members.user_denied", map[string]interface{}{"UserIDs": nonMembers}, "", http.StatusBadRequest) + c.Err = model.NewAppError("addTeamMember", "api.team.add_members.user_denied", map[string]any{"UserIDs": nonMembers}, "", http.StatusBadRequest) return } } @@ -851,7 +851,7 @@ func addTeamMembers(c *Context, w http.ResponseWriter, r *http.Request) { return } if len(nonMembers) > 0 { - c.Err = model.NewAppError("addTeamMembers", "api.team.add_members.user_denied", map[string]interface{}{"UserIDs": nonMembers}, "", http.StatusBadRequest) + c.Err = model.NewAppError("addTeamMembers", "api.team.add_members.user_denied", map[string]any{"UserIDs": nonMembers}, "", http.StatusBadRequest) return } } @@ -1185,7 +1185,7 @@ func searchTeams(c *Context, w http.ResponseWriter, r *http.Request) { var payload []byte if props.Page != nil && props.PerPage != nil { - twc := map[string]interface{}{"teams": teams, "total_count": totalCount} + twc := map[string]any{"teams": teams, "total_count": totalCount} payload = model.ToJSON(twc) } else { js, jsonErr := json.Marshal(teams) diff --git a/api4/team_local.go b/api4/team_local.go index 991c537cd1..db29d7fb48 100644 --- a/api4/team_local.go +++ b/api4/team_local.go @@ -97,7 +97,7 @@ func localInviteUsersToTeam(c *Context, w http.ResponseWriter, r *http.Request) for i := range emailList { email := strings.ToLower(emailList[i]) if !model.IsValidEmail(email) { - c.Err = model.NewAppError("localInviteUsersToTeam", "api.team.invite_members.invalid_email.app_error", map[string]interface{}{"Address": email}, "", http.StatusBadRequest) + c.Err = model.NewAppError("localInviteUsersToTeam", "api.team.invite_members.invalid_email.app_error", map[string]any{"Address": email}, "", http.StatusBadRequest) return } emailList[i] = email @@ -145,7 +145,7 @@ func localInviteUsersToTeam(c *Context, w http.ResponseWriter, r *http.Request) Error: nil, } if !isEmailAddressAllowed(email, allowedDomains) { - invite.Error = model.NewAppError("localInviteUsersToTeam", "api.team.invite_members.invalid_email.app_error", map[string]interface{}{"Addresses": email}, "", http.StatusBadRequest) + invite.Error = model.NewAppError("localInviteUsersToTeam", "api.team.invite_members.invalid_email.app_error", map[string]any{"Addresses": email}, "", http.StatusBadRequest) errList = append(errList, model.EmailInviteWithErrorToString(invite)) } else { goodEmails = append(goodEmails, email) @@ -192,7 +192,7 @@ func localInviteUsersToTeam(c *Context, w http.ResponseWriter, r *http.Request) } if len(invalidEmailList) > 0 { s := strings.Join(invalidEmailList, ", ") - c.Err = model.NewAppError("localInviteUsersToTeam", "api.team.invite_members.invalid_email.app_error", map[string]interface{}{"Addresses": s}, "", http.StatusBadRequest) + c.Err = model.NewAppError("localInviteUsersToTeam", "api.team.invite_members.invalid_email.app_error", map[string]any{"Addresses": s}, "", http.StatusBadRequest) return } err := c.App.Srv().EmailService.SendInviteEmails(team, "Administrator", "mmctl "+model.NewId(), emailList, *c.App.Config().ServiceSettings.SiteURL, nil, false) diff --git a/api4/team_test.go b/api4/team_test.go index e063f2162b..3c05daca28 100644 --- a/api4/team_test.go +++ b/api4/team_test.go @@ -3120,7 +3120,7 @@ func TestInviteUsersToTeam(t *testing.T) { require.NoError(t, err) nameFormat := *th.App.Config().TeamSettings.TeammateNameDisplay expectedSubject := i18n.T("api.templates.invite_subject", - map[string]interface{}{"SenderName": th.SystemAdminUser.GetDisplayName(nameFormat), + map[string]any{"SenderName": th.SystemAdminUser.GetDisplayName(nameFormat), "TeamDisplayName": th.BasicTeam.DisplayName, "SiteName": th.App.ClientConfig()["SiteName"]}) checkEmail(t, expectedSubject) @@ -3131,7 +3131,7 @@ func TestInviteUsersToTeam(t *testing.T) { _, _, err = th.SystemAdminClient.InviteUsersToTeamAndChannelsGracefully(th.BasicTeam.Id, []string{user1, user2}, []string{th.BasicChannel.Id}, "") require.NoError(t, err) expectedSubject = i18n.T("api.templates.invite_team_and_channel_subject", - map[string]interface{}{"SenderName": th.SystemAdminUser.GetDisplayName(nameFormat), + map[string]any{"SenderName": th.SystemAdminUser.GetDisplayName(nameFormat), "TeamDisplayName": th.BasicTeam.DisplayName, "ChannelName": th.BasicChannel.DisplayName, "SiteName": th.App.ClientConfig()["SiteName"]}) @@ -3142,7 +3142,7 @@ func TestInviteUsersToTeam(t *testing.T) { _, err = th.LocalClient.InviteUsersToTeam(th.BasicTeam.Id, emailList) require.NoError(t, err) expectedSubject = i18n.T("api.templates.invite_subject", - map[string]interface{}{"SenderName": "Administrator", + map[string]any{"SenderName": "Administrator", "TeamDisplayName": th.BasicTeam.DisplayName, "SiteName": th.App.ClientConfig()["SiteName"]}) checkEmail(t, expectedSubject) @@ -3153,7 +3153,7 @@ func TestInviteUsersToTeam(t *testing.T) { _, _, err = th.LocalClient.InviteUsersToTeamAndChannelsGracefully(th.BasicTeam.Id, []string{user1, user2}, []string{th.BasicChannel.Id}, "") require.NoError(t, err) expectedSubject = i18n.T("api.templates.invite_team_and_channel_subject", - map[string]interface{}{"SenderName": "Administrator", + map[string]any{"SenderName": "Administrator", "TeamDisplayName": th.BasicTeam.DisplayName, "ChannelName": th.BasicChannel.DisplayName, "SiteName": th.App.ClientConfig()["SiteName"]}) @@ -3277,7 +3277,7 @@ func TestInviteGuestsToTeam(t *testing.T) { nameFormat := *th.App.Config().TeamSettings.TeammateNameDisplay expectedSubject := i18n.T("api.templates.invite_guest_subject", - map[string]interface{}{"SenderName": th.SystemAdminUser.GetDisplayName(nameFormat), + map[string]any{"SenderName": th.SystemAdminUser.GetDisplayName(nameFormat), "TeamDisplayName": th.BasicTeam.DisplayName, "SiteName": th.App.ClientConfig()["SiteName"]}) diff --git a/api4/user.go b/api4/user.go index 32de510554..568e1cbbe5 100644 --- a/api4/user.go +++ b/api4/user.go @@ -1210,7 +1210,7 @@ func updateUser(c *Context, w http.ResponseWriter, r *http.Request) { if conflictField != "" { c.Err = model.NewAppError( "updateUser", "api.user.update_user.login_provider_attribute_set.app_error", - map[string]interface{}{"Field": conflictField}, "", http.StatusConflict) + map[string]any{"Field": conflictField}, "", http.StatusConflict) return } @@ -1283,7 +1283,7 @@ func patchUser(c *Context, w http.ResponseWriter, r *http.Request) { if conflictField != "" { c.Err = model.NewAppError( "patchUser", "api.user.patch_user.login_provider_attribute_set.app_error", - map[string]interface{}{"Field": conflictField}, "", http.StatusConflict) + map[string]any{"Field": conflictField}, "", http.StatusConflict) return } @@ -2933,7 +2933,7 @@ func migrateAuthToSaml(c *Context, w http.ResponseWriter, r *http.Request) { c.SetInvalidParam("auto") return } - matches, ok := props["matches"].(map[string]interface{}) + matches, ok := props["matches"].(map[string]any) if !ok { c.SetInvalidParam("matches") return diff --git a/api4/websocket_test.go b/api4/websocket_test.go index 7ff693330b..7655a44f48 100644 --- a/api4/websocket_test.go +++ b/api4/websocket_test.go @@ -267,7 +267,7 @@ func TestWebSocketSendBinary(t *testing.T) { require.True(t, ok) require.Equal(t, model.StatusOnline, status) - WebSocketClient.SendBinaryMessage("get_statuses_by_ids", map[string]interface{}{ + WebSocketClient.SendBinaryMessage("get_statuses_by_ids", map[string]any{ "user_ids": []string{th.BasicUser2.Id}, }) status, ok = resp.Data[th.BasicUser2.Id] diff --git a/app/admin.go b/app/admin.go index 910ef7ea0e..f7e681baf3 100644 --- a/app/admin.go +++ b/app/admin.go @@ -209,7 +209,7 @@ func (a *App) TestSiteURL(siteURL string) *model.AppError { func (a *App) TestEmail(userID string, cfg *model.Config) *model.AppError { if *cfg.EmailSettings.SMTPServer == "" { - return model.NewAppError("testEmail", "api.admin.test_email.missing_server", nil, i18n.T("api.context.invalid_param.app_error", map[string]interface{}{"Name": "SMTPServer"}), http.StatusBadRequest) + return model.NewAppError("testEmail", "api.admin.test_email.missing_server", nil, i18n.T("api.context.invalid_param.app_error", map[string]any{"Name": "SMTPServer"}), http.StatusBadRequest) } // if the user hasn't changed their email settings, fill in the actual SMTP password so that @@ -232,7 +232,7 @@ func (a *App) TestEmail(userID string, cfg *model.Config) *model.AppError { license := a.Srv().License() mailConfig := a.Srv().MailServiceConfig() if err := mail.SendMailUsingConfig(user.Email, T("api.admin.test_email.subject"), T("api.admin.test_email.body"), mailConfig, license != nil && *license.Features.Compliance, "", "", "", ""); err != nil { - return model.NewAppError("testEmail", "app.admin.test_email.failure", map[string]interface{}{"Error": err.Error()}, "", http.StatusInternalServerError) + return model.NewAppError("testEmail", "app.admin.test_email.failure", map[string]any{"Error": err.Error()}, "", http.StatusInternalServerError) } return nil diff --git a/app/admin_advisor.go b/app/admin_advisor.go index e284087a48..6a71e3a83c 100644 --- a/app/admin_advisor.go +++ b/app/admin_advisor.go @@ -156,7 +156,7 @@ func (a *App) NotifyAndSetWarnMetricAck(warnMetricId string, sender *model.User, if !forceAck { if *a.Config().EmailSettings.SMTPServer == "" { - return model.NewAppError("NotifyAndSetWarnMetricAck", "api.email.send_warn_metric_ack.missing_server.app_error", nil, i18n.T("api.context.invalid_param.app_error", map[string]interface{}{"Name": "SMTPServer"}), http.StatusInternalServerError) + return model.NewAppError("NotifyAndSetWarnMetricAck", "api.email.send_warn_metric_ack.missing_server.app_error", nil, i18n.T("api.context.invalid_param.app_error", map[string]any{"Name": "SMTPServer"}), http.StatusInternalServerError) } T := i18n.GetUserTranslations(sender.Locale) data := a.Srv().EmailService.NewEmailTemplateData(sender.Locale) @@ -191,11 +191,11 @@ func (a *App) NotifyAndSetWarnMetricAck(warnMetricId string, sender *model.User, body, err := a.Srv().TemplatesContainer().RenderToString("warn_metric_ack", data) if err != nil { - return model.NewAppError("NotifyAndSetWarnMetricAck", "api.email.send_warn_metric_ack.failure.app_error", map[string]interface{}{"Error": err.Error()}, "", http.StatusInternalServerError) + return model.NewAppError("NotifyAndSetWarnMetricAck", "api.email.send_warn_metric_ack.failure.app_error", map[string]any{"Error": err.Error()}, "", http.StatusInternalServerError) } if err := mail.SendMailUsingConfig(model.MmSupportAdvisorAddress, subject, body, mailConfig, false, "", "", "", sender.Email); err != nil { - return model.NewAppError("NotifyAndSetWarnMetricAck", "api.email.send_warn_metric_ack.failure.app_error", map[string]interface{}{"Error": err.Error()}, "", http.StatusInternalServerError) + return model.NewAppError("NotifyAndSetWarnMetricAck", "api.email.send_warn_metric_ack.failure.app_error", map[string]any{"Error": err.Error()}, "", http.StatusInternalServerError) } } @@ -236,7 +236,7 @@ func (a *App) setWarnMetricsStatusForId(warnMetricId string, status string) *mod Name: warnMetricId, Value: status, }); err != nil { - return model.NewAppError("setWarnMetricsStatusForId", "app.system.warn_metric.store.app_error", map[string]interface{}{"WarnMetricName": warnMetricId}, err.Error(), http.StatusInternalServerError) + return model.NewAppError("setWarnMetricsStatusForId", "app.system.warn_metric.store.app_error", map[string]any{"WarnMetricName": warnMetricId}, err.Error(), http.StatusInternalServerError) } return nil } diff --git a/app/app_iface.go b/app/app_iface.go index 58baa227d8..0e708bf8c3 100644 --- a/app/app_iface.go +++ b/app/app_iface.go @@ -170,7 +170,7 @@ type AppIface interface { GetEmojiStaticURL(emojiName string) (string, *model.AppError) // GetEnvironmentConfig returns a map of configuration keys whose values have been overridden by an environment variable. // If filter is not nil and returns false for a struct field, that field will be omitted. - GetEnvironmentConfig(filter func(reflect.StructField) bool) map[string]interface{} + GetEnvironmentConfig(filter func(reflect.StructField) bool) map[string]any // GetFilteredUsersStats is used to get a count of users based on the set of filters supported by UserCountOptions. GetFilteredUsersStats(options *model.UserCountOptions) (*model.UsersStats, *model.AppError) // GetGroupsByTeam returns the paged list and the total count of group associated to the given team. @@ -540,7 +540,7 @@ type AppIface interface { DoUploadFileExpectModification(c *request.Context, now time.Time, rawTeamId string, rawChannelId string, rawUserId string, rawFilename string, data []byte) (*model.FileInfo, []byte, *model.AppError) DownloadFromURL(downloadURL string) ([]byte, error) EnableUserAccessToken(token *model.UserAccessToken) *model.AppError - EnvironmentConfig(filter func(reflect.StructField) bool) map[string]interface{} + EnvironmentConfig(filter func(reflect.StructField) bool) map[string]any ExportPermissions(w io.Writer) error ExtractContentFromFileInfo(fileInfo *model.FileInfo) error FetchSamlMetadataFromIdp(url string) ([]byte, *model.AppError) @@ -751,7 +751,7 @@ type AppIface interface { GetSiteURL() string GetStatus(userID string) (*model.Status, *model.AppError) GetStatusFromCache(userID string) *model.Status - GetStatusesByIds(userIDs []string) (map[string]interface{}, *model.AppError) + GetStatusesByIds(userIDs []string) (map[string]any, *model.AppError) GetSystemBot() (*model.Bot, *model.AppError) GetTeam(teamID string) (*model.Team, *model.AppError) GetTeamByInviteId(inviteId string) (*model.Team, *model.AppError) diff --git a/app/authentication.go b/app/authentication.go index 6f5c406fcb..f20589cd4e 100644 --- a/app/authentication.go +++ b/app/authentication.go @@ -50,7 +50,7 @@ func (a *App) IsPasswordValid(password string) *model.AppError { var invErr *users.ErrInvalidPassword switch { case errors.As(err, &invErr): - return model.NewAppError("User.IsValid", invErr.Id(), map[string]interface{}{"Min": *a.Config().PasswordSettings.MinimumLength}, "", http.StatusBadRequest) + return model.NewAppError("User.IsValid", invErr.Id(), map[string]any{"Min": *a.Config().PasswordSettings.MinimumLength}, "", http.StatusBadRequest) default: return model.NewAppError("User.IsValid", "app.valid_password_generic.app_error", nil, err.Error(), http.StatusInternalServerError) } @@ -266,7 +266,7 @@ func (a *App) authenticateUser(c *request.Context, user *model.User, password, m if authService == model.UserAuthServiceSaml { authService = strings.ToUpper(authService) } - err := model.NewAppError("login", "api.user.login.use_auth_service.app_error", map[string]interface{}{"AuthService": authService}, "", http.StatusBadRequest) + err := model.NewAppError("login", "api.user.login.use_auth_service.app_error", map[string]any{"AuthService": authService}, "", http.StatusBadRequest) return user, err } diff --git a/app/bot.go b/app/bot.go index 803cd83497..543de8d2e1 100644 --- a/app/bot.go +++ b/app/bot.go @@ -447,7 +447,7 @@ func (a *App) PermanentDeleteBot(botUserId string) *model.AppError { var invErr *store.ErrInvalidInput switch { case errors.As(err, &invErr): - return model.NewAppError("PermanentDeleteBot", "app.bot.permenent_delete.bad_id", map[string]interface{}{"user_id": invErr.Value}, invErr.Error(), http.StatusBadRequest) + return model.NewAppError("PermanentDeleteBot", "app.bot.permenent_delete.bad_id", map[string]any{"user_id": invErr.Value}, invErr.Error(), http.StatusBadRequest) default: // last fallback in case it doesn't map to an existing app error. return model.NewAppError("PatchBot", "app.bot.permanent_delete.internal_error", nil, err.Error(), http.StatusInternalServerError) } @@ -626,7 +626,7 @@ func (a *App) getDisableBotSysadminMessage(user *model.User, userBots model.BotL T := i18n.GetUserTranslations(user.Locale) message = T("app.bot.get_disable_bot_sysadmin_message", - map[string]interface{}{ + map[string]any{ "UserName": user.Username, "NumBots": len(userBots), "BotNames": botList, diff --git a/app/channel.go b/app/channel.go index c1df9e0beb..54ab0be2f0 100644 --- a/app/channel.go +++ b/app/channel.go @@ -188,7 +188,7 @@ func (a *App) CreateChannelWithUser(c *request.Context, channel *model.Channel, } if int64(count+1) > *a.Config().TeamSettings.MaxChannelsPerTeam { - return nil, model.NewAppError("CreateChannelWithUser", "api.channel.create_channel.max_channel_limit.app_error", map[string]interface{}{"MaxChannelsPerTeam": *a.Config().TeamSettings.MaxChannelsPerTeam}, "", http.StatusBadRequest) + return nil, model.NewAppError("CreateChannelWithUser", "api.channel.create_channel.max_channel_limit.app_error", map[string]any{"MaxChannelsPerTeam": *a.Config().TeamSettings.MaxChannelsPerTeam}, "", http.StatusBadRequest) } channel.CreatorId = userID @@ -799,7 +799,7 @@ func (a *App) RestoreChannel(c *request.Context, channel *model.Channel, userID post := &model.Post{ ChannelId: channel.Id, - Message: T("api.channel.restore_channel.unarchived", map[string]interface{}{"Username": user.Username}), + Message: T("api.channel.restore_channel.unarchived", map[string]any{"Username": user.Username}), Type: model.PostTypeChannelRestored, UserId: userID, Props: model.StringInterface{ @@ -820,7 +820,7 @@ func (a *App) RestoreChannel(c *request.Context, channel *model.Channel, userID post := &model.Post{ ChannelId: channel.Id, - Message: i18n.T("api.channel.restore_channel.unarchived", map[string]interface{}{"Username": systemBot.Username}), + Message: i18n.T("api.channel.restore_channel.unarchived", map[string]any{"Username": systemBot.Username}), Type: model.PostTypeChannelRestored, UserId: systemBot.UserId, Props: model.StringInterface{ @@ -1363,7 +1363,7 @@ func (a *App) DeleteChannel(c *request.Context, channel *model.Channel, userID s } if channel.Name == model.DefaultChannelName { - err := model.NewAppError("deleteChannel", "api.channel.delete_channel.cannot.app_error", map[string]interface{}{"Channel": model.DefaultChannelName}, "", http.StatusBadRequest) + err := model.NewAppError("deleteChannel", "api.channel.delete_channel.cannot.app_error", map[string]any{"Channel": model.DefaultChannelName}, "", http.StatusBadRequest) return err } @@ -1457,7 +1457,7 @@ func (a *App) addUserToChannel(user *model.User, channel *model.Channel) (*model return nil, model.NewAppError("addUserToChannel", "api.channel.add_user_to_channel.type.app_error", nil, "", http.StatusInternalServerError) } if len(nonMembers) > 0 { - return nil, model.NewAppError("addUserToChannel", "api.channel.add_members.user_denied", map[string]interface{}{"UserIDs": nonMembers}, "", http.StatusBadRequest) + return nil, model.NewAppError("addUserToChannel", "api.channel.add_members.user_denied", map[string]any{"UserIDs": nonMembers}, "", http.StatusBadRequest) } } @@ -1594,7 +1594,7 @@ func (a *App) AddDirectChannels(teamID string, user *model.User) *model.AppError options := &model.UserGetOptions{InTeamId: teamID, Page: 0, PerPage: 100} profiles, err := a.Srv().Store.User().GetProfiles(options) if err != nil { - return model.NewAppError("AddDirectChannels", "api.user.add_direct_channels_and_forget.failed.error", map[string]interface{}{"UserId": user.Id, "TeamId": teamID, "Error": err.Error()}, "", http.StatusInternalServerError) + return model.NewAppError("AddDirectChannels", "api.user.add_direct_channels_and_forget.failed.error", map[string]any{"UserId": user.Id, "TeamId": teamID, "Error": err.Error()}, "", http.StatusInternalServerError) } var preferences model.Preferences @@ -1619,7 +1619,7 @@ func (a *App) AddDirectChannels(teamID string, user *model.User) *model.AppError } if err := a.Srv().Store.Preference().Save(preferences); err != nil { - return model.NewAppError("AddDirectChannels", "api.user.add_direct_channels_and_forget.failed.error", map[string]interface{}{"UserId": user.Id, "TeamId": teamID, "Error": err.Error()}, "", http.StatusInternalServerError) + return model.NewAppError("AddDirectChannels", "api.user.add_direct_channels_and_forget.failed.error", map[string]any{"UserId": user.Id, "TeamId": teamID, "Error": err.Error()}, "", http.StatusInternalServerError) } return nil @@ -2404,7 +2404,7 @@ func (a *App) removeUserFromChannel(c *request.Context, userIDToRemove string, r if channel.Name == model.DefaultChannelName { if !isGuest { - return model.NewAppError("RemoveUserFromChannel", "api.channel.remove.default.app_error", map[string]interface{}{"Channel": model.DefaultChannelName}, "", http.StatusBadRequest) + return model.NewAppError("RemoveUserFromChannel", "api.channel.remove.default.app_error", map[string]any{"Channel": model.DefaultChannelName}, "", http.StatusBadRequest) } } @@ -2414,7 +2414,7 @@ func (a *App) removeUserFromChannel(c *request.Context, userIDToRemove string, r return model.NewAppError("removeUserFromChannel", "api.channel.remove_user_from_channel.app_error", nil, err.Error(), http.StatusInternalServerError) } if len(nonMembers) == 0 { - return model.NewAppError("removeUserFromChannel", "api.channel.remove_members.denied", map[string]interface{}{"UserIDs": nonMembers}, "", http.StatusBadRequest) + return model.NewAppError("removeUserFromChannel", "api.channel.remove_members.denied", map[string]any{"UserIDs": nonMembers}, "", http.StatusBadRequest) } } @@ -3302,11 +3302,11 @@ func (a *App) FillInChannelsProps(channelList model.ChannelList) *model.AppError } for _, channel := range channelList { - channelMentionsProp := make(map[string]interface{}, len(channelMentions[channel])) + channelMentionsProp := make(map[string]any, len(channelMentions[channel])) for _, channelMention := range channelMentions[channel] { if mentioned, ok := mentionedChannelsByName[channelMention]; ok { if mentioned.Type == model.ChannelTypeOpen { - channelMentionsProp[mentioned.Name] = map[string]interface{}{ + channelMentionsProp[mentioned.Name] = map[string]any{ "display_name": mentioned.DisplayName, } } diff --git a/app/channel_test.go b/app/channel_test.go index 160a22fde3..13f5e27cd5 100644 --- a/app/channel_test.go +++ b/app/channel_test.go @@ -759,7 +759,7 @@ func TestFillInChannelProps(t *testing.T) { testCases := []struct { Description string Channel *model.Channel - ExpectedChannelProps map[string]interface{} + ExpectedChannelProps map[string]any }{ { "channel on basic team without references", @@ -777,9 +777,9 @@ func TestFillInChannelProps(t *testing.T) { Header: "~public1, ~private, ~other-team", Purpose: "~public2, ~private, ~other-team", }, - map[string]interface{}{ - "channel_mentions": map[string]interface{}{ - "public1": map[string]interface{}{ + map[string]any{ + "channel_mentions": map[string]any{ + "public1": map[string]any{ "display_name": "Public 1", }, }, @@ -792,9 +792,9 @@ func TestFillInChannelProps(t *testing.T) { Header: "~public1, ~private, ~other-team", Purpose: "~public2, ~private, ~other-team", }, - map[string]interface{}{ - "channel_mentions": map[string]interface{}{ - "other-team": map[string]interface{}{ + map[string]any{ + "channel_mentions": map[string]any{ + "other-team": map[string]any{ "display_name": "Other Team Channel", }, }, @@ -816,7 +816,7 @@ func TestFillInChannelProps(t *testing.T) { testCases := []struct { Description string Channels model.ChannelList - ExpectedChannelProps map[string]interface{} + ExpectedChannelProps map[string]any }{ { "single channel on basic team", @@ -828,10 +828,10 @@ func TestFillInChannelProps(t *testing.T) { Purpose: "~public2, ~private, ~other-team", }, }, - map[string]interface{}{ - "test": map[string]interface{}{ - "channel_mentions": map[string]interface{}{ - "public1": map[string]interface{}{ + map[string]any{ + "test": map[string]any{ + "channel_mentions": map[string]any{ + "public1": map[string]any{ "display_name": "Public 1", }, }, @@ -860,16 +860,16 @@ func TestFillInChannelProps(t *testing.T) { Purpose: "No references", }, }, - map[string]interface{}{ - "test": map[string]interface{}{ - "channel_mentions": map[string]interface{}{ - "public1": map[string]interface{}{ + map[string]any{ + "test": map[string]any{ + "channel_mentions": map[string]any{ + "public1": map[string]any{ "display_name": "Public 1", }, }, }, - "test2": map[string]interface{}(nil), - "test3": map[string]interface{}(nil), + "test2": map[string]any(nil), + "test3": map[string]any(nil), }, }, { @@ -894,22 +894,22 @@ func TestFillInChannelProps(t *testing.T) { Purpose: "No references", }, }, - map[string]interface{}{ - "test": map[string]interface{}{ - "channel_mentions": map[string]interface{}{ - "public1": map[string]interface{}{ + map[string]any{ + "test": map[string]any{ + "channel_mentions": map[string]any{ + "public1": map[string]any{ "display_name": "Public 1", }, }, }, - "test2": map[string]interface{}{ - "channel_mentions": map[string]interface{}{ - "other-team": map[string]interface{}{ + "test2": map[string]any{ + "channel_mentions": map[string]any{ + "other-team": map[string]any{ "display_name": "Other Team Channel", }, }, }, - "test3": map[string]interface{}(nil), + "test3": map[string]any(nil), }, }, } diff --git a/app/channels.go b/app/channels.go index bc4416f000..42e592098b 100644 --- a/app/channels.go +++ b/app/channels.go @@ -90,7 +90,7 @@ type Channels struct { func init() { RegisterProduct("channels", ProductManifest{ - Initializer: func(s *Server, services map[ServiceKey]interface{}) (Product, error) { + Initializer: func(s *Server, services map[ServiceKey]any) (Product, error) { return NewChannels(s, services) }, Dependencies: map[ServiceKey]struct{}{ @@ -101,7 +101,7 @@ func init() { }) } -func NewChannels(s *Server, services map[ServiceKey]interface{}) (*Channels, error) { +func NewChannels(s *Server, services map[ServiceKey]any) (*Channels, error) { ch := &Channels{ srv: s, imageProxy: imageproxy.MakeImageProxy(s, s.httpService, s.Log), diff --git a/app/cloud.go b/app/cloud.go index 4b2fbb93d3..4d78bdef82 100644 --- a/app/cloud.go +++ b/app/cloud.go @@ -70,7 +70,7 @@ func (a *App) NotifySystemAdminsToUpgrade(c *request.Context, currentUserTeamID } post := &model.Post{ - Message: T("api.cloud.upgrade_plan_bot_message", map[string]interface{}{"TeamName": team.Name}), + Message: T("api.cloud.upgrade_plan_bot_message", map[string]any{"TeamName": team.Name}), UserId: systemBot.UserId, ChannelId: channel.Id, Type: fmt.Sprintf("%sup_notification", model.PostCustomTypePrefix), // webapp will have to create renderer for this custom post type diff --git a/app/cluster.go b/app/cluster.go index 07cf2b95a4..9fcc5bb825 100644 --- a/app/cluster.go +++ b/app/cluster.go @@ -42,7 +42,7 @@ func (s *clusterWrapper) PublishPluginClusterEvent(productID string, ev model.Pl return nil } -func (s *clusterWrapper) PublishWebSocketEvent(productID string, event string, payload map[string]interface{}, broadcast *model.WebsocketBroadcast) { +func (s *clusterWrapper) PublishWebSocketEvent(productID string, event string, payload map[string]any, broadcast *model.WebsocketBroadcast) { ev := model.NewWebSocketEvent(fmt.Sprintf("custom_%v_%v", productID, event), "", "", "", nil) ev = ev.SetBroadcast(broadcast).SetData(payload) s.srv.Publish(ev) @@ -85,7 +85,7 @@ func (s *Server) InvokeClusterLeaderChangedListeners() { // Fixing this would require the changed event to pass the leader directly, but that // requires a lot of work. s.Go(func() { - s.clusterLeaderListeners.Range(func(_, listener interface{}) bool { + s.clusterLeaderListeners.Range(func(_, listener any) bool { listener.(func())() return true }) diff --git a/app/command.go b/app/command.go index 956c6013c6..c943261eae 100644 --- a/app/command.go +++ b/app/command.go @@ -62,7 +62,7 @@ func (a *App) CreateCommandPost(c *request.Context, post *model.Post, teamID str post.CreateAt = model.GetMillis() if strings.HasPrefix(post.Type, model.PostSystemMessagePrefix) { - err := model.NewAppError("CreateCommandPost", "api.context.invalid_param.app_error", map[string]interface{}{"Name": "post.type"}, "", http.StatusBadRequest) + err := model.NewAppError("CreateCommandPost", "api.context.invalid_param.app_error", map[string]any{"Name": "post.type"}, "", http.StatusBadRequest) return nil, err } @@ -192,7 +192,7 @@ func (a *App) ExecuteCommand(c *request.Context, args *model.CommandArgs) (*mode } trigger = strings.ToLower(trigger) if !strings.HasPrefix(trigger, "/") { - return nil, model.NewAppError("command", "api.command.execute_command.format.app_error", map[string]interface{}{"Trigger": trigger}, "", http.StatusBadRequest) + return nil, model.NewAppError("command", "api.command.execute_command.format.app_error", map[string]any{"Trigger": trigger}, "", http.StatusBadRequest) } trigger = strings.TrimPrefix(trigger, "/") @@ -230,7 +230,7 @@ func (a *App) ExecuteCommand(c *request.Context, args *model.CommandArgs) (*mode trigger = trigger[:maxTriggerLen] trigger += "..." } - return nil, model.NewAppError("command", "api.command.execute_command.not_found.app_error", map[string]interface{}{"Trigger": trigger}, "", http.StatusNotFound) + return nil, model.NewAppError("command", "api.command.execute_command.not_found.app_error", map[string]any{"Trigger": trigger}, "", http.StatusNotFound) } // MentionsToTeamMembers returns all the @ mentions found in message that @@ -474,7 +474,7 @@ func (a *App) tryExecuteCustomCommand(args *model.CommandArgs, trigger string, m hook, appErr := a.CreateCommandWebhook(cmd.Id, args) if appErr != nil { - return cmd, nil, model.NewAppError("command", "api.command.execute_command.failed.app_error", map[string]interface{}{"Trigger": trigger}, appErr.Error(), http.StatusInternalServerError) + return cmd, nil, model.NewAppError("command", "api.command.execute_command.failed.app_error", map[string]any{"Trigger": trigger}, appErr.Error(), http.StatusInternalServerError) } p.Set("response_url", args.SiteURL+"/hooks/commands/"+hook.Id) @@ -492,7 +492,7 @@ func (a *App) DoCommandRequest(cmd *model.Command, p url.Values) (*model.Command } if err != nil { - return cmd, nil, model.NewAppError("command", "api.command.execute_command.failed.app_error", map[string]interface{}{"Trigger": cmd.Trigger}, err.Error(), http.StatusInternalServerError) + return cmd, nil, model.NewAppError("command", "api.command.execute_command.failed.app_error", map[string]any{"Trigger": cmd.Trigger}, err.Error(), http.StatusInternalServerError) } if cmd.Method == model.CommandMethodGet { @@ -511,7 +511,7 @@ func (a *App) DoCommandRequest(cmd *model.Command, p url.Values) (*model.Command // Send the request resp, err := a.HTTPService().MakeClient(false).Do(req) if err != nil { - return cmd, nil, model.NewAppError("command", "api.command.execute_command.failed.app_error", map[string]interface{}{"Trigger": cmd.Trigger}, err.Error(), http.StatusInternalServerError) + return cmd, nil, model.NewAppError("command", "api.command.execute_command.failed.app_error", map[string]any{"Trigger": cmd.Trigger}, err.Error(), http.StatusInternalServerError) } defer resp.Body.Close() @@ -523,14 +523,14 @@ func (a *App) DoCommandRequest(cmd *model.Command, p url.Values) (*model.Command // Ignore the error below because the resulting string will just be the empty string if bodyBytes is nil bodyBytes, _ := ioutil.ReadAll(body) - return cmd, nil, model.NewAppError("command", "api.command.execute_command.failed_resp.app_error", map[string]interface{}{"Trigger": cmd.Trigger, "Status": resp.Status}, string(bodyBytes), http.StatusInternalServerError) + return cmd, nil, model.NewAppError("command", "api.command.execute_command.failed_resp.app_error", map[string]any{"Trigger": cmd.Trigger, "Status": resp.Status}, string(bodyBytes), http.StatusInternalServerError) } response, err := model.CommandResponseFromHTTPBody(resp.Header.Get("Content-Type"), body) if err != nil { - return cmd, nil, model.NewAppError("command", "api.command.execute_command.failed.app_error", map[string]interface{}{"Trigger": cmd.Trigger}, err.Error(), http.StatusInternalServerError) + return cmd, nil, model.NewAppError("command", "api.command.execute_command.failed.app_error", map[string]any{"Trigger": cmd.Trigger}, err.Error(), http.StatusInternalServerError) } else if response == nil { - return cmd, nil, model.NewAppError("command", "api.command.execute_command.failed_empty.app_error", map[string]interface{}{"Trigger": cmd.Trigger}, "", http.StatusInternalServerError) + return cmd, nil, model.NewAppError("command", "api.command.execute_command.failed_empty.app_error", map[string]any{"Trigger": cmd.Trigger}, "", http.StatusInternalServerError) } return cmd, response, nil @@ -564,7 +564,7 @@ func (a *App) HandleCommandResponse(c *request.Context, command *model.Command, } if lastError != nil { - return response, model.NewAppError("command", "api.command.execute_command.create_post_failed.app_error", map[string]interface{}{"Trigger": trigger}, "", http.StatusInternalServerError) + return response, model.NewAppError("command", "api.command.execute_command.create_post_failed.app_error", map[string]any{"Trigger": trigger}, "", http.StatusInternalServerError) } return response, nil @@ -681,7 +681,7 @@ func (a *App) GetCommand(commandID string) (*model.Command, *model.AppError) { var nfErr *store.ErrNotFound switch { case errors.As(err, &nfErr): - return nil, model.NewAppError("SqlCommandStore.Get", "store.sql_command.get.missing.app_error", map[string]interface{}{"command_id": commandID}, "", http.StatusNotFound) + return nil, model.NewAppError("SqlCommandStore.Get", "store.sql_command.get.missing.app_error", map[string]any{"command_id": commandID}, "", http.StatusNotFound) default: return nil, model.NewAppError("GetCommand", "app.command.getcommand.internal_error", nil, err.Error(), http.StatusInternalServerError) } @@ -710,7 +710,7 @@ func (a *App) UpdateCommand(oldCmd, updatedCmd *model.Command) (*model.Command, var appErr *model.AppError switch { case errors.As(err, &nfErr): - return nil, model.NewAppError("SqlCommandStore.Update", "store.sql_command.update.missing.app_error", map[string]interface{}{"command_id": updatedCmd.Id}, "", http.StatusNotFound) + return nil, model.NewAppError("SqlCommandStore.Update", "store.sql_command.update.missing.app_error", map[string]any{"command_id": updatedCmd.Id}, "", http.StatusNotFound) case errors.As(err, &appErr): return nil, appErr default: @@ -730,7 +730,7 @@ func (a *App) MoveCommand(team *model.Team, command *model.Command) *model.AppEr var appErr *model.AppError switch { case errors.As(err, &nfErr): - return model.NewAppError("SqlCommandStore.Update", "store.sql_command.update.missing.app_error", map[string]interface{}{"command_id": command.Id}, "", http.StatusNotFound) + return model.NewAppError("SqlCommandStore.Update", "store.sql_command.update.missing.app_error", map[string]any{"command_id": command.Id}, "", http.StatusNotFound) case errors.As(err, &appErr): return appErr default: @@ -754,7 +754,7 @@ func (a *App) RegenCommandToken(cmd *model.Command) (*model.Command, *model.AppE var appErr *model.AppError switch { case errors.As(err, &nfErr): - return nil, model.NewAppError("SqlCommandStore.Update", "store.sql_command.update.missing.app_error", map[string]interface{}{"command_id": cmd.Id}, "", http.StatusNotFound) + return nil, model.NewAppError("SqlCommandStore.Update", "store.sql_command.update.missing.app_error", map[string]any{"command_id": cmd.Id}, "", http.StatusNotFound) case errors.As(err, &appErr): return nil, appErr default: diff --git a/app/config.go b/app/config.go index b86e4f5b9c..86d59afdf8 100644 --- a/app/config.go +++ b/app/config.go @@ -113,11 +113,11 @@ func (a *App) Config() *model.Config { return a.ch.cfgSvc.Config() } -func (s *Server) EnvironmentConfig(filter func(reflect.StructField) bool) map[string]interface{} { +func (s *Server) EnvironmentConfig(filter func(reflect.StructField) bool) map[string]any { return s.configStore.GetEnvironmentOverridesWithFilter(filter) } -func (a *App) EnvironmentConfig(filter func(reflect.StructField) bool) map[string]interface{} { +func (a *App) EnvironmentConfig(filter func(reflect.StructField) bool) map[string]any { return a.Srv().EnvironmentConfig(filter) } @@ -463,7 +463,7 @@ func (a *App) GetSanitizedConfig() *model.Config { // GetEnvironmentConfig returns a map of configuration keys whose values have been overridden by an environment variable. // If filter is not nil and returns false for a struct field, that field will be omitted. -func (a *App) GetEnvironmentConfig(filter func(reflect.StructField) bool) map[string]interface{} { +func (a *App) GetEnvironmentConfig(filter func(reflect.StructField) bool) map[string]any { return a.EnvironmentConfig(filter) } diff --git a/app/email/email.go b/app/email/email.go index 27eb9ab895..27153de375 100644 --- a/app/email/email.go +++ b/app/email/email.go @@ -31,14 +31,14 @@ func (es *Service) SendChangeUsernameEmail(newUsername, email, locale, siteURL s T := i18n.GetUserTranslations(locale) subject := T("api.templates.username_change_subject", - map[string]interface{}{"SiteName": es.config().TeamSettings.SiteName, + map[string]any{"SiteName": es.config().TeamSettings.SiteName, "TeamDisplayName": es.config().TeamSettings.SiteName}) data := es.NewEmailTemplateData(locale) data.Props["SiteURL"] = siteURL data.Props["Title"] = T("api.templates.username_change_body.title") data.Props["Info"] = T("api.templates.username_change_body.info", - map[string]interface{}{"TeamDisplayName": es.config().TeamSettings.SiteName, "NewUsername": newUsername}) + map[string]any{"TeamDisplayName": es.config().TeamSettings.SiteName, "NewUsername": newUsername}) data.Props["Warning"] = T("api.templates.email_warning") body, err := es.templatesContainer.RenderToString("email_change_body", data) @@ -59,14 +59,14 @@ func (es *Service) SendEmailChangeVerifyEmail(newUserEmail, locale, siteURL, tok link := fmt.Sprintf("%s/do_verify_email?token=%s&email=%s", siteURL, token, url.QueryEscape(newUserEmail)) subject := T("api.templates.email_change_verify_subject", - map[string]interface{}{"SiteName": es.config().TeamSettings.SiteName, + map[string]any{"SiteName": es.config().TeamSettings.SiteName, "TeamDisplayName": es.config().TeamSettings.SiteName}) data := es.NewEmailTemplateData(locale) data.Props["SiteURL"] = siteURL data.Props["Title"] = T("api.templates.email_change_verify_body.title") data.Props["Info"] = T("api.templates.email_change_verify_body.info", - map[string]interface{}{"TeamDisplayName": es.config().TeamSettings.SiteName}) + map[string]any{"TeamDisplayName": es.config().TeamSettings.SiteName}) data.Props["VerifyUrl"] = link data.Props["VerifyButton"] = T("api.templates.email_change_verify_body.button") @@ -86,14 +86,14 @@ func (es *Service) SendEmailChangeEmail(oldEmail, newEmail, locale, siteURL stri T := i18n.GetUserTranslations(locale) subject := T("api.templates.email_change_subject", - map[string]interface{}{"SiteName": es.config().TeamSettings.SiteName, + map[string]any{"SiteName": es.config().TeamSettings.SiteName, "TeamDisplayName": es.config().TeamSettings.SiteName}) data := es.NewEmailTemplateData(locale) data.Props["SiteURL"] = siteURL data.Props["Title"] = T("api.templates.email_change_body.title") data.Props["Info"] = T("api.templates.email_change_body.info", - map[string]interface{}{"TeamDisplayName": es.config().TeamSettings.SiteName, "NewEmail": newEmail}) + map[string]any{"TeamDisplayName": es.config().TeamSettings.SiteName, "NewEmail": newEmail}) data.Props["Warning"] = T("api.templates.email_warning") body, err := es.templatesContainer.RenderToString("email_change_body", data) @@ -119,13 +119,13 @@ func (es *Service) SendVerifyEmail(userEmail, locale, siteURL, token, redirect s serverURL := condenseSiteURL(siteURL) subject := T("api.templates.verify_subject", - map[string]interface{}{"SiteName": es.config().TeamSettings.SiteName}) + map[string]any{"SiteName": es.config().TeamSettings.SiteName}) data := es.NewEmailTemplateData(locale) data.Props["SiteURL"] = siteURL data.Props["Title"] = T("api.templates.verify_body.title") data.Props["SubTitle1"] = T("api.templates.verify_body.subTitle1") - data.Props["ServerURL"] = T("api.templates.verify_body.serverURL", map[string]interface{}{"ServerURL": serverURL}) + data.Props["ServerURL"] = T("api.templates.verify_body.serverURL", map[string]any{"ServerURL": serverURL}) data.Props["SubTitle2"] = T("api.templates.verify_body.subTitle2") data.Props["ButtonURL"] = link data.Props["Button"] = T("api.templates.verify_body.button") @@ -150,13 +150,13 @@ func (es *Service) SendSignInChangeEmail(email, method, locale, siteURL string) T := i18n.GetUserTranslations(locale) subject := T("api.templates.signin_change_email.subject", - map[string]interface{}{"SiteName": es.config().TeamSettings.SiteName}) + map[string]any{"SiteName": es.config().TeamSettings.SiteName}) data := es.NewEmailTemplateData(locale) data.Props["SiteURL"] = siteURL data.Props["Title"] = T("api.templates.signin_change_email.body.title") data.Props["Info"] = T("api.templates.signin_change_email.body.info", - map[string]interface{}{"SiteName": es.config().TeamSettings.SiteName, "Method": method}) + map[string]any{"SiteName": es.config().TeamSettings.SiteName, "Method": method}) data.Props["Warning"] = T("api.templates.email_warning") body, err := es.templatesContainer.RenderToString("signin_change_body", data) @@ -184,14 +184,14 @@ func (es *Service) SendWelcomeEmail(userID string, email string, verified bool, serverURL := condenseSiteURL(siteURL) subject := T("api.templates.welcome_subject", - map[string]interface{}{"SiteName": es.config().TeamSettings.SiteName, + map[string]any{"SiteName": es.config().TeamSettings.SiteName, "ServerURL": serverURL}) data := es.NewEmailTemplateData(locale) data.Props["SiteURL"] = siteURL data.Props["Title"] = T("api.templates.welcome_body.title") data.Props["SubTitle1"] = T("api.templates.welcome_body.subTitle1") - data.Props["ServerURL"] = T("api.templates.welcome_body.serverURL", map[string]interface{}{"ServerURL": serverURL}) + data.Props["ServerURL"] = T("api.templates.welcome_body.serverURL", map[string]any{"ServerURL": serverURL}) data.Props["SubTitle2"] = T("api.templates.welcome_body.subTitle2") data.Props["Button"] = T("api.templates.welcome_body.button") data.Props["Info"] = T("api.templates.welcome_body.info") @@ -235,7 +235,7 @@ func (es *Service) SendCloudUpgradeConfirmationEmail(userEmail, name, date, loca data := es.NewEmailTemplateData(locale) data.Props["Title"] = T("api.templates.cloud_upgrade_confirmation.title") - data.Props["SubTitle"] = T("api.templates.cloud_upgrade_confirmation.subtitle", map[string]interface{}{"WorkspaceName": workspaceName, "Date": date}) + data.Props["SubTitle"] = T("api.templates.cloud_upgrade_confirmation.subtitle", map[string]any{"WorkspaceName": workspaceName, "Date": date}) data.Props["SiteURL"] = siteURL data.Props["ButtonURL"] = siteURL data.Props["Button"] = T("api.templates.cloud_welcome_email.button") @@ -269,7 +269,7 @@ func (es *Service) SendCloudWelcomeEmail(userEmail, locale, teamInviteID, workSp data.Props["WorkSpacePath"] = siteURL data.Props["DNS"] = dns data.Props["InviteInfo"] = T("api.templates.cloud_welcome_email.invite_info") - data.Props["InviteSubInfo"] = T("api.templates.cloud_welcome_email.invite_sub_info", map[string]interface{}{"WorkSpace": workSpaceName}) + data.Props["InviteSubInfo"] = T("api.templates.cloud_welcome_email.invite_sub_info", map[string]any{"WorkSpace": workSpaceName}) data.Props["InviteSubInfoLink"] = fmt.Sprintf("%s/signup_user_complete/?id=%s", siteURL, teamInviteID) data.Props["AddAppsInfo"] = T("api.templates.cloud_welcome_email.add_apps_info") data.Props["AddAppsSubInfo"] = T("api.templates.cloud_welcome_email.add_apps_sub_info") @@ -299,14 +299,14 @@ func (es *Service) SendPasswordChangeEmail(email, method, locale, siteURL string T := i18n.GetUserTranslations(locale) subject := T("api.templates.password_change_subject", - map[string]interface{}{"SiteName": es.config().TeamSettings.SiteName, + map[string]any{"SiteName": es.config().TeamSettings.SiteName, "TeamDisplayName": es.config().TeamSettings.SiteName}) data := es.NewEmailTemplateData(locale) data.Props["SiteURL"] = siteURL data.Props["Title"] = T("api.templates.password_change_body.title") data.Props["Info"] = T("api.templates.password_change_body.info", - map[string]interface{}{"TeamDisplayName": es.config().TeamSettings.SiteName, "TeamURL": siteURL, "Method": method}) + map[string]any{"TeamDisplayName": es.config().TeamSettings.SiteName, "TeamURL": siteURL, "Method": method}) data.Props["Warning"] = T("api.templates.email_warning") body, err := es.templatesContainer.RenderToString("password_change_body", data) @@ -325,13 +325,13 @@ func (es *Service) SendUserAccessTokenAddedEmail(email, locale, siteURL string) T := i18n.GetUserTranslations(locale) subject := T("api.templates.user_access_token_subject", - map[string]interface{}{"SiteName": es.config().TeamSettings.SiteName}) + map[string]any{"SiteName": es.config().TeamSettings.SiteName}) data := es.NewEmailTemplateData(locale) data.Props["SiteURL"] = siteURL data.Props["Title"] = T("api.templates.user_access_token_body.title") data.Props["Info"] = T("api.templates.user_access_token_body.info", - map[string]interface{}{"SiteName": es.config().TeamSettings.SiteName, "SiteURL": siteURL}) + map[string]any{"SiteName": es.config().TeamSettings.SiteName, "SiteURL": siteURL}) data.Props["Warning"] = T("api.templates.email_warning") body, err := es.templatesContainer.RenderToString("password_change_body", data) @@ -352,7 +352,7 @@ func (es *Service) SendPasswordResetEmail(email string, token *model.Token, loca link := fmt.Sprintf("%s/reset_password_complete?token=%s", siteURL, url.QueryEscape(token.Token)) subject := T("api.templates.reset_subject", - map[string]interface{}{"SiteName": es.config().TeamSettings.SiteName}) + map[string]any{"SiteName": es.config().TeamSettings.SiteName}) data := es.NewEmailTemplateData(locale) data.Props["SiteURL"] = siteURL @@ -380,16 +380,16 @@ func (es *Service) SendMfaChangeEmail(email string, activated bool, locale, site T := i18n.GetUserTranslations(locale) subject := T("api.templates.mfa_change_subject", - map[string]interface{}{"SiteName": es.config().TeamSettings.SiteName}) + map[string]any{"SiteName": es.config().TeamSettings.SiteName}) data := es.NewEmailTemplateData(locale) data.Props["SiteURL"] = siteURL if activated { - data.Props["Info"] = T("api.templates.mfa_activated_body.info", map[string]interface{}{"SiteURL": siteURL}) + data.Props["Info"] = T("api.templates.mfa_activated_body.info", map[string]any{"SiteURL": siteURL}) data.Props["Title"] = T("api.templates.mfa_activated_body.title") } else { - data.Props["Info"] = T("api.templates.mfa_deactivated_body.info", map[string]interface{}{"SiteURL": siteURL}) + data.Props["Info"] = T("api.templates.mfa_deactivated_body.info", map[string]any{"SiteURL": siteURL}) data.Props["Title"] = T("api.templates.mfa_deactivated_body.title") } data.Props["Warning"] = T("api.templates.email_warning") @@ -424,7 +424,7 @@ func (es *Service) SendInviteEmails(team *model.Team, senderName string, senderU for _, invite := range invites { if invite != "" { subject := i18n.T("api.templates.invite_subject", - map[string]interface{}{"SenderName": senderName, + map[string]any{"SenderName": senderName, "TeamDisplayName": team.DisplayName, "SiteName": es.config().TeamSettings.SiteName}) @@ -447,7 +447,7 @@ func (es *Service) SendInviteEmails(team *model.Team, senderName string, senderU tokenProps["display_name"] = team.DisplayName tokenProps["name"] = team.Name - title := i18n.T("api.templates.invite_body.title", map[string]interface{}{"SenderName": senderName, "TeamDisplayName": team.DisplayName}) + title := i18n.T("api.templates.invite_body.title", map[string]any{"SenderName": senderName, "TeamDisplayName": team.DisplayName}) if reminderData != nil { reminder := i18n.T("api.templates.invite_body.title.reminder") title = fmt.Sprintf("%s: %s", reminder, title) @@ -498,13 +498,13 @@ func (es *Service) SendGuestInviteEmails(team *model.Team, channels []*model.Cha for _, invite := range invites { if invite != "" { subject := i18n.T("api.templates.invite_guest_subject", - map[string]interface{}{"SenderName": senderName, + map[string]any{"SenderName": senderName, "TeamDisplayName": team.DisplayName, "SiteName": es.config().TeamSettings.SiteName}) data := es.NewEmailTemplateData("") data.Props["SiteURL"] = siteURL - data.Props["Title"] = i18n.T("api.templates.invite_body.title", map[string]interface{}{"SenderName": senderName, "TeamDisplayName": team.DisplayName}) + data.Props["Title"] = i18n.T("api.templates.invite_body.title", map[string]any{"SenderName": senderName, "TeamDisplayName": team.DisplayName}) data.Props["SubTitle"] = i18n.T("api.templates.invite_body_guest.subTitle") data.Props["Button"] = i18n.T("api.templates.invite_body.button") data.Props["SenderName"] = senderName @@ -610,13 +610,13 @@ func (es *Service) SendInviteEmailsToTeamAndChannels( channelsLen := len(channels) - subject := i18n.T("api.templates.invite_team_and_channels_subject", map[string]interface{}{ + subject := i18n.T("api.templates.invite_team_and_channels_subject", map[string]any{ "SenderName": senderName, "TeamDisplayName": team.DisplayName, "ChannelsLen": channelsLen, "SiteName": es.config().TeamSettings.SiteName}) - title := i18n.T("api.templates.invite_team_and_channels_body.title", map[string]interface{}{ + title := i18n.T("api.templates.invite_team_and_channels_body.title", map[string]any{ "SenderName": senderName, "ChannelsLen": channelsLen, "TeamDisplayName": team.DisplayName}) @@ -625,13 +625,13 @@ func (es *Service) SendInviteEmailsToTeamAndChannels( channelName := channels[0].DisplayName subject = i18n.T("api.templates.invite_team_and_channel_subject", - map[string]interface{}{"SenderName": senderName, + map[string]any{"SenderName": senderName, "TeamDisplayName": team.DisplayName, "ChannelName": channelName, "SiteName": es.config().TeamSettings.SiteName}, ) - title = i18n.T("api.templates.invite_team_and_channel_body.title", map[string]interface{}{ + title = i18n.T("api.templates.invite_team_and_channel_body.title", map[string]any{ "SenderName": senderName, "ChannelName": channelName, "TeamDisplayName": team.DisplayName, @@ -743,11 +743,11 @@ func (es *Service) NewEmailTemplateData(locale string) templates.Data { } return templates.Data{ - Props: map[string]interface{}{ + Props: map[string]any{ "EmailInfo1": localT("api.templates.email_info1"), "EmailInfo2": localT("api.templates.email_info2"), "EmailInfo3": localT("api.templates.email_info3", - map[string]interface{}{"SiteName": es.config().TeamSettings.SiteName}), + map[string]any{"SiteName": es.config().TeamSettings.SiteName}), "SupportEmail": *es.config().SupportSettings.SupportEmail, "Footer": localT("api.templates.email_footer"), "FooterV2": localT("api.templates.email_footer_v2"), @@ -763,14 +763,14 @@ func (es *Service) SendDeactivateAccountEmail(email string, locale, siteURL stri serverURL := condenseSiteURL(siteURL) subject := T("api.templates.deactivate_subject", - map[string]interface{}{"SiteName": es.config().TeamSettings.SiteName, + map[string]any{"SiteName": es.config().TeamSettings.SiteName, "ServerURL": serverURL}) data := es.NewEmailTemplateData(locale) data.Props["SiteURL"] = siteURL - data.Props["Title"] = T("api.templates.deactivate_body.title", map[string]interface{}{"ServerURL": serverURL}) + data.Props["Title"] = T("api.templates.deactivate_body.title", map[string]any{"ServerURL": serverURL}) data.Props["Info"] = T("api.templates.deactivate_body.info", - map[string]interface{}{"SiteURL": siteURL}) + map[string]any{"SiteURL": siteURL}) data.Props["Warning"] = T("api.templates.deactivate_body.warning") body, err := es.templatesContainer.RenderToString("deactivate_body", data) @@ -879,7 +879,7 @@ func (es *Service) SendLicenseInactivityEmail(email, name, locale, siteURL strin data := es.NewEmailTemplateData(locale) data.Props["SiteURL"] = siteURL data.Props["Title"] = T("api.templates.server_inactivity_title") - data.Props["SubTitle"] = T("api.templates.server_inactivity_subtitle", map[string]interface{}{"Name": name}) + data.Props["SubTitle"] = T("api.templates.server_inactivity_subtitle", map[string]any{"Name": name}) data.Props["InfoBullet"] = T("api.templates.server_inactivity_info_bullet") data.Props["InfoBullet1"] = T("api.templates.server_inactivity_info_bullet1") data.Props["InfoBullet2"] = T("api.templates.server_inactivity_info_bullet2") @@ -901,7 +901,7 @@ func (es *Service) SendLicenseInactivityEmail(email, name, locale, siteURL strin inactivityDurationHours = serverInactivityHours } - data.Props["FooterDisclaimer"] = T("api.templates.server_inactivity_footer_disclaimer", map[string]interface{}{"Hours": inactivityDurationHours}) + data.Props["FooterDisclaimer"] = T("api.templates.server_inactivity_footer_disclaimer", map[string]any{"Hours": inactivityDurationHours}) body, err := es.templatesContainer.RenderToString("inactivity_body", data) if err != nil { @@ -922,7 +922,7 @@ func (es *Service) SendLicenseUpForRenewalEmail(email, name, locale, siteURL, re data := es.NewEmailTemplateData(locale) data.Props["SiteURL"] = siteURL data.Props["Title"] = T("api.templates.license_up_for_renewal_title") - data.Props["SubTitle"] = T("api.templates.license_up_for_renewal_subtitle", map[string]interface{}{"UserName": name, "Days": daysToExpiration}) + data.Props["SubTitle"] = T("api.templates.license_up_for_renewal_subtitle", map[string]any{"UserName": name, "Days": daysToExpiration}) data.Props["SubTitleTwo"] = T("api.templates.license_up_for_renewal_subtitle_two") data.Props["EmailUs"] = T("api.templates.email_us_anytime_at") data.Props["Button"] = T("api.templates.license_up_for_renewal_renew_now") @@ -951,7 +951,7 @@ func (es *Service) SendPaymentFailedEmail(email string, locale string, failedPay data := es.NewEmailTemplateData(locale) data.Props["SiteURL"] = siteURL data.Props["Title"] = T("api.templates.payment_failed.title") - data.Props["Info1"] = T("api.templates.payment_failed.info1", map[string]interface{}{"CardBrand": failedPayment.CardBrand, "LastFour": failedPayment.LastFour}) + data.Props["Info1"] = T("api.templates.payment_failed.info1", map[string]any{"CardBrand": failedPayment.CardBrand, "LastFour": failedPayment.LastFour}) data.Props["Info2"] = T("api.templates.payment_failed.info2") data.Props["Info3"] = T("api.templates.payment_failed.info3") data.Props["Button"] = T("api.templates.over_limit_fix_now") @@ -1005,7 +1005,7 @@ func (es *Service) SendNoCardPaymentFailedEmail(email string, locale string, sit func (es *Service) SendRemoveExpiredLicenseEmail(renewalLink, email string, locale, siteURL string) error { T := i18n.GetUserTranslations(locale) subject := T("api.templates.remove_expired_license.subject", - map[string]interface{}{"SiteName": es.config().TeamSettings.SiteName}) + map[string]any{"SiteName": es.config().TeamSettings.SiteName}) data := es.NewEmailTemplateData(locale) data.Props["SiteURL"] = siteURL diff --git a/app/email/email_batching.go b/app/email/email_batching.go index 1b3b3b324f..ff016c0314 100644 --- a/app/email/email_batching.go +++ b/app/email/email_batching.go @@ -276,7 +276,7 @@ func (es *Service) sendBatchedEmailNotification(userID string, notifications []* tm := time.Unix(notification.post.CreateAt/1000, 0) timezone, _ := tm.Zone() - t := translateFunc("api.email_batching.send_batched_email_notification.time", map[string]interface{}{ + t := translateFunc("api.email_batching.send_batched_email_notification.time", map[string]any{ "Hour": tm.Hour(), "Minute": fmt.Sprintf("%02d", tm.Minute()), "Month": translateFunc(tm.Month().String()), @@ -292,7 +292,7 @@ func (es *Service) sendBatchedEmailNotification(userID string, notifications []* otherChannelMembersCount := 0 if threadsEnabled && notification.post.RootId != "" { - props := map[string]interface{}{"channelName": channelDisplayName} + props := map[string]any{"channelName": channelDisplayName} channelDisplayName = translateFunc("api.push_notification.title.collapsed_threads", props) if channel.Type == model.ChannelTypeDirect { channelDisplayName = translateFunc("api.push_notification.title.collapsed_threads_dm") @@ -320,7 +320,7 @@ func (es *Service) sendBatchedEmailNotification(userID string, notifications []* tm := time.Unix(notifications[0].post.CreateAt/1000, 0) - subject := translateFunc("api.email_batching.send_batched_email_notification.subject", len(notifications), map[string]interface{}{ + subject := translateFunc("api.email_batching.send_batched_email_notification.subject", len(notifications), map[string]any{ "SiteName": es.config().TeamSettings.SiteName, "Year": tm.Year(), "Month": translateFunc(tm.Month().String()), diff --git a/app/email/notification_email.go b/app/email/notification_email.go index 32ab36bd50..6f83b1191f 100644 --- a/app/email/notification_email.go +++ b/app/email/notification_email.go @@ -37,7 +37,7 @@ func (es *Service) GetMessageForNotification(post *model.Post, translateFunc i18 onlyImages = onlyImages && info.IsImage() } - props := map[string]interface{}{"Filenames": strings.Join(filenames, ", ")} + props := map[string]any{"Filenames": strings.Join(filenames, ", ")} if onlyImages { return translateFunc("api.post.get_message_for_notification.images_sent", len(filenames), props) diff --git a/app/emoji.go b/app/emoji.go index 360619ab3c..14f58d9128 100644 --- a/app/emoji.go +++ b/app/emoji.go @@ -66,7 +66,7 @@ func (a *App) CreateEmoji(sessionUserId string, emoji *model.Emoji, multiPartIma imageData := multiPartImageData.File["image"] if len(imageData) == 0 { - err := model.NewAppError("Context", "api.context.invalid_body_param.app_error", map[string]interface{}{"Name": "createEmoji"}, "", http.StatusBadRequest) + err := model.NewAppError("Context", "api.context.invalid_body_param.app_error", map[string]any{"Name": "createEmoji"}, "", http.StatusBadRequest) return nil, err } @@ -123,7 +123,7 @@ func (a *App) UploadEmojiImage(id string, imageData *multipart.FileHeader) *mode } if config.Width > MaxEmojiOriginalWidth || config.Height > MaxEmojiOriginalHeight { - return model.NewAppError("uploadEmojiImage", "api.emoji.upload.large_image.too_large.app_error", map[string]interface{}{ + return model.NewAppError("uploadEmojiImage", "api.emoji.upload.large_image.too_large.app_error", map[string]any{ "MaxWidth": MaxEmojiOriginalWidth, "MaxHeight": MaxEmojiOriginalHeight, }, "", http.StatusBadRequest) diff --git a/app/expirynotify.go b/app/expirynotify.go index 4034718245..0f5c813ced 100644 --- a/app/expirynotify.go +++ b/app/expirynotify.go @@ -79,7 +79,7 @@ func (a *App) getSessionExpiredPushMessage(session *model.Session) string { T := i18n.GetUserTranslations(locale) siteName := *a.Config().TeamSettings.SiteName - props := map[string]interface{}{"siteName": siteName, "hoursCount": *a.Config().ServiceSettings.SessionLengthMobileInHours} + props := map[string]any{"siteName": siteName, "hoursCount": *a.Config().ServiceSettings.SessionLengthMobileInHours} return T("api.push_notifications.session.expired", props) } diff --git a/app/export_test.go b/app/export_test.go index 78fecaaf8b..2e13c3b993 100644 --- a/app/export_test.go +++ b/app/export_test.go @@ -496,7 +496,7 @@ func TestExportPostWithProps(t *testing.T) { p1 := &model.Post{ ChannelId: dmChannel.Id, Message: "aa" + model.NewId() + "a", - Props: map[string]interface{}{ + Props: map[string]any{ "attachments": attachments, }, UserId: th1.BasicUser.Id, @@ -506,7 +506,7 @@ func TestExportPostWithProps(t *testing.T) { p2 := &model.Post{ ChannelId: gmChannel.Id, Message: "dd" + model.NewId() + "a", - Props: map[string]interface{}{ + Props: map[string]any{ "attachments": attachments, }, UserId: th1.BasicUser.Id, @@ -545,8 +545,8 @@ func TestExportPostWithProps(t *testing.T) { assert.Len(t, posts, 2) assert.ElementsMatch(t, gmMembers, *posts[0].ChannelMembers) assert.ElementsMatch(t, dmMembers, *posts[1].ChannelMembers) - assert.Contains(t, posts[0].Props["attachments"].([]interface{})[0], "footer") - assert.Contains(t, posts[1].Props["attachments"].([]interface{})[0], "footer") + assert.Contains(t, posts[0].Props["attachments"].([]any)[0], "footer") + assert.Contains(t, posts[1].Props["attachments"].([]any)[0], "footer") } func TestExportDMPostWithSelf(t *testing.T) { diff --git a/app/feature_flags.go b/app/feature_flags.go index 582d41d1bf..efb517eca3 100644 --- a/app/feature_flags.go +++ b/app/feature_flags.go @@ -61,7 +61,7 @@ func (s *Server) startFeatureFlagUpdateJob() error { log = s.Log } - attributes := map[string]interface{}{} + attributes := map[string]any{} // if we are part of a cloud installation, add its installation and group id if installationId := os.Getenv("MM_CLOUD_INSTALLATION_ID"); installationId != "" { diff --git a/app/featureflag/feature_flags_sync.go b/app/featureflag/feature_flags_sync.go index aa492ff9fa..98bee67552 100644 --- a/app/featureflag/feature_flags_sync.go +++ b/app/featureflag/feature_flags_sync.go @@ -22,7 +22,7 @@ type SyncParams struct { SplitKey string SyncIntervalSeconds int Log *mlog.Logger - Attributes map[string]interface{} + Attributes map[string]any } type Synchronizer struct { @@ -100,7 +100,7 @@ func featureFlagsFromMap(featuresMap map[string]string, baseFeatureFlags model.F return baseFeatureFlags } -func getStructFields(s interface{}) []string { +func getStructFields(s any) []string { structType := reflect.TypeOf(s) fieldNames := make([]string, 0, structType.NumField()) for i := 0; i < structType.NumField(); i++ { diff --git a/app/featureflag/split_logger.go b/app/featureflag/split_logger.go index 3b55283c18..1bd7a6d4c3 100644 --- a/app/featureflag/split_logger.go +++ b/app/featureflag/split_logger.go @@ -13,23 +13,23 @@ type splitLogger struct { wrappedLog *mlog.Logger } -func (s *splitLogger) Error(msg ...interface{}) { +func (s *splitLogger) Error(msg ...any) { s.wrappedLog.Error(fmt.Sprint(msg...)) } -func (s *splitLogger) Warning(msg ...interface{}) { +func (s *splitLogger) Warning(msg ...any) { s.wrappedLog.Warn(fmt.Sprint(msg...)) } // Ignoring more verbose messages from split -func (s *splitLogger) Info(msg ...interface{}) { +func (s *splitLogger) Info(msg ...any) { //s.wrappedLog.Info(fmt.Sprint(msg...)) } -func (s *splitLogger) Debug(msg ...interface{}) { +func (s *splitLogger) Debug(msg ...any) { //s.wrappedLog.Debug(fmt.Sprint(msg...)) } -func (s *splitLogger) Verbose(msg ...interface{}) { +func (s *splitLogger) Verbose(msg ...any) { //s.wrappedLog.Info(fmt.Sprint(msg...)) } diff --git a/app/file.go b/app/file.go index 4d85666c64..8a4024f650 100644 --- a/app/file.go +++ b/app/file.go @@ -456,7 +456,7 @@ func (a *App) UploadMultipartFiles(c *request.Context, teamID string, channelID file, fileErr := fileHeader.Open() if fileErr != nil { return nil, model.NewAppError("UploadFiles", "api.file.upload_file.read_request.app_error", - map[string]interface{}{"Filename": fileHeader.Filename}, fileErr.Error(), http.StatusBadRequest) + map[string]any{"Filename": fileHeader.Filename}, fileErr.Error(), http.StatusBadRequest) } // Will be closed after UploadFiles returns @@ -523,7 +523,7 @@ func (a *App) UploadFile(c *request.Context, data []byte, channelID string, file _, err := a.GetChannel(channelID) if err != nil && channelID != "" { return nil, model.NewAppError("UploadFile", "api.file.upload_file.incorrect_channelId.app_error", - map[string]interface{}{"channelId": channelID}, "", http.StatusBadRequest) + map[string]any{"channelId": channelID}, "", http.StatusBadRequest) } info, _, appError := a.DoUploadFileExpectModification(c, time.Now(), "noteam", channelID, "nouser", filename, data) @@ -898,8 +898,8 @@ func (t UploadFileTask) pathPrefix() string { "/" + t.fileinfo.Id + "/" } -func (t UploadFileTask) newAppError(id string, httpStatus int, extra ...interface{}) *model.AppError { - params := map[string]interface{}{ +func (t UploadFileTask) newAppError(id string, httpStatus int, extra ...any) *model.AppError { + params := map[string]any{ "Name": t.Name, "Filename": t.Name, "ChannelId": t.ChannelId, @@ -948,7 +948,7 @@ func (a *App) DoUploadFileExpectModification(c *request.Context, now time.Time, if info.IsImage() && !info.IsSvg() { if limitErr := checkImageResolutionLimit(info.Width, info.Height, *a.Config().FileSettings.MaxImageResolution); limitErr != nil { - err := model.NewAppError("uploadFile", "api.file.upload_file.large_image.app_error", map[string]interface{}{"Filename": filename}, limitErr.Error(), http.StatusBadRequest) + err := model.NewAppError("uploadFile", "api.file.upload_file.large_image.app_error", map[string]any{"Filename": filename}, limitErr.Error(), http.StatusBadRequest) return nil, data, err } diff --git a/app/import.go b/app/import.go index 5a5c02e95e..c02a59440c 100644 --- a/app/import.go +++ b/app/import.go @@ -314,7 +314,7 @@ func (a *App) importLine(c *request.Context, line LineImportData, dryRun bool) * } return a.importEmoji(line.Emoji, dryRun) default: - return model.NewAppError("BulkImport", "app.import.import_line.unknown_line_type.error", map[string]interface{}{"Type": line.Type}, "", http.StatusBadRequest) + return model.NewAppError("BulkImport", "app.import.import_line.unknown_line_type.error", map[string]any{"Type": line.Type}, "", http.StatusBadRequest) } } diff --git a/app/import_functions.go b/app/import_functions.go index d1993b0f5d..0a41b93566 100644 --- a/app/import_functions.go +++ b/app/import_functions.go @@ -45,7 +45,7 @@ func (a *App) importScheme(data *SchemeImportData, dryRun bool) *model.AppError if err != nil { scheme = new(model.Scheme) } else if scheme.Scope != *data.Scope { - return model.NewAppError("BulkImport", "app.import.import_scheme.scope_change.error", map[string]interface{}{"SchemeName": scheme.Name}, "", http.StatusBadRequest) + return model.NewAppError("BulkImport", "app.import.import_scheme.scope_change.error", map[string]any{"SchemeName": scheme.Name}, "", http.StatusBadRequest) } scheme.Name = *data.Name @@ -239,7 +239,7 @@ func (a *App) importChannel(c *request.Context, data *ChannelImportData, dryRun team, err := a.Srv().Store.Team().GetByName(*data.Team) if err != nil { - return model.NewAppError("BulkImport", "app.import.import_channel.team_not_found.error", map[string]interface{}{"TeamName": *data.Team}, err.Error(), http.StatusBadRequest) + return model.NewAppError("BulkImport", "app.import.import_channel.team_not_found.error", map[string]any{"TeamName": *data.Team}, err.Error(), http.StatusBadRequest) } var channel *model.Channel @@ -1068,7 +1068,7 @@ func (a *App) importReaction(data *ReactionImportData, post *model.Post) *model. var user *model.User var nErr error if user, nErr = a.Srv().Store.User().GetByUsername(*data.User); nErr != nil { - return model.NewAppError("BulkImport", "app.import.import_post.user_not_found.error", map[string]interface{}{"Username": data.User}, nErr.Error(), http.StatusBadRequest) + return model.NewAppError("BulkImport", "app.import.import_post.user_not_found.error", map[string]any{"Username": data.User}, nErr.Error(), http.StatusBadRequest) } reaction := &model.Reaction{ @@ -1200,7 +1200,7 @@ func (a *App) importAttachment(c *request.Context, data *AttachmentImportData, p if data.Data != nil { zipFile, err := data.Data.Open() if err != nil { - return nil, model.NewAppError("BulkImport", "app.import.attachment.bad_file.error", map[string]interface{}{"FilePath": *data.Path}, err.Error(), http.StatusBadRequest) + return nil, model.NewAppError("BulkImport", "app.import.attachment.bad_file.error", map[string]any{"FilePath": *data.Path}, err.Error(), http.StatusBadRequest) } defer zipFile.Close() name = data.Data.Name @@ -1208,7 +1208,7 @@ func (a *App) importAttachment(c *request.Context, data *AttachmentImportData, p } else { realFile, err := os.Open(*data.Path) if err != nil { - return nil, model.NewAppError("BulkImport", "app.import.attachment.bad_file.error", map[string]interface{}{"FilePath": *data.Path}, err.Error(), http.StatusBadRequest) + return nil, model.NewAppError("BulkImport", "app.import.attachment.bad_file.error", map[string]any{"FilePath": *data.Path}, err.Error(), http.StatusBadRequest) } defer realFile.Close() name = realFile.Name() @@ -1219,14 +1219,14 @@ func (a *App) importAttachment(c *request.Context, data *AttachmentImportData, p fileData, err := ioutil.ReadAll(file) if err != nil { - return nil, model.NewAppError("BulkImport", "app.import.attachment.read_file_data.error", map[string]interface{}{"FilePath": *data.Path}, "", http.StatusBadRequest) + return nil, model.NewAppError("BulkImport", "app.import.attachment.read_file_data.error", map[string]any{"FilePath": *data.Path}, "", http.StatusBadRequest) } // Go over existing files in the post and see if there already exists a file with the same name, size and hash. If so - skip it if post.Id != "" { oldFiles, err := a.GetFileInfosForPost(post.Id, true) if err != nil { - return nil, model.NewAppError("BulkImport", "app.import.attachment.file_upload.error", map[string]interface{}{"FilePath": *data.Path}, "", http.StatusBadRequest) + return nil, model.NewAppError("BulkImport", "app.import.attachment.file_upload.error", map[string]any{"FilePath": *data.Path}, "", http.StatusBadRequest) } for _, oldFile := range oldFiles { if oldFile.Name != path.Base(name) || oldFile.Size != int64(len(fileData)) { @@ -1236,7 +1236,7 @@ func (a *App) importAttachment(c *request.Context, data *AttachmentImportData, p newHash := sha1.Sum(fileData) oldFileData, err := a.GetFile(oldFile.Id) if err != nil { - return nil, model.NewAppError("BulkImport", "app.import.attachment.file_upload.error", map[string]interface{}{"FilePath": *data.Path}, "", http.StatusBadRequest) + return nil, model.NewAppError("BulkImport", "app.import.attachment.file_upload.error", map[string]any{"FilePath": *data.Path}, "", http.StatusBadRequest) } oldHash := sha1.Sum(oldFileData) @@ -1327,7 +1327,7 @@ func (a *App) getChannelsForPosts(teams map[string]*model.Team, data []*PostImpo var err error channel, err = a.Srv().Store.Channel().GetByName(teams[teamName].Id, *postData.Channel, true) if err != nil { - return nil, model.NewAppError("BulkImport", "app.import.import_post.channel_not_found.error", map[string]interface{}{"ChannelName": *postData.Channel}, err.Error(), http.StatusBadRequest) + return nil, model.NewAppError("BulkImport", "app.import.import_post.channel_not_found.error", map[string]any{"ChannelName": *postData.Channel}, err.Error(), http.StatusBadRequest) } teamChannels[teamName][*postData.Channel] = channel } @@ -1881,7 +1881,7 @@ func (a *App) importEmoji(data *EmojiImportData, dryRun bool) *model.AppError { file, err = os.Open(*data.Image) } if err != nil { - return model.NewAppError("BulkImport", "app.import.emoji.bad_file.error", map[string]interface{}{"EmojiName": *data.Name}, "", http.StatusBadRequest) + return model.NewAppError("BulkImport", "app.import.emoji.bad_file.error", map[string]any{"EmojiName": *data.Name}, "", http.StatusBadRequest) } defer file.Close() diff --git a/app/import_validators.go b/app/import_validators.go index 296351e5c5..3be6b8fabd 100644 --- a/app/import_validators.go +++ b/app/import_validators.go @@ -492,7 +492,7 @@ func validateDirectChannelImportData(data *DirectChannelImportData) *model.AppEr } } if !found { - return model.NewAppError("BulkImport", "app.import.validate_direct_channel_import_data.unknown_favoriter.error", map[string]interface{}{"Username": favoriter}, "", http.StatusBadRequest) + return model.NewAppError("BulkImport", "app.import.validate_direct_channel_import_data.unknown_favoriter.error", map[string]any{"Username": favoriter}, "", http.StatusBadRequest) } } } @@ -539,7 +539,7 @@ func validateDirectPostImportData(data *DirectPostImportData, maxPostSize int) * } } if !found { - return model.NewAppError("BulkImport", "app.import.validate_direct_post_import_data.unknown_flagger.error", map[string]interface{}{"Username": flagger}, "", http.StatusBadRequest) + return model.NewAppError("BulkImport", "app.import.validate_direct_post_import_data.unknown_flagger.error", map[string]any{"Username": flagger}, "", http.StatusBadRequest) } } } diff --git a/app/integration_action.go b/app/integration_action.go index 869c0dd4e8..7d9ee8db8f 100644 --- a/app/integration_action.go +++ b/app/integration_action.go @@ -51,7 +51,7 @@ func (a *App) DoPostActionWithCookie(c *request.Context, postID, actionId, userI // IsPinned and HasReaction attributes, and preserve its entire // original Props set unless the plugin returns a replacement value. // originalXxx variables are used to preserve these values. - var originalProps map[string]interface{} + var originalProps map[string]any originalIsPinned := false originalHasReactions := false @@ -59,7 +59,7 @@ func (a *App) DoPostActionWithCookie(c *request.Context, postID, actionId, userI // need to preserve some original values, as listed in // model.PostActionRetainPropKeys. remove and retain track these. remove := []string{} - retain := map[string]interface{}{} + retain := map[string]any{} datasource := "" upstreamURL := "" @@ -222,7 +222,7 @@ func (a *App) DoPostActionWithCookie(c *request.Context, postID, actionId, userI if upstreamRequest.Type == model.PostActionTypeSelect { if selectedOption != "" { if upstreamRequest.Context == nil { - upstreamRequest.Context = map[string]interface{}{} + upstreamRequest.Context = map[string]any{} } upstreamRequest.DataSource = datasource upstreamRequest.Context["selected_option"] = selectedOption @@ -548,23 +548,23 @@ func (a *App) buildWarnMetricMailtoLink(warnMetricId string, user *model.User) s _, warnMetricDisplayTexts := a.getWarnMetricStatusAndDisplayTextsForId(warnMetricId, T, false) mailBody := warnMetricDisplayTexts.EmailBody - mailBody += T("api.server.warn_metric.bot_response.mailto_contact_header", map[string]interface{}{"Contact": user.GetFullName()}) + mailBody += T("api.server.warn_metric.bot_response.mailto_contact_header", map[string]any{"Contact": user.GetFullName()}) mailBody += "\r\n" - mailBody += T("api.server.warn_metric.bot_response.mailto_email_header", map[string]interface{}{"Email": user.Email}) + mailBody += T("api.server.warn_metric.bot_response.mailto_email_header", map[string]any{"Email": user.Email}) mailBody += "\r\n" registeredUsersCount, err := a.Srv().Store.User().Count(model.UserCountOptions{}) if err != nil { mlog.Warn("Error retrieving the number of registered users", mlog.Err(err)) } else { - mailBody += i18n.T("api.server.warn_metric.bot_response.mailto_registered_users_header", map[string]interface{}{"NoRegisteredUsers": registeredUsersCount}) + mailBody += i18n.T("api.server.warn_metric.bot_response.mailto_registered_users_header", map[string]any{"NoRegisteredUsers": registeredUsersCount}) mailBody += "\r\n" } - mailBody += T("api.server.warn_metric.bot_response.mailto_site_url_header", map[string]interface{}{"SiteUrl": a.GetSiteURL()}) + mailBody += T("api.server.warn_metric.bot_response.mailto_site_url_header", map[string]any{"SiteUrl": a.GetSiteURL()}) mailBody += "\r\n" - mailBody += T("api.server.warn_metric.bot_response.mailto_diagnostic_id_header", map[string]interface{}{"DiagnosticId": a.TelemetryId()}) + mailBody += T("api.server.warn_metric.bot_response.mailto_diagnostic_id_header", map[string]any{"DiagnosticId": a.TelemetryId()}) mailBody += "\r\n" mailBody += T("api.server.warn_metric.bot_response.mailto_footer") diff --git a/app/integration_action_test.go b/app/integration_action_test.go index 7b2f04a346..6ab8ba8967 100644 --- a/app/integration_action_test.go +++ b/app/integration_action_test.go @@ -501,7 +501,7 @@ func TestSubmitInteractiveDialog(t *testing.T) { TeamId: th.BasicTeam.Id, CallbackId: "someid", State: "somestate", - Submission: map[string]interface{}{ + Submission: map[string]any{ "name1": "value1", }, } diff --git a/app/integrations.go b/app/integrations.go index 2c747e0b7f..9042f1e1bb 100644 --- a/app/integrations.go +++ b/app/integrations.go @@ -106,7 +106,7 @@ func (a *App) checkIfIntegrationsMeetFreemiumLimits(originalPluginIds []string) limit := *limits.Integrations.Enabled if enableCount > limit { - return model.NewAppError("checkIfIntegrationMeetsFreemiumLimits", "app.install_integration.reached_max_limit.error", map[string]interface{}{"NumIntegrations": limit}, "", http.StatusBadRequest) + return model.NewAppError("checkIfIntegrationMeetsFreemiumLimits", "app.install_integration.reached_max_limit.error", map[string]any{"NumIntegrations": limit}, "", http.StatusBadRequest) } return nil diff --git a/app/layer_generators/main.go b/app/layer_generators/main.go index 4ed14b50c0..4fe3586f06 100644 --- a/app/layer_generators/main.go +++ b/app/layer_generators/main.go @@ -85,7 +85,7 @@ func fixTypeName(t string) string { if t == "...func(*UploadFileTask)" { t = "...func(*app.UploadFileTask)" } - if strings.Contains(t, ".") || strings.Contains(t, "{}") { + if strings.Contains(t, ".") || strings.Contains(t, "{}") || t == "map[string]any" { return t } typeOnly := textRegexp.FindString(t) diff --git a/app/ldap.go b/app/ldap.go index 2b7c9fdcd8..20f4fdf752 100644 --- a/app/ldap.go +++ b/app/ldap.go @@ -55,7 +55,7 @@ func (a *App) GetLdapGroup(ldapGroupID string) (*model.Group, *model.AppError) { return nil, err } } else { - ae := model.NewAppError("GetLdapGroup", "ent.ldap.app_error", map[string]interface{}{"ldap_group_id": ldapGroupID}, "", http.StatusNotImplemented) + ae := model.NewAppError("GetLdapGroup", "ent.ldap.app_error", map[string]any{"ldap_group_id": ldapGroupID}, "", http.StatusNotImplemented) return nil, ae } @@ -235,7 +235,7 @@ func (a *App) AddLdapPrivateCertificate(fileData *multipart.FileHeader) *model.A func (a *App) removeLdapFile(filename string) *model.AppError { if err := a.Srv().configStore.RemoveFile(filename); err != nil { - return model.NewAppError("RemoveLdapFile", "api.admin.remove_certificate.delete.app_error", map[string]interface{}{"Filename": filename}, err.Error(), http.StatusInternalServerError) + return model.NewAppError("RemoveLdapFile", "api.admin.remove_certificate.delete.app_error", map[string]any{"Filename": filename}, err.Error(), http.StatusInternalServerError) } return nil } diff --git a/app/license.go b/app/license.go index 2d3d948190..6da4287daf 100644 --- a/app/license.go +++ b/app/license.go @@ -170,7 +170,7 @@ func (s *Server) SaveLicense(licenseBytes []byte) (*model.License, *model.AppErr } if uniqueUserCount > int64(*license.Features.Users) { - return nil, model.NewAppError("addLicense", "api.license.add_license.unique_users.app_error", map[string]interface{}{"Users": *license.Features.Users, "Count": uniqueUserCount}, "", http.StatusBadRequest) + return nil, model.NewAppError("addLicense", "api.license.add_license.unique_users.app_error", map[string]any{"Users": *license.Features.Users, "Count": uniqueUserCount}, "", http.StatusBadRequest) } if license.IsExpired() { diff --git a/app/notification.go b/app/notification.go index 972bab9f57..c371ebf4ae 100644 --- a/app/notification.go +++ b/app/notification.go @@ -386,7 +386,7 @@ func (a *App) SendNotifications(post *model.Post, team *model.Team, channel *mod post.UserId, &model.Post{ ChannelId: post.ChannelId, - Message: T("api.post.disabled_here", map[string]interface{}{"Users": *a.Config().TeamSettings.MaxNotificationsPerChannel}), + Message: T("api.post.disabled_here", map[string]any{"Users": *a.Config().TeamSettings.MaxNotificationsPerChannel}), CreateAt: post.CreateAt + 1, }, ) @@ -397,7 +397,7 @@ func (a *App) SendNotifications(post *model.Post, team *model.Team, channel *mod post.UserId, &model.Post{ ChannelId: post.ChannelId, - Message: T("api.post.disabled_channel", map[string]interface{}{"Users": *a.Config().TeamSettings.MaxNotificationsPerChannel}), + Message: T("api.post.disabled_channel", map[string]any{"Users": *a.Config().TeamSettings.MaxNotificationsPerChannel}), CreateAt: post.CreateAt + 1, }, ) @@ -408,7 +408,7 @@ func (a *App) SendNotifications(post *model.Post, team *model.Team, channel *mod post.UserId, &model.Post{ ChannelId: post.ChannelId, - Message: T("api.post.disabled_all", map[string]interface{}{"Users": *a.Config().TeamSettings.MaxNotificationsPerChannel}), + Message: T("api.post.disabled_all", map[string]any{"Users": *a.Config().TeamSettings.MaxNotificationsPerChannel}), CreateAt: post.CreateAt + 1, }, ) @@ -801,13 +801,13 @@ func makeOutOfChannelMentionPost(sender *model.User, post *model.Post, outOfChan ephemeralPostId := model.NewId() var message string if len(outOfChannelUsers) == 1 { - message = T("api.post.check_for_out_of_channel_mentions.message.one", map[string]interface{}{ + message = T("api.post.check_for_out_of_channel_mentions.message.one", map[string]any{ "Username": ocUsernames[0], }) } else if len(outOfChannelUsers) > 1 { preliminary, final := splitAtFinal(ocUsernames) - message = T("api.post.check_for_out_of_channel_mentions.message.multiple", map[string]interface{}{ + message = T("api.post.check_for_out_of_channel_mentions.message.multiple", map[string]any{ "Usernames": strings.Join(preliminary, ", @"), "LastUsername": final, }) @@ -818,7 +818,7 @@ func makeOutOfChannelMentionPost(sender *model.User, post *model.Post, outOfChan message += "\n" } - message += T("api.post.check_for_out_of_channel_groups_mentions.message.one", map[string]interface{}{ + message += T("api.post.check_for_out_of_channel_groups_mentions.message.one", map[string]any{ "Username": ogUsernames[0], }) } else if len(outOfGroupsUsers) > 1 { @@ -828,7 +828,7 @@ func makeOutOfChannelMentionPost(sender *model.User, post *model.Post, outOfChan message += "\n" } - message += T("api.post.check_for_out_of_channel_groups_mentions.message.multiple", map[string]interface{}{ + message += T("api.post.check_for_out_of_channel_groups_mentions.message.multiple", map[string]any{ "Usernames": strings.Join(preliminary, ", @"), "LastUsername": final, }) @@ -986,7 +986,7 @@ func getExplicitMentions(post *model.Post, keywords map[string][]string, groups buf := "" mentionsEnabledFields := getMentionsEnabledFields(post) for _, message := range mentionsEnabledFields { - markdown.Inspect(message, func(node interface{}) bool { + markdown.Inspect(message, func(node any) bool { text, ok := node.(*markdown.Text) if !ok { ret.processText(buf, keywords, groups) diff --git a/app/notification_email.go b/app/notification_email.go index 2178e2b414..12b7501607 100644 --- a/app/notification_email.go +++ b/app/notification_email.go @@ -145,7 +145,7 @@ func (a *App) sendNotificationEmail(notification *PostNotification, user *model. */ func getDirectMessageNotificationEmailSubject(user *model.User, post *model.Post, translateFunc i18n.TranslateFunc, siteName string, senderName string, useMilitaryTime bool) string { t := getFormattedPostTime(user, post, useMilitaryTime, translateFunc) - var subjectParameters = map[string]interface{}{ + var subjectParameters = map[string]any{ "SiteName": siteName, "SenderDisplayName": senderName, "Month": t.Month, @@ -160,7 +160,7 @@ func getDirectMessageNotificationEmailSubject(user *model.User, post *model.Post */ func getNotificationEmailSubject(user *model.User, post *model.Post, translateFunc i18n.TranslateFunc, siteName string, teamName string, useMilitaryTime bool) string { t := getFormattedPostTime(user, post, useMilitaryTime, translateFunc) - var subjectParameters = map[string]interface{}{ + var subjectParameters = map[string]any{ "SiteName": siteName, "TeamName": teamName, "Month": t.Month, @@ -175,7 +175,7 @@ func getNotificationEmailSubject(user *model.User, post *model.Post, translateFu */ func getGroupMessageNotificationEmailSubject(user *model.User, post *model.Post, translateFunc i18n.TranslateFunc, siteName string, channelName string, emailNotificationContentsType string, useMilitaryTime bool) string { t := getFormattedPostTime(user, post, useMilitaryTime, translateFunc) - var subjectParameters = map[string]interface{}{ + var subjectParameters = map[string]any{ "SiteName": siteName, "Month": t.Month, "Day": t.Day, @@ -222,7 +222,7 @@ func (a *App) getNotificationEmailBody(recipient *model.User, post *model.Post, } t := getFormattedPostTime(recipient, post, useMilitaryTime, translateFunc) - messageTime := map[string]interface{}{ + messageTime := map[string]any{ "Hour": t.Hour, "Minute": t.Minute, "TimeZone": t.TimeZone, @@ -262,36 +262,36 @@ func (a *App) getNotificationEmailBody(recipient *model.User, post *model.Post, if channel.Type == model.ChannelTypeDirect { // Direct Messages - data.Props["Title"] = translateFunc("app.notification.body.dm.title", map[string]interface{}{"SenderName": senderName}) - data.Props["SubTitle"] = translateFunc("app.notification.body.dm.subTitle", map[string]interface{}{"SenderName": senderName}) + data.Props["Title"] = translateFunc("app.notification.body.dm.title", map[string]any{"SenderName": senderName}) + data.Props["SubTitle"] = translateFunc("app.notification.body.dm.subTitle", map[string]any{"SenderName": senderName}) } else if channel.Type == model.ChannelTypeGroup { // Group Messages - data.Props["Title"] = translateFunc("app.notification.body.group.title", map[string]interface{}{"SenderName": senderName}) - data.Props["SubTitle"] = translateFunc("app.notification.body.group.subTitle", map[string]interface{}{"SenderName": senderName}) + data.Props["Title"] = translateFunc("app.notification.body.group.title", map[string]any{"SenderName": senderName}) + data.Props["SubTitle"] = translateFunc("app.notification.body.group.subTitle", map[string]any{"SenderName": senderName}) } else { // mentions - data.Props["Title"] = translateFunc("app.notification.body.mention.title", map[string]interface{}{"SenderName": senderName}) - data.Props["SubTitle"] = translateFunc("app.notification.body.mention.subTitle", map[string]interface{}{"SenderName": senderName, "ChannelName": channelName}) + data.Props["Title"] = translateFunc("app.notification.body.mention.title", map[string]any{"SenderName": senderName}) + data.Props["SubTitle"] = translateFunc("app.notification.body.mention.subTitle", map[string]any{"SenderName": senderName, "ChannelName": channelName}) pData.ChannelName = channelName } // Override title and subtile for replies with CRT enabled if a.IsCRTEnabledForUser(recipient.Id) && post.RootId != "" { // Title is the same in all cases - data.Props["Title"] = translateFunc("app.notification.body.thread.title", map[string]interface{}{"SenderName": senderName}) + data.Props["Title"] = translateFunc("app.notification.body.thread.title", map[string]any{"SenderName": senderName}) if channel.Type == model.ChannelTypeDirect { // Direct Reply - data.Props["SubTitle"] = translateFunc("app.notification.body.thread_dm.subTitle", map[string]interface{}{"SenderName": senderName}) + data.Props["SubTitle"] = translateFunc("app.notification.body.thread_dm.subTitle", map[string]any{"SenderName": senderName}) } else if channel.Type == model.ChannelTypeGroup { // Group Reply - data.Props["SubTitle"] = translateFunc("app.notification.body.thread_gm.subTitle", map[string]interface{}{"SenderName": senderName}) + data.Props["SubTitle"] = translateFunc("app.notification.body.thread_gm.subTitle", map[string]any{"SenderName": senderName}) } else if emailNotificationContentsType == model.EmailNotificationContentsFull { // Channel Reply with full content - data.Props["SubTitle"] = translateFunc("app.notification.body.thread_channel_full.subTitle", map[string]interface{}{"SenderName": senderName, "ChannelName": channelName}) + data.Props["SubTitle"] = translateFunc("app.notification.body.thread_channel_full.subTitle", map[string]any{"SenderName": senderName, "ChannelName": channelName}) } else { // Channel Reply with generic content - data.Props["SubTitle"] = translateFunc("app.notification.body.thread_channel.subTitle", map[string]interface{}{"SenderName": senderName}) + data.Props["SubTitle"] = translateFunc("app.notification.body.thread_channel.subTitle", map[string]any{"SenderName": senderName}) } } diff --git a/app/notification_push.go b/app/notification_push.go index c79987cac2..7d8421ea30 100644 --- a/app/notification_push.go +++ b/app/notification_push.go @@ -660,7 +660,7 @@ func (a *App) buildFullPushNotificationMessage(contentsConfig string, post *mode msg.IsCRTEnabled = true if post.RootId != "" { if contentsConfig != model.GenericNoChannelNotification { - props := map[string]interface{}{"channelName": channelName} + props := map[string]any{"channelName": channelName} msg.ChannelName = userLocale("api.push_notification.title.collapsed_threads", props) if channel.Type == model.ChannelTypeDirect { diff --git a/app/notification_push_test.go b/app/notification_push_test.go index 5720c1bced..40244c479f 100644 --- a/app/notification_push_test.go +++ b/app/notification_push_test.go @@ -1441,7 +1441,7 @@ func TestPushNotificationRace(t *testing.T) { filestore: &fmocks.FileBackend{}, } s.configStore = &configWrapper{srv: s, Store: memoryStore} - serviceMap := map[ServiceKey]interface{}{ + serviceMap := map[ServiceKey]any{ ConfigKey: s.configStore, LicenseKey: &licenseWrapper{s}, FilestoreKey: s.filestore, @@ -1481,7 +1481,7 @@ func TestPushNotificationAttachment(t *testing.T) { originalMessage := "hello world" post := &model.Post{ Message: originalMessage, - Props: map[string]interface{}{ + Props: map[string]any{ "attachments": []*model.SlackAttachment{ { AuthorName: "testuser", diff --git a/app/notification_test.go b/app/notification_test.go index be5666c654..f023385c0d 100644 --- a/app/notification_test.go +++ b/app/notification_test.go @@ -41,7 +41,7 @@ func TestSendNotifications(t *testing.T) { ChannelId: th.BasicChannel.Id, Message: "@" + th.BasicUser2.Username, Type: model.PostTypeAddToChannel, - Props: map[string]interface{}{model.PostPropsAddedUserId: "junk"}, + Props: map[string]any{model.PostPropsAddedUserId: "junk"}, }, true) require.Nil(t, appErr) @@ -181,7 +181,7 @@ func TestSendNotificationsWithManyUsers(t *testing.T) { ChannelId: th.BasicChannel.Id, Message: "@channel", Type: model.PostTypeAddToChannel, - Props: map[string]interface{}{model.PostPropsAddedUserId: "junk"}, + Props: map[string]any{model.PostPropsAddedUserId: "junk"}, }, true) require.Nil(t, appErr1) @@ -201,7 +201,7 @@ func TestSendNotificationsWithManyUsers(t *testing.T) { ChannelId: th.BasicChannel.Id, Message: "@channel", Type: model.PostTypeAddToChannel, - Props: map[string]interface{}{model.PostPropsAddedUserId: "junk"}, + Props: map[string]any{model.PostPropsAddedUserId: "junk"}, }, true) require.Nil(t, appErr1) diff --git a/app/oauth.go b/app/oauth.go index eb5126ab7a..104fe654c6 100644 --- a/app/oauth.go +++ b/app/oauth.go @@ -567,7 +567,7 @@ func (a *App) getSSOProvider(service string) (einterfaces.OAuthProvider, *model. provider := einterfaces.GetOAuthProvider(providerType) if provider == nil { return nil, model.NewAppError("getSSOProvider", "api.user.login_by_oauth.not_available.app_error", - map[string]interface{}{"Service": strings.Title(service)}, "", http.StatusNotImplemented) + map[string]any{"Service": strings.Title(service)}, "", http.StatusNotImplemented) } return provider, nil } @@ -581,18 +581,18 @@ func (a *App) LoginByOAuth(c *request.Context, service string, userData io.Reade buf := bytes.Buffer{} if _, err := buf.ReadFrom(userData); err != nil { return nil, model.NewAppError("LoginByOAuth2", "api.user.login_by_oauth.parse.app_error", - map[string]interface{}{"Service": service}, "", http.StatusBadRequest) + map[string]any{"Service": service}, "", http.StatusBadRequest) } authUser, err1 := provider.GetUserFromJSON(bytes.NewReader(buf.Bytes()), tokenUser) if err1 != nil { return nil, model.NewAppError("LoginByOAuth", "api.user.login_by_oauth.parse.app_error", - map[string]interface{}{"Service": service}, err1.Error(), http.StatusBadRequest) + map[string]any{"Service": service}, err1.Error(), http.StatusBadRequest) } if *authUser.AuthData == "" { return nil, model.NewAppError("LoginByOAuth3", "api.user.login_by_oauth.parse.app_error", - map[string]interface{}{"Service": service}, "", http.StatusBadRequest) + map[string]any{"Service": service}, "", http.StatusBadRequest) } user, err := a.GetUserByAuth(model.NewString(*authUser.AuthData), service) @@ -638,12 +638,12 @@ func (a *App) CompleteSwitchWithOAuth(service string, userData io.Reader, email ssoUser, err1 := provider.GetUserFromJSON(userData, tokenUser) if err1 != nil { return nil, model.NewAppError("CompleteSwitchWithOAuth", "api.user.complete_switch_with_oauth.parse.app_error", - map[string]interface{}{"Service": service}, err1.Error(), http.StatusBadRequest) + map[string]any{"Service": service}, err1.Error(), http.StatusBadRequest) } if *ssoUser.AuthData == "" { return nil, model.NewAppError("CompleteSwitchWithOAuth", "api.user.complete_switch_with_oauth.parse.app_error", - map[string]interface{}{"Service": service}, "", http.StatusBadRequest) + map[string]any{"Service": service}, "", http.StatusBadRequest) } user, nErr := a.Srv().Store.User().GetByEmail(email) @@ -877,7 +877,7 @@ func (a *App) AuthorizeOAuthUser(w http.ResponseWriter, r *http.Request, service req, requestErr = http.NewRequest("GET", *sso.UserAPIEndpoint, strings.NewReader("")) if requestErr != nil { - return nil, "", stateProps, nil, model.NewAppError("AuthorizeOAuthUser", "api.user.authorize_oauth_user.service.app_error", map[string]interface{}{"Service": service}, requestErr.Error(), http.StatusInternalServerError) + return nil, "", stateProps, nil, model.NewAppError("AuthorizeOAuthUser", "api.user.authorize_oauth_user.service.app_error", map[string]any{"Service": service}, requestErr.Error(), http.StatusInternalServerError) } req.Header.Set("Content-Type", "application/x-www-form-urlencoded") @@ -886,7 +886,7 @@ func (a *App) AuthorizeOAuthUser(w http.ResponseWriter, r *http.Request, service resp, err = a.HTTPService().MakeClient(true).Do(req) if err != nil { - return nil, "", stateProps, nil, model.NewAppError("AuthorizeOAuthUser", "api.user.authorize_oauth_user.service.app_error", map[string]interface{}{"Service": service}, err.Error(), http.StatusInternalServerError) + return nil, "", stateProps, nil, model.NewAppError("AuthorizeOAuthUser", "api.user.authorize_oauth_user.service.app_error", map[string]any{"Service": service}, err.Error(), http.StatusInternalServerError) } else if resp.StatusCode != http.StatusOK { defer resp.Body.Close() diff --git a/app/opentracing/opentracing_layer.go b/app/opentracing/opentracing_layer.go index 288071b431..3e8784a8c0 100644 --- a/app/opentracing/opentracing_layer.go +++ b/app/opentracing/opentracing_layer.go @@ -3933,7 +3933,7 @@ func (a *OpenTracingAppLayer) EnsureBot(c *request.Context, productID string, bo return resultVar0, resultVar1 } -func (a *OpenTracingAppLayer) EnvironmentConfig(filter func(reflect.StructField) bool) map[string]interface{} { +func (a *OpenTracingAppLayer) EnvironmentConfig(filter func(reflect.StructField) bool) map[string]any { origCtx := a.ctx span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.EnvironmentConfig") @@ -5865,7 +5865,7 @@ func (a *OpenTracingAppLayer) GetEmojiStaticURL(emojiName string) (string, *mode return resultVar0, resultVar1 } -func (a *OpenTracingAppLayer) GetEnvironmentConfig(filter func(reflect.StructField) bool) map[string]interface{} { +func (a *OpenTracingAppLayer) GetEnvironmentConfig(filter func(reflect.StructField) bool) map[string]any { origCtx := a.ctx span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.GetEnvironmentConfig") @@ -9117,7 +9117,7 @@ func (a *OpenTracingAppLayer) GetStatusFromCache(userID string) *model.Status { return resultVar0 } -func (a *OpenTracingAppLayer) GetStatusesByIds(userIDs []string) (map[string]interface{}, *model.AppError) { +func (a *OpenTracingAppLayer) GetStatusesByIds(userIDs []string) (map[string]any, *model.AppError) { origCtx := a.ctx span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.GetStatusesByIds") diff --git a/app/options.go b/app/options.go index 76bcea5310..4c35cd0478 100644 --- a/app/options.go +++ b/app/options.go @@ -20,7 +20,7 @@ type Option func(s *Server) error // construct an app with a different store. // // The override parameter must be either a store.Store or func(App) store.Store(). -func StoreOverride(override interface{}) Option { +func StoreOverride(override any) Option { return func(s *Server) error { switch o := override.(type) { case store.Store: diff --git a/app/permissions_test.go b/app/permissions_test.go index bfe98f5992..08b6b58f18 100644 --- a/app/permissions_test.go +++ b/app/permissions_test.go @@ -54,7 +54,7 @@ func TestExportPermissions(t *testing.T) { firstResult := results[0] - var row map[string]interface{} + var row map[string]any err = json.Unmarshal(firstResult, &row) if err != nil { t.Error(err) diff --git a/app/plugin_api.go b/app/plugin_api.go index fb17cc2059..dde877d0d3 100644 --- a/app/plugin_api.go +++ b/app/plugin_api.go @@ -40,8 +40,8 @@ func NewPluginAPI(a *App, c *request.Context, manifest *model.Manifest) *PluginA } } -func (api *PluginAPI) LoadPluginConfiguration(dest interface{}) error { - finalConfig := make(map[string]interface{}) +func (api *PluginAPI) LoadPluginConfiguration(dest any) error { + finalConfig := make(map[string]any) // First set final config to defaults if api.manifest.SettingsSchema != nil { @@ -104,15 +104,15 @@ func (api *PluginAPI) SaveConfig(config *model.Config) *model.AppError { return err } -func (api *PluginAPI) GetPluginConfig() map[string]interface{} { +func (api *PluginAPI) GetPluginConfig() map[string]any { cfg := api.app.GetSanitizedConfig() if pluginConfig, isOk := cfg.PluginSettings.Plugins[api.manifest.Id]; isOk { return pluginConfig } - return map[string]interface{}{} + return map[string]any{} } -func (api *PluginAPI) SavePluginConfig(pluginConfig map[string]interface{}) *model.AppError { +func (api *PluginAPI) SavePluginConfig(pluginConfig map[string]any) *model.AppError { cfg := api.app.GetSanitizedConfig() cfg.PluginSettings.Plugins[api.manifest.Id] = pluginConfig _, _, err := api.app.SaveConfig(cfg, true) @@ -908,7 +908,7 @@ func (api *PluginAPI) KVList(page, perPage int) ([]string, *model.AppError) { return api.app.ListPluginKeys(api.id, page, perPage) } -func (api *PluginAPI) PublishWebSocketEvent(event string, payload map[string]interface{}, broadcast *model.WebsocketBroadcast) { +func (api *PluginAPI) PublishWebSocketEvent(event string, payload map[string]any, broadcast *model.WebsocketBroadcast) { ev := model.NewWebSocketEvent(fmt.Sprintf("custom_%v_%v", api.id, event), "", "", "", nil) ev = ev.SetBroadcast(broadcast).SetData(payload) api.app.Publish(ev) @@ -930,16 +930,16 @@ func (api *PluginAPI) RolesGrantPermission(roleNames []string, permissionId stri return api.app.RolesGrantPermission(roleNames, permissionId) } -func (api *PluginAPI) LogDebug(msg string, keyValuePairs ...interface{}) { +func (api *PluginAPI) LogDebug(msg string, keyValuePairs ...any) { api.logger.Debugw(msg, keyValuePairs...) } -func (api *PluginAPI) LogInfo(msg string, keyValuePairs ...interface{}) { +func (api *PluginAPI) LogInfo(msg string, keyValuePairs ...any) { api.logger.Infow(msg, keyValuePairs...) } -func (api *PluginAPI) LogError(msg string, keyValuePairs ...interface{}) { +func (api *PluginAPI) LogError(msg string, keyValuePairs ...any) { api.logger.Errorw(msg, keyValuePairs...) } -func (api *PluginAPI) LogWarn(msg string, keyValuePairs ...interface{}) { +func (api *PluginAPI) LogWarn(msg string, keyValuePairs ...any) { api.logger.Warnw(msg, keyValuePairs...) } diff --git a/app/plugin_api_test.go b/app/plugin_api_test.go index bd7833b554..cfed84128b 100644 --- a/app/plugin_api_test.go +++ b/app/plugin_api_test.go @@ -54,7 +54,7 @@ func getDefaultPluginSettingsSchema() string { func setDefaultPluginConfig(th *TestHelper, pluginID string) { th.App.UpdateConfig(func(cfg *model.Config) { - cfg.PluginSettings.Plugins[pluginID] = map[string]interface{}{ + cfg.PluginSettings.Plugins[pluginID] = map[string]any{ "BasicChannelName": th.BasicChannel.Name, "BasicChannelId": th.BasicChannel.Id, "BasicTeamName": th.BasicTeam.Name, @@ -691,7 +691,7 @@ func TestPluginAPISavePluginConfig(t *testing.T) { pluginConfigJsonString := `{"mystringsetting": "str", "MyIntSetting": 32, "myboolsetting": true}` - var pluginConfig map[string]interface{} + var pluginConfig map[string]any err := json.Unmarshal([]byte(pluginConfigJsonString), &pluginConfig) require.NoError(t, err) @@ -733,7 +733,7 @@ func TestPluginAPIGetPluginConfig(t *testing.T) { api := NewPluginAPI(th.App, th.Context, manifest) pluginConfigJsonString := `{"mystringsetting": "str", "myintsetting": 32, "myboolsetting": true}` - var pluginConfig map[string]interface{} + var pluginConfig map[string]any err := json.Unmarshal([]byte(pluginConfigJsonString), &pluginConfig) require.NoError(t, err) @@ -750,7 +750,7 @@ func TestPluginAPILoadPluginConfiguration(t *testing.T) { th := Setup(t) defer th.TearDown() - var pluginJson map[string]interface{} + var pluginJson map[string]any err := json.Unmarshal([]byte(`{"mystringsetting": "str", "MyIntSetting": 32, "myboolsetting": true}`), &pluginJson) require.NoError(t, err) @@ -785,7 +785,7 @@ func TestPluginAPILoadPluginConfigurationDefaults(t *testing.T) { th := Setup(t) defer th.TearDown() - var pluginJson map[string]interface{} + var pluginJson map[string]any err := json.Unmarshal([]byte(`{"mystringsetting": "override"}`), &pluginJson) require.NoError(t, err) @@ -967,7 +967,7 @@ func TestInstallPlugin(t *testing.T) { th.App.UpdateConfig(func(cfg *model.Config) { *cfg.PluginSettings.Enable = true *cfg.PluginSettings.EnableUploads = true - cfg.PluginSettings.Plugins["testinstallplugin"] = map[string]interface{}{ + cfg.PluginSettings.Plugins["testinstallplugin"] = map[string]any{ "DownloadURL": ts.URL + "/testplugin.tar.gz", } }) @@ -1789,7 +1789,7 @@ func TestPluginHTTPUpgradeWebSocket(t *testing.T) { require.Equal(t, resp.Status, model.StatusOk) for i := 0; i < 10; i++ { - wsc.SendMessage("custom_action", map[string]interface{}{"value": i}) + wsc.SendMessage("custom_action", map[string]any{"value": i}) var resp *model.WebSocketResponse select { case resp = <-wsc.ResponseChannel: diff --git a/app/plugin_api_tests/basic_config.go b/app/plugin_api_tests/basic_config.go index 001288ba15..4cda1d9bb9 100644 --- a/app/plugin_api_tests/basic_config.go +++ b/app/plugin_api_tests/basic_config.go @@ -19,7 +19,7 @@ type BasicConfig struct { BasicUserID string } -func IsEmpty(object interface{}) bool { +func IsEmpty(object any) bool { // get nil case out of the way if object == nil { diff --git a/app/plugin_api_tests/manual.test_http_upgrade_websocket_plugin/main.go b/app/plugin_api_tests/manual.test_http_upgrade_websocket_plugin/main.go index 99a1ecac11..96930d7fbe 100644 --- a/app/plugin_api_tests/manual.test_http_upgrade_websocket_plugin/main.go +++ b/app/plugin_api_tests/manual.test_http_upgrade_websocket_plugin/main.go @@ -37,7 +37,7 @@ func (p *Plugin) ServeHTTP(_ *plugin.Context, w http.ResponseWriter, r *http.Req if err != nil { break } - resp := model.NewWebSocketResponse("OK", req.Seq, map[string]interface{}{"action": req.Action, "value": req.Data["value"]}) + resp := model.NewWebSocketResponse("OK", req.Seq, map[string]any{"action": req.Action, "value": req.Data["value"]}) respJSON, err := resp.ToJSON() if err != nil { break diff --git a/app/plugin_commands.go b/app/plugin_commands.go index 48c0dc8811..46201601e4 100644 --- a/app/plugin_commands.go +++ b/app/plugin_commands.go @@ -142,7 +142,7 @@ func (a *App) tryExecutePluginCommand(c *request.Context, args *model.CommandArg // Checking if plugin is working or not if err := pluginsEnvironment.PerformHealthCheck(matched.PluginId); err != nil { - return matched.Command, nil, model.NewAppError("ExecutePluginCommand", "model.plugin_command_error.error.app_error", map[string]interface{}{"Command": trigger}, "err= Plugin has recently crashed: "+matched.PluginId, http.StatusInternalServerError) + return matched.Command, nil, model.NewAppError("ExecutePluginCommand", "model.plugin_command_error.error.app_error", map[string]any{"Command": trigger}, "err= Plugin has recently crashed: "+matched.PluginId, http.StatusInternalServerError) } pluginHooks, err := pluginsEnvironment.HooksForPlugin(matched.PluginId) @@ -163,7 +163,7 @@ func (a *App) tryExecutePluginCommand(c *request.Context, args *model.CommandArg // Checking if plugin crashed after running the command if err := pluginsEnvironment.PerformHealthCheck(matched.PluginId); err != nil { errMessage := fmt.Sprintf("err= Plugin %s crashed due to /%s command", matched.PluginId, trigger) - return matched.Command, nil, model.NewAppError("ExecutePluginCommand", "model.plugin_command_crash.error.app_error", map[string]interface{}{"Command": trigger, "PluginId": matched.PluginId}, errMessage, http.StatusInternalServerError) + return matched.Command, nil, model.NewAppError("ExecutePluginCommand", "model.plugin_command_crash.error.app_error", map[string]any{"Command": trigger, "PluginId": matched.PluginId}, errMessage, http.StatusInternalServerError) } // This is a response from the plugin, which may set an incorrect status code; // e.g setting a status code of 0 will crash the server. So we always bucket everything under 500. diff --git a/app/plugin_commands_test.go b/app/plugin_commands_test.go index 5c3ffc4a64..e56cf74718 100644 --- a/app/plugin_commands_test.go +++ b/app/plugin_commands_test.go @@ -30,7 +30,7 @@ func TestPluginCommand(t *testing.T) { t.Run("command handled by plugin", func(t *testing.T) { th.App.UpdateConfig(func(cfg *model.Config) { - cfg.PluginSettings.Plugins["testloadpluginconfig"] = map[string]interface{}{ + cfg.PluginSettings.Plugins["testloadpluginconfig"] = map[string]any{ "TeamId": args.TeamId, } }) @@ -111,7 +111,7 @@ func TestPluginCommand(t *testing.T) { t.Run("re-entrant command registration on config change", func(t *testing.T) { th.App.UpdateConfig(func(cfg *model.Config) { - cfg.PluginSettings.Plugins["testloadpluginconfig"] = map[string]interface{}{ + cfg.PluginSettings.Plugins["testloadpluginconfig"] = map[string]any{ "TeamId": args.TeamId, } }) @@ -162,7 +162,7 @@ func TestPluginCommand(t *testing.T) { // Saving the plugin config eventually results in a call to // OnConfigurationChange. This used to deadlock on account of // effectively acquiring a RWLock reentrantly. - err := p.API.SavePluginConfig(map[string]interface{}{ + err := p.API.SavePluginConfig(map[string]any{ "TeamId": p.configuration.TeamId, }) if err != nil { @@ -218,7 +218,7 @@ func TestPluginCommand(t *testing.T) { t.Run("plugins can override built-in commands", func(t *testing.T) { th.App.UpdateConfig(func(cfg *model.Config) { - cfg.PluginSettings.Plugins["testloadpluginconfig"] = map[string]interface{}{ + cfg.PluginSettings.Plugins["testloadpluginconfig"] = map[string]any{ "TeamId": args.TeamId, } }) @@ -379,7 +379,7 @@ func TestPluginCommand(t *testing.T) { t.Run("plugin returning status code 0", func(t *testing.T) { th.App.UpdateConfig(func(cfg *model.Config) { - cfg.PluginSettings.Plugins["testloadpluginconfig"] = map[string]interface{}{ + cfg.PluginSettings.Plugins["testloadpluginconfig"] = map[string]any{ "TeamId": args.TeamId, } }) diff --git a/app/plugin_db_driver.go b/app/plugin_db_driver.go index 2b9cfbac7d..7962f8ede0 100644 --- a/app/plugin_db_driver.go +++ b/app/plugin_db_driver.go @@ -72,7 +72,7 @@ func (d *DriverImpl) ConnPing(connID string) error { return driver.ErrBadConn } - return conn.Raw(func(innerConn interface{}) error { + return conn.Raw(func(innerConn any) error { return innerConn.(driver.Pinger).Ping(context.Background()) }) } @@ -86,7 +86,7 @@ func (d *DriverImpl) ConnQuery(connID, q string, args []driver.NamedValue) (_ st return "", driver.ErrBadConn } - err = conn.Raw(func(innerConn interface{}) error { + err = conn.Raw(func(innerConn any) error { rows, err = innerConn.(driver.QueryerContext).QueryContext(context.Background(), q, args) return err }) @@ -112,7 +112,7 @@ func (d *DriverImpl) ConnExec(connID, q string, args []driver.NamedValue) (_ plu return ret, driver.ErrBadConn } - err = conn.Raw(func(innerConn interface{}) error { + err = conn.Raw(func(innerConn any) error { res, err = innerConn.(driver.ExecerContext).ExecContext(context.Background(), q, args) return err }) @@ -148,7 +148,7 @@ func (d *DriverImpl) Tx(connID string, opts driver.TxOptions) (_ string, err err return "", driver.ErrBadConn } - err = conn.Raw(func(innerConn interface{}) error { + err = conn.Raw(func(innerConn any) error { tx, err = innerConn.(driver.ConnBeginTx).BeginTx(context.Background(), opts) return err }) @@ -190,7 +190,7 @@ func (d *DriverImpl) Stmt(connID, q string) (_ string, err error) { return "", driver.ErrBadConn } - err = conn.Raw(func(innerConn interface{}) error { + err = conn.Raw(func(innerConn any) error { stmt, err = innerConn.(driver.Conn).Prepare(q) return err }) diff --git a/app/plugin_deadlock_test.go b/app/plugin_deadlock_test.go index eb151aeb64..359b9c4f41 100644 --- a/app/plugin_deadlock_test.go +++ b/app/plugin_deadlock_test.go @@ -54,7 +54,7 @@ func TestPluginDeadlock(t *testing.T) { UserId: "{{.User.Id}}", ChannelId: "{{.Channel.Id}}", Message: "message", - Props: map[string]interface{}{ + Props: map[string]any{ "from_plugin": true, }, }) @@ -129,7 +129,7 @@ func TestPluginDeadlock(t *testing.T) { UserId: "{{.User.Id}}", ChannelId: "{{.Channel.Id}}", Message: "message", - Props: map[string]interface{}{ + Props: map[string]any{ "from_plugin": true, }, }) @@ -244,7 +244,7 @@ func TestPluginDeadlock(t *testing.T) { UserId: "{{.User.Id}}", ChannelId: "{{.Channel.Id}}", Message: "messageUpdated", - Props: map[string]interface{}{ + Props: map[string]any{ "from_plugin": true, }, } diff --git a/app/plugin_hooks_test.go b/app/plugin_hooks_test.go index 84edff0335..08a160bbad 100644 --- a/app/plugin_hooks_test.go +++ b/app/plugin_hooks_test.go @@ -885,7 +885,7 @@ func TestErrorString(t *testing.T) { } func (p *MyPlugin) OnActivate() error { - return model.NewAppError("where", "id", map[string]interface{}{"param": 1}, "details", 42) + return model.NewAppError("where", "id", map[string]any{"param": 1}, "details", 42) } func main() { diff --git a/app/plugin_install.go b/app/plugin_install.go index a700f94916..73d6a9e20f 100644 --- a/app/plugin_install.go +++ b/app/plugin_install.go @@ -320,7 +320,7 @@ func extractPlugin(pluginFile io.ReadSeeker, extractDir string) (*model.Manifest } if !model.IsValidPluginId(manifest.Id) { - return nil, "", model.NewAppError("installPluginLocally", "app.plugin.invalid_id.app_error", map[string]interface{}{"Min": model.MinIdLength, "Max": model.MaxIdLength, "Regex": model.ValidIdRegex}, "", http.StatusBadRequest) + return nil, "", model.NewAppError("installPluginLocally", "app.plugin.invalid_id.app_error", map[string]any{"Min": model.MinIdLength, "Max": model.MaxIdLength, "Regex": model.ValidIdRegex}, "", http.StatusBadRequest) } return manifest, extractDir, nil diff --git a/app/post.go b/app/post.go index 217fdf2d19..c174bb99f8 100644 --- a/app/post.go +++ b/app/post.go @@ -44,12 +44,12 @@ func (a *App) CreatePostAsUser(c *request.Context, post *model.Post, currentSess // Check that channel has not been deleted channel, errCh := a.Srv().Store.Channel().Get(post.ChannelId, true) if errCh != nil { - err := model.NewAppError("CreatePostAsUser", "api.context.invalid_param.app_error", map[string]interface{}{"Name": "post.channel_id"}, errCh.Error(), http.StatusBadRequest) + err := model.NewAppError("CreatePostAsUser", "api.context.invalid_param.app_error", map[string]any{"Name": "post.channel_id"}, errCh.Error(), http.StatusBadRequest) return nil, err } if strings.HasPrefix(post.Type, model.PostSystemMessagePrefix) { - err := model.NewAppError("CreatePostAsUser", "api.context.invalid_param.app_error", map[string]interface{}{"Name": "post.type"}, "", http.StatusBadRequest) + err := model.NewAppError("CreatePostAsUser", "api.context.invalid_param.app_error", map[string]any{"Name": "post.type"}, "", http.StatusBadRequest) return nil, err } @@ -240,7 +240,7 @@ func (a *App) CreatePost(c *request.Context, post *model.Post, channel *model.Ch if attachments, ok := post.GetProp("attachments").([]*model.SlackAttachment); ok { jsonAttachments, err := json.Marshal(attachments) if err == nil { - attachmentsInterface := []interface{}{} + attachmentsInterface := []any{} err = json.Unmarshal(jsonAttachments, &attachmentsInterface) post.AddProp("attachments", attachmentsInterface) } @@ -410,13 +410,13 @@ func (a *App) attachFilesToPost(post *model.Post) *model.AppError { // If channel is nil, FillInPostProps will look up the channel corresponding to the post. func (a *App) FillInPostProps(post *model.Post, channel *model.Channel) *model.AppError { channelMentions := post.ChannelMentions() - channelMentionsProp := make(map[string]interface{}) + channelMentionsProp := make(map[string]any) if len(channelMentions) > 0 { if channel == nil { postChannel, err := a.Srv().Store.Channel().GetForPost(post.Id) if err != nil { - return model.NewAppError("FillInPostProps", "api.context.invalid_param.app_error", map[string]interface{}{"Name": "post.channel_id"}, err.Error(), http.StatusBadRequest) + return model.NewAppError("FillInPostProps", "api.context.invalid_param.app_error", map[string]any{"Name": "post.channel_id"}, err.Error(), http.StatusBadRequest) } channel = postChannel } @@ -433,7 +433,7 @@ func (a *App) FillInPostProps(post *model.Post, channel *model.Channel) *model.A mlog.Warn("Failed to get team of the channel mention", mlog.String("team_id", channel.TeamId), mlog.String("channel_id", channel.Id), mlog.Err(err)) continue } - channelMentionsProp[mentioned.Name] = map[string]interface{}{ + channelMentionsProp[mentioned.Name] = map[string]any{ "display_name": mentioned.DisplayName, "team_name": team.Name, } @@ -589,7 +589,7 @@ func (a *App) UpdatePost(c *request.Context, post *model.Post, safeUpdate bool) } if oldPost.DeleteAt != 0 { - err = model.NewAppError("UpdatePost", "api.post.update_post.permissions_details.app_error", map[string]interface{}{"PostId": post.Id}, "", http.StatusBadRequest) + err = model.NewAppError("UpdatePost", "api.post.update_post.permissions_details.app_error", map[string]any{"PostId": post.Id}, "", http.StatusBadRequest) return nil, err } @@ -599,7 +599,7 @@ func (a *App) UpdatePost(c *request.Context, post *model.Post, safeUpdate bool) } if *a.Config().ServiceSettings.PostEditTimeLimit != -1 && model.GetMillis() > oldPost.CreateAt+int64(*a.Config().ServiceSettings.PostEditTimeLimit*1000) && post.Message != oldPost.Message { - err = model.NewAppError("UpdatePost", "api.post.update_post.permissions_time_limit.app_error", map[string]interface{}{"timeLimit": *a.Config().ServiceSettings.PostEditTimeLimit}, "", http.StatusBadRequest) + err = model.NewAppError("UpdatePost", "api.post.update_post.permissions_time_limit.app_error", map[string]any{"timeLimit": *a.Config().ServiceSettings.PostEditTimeLimit}, "", http.StatusBadRequest) return nil, err } diff --git a/app/post_metadata.go b/app/post_metadata.go index 7ccd2f6198..75329b3f23 100644 --- a/app/post_metadata.go +++ b/app/post_metadata.go @@ -433,7 +433,7 @@ func (a *App) getFirstLinkAndImages(str string) (string, []string) { firstLink := "" images := []string{} - markdown.Inspect(str, func(blockOrInline interface{}) bool { + markdown.Inspect(str, func(blockOrInline any) bool { switch v := blockOrInline.(type) { case *markdown.Autolink: if link := v.Destination(); firstLink == "" && a.isLinkAllowedForPreview(link) { diff --git a/app/post_metadata_test.go b/app/post_metadata_test.go index 6ffa0f88a7..9f3566a5e5 100644 --- a/app/post_metadata_test.go +++ b/app/post_metadata_test.go @@ -213,7 +213,7 @@ func TestPreparePostForClient(t *testing.T) { UserId: th.BasicUser.Id, ChannelId: th.BasicChannel.Id, Message: ":" + emoji.Name + ": :taco:", - Props: map[string]interface{}{ + Props: map[string]any{ "attachments": []*model.SlackAttachment{ { Text: ":" + emoji.Name + ":", @@ -257,7 +257,7 @@ func TestPreparePostForClient(t *testing.T) { UserId: th.BasicUser.Id, ChannelId: th.BasicChannel.Id, Message: ":" + emoji3.Name + ": :taco:", - Props: map[string]interface{}{ + Props: map[string]any{ "attachments": []*model.SlackAttachment{ { Text: ":" + emoji4.Name + ":", @@ -490,9 +490,9 @@ func TestPreparePostForClient(t *testing.T) { post, err := th.App.CreatePost(th.Context, &model.Post{ UserId: th.BasicUser.Id, ChannelId: th.BasicChannel.Id, - Props: map[string]interface{}{ - "attachments": []interface{}{ - map[string]interface{}{ + Props: map[string]any{ + "attachments": []any{ + map[string]any{ "text": "![icon](" + server.URL + "/test-image1.png)", }, }, @@ -1300,7 +1300,7 @@ func TestGetImagesForPost(t *testing.T) { Embeds: []*model.PostEmbed{ { Type: model.PostEmbedOpengraph, - Data: map[string]interface{}{}, + Data: map[string]any{}, }, }, }, @@ -1401,7 +1401,7 @@ func TestGetEmojiNamesForPost(t *testing.T) { Description: "in message attachments", Post: &model.Post{ Message: "this is a post", - Props: map[string]interface{}{ + Props: map[string]any{ "attachments": []*model.SlackAttachment{ { Text: ":emoji1:", @@ -1429,7 +1429,7 @@ func TestGetEmojiNamesForPost(t *testing.T) { Description: "with duplicates", Post: &model.Post{ Message: "this is :emoji1", - Props: map[string]interface{}{ + Props: map[string]any{ "attachments": []*model.SlackAttachment{ { Text: ":emoji2:", @@ -1486,7 +1486,7 @@ func TestGetCustomEmojisForPost(t *testing.T) { post := &model.Post{ Message: ":" + emojis[1].Name + ":", - Props: map[string]interface{}{ + Props: map[string]any{ "attachments": []*model.SlackAttachment{ { Pretext: ":" + emojis[2].Name + ":", @@ -1512,7 +1512,7 @@ func TestGetCustomEmojisForPost(t *testing.T) { t.Run("with emojis that don't exist", func(t *testing.T) { post := &model.Post{ Message: ":secret: :" + emojis[0].Name + ":", - Props: map[string]interface{}{ + Props: map[string]any{ "attachments": []*model.SlackAttachment{ { Text: ":imaginary:", @@ -1529,7 +1529,7 @@ func TestGetCustomEmojisForPost(t *testing.T) { t.Run("with no emojis", func(t *testing.T) { post := &model.Post{ Message: "this post is boring", - Props: map[string]interface{}{}, + Props: map[string]any{}, } emojisForPost, err := th.App.getCustomEmojisForPost(post, nil) @@ -1693,7 +1693,7 @@ func TestGetImagesInMessageAttachments(t *testing.T) { { Name: "empty attachments", Post: &model.Post{ - Props: map[string]interface{}{ + Props: map[string]any{ "attachments": []*model.SlackAttachment{}, }, }, @@ -1702,7 +1702,7 @@ func TestGetImagesInMessageAttachments(t *testing.T) { { Name: "attachment with no fields that can contain images", Post: &model.Post{ - Props: map[string]interface{}{ + Props: map[string]any{ "attachments": []*model.SlackAttachment{ { Title: "This is the title", @@ -1715,7 +1715,7 @@ func TestGetImagesInMessageAttachments(t *testing.T) { { Name: "images in text", Post: &model.Post{ - Props: map[string]interface{}{ + Props: map[string]any{ "attachments": []*model.SlackAttachment{ { Text: "![logo](https://example.com/logo) and ![icon](https://example.com/icon)", @@ -1728,7 +1728,7 @@ func TestGetImagesInMessageAttachments(t *testing.T) { { Name: "images in pretext", Post: &model.Post{ - Props: map[string]interface{}{ + Props: map[string]any{ "attachments": []*model.SlackAttachment{ { Pretext: "![logo](https://example.com/logo1) and ![icon](https://example.com/icon1)", @@ -1741,7 +1741,7 @@ func TestGetImagesInMessageAttachments(t *testing.T) { { Name: "images in fields", Post: &model.Post{ - Props: map[string]interface{}{ + Props: map[string]any{ "attachments": []*model.SlackAttachment{ { Fields: []*model.SlackAttachmentField{ @@ -1758,7 +1758,7 @@ func TestGetImagesInMessageAttachments(t *testing.T) { { Name: "image in author_icon", Post: &model.Post{ - Props: map[string]interface{}{ + Props: map[string]any{ "attachments": []*model.SlackAttachment{ { AuthorIcon: "https://example.com/icon2", @@ -1771,7 +1771,7 @@ func TestGetImagesInMessageAttachments(t *testing.T) { { Name: "image in image_url", Post: &model.Post{ - Props: map[string]interface{}{ + Props: map[string]any{ "attachments": []*model.SlackAttachment{ { ImageURL: "https://example.com/image", @@ -1784,7 +1784,7 @@ func TestGetImagesInMessageAttachments(t *testing.T) { { Name: "image in thumb_url", Post: &model.Post{ - Props: map[string]interface{}{ + Props: map[string]any{ "attachments": []*model.SlackAttachment{ { ThumbURL: "https://example.com/image", @@ -1797,7 +1797,7 @@ func TestGetImagesInMessageAttachments(t *testing.T) { { Name: "image in footer_icon", Post: &model.Post{ - Props: map[string]interface{}{ + Props: map[string]any{ "attachments": []*model.SlackAttachment{ { FooterIcon: "https://example.com/image", @@ -1810,7 +1810,7 @@ func TestGetImagesInMessageAttachments(t *testing.T) { { Name: "images in multiple fields", Post: &model.Post{ - Props: map[string]interface{}{ + Props: map[string]any{ "attachments": []*model.SlackAttachment{ { Fields: []*model.SlackAttachmentField{ @@ -1830,7 +1830,7 @@ func TestGetImagesInMessageAttachments(t *testing.T) { { Name: "non-string field", Post: &model.Post{ - Props: map[string]interface{}{ + Props: map[string]any{ "attachments": []*model.SlackAttachment{ { Fields: []*model.SlackAttachmentField{ @@ -1847,7 +1847,7 @@ func TestGetImagesInMessageAttachments(t *testing.T) { { Name: "images in multiple locations", Post: &model.Post{ - Props: map[string]interface{}{ + Props: map[string]any{ "attachments": []*model.SlackAttachment{ { Text: "![text](https://example.com/text)", @@ -1869,7 +1869,7 @@ func TestGetImagesInMessageAttachments(t *testing.T) { { Name: "multiple attachments", Post: &model.Post{ - Props: map[string]interface{}{ + Props: map[string]any{ "attachments": []*model.SlackAttachment{ { Text: "![logo](https://example.com/logo)", diff --git a/app/post_test.go b/app/post_test.go index 5fe4156016..4cc4d44bfe 100644 --- a/app/post_test.go +++ b/app/post_test.go @@ -429,8 +429,8 @@ func TestPostChannelMentions(t *testing.T) { post, err = th.App.CreatePostAsUser(th.Context, post, "", true) require.Nil(t, err) - assert.Equal(t, map[string]interface{}{ - "mention-test": map[string]interface{}{ + assert.Equal(t, map[string]any{ + "mention-test": map[string]any{ "display_name": "Mention Test", "team_name": th.BasicTeam.Name, }, @@ -439,8 +439,8 @@ func TestPostChannelMentions(t *testing.T) { post.Message = fmt.Sprintf("goodbye, ~%v!", channelToMention.Name) result, err := th.App.UpdatePost(th.Context, post, false) require.Nil(t, err) - assert.Equal(t, map[string]interface{}{ - "mention-test": map[string]interface{}{ + assert.Equal(t, map[string]any{ + "mention-test": map[string]any{ "display_name": "Mention Test", "team_name": th.BasicTeam.Name, }, @@ -858,7 +858,7 @@ func TestCreatePost(t *testing.T) { Description string Channel *model.Channel Author string - Assert func(t assert.TestingT, object interface{}, msgAndArgs ...interface{}) bool + Assert func(t assert.TestingT, object any, msgAndArgs ...any) bool }{ { Description: "removes metadata from post for members who cannot read channel", @@ -1345,7 +1345,7 @@ func TestUpdatePost(t *testing.T) { Description string Channel *model.Channel Author string - Assert func(t assert.TestingT, object interface{}, msgAndArgs ...interface{}) bool + Assert func(t assert.TestingT, object any, msgAndArgs ...any) bool }{ { Description: "removes metadata from post for members who cannot read channel", @@ -1879,7 +1879,7 @@ func TestCountMentionsFromPost(t *testing.T) { ChannelId: channel.Id, Message: "test", Type: model.PostTypeAddToChannel, - Props: map[string]interface{}{ + Props: map[string]any{ model.PostPropsAddedUserId: model.NewId(), }, }, channel, false, true) @@ -1889,7 +1889,7 @@ func TestCountMentionsFromPost(t *testing.T) { ChannelId: channel.Id, Message: "test2", Type: model.PostTypeAddToChannel, - Props: map[string]interface{}{ + Props: map[string]any{ model.PostPropsAddedUserId: user2.Id, }, }, channel, false, true) @@ -1899,7 +1899,7 @@ func TestCountMentionsFromPost(t *testing.T) { ChannelId: channel.Id, Message: "test3", Type: model.PostTypeAddToChannel, - Props: map[string]interface{}{ + Props: map[string]any{ model.PostPropsAddedUserId: user2.Id, }, }, channel, false, true) @@ -2089,7 +2089,7 @@ func TestCountMentionsFromPost(t *testing.T) { UserId: user2.Id, ChannelId: channel.Id, Message: fmt.Sprintf("@%s", user2.Username), - Props: map[string]interface{}{ + Props: map[string]any{ "from_webhook": "true", }, }, channel, false, true) diff --git a/app/product.go b/app/product.go index 2e09f137c8..a8c15a9e0a 100644 --- a/app/product.go +++ b/app/product.go @@ -14,7 +14,7 @@ type Product interface { } type ProductManifest struct { - Initializer func(*Server, map[ServiceKey]interface{}) (Product, error) + Initializer func(*Server, map[ServiceKey]any) (Product, error) Dependencies map[ServiceKey]struct{} } @@ -26,7 +26,7 @@ func RegisterProduct(name string, m ProductManifest) { func (s *Server) initializeProducts( productMap map[string]ProductManifest, - serviceMap map[ServiceKey]interface{}, + serviceMap map[ServiceKey]any, ) error { // create a product map to consume pmap := make(map[string]struct{}) diff --git a/app/product_notices.go b/app/product_notices.go index a3692db342..810cfe006a 100644 --- a/app/product_notices.go +++ b/app/product_notices.go @@ -198,7 +198,7 @@ func noticeMatchesConditions(config *model.Config, preferences store.PreferenceS return true, nil } -func validateUserConfigEntry(preferences store.PreferenceStore, userID string, key string, expectedValue interface{}) (bool, error) { +func validateUserConfigEntry(preferences store.PreferenceStore, userID string, key string, expectedValue any) (bool, error) { parts := strings.Split(key, ".") if len(parts) != 2 { return false, errors.New("Invalid format of user config. Must be in form of Category.SettingName") @@ -213,7 +213,7 @@ func validateUserConfigEntry(preferences store.PreferenceStore, userID string, k return pref.Value == expectedValue, nil } -func validateConfigEntry(conf *model.Config, path string, expectedValue interface{}) bool { +func validateConfigEntry(conf *model.Config, path string, expectedValue any) bool { value, found := config.GetValueByPath(strings.Split(path, "."), *conf) if !found { return false diff --git a/app/product_notices_test.go b/app/product_notices_test.go index 8fe49db619..c2f04dcff6 100644 --- a/app/product_notices_test.go +++ b/app/product_notices_test.go @@ -114,7 +114,7 @@ func TestNoticeValidation(t *testing.T) { args: args{ notice: &model.ProductNotice{ Conditions: model.Conditions{ - ServerConfig: map[string]interface{}{"ServiceSettings.LetsEncryptCertificateCacheFile": "./config/letsencrypt.cache"}, + ServerConfig: map[string]any{"ServiceSettings.LetsEncryptCertificateCacheFile": "./config/letsencrypt.cache"}, }, }, }, @@ -126,7 +126,7 @@ func TestNoticeValidation(t *testing.T) { args: args{ notice: &model.ProductNotice{ Conditions: model.Conditions{ - ServerConfig: map[string]interface{}{"ServiceSettings.ZZ": "test"}, + ServerConfig: map[string]any{"ServiceSettings.ZZ": "test"}, }, }, }, @@ -138,7 +138,7 @@ func TestNoticeValidation(t *testing.T) { args: args{ notice: &model.ProductNotice{ Conditions: model.Conditions{ - UserConfig: map[string]interface{}{"Stuff": "test"}, + UserConfig: map[string]any{"Stuff": "test"}, }, }, }, @@ -150,7 +150,7 @@ func TestNoticeValidation(t *testing.T) { args: args{ notice: &model.ProductNotice{ Conditions: model.Conditions{ - UserConfig: map[string]interface{}{"Stuff.Data": "test"}, + UserConfig: map[string]any{"Stuff.Data": "test"}, }, }, }, @@ -162,7 +162,7 @@ func TestNoticeValidation(t *testing.T) { args: args{ notice: &model.ProductNotice{ Conditions: model.Conditions{ - UserConfig: map[string]interface{}{"Stuff.Data2": "test"}, + UserConfig: map[string]any{"Stuff.Data2": "test"}, }, }, }, @@ -174,7 +174,7 @@ func TestNoticeValidation(t *testing.T) { args: args{ notice: &model.ProductNotice{ Conditions: model.Conditions{ - UserConfig: map[string]interface{}{"Stuff.Data3": "stuff"}, + UserConfig: map[string]any{"Stuff.Data3": "stuff"}, }, }, }, diff --git a/app/product_test.go b/app/product_test.go index 1bfd408773..bafba19cbd 100644 --- a/app/product_test.go +++ b/app/product_test.go @@ -16,7 +16,7 @@ const ( type productA struct{} -func newProductA(s *Server, m map[ServiceKey]interface{}) (Product, error) { +func newProductA(s *Server, m map[ServiceKey]any) (Product, error) { m[testSrvKey1] = nil return &productA{}, nil } @@ -26,7 +26,7 @@ func (p *productA) Stop() error { return nil } type productB struct{} -func newProductB(s *Server, m map[ServiceKey]interface{}) (Product, error) { +func newProductB(s *Server, m map[ServiceKey]any) (Product, error) { m[testSrvKey2] = nil return &productB{}, nil } @@ -36,7 +36,7 @@ func (p *productB) Stop() error { return nil } func TestInitializeProducts(t *testing.T) { t.Run("2 products and no circular dependency", func(t *testing.T) { - serviceMap := map[ServiceKey]interface{}{ + serviceMap := map[ServiceKey]any{ ConfigKey: nil, LicenseKey: nil, FilestoreKey: nil, @@ -73,7 +73,7 @@ func TestInitializeProducts(t *testing.T) { }) t.Run("2 products and circular dependency", func(t *testing.T) { - serviceMap := map[ServiceKey]interface{}{ + serviceMap := map[ServiceKey]any{ ConfigKey: nil, LicenseKey: nil, FilestoreKey: nil, @@ -110,7 +110,7 @@ func TestInitializeProducts(t *testing.T) { }) t.Run("2 products and one w/o any dependency", func(t *testing.T) { - serviceMap := map[ServiceKey]interface{}{ + serviceMap := map[ServiceKey]any{ ConfigKey: nil, LicenseKey: nil, FilestoreKey: nil, diff --git a/app/request/context.go b/app/request/context.go index c3d895fdc5..e822c25568 100644 --- a/app/request/context.go +++ b/app/request/context.go @@ -45,7 +45,7 @@ func EmptyContext() *Context { } } -func (c *Context) T(translationID string, args ...interface{}) string { +func (c *Context) T(translationID string, args ...any) string { return c.t(translationID, args...) } func (c *Context) Session() *model.Session { diff --git a/app/saml.go b/app/saml.go index 4677a81831..58787bf08a 100644 --- a/app/saml.go +++ b/app/saml.go @@ -108,7 +108,7 @@ func (a *App) AddSamlIdpCertificate(fileData *multipart.FileHeader) *model.AppEr func (a *App) removeSamlFile(filename string) *model.AppError { if err := a.Srv().configStore.RemoveFile(filename); err != nil { - return model.NewAppError("RemoveSamlFile", "api.admin.remove_certificate.delete.app_error", map[string]interface{}{"Filename": filename}, err.Error(), http.StatusInternalServerError) + return model.NewAppError("RemoveSamlFile", "api.admin.remove_certificate.delete.app_error", map[string]any{"Filename": filename}, err.Error(), http.StatusInternalServerError) } return nil diff --git a/app/server.go b/app/server.go index c148a9a2b5..391ffed9e6 100644 --- a/app/server.go +++ b/app/server.go @@ -392,7 +392,7 @@ func NewServer(options ...Option) (*Server, error) { return nil, errors.Wrapf(err, "unable to create teams service") } - serviceMap := map[ServiceKey]interface{}{ + serviceMap := map[ServiceKey]any{ ChannelKey: &channelsWrapper{srv: s}, ConfigKey: s.configStore, LicenseKey: s.licenseWrapper, diff --git a/app/server_inactivity.go b/app/server_inactivity.go index 27164d47b0..3bb83e7f0c 100644 --- a/app/server_inactivity.go +++ b/app/server_inactivity.go @@ -75,7 +75,7 @@ func (s *Server) takeInactivityAction() { mlog.Warn("No SiteURL configured") } - properties := map[string]interface{}{ + properties := map[string]any{ "SiteURL": siteURL, } s.GetTelemetryService().SendTelemetry("inactive_server", properties) diff --git a/app/session.go b/app/session.go index e1a4e1c913..c412edaa67 100644 --- a/app/session.go +++ b/app/session.go @@ -44,7 +44,7 @@ func (a *App) GetCloudSession(token string) (*model.Session, *model.AppError) { session.AddProp(model.SessionPropType, model.SessionTypeCloudKey) return session, nil } - return nil, model.NewAppError("GetCloudSession", "api.context.invalid_token.error", map[string]interface{}{"Token": token, "Error": ""}, "The provided token is invalid", http.StatusUnauthorized) + return nil, model.NewAppError("GetCloudSession", "api.context.invalid_token.error", map[string]any{"Token": token, "Error": ""}, "The provided token is invalid", http.StatusUnauthorized) } func (a *App) GetRemoteClusterSession(token string, remoteId string) (*model.Session, *model.AppError) { @@ -59,7 +59,7 @@ func (a *App) GetRemoteClusterSession(token string, remoteId string) (*model.Ses session.AddProp(model.SessionPropType, model.SessionTypeRemoteclusterToken) return session, nil } - return nil, model.NewAppError("GetRemoteClusterSession", "api.context.invalid_token.error", map[string]interface{}{"Token": token, "Error": ""}, "The provided token is invalid", http.StatusUnauthorized) + return nil, model.NewAppError("GetRemoteClusterSession", "api.context.invalid_token.error", map[string]any{"Token": token, "Error": ""}, "The provided token is invalid", http.StatusUnauthorized) } func (a *App) GetSession(token string) (*model.Session, *model.AppError) { @@ -68,7 +68,7 @@ func (a *App) GetSession(token string) (*model.Session, *model.AppError) { // If we don't have the session we are going to create one with the token eventually. if session, _ = a.ch.srv.userService.GetSession(token); session != nil { if session.Token != token { - return nil, model.NewAppError("GetSession", "api.context.invalid_token.error", map[string]interface{}{"Token": token, "Error": ""}, "session token is different from the one in DB", http.StatusUnauthorized) + return nil, model.NewAppError("GetSession", "api.context.invalid_token.error", map[string]any{"Token": token, "Error": ""}, "session token is different from the one in DB", http.StatusUnauthorized) } if !session.IsExpired() { @@ -88,12 +88,12 @@ func (a *App) GetSession(token string) (*model.Session, *model.AppError) { } else { mlog.Warn("Error while creating session for user access token", mlog.Err(appErr)) } - return nil, model.NewAppError("GetSession", "api.context.invalid_token.error", map[string]interface{}{"Token": token, "Error": detailedError}, "", statusCode) + return nil, model.NewAppError("GetSession", "api.context.invalid_token.error", map[string]any{"Token": token, "Error": detailedError}, "", statusCode) } } if session.Id == "" || session.IsExpired() { - return nil, model.NewAppError("GetSession", "api.context.invalid_token.error", map[string]interface{}{"Token": token, "Error": ""}, "session is either nil or expired", http.StatusUnauthorized) + return nil, model.NewAppError("GetSession", "api.context.invalid_token.error", map[string]any{"Token": token, "Error": ""}, "session is either nil or expired", http.StatusUnauthorized) } if *a.Config().ServiceSettings.SessionIdleTimeoutInMinutes > 0 && @@ -116,7 +116,7 @@ func (a *App) GetSession(token string) (*model.Session, *model.AppError) { mlog.Warn("Error while revoking session", mlog.Err(err)) } }) - return nil, model.NewAppError("GetSession", "api.context.invalid_token.error", map[string]interface{}{"Token": token, "Error": ""}, "idle timeout", http.StatusUnauthorized) + return nil, model.NewAppError("GetSession", "api.context.invalid_token.error", map[string]any{"Token": token, "Error": ""}, "idle timeout", http.StatusUnauthorized) } } diff --git a/app/slashcommands/command_channel_header.go b/app/slashcommands/command_channel_header.go index 24a8acb884..d6c25dab08 100644 --- a/app/slashcommands/command_channel_header.go +++ b/app/slashcommands/command_channel_header.go @@ -97,7 +97,7 @@ func (*HeaderProvider) DoCommand(a *app.App, c *request.Context, args *model.Com if err != nil { text := args.T("api.command_channel_header.update_channel.app_error") if err.Id == "model.channel.is_valid.header.app_error" { - text = args.T("api.command_channel_header.update_channel.max_length", map[string]interface{}{ + text = args.T("api.command_channel_header.update_channel.max_length", map[string]any{ "MaxLength": model.ChannelHeaderMaxRunes, }) } diff --git a/app/slashcommands/command_channel_header_test.go b/app/slashcommands/command_channel_header_test.go index 5a6ec51fa5..1cf7d4d6a4 100644 --- a/app/slashcommands/command_channel_header_test.go +++ b/app/slashcommands/command_channel_header_test.go @@ -21,7 +21,7 @@ func TestHeaderProviderDoCommand(t *testing.T) { // Try a public channel *with* permission. args := &model.CommandArgs{ - T: func(s string, args ...interface{}) string { return s }, + T: func(s string, args ...any) string { return s }, ChannelId: th.BasicChannel.Id, UserId: th.BasicUser.Id, } @@ -38,7 +38,7 @@ func TestHeaderProviderDoCommand(t *testing.T) { // Try a public channel *without* permission. args = &model.CommandArgs{ - T: func(s string, args ...interface{}) string { return s }, + T: func(s string, args ...any) string { return s }, ChannelId: th.BasicChannel.Id, UserId: th.BasicUser.Id, } @@ -52,7 +52,7 @@ func TestHeaderProviderDoCommand(t *testing.T) { privateChannel := th.createPrivateChannel(th.BasicTeam) args = &model.CommandArgs{ - T: func(s string, args ...interface{}) string { return s }, + T: func(s string, args ...any) string { return s }, ChannelId: privateChannel.Id, UserId: th.BasicUser.Id, } @@ -64,7 +64,7 @@ func TestHeaderProviderDoCommand(t *testing.T) { // Try a private channel *without* permission. args = &model.CommandArgs{ - T: func(s string, args ...interface{}) string { return s }, + T: func(s string, args ...any) string { return s }, ChannelId: privateChannel.Id, UserId: th.BasicUser.Id, } @@ -80,7 +80,7 @@ func TestHeaderProviderDoCommand(t *testing.T) { groupChannel := th.createGroupChannel(user1, user2) args = &model.CommandArgs{ - T: func(s string, args ...interface{}) string { return s }, + T: func(s string, args ...any) string { return s }, ChannelId: groupChannel.Id, UserId: user1.Id, } @@ -90,7 +90,7 @@ func TestHeaderProviderDoCommand(t *testing.T) { // Try a group channel *without* being a member. args = &model.CommandArgs{ - T: func(s string, args ...interface{}) string { return s }, + T: func(s string, args ...any) string { return s }, ChannelId: groupChannel.Id, UserId: user3.Id, } @@ -102,7 +102,7 @@ func TestHeaderProviderDoCommand(t *testing.T) { directChannel := th.createDmChannel(user1) args = &model.CommandArgs{ - T: func(s string, args ...interface{}) string { return s }, + T: func(s string, args ...any) string { return s }, ChannelId: directChannel.Id, UserId: th.BasicUser.Id, } @@ -112,7 +112,7 @@ func TestHeaderProviderDoCommand(t *testing.T) { // Try a direct channel *without* being a member. args = &model.CommandArgs{ - T: func(s string, args ...interface{}) string { return s }, + T: func(s string, args ...any) string { return s }, ChannelId: directChannel.Id, UserId: user2.Id, } diff --git a/app/slashcommands/command_channel_purpose.go b/app/slashcommands/command_channel_purpose.go index e51947039a..b3760934b0 100644 --- a/app/slashcommands/command_channel_purpose.go +++ b/app/slashcommands/command_channel_purpose.go @@ -82,7 +82,7 @@ func (*PurposeProvider) DoCommand(a *app.App, c *request.Context, args *model.Co if err != nil { text := args.T("api.command_channel_purpose.update_channel.app_error") if err.Id == "model.channel.is_valid.purpose.app_error" { - text = args.T("api.command_channel_purpose.update_channel.max_length", map[string]interface{}{ + text = args.T("api.command_channel_purpose.update_channel.max_length", map[string]any{ "MaxLength": model.ChannelPurposeMaxRunes, }) } diff --git a/app/slashcommands/command_channel_purpose_test.go b/app/slashcommands/command_channel_purpose_test.go index d03b647ac5..3f6e9a71d9 100644 --- a/app/slashcommands/command_channel_purpose_test.go +++ b/app/slashcommands/command_channel_purpose_test.go @@ -21,7 +21,7 @@ func TestPurposeProviderDoCommand(t *testing.T) { th.addPermissionToRole(model.PermissionManagePublicChannelProperties.Id, model.ChannelUserRoleId) args := &model.CommandArgs{ - T: func(s string, args ...interface{}) string { return s }, + T: func(s string, args ...any) string { return s }, ChannelId: th.BasicChannel.Id, UserId: th.BasicUser.Id, } @@ -38,7 +38,7 @@ func TestPurposeProviderDoCommand(t *testing.T) { th.removePermissionFromRole(model.PermissionManagePublicChannelProperties.Id, model.ChannelUserRoleId) args = &model.CommandArgs{ - T: func(s string, args ...interface{}) string { return s }, + T: func(s string, args ...any) string { return s }, ChannelId: th.BasicChannel.Id, } @@ -51,7 +51,7 @@ func TestPurposeProviderDoCommand(t *testing.T) { th.addPermissionToRole(model.PermissionManagePrivateChannelProperties.Id, model.ChannelUserRoleId) args = &model.CommandArgs{ - T: func(s string, args ...interface{}) string { return s }, + T: func(s string, args ...any) string { return s }, ChannelId: privateChannel.Id, UserId: th.BasicUser.Id, } @@ -63,7 +63,7 @@ func TestPurposeProviderDoCommand(t *testing.T) { th.removePermissionFromRole(model.PermissionManagePrivateChannelProperties.Id, model.ChannelUserRoleId) args = &model.CommandArgs{ - T: func(s string, args ...interface{}) string { return s }, + T: func(s string, args ...any) string { return s }, ChannelId: privateChannel.Id, } @@ -77,7 +77,7 @@ func TestPurposeProviderDoCommand(t *testing.T) { groupChannel := th.createGroupChannel(user1, user2) args = &model.CommandArgs{ - T: func(s string, args ...interface{}) string { return s }, + T: func(s string, args ...any) string { return s }, ChannelId: groupChannel.Id, } @@ -88,7 +88,7 @@ func TestPurposeProviderDoCommand(t *testing.T) { directChannel := th.createDmChannel(user1) args = &model.CommandArgs{ - T: func(s string, args ...interface{}) string { return s }, + T: func(s string, args ...any) string { return s }, ChannelId: directChannel.Id, } diff --git a/app/slashcommands/command_channel_rename.go b/app/slashcommands/command_channel_rename.go index bf892374ec..cf2987c993 100644 --- a/app/slashcommands/command_channel_rename.go +++ b/app/slashcommands/command_channel_rename.go @@ -73,14 +73,14 @@ func (*RenameProvider) DoCommand(a *app.App, c *request.Context, args *model.Com } } else if len(message) > model.ChannelNameMaxLength { return &model.CommandResponse{ - Text: args.T("api.command_channel_rename.too_long.app_error", map[string]interface{}{ + Text: args.T("api.command_channel_rename.too_long.app_error", map[string]any{ "Length": model.ChannelNameMaxLength, }), ResponseType: model.CommandResponseTypeEphemeral, } } else if len(message) < model.ChannelNameMinLength { return &model.CommandResponse{ - Text: args.T("api.command_channel_rename.too_short.app_error", map[string]interface{}{ + Text: args.T("api.command_channel_rename.too_short.app_error", map[string]any{ "Length": model.ChannelNameMinLength, }), ResponseType: model.CommandResponseTypeEphemeral, diff --git a/app/slashcommands/command_channel_rename_test.go b/app/slashcommands/command_channel_rename_test.go index 26fd9686df..ff8aabbb64 100644 --- a/app/slashcommands/command_channel_rename_test.go +++ b/app/slashcommands/command_channel_rename_test.go @@ -20,7 +20,7 @@ func TestRenameProviderDoCommand(t *testing.T) { rp := RenameProvider{} args := &model.CommandArgs{ - T: func(s string, args ...interface{}) string { return s }, + T: func(s string, args ...any) string { return s }, ChannelId: th.BasicChannel.Id, UserId: th.BasicUser.Id, } @@ -41,7 +41,7 @@ func TestRenameProviderDoCommand(t *testing.T) { th.removePermissionFromRole(model.PermissionManagePublicChannelProperties.Id, model.ChannelUserRoleId) args = &model.CommandArgs{ - T: func(s string, args ...interface{}) string { return s }, + T: func(s string, args ...any) string { return s }, ChannelId: th.BasicChannel.Id, UserId: th.BasicUser.Id, } @@ -55,7 +55,7 @@ func TestRenameProviderDoCommand(t *testing.T) { th.addPermissionToRole(model.PermissionManagePrivateChannelProperties.Id, model.ChannelUserRoleId) args = &model.CommandArgs{ - T: func(s string, args ...interface{}) string { return s }, + T: func(s string, args ...any) string { return s }, ChannelId: privateChannel.Id, UserId: th.BasicUser.Id, } @@ -67,7 +67,7 @@ func TestRenameProviderDoCommand(t *testing.T) { th.removePermissionFromRole(model.PermissionManagePrivateChannelProperties.Id, model.ChannelUserRoleId) args = &model.CommandArgs{ - T: func(s string, args ...interface{}) string { return s }, + T: func(s string, args ...any) string { return s }, ChannelId: privateChannel.Id, UserId: th.BasicUser.Id, } @@ -82,7 +82,7 @@ func TestRenameProviderDoCommand(t *testing.T) { groupChannel := th.createGroupChannel(user1, user2) args = &model.CommandArgs{ - T: func(s string, args ...interface{}) string { return s }, + T: func(s string, args ...any) string { return s }, ChannelId: groupChannel.Id, UserId: th.BasicUser.Id, } @@ -94,7 +94,7 @@ func TestRenameProviderDoCommand(t *testing.T) { directChannel := th.createDmChannel(user1) args = &model.CommandArgs{ - T: func(s string, args ...interface{}) string { return s }, + T: func(s string, args ...any) string { return s }, ChannelId: directChannel.Id, UserId: th.BasicUser.Id, } diff --git a/app/slashcommands/command_code_test.go b/app/slashcommands/command_code_test.go index 732b3bef0a..e43bd6d469 100644 --- a/app/slashcommands/command_code_test.go +++ b/app/slashcommands/command_code_test.go @@ -12,7 +12,7 @@ import ( func TestCodeProviderDoCommand(t *testing.T) { cp := CodeProvider{} args := &model.CommandArgs{ - T: func(s string, args ...interface{}) string { return s }, + T: func(s string, args ...any) string { return s }, } for msg, expected := range map[string]string{ diff --git a/app/slashcommands/command_custom_status.go b/app/slashcommands/command_custom_status.go index a75fbcbf65..4f50614c8d 100644 --- a/app/slashcommands/command_custom_status.go +++ b/app/slashcommands/command_custom_status.go @@ -68,7 +68,7 @@ func (*CustomStatusProvider) DoCommand(a *app.App, c *request.Context, args *mod return &model.CommandResponse{ ResponseType: model.CommandResponseTypeEphemeral, - Text: args.T("api.command_custom_status.success", map[string]interface{}{ + Text: args.T("api.command_custom_status.success", map[string]any{ "EmojiName": ":" + customStatus.Emoji + ":", "StatusMessage": customStatus.Text, }), diff --git a/app/slashcommands/command_groupmsg.go b/app/slashcommands/command_groupmsg.go index 8ecf74da46..4b26675f9e 100644 --- a/app/slashcommands/command_groupmsg.go +++ b/app/slashcommands/command_groupmsg.go @@ -73,7 +73,7 @@ func (*groupmsgProvider) DoCommand(a *app.App, c *request.Context, args *model.C } if len(invalidUsernames) > 0 { - invalidUsersString := map[string]interface{}{ + invalidUsersString := map[string]any{ "Users": "@" + strings.Join(invalidUsernames, ", @"), } return &model.CommandResponse{ @@ -87,7 +87,7 @@ func (*groupmsgProvider) DoCommand(a *app.App, c *request.Context, args *model.C } if len(targetUsersSlice) < model.ChannelGroupMinUsers { - minUsers := map[string]interface{}{ + minUsers := map[string]any{ "MinUsers": model.ChannelGroupMinUsers - 1, } return &model.CommandResponse{ @@ -97,7 +97,7 @@ func (*groupmsgProvider) DoCommand(a *app.App, c *request.Context, args *model.C } if len(targetUsersSlice) > model.ChannelGroupMaxUsers { - maxUsers := map[string]interface{}{ + maxUsers := map[string]any{ "MaxUsers": model.ChannelGroupMaxUsers - 1, } return &model.CommandResponse{ diff --git a/app/slashcommands/command_invite.go b/app/slashcommands/command_invite.go index a6b0625b76..6ba9e22dc8 100644 --- a/app/slashcommands/command_invite.go +++ b/app/slashcommands/command_invite.go @@ -75,7 +75,7 @@ func (*InviteProvider) DoCommand(a *app.App, c *request.Context, args *model.Com if channelToJoin, err = a.GetChannelByName(targetChannelName, args.TeamId, false); err != nil { return &model.CommandResponse{ - Text: args.T("api.command_invite.channel.error", map[string]interface{}{ + Text: args.T("api.command_invite.channel.error", map[string]any{ "Channel": targetChannelName, }), ResponseType: model.CommandResponseTypeEphemeral, @@ -96,7 +96,7 @@ func (*InviteProvider) DoCommand(a *app.App, c *request.Context, args *model.Com case model.ChannelTypeOpen: if !a.HasPermissionToChannel(args.UserId, channelToJoin.Id, model.PermissionManagePublicChannelMembers) { return &model.CommandResponse{ - Text: args.T("api.command_invite.permission.app_error", map[string]interface{}{ + Text: args.T("api.command_invite.permission.app_error", map[string]any{ "User": userProfile.Username, "Channel": channelToJoin.Name, }), @@ -108,7 +108,7 @@ func (*InviteProvider) DoCommand(a *app.App, c *request.Context, args *model.Com if _, err = a.GetChannelMember(context.Background(), channelToJoin.Id, args.UserId); err == nil { // User doing the inviting is a member of the channel. return &model.CommandResponse{ - Text: args.T("api.command_invite.permission.app_error", map[string]interface{}{ + Text: args.T("api.command_invite.permission.app_error", map[string]any{ "User": userProfile.Username, "Channel": channelToJoin.Name, }), @@ -117,7 +117,7 @@ func (*InviteProvider) DoCommand(a *app.App, c *request.Context, args *model.Com } // User doing the inviting is *not* a member of the channel. return &model.CommandResponse{ - Text: args.T("api.command_invite.private_channel.app_error", map[string]interface{}{ + Text: args.T("api.command_invite.private_channel.app_error", map[string]any{ "Channel": channelToJoin.Name, }), ResponseType: model.CommandResponseTypeEphemeral, @@ -134,7 +134,7 @@ func (*InviteProvider) DoCommand(a *app.App, c *request.Context, args *model.Com _, err = a.GetChannelMember(context.Background(), channelToJoin.Id, userProfile.Id) if err == nil { return &model.CommandResponse{ - Text: args.T("api.command_invite.user_already_in_channel.app_error", map[string]interface{}{ + Text: args.T("api.command_invite.user_already_in_channel.app_error", map[string]any{ "User": userProfile.Username, }), ResponseType: model.CommandResponseTypeEphemeral, @@ -149,7 +149,7 @@ func (*InviteProvider) DoCommand(a *app.App, c *request.Context, args *model.Com text = args.T("api.command_invite.group_constrained_user_denied") } else if err.Id == "app.team.get_member.missing.app_error" || err.Id == "api.channel.add_user.to.channel.failed.deleted.app_error" { - text = args.T("api.command_invite.user_not_in_team.app_error", map[string]interface{}{ + text = args.T("api.command_invite.user_not_in_team.app_error", map[string]any{ "Username": userProfile.Username, }) } else { @@ -163,7 +163,7 @@ func (*InviteProvider) DoCommand(a *app.App, c *request.Context, args *model.Com if args.ChannelId != channelToJoin.Id { return &model.CommandResponse{ - Text: args.T("api.command_invite.success", map[string]interface{}{ + Text: args.T("api.command_invite.success", map[string]any{ "User": userProfile.Username, "Channel": channelToJoin.Name, }), diff --git a/app/slashcommands/command_invite_people_test.go b/app/slashcommands/command_invite_people_test.go index 0a13e7b433..8956b884b5 100644 --- a/app/slashcommands/command_invite_people_test.go +++ b/app/slashcommands/command_invite_people_test.go @@ -26,7 +26,7 @@ func TestInvitePeopleProvider(t *testing.T) { // Test without required permissions args := &model.CommandArgs{ - T: func(s string, args ...interface{}) string { return s }, + T: func(s string, args ...any) string { return s }, ChannelId: th.BasicChannel.Id, TeamId: th.BasicTeam.Id, UserId: notTeamUser.Id, diff --git a/app/slashcommands/command_invite_test.go b/app/slashcommands/command_invite_test.go index b792cf8807..25525a8cd2 100644 --- a/app/slashcommands/command_invite_test.go +++ b/app/slashcommands/command_invite_test.go @@ -58,7 +58,7 @@ func TestInviteProvider(t *testing.T) { InviteP := InviteProvider{} args := &model.CommandArgs{ - T: func(s string, args ...interface{}) string { return s }, + T: func(s string, args ...any) string { return s }, ChannelId: th.BasicChannel.Id, TeamId: th.BasicTeam.Id, UserId: th.BasicUser.Id, @@ -195,7 +195,7 @@ func TestInviteGroup(t *testing.T) { InviteP := InviteProvider{} args := &model.CommandArgs{ - T: func(s string, args ...interface{}) string { return s }, + T: func(s string, args ...any) string { return s }, ChannelId: th.BasicChannel.Id, TeamId: th.BasicTeam.Id, UserId: th.BasicUser.Id, diff --git a/app/slashcommands/command_leave.go b/app/slashcommands/command_leave.go index ad3a80f032..e3b0893ac1 100644 --- a/app/slashcommands/command_leave.go +++ b/app/slashcommands/command_leave.go @@ -49,7 +49,7 @@ func (*LeaveProvider) DoCommand(a *app.App, c *request.Context, args *model.Comm err = a.LeaveChannel(c, args.ChannelId, args.UserId) if err != nil { if channel.Name == model.DefaultChannelName { - return &model.CommandResponse{Text: args.T("api.channel.leave.default.app_error", map[string]interface{}{"Channel": model.DefaultChannelName}), ResponseType: model.CommandResponseTypeEphemeral} + return &model.CommandResponse{Text: args.T("api.channel.leave.default.app_error", map[string]any{"Channel": model.DefaultChannelName}), ResponseType: model.CommandResponseTypeEphemeral} } return &model.CommandResponse{Text: args.T("api.command_leave.fail.app_error"), ResponseType: model.CommandResponseTypeEphemeral} } diff --git a/app/slashcommands/command_leave_test.go b/app/slashcommands/command_leave_test.go index c883f418c3..b04b5492c2 100644 --- a/app/slashcommands/command_leave_test.go +++ b/app/slashcommands/command_leave_test.go @@ -50,7 +50,7 @@ func TestLeaveProviderDoCommand(t *testing.T) { t.Run("Should error when no Channel ID in args", func(t *testing.T) { args := &model.CommandArgs{ UserId: th.BasicUser.Id, - T: func(s string, args ...interface{}) string { return s }, + T: func(s string, args ...any) string { return s }, } actual := lp.DoCommand(th.App, th.Context, args, "") assert.Equal(t, "api.command_leave.fail.app_error", actual.Text) @@ -61,7 +61,7 @@ func TestLeaveProviderDoCommand(t *testing.T) { args := &model.CommandArgs{ UserId: th.BasicUser.Id, ChannelId: publicChannel.Id, - T: func(s string, args ...interface{}) string { return s }, + T: func(s string, args ...any) string { return s }, } actual := lp.DoCommand(th.App, th.Context, args, "") assert.Equal(t, "api.command_leave.fail.app_error", actual.Text) @@ -72,7 +72,7 @@ func TestLeaveProviderDoCommand(t *testing.T) { args := &model.CommandArgs{ UserId: th.BasicUser.Id, ChannelId: publicChannel.Id, - T: func(s string, args ...interface{}) string { return s }, + T: func(s string, args ...any) string { return s }, TeamId: th.BasicTeam.Id, SiteURL: "http://localhost:8065", } @@ -90,7 +90,7 @@ func TestLeaveProviderDoCommand(t *testing.T) { args := &model.CommandArgs{ UserId: th.BasicUser.Id, ChannelId: privateChannel.Id, - T: func(s string, args ...interface{}) string { return s }, + T: func(s string, args ...any) string { return s }, TeamId: th.BasicTeam.Id, SiteURL: "http://localhost:8065", } @@ -102,7 +102,7 @@ func TestLeaveProviderDoCommand(t *testing.T) { args := &model.CommandArgs{ UserId: th.BasicUser.Id, ChannelId: defaultChannel.Id, - T: func(s string, args ...interface{}) string { return s }, + T: func(s string, args ...any) string { return s }, TeamId: th.BasicTeam.Id, SiteURL: "http://localhost:8065", } @@ -114,7 +114,7 @@ func TestLeaveProviderDoCommand(t *testing.T) { args := &model.CommandArgs{ UserId: guest.Id, ChannelId: defaultChannel.Id, - T: func(s string, args ...interface{}) string { return s }, + T: func(s string, args ...any) string { return s }, TeamId: th.BasicTeam.Id, SiteURL: "http://localhost:8065", } @@ -132,7 +132,7 @@ func TestLeaveProviderDoCommand(t *testing.T) { args := &model.CommandArgs{ UserId: guest.Id, ChannelId: publicChannel.Id, - T: func(s string, args ...interface{}) string { return s }, + T: func(s string, args ...any) string { return s }, TeamId: th.BasicTeam.Id, SiteURL: "http://localhost:8065", } diff --git a/app/slashcommands/command_mute.go b/app/slashcommands/command_mute.go index 6b2c19e54c..ab24f8c919 100644 --- a/app/slashcommands/command_mute.go +++ b/app/slashcommands/command_mute.go @@ -58,13 +58,13 @@ func (*MuteProvider) DoCommand(a *app.App, c *request.Context, args *model.Comma channel, _ = a.Srv().Store.Channel().GetByName(channel.TeamId, channelName, true) if channel == nil { - return &model.CommandResponse{Text: args.T("api.command_mute.error", map[string]interface{}{"Channel": channelName}), ResponseType: model.CommandResponseTypeEphemeral} + return &model.CommandResponse{Text: args.T("api.command_mute.error", map[string]any{"Channel": channelName}), ResponseType: model.CommandResponseTypeEphemeral} } } channelMember, err := a.ToggleMuteChannel(channel.Id, args.UserId) if err != nil { - return &model.CommandResponse{Text: args.T("api.command_mute.not_member.error", map[string]interface{}{"Channel": channelName}), ResponseType: model.CommandResponseTypeEphemeral} + return &model.CommandResponse{Text: args.T("api.command_mute.not_member.error", map[string]any{"Channel": channelName}), ResponseType: model.CommandResponseTypeEphemeral} } // Direct and Group messages won't have a nice channel title, omit it @@ -76,7 +76,7 @@ func (*MuteProvider) DoCommand(a *app.App, c *request.Context, args *model.Comma } if channelMember.NotifyProps[model.MarkUnreadNotifyProp] == model.ChannelNotifyMention { - return &model.CommandResponse{Text: args.T("api.command_mute.success_mute", map[string]interface{}{"Channel": channel.DisplayName}), ResponseType: model.CommandResponseTypeEphemeral} + return &model.CommandResponse{Text: args.T("api.command_mute.success_mute", map[string]any{"Channel": channel.DisplayName}), ResponseType: model.CommandResponseTypeEphemeral} } - return &model.CommandResponse{Text: args.T("api.command_mute.success_unmute", map[string]interface{}{"Channel": channel.DisplayName}), ResponseType: model.CommandResponseTypeEphemeral} + return &model.CommandResponse{Text: args.T("api.command_mute.success_unmute", map[string]any{"Channel": channel.DisplayName}), ResponseType: model.CommandResponseTypeEphemeral} } diff --git a/app/slashcommands/command_remote.go b/app/slashcommands/command_remote.go index 90ce6d8e8c..a17737a8ae 100644 --- a/app/slashcommands/command_remote.go +++ b/app/slashcommands/command_remote.go @@ -36,7 +36,7 @@ func (rp *RemoteProvider) GetTrigger() string { func (rp *RemoteProvider) GetCommand(a *app.App, T i18n.TranslateFunc) *model.Command { - remote := model.NewAutocompleteData(rp.GetTrigger(), "[action]", T("api.command_remote.remote_add_remove.help", map[string]interface{}{"Actions": AvailableRemoteActions})) + remote := model.NewAutocompleteData(rp.GetTrigger(), "[action]", T("api.command_remote.remote_add_remove.help", map[string]any{"Actions": AvailableRemoteActions})) create := model.NewAutocompleteData("create", "", T("api.command_remote.invite.help")) create.AddNamedTextArgument("name", T("api.command_remote.name.help"), T("api.command_remote.name.hint"), "", true) @@ -71,13 +71,13 @@ func (rp *RemoteProvider) GetCommand(a *app.App, T i18n.TranslateFunc) *model.Co func (rp *RemoteProvider) DoCommand(a *app.App, c *request.Context, args *model.CommandArgs, message string) *model.CommandResponse { if !a.HasPermissionTo(args.UserId, model.PermissionManageSecureConnections) { - return responsef(args.T("api.command_remote.permission_required", map[string]interface{}{"Permission": "manage_secure_connections"})) + return responsef(args.T("api.command_remote.permission_required", map[string]any{"Permission": "manage_secure_connections"})) } margs := parseNamedArgs(args.Command) action, ok := margs[ActionKey] if !ok { - return responsef(args.T("api.command_remote.missing_command", map[string]interface{}{"Actions": AvailableRemoteActions})) + return responsef(args.T("api.command_remote.missing_command", map[string]any{"Actions": AvailableRemoteActions})) } switch action { @@ -91,7 +91,7 @@ func (rp *RemoteProvider) DoCommand(a *app.App, c *request.Context, args *model. return rp.doStatus(a, args, margs) } - return responsef(args.T("api.command_remote.unknown_action", map[string]interface{}{"Action": action})) + return responsef(args.T("api.command_remote.unknown_action", map[string]any{"Action": action})) } func (rp *RemoteProvider) GetAutoCompleteListItems(a *app.App, commandArgs *model.CommandArgs, arg *model.AutocompleteArg, parsed, toBeParsed string) ([]model.AutocompleteListItem, error) { @@ -110,12 +110,12 @@ func (rp *RemoteProvider) GetAutoCompleteListItems(a *app.App, commandArgs *mode func (rp *RemoteProvider) doCreate(a *app.App, args *model.CommandArgs, margs map[string]string) *model.CommandResponse { password := margs["password"] if password == "" { - return responsef(args.T("api.command_remote.missing_empty", map[string]interface{}{"Arg": "password"})) + return responsef(args.T("api.command_remote.missing_empty", map[string]any{"Arg": "password"})) } name := margs["name"] if name == "" { - return responsef(args.T("api.command_remote.missing_empty", map[string]interface{}{"Arg": "name"})) + return responsef(args.T("api.command_remote.missing_empty", map[string]any{"Arg": "name"})) } displayname := margs["displayname"] @@ -137,7 +137,7 @@ func (rp *RemoteProvider) doCreate(a *app.App, args *model.CommandArgs, margs ma rcSaved, appErr := a.AddRemoteCluster(rc) if appErr != nil { - return responsef(args.T("api.command_remote.add_remote.error", map[string]interface{}{"Error": appErr.Error()})) + return responsef(args.T("api.command_remote.add_remote.error", map[string]any{"Error": appErr.Error()})) } // Display the encrypted invitation @@ -149,24 +149,24 @@ func (rp *RemoteProvider) doCreate(a *app.App, args *model.CommandArgs, margs ma } encrypted, err := invite.Encrypt(password) if err != nil { - return responsef(args.T("api.command_remote.encrypt_invitation.error", map[string]interface{}{"Error": err.Error()})) + return responsef(args.T("api.command_remote.encrypt_invitation.error", map[string]any{"Error": err.Error()})) } encoded := base64.URLEncoding.EncodeToString(encrypted) return responsef("##### " + args.T("api.command_remote.invitation_created") + "\n" + - args.T("api.command_remote.invite_summary", map[string]interface{}{"Command": "/secure-connection accept", "Invitation": encoded, "SiteURL": invite.SiteURL})) + args.T("api.command_remote.invite_summary", map[string]any{"Command": "/secure-connection accept", "Invitation": encoded, "SiteURL": invite.SiteURL})) } // doAccept accepts an invitation generated by a remote site. func (rp *RemoteProvider) doAccept(a *app.App, args *model.CommandArgs, margs map[string]string) *model.CommandResponse { password := margs["password"] if password == "" { - return responsef(args.T("api.command_remote.missing_empty", map[string]interface{}{"Arg": "password"})) + return responsef(args.T("api.command_remote.missing_empty", map[string]any{"Arg": "password"})) } name := margs["name"] if name == "" { - return responsef(args.T("api.command_remote.missing_empty", map[string]interface{}{"Arg": "name"})) + return responsef(args.T("api.command_remote.missing_empty", map[string]any{"Arg": "name"})) } displayname := margs["displayname"] @@ -176,18 +176,18 @@ func (rp *RemoteProvider) doAccept(a *app.App, args *model.CommandArgs, margs ma blob := margs["invite"] if blob == "" { - return responsef(args.T("api.command_remote.missing_empty", map[string]interface{}{"Arg": "invite"})) + return responsef(args.T("api.command_remote.missing_empty", map[string]any{"Arg": "invite"})) } // invite is encoded as base64 and encrypted decoded, err := base64.URLEncoding.DecodeString(blob) if err != nil { - return responsef(args.T("api.command_remote.decode_invitation.error", map[string]interface{}{"Error": err.Error()})) + return responsef(args.T("api.command_remote.decode_invitation.error", map[string]any{"Error": err.Error()})) } invite := &model.RemoteClusterInvite{} err = invite.Decrypt(decoded, password) if err != nil { - return responsef(args.T("api.command_remote.incorrect_password.error", map[string]interface{}{"Error": err.Error()})) + return responsef(args.T("api.command_remote.incorrect_password.error", map[string]any{"Error": err.Error()})) } rcs, _ := a.GetRemoteClusterService() @@ -202,36 +202,36 @@ func (rp *RemoteProvider) doAccept(a *app.App, args *model.CommandArgs, margs ma rc, err := rcs.AcceptInvitation(invite, name, displayname, args.UserId, args.TeamId, url) if err != nil { - return responsef(args.T("api.command_remote.accept_invitation.error", map[string]interface{}{"Error": err.Error()})) + return responsef(args.T("api.command_remote.accept_invitation.error", map[string]any{"Error": err.Error()})) } - return responsef("##### " + args.T("api.command_remote.accept_invitation", map[string]interface{}{"SiteURL": rc.SiteURL})) + return responsef("##### " + args.T("api.command_remote.accept_invitation", map[string]any{"SiteURL": rc.SiteURL})) } // doRemove removes a remote cluster from the database, effectively revoking the trust relationship. func (rp *RemoteProvider) doRemove(a *app.App, args *model.CommandArgs, margs map[string]string) *model.CommandResponse { id, ok := margs["connectionID"] if !ok { - return responsef(args.T("api.command_remote.missing_empty", map[string]interface{}{"Arg": "remoteId"})) + return responsef(args.T("api.command_remote.missing_empty", map[string]any{"Arg": "remoteId"})) } deleted, err := a.DeleteRemoteCluster(id) if err != nil { - responsef(args.T("api.command_remote.remove_remote.error", map[string]interface{}{"Error": err.Error()})) + responsef(args.T("api.command_remote.remove_remote.error", map[string]any{"Error": err.Error()})) } result := "removed" if !deleted { result = "**NOT FOUND**" } - return responsef("##### " + args.T("api.command_remote.cluster_removed", map[string]interface{}{"RemoteId": id, "Result": result})) + return responsef("##### " + args.T("api.command_remote.cluster_removed", map[string]any{"RemoteId": id, "Result": result})) } // doStatus displays connection status for all remote clusters. func (rp *RemoteProvider) doStatus(a *app.App, args *model.CommandArgs, _ map[string]string) *model.CommandResponse { list, err := a.GetAllRemoteClusters(model.RemoteClusterQueryFilter{}) if err != nil { - responsef(args.T("api.command_remote.fetch_status.error", map[string]interface{}{"Error": err.Error()})) + responsef(args.T("api.command_remote.fetch_status.error", map[string]any{"Error": err.Error()})) } if len(list) == 0 { diff --git a/app/slashcommands/command_remove.go b/app/slashcommands/command_remove.go index e98a6c64bf..daa42edca3 100644 --- a/app/slashcommands/command_remove.go +++ b/app/slashcommands/command_remove.go @@ -128,7 +128,7 @@ func doCommand(a *app.App, c *request.Context, args *model.CommandArgs, message if err != nil { nameFormat := *a.Config().TeamSettings.TeammateNameDisplay return &model.CommandResponse{ - Text: args.T("api.command_remove.user_not_in_channel", map[string]interface{}{ + Text: args.T("api.command_remove.user_not_in_channel", map[string]any{ "Username": userProfile.GetDisplayName(nameFormat), }), ResponseType: model.CommandResponseTypeEphemeral, @@ -140,7 +140,7 @@ func doCommand(a *app.App, c *request.Context, args *model.CommandArgs, message if err.Id == "api.channel.remove_members.denied" { text = args.T("api.command_remove.group_constrained_user_denied") } else { - text = args.T(err.Id, map[string]interface{}{ + text = args.T(err.Id, map[string]any{ "Channel": model.DefaultChannelName, }) } diff --git a/app/slashcommands/command_remove_test.go b/app/slashcommands/command_remove_test.go index 9e775ee784..617a387bb0 100644 --- a/app/slashcommands/command_remove_test.go +++ b/app/slashcommands/command_remove_test.go @@ -40,7 +40,7 @@ func TestRemoveProviderDoCommand(t *testing.T) { // Try a public channel *without* permission. args := &model.CommandArgs{ - T: func(s string, args ...interface{}) string { return s }, + T: func(s string, args ...any) string { return s }, ChannelId: publicChannel.Id, UserId: th.BasicUser.Id, } @@ -51,7 +51,7 @@ func TestRemoveProviderDoCommand(t *testing.T) { // Try a public channel *with* permission. th.App.AddUserToChannel(th.BasicUser, publicChannel, false) args = &model.CommandArgs{ - T: func(s string, args ...interface{}) string { return s }, + T: func(s string, args ...any) string { return s }, ChannelId: publicChannel.Id, UserId: th.BasicUser.Id, } @@ -61,7 +61,7 @@ func TestRemoveProviderDoCommand(t *testing.T) { // Try a private channel *without* permission. args = &model.CommandArgs{ - T: func(s string, args ...interface{}) string { return s }, + T: func(s string, args ...any) string { return s }, ChannelId: privateChannel.Id, UserId: th.BasicUser.Id, } @@ -72,7 +72,7 @@ func TestRemoveProviderDoCommand(t *testing.T) { // Try a private channel *with* permission. th.App.AddUserToChannel(th.BasicUser, privateChannel, false) args = &model.CommandArgs{ - T: func(s string, args ...interface{}) string { return s }, + T: func(s string, args ...any) string { return s }, ChannelId: privateChannel.Id, UserId: th.BasicUser.Id, } @@ -87,7 +87,7 @@ func TestRemoveProviderDoCommand(t *testing.T) { groupChannel := th.createGroupChannel(user1, user2) args = &model.CommandArgs{ - T: func(s string, args ...interface{}) string { return s }, + T: func(s string, args ...any) string { return s }, ChannelId: groupChannel.Id, UserId: th.BasicUser.Id, } @@ -99,7 +99,7 @@ func TestRemoveProviderDoCommand(t *testing.T) { directChannel := th.createDmChannel(user1) args = &model.CommandArgs{ - T: func(s string, args ...interface{}) string { return s }, + T: func(s string, args ...any) string { return s }, ChannelId: directChannel.Id, UserId: th.BasicUser.Id, } @@ -114,7 +114,7 @@ func TestRemoveProviderDoCommand(t *testing.T) { th.App.UpdateActive(th.Context, deactivatedUser, false) args = &model.CommandArgs{ - T: func(s string, args ...interface{}) string { return s }, + T: func(s string, args ...any) string { return s }, ChannelId: publicChannel.Id, UserId: th.BasicUser.Id, } diff --git a/app/slashcommands/command_share.go b/app/slashcommands/command_share.go index 30fa0d40d8..2411c0b1af 100644 --- a/app/slashcommands/command_share.go +++ b/app/slashcommands/command_share.go @@ -31,7 +31,7 @@ func (sp *ShareProvider) GetTrigger() string { } func (sp *ShareProvider) GetCommand(a *app.App, T i18n.TranslateFunc) *model.Command { - share := model.NewAutocompleteData(CommandTriggerShare, "[action]", T("api.command_share.available_actions", map[string]interface{}{"Actions": AvailableShareActions})) + share := model.NewAutocompleteData(CommandTriggerShare, "[action]", T("api.command_share.available_actions", map[string]any{"Actions": AvailableShareActions})) inviteRemote := model.NewAutocompleteData("invite", "", T("api.command_share.invite_remote.help")) inviteRemote.AddNamedDynamicListArgument("connectionID", T("api.command_share.remote_id.help"), "builtin:"+CommandTriggerShare, true) @@ -122,7 +122,7 @@ func (sp *ShareProvider) getAutoCompleteUnInviteRemote(a *app.App, _ *model.Comm func (sp *ShareProvider) DoCommand(a *app.App, c *request.Context, args *model.CommandArgs, message string) *model.CommandResponse { if !a.HasPermissionTo(args.UserId, model.PermissionManageSharedChannels) { - return responsef(args.T("api.command_share.permission_required", map[string]interface{}{"Permission": "manage_shared_channels"})) + return responsef(args.T("api.command_share.permission_required", map[string]any{"Permission": "manage_shared_channels"})) } if a.Srv().GetSharedChannelSyncService() == nil { @@ -136,7 +136,7 @@ func (sp *ShareProvider) DoCommand(a *app.App, c *request.Context, args *model.C margs := parseNamedArgs(args.Command) action, ok := margs[ActionKey] if !ok { - return responsef(args.T("api.command_share.missing_action", map[string]interface{}{"Actions": AvailableShareActions})) + return responsef(args.T("api.command_share.missing_action", map[string]any{"Actions": AvailableShareActions})) } switch action { @@ -151,14 +151,14 @@ func (sp *ShareProvider) DoCommand(a *app.App, c *request.Context, args *model.C case "status": return sp.doStatus(a, args, margs) } - return responsef(args.T("api.command_share.unknown_action", map[string]interface{}{"Action": action, "Actions": AvailableShareActions})) + return responsef(args.T("api.command_share.unknown_action", map[string]any{"Action": action, "Actions": AvailableShareActions})) } func (sp *ShareProvider) doShareChannel(a *app.App, args *model.CommandArgs, margs map[string]string) *model.CommandResponse { // check that channel exists. channel, errApp := a.GetChannel(args.ChannelId) if errApp != nil { - return responsef(args.T("api.command_share.share_channel.error", map[string]interface{}{"Error": errApp.Error()})) + return responsef(args.T("api.command_share.share_channel.error", map[string]any{"Error": errApp.Error()})) } if name := margs["name"]; name == "" { @@ -179,7 +179,7 @@ func (sp *ShareProvider) doShareChannel(a *app.App, args *model.CommandArgs, mar readonly, err := parseBool(margs["readonly"]) if err != nil { - return responsef(args.T("api.command_share.invalid_value.error", map[string]interface{}{"Arg": "readonly", "Error": err.Error()})) + return responsef(args.T("api.command_share.invalid_value.error", map[string]any{"Arg": "readonly", "Error": err.Error()})) } sc := &model.SharedChannel{ @@ -195,7 +195,7 @@ func (sp *ShareProvider) doShareChannel(a *app.App, args *model.CommandArgs, mar } if _, err := a.SaveSharedChannel(sc); err != nil { - return responsef(args.T("api.command_share.share_channel.error", map[string]interface{}{"Error": err.Error()})) + return responsef(args.T("api.command_share.share_channel.error", map[string]any{"Error": err.Error()})) } notifyClientsForChannelUpdate(a, sc) @@ -206,12 +206,12 @@ func (sp *ShareProvider) doShareChannel(a *app.App, args *model.CommandArgs, mar func (sp *ShareProvider) doUnshareChannel(a *app.App, args *model.CommandArgs, margs map[string]string) *model.CommandResponse { sc, appErr := a.GetSharedChannel(args.ChannelId) if appErr != nil { - return responsef(args.T("api.command_share.shared_channel_unshare.error", map[string]interface{}{"Error": appErr.Error()})) + return responsef(args.T("api.command_share.shared_channel_unshare.error", map[string]any{"Error": appErr.Error()})) } deleted, err := a.DeleteSharedChannel(args.ChannelId) if err != nil { - return responsef(args.T("api.command_share.shared_channel_unshare.error", map[string]interface{}{"Error": err.Error()})) + return responsef(args.T("api.command_share.shared_channel_unshare.error", map[string]any{"Error": err.Error()})) } if !deleted { return responsef(args.T("api.command_share.not_shared_channel_unshare")) @@ -230,7 +230,7 @@ func (sp *ShareProvider) doInviteRemote(a *app.App, args *model.CommandArgs, mar hasRemote, err := a.HasRemote(args.ChannelId, remoteId) if err != nil { - return responsef(args.T("api.command_share.fetch_remote.error", map[string]interface{}{"Error": err.Error()})) + return responsef(args.T("api.command_share.fetch_remote.error", map[string]any{"Error": err.Error()})) } if hasRemote { return responsef(args.T("api.command_share.remote_already_invited")) @@ -239,7 +239,7 @@ func (sp *ShareProvider) doInviteRemote(a *app.App, args *model.CommandArgs, mar // Check if channel is shared or not. hasChan, err := a.HasSharedChannel(args.ChannelId) if err != nil { - return responsef(args.T("api.command_share.check_channel_exist.error", map[string]interface{}{"Error": err.Error()})) + return responsef(args.T("api.command_share.check_channel_exist.error", map[string]any{"Error": err.Error()})) } if !hasChan { // If it doesn't exist, then create it. @@ -259,19 +259,19 @@ func (sp *ShareProvider) doInviteRemote(a *app.App, args *model.CommandArgs, mar rc, appErr := a.GetRemoteCluster(remoteId) if appErr != nil { - return responsef(args.T("api.command_share.remote_id_invalid.error", map[string]interface{}{"Error": appErr.Error()})) + return responsef(args.T("api.command_share.remote_id_invalid.error", map[string]any{"Error": appErr.Error()})) } channel, errApp := a.GetChannel(args.ChannelId) if errApp != nil { - return responsef(args.T("api.command_share.channel_invite.error", map[string]interface{}{"Name": rc.DisplayName, "Error": errApp.Error()})) + return responsef(args.T("api.command_share.channel_invite.error", map[string]any{"Name": rc.DisplayName, "Error": errApp.Error()})) } // send channel invite to remote cluster if err := a.Srv().GetSharedChannelSyncService().SendChannelInvite(channel, args.UserId, rc); err != nil { - return responsef(args.T("api.command_share.channel_invite.error", map[string]interface{}{"Name": rc.DisplayName, "Error": err.Error()})) + return responsef(args.T("api.command_share.channel_invite.error", map[string]any{"Name": rc.DisplayName, "Error": err.Error()})) } - return responsef("##### " + args.T("api.command_share.invitation_sent", map[string]interface{}{"Name": rc.DisplayName, "SiteURL": rc.SiteURL})) + return responsef("##### " + args.T("api.command_share.invitation_sent", map[string]any{"Name": rc.DisplayName, "SiteURL": rc.SiteURL})) } func (sp *ShareProvider) doUninviteRemote(a *app.App, args *model.CommandArgs, margs map[string]string) *model.CommandResponse { @@ -282,20 +282,20 @@ func (sp *ShareProvider) doUninviteRemote(a *app.App, args *model.CommandArgs, m scr, err := a.GetSharedChannelRemoteByIds(args.ChannelId, remoteId) if err != nil || scr.ChannelId != args.ChannelId { - return responsef(args.T("api.command_share.channel_remote_id_not_exists", map[string]interface{}{"RemoteId": remoteId})) + return responsef(args.T("api.command_share.channel_remote_id_not_exists", map[string]any{"RemoteId": remoteId})) } deleted, err := a.DeleteSharedChannelRemote(scr.Id) if err != nil || !deleted { - return responsef(args.T("api.command_share.could_not_uninvite.error", map[string]interface{}{"RemoteId": remoteId, "Error": err.Error()})) + return responsef(args.T("api.command_share.could_not_uninvite.error", map[string]any{"RemoteId": remoteId, "Error": err.Error()})) } - return responsef("##### " + args.T("api.command_share.remote_uninvited", map[string]interface{}{"RemoteId": remoteId})) + return responsef("##### " + args.T("api.command_share.remote_uninvited", map[string]any{"RemoteId": remoteId})) } func (sp *ShareProvider) doStatus(a *app.App, args *model.CommandArgs, _ map[string]string) *model.CommandResponse { statuses, err := a.GetSharedChannelRemotesStatus(args.ChannelId) if err != nil { - return responsef(args.T("api.command_share.fetch_remote_status.error", map[string]interface{}{"Error": err.Error()})) + return responsef(args.T("api.command_share.fetch_remote_status.error", map[string]any{"Error": err.Error()})) } if len(statuses) == 0 { return responsef(args.T("api.command_share.no_remote_invited")) @@ -303,7 +303,7 @@ func (sp *ShareProvider) doStatus(a *app.App, args *model.CommandArgs, _ map[str var sb strings.Builder - fmt.Fprintf(&sb, args.T("api.command_share.channel_status_id", map[string]interface{}{"ChannelId": statuses[0].ChannelId})+"\n\n") + fmt.Fprintf(&sb, args.T("api.command_share.channel_status_id", map[string]any{"ChannelId": statuses[0].ChannelId})+"\n\n") fmt.Fprintf(&sb, args.T("api.command_share.remote_table_header")+" \n") // "| Secure Connection | SiteURL | ReadOnly | InviteAccepted | Online | Last Sync |" diff --git a/app/slashcommands/command_share_test.go b/app/slashcommands/command_share_test.go index 36b7ce3423..8a58e44df0 100644 --- a/app/slashcommands/command_share_test.go +++ b/app/slashcommands/command_share_test.go @@ -39,7 +39,7 @@ func TestShareProviderDoCommand(t *testing.T) { channel := th.CreateChannel(th.BasicTeam, WithShared(false)) args := &model.CommandArgs{ - T: func(s string, args ...interface{}) string { return s }, + T: func(s string, args ...any) string { return s }, ChannelId: channel.Id, UserId: th.BasicUser.Id, TeamId: th.BasicTeam.Id, @@ -74,7 +74,7 @@ func TestShareProviderDoCommand(t *testing.T) { commandProvider := ShareProvider{} channel := th.CreateChannel(th.BasicTeam, WithShared(true)) args := &model.CommandArgs{ - T: func(s string, args ...interface{}) string { return s }, + T: func(s string, args ...any) string { return s }, ChannelId: channel.Id, UserId: th.BasicUser.Id, TeamId: th.BasicTeam.Id, diff --git a/app/slashcommands/command_test.go b/app/slashcommands/command_test.go index 33593c290e..a227b6e9e3 100644 --- a/app/slashcommands/command_test.go +++ b/app/slashcommands/command_test.go @@ -106,7 +106,7 @@ func TestExecuteCommand(t *testing.T) { TeamId: th.BasicTeam.Id, ChannelId: th.BasicChannel.Id, UserId: th.BasicUser.Id, - T: func(s string, args ...interface{}) string { return s }, + T: func(s string, args ...any) string { return s }, } resp, err := th.App.ExecuteCommand(th.Context, args) require.Nil(t, err) @@ -119,7 +119,7 @@ func TestExecuteCommand(t *testing.T) { t.Run("missing slash character", func(t *testing.T) { argsMissingSlashCharacter := &model.CommandArgs{ Command: "missing leading slash character", - T: func(s string, args ...interface{}) string { return s }, + T: func(s string, args ...any) string { return s }, } _, err := th.App.ExecuteCommand(th.Context, argsMissingSlashCharacter) require.Equal(t, "api.command.execute_command.format.app_error", err.Id) @@ -128,7 +128,7 @@ func TestExecuteCommand(t *testing.T) { t.Run("empty", func(t *testing.T) { argsMissingSlashCharacter := &model.CommandArgs{ Command: "", - T: func(s string, args ...interface{}) string { return s }, + T: func(s string, args ...any) string { return s }, } _, err := th.App.ExecuteCommand(th.Context, argsMissingSlashCharacter) require.Equal(t, "api.command.execute_command.format.app_error", err.Id) diff --git a/app/slashcommands/util.go b/app/slashcommands/util.go index dc59fb7278..521fef7f51 100644 --- a/app/slashcommands/util.go +++ b/app/slashcommands/util.go @@ -17,7 +17,7 @@ const ( ) // responsef creates an ephemeral command response using printf syntax. -func responsef(format string, args ...interface{}) *model.CommandResponse { +func responsef(format string, args ...any) *model.CommandResponse { return &model.CommandResponse{ ResponseType: model.CommandResponseTypeEphemeral, Text: fmt.Sprintf(format, args...), diff --git a/app/status.go b/app/status.go index c3d34d8048..7ec9c304f5 100644 --- a/app/status.go +++ b/app/status.go @@ -51,12 +51,12 @@ func (a *App) GetAllStatuses() map[string]*model.Status { return statusMap } -func (a *App) GetStatusesByIds(userIDs []string) (map[string]interface{}, *model.AppError) { +func (a *App) GetStatusesByIds(userIDs []string) (map[string]any, *model.AppError) { if !*a.Config().ServiceSettings.EnableUserStatuses { - return map[string]interface{}{}, nil + return map[string]any{}, nil } - statusMap := map[string]interface{}{} + statusMap := map[string]any{} metrics := a.Metrics() missingUserIds := []string{} diff --git a/app/syncables.go b/app/syncables.go index 731aceb982..123bc756b6 100644 --- a/app/syncables.go +++ b/app/syncables.go @@ -227,7 +227,7 @@ func (a *App) SyncSyncableRoles(syncableID string, syncableType model.GroupSynca } return nil default: - return model.NewAppError("App.SyncSyncableRoles", "groups.unsupported_syncable_type", map[string]interface{}{"Value": syncableType}, "", http.StatusInternalServerError) + return model.NewAppError("App.SyncSyncableRoles", "groups.unsupported_syncable_type", map[string]any{"Value": syncableType}, "", http.StatusInternalServerError) } } diff --git a/app/team.go b/app/team.go index 5b2d5279f9..f15cd64f58 100644 --- a/app/team.go +++ b/app/team.go @@ -220,7 +220,7 @@ func (a *App) UpdateTeam(team *model.Team) (*model.Team, *model.AppError) { case errors.As(err, &appErr): return nil, appErr case errors.As(err, &domErr): - return nil, model.NewAppError("UpdateTeam", "api.team.update_restricted_domains.mismatch.app_error", map[string]interface{}{"Domain": domErr.Domain}, "", http.StatusBadRequest) + return nil, model.NewAppError("UpdateTeam", "api.team.update_restricted_domains.mismatch.app_error", map[string]any{"Domain": domErr.Domain}, "", http.StatusBadRequest) default: return nil, model.NewAppError("UpdateTeam", "app.team.update.updating.app_error", nil, err.Error(), http.StatusInternalServerError) } @@ -265,7 +265,7 @@ func (a *App) RenameTeam(team *model.Team, newTeamName string, newDisplayName st case errors.As(err, &appErr): return nil, appErr case errors.As(err, &domErr): - return nil, model.NewAppError("RenameTeam", "api.team.update_restricted_domains.mismatch.app_error", map[string]interface{}{"Domain": domErr.Domain}, "", http.StatusBadRequest) + return nil, model.NewAppError("RenameTeam", "api.team.update_restricted_domains.mismatch.app_error", map[string]any{"Domain": domErr.Domain}, "", http.StatusBadRequest) default: return nil, model.NewAppError("RenameTeam", "app.team.update.updating.app_error", nil, err.Error(), http.StatusInternalServerError) } @@ -351,7 +351,7 @@ func (a *App) PatchTeam(teamID string, patch *model.TeamPatch) (*model.Team, *mo case errors.As(err, &appErr): return nil, appErr case errors.As(err, &domErr): - return nil, model.NewAppError("PatchTeam", "api.team.update_restricted_domains.mismatch.app_error", map[string]interface{}{"Domain": domErr.Domain}, "", http.StatusBadRequest) + return nil, model.NewAppError("PatchTeam", "api.team.update_restricted_domains.mismatch.app_error", map[string]any{"Domain": domErr.Domain}, "", http.StatusBadRequest) default: return nil, model.NewAppError("PatchTeam", "app.team.update.updating.app_error", nil, err.Error(), http.StatusInternalServerError) } @@ -1419,7 +1419,7 @@ func (a *App) InviteNewUsersToTeamGracefully(memberInvite *model.MemberInvite, t Error: nil, } if !teams.IsEmailAddressAllowed(email, allowedDomains) { - invite.Error = model.NewAppError("InviteNewUsersToTeam", "api.team.invite_members.invalid_email.app_error", map[string]interface{}{"Addresses": email}, "", http.StatusBadRequest) + invite.Error = model.NewAppError("InviteNewUsersToTeam", "api.team.invite_members.invalid_email.app_error", map[string]any{"Addresses": email}, "", http.StatusBadRequest) } else { goodEmails = append(goodEmails, email) } @@ -1550,7 +1550,7 @@ func (a *App) InviteGuestsToChannelsGracefully(teamID string, guestsInvite *mode Error: nil, } if !users.CheckEmailDomain(email, *a.Config().GuestAccountsSettings.RestrictCreationToDomains) { - invite.Error = model.NewAppError("InviteGuestsToChannelsGracefully", "api.team.invite_members.invalid_email.app_error", map[string]interface{}{"Addresses": email}, "", http.StatusBadRequest) + invite.Error = model.NewAppError("InviteGuestsToChannelsGracefully", "api.team.invite_members.invalid_email.app_error", map[string]any{"Addresses": email}, "", http.StatusBadRequest) } else { goodEmails = append(goodEmails, email) } @@ -1616,7 +1616,7 @@ func (a *App) InviteNewUsersToTeam(emailList []string, teamID, senderId string) if len(invalidEmailList) > 0 { s := strings.Join(invalidEmailList, ", ") - return model.NewAppError("InviteNewUsersToTeam", "api.team.invite_members.invalid_email.app_error", map[string]interface{}{"Addresses": s}, "", http.StatusBadRequest) + return model.NewAppError("InviteNewUsersToTeam", "api.team.invite_members.invalid_email.app_error", map[string]any{"Addresses": s}, "", http.StatusBadRequest) } nameFormat := *a.Config().TeamSettings.TeammateNameDisplay @@ -1654,7 +1654,7 @@ func (a *App) InviteGuestsToChannels(teamID string, guestsInvite *model.GuestsIn if len(invalidEmailList) > 0 { s := strings.Join(invalidEmailList, ", ") - return model.NewAppError("InviteGuestsToChannels", "api.team.invite_members.invalid_email.app_error", map[string]interface{}{"Addresses": s}, "", http.StatusBadRequest) + return model.NewAppError("InviteGuestsToChannels", "api.team.invite_members.invalid_email.app_error", map[string]any{"Addresses": s}, "", http.StatusBadRequest) } nameFormat := *a.Config().TeamSettings.TeammateNameDisplay diff --git a/app/upload.go b/app/upload.go index 06ac8965b1..93ff614619 100644 --- a/app/upload.go +++ b/app/upload.go @@ -47,7 +47,7 @@ func (a *App) runPluginsHook(c *request.Context, info *model.FileInfo, file io.R newInfo, rejStr := hooks.FileWillBeUploaded(pluginContext, info, file, w) if rejStr != "" { rejErr = model.NewAppError("runPluginsHook", "app.upload.run_plugins_hook.rejected", - map[string]interface{}{"Filename": info.Name, "Reason": rejStr}, "", http.StatusBadRequest) + map[string]any{"Filename": info.Name, "Reason": rejStr}, "", http.StatusBadRequest) return false } if newInfo != nil { @@ -102,7 +102,7 @@ func (a *App) runPluginsHook(c *request.Context, info *model.FileInfo, file io.R func (a *App) CreateUploadSession(us *model.UploadSession) (*model.UploadSession, *model.AppError) { if us.FileSize > *a.Config().FileSettings.MaxFileSize { return nil, model.NewAppError("CreateUploadSession", "app.upload.create.upload_too_large.app_error", - map[string]interface{}{"channelId": us.ChannelId}, "", http.StatusRequestEntityTooLarge) + map[string]any{"channelId": us.ChannelId}, "", http.StatusRequestEntityTooLarge) } us.FileOffset = 0 @@ -121,11 +121,11 @@ func (a *App) CreateUploadSession(us *model.UploadSession) (*model.UploadSession channel, err := a.GetChannel(us.ChannelId) if err != nil { return nil, model.NewAppError("CreateUploadSession", "app.upload.create.incorrect_channel_id.app_error", - map[string]interface{}{"channelId": us.ChannelId}, "", http.StatusBadRequest) + map[string]any{"channelId": us.ChannelId}, "", http.StatusBadRequest) } if channel.DeleteAt != 0 { return nil, model.NewAppError("CreateUploadSession", "app.upload.create.cannot_upload_to_deleted_channel.app_error", - map[string]interface{}{"channelId": us.ChannelId}, "", http.StatusBadRequest) + map[string]any{"channelId": us.ChannelId}, "", http.StatusBadRequest) } } @@ -217,7 +217,7 @@ func (a *App) UploadData(c *request.Context, us *model.UploadSession, rd io.Read errStr = err.Error() } return nil, model.NewAppError("UploadData", "app.upload.upload_data.first_part_too_small.app_error", - map[string]interface{}{"Size": minFirstPartSize}, errStr, http.StatusBadRequest) + map[string]any{"Size": minFirstPartSize}, errStr, http.StatusBadRequest) } } else if us.FileOffset < us.FileSize { // resume upload @@ -266,7 +266,7 @@ func (a *App) UploadData(c *request.Context, us *model.UploadSession, rd io.Read if info.IsImage() && !info.IsSvg() { if limitErr := checkImageResolutionLimit(info.Width, info.Height, *a.Config().FileSettings.MaxImageResolution); limitErr != nil { return nil, model.NewAppError("uploadData", "app.upload.upload_data.large_image.app_error", - map[string]interface{}{"Filename": us.Filename, "Width": info.Width, "Height": info.Height}, "", http.StatusBadRequest) + map[string]any{"Filename": us.Filename, "Width": info.Width, "Height": info.Height}, "", http.StatusBadRequest) } nameWithoutExtension := info.Name[:strings.LastIndex(info.Name, ".")] diff --git a/app/user.go b/app/user.go index ffdc112ba8..75aeb4ad3b 100644 --- a/app/user.go +++ b/app/user.go @@ -137,7 +137,7 @@ func (a *App) CreateUserWithInviteId(c *request.Context, user *model.User, invit } if !users.CheckUserDomain(user, team.AllowedDomains) { - return nil, model.NewAppError("CreateUserWithInviteId", "api.team.invite_members.invalid_email.app_error", map[string]interface{}{"Addresses": team.AllowedDomains}, "", http.StatusForbidden) + return nil, model.NewAppError("CreateUserWithInviteId", "api.team.invite_members.invalid_email.app_error", map[string]any{"Addresses": team.AllowedDomains}, "", http.StatusForbidden) } user.EmailVerified = false @@ -319,7 +319,7 @@ func (a *App) CreateOAuthUser(c *request.Context, service string, userData io.Re } user, err1 := provider.GetUserFromJSON(userData, tokenUser) if err1 != nil { - return nil, model.NewAppError("CreateOAuthUser", "api.user.create_oauth_user.create.app_error", map[string]interface{}{"Service": service}, err1.Error(), http.StatusInternalServerError) + return nil, model.NewAppError("CreateOAuthUser", "api.user.create_oauth_user.create.app_error", map[string]any{"Service": service}, err1.Error(), http.StatusInternalServerError) } if user.AuthService == "" { user.AuthService = service @@ -342,7 +342,7 @@ func (a *App) CreateOAuthUser(c *request.Context, service string, userData io.Re userByEmail, _ := a.ch.srv.userService.GetUserByEmail(user.Email) if userByEmail != nil { if userByEmail.AuthService == "" { - return nil, model.NewAppError("CreateOAuthUser", "api.user.create_oauth_user.already_attached.app_error", map[string]interface{}{"Service": service, "Auth": model.UserAuthServiceEmail}, "email="+user.Email, http.StatusBadRequest) + return nil, model.NewAppError("CreateOAuthUser", "api.user.create_oauth_user.already_attached.app_error", map[string]any{"Service": service, "Auth": model.UserAuthServiceEmail}, "email="+user.Email, http.StatusBadRequest) } if provider.IsSameUser(userByEmail, user) { if _, err := a.Srv().Store.User().UpdateAuthData(userByEmail.Id, user.AuthService, user.AuthData, "", false); err != nil { @@ -351,7 +351,7 @@ func (a *App) CreateOAuthUser(c *request.Context, service string, userData io.Re } return userByEmail, nil } - return nil, model.NewAppError("CreateOAuthUser", "api.user.create_oauth_user.already_attached.app_error", map[string]interface{}{"Service": service, "Auth": userByEmail.AuthService}, "email="+user.Email+" authData="+*user.AuthData, http.StatusBadRequest) + return nil, model.NewAppError("CreateOAuthUser", "api.user.create_oauth_user.already_attached.app_error", map[string]any{"Service": service, "Auth": userByEmail.AuthService}, "email="+user.Email+" authData="+*user.AuthData, http.StatusBadRequest) } user.EmailVerified = true @@ -1592,7 +1592,7 @@ func (a *App) PermanentDeleteUser(c *request.Context, user *model.User) *model.A var invErr *store.ErrInvalidInput switch { case errors.As(err, &invErr): - return model.NewAppError("PermanentDeleteUser", "app.bot.permenent_delete.bad_id", map[string]interface{}{"user_id": invErr.Value}, invErr.Error(), http.StatusBadRequest) + return model.NewAppError("PermanentDeleteUser", "app.bot.permenent_delete.bad_id", map[string]any{"user_id": invErr.Value}, invErr.Error(), http.StatusBadRequest) default: // last fallback in case it doesn't map to an existing app error. return model.NewAppError("PermanentDeleteUser", "app.bot.permanent_delete.internal_error", nil, err.Error(), http.StatusInternalServerError) } @@ -1952,7 +1952,7 @@ func (a *App) AutocompleteUsersInTeam(teamID string, term string, options *model func (a *App) UpdateOAuthUserAttrs(userData io.Reader, user *model.User, provider einterfaces.OAuthProvider, service string, tokenUser *model.User) *model.AppError { oauthUser, err1 := provider.GetUserFromJSON(userData, tokenUser) if err1 != nil { - return model.NewAppError("UpdateOAuthUserAttrs", "api.user.update_oauth_user_attrs.get_user.app_error", map[string]interface{}{"Service": service}, err1.Error(), http.StatusBadRequest) + return model.NewAppError("UpdateOAuthUserAttrs", "api.user.update_oauth_user_attrs.get_user.app_error", map[string]any{"Service": service}, err1.Error(), http.StatusBadRequest) } userAttrsChanged := false diff --git a/app/users/helper_test.go b/app/users/helper_test.go index 94375778f0..aee08a17a3 100644 --- a/app/users/helper_test.go +++ b/app/users/helper_test.go @@ -91,7 +91,7 @@ func setupTestHelper(s store.Store, includeCacheLayer bool, tb testing.TB) *Test sessionCache: cache, config: configStore.Get, sessionPool: sync.Pool{ - New: func() interface{} { + New: func() any { return &model.Session{} }, }, diff --git a/app/users/service.go b/app/users/service.go index 8a61e31fe8..98a65958a2 100644 --- a/app/users/service.go +++ b/app/users/service.go @@ -69,7 +69,7 @@ func New(c ServiceConfig) (*UserService, error) { cluster: c.Cluster, sessionCache: sessionCache, sessionPool: sync.Pool{ - New: func() interface{} { + New: func() any { return &model.Session{} }, }, diff --git a/app/web_conn.go b/app/web_conn.go index 6f7e452358..5ac66c008e 100644 --- a/app/web_conn.go +++ b/app/web_conn.go @@ -362,7 +362,7 @@ func (wc *WebConn) readPump() { } var decoder interface { - Decode(v interface{}) error + Decode(v any) error } if msgType == websocket.TextMessage { decoder = json.NewDecoder(rd) diff --git a/app/webhook.go b/app/webhook.go index ebb4870fac..95794aa26e 100644 --- a/app/webhook.go +++ b/app/webhook.go @@ -187,7 +187,7 @@ func SplitWebhookPost(post *model.Post, maxPostSize int) ([]*model.Post, *model. base := post.Clone() base.Message = "" - base.SetProps(make(map[string]interface{})) + base.SetProps(make(map[string]any)) for k, v := range post.GetProps() { if k != "attachments" { base.AddProp(k, v) @@ -195,7 +195,7 @@ func SplitWebhookPost(post *model.Post, maxPostSize int) ([]*model.Post, *model. } if utf8.RuneCountInString(model.StringInterfaceToJSON(base.GetProps())) > model.PostPropsMaxUserRunes { - return nil, model.NewAppError("SplitWebhookPost", "web.incoming_webhook.split_props_length.app_error", map[string]interface{}{"Max": model.PostPropsMaxUserRunes}, "", http.StatusBadRequest) + return nil, model.NewAppError("SplitWebhookPost", "web.incoming_webhook.split_props_length.app_error", map[string]any{"Max": model.PostPropsMaxUserRunes}, "", http.StatusBadRequest) } for utf8.RuneCountInString(remainingText) > maxPostSize { @@ -221,7 +221,7 @@ func SplitWebhookPost(post *model.Post, maxPostSize int) ([]*model.Post, *model. newAttachment := *attachment for { lastSplit := splits[len(splits)-1] - newProps := make(map[string]interface{}) + newProps := make(map[string]any) for k, v := range lastSplit.GetProps() { newProps[k] = v } @@ -244,7 +244,7 @@ func SplitWebhookPost(post *model.Post, maxPostSize int) ([]*model.Post, *model. truncationNeeded := runeCount - model.PostPropsMaxUserRunes textRuneCount := utf8.RuneCountInString(attachment.Text) if textRuneCount < truncationNeeded { - return nil, model.NewAppError("SplitWebhookPost", "web.incoming_webhook.split_props_length.app_error", map[string]interface{}{"Max": model.PostPropsMaxUserRunes}, "", http.StatusBadRequest) + return nil, model.NewAppError("SplitWebhookPost", "web.incoming_webhook.split_props_length.app_error", map[string]any{"Max": model.PostPropsMaxUserRunes}, "", http.StatusBadRequest) } x := 0 for index := range attachment.Text { @@ -271,7 +271,7 @@ func (a *App) CreateWebhookPost(c *request.Context, userID string, channel *mode post.AddProp("from_webhook", "true") if strings.HasPrefix(post.Type, model.PostSystemMessagePrefix) { - err := model.NewAppError("CreateWebhookPost", "api.context.invalid_param.app_error", map[string]interface{}{"Name": "post.type"}, "", http.StatusBadRequest) + err := model.NewAppError("CreateWebhookPost", "api.context.invalid_param.app_error", map[string]any{"Name": "post.type"}, "", http.StatusBadRequest) return nil, err } @@ -828,7 +828,7 @@ func (a *App) HandleCommandWebhook(c *request.Context, hookID string, response * var nfErr *store.ErrNotFound switch { case errors.As(nErr, &nfErr): - return model.NewAppError("HandleCommandWebhook", "app.command_webhook.get.missing", map[string]interface{}{"hook_id": hookID}, nfErr.Error(), http.StatusNotFound) + return model.NewAppError("HandleCommandWebhook", "app.command_webhook.get.missing", map[string]any{"hook_id": hookID}, nfErr.Error(), http.StatusNotFound) default: return model.NewAppError("HandleCommandWebhook", "app.command_webhook.get.internal_error", nil, nErr.Error(), http.StatusInternalServerError) } diff --git a/app/webhook_test.go b/app/webhook_test.go index e28835862c..d307eba373 100644 --- a/app/webhook_test.go +++ b/app/webhook_test.go @@ -388,7 +388,7 @@ func TestSplitWebhookPost(t *testing.T) { "LongPostAndMultipleAttachments": { Post: &model.Post{ Message: strings.Repeat("本", maxPostSize*3/2), - Props: map[string]interface{}{ + Props: map[string]any{ "attachments": []*model.SlackAttachment{ { Text: strings.Repeat("本", 1000), @@ -408,7 +408,7 @@ func TestSplitWebhookPost(t *testing.T) { }, { Message: strings.Repeat("本", maxPostSize/2), - Props: map[string]interface{}{ + Props: map[string]any{ "attachments": []*model.SlackAttachment{ { Text: strings.Repeat("本", 1000), @@ -420,7 +420,7 @@ func TestSplitWebhookPost(t *testing.T) { }, }, { - Props: map[string]interface{}{ + Props: map[string]any{ "attachments": []*model.SlackAttachment{ { Text: strings.Repeat("本", model.PostPropsMaxUserRunes-1000), @@ -433,7 +433,7 @@ func TestSplitWebhookPost(t *testing.T) { "UnsplittableProps": { Post: &model.Post{ Message: "foo", - Props: map[string]interface{}{ + Props: map[string]any{ "foo": strings.Repeat("x", model.PostPropsMaxUserRunes*2), }, }, @@ -467,7 +467,7 @@ func makePost(message int, attachments []int) *model.Post { } sa = append(sa, attach) } - props = map[string]interface{}{"attachments": sa} + props = map[string]any{"attachments": sa} } post := &model.Post{ Message: strings.Repeat("那", message), @@ -782,7 +782,7 @@ func TestDoOutgoingWebhookRequest(t *testing.T) { }) t.Run("with a slow response", func(t *testing.T) { - releaseHandler := make(chan interface{}) + releaseHandler := make(chan any) server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { // Don't actually handle the response, allowing the app to timeout. diff --git a/app/webhub_fuzz.go b/app/webhub_fuzz.go index b0d249a84d..5f39d8952d 100644 --- a/app/webhub_fuzz.go +++ b/app/webhub_fuzz.go @@ -101,7 +101,7 @@ type actionData struct { selectTeamID string invalidateConnUserID string updateConnUserID string - attachment map[string]interface{} + attachment map[string]any } func getActionData(data []byte, userIDs, teamIDs, channelIDs []string) *actionData { @@ -131,7 +131,7 @@ func getActionData(data []byte, userIDs, teamIDs, channelIDs []string) *actionDa input.updateConnUserID = userIDs[int(data[4])%len(userIDs)] input.event = events[int(data[5])%len(events)] data = data[6:] - input.attachment = make(map[string]interface{}) + input.attachment = make(map[string]any) for len(data) >= 4 { // 2 bytes key, 2 bytes value k := data[:2] v := data[2:4] diff --git a/audit/record.go b/audit/record.go index 08aebcb59c..6f392309ab 100644 --- a/audit/record.go +++ b/audit/record.go @@ -4,11 +4,11 @@ package audit // Meta represents metadata that can be added to a audit record as name/value pairs. -type Meta map[string]interface{} +type Meta map[string]any // FuncMetaTypeConv defines a function that can convert meta data types into something // that serializes well for audit records. -type FuncMetaTypeConv func(val interface{}) (newVal interface{}, converted bool) +type FuncMetaTypeConv func(val any) (newVal any, converted bool) // Record provides a consistent set of fields used for all audit logging. type Record struct { @@ -34,7 +34,7 @@ func (rec *Record) Fail() { } // AddMeta adds a single name/value pair to this audit record's metadata. -func (rec *Record) AddMeta(name string, val interface{}) { +func (rec *Record) AddMeta(name string, val any) { if rec.Meta == nil { rec.Meta = Meta{} } diff --git a/audit/record_test.go b/audit/record_test.go index 4c809d4f42..e9c5d8bd60 100644 --- a/audit/record_test.go +++ b/audit/record_test.go @@ -20,7 +20,7 @@ type wilted struct { wilt1 string } -func conv(val interface{}) (interface{}, bool) { +func conv(val any) (any, bool) { switch v := val.(type) { case *bloated: return &wilted{wilt1: v.fld1}, true @@ -34,7 +34,7 @@ func TestRecord_AddMeta(t *testing.T) { } type args struct { name string - val interface{} + val any } tests := []struct { name string diff --git a/cmd/mattermost/commands/main_test.go b/cmd/mattermost/commands/main_test.go index eedfb08147..842bdda7e9 100644 --- a/cmd/mattermost/commands/main_test.go +++ b/cmd/mattermost/commands/main_test.go @@ -72,7 +72,7 @@ type TestNewTeamSettings struct { type TestPluginSettings struct { Enable *bool Directory *string `restricted:"true"` - Plugins map[string]map[string]interface{} + Plugins map[string]map[string]any PluginStates map[string]*model.PluginState SignaturePublicKeyFiles []string } diff --git a/cmd/mattermost/commands/output.go b/cmd/mattermost/commands/output.go index b2ee4b7c54..bf4584a78c 100644 --- a/cmd/mattermost/commands/output.go +++ b/cmd/mattermost/commands/output.go @@ -8,14 +8,14 @@ import ( "os" ) -func CommandPrintln(a ...interface{}) (int, error) { +func CommandPrintln(a ...any) (int, error) { return fmt.Println(a...) } -func CommandPrintErrorln(a ...interface{}) (int, error) { +func CommandPrintErrorln(a ...any) (int, error) { return fmt.Fprintln(os.Stderr, a...) } -func CommandPrettyPrintln(a ...interface{}) (int, error) { +func CommandPrettyPrintln(a ...any) (int, error) { return fmt.Fprintln(os.Stdout, a...) } diff --git a/cmd/mattermost/commands/utils.go b/cmd/mattermost/commands/utils.go index 08d39e4679..fb7a56d262 100644 --- a/cmd/mattermost/commands/utils.go +++ b/cmd/mattermost/commands/utils.go @@ -36,7 +36,7 @@ func printStringMap(value reflect.Value, tabVal int) string { for _, keyString := range sortedKeys { key := stringToKeyMap[keyString] val := value.MapIndex(key) - if newVal, ok := val.Interface().(map[string]interface{}); !ok { + if newVal, ok := val.Interface().(map[string]any); !ok { fmt.Fprintf(out, "%s", strings.Repeat("\t", tabVal)) fmt.Fprintf(out, "%v: \"%v\"\n", key.Interface(), val.Interface()) } else { diff --git a/cmd/mattermost/commands/utils_test.go b/cmd/mattermost/commands/utils_test.go index 38db114b20..94e01ea881 100644 --- a/cmd/mattermost/commands/utils_test.go +++ b/cmd/mattermost/commands/utils_test.go @@ -11,18 +11,18 @@ import ( ) func TestPrintMap(t *testing.T) { - inputCases := []interface{}{ - map[string]interface{}{ + inputCases := []any{ + map[string]any{ "CustomerType": "A9", "SmtpUsername": "", "SmtpPassword": "", "EmailAddress": "", }, - map[string]interface{}{ + map[string]any{ "EnableExport": false, "ExportFormat": "actiance", "DailyRunTime": "01:00", - "GlobalRelaySettings": map[string]interface{}{ + "GlobalRelaySettings": map[string]any{ "CustomerType": "A9", "SmtpUsername": "", "SmtpPassword": "", diff --git a/config/database.go b/config/database.go index f2447b2b27..1c3add6bbb 100644 --- a/config/database.go +++ b/config/database.go @@ -278,7 +278,7 @@ func (ds *DatabaseStore) persist(cfg *model.Config) error { return errors.Wrap(err, "failed to query active configuration") } if oldId != "" { - if _, err := tx.NamedExec("UPDATE Configurations SET Active = NULL WHERE Id = :id", map[string]interface{}{"id": oldId}); err != nil { + if _, err := tx.NamedExec("UPDATE Configurations SET Active = NULL WHERE Id = :id", map[string]any{"id": oldId}); err != nil { return errors.Wrap(err, "failed to deactivate current configuration") } } @@ -288,7 +288,7 @@ func (ds *DatabaseStore) persist(cfg *model.Config) error { } } - params := map[string]interface{}{ + params := map[string]any{ "id": model.NewId(), "value": value, "create_at": model.GetMillis(), @@ -329,7 +329,7 @@ func (ds *DatabaseStore) Load() ([]byte, error) { // GetFile fetches the contents of a previously persisted configuration file. func (ds *DatabaseStore) GetFile(name string) ([]byte, error) { - query, args, err := sqlx.Named("SELECT Data FROM ConfigurationFiles WHERE Name = :name", map[string]interface{}{ + query, args, err := sqlx.Named("SELECT Data FROM ConfigurationFiles WHERE Name = :name", map[string]any{ "name": name, }) if err != nil { @@ -351,7 +351,7 @@ func (ds *DatabaseStore) SetFile(name string, data []byte) error { if err != nil { return errors.Wrap(err, "file data failed length check") } - params := map[string]interface{}{ + params := map[string]any{ "name": name, "data": data, "create_at": model.GetMillis(), @@ -380,7 +380,7 @@ func (ds *DatabaseStore) SetFile(name string, data []byte) error { // HasFile returns true if the given file was previously persisted. func (ds *DatabaseStore) HasFile(name string) (bool, error) { - query, args, err := sqlx.Named("SELECT COUNT(*) FROM ConfigurationFiles WHERE Name = :name", map[string]interface{}{ + query, args, err := sqlx.Named("SELECT COUNT(*) FROM ConfigurationFiles WHERE Name = :name", map[string]any{ "name": name, }) if err != nil { @@ -398,7 +398,7 @@ func (ds *DatabaseStore) HasFile(name string) (bool, error) { // RemoveFile remoevs a previously persisted configuration file. func (ds *DatabaseStore) RemoveFile(name string) error { - _, err := ds.db.NamedExec("DELETE FROM ConfigurationFiles WHERE Name = :name", map[string]interface{}{ + _, err := ds.db.NamedExec("DELETE FROM ConfigurationFiles WHERE Name = :name", map[string]any{ "name": name, }) if err != nil { @@ -420,7 +420,7 @@ func (ds *DatabaseStore) Close() error { // removes configurations from database if they are older than threshold. func (ds *DatabaseStore) cleanUp(thresholdCreatAt int) error { - if _, err := ds.db.NamedExec("DELETE FROM Configurations Where CreateAt < :timestamp", map[string]interface{}{"timestamp": thresholdCreatAt}); err != nil { + if _, err := ds.db.NamedExec("DELETE FROM Configurations Where CreateAt < :timestamp", map[string]any{"timestamp": thresholdCreatAt}); err != nil { return errors.Wrap(err, "unable to clean Configurations table") } diff --git a/config/database_test.go b/config/database_test.go index eedaafd758..4eab71fc5c 100644 --- a/config/database_test.go +++ b/config/database_test.go @@ -47,7 +47,7 @@ func setupConfigDatabase(t *testing.T, cfg *model.Config, files map[string][]byt require.NoError(t, err) id := model.NewId() - _, err = ds.db.NamedExec("INSERT INTO Configurations (Id, Value, CreateAt, Active) VALUES(:Id, :Value, :CreateAt, TRUE)", map[string]interface{}{ + _, err = ds.db.NamedExec("INSERT INTO Configurations (Id, Value, CreateAt, Active) VALUES(:Id, :Value, :CreateAt, TRUE)", map[string]any{ "Id": id, "Value": cfgData, "CreateAt": model.GetMillis(), @@ -55,7 +55,7 @@ func setupConfigDatabase(t *testing.T, cfg *model.Config, files map[string][]byt require.NoError(t, err) for name, data := range files { - params := map[string]interface{}{ + params := map[string]any{ "name": name, "data": data, "create_at": model.GetMillis(), @@ -268,7 +268,7 @@ func TestDatabaseStoreGetEnvironmentOverrides(t *testing.T) { defer ds.Close() assert.Equal(t, "http://override", *ds.Get().ServiceSettings.SiteURL) - assert.Equal(t, map[string]interface{}{"ServiceSettings": map[string]interface{}{"SiteURL": true}}, ds.GetEnvironmentOverrides()) + assert.Equal(t, map[string]any{"ServiceSettings": map[string]any{"SiteURL": true}}, ds.GetEnvironmentOverrides()) }) t.Run("get override for a string variable with a custom default value", func(t *testing.T) { @@ -291,7 +291,7 @@ func TestDatabaseStoreGetEnvironmentOverrides(t *testing.T) { // environment override should take priority over the custom default value assert.Equal(t, "http://override", *ds.Get().ServiceSettings.SiteURL) - assert.Equal(t, map[string]interface{}{"ServiceSettings": map[string]interface{}{"SiteURL": true}}, ds.GetEnvironmentOverrides()) + assert.Equal(t, map[string]any{"ServiceSettings": map[string]any{"SiteURL": true}}, ds.GetEnvironmentOverrides()) }) t.Run("get override for a bool variable", func(t *testing.T) { @@ -313,7 +313,7 @@ func TestDatabaseStoreGetEnvironmentOverrides(t *testing.T) { defer ds.Close() assert.Equal(t, true, *ds.Get().PluginSettings.EnableUploads) - assert.Equal(t, map[string]interface{}{"PluginSettings": map[string]interface{}{"EnableUploads": true}}, ds.GetEnvironmentOverrides()) + assert.Equal(t, map[string]any{"PluginSettings": map[string]any{"EnableUploads": true}}, ds.GetEnvironmentOverrides()) }) t.Run("get override for an int variable", func(t *testing.T) { @@ -335,7 +335,7 @@ func TestDatabaseStoreGetEnvironmentOverrides(t *testing.T) { defer ds.Close() assert.Equal(t, 3000, *ds.Get().TeamSettings.MaxUsersPerTeam) - assert.Equal(t, map[string]interface{}{"TeamSettings": map[string]interface{}{"MaxUsersPerTeam": true}}, ds.GetEnvironmentOverrides()) + assert.Equal(t, map[string]any{"TeamSettings": map[string]any{"MaxUsersPerTeam": true}}, ds.GetEnvironmentOverrides()) }) t.Run("get override for an int64 variable", func(t *testing.T) { @@ -357,7 +357,7 @@ func TestDatabaseStoreGetEnvironmentOverrides(t *testing.T) { defer ds.Close() assert.Equal(t, int64(123456), *ds.Get().ServiceSettings.TLSStrictTransportMaxAge) - assert.Equal(t, map[string]interface{}{"ServiceSettings": map[string]interface{}{"TLSStrictTransportMaxAge": true}}, ds.GetEnvironmentOverrides()) + assert.Equal(t, map[string]any{"ServiceSettings": map[string]any{"TLSStrictTransportMaxAge": true}}, ds.GetEnvironmentOverrides()) }) t.Run("get override for a slice variable - one value", func(t *testing.T) { @@ -379,7 +379,7 @@ func TestDatabaseStoreGetEnvironmentOverrides(t *testing.T) { defer ds.Close() assert.Equal(t, []string{"user:pwd@db:5432/test-db"}, ds.Get().SqlSettings.DataSourceReplicas) - assert.Equal(t, map[string]interface{}{"SqlSettings": map[string]interface{}{"DataSourceReplicas": true}}, ds.GetEnvironmentOverrides()) + assert.Equal(t, map[string]any{"SqlSettings": map[string]any{"DataSourceReplicas": true}}, ds.GetEnvironmentOverrides()) }) t.Run("get override for a slice variable - three values", func(t *testing.T) { @@ -404,7 +404,7 @@ func TestDatabaseStoreGetEnvironmentOverrides(t *testing.T) { defer ds.Close() assert.Equal(t, []string{"user:pwd@db:5432/test-db", "user:pwd@db2:5433/test-db2", "user:pwd@db3:5434/test-db3"}, ds.Get().SqlSettings.DataSourceReplicas) - assert.Equal(t, map[string]interface{}{"SqlSettings": map[string]interface{}{"DataSourceReplicas": true}}, ds.GetEnvironmentOverrides()) + assert.Equal(t, map[string]any{"SqlSettings": map[string]any{"DataSourceReplicas": true}}, ds.GetEnvironmentOverrides()) }) } @@ -679,7 +679,7 @@ func TestDatabaseStoreLoad(t *testing.T) { err = ds.Load() require.NoError(t, err) assert.Equal(t, "http://override", *ds.Get().ServiceSettings.SiteURL) - assert.Equal(t, map[string]interface{}{"ServiceSettings": map[string]interface{}{"SiteURL": true}}, ds.GetEnvironmentOverrides()) + assert.Equal(t, map[string]any{"ServiceSettings": map[string]any{"SiteURL": true}}, ds.GetEnvironmentOverrides()) }) t.Run("do not persist environment variables - string", func(t *testing.T) { @@ -697,7 +697,7 @@ func TestDatabaseStoreLoad(t *testing.T) { require.NoError(t, err) assert.Equal(t, "http://overridePersistEnvVariables", *ds.Get().ServiceSettings.SiteURL) - assert.Equal(t, map[string]interface{}{"ServiceSettings": map[string]interface{}{"SiteURL": true}}, ds.GetEnvironmentOverrides()) + assert.Equal(t, map[string]any{"ServiceSettings": map[string]any{"SiteURL": true}}, ds.GetEnvironmentOverrides()) // check that in DB config does not include overwritten variable _, actualConfig := getActualDatabaseConfig(t) assert.Equal(t, "http://minimal", *actualConfig.ServiceSettings.SiteURL) @@ -720,7 +720,7 @@ func TestDatabaseStoreLoad(t *testing.T) { require.NoError(t, err) assert.Equal(t, true, *ds.Get().PluginSettings.EnableUploads) - assert.Equal(t, map[string]interface{}{"PluginSettings": map[string]interface{}{"EnableUploads": true}}, ds.GetEnvironmentOverrides()) + assert.Equal(t, map[string]any{"PluginSettings": map[string]any{"EnableUploads": true}}, ds.GetEnvironmentOverrides()) // check that in DB config does not include overwritten variable _, actualConfig := getActualDatabaseConfig(t) assert.Equal(t, false, *actualConfig.PluginSettings.EnableUploads) @@ -743,7 +743,7 @@ func TestDatabaseStoreLoad(t *testing.T) { require.NoError(t, err) assert.Equal(t, 3000, *ds.Get().TeamSettings.MaxUsersPerTeam) - assert.Equal(t, map[string]interface{}{"TeamSettings": map[string]interface{}{"MaxUsersPerTeam": true}}, ds.GetEnvironmentOverrides()) + assert.Equal(t, map[string]any{"TeamSettings": map[string]any{"MaxUsersPerTeam": true}}, ds.GetEnvironmentOverrides()) // check that in DB config does not include overwritten variable _, actualConfig := getActualDatabaseConfig(t) assert.Equal(t, model.TeamSettingsDefaultMaxUsersPerTeam, *actualConfig.TeamSettings.MaxUsersPerTeam) @@ -766,7 +766,7 @@ func TestDatabaseStoreLoad(t *testing.T) { require.NoError(t, err) assert.Equal(t, int64(123456), *ds.Get().ServiceSettings.TLSStrictTransportMaxAge) - assert.Equal(t, map[string]interface{}{"ServiceSettings": map[string]interface{}{"TLSStrictTransportMaxAge": true}}, ds.GetEnvironmentOverrides()) + assert.Equal(t, map[string]any{"ServiceSettings": map[string]any{"TLSStrictTransportMaxAge": true}}, ds.GetEnvironmentOverrides()) // check that in DB config does not include overwritten variable _, actualConfig := getActualDatabaseConfig(t) assert.Equal(t, int64(63072000), *actualConfig.ServiceSettings.TLSStrictTransportMaxAge) @@ -789,7 +789,7 @@ func TestDatabaseStoreLoad(t *testing.T) { require.NoError(t, err) assert.Equal(t, []string{"user:pwd@db:5432/test-db"}, ds.Get().SqlSettings.DataSourceReplicas) - assert.Equal(t, map[string]interface{}{"SqlSettings": map[string]interface{}{"DataSourceReplicas": true}}, ds.GetEnvironmentOverrides()) + assert.Equal(t, map[string]any{"SqlSettings": map[string]any{"DataSourceReplicas": true}}, ds.GetEnvironmentOverrides()) // check that in DB config does not include overwritten variable _, actualConfig := getActualDatabaseConfig(t) assert.Equal(t, []string{}, actualConfig.SqlSettings.DataSourceReplicas) @@ -814,7 +814,7 @@ func TestDatabaseStoreLoad(t *testing.T) { require.NoError(t, err) assert.Equal(t, []string{"user:pwd@db:5432/test-db"}, ds.Get().SqlSettings.DataSourceReplicas) - assert.Equal(t, map[string]interface{}{"SqlSettings": map[string]interface{}{"DataSourceReplicas": true}}, ds.GetEnvironmentOverrides()) + assert.Equal(t, map[string]any{"SqlSettings": map[string]any{"DataSourceReplicas": true}}, ds.GetEnvironmentOverrides()) // check that in DB config does not include overwritten variable _, actualConfig := getActualDatabaseConfig(t) assert.Equal(t, []string{"user:pwd@db:5432/test-db", "user:pwd@db2:5433/test-db2", "user:pwd@db3:5434/test-db3"}, actualConfig.SqlSettings.DataSourceReplicas) @@ -833,7 +833,7 @@ func TestDatabaseStoreLoad(t *testing.T) { truncateTables(t) id := model.NewId() - _, err = mainHelper.GetSQLStore().GetMasterX().NamedExec("INSERT INTO Configurations (Id, Value, CreateAt, Active) VALUES(:id, :value, :createat, TRUE)", map[string]interface{}{ + _, err = mainHelper.GetSQLStore().GetMasterX().NamedExec("INSERT INTO Configurations (Id, Value, CreateAt, Active) VALUES(:id, :value, :createat, TRUE)", map[string]any{ "id": id, "value": cfgData, "createat": model.GetMillis(), @@ -1140,7 +1140,7 @@ func TestCleanUp(t *testing.T) { // first 2 (0 and 1) will be within a month constraint, others will be older than // a month hence we expect 3 configurations to be removed from the database. m := -1 * i * 24 * 20 - params := map[string]interface{}{ + params := map[string]any{ "id": model.NewId(), "value": string(b), "create_at": model.GetMillisForTime(now.Add(time.Duration(m) * time.Hour)), diff --git a/config/diff.go b/config/diff.go index 1390918445..ce2f706046 100644 --- a/config/diff.go +++ b/config/diff.go @@ -13,9 +13,9 @@ import ( type ConfigDiffs []ConfigDiff type ConfigDiff struct { - Path string `json:"path"` - BaseVal interface{} `json:"base_val"` - ActualVal interface{} `json:"actual_val"` + Path string `json:"path"` + BaseVal any `json:"base_val"` + ActualVal any `json:"actual_val"` } var configSensitivePaths = map[string]bool{ diff --git a/config/diff_test.go b/config/diff_test.go index 405547bd3a..15ec6f41f7 100644 --- a/config/diff_test.go +++ b/config/diff_test.go @@ -511,7 +511,7 @@ func TestDiffSanitized(t *testing.T) { defaultConfigGen(), func() *model.Config { cfg := defaultConfigGen() - cfg.PluginSettings.Plugins = map[string]map[string]interface{}{ + cfg.PluginSettings.Plugins = map[string]map[string]any{ "com.mattermost.newplugin": { "key": true, }, @@ -915,7 +915,7 @@ func TestDiff(t *testing.T) { "map type change", func() *model.Config { cfg := defaultConfigGen() - cfg.PluginSettings.Plugins = map[string]map[string]interface{}{ + cfg.PluginSettings.Plugins = map[string]map[string]any{ "com.mattermost.newplugin": { "key": true, }, @@ -924,7 +924,7 @@ func TestDiff(t *testing.T) { }(), func() *model.Config { cfg := defaultConfigGen() - cfg.PluginSettings.Plugins = map[string]map[string]interface{}{ + cfg.PluginSettings.Plugins = map[string]map[string]any{ "com.mattermost.newplugin": { "key": "string", }, @@ -934,15 +934,15 @@ func TestDiff(t *testing.T) { ConfigDiffs{ { Path: "PluginSettings.Plugins", - BaseVal: func() interface{} { - return map[string]map[string]interface{}{ + BaseVal: func() any { + return map[string]map[string]any{ "com.mattermost.newplugin": { "key": true, }, } }(), - ActualVal: func() interface{} { - return map[string]map[string]interface{}{ + ActualVal: func() any { + return map[string]map[string]any{ "com.mattermost.newplugin": { "key": "string", }, diff --git a/config/emitter.go b/config/emitter.go index 4431cba2dc..b35295b122 100644 --- a/config/emitter.go +++ b/config/emitter.go @@ -32,7 +32,7 @@ func (e *emitter) RemoveListener(id string) { // invokeConfigListeners synchronously notifies all listeners about the configuration change. func (e *emitter) invokeConfigListeners(oldCfg, newCfg *model.Config) { - e.listeners.Range(func(key, value interface{}) bool { + e.listeners.Range(func(key, value any) bool { listener := value.(Listener) listener(oldCfg, newCfg) return true @@ -58,7 +58,7 @@ func (e *logSrcEmitter) RemoveListener(id string) { // invokeConfigListeners synchronously notifies all listeners about the configuration change. func (e *logSrcEmitter) invokeConfigListeners(oldCfg, newCfg mlog.LoggerConfiguration) { - e.listeners.Range(func(key, value interface{}) bool { + e.listeners.Range(func(key, value any) bool { listener := value.(LogSrcListener) listener(oldCfg, newCfg) return true diff --git a/config/environment.go b/config/environment.go index d6b68864c2..12e6727484 100644 --- a/config/environment.go +++ b/config/environment.go @@ -87,19 +87,19 @@ func applyEnvironmentMap(inputConfig *model.Config, env map[string]string) *mode return appliedConfig } -// generateEnvironmentMap creates a map[string]interface{} containing true at the leaves mirroring the +// generateEnvironmentMap creates a map[string]any containing true at the leaves mirroring the // configuration structure so the client can know which env variables are overridden -func generateEnvironmentMap(env map[string]string, filter func(reflect.StructField) bool) map[string]interface{} { +func generateEnvironmentMap(env map[string]string, filter func(reflect.StructField) bool) map[string]any { rType := reflect.TypeOf(model.Config{}) return generateEnvironmentMapWithBaseKey(env, rType, "MM", filter) } -func generateEnvironmentMapWithBaseKey(env map[string]string, rType reflect.Type, base string, filter func(reflect.StructField) bool) map[string]interface{} { +func generateEnvironmentMapWithBaseKey(env map[string]string, rType reflect.Type, base string, filter func(reflect.StructField) bool) map[string]any { if rType.Kind() != reflect.Struct { return nil } - mapRepresentation := make(map[string]interface{}) + mapRepresentation := make(map[string]any) for i := 0; i < rType.NumField(); i++ { rField := rType.Field(i) if filter != nil && !filter(rField) { @@ -126,7 +126,7 @@ func generateEnvironmentMapWithBaseKey(env map[string]string, rType reflect.Type // removeEnvOverrides returns a new config without the given environment overrides. // If a config variable has an environment override, that variable is set to the value that was // read from the store. -func removeEnvOverrides(cfg, cfgWithoutEnv *model.Config, envOverrides map[string]interface{}) *model.Config { +func removeEnvOverrides(cfg, cfgWithoutEnv *model.Config, envOverrides map[string]any) *model.Config { paths := getPaths(envOverrides) newCfg := cfg.Clone() for _, path := range paths { @@ -142,13 +142,13 @@ func removeEnvOverrides(cfg, cfgWithoutEnv *model.Config, envOverrides map[strin // getPaths turns a nested map into a slice of paths describing the keys of the map. Eg: // map[string]map[string]map[string]bool{"this":{"is first":{"path":true}, "is second":{"path":true}))) is turned into: // [][]string{{"this", "is first", "path"}, {"this", "is second", "path"}} -func getPaths(m map[string]interface{}) [][]string { +func getPaths(m map[string]any) [][]string { return getPathsRec(m, nil) } // getPathsRec assembles the paths (see `getPaths` above) -func getPathsRec(src interface{}, curPath []string) [][]string { - if srcMap, ok := src.(map[string]interface{}); ok { +func getPathsRec(src any, curPath []string) [][]string { + if srcMap, ok := src.(map[string]any); ok { paths := [][]string{} for k, v := range srcMap { paths = append(paths, getPathsRec(v, append(curPath, k))...) @@ -161,10 +161,10 @@ func getPathsRec(src interface{}, curPath []string) [][]string { // getVal walks `src` (here it starts with a model.Config, then recurses into its leaves) // and returns the reflect.Value of the leaf at the end `path` -func getVal(src interface{}, path []string) reflect.Value { +func getVal(src any, path []string) reflect.Value { var val reflect.Value - // If we recursed on a Value, we already have it. If we're calling on an interface{}, get the Value. + // If we recursed on a Value, we already have it. If we're calling on an any, get the Value. switch v := src.(type) { case reflect.Value: val = v diff --git a/config/file_test.go b/config/file_test.go index c1ed624eff..0ae493b499 100644 --- a/config/file_test.go +++ b/config/file_test.go @@ -295,7 +295,7 @@ func TestFileStoreGetEnvironmentOverrides(t *testing.T) { defer fs.Close() assert.Equal(t, "http://override", *fs.Get().ServiceSettings.SiteURL) - assert.Equal(t, map[string]interface{}{"ServiceSettings": map[string]interface{}{"SiteURL": true}}, fs.GetEnvironmentOverrides()) + assert.Equal(t, map[string]any{"ServiceSettings": map[string]any{"SiteURL": true}}, fs.GetEnvironmentOverrides()) }) t.Run("get override for a string variable, with custom defaults", func(t *testing.T) { @@ -322,7 +322,7 @@ func TestFileStoreGetEnvironmentOverrides(t *testing.T) { // environment override should take priority over the custom default value assert.Equal(t, "http://override", *fs.Get().ServiceSettings.SiteURL) - assert.Equal(t, map[string]interface{}{"ServiceSettings": map[string]interface{}{"SiteURL": true}}, fs.GetEnvironmentOverrides()) + assert.Equal(t, map[string]any{"ServiceSettings": map[string]any{"SiteURL": true}}, fs.GetEnvironmentOverrides()) }) t.Run("get override for a bool variable", func(t *testing.T) { @@ -348,7 +348,7 @@ func TestFileStoreGetEnvironmentOverrides(t *testing.T) { defer fs.Close() assert.Equal(t, true, *fs.Get().PluginSettings.EnableUploads) - assert.Equal(t, map[string]interface{}{"PluginSettings": map[string]interface{}{"EnableUploads": true}}, fs.GetEnvironmentOverrides()) + assert.Equal(t, map[string]any{"PluginSettings": map[string]any{"EnableUploads": true}}, fs.GetEnvironmentOverrides()) }) t.Run("get override for an int variable", func(t *testing.T) { @@ -374,7 +374,7 @@ func TestFileStoreGetEnvironmentOverrides(t *testing.T) { defer fs.Close() assert.Equal(t, 3000, *fs.Get().TeamSettings.MaxUsersPerTeam) - assert.Equal(t, map[string]interface{}{"TeamSettings": map[string]interface{}{"MaxUsersPerTeam": true}}, fs.GetEnvironmentOverrides()) + assert.Equal(t, map[string]any{"TeamSettings": map[string]any{"MaxUsersPerTeam": true}}, fs.GetEnvironmentOverrides()) }) t.Run("get override for an int64 variable", func(t *testing.T) { @@ -400,7 +400,7 @@ func TestFileStoreGetEnvironmentOverrides(t *testing.T) { defer fs.Close() assert.Equal(t, int64(123456), *fs.Get().ServiceSettings.TLSStrictTransportMaxAge) - assert.Equal(t, map[string]interface{}{"ServiceSettings": map[string]interface{}{"TLSStrictTransportMaxAge": true}}, fs.GetEnvironmentOverrides()) + assert.Equal(t, map[string]any{"ServiceSettings": map[string]any{"TLSStrictTransportMaxAge": true}}, fs.GetEnvironmentOverrides()) }) t.Run("get override for a slice variable - one value", func(t *testing.T) { @@ -426,7 +426,7 @@ func TestFileStoreGetEnvironmentOverrides(t *testing.T) { defer fs.Close() assert.Equal(t, []string{"user:pwd@db:5432/test-db"}, fs.Get().SqlSettings.DataSourceReplicas) - assert.Equal(t, map[string]interface{}{"SqlSettings": map[string]interface{}{"DataSourceReplicas": true}}, fs.GetEnvironmentOverrides()) + assert.Equal(t, map[string]any{"SqlSettings": map[string]any{"DataSourceReplicas": true}}, fs.GetEnvironmentOverrides()) }) t.Run("get override for a slice variable - three values", func(t *testing.T) { @@ -452,7 +452,7 @@ func TestFileStoreGetEnvironmentOverrides(t *testing.T) { defer fs.Close() assert.Equal(t, []string{"user:pwd@db:5432/test-db", "user:pwd@db2:5433/test-db2", "user:pwd@db3:5434/test-db3"}, fs.Get().SqlSettings.DataSourceReplicas) - assert.Equal(t, map[string]interface{}{"SqlSettings": map[string]interface{}{"DataSourceReplicas": true}}, fs.GetEnvironmentOverrides()) + assert.Equal(t, map[string]any{"SqlSettings": map[string]any{"DataSourceReplicas": true}}, fs.GetEnvironmentOverrides()) }) } @@ -647,7 +647,7 @@ func TestFileStoreLoad(t *testing.T) { err := configStore.Load() require.NoError(t, err) assert.Equal(t, "http://override", *configStore.Get().ServiceSettings.SiteURL) - assert.Equal(t, map[string]interface{}{"ServiceSettings": map[string]interface{}{"SiteURL": true}}, configStore.GetEnvironmentOverrides()) + assert.Equal(t, map[string]any{"ServiceSettings": map[string]any{"SiteURL": true}}, configStore.GetEnvironmentOverrides()) }) t.Run("do not persist environment variables - string", func(t *testing.T) { @@ -669,7 +669,7 @@ func TestFileStoreLoad(t *testing.T) { require.NoError(t, err) assert.Equal(t, "http://overridePersistEnvVariables", *fs.Get().ServiceSettings.SiteURL) - assert.Equal(t, map[string]interface{}{"ServiceSettings": map[string]interface{}{"SiteURL": true}}, fs.GetEnvironmentOverrides()) + assert.Equal(t, map[string]any{"ServiceSettings": map[string]any{"SiteURL": true}}, fs.GetEnvironmentOverrides()) // check that on disk config does not include overwritten variable actualConfig := getActualFileConfig(t, path) assert.Equal(t, "http://minimal", *actualConfig.ServiceSettings.SiteURL) @@ -694,7 +694,7 @@ func TestFileStoreLoad(t *testing.T) { require.NoError(t, err) assert.Equal(t, true, *fs.Get().PluginSettings.EnableUploads) - assert.Equal(t, map[string]interface{}{"PluginSettings": map[string]interface{}{"EnableUploads": true}}, fs.GetEnvironmentOverrides()) + assert.Equal(t, map[string]any{"PluginSettings": map[string]any{"EnableUploads": true}}, fs.GetEnvironmentOverrides()) // check that on disk config does not include overwritten variable actualConfig := getActualFileConfig(t, path) assert.Equal(t, false, *actualConfig.PluginSettings.EnableUploads) @@ -719,7 +719,7 @@ func TestFileStoreLoad(t *testing.T) { require.NoError(t, err) assert.Equal(t, 3000, *fs.Get().TeamSettings.MaxUsersPerTeam) - assert.Equal(t, map[string]interface{}{"TeamSettings": map[string]interface{}{"MaxUsersPerTeam": true}}, fs.GetEnvironmentOverrides()) + assert.Equal(t, map[string]any{"TeamSettings": map[string]any{"MaxUsersPerTeam": true}}, fs.GetEnvironmentOverrides()) // check that on disk config does not include overwritten variable actualConfig := getActualFileConfig(t, path) assert.Equal(t, model.TeamSettingsDefaultMaxUsersPerTeam, *actualConfig.TeamSettings.MaxUsersPerTeam) @@ -744,7 +744,7 @@ func TestFileStoreLoad(t *testing.T) { require.NoError(t, err) assert.Equal(t, int64(123456), *fs.Get().ServiceSettings.TLSStrictTransportMaxAge) - assert.Equal(t, map[string]interface{}{"ServiceSettings": map[string]interface{}{"TLSStrictTransportMaxAge": true}}, fs.GetEnvironmentOverrides()) + assert.Equal(t, map[string]any{"ServiceSettings": map[string]any{"TLSStrictTransportMaxAge": true}}, fs.GetEnvironmentOverrides()) // check that on disk config does not include overwritten variable actualConfig := getActualFileConfig(t, path) assert.Equal(t, int64(63072000), *actualConfig.ServiceSettings.TLSStrictTransportMaxAge) @@ -769,7 +769,7 @@ func TestFileStoreLoad(t *testing.T) { require.NoError(t, err) assert.Equal(t, []string{"user:pwd@db:5432/test-db"}, fs.Get().SqlSettings.DataSourceReplicas) - assert.Equal(t, map[string]interface{}{"SqlSettings": map[string]interface{}{"DataSourceReplicas": true}}, fs.GetEnvironmentOverrides()) + assert.Equal(t, map[string]any{"SqlSettings": map[string]any{"DataSourceReplicas": true}}, fs.GetEnvironmentOverrides()) // check that on disk config does not include overwritten variable actualConfig := getActualFileConfig(t, path) assert.Equal(t, []string{}, actualConfig.SqlSettings.DataSourceReplicas) @@ -796,7 +796,7 @@ func TestFileStoreLoad(t *testing.T) { require.NoError(t, err) assert.Equal(t, []string{"user:pwd@db:5432/test-db"}, fs.Get().SqlSettings.DataSourceReplicas) - assert.Equal(t, map[string]interface{}{"SqlSettings": map[string]interface{}{"DataSourceReplicas": true}}, fs.GetEnvironmentOverrides()) + assert.Equal(t, map[string]any{"SqlSettings": map[string]any{"DataSourceReplicas": true}}, fs.GetEnvironmentOverrides()) // check that on disk config does not include overwritten variable actualConfig := getActualFileConfig(t, path) assert.Equal(t, []string{"user:pwd@db:5432/test-db", "user:pwd@db2:5433/test-db2", "user:pwd@db3:5434/test-db3"}, actualConfig.SqlSettings.DataSourceReplicas) diff --git a/config/logger_test.go b/config/logger_test.go index b6f77852da..a629aec2fc 100644 --- a/config/logger_test.go +++ b/config/logger_test.go @@ -38,13 +38,13 @@ func TestMloggerConfigFromAuditConfig(t *testing.T) { assert.ElementsMatch(t, targetCfg.Levels, []mlog.Level{mlog.LvlAuditAPI, mlog.LvlAuditContent, mlog.LvlAuditPerms, mlog.LvlAuditCLI}) // check format options - optionsExpected := map[string]interface{}{ + optionsExpected := map[string]any{ "disable_timestamp": false, "disable_msg": true, "disable_stacktrace": true, "disable_level": true, } - var optionsReceived map[string]interface{} + var optionsReceived map[string]any err = json.Unmarshal(targetCfg.FormatOptions, &optionsReceived) require.NoError(t, err, "unmarshal should not fail") assert.Equal(t, optionsExpected, optionsReceived) diff --git a/config/store.go b/config/store.go index 760d779dab..69e5bfa778 100644 --- a/config/store.go +++ b/config/store.go @@ -137,13 +137,13 @@ func (s *Store) GetNoEnv() *model.Config { } // GetEnvironmentOverrides fetches the configuration fields overridden by environment variables. -func (s *Store) GetEnvironmentOverrides() map[string]interface{} { +func (s *Store) GetEnvironmentOverrides() map[string]any { return generateEnvironmentMap(GetEnvironment(), nil) } // GetEnvironmentOverridesWithFilter fetches the configuration fields overridden by environment variables. // If filter is not nil and returns false for a struct field, that field will be omitted. -func (s *Store) GetEnvironmentOverridesWithFilter(filter func(reflect.StructField) bool) map[string]interface{} { +func (s *Store) GetEnvironmentOverridesWithFilter(filter func(reflect.StructField) bool) map[string]any { return generateEnvironmentMap(GetEnvironment(), filter) } diff --git a/config/utils.go b/config/utils.go index 3034db01ab..9faa69e738 100644 --- a/config/utils.go +++ b/config/utils.go @@ -201,11 +201,11 @@ func stripPassword(dsn, schema string) string { } func isJSONMap(data string) bool { - var m map[string]interface{} + var m map[string]any return json.Unmarshal([]byte(data), &m) == nil } -func GetValueByPath(path []string, obj interface{}) (interface{}, bool) { +func GetValueByPath(path []string, obj any) (any, bool) { r := reflect.ValueOf(obj) var val reflect.Value if r.Kind() == reflect.Map { diff --git a/einterfaces/mocks/AppContextInterface.go b/einterfaces/mocks/AppContextInterface.go index 4cd8f9bcea..6dd47b04d4 100644 --- a/einterfaces/mocks/AppContextInterface.go +++ b/einterfaces/mocks/AppContextInterface.go @@ -87,14 +87,14 @@ func (_m *AppContextInterface) Session() *model.Session { } // T provides a mock function with given fields: translationID, args -func (_m *AppContextInterface) T(translationID string, args ...interface{}) string { - var _ca []interface{} +func (_m *AppContextInterface) T(translationID string, args ...any) string { + var _ca []any _ca = append(_ca, translationID) _ca = append(_ca, args...) ret := _m.Called(_ca...) var r0 string - if rf, ok := ret.Get(0).(func(string, ...interface{}) string); ok { + if rf, ok := ret.Get(0).(func(string, ...any) string); ok { r0 = rf(translationID, args...) } else { r0 = ret.Get(0).(string) diff --git a/jobs/migrations/advanced_permissions_phase_2.go b/jobs/migrations/advanced_permissions_phase_2.go index caebb980a9..4dbf0b233b 100644 --- a/jobs/migrations/advanced_permissions_phase_2.go +++ b/jobs/migrations/advanced_permissions_phase_2.go @@ -65,7 +65,7 @@ func (worker *Worker) runAdvancedPermissionsPhase2Migration(lastDone string) (bo } else { progress = AdvancedPermissionsPhase2ProgressFromJSON(strings.NewReader(lastDone)) if !progress.IsValid() { - return false, "", model.NewAppError("MigrationsWorker.runAdvancedPermissionsPhase2Migration", "migrations.worker.run_advanced_permissions_phase_2_migration.invalid_progress", map[string]interface{}{"progress": progress.ToJSON()}, "", http.StatusInternalServerError) + return false, "", model.NewAppError("MigrationsWorker.runAdvancedPermissionsPhase2Migration", "migrations.worker.run_advanced_permissions_phase_2_migration.invalid_progress", map[string]any{"progress": progress.ToJSON()}, "", http.StatusInternalServerError) } } diff --git a/jobs/migrations/worker.go b/jobs/migrations/worker.go index 001c04a493..9b121f7865 100644 --- a/jobs/migrations/worker.go +++ b/jobs/migrations/worker.go @@ -167,7 +167,7 @@ func (worker *Worker) runMigration(key string, lastDone string) (bool, string, * case model.MigrationKeyAdvancedPermissionsPhase2: done, progress, err = worker.runAdvancedPermissionsPhase2Migration(lastDone) default: - return false, "", model.NewAppError("MigrationsWorker.runMigration", "migrations.worker.run_migration.unknown_key", map[string]interface{}{"key": key}, "", http.StatusInternalServerError) + return false, "", model.NewAppError("MigrationsWorker.runMigration", "migrations.worker.run_migration.unknown_key", map[string]any{"key": key}, "", http.StatusInternalServerError) } if done { diff --git a/jobs/resend_invitation_email/worker.go b/jobs/resend_invitation_email/worker.go index d193b55261..1cb88238fe 100644 --- a/jobs/resend_invitation_email/worker.go +++ b/jobs/resend_invitation_email/worker.go @@ -203,5 +203,5 @@ func (rseworker *ResendInvitationEmailWorker) ResendEmails(job *model.Job, inter mlog.Error("Worker: Failed to send emails", mlog.String("worker", rseworker.name), mlog.String("job_id", job.Id), mlog.String("error", appErr.Error())) rseworker.setJobError(job, appErr) } - rseworker.telemetryService.SendTelemetry("track_invite_email_resend", map[string]interface{}{interval: interval}) + rseworker.telemetryService.SendTelemetry("track_invite_email_resend", map[string]any{interval: interval}) } diff --git a/model/auditconv.go b/model/auditconv.go index 1bcb2363bc..b3182beee7 100644 --- a/model/auditconv.go +++ b/model/auditconv.go @@ -10,7 +10,7 @@ import ( ) // AuditModelTypeConv converts key model types to something better suited for audit output. -func AuditModelTypeConv(val interface{}) (newVal interface{}, converted bool) { +func AuditModelTypeConv(val any) (newVal any, converted bool) { if val == nil { return nil, false } diff --git a/model/auditconv_test.go b/model/auditconv_test.go index 27511fdddc..35275918bb 100644 --- a/model/auditconv_test.go +++ b/model/auditconv_test.go @@ -24,13 +24,13 @@ func TestAuditModelTypeConv(t *testing.T) { userPatch := &UserPatch{} type args struct { - val interface{} + val any } tests := []struct { name string args args wantConverted bool - wantNewVal interface{} + wantNewVal any }{ {name: "nil value", args: args{val: nil}, wantConverted: false, wantNewVal: nil}, {name: "string value", args: args{val: "hello"}, wantConverted: false, wantNewVal: "hello"}, diff --git a/model/bot.go b/model/bot.go index 7b58108993..8e177cfec4 100644 --- a/model/bot.go +++ b/model/bot.go @@ -53,8 +53,8 @@ type BotGetOptions struct { type BotList []*Bot // Trace describes the minimum information required to identify a bot for the purpose of logging. -func (b *Bot) Trace() map[string]interface{} { - return map[string]interface{}{"user_id": b.UserId} +func (b *Bot) Trace() map[string]any { + return map[string]any{"user_id": b.UserId} } // Clone returns a shallow copy of the bot. @@ -192,7 +192,7 @@ func (l *BotList) Etag() string { // MakeBotNotFoundError creates the error returned when a bot does not exist, or when the user isn't allowed to query the bot. // The errors must the same in both cases to avoid leaking that a user is a bot. func MakeBotNotFoundError(userId string) *AppError { - return NewAppError("SqlBotStore.Get", "store.sql_bot.get.missing.app_error", map[string]interface{}{"user_id": userId}, "", http.StatusNotFound) + return NewAppError("SqlBotStore.Get", "store.sql_bot.get.missing.app_error", map[string]any{"user_id": userId}, "", http.StatusNotFound) } func IsBotDMChannel(channel *Channel, botUserID string) bool { diff --git a/model/bot_test.go b/model/bot_test.go index 97d894e025..0a402ff312 100644 --- a/model/bot_test.go +++ b/model/bot_test.go @@ -24,7 +24,7 @@ func TestBotTrace(t *testing.T) { DeleteAt: 4, } - require.Equal(t, map[string]interface{}{"user_id": bot.UserId}, bot.Trace()) + require.Equal(t, map[string]any{"user_id": bot.UserId}, bot.Trace()) } func TestBotClone(t *testing.T) { diff --git a/model/channel.go b/model/channel.go index eb0e220a20..a43e6d67f8 100644 --- a/model/channel.go +++ b/model/channel.go @@ -38,27 +38,27 @@ const ( ) type Channel struct { - Id string `json:"id"` - CreateAt int64 `json:"create_at"` - UpdateAt int64 `json:"update_at"` - DeleteAt int64 `json:"delete_at"` - TeamId string `json:"team_id"` - Type ChannelType `json:"type"` - DisplayName string `json:"display_name"` - Name string `json:"name"` - Header string `json:"header"` - Purpose string `json:"purpose"` - LastPostAt int64 `json:"last_post_at"` - TotalMsgCount int64 `json:"total_msg_count"` - ExtraUpdateAt int64 `json:"extra_update_at"` - CreatorId string `json:"creator_id"` - SchemeId *string `json:"scheme_id"` - Props map[string]interface{} `json:"props"` - GroupConstrained *bool `json:"group_constrained"` - Shared *bool `json:"shared"` - TotalMsgCountRoot int64 `json:"total_msg_count_root"` - PolicyID *string `json:"policy_id"` - LastRootPostAt int64 `json:"last_root_post_at"` + Id string `json:"id"` + CreateAt int64 `json:"create_at"` + UpdateAt int64 `json:"update_at"` + DeleteAt int64 `json:"delete_at"` + TeamId string `json:"team_id"` + Type ChannelType `json:"type"` + DisplayName string `json:"display_name"` + Name string `json:"name"` + Header string `json:"header"` + Purpose string `json:"purpose"` + LastPostAt int64 `json:"last_post_at"` + TotalMsgCount int64 `json:"total_msg_count"` + ExtraUpdateAt int64 `json:"extra_update_at"` + CreatorId string `json:"creator_id"` + SchemeId *string `json:"scheme_id"` + Props map[string]any `json:"props"` + GroupConstrained *bool `json:"group_constrained"` + Shared *bool `json:"shared"` + TotalMsgCountRoot int64 `json:"total_msg_count_root"` + PolicyID *string `json:"policy_id"` + LastRootPostAt int64 `json:"last_root_post_at"` } type ChannelWithTeamData struct { @@ -296,11 +296,11 @@ func (o *Channel) Patch(patch *ChannelPatch) { func (o *Channel) MakeNonNil() { if o.Props == nil { - o.Props = make(map[string]interface{}) + o.Props = make(map[string]any) } } -func (o *Channel) AddProp(key string, value interface{}) { +func (o *Channel) AddProp(key string, value any) { o.MakeNonNil() o.Props[key] = value @@ -342,7 +342,7 @@ func (t ChannelType) MarshalJSON() ([]byte, error) { return json.Marshal(string(t)) } -func (t *ChannelType) UnmarshalGraphQL(input interface{}) error { +func (t *ChannelType) UnmarshalGraphQL(input any) error { chType, ok := input.(string) if !ok { return errors.New("wrong type") diff --git a/model/channel_member.go b/model/channel_member.go index cf26d3eae5..64bdbd3d2f 100644 --- a/model/channel_member.go +++ b/model/channel_member.go @@ -143,7 +143,7 @@ func (o *ChannelMember) IsValid() *AppError { if len(o.Roles) > UserRolesMaxLength { return NewAppError("ChannelMember.IsValid", "model.channel_member.is_valid.roles_limit.app_error", - map[string]interface{}{"Limit": UserRolesMaxLength}, "", http.StatusBadRequest) + map[string]any{"Limit": UserRolesMaxLength}, "", http.StatusBadRequest) } return nil diff --git a/model/channel_sidebar.go b/model/channel_sidebar.go index d5d21112da..e37f5601e5 100644 --- a/model/channel_sidebar.go +++ b/model/channel_sidebar.go @@ -97,7 +97,7 @@ func (t SidebarCategoryType) MarshalJSON() ([]byte, error) { return json.Marshal(string(t)) } -func (t *SidebarCategoryType) UnmarshalGraphQL(input interface{}) error { +func (t *SidebarCategoryType) UnmarshalGraphQL(input any) error { chType, ok := input.(string) if !ok { return errors.New("wrong type") @@ -115,7 +115,7 @@ func (t SidebarCategorySorting) MarshalJSON() ([]byte, error) { return json.Marshal(string(t)) } -func (t *SidebarCategorySorting) UnmarshalGraphQL(input interface{}) error { +func (t *SidebarCategorySorting) UnmarshalGraphQL(input any) error { chType, ok := input.(string) if !ok { return errors.New("wrong type") diff --git a/model/client4.go b/model/client4.go index 8a4ac768b4..9020a6ec53 100644 --- a/model/client4.go +++ b/model/client4.go @@ -1372,7 +1372,7 @@ func (c *Client4) UpdateUserAuth(userId string, userAuth *UserAuth) (*UserAuth, // is true and a valid code is provided. If activate is false, then code is not // required and multi-factor authentication is disabled for the user. func (c *Client4) UpdateUserMfa(userId, code string, activate bool) (*Response, error) { - requestBody := make(map[string]interface{}) + requestBody := make(map[string]any) requestBody["activate"] = activate requestBody["code"] = code @@ -1454,7 +1454,7 @@ func (c *Client4) UpdateUserRoles(userId, roles string) (*Response, error) { // UpdateUserActive updates status of a user whether active or not. func (c *Client4) UpdateUserActive(userId string, active bool) (*Response, error) { - requestBody := make(map[string]interface{}) + requestBody := make(map[string]any) requestBody["active"] = active r, err := c.DoAPIPut(c.userRoute(userId)+"/active", StringInterfaceToJSON(requestBody)) if err != nil { @@ -3292,7 +3292,7 @@ func (c *Client4) PermanentDeleteChannel(channelId string) (*Response, error) { // MoveChannel moves the channel to the destination team. func (c *Client4) MoveChannel(channelId, teamId string, force bool) (*Channel, *Response, error) { - requestBody := map[string]interface{}{ + requestBody := map[string]any{ "team_id": teamId, "force": force, } @@ -4126,7 +4126,7 @@ func (c *Client4) SearchPostsWithParams(teamId string, params *SearchParameter) // SearchPostsWithMatches returns any posts with matching terms string, including. func (c *Client4) SearchPostsWithMatches(teamId string, terms string, isOrSearch bool) (*PostSearchResults, *Response, error) { - requestBody := map[string]interface{}{"terms": terms, "is_or_search": isOrSearch} + requestBody := map[string]any{"terms": terms, "is_or_search": isOrSearch} var route string if teamId == "" { route = c.postsRoute() + "/search" @@ -4553,7 +4553,7 @@ func (c *Client4) GetOldClientConfig(etag string) (map[string]string, *Response, // GetEnvironmentConfig will retrieve a map mirroring the server configuration where fields // are set to true if the corresponding config setting is set through an environment variable. // Settings that haven't been set through environment variables will be missing from the map. -func (c *Client4) GetEnvironmentConfig() (map[string]interface{}, *Response, error) { +func (c *Client4) GetEnvironmentConfig() (map[string]any, *Response, error) { r, err := c.DoAPIGet(c.configRoute()+"/environment", "") if err != nil { return nil, BuildResponse(r), err @@ -5140,7 +5140,7 @@ func (c *Client4) GetSamlMetadataFromIdp(samlMetadataURL string) (*SamlMetadataR // ResetSamlAuthDataToEmail resets the AuthData field of SAML users to their Email. func (c *Client4) ResetSamlAuthDataToEmail(includeDeleted bool, dryRun bool, userIDs []string) (int64, *Response, error) { - params := map[string]interface{}{ + params := map[string]any{ "include_deleted": includeDeleted, "dry_run": dryRun, "user_ids": userIDs, @@ -5262,7 +5262,7 @@ func (c *Client4) GetClusterStatus() ([]*ClusterInfo, *Response, error) { // If includeRemovedMembers is true, then group members who left or were removed from a // synced team/channel will be re-joined; otherwise, they will be excluded. func (c *Client4) SyncLdap(includeRemovedMembers bool) (*Response, error) { - reqBody, jsonErr := json.Marshal(map[string]interface{}{ + reqBody, jsonErr := json.Marshal(map[string]any{ "include_removed_members": includeRemovedMembers, }) if jsonErr != nil { @@ -5478,7 +5478,7 @@ func (c *Client4) GetGroupsByUserId(userId string) ([]*Group, *Response, error) } func (c *Client4) MigrateAuthToLdap(fromAuthService string, matchField string, force bool) (*Response, error) { - r, err := c.DoAPIPost(c.usersRoute()+"/migrate_auth/ldap", StringInterfaceToJSON(map[string]interface{}{ + r, err := c.DoAPIPost(c.usersRoute()+"/migrate_auth/ldap", StringInterfaceToJSON(map[string]any{ "from": fromAuthService, "force": force, "match_field": matchField, @@ -5491,7 +5491,7 @@ func (c *Client4) MigrateAuthToLdap(fromAuthService string, matchField string, f } func (c *Client4) MigrateAuthToSaml(fromAuthService string, usersMap map[string]string, auto bool) (*Response, error) { - r, err := c.DoAPIPost(c.usersRoute()+"/migrate_auth/saml", StringInterfaceToJSON(map[string]interface{}{ + r, err := c.DoAPIPost(c.usersRoute()+"/migrate_auth/saml", StringInterfaceToJSON(map[string]any{ "from": fromAuthService, "auto": auto, "matches": usersMap, @@ -6003,7 +6003,7 @@ func (c *Client4) GetTeamsForRetentionPolicy(policyID string, page, perPage int) // SearchTeamsForRetentionPolicy will search the teams to which the specified policy is currently applied. func (c *Client4) SearchTeamsForRetentionPolicy(policyID string, term string) ([]*Team, *Response, error) { - body, jsonErr := json.Marshal(map[string]interface{}{"term": term}) + body, jsonErr := json.Marshal(map[string]any{"term": term}) if jsonErr != nil { return nil, nil, NewAppError("SearchTeamsForRetentionPolicy", "api.marshal_error", nil, jsonErr.Error(), http.StatusInternalServerError) } @@ -6066,7 +6066,7 @@ func (c *Client4) GetChannelsForRetentionPolicy(policyID string, page, perPage i // SearchChannelsForRetentionPolicy will search the channels to which the specified policy is currently applied. func (c *Client4) SearchChannelsForRetentionPolicy(policyID string, term string) (ChannelListWithTeamData, *Response, error) { - body, jsonErr := json.Marshal(map[string]interface{}{"term": term}) + body, jsonErr := json.Marshal(map[string]any{"term": term}) if jsonErr != nil { return nil, nil, NewAppError("SearchChannelsForRetentionPolicy", "api.marshal_error", nil, jsonErr.Error(), http.StatusInternalServerError) } @@ -7232,7 +7232,7 @@ func (c *Client4) GetServerBusy() (*ServerBusyState, *Response, error) { // RegisterTermsOfServiceAction saves action performed by a user against a specific terms of service. func (c *Client4) RegisterTermsOfServiceAction(userId, termsOfServiceId string, accepted bool) (*Response, error) { url := c.userTermsOfServiceRoute(userId) - data := map[string]interface{}{"termsOfServiceId": termsOfServiceId, "accepted": accepted} + data := map[string]any{"termsOfServiceId": termsOfServiceId, "accepted": accepted} r, err := c.DoAPIPost(url, StringInterfaceToJSON(data)) if err != nil { return BuildResponse(r), err @@ -7274,7 +7274,7 @@ func (c *Client4) GetUserTermsOfService(userId, etag string) (*UserTermsOfServic // CreateTermsOfService creates new terms of service. func (c *Client4) CreateTermsOfService(text, userId string) (*TermsOfService, *Response, error) { url := c.termsOfServiceRoute() - data := map[string]interface{}{"text": text} + data := map[string]any{"text": text} r, err := c.DoAPIPost(url, StringInterfaceToJSON(data)) if err != nil { return nil, BuildResponse(r), err @@ -7573,7 +7573,7 @@ func (c *Client4) GetChannelMemberCountsByGroup(channelID string, includeTimezon // RequestTrialLicense will request a trial license and install it in the server func (c *Client4) RequestTrialLicense(users int) (*Response, error) { - b, jsonErr := json.Marshal(map[string]interface{}{"users": users, "terms_accepted": true}) + b, jsonErr := json.Marshal(map[string]any{"users": users, "terms_accepted": true}) if jsonErr != nil { return nil, NewAppError("RequestTrialLicense", "api.marshal_error", nil, jsonErr.Error(), http.StatusInternalServerError) } diff --git a/model/client4_test.go b/model/client4_test.go index 5f9bd828cf..73f6ae2c6b 100644 --- a/model/client4_test.go +++ b/model/client4_test.go @@ -29,13 +29,13 @@ func TestClient4TrimTrailingSlash(t *testing.T) { // https://github.com/mattermost/mattermost-server/v6/issues/8205 func TestClient4CreatePost(t *testing.T) { post := &Post{ - Props: map[string]interface{}{ + Props: map[string]any{ "attachments": []*SlackAttachment{ { Actions: []*PostAction{ { Integration: &PostActionIntegration{ - Context: map[string]interface{}{ + Context: map[string]any{ "foo": "bar", }, URL: "http://foo.com", @@ -58,7 +58,7 @@ func TestClient4CreatePost(t *testing.T) { Actions: []*PostAction{ { Integration: &PostActionIntegration{ - Context: map[string]interface{}{ + Context: map[string]any{ "foo": "bar", }, URL: "http://foo.com", diff --git a/model/cloud.go b/model/cloud.go index 7a1a39be15..46d7b7baad 100644 --- a/model/cloud.go +++ b/model/cloud.go @@ -175,13 +175,13 @@ type Invoice struct { // InvoiceLineItem model represents a cloud invoice lineitem tied to an invoice. type InvoiceLineItem struct { - PriceID string `json:"price_id"` - Total int64 `json:"total"` - Quantity float64 `json:"quantity"` - PricePerUnit int64 `json:"price_per_unit"` - Description string `json:"description"` - Type string `json:"type"` - Metadata map[string]interface{} `json:"metadata"` + PriceID string `json:"price_id"` + Total int64 `json:"total"` + Quantity float64 `json:"quantity"` + PricePerUnit int64 `json:"price_per_unit"` + Description string `json:"description"` + Type string `json:"type"` + Metadata map[string]any `json:"metadata"` } type CWSWebhookPayload struct { diff --git a/model/command_autocomplete.go b/model/command_autocomplete.go index a71a08c6ec..63092a59eb 100644 --- a/model/command_autocomplete.go +++ b/model/command_autocomplete.go @@ -54,7 +54,7 @@ type AutocompleteArg struct { // Required determines if argument is optional or not. Required bool // Actual data of the argument (depends on the Type) - Data interface{} + Data any } // AutocompleteTextArg describes text user can input as an argument. @@ -304,7 +304,7 @@ func (a *AutocompleteArg) Equals(arg *AutocompleteArg) bool { // UnmarshalJSON will unmarshal argument func (a *AutocompleteArg) UnmarshalJSON(b []byte) error { - var arg map[string]interface{} + var arg map[string]any if err := json.Unmarshal(b, &arg); err != nil { return errors.Wrapf(err, "Can't unmarshal argument %s", string(b)) } @@ -336,7 +336,7 @@ func (a *AutocompleteArg) UnmarshalJSON(b []byte) error { } if a.Type == AutocompleteArgTypeText { - m, ok := data.(map[string]interface{}) + m, ok := data.(map[string]any) if !ok { return errors.Errorf("Wrong Data type in the TextInput argument %s", string(b)) } @@ -350,18 +350,18 @@ func (a *AutocompleteArg) UnmarshalJSON(b []byte) error { } a.Data = &AutocompleteTextArg{Hint: hint, Pattern: pattern} } else if a.Type == AutocompleteArgTypeStaticList { - m, ok := data.(map[string]interface{}) + m, ok := data.(map[string]any) if !ok { return errors.Errorf("Wrong Data type in the StaticList argument %s", string(b)) } - list, ok := m["PossibleArguments"].([]interface{}) + list, ok := m["PossibleArguments"].([]any) if !ok { return errors.Errorf("No field PossibleArguments in the StaticList argument %s", string(b)) } possibleArguments := []AutocompleteListItem{} for i := range list { - args, ok := list[i].(map[string]interface{}) + args, ok := list[i].(map[string]any) if !ok { return errors.Errorf("Wrong AutocompleteStaticListItem type in the StaticList argument %s", string(b)) } @@ -387,7 +387,7 @@ func (a *AutocompleteArg) UnmarshalJSON(b []byte) error { } a.Data = &AutocompleteStaticListArg{PossibleArguments: possibleArguments} } else if a.Type == AutocompleteArgTypeDynamicList { - m, ok := data.(map[string]interface{}) + m, ok := data.(map[string]any) if !ok { return errors.Errorf("Wrong type in the DynamicList argument %s", string(b)) } diff --git a/model/config.go b/model/config.go index 1dc3f20693..a93b86e195 100644 --- a/model/config.go +++ b/model/config.go @@ -2736,21 +2736,21 @@ type PluginState struct { } type PluginSettings struct { - Enable *bool `access:"plugins,write_restrictable"` - EnableUploads *bool `access:"plugins,write_restrictable,cloud_restrictable"` - AllowInsecureDownloadURL *bool `access:"plugins,write_restrictable,cloud_restrictable"` - EnableHealthCheck *bool `access:"plugins,write_restrictable,cloud_restrictable"` - Directory *string `access:"plugins,write_restrictable,cloud_restrictable"` // telemetry: none - ClientDirectory *string `access:"plugins,write_restrictable,cloud_restrictable"` // telemetry: none - Plugins map[string]map[string]interface{} `access:"plugins"` // telemetry: none - PluginStates map[string]*PluginState `access:"plugins"` // telemetry: none - EnableMarketplace *bool `access:"plugins,write_restrictable,cloud_restrictable"` - EnableRemoteMarketplace *bool `access:"plugins,write_restrictable,cloud_restrictable"` - AutomaticPrepackagedPlugins *bool `access:"plugins,write_restrictable,cloud_restrictable"` - RequirePluginSignature *bool `access:"plugins,write_restrictable,cloud_restrictable"` - MarketplaceURL *string `access:"plugins,write_restrictable,cloud_restrictable"` - SignaturePublicKeyFiles []string `access:"plugins,write_restrictable,cloud_restrictable"` - ChimeraOAuthProxyURL *string `access:"plugins,write_restrictable,cloud_restrictable"` + Enable *bool `access:"plugins,write_restrictable"` + EnableUploads *bool `access:"plugins,write_restrictable,cloud_restrictable"` + AllowInsecureDownloadURL *bool `access:"plugins,write_restrictable,cloud_restrictable"` + EnableHealthCheck *bool `access:"plugins,write_restrictable,cloud_restrictable"` + Directory *string `access:"plugins,write_restrictable,cloud_restrictable"` // telemetry: none + ClientDirectory *string `access:"plugins,write_restrictable,cloud_restrictable"` // telemetry: none + Plugins map[string]map[string]any `access:"plugins"` // telemetry: none + PluginStates map[string]*PluginState `access:"plugins"` // telemetry: none + EnableMarketplace *bool `access:"plugins,write_restrictable,cloud_restrictable"` + EnableRemoteMarketplace *bool `access:"plugins,write_restrictable,cloud_restrictable"` + AutomaticPrepackagedPlugins *bool `access:"plugins,write_restrictable,cloud_restrictable"` + RequirePluginSignature *bool `access:"plugins,write_restrictable,cloud_restrictable"` + MarketplaceURL *string `access:"plugins,write_restrictable,cloud_restrictable"` + SignaturePublicKeyFiles []string `access:"plugins,write_restrictable,cloud_restrictable"` + ChimeraOAuthProxyURL *string `access:"plugins,write_restrictable,cloud_restrictable"` } func (s *PluginSettings) SetDefaults(ls LogSettings) { @@ -2779,7 +2779,7 @@ func (s *PluginSettings) SetDefaults(ls LogSettings) { } if s.Plugins == nil { - s.Plugins = make(map[string]map[string]interface{}) + s.Plugins = make(map[string]map[string]any) } if s.PluginStates == nil { @@ -3145,7 +3145,7 @@ func (o *Config) Clone() *Config { func (o *Config) ToJSONFiltered(tagType, tagValue string) ([]byte, error) { filteredConfigMap := structToMapFilteredByTag(*o, tagType, tagValue) for key, value := range filteredConfigMap { - v, ok := value.(map[string]interface{}) + v, ok := value.(map[string]any) if ok && len(v) == 0 { delete(filteredConfigMap, key) } @@ -3275,7 +3275,7 @@ func (o *Config) IsValid() *AppError { } if *o.PasswordSettings.MinimumLength < PasswordMinimumLength || *o.PasswordSettings.MinimumLength > PasswordMaximumLength { - return NewAppError("Config.IsValid", "model.config.is_valid.password_length.app_error", map[string]interface{}{"MinLength": PasswordMinimumLength, "MaxLength": PasswordMaximumLength}, "", http.StatusBadRequest) + return NewAppError("Config.IsValid", "model.config.is_valid.password_length.app_error", map[string]any{"MinLength": PasswordMinimumLength, "MaxLength": PasswordMaximumLength}, "", http.StatusBadRequest) } if err := o.RateLimitSettings.isValid(); err != nil { @@ -3342,7 +3342,7 @@ func (s *TeamSettings) isValid() *AppError { } if len(*s.SiteName) > SitenameMaxLength { - return NewAppError("Config.IsValid", "model.config.is_valid.sitename_length.app_error", map[string]interface{}{"MaxLength": SitenameMaxLength}, "", http.StatusBadRequest) + return NewAppError("Config.IsValid", "model.config.is_valid.sitename_length.app_error", map[string]any{"MaxLength": SitenameMaxLength}, "", http.StatusBadRequest) } return nil @@ -3402,7 +3402,7 @@ func (s *FileSettings) isValid() *AppError { } if *s.MaxImageDecoderConcurrency < -1 || *s.MaxImageDecoderConcurrency == 0 { - return NewAppError("Config.IsValid", "model.config.is_valid.image_decoder_concurrency.app_error", map[string]interface{}{"Value": *s.MaxImageDecoderConcurrency}, "", http.StatusBadRequest) + return NewAppError("Config.IsValid", "model.config.is_valid.image_decoder_concurrency.app_error", map[string]any{"Value": *s.MaxImageDecoderConcurrency}, "", http.StatusBadRequest) } return nil @@ -3605,7 +3605,7 @@ func (s *ServiceSettings) isValid() *AppError { if len(s.TLSOverwriteCiphers) > 0 { for _, cipher := range s.TLSOverwriteCiphers { if _, ok := ServerTLSSupportedCiphers[cipher]; !ok { - return NewAppError("Config.IsValid", "model.config.is_valid.tls_overwrite_cipher.app_error", map[string]interface{}{"name": cipher}, "", http.StatusBadRequest) + return NewAppError("Config.IsValid", "model.config.is_valid.tls_overwrite_cipher.app_error", map[string]any{"name": cipher}, "", http.StatusBadRequest) } } } @@ -3699,7 +3699,7 @@ func (s *ElasticsearchSettings) isValid() *AppError { minBatchSize := 1 if *s.BatchSize < minBatchSize { - return NewAppError("Config.IsValid", "model.config.is_valid.elastic_search.bulk_indexing_batch_size.app_error", map[string]interface{}{"BatchSize": minBatchSize}, "", http.StatusBadRequest) + return NewAppError("Config.IsValid", "model.config.is_valid.elastic_search.bulk_indexing_batch_size.app_error", map[string]any{"BatchSize": minBatchSize}, "", http.StatusBadRequest) } if *s.RequestTimeoutSeconds < 1 { @@ -3724,7 +3724,7 @@ func (bs *BleveSettings) isValid() *AppError { } minBatchSize := 1 if *bs.BatchSize < minBatchSize { - return NewAppError("Config.IsValid", "model.config.is_valid.bleve_search.bulk_indexing_batch_size.app_error", map[string]interface{}{"BatchSize": minBatchSize}, "", http.StatusBadRequest) + return NewAppError("Config.IsValid", "model.config.is_valid.bleve_search.bulk_indexing_batch_size.app_error", map[string]any{"BatchSize": minBatchSize}, "", http.StatusBadRequest) } return nil @@ -3801,7 +3801,7 @@ func (s *DisplaySettings) isValid() *AppError { return NewAppError( "Config.IsValid", "model.config.is_valid.display.custom_url_schemes.app_error", - map[string]interface{}{"Scheme": scheme}, + map[string]any{"Scheme": scheme}, "", http.StatusBadRequest, ) @@ -3911,7 +3911,7 @@ func (o *Config) Sanitize() { // structToMapFilteredByTag converts a struct into a map removing those fields that has the tag passed // as argument -func structToMapFilteredByTag(t interface{}, typeOfTag, filterTag string) map[string]interface{} { +func structToMapFilteredByTag(t any, typeOfTag, filterTag string) map[string]any { defer func() { if r := recover(); r != nil { mlog.Warn("Panicked in structToMapFilteredByTag. This should never happen.", mlog.Any("recover", r)) @@ -3925,7 +3925,7 @@ func structToMapFilteredByTag(t interface{}, typeOfTag, filterTag string) map[st return nil } - out := map[string]interface{}{} + out := map[string]any{} for i := 0; i < val.NumField(); i++ { field := val.Field(i) @@ -3936,7 +3936,7 @@ func structToMapFilteredByTag(t interface{}, typeOfTag, filterTag string) map[st continue } - var value interface{} + var value any switch field.Kind() { case reflect.Struct: diff --git a/model/config_test.go b/model/config_test.go index 8479dfb89c..2e0ca54fdb 100644 --- a/model/config_test.go +++ b/model/config_test.go @@ -1321,12 +1321,12 @@ func TestConfigFilteredByTag(t *testing.T) { cfgMap := structToMapFilteredByTag(c, ConfigAccessTagType, ConfigAccessTagCloudRestrictable) // Remove entire sections but the map is still there - clusterSettings, ok := cfgMap["SqlSettings"].(map[string]interface{}) + clusterSettings, ok := cfgMap["SqlSettings"].(map[string]any) require.True(t, ok) require.Equal(t, 0, len(clusterSettings)) // Some fields are removed if they have the filtering tag - serviceSettings, ok := cfgMap["ServiceSettings"].(map[string]interface{}) + serviceSettings, ok := cfgMap["ServiceSettings"].(map[string]any) require.True(t, ok) _, ok = serviceSettings["ListenAddress"] require.False(t, ok) diff --git a/model/group.go b/model/group.go index 428c431a67..612299ea35 100644 --- a/model/group.go +++ b/model/group.go @@ -141,11 +141,11 @@ func (group *Group) IsValidForCreate() *AppError { } if l := len(group.DisplayName); l == 0 || l > GroupDisplayNameMaxLength { - return NewAppError("Group.IsValidForCreate", "model.group.display_name.app_error", map[string]interface{}{"GroupDisplayNameMaxLength": GroupDisplayNameMaxLength}, "", http.StatusBadRequest) + return NewAppError("Group.IsValidForCreate", "model.group.display_name.app_error", map[string]any{"GroupDisplayNameMaxLength": GroupDisplayNameMaxLength}, "", http.StatusBadRequest) } if len(group.Description) > GroupDescriptionMaxLength { - return NewAppError("Group.IsValidForCreate", "model.group.description.app_error", map[string]interface{}{"GroupDescriptionMaxLength": GroupDescriptionMaxLength}, "", http.StatusBadRequest) + return NewAppError("Group.IsValidForCreate", "model.group.description.app_error", map[string]any{"GroupDescriptionMaxLength": GroupDescriptionMaxLength}, "", http.StatusBadRequest) } isValidSource := false @@ -197,11 +197,11 @@ func (group *Group) IsValidName() *AppError { if group.Name == nil { if group.AllowReference { - return NewAppError("Group.IsValidName", "model.group.name.app_error", map[string]interface{}{"GroupNameMaxLength": GroupNameMaxLength}, "", http.StatusBadRequest) + return NewAppError("Group.IsValidName", "model.group.name.app_error", map[string]any{"GroupNameMaxLength": GroupNameMaxLength}, "", http.StatusBadRequest) } } else { if l := len(*group.Name); l == 0 || l > GroupNameMaxLength { - return NewAppError("Group.IsValidName", "model.group.name.invalid_length.app_error", map[string]interface{}{"GroupNameMaxLength": GroupNameMaxLength}, "", http.StatusBadRequest) + return NewAppError("Group.IsValidName", "model.group.name.invalid_length.app_error", map[string]any{"GroupNameMaxLength": GroupNameMaxLength}, "", http.StatusBadRequest) } if !validGroupnameChars.MatchString(*group.Name) { diff --git a/model/group_syncable.go b/model/group_syncable.go index 1f1bf60f69..aebcd142c6 100644 --- a/model/group_syncable.go +++ b/model/group_syncable.go @@ -53,7 +53,7 @@ func (syncable *GroupSyncable) IsValid() *AppError { } func (syncable *GroupSyncable) UnmarshalJSON(b []byte) error { - var kvp map[string]interface{} + var kvp map[string]any err := json.Unmarshal(b, &kvp) if err != nil { return err diff --git a/model/integration_action.go b/model/integration_action.go index 4c645d0288..c45f28284c 100644 --- a/model/integration_action.go +++ b/model/integration_action.go @@ -164,7 +164,7 @@ type PostActionCookie struct { ChannelId string `json:"channel_id,omitempty"` DataSource string `json:"data_source,omitempty"` Integration *PostActionIntegration `json:"integration,omitempty"` - RetainProps map[string]interface{} `json:"retain_props,omitempty"` + RetainProps map[string]any `json:"retain_props,omitempty"` RemoveProps []string `json:"remove_props,omitempty"` } @@ -174,22 +174,22 @@ type PostActionOptions struct { } type PostActionIntegration struct { - URL string `json:"url,omitempty"` - Context map[string]interface{} `json:"context,omitempty"` + URL string `json:"url,omitempty"` + Context map[string]any `json:"context,omitempty"` } type PostActionIntegrationRequest struct { - UserId string `json:"user_id"` - UserName string `json:"user_name"` - ChannelId string `json:"channel_id"` - ChannelName string `json:"channel_name"` - TeamId string `json:"team_id"` - TeamName string `json:"team_domain"` - PostId string `json:"post_id"` - TriggerId string `json:"trigger_id"` - Type string `json:"type"` - DataSource string `json:"data_source"` - Context map[string]interface{} `json:"context,omitempty"` + UserId string `json:"user_id"` + UserName string `json:"user_name"` + ChannelId string `json:"channel_id"` + ChannelName string `json:"channel_name"` + TeamId string `json:"team_id"` + TeamName string `json:"team_domain"` + PostId string `json:"post_id"` + TriggerId string `json:"trigger_id"` + Type string `json:"type"` + DataSource string `json:"data_source"` + Context map[string]any `json:"context,omitempty"` } type PostActionIntegrationResponse struct { @@ -236,15 +236,15 @@ type OpenDialogRequest struct { } type SubmitDialogRequest struct { - Type string `json:"type"` - URL string `json:"url,omitempty"` - CallbackId string `json:"callback_id"` - State string `json:"state"` - UserId string `json:"user_id"` - ChannelId string `json:"channel_id"` - TeamId string `json:"team_id"` - Submission map[string]interface{} `json:"submission"` - Cancelled bool `json:"cancelled"` + Type string `json:"type"` + URL string `json:"url,omitempty"` + CallbackId string `json:"callback_id"` + State string `json:"state"` + UserId string `json:"user_id"` + ChannelId string `json:"channel_id"` + TeamId string `json:"team_id"` + Submission map[string]any `json:"submission"` + Cancelled bool `json:"cancelled"` } type SubmitDialogResponse struct { @@ -298,7 +298,7 @@ func DecodeAndVerifyTriggerId(triggerId string, s *ecdsa.PrivateKey) (string, st now := GetMillis() if now-timestamp > InteractiveDialogTriggerTimeoutMilliseconds { - return "", "", NewAppError("DecodeAndVerifyTriggerId", "interactive_message.decode_trigger_id.expired", map[string]interface{}{"Seconds": InteractiveDialogTriggerTimeoutMilliseconds / 1000}, "", http.StatusBadRequest) + return "", "", NewAppError("DecodeAndVerifyTriggerId", "interactive_message.decode_trigger_id.expired", map[string]any{"Seconds": InteractiveDialogTriggerTimeoutMilliseconds / 1000}, "", http.StatusBadRequest) } signature, err := base64.StdEncoding.DecodeString(split[3]) @@ -373,7 +373,7 @@ func AddPostActionCookies(o *Post, secret []byte) *Post { p := o.Clone() // retainedProps carry over their value from the old post, including no value - retainProps := map[string]interface{}{} + retainProps := map[string]any{} removeProps := []string{} for _, key := range PostActionRetainPropKeys { value, ok := p.GetProps()[key] diff --git a/model/integration_action_test.go b/model/integration_action_test.go index 1123cf44ea..d1feff68d9 100644 --- a/model/integration_action_test.go +++ b/model/integration_action_test.go @@ -86,8 +86,8 @@ func TestPostActionIntegrationEquals(t *testing.T) { t.Run("equal uncomparable types", func(t *testing.T) { pa1 := &PostAction{ Integration: &PostActionIntegration{ - Context: map[string]interface{}{ - "a": map[string]interface{}{ + Context: map[string]any{ + "a": map[string]any{ "a": 0, }, }, @@ -95,8 +95,8 @@ func TestPostActionIntegrationEquals(t *testing.T) { } pa2 := &PostAction{ Integration: &PostActionIntegration{ - Context: map[string]interface{}{ - "a": map[string]interface{}{ + Context: map[string]any{ + "a": map[string]any{ "a": 0, }, }, @@ -108,14 +108,14 @@ func TestPostActionIntegrationEquals(t *testing.T) { t.Run("equal comparable types", func(t *testing.T) { pa1 := &PostAction{ Integration: &PostActionIntegration{ - Context: map[string]interface{}{ + Context: map[string]any{ "a": "test", }, }, } pa2 := &PostAction{ Integration: &PostActionIntegration{ - Context: map[string]interface{}{ + Context: map[string]any{ "a": "test", }, }, @@ -126,8 +126,8 @@ func TestPostActionIntegrationEquals(t *testing.T) { t.Run("non-equal types", func(t *testing.T) { pa1 := &PostAction{ Integration: &PostActionIntegration{ - Context: map[string]interface{}{ - "a": map[string]interface{}{ + Context: map[string]any{ + "a": map[string]any{ "a": 0, }, }, @@ -135,7 +135,7 @@ func TestPostActionIntegrationEquals(t *testing.T) { } pa2 := &PostAction{ Integration: &PostActionIntegration{ - Context: map[string]interface{}{ + Context: map[string]any{ "a": "test", }, }, diff --git a/model/integrity.go b/model/integrity.go index 744ad07c6f..077d4ad836 100644 --- a/model/integrity.go +++ b/model/integrity.go @@ -22,25 +22,25 @@ type RelationalIntegrityCheckData struct { } type IntegrityCheckResult struct { - Data interface{} `json:"data"` - Err error `json:"err"` + Data any `json:"data"` + Err error `json:"err"` } func (r *IntegrityCheckResult) UnmarshalJSON(b []byte) error { - var data map[string]interface{} + var data map[string]any if err := json.Unmarshal(b, &data); err != nil { return err } if d, ok := data["data"]; ok && d != nil { var rdata RelationalIntegrityCheckData - m := d.(map[string]interface{}) + m := d.(map[string]any) rdata.ParentName = m["parent_name"].(string) rdata.ChildName = m["child_name"].(string) rdata.ParentIdAttr = m["parent_id_attr"].(string) rdata.ChildIdAttr = m["child_id_attr"].(string) - for _, recData := range m["records"].([]interface{}) { + for _, recData := range m["records"].([]any) { var record OrphanedRecord - m := recData.(map[string]interface{}) + m := recData.(map[string]any) if val := m["parent_id"]; val != nil { record.ParentId = NewString(val.(string)) } diff --git a/model/license.go b/model/license.go index c647faca87..5fc844e7af 100644 --- a/model/license.go +++ b/model/license.go @@ -111,8 +111,8 @@ type Features struct { FutureFeatures *bool `json:"future_features"` } -func (f *Features) ToMap() map[string]interface{} { - return map[string]interface{}{ +func (f *Features) ToMap() map[string]any { + return map[string]any{ "ldap": *f.LDAP, "ldap_groups": *f.LDAPGroups, "mfa": *f.MFA, diff --git a/model/link_metadata.go b/model/link_metadata.go index 66d1073980..8f5fda1ec9 100644 --- a/model/link_metadata.go +++ b/model/link_metadata.go @@ -38,7 +38,7 @@ type LinkMetadata struct { // - *model.PostImage if the linked content is an image // - *opengraph.OpenGraph if the linked content is an HTML document // - nil if the linked content has no metadata - Data interface{} + Data any } // truncateText ensure string is 300 chars, truncate and add ellipsis @@ -142,7 +142,7 @@ func (o *LinkMetadata) DeserializeDataToConcreteType() error { return nil } - var data interface{} + var data any var err error switch o.Type { diff --git a/model/manifest.go b/model/manifest.go index fda365f256..d017df164e 100644 --- a/model/manifest.go +++ b/model/manifest.go @@ -79,7 +79,7 @@ type PluginSetting struct { Placeholder string `json:"placeholder" yaml:"placeholder"` // The default value of the setting. - Default interface{} `json:"default" yaml:"default"` + Default any `json:"default" yaml:"default"` // For "radio" or "dropdown" settings, this is the list of pre-defined options that the user can choose // from. @@ -183,7 +183,7 @@ type Manifest struct { SettingsSchema *PluginSettingsSchema `json:"settings_schema,omitempty" yaml:"settings_schema,omitempty"` // Plugins can store any kind of data in Props to allow other plugins to use it. - Props map[string]interface{} `json:"props,omitempty" yaml:"props,omitempty"` + Props map[string]any `json:"props,omitempty" yaml:"props,omitempty"` // RequiredConfig defines any required server configuration fields for the plugin to function properly. // diff --git a/model/message_export.go b/model/message_export.go index cc8f882b39..d21d467b4f 100644 --- a/model/message_export.go +++ b/model/message_export.go @@ -40,7 +40,7 @@ type MessageExportCursor struct { // PreviewID returns the value of the post's previewed_post prop, if present, or an empty string. func (m *MessageExport) PreviewID() string { var previewID string - props := map[string]interface{}{} + props := map[string]any{} if m.PostProps != nil && json.Unmarshal([]byte(*m.PostProps), &props) == nil { if val, ok := props[PostPropsPreviewedPost]; ok { previewID = val.(string) diff --git a/model/plugin_key_value.go b/model/plugin_key_value.go index c615bcf7a8..f9433f7f1b 100644 --- a/model/plugin_key_value.go +++ b/model/plugin_key_value.go @@ -22,11 +22,11 @@ type PluginKeyValue struct { func (kv *PluginKeyValue) IsValid() *AppError { if kv.PluginId == "" || utf8.RuneCountInString(kv.PluginId) > KeyValuePluginIdMaxRunes { - return NewAppError("PluginKeyValue.IsValid", "model.plugin_key_value.is_valid.plugin_id.app_error", map[string]interface{}{"Max": KeyValueKeyMaxRunes, "Min": 0}, "key="+kv.Key, http.StatusBadRequest) + return NewAppError("PluginKeyValue.IsValid", "model.plugin_key_value.is_valid.plugin_id.app_error", map[string]any{"Max": KeyValueKeyMaxRunes, "Min": 0}, "key="+kv.Key, http.StatusBadRequest) } if kv.Key == "" || utf8.RuneCountInString(kv.Key) > KeyValueKeyMaxRunes { - return NewAppError("PluginKeyValue.IsValid", "model.plugin_key_value.is_valid.key.app_error", map[string]interface{}{"Max": KeyValueKeyMaxRunes, "Min": 0}, "key="+kv.Key, http.StatusBadRequest) + return NewAppError("PluginKeyValue.IsValid", "model.plugin_key_value.is_valid.key.app_error", map[string]any{"Max": KeyValueKeyMaxRunes, "Min": 0}, "key="+kv.Key, http.StatusBadRequest) } return nil diff --git a/model/post.go b/model/post.go index f5ae88c759..e394f68e56 100644 --- a/model/post.go +++ b/model/post.go @@ -411,7 +411,7 @@ func (o *Post) PreSave() { func (o *Post) PreCommit() { if o.GetProps() == nil { - o.SetProps(make(map[string]interface{})) + o.SetProps(make(map[string]any)) } if o.Filenames == nil { @@ -430,14 +430,14 @@ func (o *Post) PreCommit() { func (o *Post) MakeNonNil() { if o.GetProps() == nil { - o.SetProps(make(map[string]interface{})) + o.SetProps(make(map[string]any)) } } func (o *Post) DelProp(key string) { o.propsMu.Lock() defer o.propsMu.Unlock() - propsCopy := make(map[string]interface{}, len(o.Props)-1) + propsCopy := make(map[string]any, len(o.Props)-1) for k, v := range o.Props { propsCopy[k] = v } @@ -445,10 +445,10 @@ func (o *Post) DelProp(key string) { o.Props = propsCopy } -func (o *Post) AddProp(key string, value interface{}) { +func (o *Post) AddProp(key string, value any) { o.propsMu.Lock() defer o.propsMu.Unlock() - propsCopy := make(map[string]interface{}, len(o.Props)+1) + propsCopy := make(map[string]any, len(o.Props)+1) for k, v := range o.Props { propsCopy[k] = v } @@ -468,7 +468,7 @@ func (o *Post) SetProps(props StringInterface) { o.Props = props } -func (o *Post) GetProp(key string) interface{} { +func (o *Post) GetProp(key string) any { o.propsMu.RLock() defer o.propsMu.RUnlock() return o.Props[key] @@ -567,7 +567,7 @@ func (o *Post) Attachments() []*SlackAttachment { return attachments } var ret []*SlackAttachment - if attachments, ok := o.GetProp("attachments").([]interface{}); ok { + if attachments, ok := o.GetProp("attachments").([]any); ok { for _, attachment := range attachments { if enc, err := json.Marshal(attachment); err == nil { var decoded SlackAttachment @@ -648,7 +648,7 @@ func RewriteImageURLs(message string, f func(string) string) string { var ranges []markdown.Range - markdown.Inspect(message, func(blockOrInline interface{}) bool { + markdown.Inspect(message, func(blockOrInline any) bool { switch v := blockOrInline.(type) { case *markdown.ReferenceImage: ranges = append(ranges, v.ReferenceDefinition.RawDestination) diff --git a/model/post_embed.go b/model/post_embed.go index b72ae6e106..6b14a34fe4 100644 --- a/model/post_embed.go +++ b/model/post_embed.go @@ -21,5 +21,5 @@ type PostEmbed struct { URL string `json:"url,omitempty"` // Any additional data for the embedded content. Only used for OpenGraph embeds. - Data interface{} `json:"data,omitempty"` + Data any `json:"data,omitempty"` } diff --git a/model/post_test.go b/model/post_test.go index d8e6fbd100..f6935c7ca6 100644 --- a/model/post_test.go +++ b/model/post_test.go @@ -277,7 +277,7 @@ func TestPost_AttachmentsEqual(t *testing.T) { }, Integration: &PostActionIntegration{ URL: "http://localhost", - Context: map[string]interface{}{ + Context: map[string]any{ "context": "foobar", "test": 123, }, @@ -299,7 +299,7 @@ func TestPost_AttachmentsEqual(t *testing.T) { }, Integration: &PostActionIntegration{ URL: "http://localhost", - Context: map[string]interface{}{ + Context: map[string]any{ "context": "foobar", "test": 123, }, @@ -324,7 +324,7 @@ func TestPost_AttachmentsEqual(t *testing.T) { }, Integration: &PostActionIntegration{ URL: "http://localhost", - Context: map[string]interface{}{ + Context: map[string]any{ "context": "foobar", "test": "mattermost", }, @@ -346,7 +346,7 @@ func TestPost_AttachmentsEqual(t *testing.T) { }, Integration: &PostActionIntegration{ URL: "http://localhost", - Context: map[string]interface{}{ + Context: map[string]any{ "context": "foobar", "test": 123, }, @@ -848,7 +848,7 @@ func TestPostPatchDisableMentionHighlights(t *testing.T) { func TestPostAttachments(t *testing.T) { p := &Post{ - Props: map[string]interface{}{ + Props: map[string]any{ "attachments": []byte(`[{ "actions" : {null} }] @@ -857,17 +857,17 @@ func TestPostAttachments(t *testing.T) { } t.Run("empty actions", func(t *testing.T) { - p.Props["attachments"] = []interface{}{ - map[string]interface{}{"actions": []interface{}{}}, + p.Props["attachments"] = []any{ + map[string]any{"actions": []any{}}, } attachments := p.Attachments() require.Empty(t, attachments[0].Actions) }) t.Run("a couple of actions", func(t *testing.T) { - p.Props["attachments"] = []interface{}{ - map[string]interface{}{"actions": []interface{}{ - map[string]interface{}{"id": "test1"}, map[string]interface{}{"id": "test2"}}, + p.Props["attachments"] = []any{ + map[string]any{"actions": []any{ + map[string]any{"id": "test1"}, map[string]any{"id": "test2"}}, }, } @@ -878,9 +878,9 @@ func TestPostAttachments(t *testing.T) { }) t.Run("should ignore null actions", func(t *testing.T) { - p.Props["attachments"] = []interface{}{ - map[string]interface{}{"actions": []interface{}{ - map[string]interface{}{"id": "test1"}, nil, map[string]interface{}{"id": "test2"}, nil, nil}, + p.Props["attachments"] = []any{ + map[string]any{"actions": []any{ + map[string]any{"id": "test1"}, nil, map[string]any{"id": "test2"}, nil, nil}, }, } @@ -891,11 +891,11 @@ func TestPostAttachments(t *testing.T) { }) t.Run("nil fields", func(t *testing.T) { - p.Props["attachments"] = []interface{}{ - map[string]interface{}{"fields": []interface{}{ - map[string]interface{}{"value": ":emoji1:"}, + p.Props["attachments"] = []any{ + map[string]any{"fields": []any{ + map[string]any{"value": ":emoji1:"}, nil, - map[string]interface{}{"value": ":emoji2:"}, + map[string]any{"value": ":emoji2:"}, }, }, } diff --git a/model/product_notices.go b/model/product_notices.go index 94343cb4c4..d2d81cac75 100644 --- a/model/product_notices.go +++ b/model/product_notices.go @@ -40,19 +40,19 @@ func (n *ProductNotice) TeamAdminOnly() bool { } type Conditions struct { - Audience *NoticeAudience `json:"audience,omitempty"` - ClientType *NoticeClientType `json:"clientType,omitempty"` // Only show the notice on specific clients. Defaults to 'all' - DesktopVersion []string `json:"desktopVersion,omitempty"` // What desktop client versions does this notice apply to.; Format: semver ranges (https://devhints.io/semver); Example: [">=1.2.3 < ~2.4.x"]; Example: ["= 2020-03-01T00:00:00Z" - show after specified date; "< 2020-03-01T00:00:00Z" - show before the specified date; "> 2020-03-01T00:00:00Z <= 2020-04-01T00:00:00Z" - show only between the specified dates - InstanceType *NoticeInstanceType `json:"instanceType,omitempty"` - MobileVersion []string `json:"mobileVersion,omitempty"` // What mobile client versions does this notice apply to.; Format: semver ranges (https://devhints.io/semver); Example: [">=1.2.3 < ~2.4.x"]; Example: ["=1.2.3 < ~2.4.x"]; Example: ["=1.2.3 < ~2.4.x"]; Example: ["= 2020-03-01T00:00:00Z" - show after specified date; "< 2020-03-01T00:00:00Z" - show before the specified date; "> 2020-03-01T00:00:00Z <= 2020-04-01T00:00:00Z" - show only between the specified dates + InstanceType *NoticeInstanceType `json:"instanceType,omitempty"` + MobileVersion []string `json:"mobileVersion,omitempty"` // What mobile client versions does this notice apply to.; Format: semver ranges (https://devhints.io/semver); Example: [">=1.2.3 < ~2.4.x"]; Example: ["=1.2.3 < ~2.4.x"]; Example: [" UserRolesMaxLength { return NewAppError("Session.IsValid", "model.session.is_valid.roles_limit.app_error", - map[string]interface{}{"Limit": UserRolesMaxLength}, "session_id="+s.Id, http.StatusBadRequest) + map[string]any{"Limit": UserRolesMaxLength}, "session_id="+s.Id, http.StatusBadRequest) } return nil diff --git a/model/slack_attachment.go b/model/slack_attachment.go index 94ba9935f3..60c9667404 100644 --- a/model/slack_attachment.go +++ b/model/slack_attachment.go @@ -26,7 +26,7 @@ type SlackAttachment struct { ThumbURL string `json:"thumb_url"` Footer string `json:"footer"` FooterIcon string `json:"footer_icon"` - Timestamp interface{} `json:"ts"` // This is either a string or an int64 + Timestamp any `json:"ts"` // This is either a string or an int64 Actions []*PostAction `json:"actions,omitempty"` } @@ -116,7 +116,7 @@ func (s *SlackAttachment) Equals(input *SlackAttachment) bool { type SlackAttachmentField struct { Title string `json:"title"` - Value interface{} `json:"value"` + Value any `json:"value"` Short SlackCompatibleBool `json:"short"` } diff --git a/model/slack_attachment_test.go b/model/slack_attachment_test.go index 241fddac86..2ccc05689b 100644 --- a/model/slack_attachment_test.go +++ b/model/slack_attachment_test.go @@ -18,7 +18,7 @@ func TestParseSlackAttachment(t *testing.T) { expectedPost := &Post{ Type: PostTypeSlackAttachment, - Props: map[string]interface{}{ + Props: map[string]any{ "attachments": []*SlackAttachment{}, }, } @@ -35,7 +35,7 @@ func TestParseSlackAttachment(t *testing.T) { expectedPost := &Post{ Type: PostTypeSlackAttachment, - Props: map[string]interface{}{ + Props: map[string]any{ "attachments": []*SlackAttachment{}, }, } diff --git a/model/status.go b/model/status.go index 5a5e942571..e362afe844 100644 --- a/model/status.go +++ b/model/status.go @@ -56,8 +56,8 @@ func StatusListToJSON(u []*Status) ([]byte, error) { return json.Marshal(list) } -func StatusMapToInterfaceMap(statusMap map[string]*Status) map[string]interface{} { - interfaceMap := map[string]interface{}{} +func StatusMapToInterfaceMap(statusMap map[string]*Status) map[string]any { + interfaceMap := map[string]any{} for _, s := range statusMap { // Omitted statues mean offline if s.Status != StatusOffline { diff --git a/model/status_test.go b/model/status_test.go index a741962189..076f8c5662 100644 --- a/model/status_test.go +++ b/model/status_test.go @@ -30,7 +30,7 @@ func TestStatusListToJSON(t *testing.T) { jsonStatuses, err := StatusListToJSON(statuses) assert.NoError(t, err) - var dat []map[string]interface{} + var dat []map[string]any if err := json.Unmarshal(jsonStatuses, &dat); err != nil { panic(err) } diff --git a/model/team_member.go b/model/team_member.go index 45a2280379..7782080ef2 100644 --- a/model/team_member.go +++ b/model/team_member.go @@ -113,7 +113,7 @@ func (o *TeamMember) IsValid() *AppError { if len(o.Roles) > UserRolesMaxLength { return NewAppError("TeamMember.IsValid", "model.team_member.is_valid.roles_limit.app_error", - map[string]interface{}{"Limit": UserRolesMaxLength}, "", http.StatusBadRequest) + map[string]any{"Limit": UserRolesMaxLength}, "", http.StatusBadRequest) } return nil diff --git a/model/terms_of_service.go b/model/terms_of_service.go index b6e531a22a..26bc6a1d14 100644 --- a/model/terms_of_service.go +++ b/model/terms_of_service.go @@ -42,7 +42,7 @@ func InvalidTermsOfServiceError(fieldName string, termsOfServiceId string) *AppE if termsOfServiceId != "" { details = "terms_of_service_id=" + termsOfServiceId } - return NewAppError("TermsOfService.IsValid", id, map[string]interface{}{"MaxLength": PostMessageMaxRunesV2}, details, http.StatusBadRequest) + return NewAppError("TermsOfService.IsValid", id, map[string]any{"MaxLength": PostMessageMaxRunesV2}, details, http.StatusBadRequest) } func (t *TermsOfService) PreSave() { diff --git a/model/user.go b/model/user.go index 3edca4fa59..f8fdef1ea6 100644 --- a/model/user.go +++ b/model/user.go @@ -335,7 +335,7 @@ func (u *User) IsValid() *AppError { if len(u.Roles) > UserRolesMaxLength { return NewAppError("User.IsValid", "model.user.is_valid.roles_limit.app_error", - map[string]interface{}{"Limit": UserRolesMaxLength}, "user_id="+u.Id, http.StatusBadRequest) + map[string]any{"Limit": UserRolesMaxLength}, "user_id="+u.Id, http.StatusBadRequest) } return nil diff --git a/model/utils.go b/model/utils.go index 867f40c4a2..3cfa30470a 100644 --- a/model/utils.go +++ b/model/utils.go @@ -36,7 +36,7 @@ const ( BinaryParamKey = "MM_BINARY_PARAMETERS" ) -type StringInterface map[string]interface{} +type StringInterface map[string]any type StringArray []string func (sa StringArray) Remove(input string) StringArray { @@ -86,7 +86,7 @@ func (sa StringArray) Value() (driver.Value, error) { } // Scan converts database column value to StringArray -func (sa *StringArray) Scan(value interface{}) error { +func (sa *StringArray) Scan(value any) error { if value == nil { return nil } @@ -105,7 +105,7 @@ func (sa *StringArray) Scan(value interface{}) error { } // Scan converts database column value to StringMap -func (m *StringMap) Scan(value interface{}) error { +func (m *StringMap) Scan(value any) error { if value == nil { return nil } @@ -148,7 +148,7 @@ func (m StringMap) MarshalJSON() ([]byte, error) { return json.Marshal((map[string]string)(m)) } -func (m *StringMap) UnmarshalGraphQL(input interface{}) error { +func (m *StringMap) UnmarshalGraphQL(input any) error { json, ok := input.(map[string]string) if !ok { return errors.New("wrong type") @@ -158,7 +158,7 @@ func (m *StringMap) UnmarshalGraphQL(input interface{}) error { return nil } -func (si *StringInterface) Scan(value interface{}) error { +func (si *StringInterface) Scan(value any) error { if value == nil { return nil } @@ -203,7 +203,7 @@ type AppError struct { StatusCode int `json:"status_code,omitempty"` // The http status code Where string `json:"-"` // The function where it happened in the form of Struct.Func IsOAuth bool `json:"is_oauth,omitempty"` // Whether the error is OAuth specific - params map[string]interface{} + params map[string]any } func (er *AppError) Error() string { @@ -254,7 +254,7 @@ func AppErrorFromJSON(data io.Reader) *AppError { return &er } -func NewAppError(where string, id string, params map[string]interface{}, details string, status int) *AppError { +func NewAppError(where string, id string, params map[string]any, details string, status int) *AppError { ap := &AppError{} ap.Id = id ap.params = params @@ -391,10 +391,10 @@ func ArrayFromJSON(data io.Reader) []string { return objmap } -func ArrayFromInterface(data interface{}) []string { +func ArrayFromInterface(data any) []string { stringArray := []string{} - dataArray, ok := data.([]interface{}) + dataArray, ok := data.([]any) if !ok { return stringArray } @@ -408,23 +408,23 @@ func ArrayFromInterface(data interface{}) []string { return stringArray } -func StringInterfaceToJSON(objmap map[string]interface{}) string { +func StringInterfaceToJSON(objmap map[string]any) string { b, _ := json.Marshal(objmap) return string(b) } -func StringInterfaceFromJSON(data io.Reader) map[string]interface{} { +func StringInterfaceFromJSON(data io.Reader) map[string]any { decoder := json.NewDecoder(data) - var objmap map[string]interface{} + var objmap map[string]any if err := decoder.Decode(&objmap); err != nil { - return make(map[string]interface{}) + return make(map[string]any) } return objmap } // ToJSON serializes an arbitrary data type to JSON, discarding the error. -func ToJSON(v interface{}) []byte { +func ToJSON(v any) []byte { b, _ := json.Marshal(v) return b } @@ -531,7 +531,7 @@ func IsValidAlphaNumHyphenUnderscorePlus(s string) bool { return validSimpleAlphaNumHyphenUnderscorePlus.MatchString(s) } -func Etag(parts ...interface{}) string { +func Etag(parts ...any) string { etag := CurrentVersion diff --git a/model/utils_test.go b/model/utils_test.go index 35a1ccf93c..b81556d9d5 100644 --- a/model/utils_test.go +++ b/model/utils_test.go @@ -621,7 +621,7 @@ func TestNowhereNil(t *testing.T) { testCases := []struct { Description string - Value interface{} + Value any Expected bool }{ { @@ -770,7 +770,7 @@ func TestNowhereNil(t *testing.T) { // checkNowhereNil checks that the given interface value is not nil, and if a struct, that all of // its public fields are also nowhere nil -func checkNowhereNil(t *testing.T, name string, value interface{}) bool { +func checkNowhereNil(t *testing.T, name string, value any) bool { if value == nil { return false } diff --git a/model/websocket_client.go b/model/websocket_client.go index b80d477751..bd9faa9c4c 100644 --- a/model/websocket_client.go +++ b/model/websocket_client.go @@ -32,7 +32,7 @@ const ( type writeMessage struct { msgType msgType - data interface{} + data any } const avgReadMsgSizeBytes = 1024 @@ -111,7 +111,7 @@ func makeClient(dialer *websocket.Dialer, url, connectURL, authToken string, hea client.configurePingHandling() go client.writer() - client.SendMessage(WebsocketAuthenticationChallenge, map[string]interface{}{"token": authToken}) + client.SendMessage(WebsocketAuthenticationChallenge, map[string]any{"token": authToken}) return client, nil } @@ -157,7 +157,7 @@ func (wsc *WebSocketClient) ConnectWithDialer(dialer *websocket.Dialer) *AppErro wsc.EventChannel = make(chan *WebSocketEvent, 100) wsc.ResponseChannel = make(chan *WebSocketResponse, 100) - wsc.SendMessage(WebsocketAuthenticationChallenge, map[string]interface{}{"token": wsc.AuthToken}) + wsc.SendMessage(WebsocketAuthenticationChallenge, map[string]any{"token": wsc.AuthToken}) return nil } @@ -268,7 +268,7 @@ func (wsc *WebSocketClient) Listen() { }() } -func (wsc *WebSocketClient) SendMessage(action string, data map[string]interface{}) { +func (wsc *WebSocketClient) SendMessage(action string, data map[string]any) { req := &WebSocketRequest{} req.Seq = wsc.Sequence req.Action = action @@ -281,7 +281,7 @@ func (wsc *WebSocketClient) SendMessage(action string, data map[string]interface } } -func (wsc *WebSocketClient) SendBinaryMessage(action string, data map[string]interface{}) error { +func (wsc *WebSocketClient) SendBinaryMessage(action string, data map[string]any) error { req := &WebSocketRequest{} req.Seq = wsc.Sequence req.Action = action @@ -304,7 +304,7 @@ func (wsc *WebSocketClient) SendBinaryMessage(action string, data map[string]int // UserTyping will push a user_typing event out to all connected users // who are in the specified channel func (wsc *WebSocketClient) UserTyping(channelId, parentId string) { - data := map[string]interface{}{ + data := map[string]any{ "channel_id": channelId, "parent_id": parentId, } @@ -320,7 +320,7 @@ func (wsc *WebSocketClient) GetStatuses() { // GetStatusesByIds will fetch certain user statuses based on ids and return // a map of string statuses using user id as the key func (wsc *WebSocketClient) GetStatusesByIds(userIds []string) { - data := map[string]interface{}{ + data := map[string]any{ "user_ids": userIds, } wsc.SendMessage("get_statuses_by_ids", data) diff --git a/model/websocket_client_test.go b/model/websocket_client_test.go index c3a5b001ed..3fc3e8b501 100644 --- a/model/websocket_client_test.go +++ b/model/websocket_client_test.go @@ -167,7 +167,7 @@ func TestWebSocketClose(t *testing.T) { }) } -func binaryWebsocketHandler(t *testing.T, clientData map[string]interface{}, doneCh chan struct{}) http.HandlerFunc { +func binaryWebsocketHandler(t *testing.T, clientData map[string]any, doneCh chan struct{}) http.HandlerFunc { return func(w http.ResponseWriter, req *http.Request) { defer close(doneCh) upgrader := &websocket.Upgrader{ @@ -194,7 +194,7 @@ func binaryWebsocketHandler(t *testing.T, clientData map[string]interface{}, don } func TestWebSocketSendBinaryMessage(t *testing.T) { - clientData := map[string]interface{}{ + clientData := map[string]any{ "data": []byte("some data to send as binary"), } @@ -208,7 +208,7 @@ func TestWebSocketSendBinaryMessage(t *testing.T) { cli.Listen() defer cli.Close() - err = cli.SendBinaryMessage("binaryAction", map[string]interface{}{ + err = cli.SendBinaryMessage("binaryAction", map[string]any{ "unmarshable": func() {}, }) require.Error(t, err) diff --git a/model/websocket_message.go b/model/websocket_message.go index 1c7236d28b..fcb0416ed7 100644 --- a/model/websocket_message.go +++ b/model/websocket_message.go @@ -152,15 +152,15 @@ func (p *precomputedWebSocketEventJSON) copy() *precomputedWebSocketEventJSON { // webSocketEventJSON mirrors WebSocketEvent to make some of its unexported fields serializable type webSocketEventJSON struct { - Event string `json:"event"` - Data map[string]interface{} `json:"data"` - Broadcast *WebsocketBroadcast `json:"broadcast"` - Sequence int64 `json:"seq"` + Event string `json:"event"` + Data map[string]any `json:"data"` + Broadcast *WebsocketBroadcast `json:"broadcast"` + Sequence int64 `json:"seq"` } type WebSocketEvent struct { event string - data map[string]interface{} + data map[string]any broadcast *WebsocketBroadcast sequence int64 precomputedJSON *precomputedWebSocketEventJSON @@ -181,14 +181,14 @@ func (ev *WebSocketEvent) PrecomputeJSON() *WebSocketEvent { return copy } -func (ev *WebSocketEvent) Add(key string, value interface{}) { +func (ev *WebSocketEvent) Add(key string, value any) { ev.data[key] = value } func NewWebSocketEvent(event, teamId, channelId, userId string, omitUsers map[string]bool) *WebSocketEvent { return &WebSocketEvent{ event: event, - data: make(map[string]interface{}), + data: make(map[string]any), broadcast: &WebsocketBroadcast{ TeamId: teamId, ChannelId: channelId, @@ -209,9 +209,9 @@ func (ev *WebSocketEvent) Copy() *WebSocketEvent { } func (ev *WebSocketEvent) DeepCopy() *WebSocketEvent { - var dataCopy map[string]interface{} + var dataCopy map[string]any if ev.data != nil { - dataCopy = make(map[string]interface{}, len(ev.data)) + dataCopy = make(map[string]any, len(ev.data)) for k, v := range ev.data { dataCopy[k] = v } @@ -227,7 +227,7 @@ func (ev *WebSocketEvent) DeepCopy() *WebSocketEvent { return copy } -func (ev *WebSocketEvent) GetData() map[string]interface{} { +func (ev *WebSocketEvent) GetData() map[string]any { return ev.data } @@ -245,7 +245,7 @@ func (ev *WebSocketEvent) SetEvent(event string) *WebSocketEvent { return copy } -func (ev *WebSocketEvent) SetData(data map[string]interface{}) *WebSocketEvent { +func (ev *WebSocketEvent) SetData(data map[string]any) *WebSocketEvent { copy := ev.Copy() copy.data = data return copy @@ -308,7 +308,7 @@ func WebSocketEventFromJSON(data io.Reader) (*WebSocketEvent, error) { ev.event = o.Event if u, ok := o.Data["user"]; ok { // We need to convert to and from JSON again - // because the user is in the form of a map[string]interface{}. + // because the user is in the form of a map[string]any. buf, err := json.Marshal(u) if err != nil { return nil, err @@ -330,17 +330,17 @@ func WebSocketEventFromJSON(data io.Reader) (*WebSocketEvent, error) { // for a request made to the server. This is available through the ResponseChannel // channel in WebSocketClient. type WebSocketResponse struct { - Status string `json:"status"` // The status of the response. For example: OK, FAIL. - SeqReply int64 `json:"seq_reply,omitempty"` // A counter which is incremented for every response sent. - Data map[string]interface{} `json:"data,omitempty"` // The data contained in the response. - Error *AppError `json:"error,omitempty"` // A field that is set if any error has occurred. + Status string `json:"status"` // The status of the response. For example: OK, FAIL. + SeqReply int64 `json:"seq_reply,omitempty"` // A counter which is incremented for every response sent. + Data map[string]any `json:"data,omitempty"` // The data contained in the response. + Error *AppError `json:"error,omitempty"` // A field that is set if any error has occurred. } -func (m *WebSocketResponse) Add(key string, value interface{}) { +func (m *WebSocketResponse) Add(key string, value any) { m.Data[key] = value } -func NewWebSocketResponse(status string, seqReply int64, data map[string]interface{}) *WebSocketResponse { +func NewWebSocketResponse(status string, seqReply int64, data map[string]any) *WebSocketResponse { return &WebSocketResponse{Status: status, SeqReply: seqReply, Data: data} } diff --git a/model/websocket_message_test.go b/model/websocket_message_test.go index f9fe4d1d75..95cad01d95 100644 --- a/model/websocket_message_test.go +++ b/model/websocket_message_test.go @@ -56,7 +56,7 @@ func TestWebSocketEventImmutable(t *testing.T) { require.NotEqual(t, m.GetBroadcast(), new.GetBroadcast()) require.Equal(t, new.GetBroadcast(), broadcast) - data := map[string]interface{}{ + data := map[string]any{ "key": "val", "key2": "val2", } @@ -85,12 +85,12 @@ func TestWebSocketEventFromJSON(t *testing.T) { require.NotNil(t, ev, "should have parsed") require.Equal(t, ev.EventType(), "test") require.Equal(t, ev.GetSequence(), int64(45)) - require.Equal(t, ev.data, map[string]interface{}{"key": "val"}) + require.Equal(t, ev.data, map[string]any{"key": "val"}) require.Equal(t, ev.GetBroadcast(), &WebsocketBroadcast{UserId: "userid"}) } func TestWebSocketResponse(t *testing.T) { - m := NewWebSocketResponse("OK", 1, map[string]interface{}{}) + m := NewWebSocketResponse("OK", 1, map[string]any{}) e := NewWebSocketError(1, &AppError{}) m.Add("RootId", NewId()) json, err := m.ToJSON() diff --git a/model/websocket_request.go b/model/websocket_request.go index a7750bcea8..71f762e4fc 100644 --- a/model/websocket_request.go +++ b/model/websocket_request.go @@ -12,9 +12,9 @@ import ( // WebSocketRequest represents a request made to the server through a websocket. type WebSocketRequest struct { // Client-provided fields - Seq int64 `json:"seq" msgpack:"seq"` // A counter which is incremented for every request made. - Action string `json:"action" msgpack:"action"` // The action to perform for a request. For example: get_statuses, user_typing. - Data map[string]interface{} `json:"data" msgpack:"data"` // The metadata for an action. + Seq int64 `json:"seq" msgpack:"seq"` // A counter which is incremented for every request made. + Action string `json:"action" msgpack:"action"` // The action to perform for a request. For example: get_statuses, user_typing. + Data map[string]any `json:"data" msgpack:"data"` // The metadata for an action. // Server-provided fields Session Session `json:"-" msgpack:"-"` diff --git a/plugin/api.go b/plugin/api.go index a23ec2331e..6ccbc8c60f 100644 --- a/plugin/api.go +++ b/plugin/api.go @@ -23,7 +23,7 @@ type API interface { // // @tag Plugin // Minimum server version: 5.2 - LoadPluginConfiguration(dest interface{}) error + LoadPluginConfiguration(dest any) error // RegisterCommand registers a custom slash command. When the command is triggered, your plugin // can fulfill it via the ExecuteCommand hook. @@ -66,13 +66,13 @@ type API interface { // // @tag Plugin // Minimum server version: 5.6 - GetPluginConfig() map[string]interface{} + GetPluginConfig() map[string]any // SavePluginConfig sets the given config for plugin and persists the changes // // @tag Plugin // Minimum server version: 5.6 - SavePluginConfig(config map[string]interface{}) *model.AppError + SavePluginConfig(config map[string]any) *model.AppError // GetBundlePath returns the absolute path where the plugin's bundle was unpacked. // @@ -938,7 +938,7 @@ type API interface { // broadcast determines to which users to send the event. // // Minimum server version: 5.2 - PublishWebSocketEvent(event string, payload map[string]interface{}, broadcast *model.WebsocketBroadcast) + PublishWebSocketEvent(event string, payload map[string]any, broadcast *model.WebsocketBroadcast) // HasPermissionTo check if the user has the permission at system scope. // @@ -971,7 +971,7 @@ type API interface { // // @tag Logging // Minimum server version: 5.2 - LogDebug(msg string, keyValuePairs ...interface{}) + LogDebug(msg string, keyValuePairs ...any) // LogInfo writes a log message to the Mattermost server log file. // Appropriate context such as the plugin name will already be added as fields so plugins @@ -979,7 +979,7 @@ type API interface { // // @tag Logging // Minimum server version: 5.2 - LogInfo(msg string, keyValuePairs ...interface{}) + LogInfo(msg string, keyValuePairs ...any) // LogError writes a log message to the Mattermost server log file. // Appropriate context such as the plugin name will already be added as fields so plugins @@ -987,7 +987,7 @@ type API interface { // // @tag Logging // Minimum server version: 5.2 - LogError(msg string, keyValuePairs ...interface{}) + LogError(msg string, keyValuePairs ...any) // LogWarn writes a log message to the Mattermost server log file. // Appropriate context such as the plugin name will already be added as fields so plugins @@ -995,7 +995,7 @@ type API interface { // // @tag Logging // Minimum server version: 5.2 - LogWarn(msg string, keyValuePairs ...interface{}) + LogWarn(msg string, keyValuePairs ...any) // SendMail sends an email to a specific address // diff --git a/plugin/api_timer_layer_generated.go b/plugin/api_timer_layer_generated.go index d0d236802a..761bd0f21f 100644 --- a/plugin/api_timer_layer_generated.go +++ b/plugin/api_timer_layer_generated.go @@ -28,7 +28,7 @@ func (api *apiTimerLayer) recordTime(startTime timePkg.Time, name string, succes } } -func (api *apiTimerLayer) LoadPluginConfiguration(dest interface{}) error { +func (api *apiTimerLayer) LoadPluginConfiguration(dest any) error { startTime := timePkg.Now() _returnsA := api.apiImpl.LoadPluginConfiguration(dest) api.recordTime(startTime, "LoadPluginConfiguration", _returnsA == nil) @@ -77,14 +77,14 @@ func (api *apiTimerLayer) SaveConfig(config *model.Config) *model.AppError { return _returnsA } -func (api *apiTimerLayer) GetPluginConfig() map[string]interface{} { +func (api *apiTimerLayer) GetPluginConfig() map[string]any { startTime := timePkg.Now() _returnsA := api.apiImpl.GetPluginConfig() api.recordTime(startTime, "GetPluginConfig", true) return _returnsA } -func (api *apiTimerLayer) SavePluginConfig(config map[string]interface{}) *model.AppError { +func (api *apiTimerLayer) SavePluginConfig(config map[string]any) *model.AppError { startTime := timePkg.Now() _returnsA := api.apiImpl.SavePluginConfig(config) api.recordTime(startTime, "SavePluginConfig", _returnsA == nil) @@ -1007,7 +1007,7 @@ func (api *apiTimerLayer) KVList(page, perPage int) ([]string, *model.AppError) return _returnsA, _returnsB } -func (api *apiTimerLayer) PublishWebSocketEvent(event string, payload map[string]interface{}, broadcast *model.WebsocketBroadcast) { +func (api *apiTimerLayer) PublishWebSocketEvent(event string, payload map[string]any, broadcast *model.WebsocketBroadcast) { startTime := timePkg.Now() api.apiImpl.PublishWebSocketEvent(event, payload, broadcast) api.recordTime(startTime, "PublishWebSocketEvent", true) @@ -1041,25 +1041,25 @@ func (api *apiTimerLayer) RolesGrantPermission(roleNames []string, permissionId return _returnsA } -func (api *apiTimerLayer) LogDebug(msg string, keyValuePairs ...interface{}) { +func (api *apiTimerLayer) LogDebug(msg string, keyValuePairs ...any) { startTime := timePkg.Now() api.apiImpl.LogDebug(msg, keyValuePairs...) api.recordTime(startTime, "LogDebug", true) } -func (api *apiTimerLayer) LogInfo(msg string, keyValuePairs ...interface{}) { +func (api *apiTimerLayer) LogInfo(msg string, keyValuePairs ...any) { startTime := timePkg.Now() api.apiImpl.LogInfo(msg, keyValuePairs...) api.recordTime(startTime, "LogInfo", true) } -func (api *apiTimerLayer) LogError(msg string, keyValuePairs ...interface{}) { +func (api *apiTimerLayer) LogError(msg string, keyValuePairs ...any) { startTime := timePkg.Now() api.apiImpl.LogError(msg, keyValuePairs...) api.recordTime(startTime, "LogError", true) } -func (api *apiTimerLayer) LogWarn(msg string, keyValuePairs ...interface{}) { +func (api *apiTimerLayer) LogWarn(msg string, keyValuePairs ...any) { startTime := timePkg.Now() api.apiImpl.LogWarn(msg, keyValuePairs...) api.recordTime(startTime, "LogWarn", true) diff --git a/plugin/client.go b/plugin/client.go index 2ef19567e1..f681932b4c 100644 --- a/plugin/client.go +++ b/plugin/client.go @@ -15,7 +15,7 @@ const ( // Starts the serving of a Mattermost plugin over net/rpc. gRPC is not yet supported. // // Call this when your plugin is ready to start. -func ClientMain(pluginImplementation interface{}) { +func ClientMain(pluginImplementation any) { if impl, ok := pluginImplementation.(interface { SetAPI(api API) SetDriver(driver Driver) diff --git a/plugin/client_rpc.go b/plugin/client_rpc.go index e8115d70e5..aaf4f66a1d 100644 --- a/plugin/client_rpc.go +++ b/plugin/client_rpc.go @@ -43,24 +43,24 @@ type hooksRPCClient struct { } type hooksRPCServer struct { - impl interface{} + impl any muxBroker *plugin.MuxBroker apiRPCClient *apiRPCClient } // Implements hashicorp/go-plugin/plugin.Plugin interface to connect the hooks of a plugin type hooksPlugin struct { - hooks interface{} + hooks any apiImpl API driverImpl Driver log *mlog.Logger } -func (p *hooksPlugin) Server(b *plugin.MuxBroker) (interface{}, error) { +func (p *hooksPlugin) Server(b *plugin.MuxBroker) (any, error) { return &hooksRPCServer{impl: p.hooks, muxBroker: b}, nil } -func (p *hooksPlugin) Client(b *plugin.MuxBroker, client *rpc.Client) (interface{}, error) { +func (p *hooksPlugin) Client(b *plugin.MuxBroker, client *rpc.Client) (any, error) { return &hooksRPCClient{client: client, log: p.log, muxBroker: b, @@ -158,8 +158,8 @@ func decodableError(err error) error { // Registering some types used by MM for encoding/gob used by rpc func init() { gob.Register([]*model.SlackAttachment{}) - gob.Register([]interface{}{}) - gob.Register(map[string]interface{}{}) + gob.Register([]any{}) + gob.Register(map[string]any{}) gob.Register(&model.AppError{}) gob.Register(&pq.Error{}) gob.Register(&mysql.MySQLError{}) @@ -328,7 +328,7 @@ type Z_LoadPluginConfigurationArgsReturns struct { A []byte } -func (g *apiRPCClient) LoadPluginConfiguration(dest interface{}) error { +func (g *apiRPCClient) LoadPluginConfiguration(dest any) error { _args := &Z_LoadPluginConfigurationArgsArgs{} _returns := &Z_LoadPluginConfigurationArgsReturns{} if err := g.client.Call("Plugin.LoadPluginConfiguration", _args, _returns); err != nil { @@ -341,9 +341,9 @@ func (g *apiRPCClient) LoadPluginConfiguration(dest interface{}) error { } func (s *apiRPCServer) LoadPluginConfiguration(args *Z_LoadPluginConfigurationArgsArgs, returns *Z_LoadPluginConfigurationArgsReturns) error { - var config interface{} + var config any if hook, ok := s.impl.(interface { - LoadPluginConfiguration(dest interface{}) error + LoadPluginConfiguration(dest any) error }); ok { if err := hook.LoadPluginConfiguration(&config); err != nil { return err @@ -705,13 +705,13 @@ func (s *hooksRPCServer) MessageWillBeUpdated(args *Z_MessageWillBeUpdatedArgs, type Z_LogDebugArgs struct { A string - B []interface{} + B []any } type Z_LogDebugReturns struct { } -func (g *apiRPCClient) LogDebug(msg string, keyValuePairs ...interface{}) { +func (g *apiRPCClient) LogDebug(msg string, keyValuePairs ...any) { stringifiedPairs := stringifyToObjects(keyValuePairs) _args := &Z_LogDebugArgs{msg, stringifiedPairs} _returns := &Z_LogDebugReturns{} @@ -723,7 +723,7 @@ func (g *apiRPCClient) LogDebug(msg string, keyValuePairs ...interface{}) { func (s *apiRPCServer) LogDebug(args *Z_LogDebugArgs, returns *Z_LogDebugReturns) error { if hook, ok := s.impl.(interface { - LogDebug(msg string, keyValuePairs ...interface{}) + LogDebug(msg string, keyValuePairs ...any) }); ok { hook.LogDebug(args.A, args.B...) } else { @@ -734,13 +734,13 @@ func (s *apiRPCServer) LogDebug(args *Z_LogDebugArgs, returns *Z_LogDebugReturns type Z_LogInfoArgs struct { A string - B []interface{} + B []any } type Z_LogInfoReturns struct { } -func (g *apiRPCClient) LogInfo(msg string, keyValuePairs ...interface{}) { +func (g *apiRPCClient) LogInfo(msg string, keyValuePairs ...any) { stringifiedPairs := stringifyToObjects(keyValuePairs) _args := &Z_LogInfoArgs{msg, stringifiedPairs} _returns := &Z_LogInfoReturns{} @@ -752,7 +752,7 @@ func (g *apiRPCClient) LogInfo(msg string, keyValuePairs ...interface{}) { func (s *apiRPCServer) LogInfo(args *Z_LogInfoArgs, returns *Z_LogInfoReturns) error { if hook, ok := s.impl.(interface { - LogInfo(msg string, keyValuePairs ...interface{}) + LogInfo(msg string, keyValuePairs ...any) }); ok { hook.LogInfo(args.A, args.B...) } else { @@ -763,13 +763,13 @@ func (s *apiRPCServer) LogInfo(args *Z_LogInfoArgs, returns *Z_LogInfoReturns) e type Z_LogWarnArgs struct { A string - B []interface{} + B []any } type Z_LogWarnReturns struct { } -func (g *apiRPCClient) LogWarn(msg string, keyValuePairs ...interface{}) { +func (g *apiRPCClient) LogWarn(msg string, keyValuePairs ...any) { stringifiedPairs := stringifyToObjects(keyValuePairs) _args := &Z_LogWarnArgs{msg, stringifiedPairs} _returns := &Z_LogWarnReturns{} @@ -781,7 +781,7 @@ func (g *apiRPCClient) LogWarn(msg string, keyValuePairs ...interface{}) { func (s *apiRPCServer) LogWarn(args *Z_LogWarnArgs, returns *Z_LogWarnReturns) error { if hook, ok := s.impl.(interface { - LogWarn(msg string, keyValuePairs ...interface{}) + LogWarn(msg string, keyValuePairs ...any) }); ok { hook.LogWarn(args.A, args.B...) } else { @@ -792,13 +792,13 @@ func (s *apiRPCServer) LogWarn(args *Z_LogWarnArgs, returns *Z_LogWarnReturns) e type Z_LogErrorArgs struct { A string - B []interface{} + B []any } type Z_LogErrorReturns struct { } -func (g *apiRPCClient) LogError(msg string, keyValuePairs ...interface{}) { +func (g *apiRPCClient) LogError(msg string, keyValuePairs ...any) { stringifiedPairs := stringifyToObjects(keyValuePairs) _args := &Z_LogErrorArgs{msg, stringifiedPairs} _returns := &Z_LogErrorReturns{} @@ -809,7 +809,7 @@ func (g *apiRPCClient) LogError(msg string, keyValuePairs ...interface{}) { func (s *apiRPCServer) LogError(args *Z_LogErrorArgs, returns *Z_LogErrorReturns) error { if hook, ok := s.impl.(interface { - LogError(msg string, keyValuePairs ...interface{}) + LogError(msg string, keyValuePairs ...any) }); ok { hook.LogError(args.A, args.B...) } else { diff --git a/plugin/client_rpc_generated.go b/plugin/client_rpc_generated.go index 8c9b9162b1..45dc6c0143 100644 --- a/plugin/client_rpc_generated.go +++ b/plugin/client_rpc_generated.go @@ -982,10 +982,10 @@ type Z_GetPluginConfigArgs struct { } type Z_GetPluginConfigReturns struct { - A map[string]interface{} + A map[string]any } -func (g *apiRPCClient) GetPluginConfig() map[string]interface{} { +func (g *apiRPCClient) GetPluginConfig() map[string]any { _args := &Z_GetPluginConfigArgs{} _returns := &Z_GetPluginConfigReturns{} if err := g.client.Call("Plugin.GetPluginConfig", _args, _returns); err != nil { @@ -996,7 +996,7 @@ func (g *apiRPCClient) GetPluginConfig() map[string]interface{} { func (s *apiRPCServer) GetPluginConfig(args *Z_GetPluginConfigArgs, returns *Z_GetPluginConfigReturns) error { if hook, ok := s.impl.(interface { - GetPluginConfig() map[string]interface{} + GetPluginConfig() map[string]any }); ok { returns.A = hook.GetPluginConfig() } else { @@ -1006,14 +1006,14 @@ func (s *apiRPCServer) GetPluginConfig(args *Z_GetPluginConfigArgs, returns *Z_G } type Z_SavePluginConfigArgs struct { - A map[string]interface{} + A map[string]any } type Z_SavePluginConfigReturns struct { A *model.AppError } -func (g *apiRPCClient) SavePluginConfig(config map[string]interface{}) *model.AppError { +func (g *apiRPCClient) SavePluginConfig(config map[string]any) *model.AppError { _args := &Z_SavePluginConfigArgs{config} _returns := &Z_SavePluginConfigReturns{} if err := g.client.Call("Plugin.SavePluginConfig", _args, _returns); err != nil { @@ -1024,7 +1024,7 @@ func (g *apiRPCClient) SavePluginConfig(config map[string]interface{}) *model.Ap func (s *apiRPCServer) SavePluginConfig(args *Z_SavePluginConfigArgs, returns *Z_SavePluginConfigReturns) error { if hook, ok := s.impl.(interface { - SavePluginConfig(config map[string]interface{}) *model.AppError + SavePluginConfig(config map[string]any) *model.AppError }); ok { returns.A = hook.SavePluginConfig(args.A) } else { @@ -4854,14 +4854,14 @@ func (s *apiRPCServer) KVList(args *Z_KVListArgs, returns *Z_KVListReturns) erro type Z_PublishWebSocketEventArgs struct { A string - B map[string]interface{} + B map[string]any C *model.WebsocketBroadcast } type Z_PublishWebSocketEventReturns struct { } -func (g *apiRPCClient) PublishWebSocketEvent(event string, payload map[string]interface{}, broadcast *model.WebsocketBroadcast) { +func (g *apiRPCClient) PublishWebSocketEvent(event string, payload map[string]any, broadcast *model.WebsocketBroadcast) { _args := &Z_PublishWebSocketEventArgs{event, payload, broadcast} _returns := &Z_PublishWebSocketEventReturns{} if err := g.client.Call("Plugin.PublishWebSocketEvent", _args, _returns); err != nil { @@ -4872,7 +4872,7 @@ func (g *apiRPCClient) PublishWebSocketEvent(event string, payload map[string]in func (s *apiRPCServer) PublishWebSocketEvent(args *Z_PublishWebSocketEventArgs, returns *Z_PublishWebSocketEventReturns) error { if hook, ok := s.impl.(interface { - PublishWebSocketEvent(event string, payload map[string]interface{}, broadcast *model.WebsocketBroadcast) + PublishWebSocketEvent(event string, payload map[string]any, broadcast *model.WebsocketBroadcast) }); ok { hook.PublishWebSocketEvent(args.A, args.B, args.C) } else { diff --git a/plugin/environment.go b/plugin/environment.go index 51684ac34c..a24f1573ed 100644 --- a/plugin/environment.go +++ b/plugin/environment.go @@ -120,7 +120,7 @@ func (env *Environment) PrepackagedPlugins() []*PrepackagedPlugin { // The returned list should not be modified. func (env *Environment) Active() []*model.BundleInfo { activePlugins := []*model.BundleInfo{} - env.registeredPlugins.Range(func(key, value interface{}) bool { + env.registeredPlugins.Range(func(key, value any) bool { plugin := value.(registeredPlugin) if env.IsActive(plugin.BundleInfo.Manifest.Id) { activePlugins = append(activePlugins, plugin.BundleInfo) @@ -365,7 +365,7 @@ func (env *Environment) Shutdown() { env.TogglePluginHealthCheckJob(false) var wg sync.WaitGroup - env.registeredPlugins.Range(func(key, value interface{}) bool { + env.registeredPlugins.Range(func(key, value any) bool { rp := value.(registeredPlugin) if rp.supervisor == nil || !env.IsActive(rp.BundleInfo.Manifest.Id) { @@ -399,7 +399,7 @@ func (env *Environment) Shutdown() { wg.Wait() - env.registeredPlugins.Range(func(key, value interface{}) bool { + env.registeredPlugins.Range(func(key, value any) bool { env.registeredPlugins.Delete(key) return true @@ -484,7 +484,7 @@ func (env *Environment) HooksForPlugin(id string) (Hooks, error) { func (env *Environment) RunMultiPluginHook(hookRunnerFunc func(hooks Hooks) bool, hookId int) { startTime := time.Now() - env.registeredPlugins.Range(func(key, value interface{}) bool { + env.registeredPlugins.Range(func(key, value any) bool { rp := value.(registeredPlugin) if rp.supervisor == nil || !rp.supervisor.Implements(hookId) || !env.IsActive(rp.BundleInfo.Manifest.Id) { @@ -502,7 +502,7 @@ func (env *Environment) RunMultiPluginHook(hookRunnerFunc func(hooks Hooks) bool return result }) - env.registeredProducts.Range(func(key, value interface{}) bool { + env.registeredProducts.Range(func(key, value any) bool { rp := value.(*registeredProduct) if !rp.Implements(hookId) { diff --git a/plugin/example_help_test.go b/plugin/example_help_test.go index cd18e1ceb9..b192f6e302 100644 --- a/plugin/example_help_test.go +++ b/plugin/example_help_test.go @@ -109,7 +109,7 @@ func (p *HelpPlugin) MessageHasBeenPosted(c *plugin.Context, post *model.Post) { p.API.SendEphemeralPost(post.UserId, &model.Post{ ChannelId: configuration.channelID, Message: "You asked for help? Checkout https://support.mattermost.com/hc/en-us", - Props: map[string]interface{}{ + Props: map[string]any{ "sent_by_plugin": true, }, }) diff --git a/plugin/hclog_adapter.go b/plugin/hclog_adapter.go index 4142298f48..a12e8f692c 100644 --- a/plugin/hclog_adapter.go +++ b/plugin/hclog_adapter.go @@ -19,7 +19,7 @@ type hclogAdapter struct { extrasKey string } -func (h *hclogAdapter) Log(level hclog.Level, msg string, args ...interface{}) { +func (h *hclogAdapter) Log(level hclog.Level, msg string, args ...any) { switch level { case hclog.Trace: h.Trace(msg, args...) @@ -37,7 +37,7 @@ func (h *hclogAdapter) Log(level hclog.Level, msg string, args ...interface{}) { } } -func (h *hclogAdapter) Trace(msg string, args ...interface{}) { +func (h *hclogAdapter) Trace(msg string, args ...any) { extras := strings.TrimSpace(fmt.Sprint(args...)) if extras != "" { h.wrappedLogger.Debug(msg, mlog.String(h.extrasKey, extras)) @@ -46,7 +46,7 @@ func (h *hclogAdapter) Trace(msg string, args ...interface{}) { } } -func (h *hclogAdapter) Debug(msg string, args ...interface{}) { +func (h *hclogAdapter) Debug(msg string, args ...any) { extras := strings.TrimSpace(fmt.Sprint(args...)) if extras != "" { h.wrappedLogger.Debug(msg, mlog.String(h.extrasKey, extras)) @@ -55,7 +55,7 @@ func (h *hclogAdapter) Debug(msg string, args ...interface{}) { } } -func (h *hclogAdapter) Info(msg string, args ...interface{}) { +func (h *hclogAdapter) Info(msg string, args ...any) { extras := strings.TrimSpace(fmt.Sprint(args...)) if extras != "" { h.wrappedLogger.Info(msg, mlog.String(h.extrasKey, extras)) @@ -64,7 +64,7 @@ func (h *hclogAdapter) Info(msg string, args ...interface{}) { } } -func (h *hclogAdapter) Warn(msg string, args ...interface{}) { +func (h *hclogAdapter) Warn(msg string, args ...any) { extras := strings.TrimSpace(fmt.Sprint(args...)) if extras != "" { h.wrappedLogger.Warn(msg, mlog.String(h.extrasKey, extras)) @@ -73,7 +73,7 @@ func (h *hclogAdapter) Warn(msg string, args ...interface{}) { } } -func (h *hclogAdapter) Error(msg string, args ...interface{}) { +func (h *hclogAdapter) Error(msg string, args ...any) { extras := strings.TrimSpace(fmt.Sprint(args...)) if extras != "" { h.wrappedLogger.Error(msg, mlog.String(h.extrasKey, extras)) @@ -102,7 +102,7 @@ func (h *hclogAdapter) IsError() bool { return true } -func (h *hclogAdapter) With(args ...interface{}) hclog.Logger { +func (h *hclogAdapter) With(args ...any) hclog.Logger { return h } @@ -124,8 +124,8 @@ func (h *hclogAdapter) StandardWriter(opts *hclog.StandardLoggerOptions) io.Writ func (h *hclogAdapter) SetLevel(hclog.Level) {} -func (h *hclogAdapter) ImpliedArgs() []interface{} { - return []interface{}{} +func (h *hclogAdapter) ImpliedArgs() []any { + return []any{} } func (h *hclogAdapter) Name() string { diff --git a/plugin/interface_generator/main.go b/plugin/interface_generator/main.go index 6f3d6d9802..878b94501b 100644 --- a/plugin/interface_generator/main.go +++ b/plugin/interface_generator/main.go @@ -534,7 +534,7 @@ type HooksTemplateParams struct { } func generateHooksGlue(info *PluginInterfaceInfo) { - templateFunctions := map[string]interface{}{ + templateFunctions := map[string]any{ "funcStyle": func(fields *ast.FieldList) string { return FieldListToFuncList(fields, info.FileSet) }, "structStyle": func(fields *ast.FieldList) string { return FieldListToStructList(fields, info.FileSet) }, "valuesOnly": func(fields *ast.FieldList) string { return FieldListToNames(fields, false) }, @@ -586,7 +586,7 @@ func generateHooksGlue(info *PluginInterfaceInfo) { } func generateProductHooksInterfaces(info *PluginInterfaceInfo) { - templateFunctions := map[string]interface{}{ + templateFunctions := map[string]any{ "funcStyle": func(fields *ast.FieldList) string { return FieldListToFuncList(fields, info.FileSet) }, "valuesOnly": func(fields *ast.FieldList) string { return FieldListToNames(fields, false) }, } @@ -619,7 +619,7 @@ func generateProductHooksInterfaces(info *PluginInterfaceInfo) { } func generatePluginTimerLayer(info *PluginInterfaceInfo) { - templateFunctions := map[string]interface{}{ + templateFunctions := map[string]any{ "funcStyle": func(fields *ast.FieldList) string { return FieldListToFuncList(fields, info.FileSet) }, "structStyle": func(fields *ast.FieldList) string { return FieldListToStructList(fields, info.FileSet) }, "valuesOnly": func(fields *ast.FieldList) string { return FieldListToNames(fields, true) }, diff --git a/plugin/plugintest/mock/mock.go b/plugin/plugintest/mock/mock.go index 397ba42883..8e6c5cf372 100644 --- a/plugin/plugintest/mock/mock.go +++ b/plugin/plugintest/mock/mock.go @@ -24,10 +24,10 @@ func AnythingOfType(t string) AnythingOfTypeArgument { return mock.AnythingOfType(t) } -func AssertExpectationsForObjects(t TestingT, testObjects ...interface{}) bool { +func AssertExpectationsForObjects(t TestingT, testObjects ...any) bool { return mock.AssertExpectationsForObjects(t, testObjects...) } -func MatchedBy(fn interface{}) interface{} { +func MatchedBy(fn any) any { return mock.MatchedBy(fn) } diff --git a/plugin/stringifier.go b/plugin/stringifier.go index 6f4fcfbac4..4d0bb7a11b 100644 --- a/plugin/stringifier.go +++ b/plugin/stringifier.go @@ -7,7 +7,7 @@ import ( "fmt" ) -func stringify(objects []interface{}) []string { +func stringify(objects []any) []string { stringified := make([]string, len(objects)) for i, object := range objects { stringified[i] = fmt.Sprintf("%+v", object) @@ -15,17 +15,17 @@ func stringify(objects []interface{}) []string { return stringified } -func toObjects(strings []string) []interface{} { +func toObjects(strings []string) []any { if strings == nil { return nil } - objects := make([]interface{}, len(strings)) + objects := make([]any, len(strings)) for i, string := range strings { objects[i] = string } return objects } -func stringifyToObjects(objects []interface{}) []interface{} { +func stringifyToObjects(objects []any) []any { return toObjects(stringify(objects)) } diff --git a/plugin/stringifier_test.go b/plugin/stringifier_test.go index e81a3c1b14..47995a721e 100644 --- a/plugin/stringifier_test.go +++ b/plugin/stringifier_test.go @@ -16,11 +16,11 @@ func TestStringify(t *testing.T) { assert.Empty(t, strings) }) t.Run("EmptyShouldReturnEmpty", func(t *testing.T) { - strings := stringify(make([]interface{}, 0)) + strings := stringify(make([]any, 0)) assert.Empty(t, strings) }) t.Run("PrimitivesAndCompositesShouldReturnCorrectValues", func(t *testing.T) { - strings := stringify([]interface{}{ + strings := stringify([]any{ 1234, 3.14159265358979323846264338327950288419716939937510, true, @@ -46,7 +46,7 @@ func TestStringify(t *testing.T) { }, strings) }) t.Run("ErrorShouldReturnFormattedStack", func(t *testing.T) { - strings := stringify([]interface{}{ + strings := stringify([]any{ errors.New("error"), errors.WithStack(errors.New("error")), }) @@ -89,6 +89,6 @@ func TestToObjects(t *testing.T) { }) t.Run("ShouldReturnSliceOfObjects", func(t *testing.T) { objects := toObjects([]string{"foo", "bar"}) - assert.Equal(t, []interface{}{"foo", "bar"}, objects) + assert.Equal(t, []any{"foo", "bar"}, objects) }) } diff --git a/product/api.go b/product/api.go index a81f41412a..6e4a695252 100644 --- a/product/api.go +++ b/product/api.go @@ -49,7 +49,7 @@ type PermissionService interface { // The service shall be registered via app.ClusterKey key. type ClusterService interface { PublishPluginClusterEvent(productID string, ev model.PluginClusterEvent, opts model.PluginClusterEventSendOptions) error - PublishWebSocketEvent(productID string, event string, payload map[string]interface{}, broadcast *model.WebsocketBroadcast) + PublishWebSocketEvent(productID string, event string, payload map[string]any, broadcast *model.WebsocketBroadcast) } // ChannelService provides channel related API The service implementation is provided by diff --git a/services/cache/cache.go b/services/cache/cache.go index 9c0ef08e22..54323b2e97 100644 --- a/services/cache/cache.go +++ b/services/cache/cache.go @@ -20,19 +20,19 @@ type Cache interface { // Set adds the given key and value to the store without an expiry. If the key already exists, // it will overwrite the previous value. - Set(key string, value interface{}) error + Set(key string, value any) error // SetWithDefaultExpiry adds the given key and value to the store with the default expiry. If // the key already exists, it will overwrite the previous value - SetWithDefaultExpiry(key string, value interface{}) error + SetWithDefaultExpiry(key string, value any) error // SetWithExpiry adds the given key and value to the cache with the given expiry. If the key // already exists, it will overwrite the previous value - SetWithExpiry(key string, value interface{}, ttl time.Duration) error + SetWithExpiry(key string, value any, ttl time.Duration) error // Get the content stored in the cache for the given key, and decode it into the value interface. // Return ErrKeyNotFound if the key is missing from the cache - Get(key string, value interface{}) error + Get(key string, value any) error // Remove deletes the value for a given key. Remove(key string) error diff --git a/services/cache/lru.go b/services/cache/lru.go index dcb43589c3..08852f02c4 100644 --- a/services/cache/lru.go +++ b/services/cache/lru.go @@ -70,25 +70,25 @@ func (l *LRU) Purge() error { // Set adds the given key and value to the store without an expiry. If the key already exists, // it will overwrite the previous value. -func (l *LRU) Set(key string, value interface{}) error { +func (l *LRU) Set(key string, value any) error { return l.SetWithExpiry(key, value, 0) } // SetWithDefaultExpiry adds the given key and value to the store with the default expiry. If // the key already exists, it will overwrite the previous value -func (l *LRU) SetWithDefaultExpiry(key string, value interface{}) error { +func (l *LRU) SetWithDefaultExpiry(key string, value any) error { return l.SetWithExpiry(key, value, l.defaultExpiry) } // SetWithExpiry adds the given key and value to the cache with the given expiry. If the key // already exists, it will overwrite the previous value -func (l *LRU) SetWithExpiry(key string, value interface{}, ttl time.Duration) error { +func (l *LRU) SetWithExpiry(key string, value any, ttl time.Duration) error { return l.set(key, value, ttl) } // Get the content stored in the cache for the given key, and decode it into the value interface. // return ErrKeyNotFound if the key is missing from the cache -func (l *LRU) Get(key string, value interface{}) error { +func (l *LRU) Get(key string, value any) error { return l.get(key, value) } @@ -137,7 +137,7 @@ func (l *LRU) Name() string { return l.name } -func (l *LRU) set(key string, value interface{}, ttl time.Duration) error { +func (l *LRU) set(key string, value any, ttl time.Duration) error { var expires time.Time if ttl > 0 { expires = time.Now().Add(ttl) @@ -184,7 +184,7 @@ func (l *LRU) set(key string, value interface{}, ttl time.Duration) error { return nil } -func (l *LRU) get(key string, value interface{}) error { +func (l *LRU) get(key string, value any) error { val, err := l.getItem(key) if err != nil { return err diff --git a/services/cache/lru_striped.go b/services/cache/lru_striped.go index f8bae110bf..3e11933bfa 100644 --- a/services/cache/lru_striped.go +++ b/services/cache/lru_striped.go @@ -63,22 +63,22 @@ func (L LRUStriped) Purge() error { } // Set does the same as LRU.Set -func (L LRUStriped) Set(key string, value interface{}) error { +func (L LRUStriped) Set(key string, value any) error { return L.keyBucket(key).Set(key, value) } // SetWithDefaultExpiry does the same as LRU.SetWithDefaultExpiry -func (L LRUStriped) SetWithDefaultExpiry(key string, value interface{}) error { +func (L LRUStriped) SetWithDefaultExpiry(key string, value any) error { return L.keyBucket(key).SetWithDefaultExpiry(key, value) } // SetWithExpiry does the same as LRU.SetWithExpiry -func (L LRUStriped) SetWithExpiry(key string, value interface{}, ttl time.Duration) error { +func (L LRUStriped) SetWithExpiry(key string, value any, ttl time.Duration) error { return L.keyBucket(key).SetWithExpiry(key, value, ttl) } // Get does the same as LRU.Get -func (L LRUStriped) Get(key string, value interface{}) error { +func (L LRUStriped) Get(key string, value any) error { return L.keyBucket(key).Get(key, value) } diff --git a/services/cache/lru_test.go b/services/cache/lru_test.go index ed7b3d87c4..54b3cf814a 100644 --- a/services/cache/lru_test.go +++ b/services/cache/lru_test.go @@ -112,7 +112,7 @@ func TestLRUMarshalUnMarshal(t *testing.T) { InvalidateClusterEvent: "", }) - value1 := map[string]interface{}{ + value1 := map[string]any{ "key1": 1, "key2": "value2", } @@ -120,7 +120,7 @@ func TestLRUMarshalUnMarshal(t *testing.T) { require.NoError(t, err) - var value2 map[string]interface{} + var value2 map[string]any err = l.Get("test", &value2) require.NoError(t, err) assert.EqualValues(t, 1, value2["key1"]) @@ -143,7 +143,7 @@ func TestLRUMarshalUnMarshal(t *testing.T) { Message: "OriginalId", MessageSource: "MessageSource", Type: "Type", - Props: map[string]interface{}{ + Props: map[string]any{ "key": "val", }, Hashtags: "Hashtags", @@ -490,7 +490,7 @@ func BenchmarkLRU(b *testing.B) { Message: "OriginalId", MessageSource: "MessageSource", Type: "Type", - Props: map[string]interface{}{ + Props: map[string]any{ "key": "val", }, Hashtags: "Hashtags", diff --git a/services/cache/mocks/Cache.go b/services/cache/mocks/Cache.go index feca180bc6..f89104398b 100644 --- a/services/cache/mocks/Cache.go +++ b/services/cache/mocks/Cache.go @@ -14,11 +14,11 @@ type Cache struct { } // Get provides a mock function with given fields: key, value -func (_m *Cache) Get(key string, value interface{}) error { +func (_m *Cache) Get(key string, value any) error { ret := _m.Called(key, value) var r0 error - if rf, ok := ret.Get(0).(func(string, interface{}) error); ok { + if rf, ok := ret.Get(0).(func(string, any) error); ok { r0 = rf(key, value) } else { r0 = ret.Error(0) @@ -128,11 +128,11 @@ func (_m *Cache) Remove(key string) error { } // Set provides a mock function with given fields: key, value -func (_m *Cache) Set(key string, value interface{}) error { +func (_m *Cache) Set(key string, value any) error { ret := _m.Called(key, value) var r0 error - if rf, ok := ret.Get(0).(func(string, interface{}) error); ok { + if rf, ok := ret.Get(0).(func(string, any) error); ok { r0 = rf(key, value) } else { r0 = ret.Error(0) @@ -142,11 +142,11 @@ func (_m *Cache) Set(key string, value interface{}) error { } // SetWithDefaultExpiry provides a mock function with given fields: key, value -func (_m *Cache) SetWithDefaultExpiry(key string, value interface{}) error { +func (_m *Cache) SetWithDefaultExpiry(key string, value any) error { ret := _m.Called(key, value) var r0 error - if rf, ok := ret.Get(0).(func(string, interface{}) error); ok { + if rf, ok := ret.Get(0).(func(string, any) error); ok { r0 = rf(key, value) } else { r0 = ret.Error(0) @@ -156,11 +156,11 @@ func (_m *Cache) SetWithDefaultExpiry(key string, value interface{}) error { } // SetWithExpiry provides a mock function with given fields: key, value, ttl -func (_m *Cache) SetWithExpiry(key string, value interface{}, ttl time.Duration) error { +func (_m *Cache) SetWithExpiry(key string, value any, ttl time.Duration) error { ret := _m.Called(key, value, ttl) var r0 error - if rf, ok := ret.Get(0).(func(string, interface{}, time.Duration) error); ok { + if rf, ok := ret.Get(0).(func(string, any, time.Duration) error); ok { r0 = rf(key, value, ttl) } else { r0 = ret.Error(0) diff --git a/services/marketplace/client.go b/services/marketplace/client.go index 36c1b7f02a..e64f343fe8 100644 --- a/services/marketplace/client.go +++ b/services/marketplace/client.go @@ -119,7 +119,7 @@ func closeBody(r *http.Response) { } } -func (c *Client) buildURL(urlPath string, args ...interface{}) string { +func (c *Client) buildURL(urlPath string, args ...any) string { return fmt.Sprintf("%s/%s", strings.TrimRight(c.address, "/"), strings.TrimLeft(fmt.Sprintf(urlPath, args...), "/")) } diff --git a/services/remotecluster/response.go b/services/remotecluster/response.go index 04e97d7a60..18fdd21dfd 100644 --- a/services/remotecluster/response.go +++ b/services/remotecluster/response.go @@ -20,7 +20,7 @@ func (r *Response) IsSuccess() bool { } // SetPayload serializes an arbitrary struct as a RawMessage. -func (r *Response) SetPayload(v interface{}) error { +func (r *Response) SetPayload(v any) error { raw, err := json.Marshal(v) if err != nil { return err diff --git a/services/remotecluster/send.go b/services/remotecluster/send.go index 2e2abae00e..73c70a920c 100644 --- a/services/remotecluster/send.go +++ b/services/remotecluster/send.go @@ -12,7 +12,7 @@ import ( // // There are a number of send channels (`MaxConcurrentSends`) to allow for sending to multiple // remotes concurrently, while preserving message order for each remote. -func (rcs *Service) enqueueTask(ctx context.Context, remoteId string, task interface{}) error { +func (rcs *Service) enqueueTask(ctx context.Context, remoteId string, task any) error { if ctx == nil { ctx = context.Background() } diff --git a/services/remotecluster/service.go b/services/remotecluster/service.go index c96b8f7f77..e9eb8918c6 100644 --- a/services/remotecluster/service.go +++ b/services/remotecluster/service.go @@ -79,7 +79,7 @@ type ConnectionStateListener func(rc *model.RemoteCluster, online bool) type Service struct { server ServerIface httpClient *http.Client - send []chan interface{} + send []chan any // everything below guarded by `mux` mux sync.RWMutex @@ -120,9 +120,9 @@ func NewRemoteClusterService(server ServerIface) (*Service, error) { connectionStateListeners: make(map[string]ConnectionStateListener), } - service.send = make([]chan interface{}, MaxConcurrentSends) + service.send = make([]chan any, MaxConcurrentSends) for i := range service.send { - service.send[i] = make(chan interface{}, SendChanBuffer) + service.send[i] = make(chan any, SendChanBuffer) } return service, nil diff --git a/services/searchengine/bleveengine/bleve.go b/services/searchengine/bleveengine/bleve.go index 76bcb02d14..5a43a712ed 100644 --- a/services/searchengine/bleveengine/bleve.go +++ b/services/searchengine/bleveengine/bleve.go @@ -134,7 +134,7 @@ func (b *BleveEngine) createOrOpenIndex(indexName string, mapping *mapping.Index return index, nil } - index, err := bleve.NewUsing(indexPath, mapping, "scorch", "scorch", map[string]interface{}{ + index, err := bleve.NewUsing(indexPath, mapping, "scorch", "scorch", map[string]any{ "forceSegmentType": "zap", "forceSegmentVersion": 15, }) diff --git a/services/sharedchannel/mock_AppIface_test.go b/services/sharedchannel/mock_AppIface_test.go index 75b3f810b4..2e996458dc 100644 --- a/services/sharedchannel/mock_AppIface_test.go +++ b/services/sharedchannel/mock_AppIface_test.go @@ -202,11 +202,11 @@ func (_m *MockAppIface) FileReader(path string) (filestore.ReadCloseSeeker, *mod // GetOrCreateDirectChannel provides a mock function with given fields: c, userId, otherUserId, channelOptions func (_m *MockAppIface) GetOrCreateDirectChannel(c *request.Context, userId string, otherUserId string, channelOptions ...model.ChannelOption) (*model.Channel, *model.AppError) { - _va := make([]interface{}, len(channelOptions)) + _va := make([]any, len(channelOptions)) for _i := range channelOptions { _va[_i] = channelOptions[_i] } - var _ca []interface{} + var _ca []any _ca = append(_ca, c, userId, otherUserId) _ca = append(_ca, _va...) ret := _m.Called(_ca...) diff --git a/services/sharedchannel/service.go b/services/sharedchannel/service.go index a24bd18f81..8c7c4115c0 100644 --- a/services/sharedchannel/service.go +++ b/services/sharedchannel/service.go @@ -72,7 +72,7 @@ type errNotFound interface { // errInvalidInput allows checking against Store.ErrInvalidInput errors without making Store a dependency. type errInvalidInput interface { - InvalidInputInfo() (entity string, field string, value interface{}) + InvalidInputInfo() (entity string, field string, value any) } // Service provides shared channel synchronization. diff --git a/services/sharedchannel/sync_send.go b/services/sharedchannel/sync_send.go index ff12daeb85..285d764505 100644 --- a/services/sharedchannel/sync_send.go +++ b/services/sharedchannel/sync_send.go @@ -327,7 +327,7 @@ func (scs *Service) notifyRemoteOffline(posts []*model.Post, rc *model.RemoteClu T := scs.getUserTranslations(post.UserId) ephemeral := &model.Post{ ChannelId: post.ChannelId, - Message: T("sharedchannel.cannot_deliver_post", map[string]interface{}{"Remote": rc.DisplayName}), + Message: T("sharedchannel.cannot_deliver_post", map[string]any{"Remote": rc.DisplayName}), CreateAt: post.CreateAt + 1, } scs.app.SendEphemeralPost(post.UserId, ephemeral) diff --git a/services/slackimport/slackimport.go b/services/slackimport/slackimport.go index 7aa9e13ace..f290370332 100644 --- a/services/slackimport/slackimport.go +++ b/services/slackimport/slackimport.go @@ -136,42 +136,42 @@ func (si *SlackImporter) SlackImport(fileData multipart.File, fileSize int64, te for _, file := range zipreader.File { fileReader, err := file.Open() if err != nil { - log.WriteString(i18n.T("api.slackimport.slack_import.open.app_error", map[string]interface{}{"Filename": file.Name})) - return model.NewAppError("SlackImport", "api.slackimport.slack_import.open.app_error", map[string]interface{}{"Filename": file.Name}, err.Error(), http.StatusInternalServerError), log + log.WriteString(i18n.T("api.slackimport.slack_import.open.app_error", map[string]any{"Filename": file.Name})) + return model.NewAppError("SlackImport", "api.slackimport.slack_import.open.app_error", map[string]any{"Filename": file.Name}, err.Error(), http.StatusInternalServerError), log } reader := utils.NewLimitedReaderWithError(fileReader, slackImportMaxFileSize) if file.Name == "channels.json" { publicChannels, err = slackParseChannels(reader, model.ChannelTypeOpen) if errors.Is(err, utils.SizeLimitExceeded) { - log.WriteString(i18n.T("api.slackimport.slack_import.zip.file_too_large", map[string]interface{}{"Filename": file.Name})) + log.WriteString(i18n.T("api.slackimport.slack_import.zip.file_too_large", map[string]any{"Filename": file.Name})) continue } channels = append(channels, publicChannels...) } else if file.Name == "dms.json" { directChannels, err = slackParseChannels(reader, model.ChannelTypeDirect) if errors.Is(err, utils.SizeLimitExceeded) { - log.WriteString(i18n.T("api.slackimport.slack_import.zip.file_too_large", map[string]interface{}{"Filename": file.Name})) + log.WriteString(i18n.T("api.slackimport.slack_import.zip.file_too_large", map[string]any{"Filename": file.Name})) continue } channels = append(channels, directChannels...) } else if file.Name == "groups.json" { privateChannels, err = slackParseChannels(reader, model.ChannelTypePrivate) if errors.Is(err, utils.SizeLimitExceeded) { - log.WriteString(i18n.T("api.slackimport.slack_import.zip.file_too_large", map[string]interface{}{"Filename": file.Name})) + log.WriteString(i18n.T("api.slackimport.slack_import.zip.file_too_large", map[string]any{"Filename": file.Name})) continue } channels = append(channels, privateChannels...) } else if file.Name == "mpims.json" { groupChannels, err = slackParseChannels(reader, model.ChannelTypeGroup) if errors.Is(err, utils.SizeLimitExceeded) { - log.WriteString(i18n.T("api.slackimport.slack_import.zip.file_too_large", map[string]interface{}{"Filename": file.Name})) + log.WriteString(i18n.T("api.slackimport.slack_import.zip.file_too_large", map[string]any{"Filename": file.Name})) continue } channels = append(channels, groupChannels...) } else if file.Name == "users.json" { users, err = slackParseUsers(reader) if errors.Is(err, utils.SizeLimitExceeded) { - log.WriteString(i18n.T("api.slackimport.slack_import.zip.file_too_large", map[string]interface{}{"Filename": file.Name})) + log.WriteString(i18n.T("api.slackimport.slack_import.zip.file_too_large", map[string]any{"Filename": file.Name})) continue } } else { @@ -179,7 +179,7 @@ func (si *SlackImporter) SlackImport(fileData multipart.File, fileSize int64, te if len(spl) == 2 && strings.HasSuffix(spl[1], ".json") { newposts, err := slackParsePosts(reader) if errors.Is(err, utils.SizeLimitExceeded) { - log.WriteString(i18n.T("api.slackimport.slack_import.zip.file_too_large", map[string]interface{}{"Filename": file.Name})) + log.WriteString(i18n.T("api.slackimport.slack_import.zip.file_too_large", map[string]any{"Filename": file.Name})) continue } channel := spl[0] @@ -247,7 +247,7 @@ func (si *SlackImporter) slackAddUsers(teamId string, slackusers []slackUser, im email := sUser.Profile.Email if email == "" { email = sUser.Username + "@example.com" - importerLog.WriteString(i18n.T("api.slackimport.slack_add_users.missing_email_address", map[string]interface{}{"Email": email, "Username": sUser.Username})) + importerLog.WriteString(i18n.T("api.slackimport.slack_add_users.missing_email_address", map[string]any{"Email": email, "Username": sUser.Username})) mlog.Warn("Slack Import: User does not have an email address in the Slack export. Used username as a placeholder. The user should update their email address once logged in to the system.", mlog.String("user_email", email), mlog.String("user_name", sUser.Username)) } @@ -257,9 +257,9 @@ func (si *SlackImporter) slackAddUsers(teamId string, slackusers []slackUser, im if existingUser, err := si.store.User().GetByEmail(email); err == nil { addedUsers[sUser.Id] = existingUser if _, err := si.actions.JoinUserToTeam(team, addedUsers[sUser.Id], ""); err != nil { - importerLog.WriteString(i18n.T("api.slackimport.slack_add_users.merge_existing_failed", map[string]interface{}{"Email": existingUser.Email, "Username": existingUser.Username})) + importerLog.WriteString(i18n.T("api.slackimport.slack_add_users.merge_existing_failed", map[string]any{"Email": existingUser.Email, "Username": existingUser.Username})) } else { - importerLog.WriteString(i18n.T("api.slackimport.slack_add_users.merge_existing", map[string]interface{}{"Email": existingUser.Email, "Username": existingUser.Username})) + importerLog.WriteString(i18n.T("api.slackimport.slack_add_users.merge_existing", map[string]any{"Email": existingUser.Email, "Username": existingUser.Username})) } continue } @@ -275,11 +275,11 @@ func (si *SlackImporter) slackAddUsers(teamId string, slackusers []slackUser, im mUser := si.oldImportUser(team, &newUser) if mUser == nil { - importerLog.WriteString(i18n.T("api.slackimport.slack_add_users.unable_import", map[string]interface{}{"Username": sUser.Username})) + importerLog.WriteString(i18n.T("api.slackimport.slack_add_users.unable_import", map[string]any{"Username": sUser.Username})) continue } addedUsers[sUser.Id] = mUser - importerLog.WriteString(i18n.T("api.slackimport.slack_add_users.email_pwd", map[string]interface{}{"Email": newUser.Email, "Password": password})) + importerLog.WriteString(i18n.T("api.slackimport.slack_add_users.email_pwd", map[string]any{"Email": newUser.Email, "Password": password})) } return addedUsers @@ -306,11 +306,11 @@ func (si *SlackImporter) slackAddBotUser(teamId string, log *bytes.Buffer) *mode mUser := si.oldImportUser(team, &botUser) if mUser == nil { - log.WriteString(i18n.T("api.slackimport.slack_add_bot_user.unable_import", map[string]interface{}{"Username": username})) + log.WriteString(i18n.T("api.slackimport.slack_add_bot_user.unable_import", map[string]any{"Username": username})) return nil } - log.WriteString(i18n.T("api.slackimport.slack_add_bot_user.email_pwd", map[string]interface{}{"Email": botUser.Email, "Password": password})) + log.WriteString(i18n.T("api.slackimport.slack_add_bot_user.email_pwd", map[string]any{"Email": botUser.Email, "Password": password})) return mUser } @@ -553,11 +553,11 @@ func (si *SlackImporter) addSlackUsersToChannel(members []string, users map[stri for _, member := range members { user, ok := users[member] if !ok { - log.WriteString(i18n.T("api.slackimport.slack_add_channels.failed_to_add_user", map[string]interface{}{"Username": "?"})) + log.WriteString(i18n.T("api.slackimport.slack_add_channels.failed_to_add_user", map[string]any{"Username": "?"})) continue } if _, err := si.actions.AddUserToChannel(user, channel, false); err != nil { - log.WriteString(i18n.T("api.slackimport.slack_add_channels.failed_to_add_user", map[string]interface{}{"Username": user.Username})) + log.WriteString(i18n.T("api.slackimport.slack_add_channels.failed_to_add_user", map[string]any{"Username": user.Username})) } } } @@ -613,7 +613,7 @@ func (si *SlackImporter) slackAddChannels(teamId string, slackchannels []slackCh var err error if mChannel, err = si.store.Channel().GetByName(teamId, sChannel.Name, true); err == nil { // The channel already exists as an active channel. Merge with the existing one. - importerLog.WriteString(i18n.T("api.slackimport.slack_add_channels.merge", map[string]interface{}{"DisplayName": newChannel.DisplayName})) + importerLog.WriteString(i18n.T("api.slackimport.slack_add_channels.merge", map[string]any{"DisplayName": newChannel.DisplayName})) } else if _, nErr := si.store.Channel().GetDeletedByName(teamId, sChannel.Name); nErr == nil { // The channel already exists but has been deleted. Generate a random string for the handle instead. newChannel.Name = model.NewId() @@ -625,7 +625,7 @@ func (si *SlackImporter) slackAddChannels(teamId string, slackchannels []slackCh mChannel = si.oldImportChannel(&newChannel, sChannel, users) if mChannel == nil { mlog.Warn("Slack Import: Unable to import Slack channel.", mlog.String("channel_display_name", newChannel.DisplayName)) - importerLog.WriteString(i18n.T("api.slackimport.slack_add_channels.import_failed", map[string]interface{}{"DisplayName": newChannel.DisplayName})) + importerLog.WriteString(i18n.T("api.slackimport.slack_add_channels.import_failed", map[string]any{"DisplayName": newChannel.DisplayName})) continue } } diff --git a/services/telemetry/telemetry.go b/services/telemetry/telemetry.go index 92d1fe1625..a06b697f4c 100644 --- a/services/telemetry/telemetry.go +++ b/services/telemetry/telemetry.go @@ -165,12 +165,12 @@ func (ts *TelemetryService) sendDailyTelemetry(override bool) { } } -func (ts *TelemetryService) SendTelemetry(event string, properties map[string]interface{}) { +func (ts *TelemetryService) SendTelemetry(event string, properties map[string]any) { if ts.rudderClient != nil { var context *rudder.Context // if we are part of a cloud installation, add it's ID to the tracked event's context if installationId := os.Getenv("MM_CLOUD_INSTALLATION_ID"); installationId != "" { - context = &rudder.Context{Traits: map[string]interface{}{"installationId": installationId}} + context = &rudder.Context{Traits: map[string]any{"installationId": installationId}} } ts.rudderClient.Enqueue(rudder.Track{ Event: event, @@ -193,11 +193,11 @@ func isDefaultArray(setting, defaultValue []string) bool { return true } -func isDefault(setting interface{}, defaultValue interface{}) bool { +func isDefault(setting any, defaultValue any) bool { return setting == defaultValue } -func pluginSetting(pluginSettings *model.PluginSettings, plugin, key string, defaultValue interface{}) interface{} { +func pluginSetting(pluginSettings *model.PluginSettings, plugin, key string, defaultValue any) any { settings, ok := pluginSettings.Plugins[plugin] if !ok { return defaultValue @@ -331,7 +331,7 @@ func (ts *TelemetryService) trackActivity() { activeUsersMonthlyCount = r.Data.(int64) } - activity := map[string]interface{}{ + activity := map[string]any{ "registered_users": userCount, "bot_accounts": botAccountsCount, "guest_accounts": guestAccountsCount, @@ -365,7 +365,7 @@ func (ts *TelemetryService) trackActivity() { func (ts *TelemetryService) trackConfig() { cfg := ts.srv.Config() - ts.SendTelemetry(TrackConfigService, map[string]interface{}{ + ts.SendTelemetry(TrackConfigService, map[string]any{ "web_server_mode": *cfg.ServiceSettings.WebserverMode, "enable_security_fix_alert": *cfg.ServiceSettings.EnableSecurityFixAlert, "enable_insecure_outgoing_connections": *cfg.ServiceSettings.EnableInsecureOutgoingConnections, @@ -449,7 +449,7 @@ func (ts *TelemetryService) trackConfig() { "enable_custom_groups": *cfg.ServiceSettings.EnableCustomGroups, }) - ts.SendTelemetry(TrackConfigTeam, map[string]interface{}{ + ts.SendTelemetry(TrackConfigTeam, map[string]any{ "enable_user_creation": cfg.TeamSettings.EnableUserCreation, "enable_open_server": *cfg.TeamSettings.EnableOpenServer, "enable_user_deactivation": *cfg.TeamSettings.EnableUserDeactivation, @@ -472,14 +472,14 @@ func (ts *TelemetryService) trackConfig() { "experimental_default_channels": len(cfg.TeamSettings.ExperimentalDefaultChannels), }) - ts.SendTelemetry(TrackConfigClientReq, map[string]interface{}{ + ts.SendTelemetry(TrackConfigClientReq, map[string]any{ "android_latest_version": cfg.ClientRequirements.AndroidLatestVersion, "android_min_version": cfg.ClientRequirements.AndroidMinVersion, "ios_latest_version": cfg.ClientRequirements.IosLatestVersion, "ios_min_version": cfg.ClientRequirements.IosMinVersion, }) - ts.SendTelemetry(TrackConfigSQL, map[string]interface{}{ + ts.SendTelemetry(TrackConfigSQL, map[string]any{ "driver_name": *cfg.SqlSettings.DriverName, "trace": cfg.SqlSettings.Trace, "max_idle_conns": *cfg.SqlSettings.MaxIdleConns, @@ -493,7 +493,7 @@ func (ts *TelemetryService) trackConfig() { "migrations_statement_timeout_seconds": *cfg.SqlSettings.MigrationsStatementTimeoutSeconds, }) - ts.SendTelemetry(TrackConfigLog, map[string]interface{}{ + ts.SendTelemetry(TrackConfigLog, map[string]any{ "enable_console": cfg.LogSettings.EnableConsole, "console_level": cfg.LogSettings.ConsoleLevel, "console_json": *cfg.LogSettings.ConsoleJson, @@ -505,7 +505,7 @@ func (ts *TelemetryService) trackConfig() { "advanced_logging_config": *cfg.LogSettings.AdvancedLoggingConfig != "", }) - ts.SendTelemetry(TrackConfigAudit, map[string]interface{}{ + ts.SendTelemetry(TrackConfigAudit, map[string]any{ "file_enabled": *cfg.ExperimentalAuditSettings.FileEnabled, "file_max_size_mb": *cfg.ExperimentalAuditSettings.FileMaxSizeMB, "file_max_age_days": *cfg.ExperimentalAuditSettings.FileMaxAgeDays, @@ -515,7 +515,7 @@ func (ts *TelemetryService) trackConfig() { "advanced_logging_config": *cfg.ExperimentalAuditSettings.AdvancedLoggingConfig != "", }) - ts.SendTelemetry(TrackConfigNotificationLog, map[string]interface{}{ + ts.SendTelemetry(TrackConfigNotificationLog, map[string]any{ "enable_console": *cfg.NotificationLogSettings.EnableConsole, "console_level": *cfg.NotificationLogSettings.ConsoleLevel, "console_json": *cfg.NotificationLogSettings.ConsoleJson, @@ -526,7 +526,7 @@ func (ts *TelemetryService) trackConfig() { "advanced_logging_config": *cfg.NotificationLogSettings.AdvancedLoggingConfig != "", }) - ts.SendTelemetry(TrackConfigPassword, map[string]interface{}{ + ts.SendTelemetry(TrackConfigPassword, map[string]any{ "minimum_length": *cfg.PasswordSettings.MinimumLength, "lowercase": *cfg.PasswordSettings.Lowercase, "number": *cfg.PasswordSettings.Number, @@ -534,7 +534,7 @@ func (ts *TelemetryService) trackConfig() { "symbol": *cfg.PasswordSettings.Symbol, }) - ts.SendTelemetry(TrackConfigFile, map[string]interface{}{ + ts.SendTelemetry(TrackConfigFile, map[string]any{ "enable_public_links": cfg.FileSettings.EnablePublicLink, "driver_name": *cfg.FileSettings.DriverName, "isdefault_directory": isDefault(*cfg.FileSettings.Directory, model.FileSettingsDefaultDirectory), @@ -553,7 +553,7 @@ func (ts *TelemetryService) trackConfig() { "enable_mobile_download": *cfg.FileSettings.EnableMobileDownload, }) - ts.SendTelemetry(TrackConfigEmail, map[string]interface{}{ + ts.SendTelemetry(TrackConfigEmail, map[string]any{ "enable_sign_up_with_email": cfg.EmailSettings.EnableSignUpWithEmail, "enable_sign_in_with_email": *cfg.EmailSettings.EnableSignInWithEmail, "enable_sign_in_with_username": *cfg.EmailSettings.EnableSignInWithUsername, @@ -581,7 +581,7 @@ func (ts *TelemetryService) trackConfig() { "enable_inactivity_email": *cfg.EmailSettings.EnableInactivityEmail, }) - ts.SendTelemetry(TrackConfigRate, map[string]interface{}{ + ts.SendTelemetry(TrackConfigRate, map[string]any{ "enable_rate_limiter": *cfg.RateLimitSettings.Enable, "vary_by_remote_address": *cfg.RateLimitSettings.VaryByRemoteAddr, "vary_by_user": *cfg.RateLimitSettings.VaryByUser, @@ -591,19 +591,19 @@ func (ts *TelemetryService) trackConfig() { "isdefault_vary_by_header": isDefault(cfg.RateLimitSettings.VaryByHeader, ""), }) - ts.SendTelemetry(TrackConfigPrivacy, map[string]interface{}{ + ts.SendTelemetry(TrackConfigPrivacy, map[string]any{ "show_email_address": cfg.PrivacySettings.ShowEmailAddress, "show_full_name": cfg.PrivacySettings.ShowFullName, }) - ts.SendTelemetry(TrackConfigTheme, map[string]interface{}{ + ts.SendTelemetry(TrackConfigTheme, map[string]any{ "enable_theme_selection": *cfg.ThemeSettings.EnableThemeSelection, "isdefault_default_theme": isDefault(*cfg.ThemeSettings.DefaultTheme, model.TeamSettingsDefaultTeamText), "allow_custom_themes": *cfg.ThemeSettings.AllowCustomThemes, "allowed_themes": len(cfg.ThemeSettings.AllowedThemes), }) - ts.SendTelemetry(TrackConfigOAuth, map[string]interface{}{ + ts.SendTelemetry(TrackConfigOAuth, map[string]any{ "enable_gitlab": cfg.GitLabSettings.Enable, "openid_gitlab": *cfg.GitLabSettings.Enable && strings.Contains(*cfg.GitLabSettings.Scope, model.ServiceOpenid), "enable_google": cfg.GoogleSettings.Enable, @@ -613,7 +613,7 @@ func (ts *TelemetryService) trackConfig() { "enable_openid": cfg.OpenIdSettings.Enable, }) - ts.SendTelemetry(TrackConfigSupport, map[string]interface{}{ + ts.SendTelemetry(TrackConfigSupport, map[string]any{ "isdefault_terms_of_service_link": isDefault(*cfg.SupportSettings.TermsOfServiceLink, model.SupportSettingsDefaultTermsOfServiceLink), "isdefault_privacy_policy_link": isDefault(*cfg.SupportSettings.PrivacyPolicyLink, model.SupportSettingsDefaultPrivacyPolicyLink), "isdefault_about_link": isDefault(*cfg.SupportSettings.AboutLink, model.SupportSettingsDefaultAboutLink), @@ -625,7 +625,7 @@ func (ts *TelemetryService) trackConfig() { "enable_ask_community_link": *cfg.SupportSettings.EnableAskCommunityLink, }) - ts.SendTelemetry(TrackConfigLDAP, map[string]interface{}{ + ts.SendTelemetry(TrackConfigLDAP, map[string]any{ "enable": *cfg.LdapSettings.Enable, "enable_sync": *cfg.LdapSettings.EnableSync, "enable_admin_filter": *cfg.LdapSettings.EnableAdminFilter, @@ -656,18 +656,18 @@ func (ts *TelemetryService) trackConfig() { "isnotempty_private_key": !isDefault(*cfg.LdapSettings.PrivateKeyFile, ""), }) - ts.SendTelemetry(TrackConfigCompliance, map[string]interface{}{ + ts.SendTelemetry(TrackConfigCompliance, map[string]any{ "enable": *cfg.ComplianceSettings.Enable, "enable_daily": *cfg.ComplianceSettings.EnableDaily, }) - ts.SendTelemetry(TrackConfigLocalization, map[string]interface{}{ + ts.SendTelemetry(TrackConfigLocalization, map[string]any{ "default_server_locale": *cfg.LocalizationSettings.DefaultServerLocale, "default_client_locale": *cfg.LocalizationSettings.DefaultClientLocale, "available_locales": *cfg.LocalizationSettings.AvailableLocales, }) - ts.SendTelemetry(TrackConfigSAML, map[string]interface{}{ + ts.SendTelemetry(TrackConfigSAML, map[string]any{ "enable": *cfg.SamlSettings.Enable, "enable_sync_with_ldap": *cfg.SamlSettings.EnableSyncWithLdap, "enable_sync_with_ldap_include_auth": *cfg.SamlSettings.EnableSyncWithLdapIncludeAuth, @@ -696,7 +696,7 @@ func (ts *TelemetryService) trackConfig() { "isdefault_login_button_text_color": isDefault(*cfg.SamlSettings.LoginButtonTextColor, ""), }) - ts.SendTelemetry(TrackConfigCluster, map[string]interface{}{ + ts.SendTelemetry(TrackConfigCluster, map[string]any{ "enable": *cfg.ClusterSettings.Enable, "network_interface": isDefault(*cfg.ClusterSettings.NetworkInterface, ""), "bind_address": isDefault(*cfg.ClusterSettings.BindAddress, ""), @@ -707,19 +707,19 @@ func (ts *TelemetryService) trackConfig() { "read_only_config": *cfg.ClusterSettings.ReadOnlyConfig, }) - ts.SendTelemetry(TrackConfigMetrics, map[string]interface{}{ + ts.SendTelemetry(TrackConfigMetrics, map[string]any{ "enable": *cfg.MetricsSettings.Enable, "block_profile_rate": *cfg.MetricsSettings.BlockProfileRate, }) - ts.SendTelemetry(TrackConfigNativeApp, map[string]interface{}{ + ts.SendTelemetry(TrackConfigNativeApp, map[string]any{ "isdefault_app_custom_url_schemes": isDefaultArray(cfg.NativeAppSettings.AppCustomURLSchemes, model.GetDefaultAppCustomURLSchemes()), "isdefault_app_download_link": isDefault(*cfg.NativeAppSettings.AppDownloadLink, model.NativeappSettingsDefaultAppDownloadLink), "isdefault_android_app_download_link": isDefault(*cfg.NativeAppSettings.AndroidAppDownloadLink, model.NativeappSettingsDefaultAndroidAppDownloadLink), "isdefault_iosapp_download_link": isDefault(*cfg.NativeAppSettings.IosAppDownloadLink, model.NativeappSettingsDefaultIosAppDownloadLink), }) - ts.SendTelemetry(TrackConfigExperimental, map[string]interface{}{ + ts.SendTelemetry(TrackConfigExperimental, map[string]any{ "client_side_cert_enable": *cfg.ExperimentalSettings.ClientSideCertEnable, "isdefault_client_side_cert_check": isDefault(*cfg.ExperimentalSettings.ClientSideCertCheck, model.ClientSideCertCheckPrimaryAuth), "link_metadata_timeout_milliseconds": *cfg.ExperimentalSettings.LinkMetadataTimeoutMilliseconds, @@ -731,11 +731,11 @@ func (ts *TelemetryService) trackConfig() { "enable_app_bar": *cfg.ExperimentalSettings.EnableAppBar, }) - ts.SendTelemetry(TrackConfigAnalytics, map[string]interface{}{ + ts.SendTelemetry(TrackConfigAnalytics, map[string]any{ "isdefault_max_users_for_statistics": isDefault(*cfg.AnalyticsSettings.MaxUsersForStatistics, model.AnalyticsSettingsDefaultMaxUsersForStatistics), }) - ts.SendTelemetry(TrackConfigAnnouncement, map[string]interface{}{ + ts.SendTelemetry(TrackConfigAnnouncement, map[string]any{ "enable_banner": *cfg.AnnouncementSettings.EnableBanner, "isdefault_banner_color": isDefault(*cfg.AnnouncementSettings.BannerColor, model.AnnouncementSettingsDefaultBannerColor), "isdefault_banner_text_color": isDefault(*cfg.AnnouncementSettings.BannerTextColor, model.AnnouncementSettingsDefaultBannerTextColor), @@ -744,7 +744,7 @@ func (ts *TelemetryService) trackConfig() { "user_notices_enabled": *cfg.AnnouncementSettings.UserNoticesEnabled, }) - ts.SendTelemetry(TrackConfigElasticsearch, map[string]interface{}{ + ts.SendTelemetry(TrackConfigElasticsearch, map[string]any{ "isdefault_connection_url": isDefault(*cfg.ElasticsearchSettings.ConnectionURL, model.ElasticsearchSettingsDefaultConnectionURL), "isdefault_username": isDefault(*cfg.ElasticsearchSettings.Username, model.ElasticsearchSettingsDefaultUsername), "isdefault_password": isDefault(*cfg.ElasticsearchSettings.Password, model.ElasticsearchSettingsDefaultPassword), @@ -768,7 +768,7 @@ func (ts *TelemetryService) trackConfig() { ts.trackPluginConfig(cfg, model.PluginSettingsDefaultMarketplaceURL) - ts.SendTelemetry(TrackConfigDataRetention, map[string]interface{}{ + ts.SendTelemetry(TrackConfigDataRetention, map[string]any{ "enable_message_deletion": *cfg.DataRetentionSettings.EnableMessageDeletion, "enable_file_deletion": *cfg.DataRetentionSettings.EnableFileDeletion, "enable_boards_deletion": *cfg.DataRetentionSettings.EnableBoardsDeletion, @@ -781,7 +781,7 @@ func (ts *TelemetryService) trackConfig() { "cleanup_config_threshold_days": *cfg.JobSettings.CleanupConfigThresholdDays, }) - ts.SendTelemetry(TrackConfigMessageExport, map[string]interface{}{ + ts.SendTelemetry(TrackConfigMessageExport, map[string]any{ "enable_message_export": *cfg.MessageExportSettings.EnableExport, "export_format": *cfg.MessageExportSettings.ExportFormat, "daily_run_time": *cfg.MessageExportSettings.DailyRunTime, @@ -795,39 +795,39 @@ func (ts *TelemetryService) trackConfig() { "download_export_results": *cfg.MessageExportSettings.DownloadExportResults, }) - ts.SendTelemetry(TrackConfigDisplay, map[string]interface{}{ + ts.SendTelemetry(TrackConfigDisplay, map[string]any{ "experimental_timezone": *cfg.DisplaySettings.ExperimentalTimezone, "isdefault_custom_url_schemes": len(cfg.DisplaySettings.CustomURLSchemes) != 0, }) - ts.SendTelemetry(TrackConfigGuestAccounts, map[string]interface{}{ + ts.SendTelemetry(TrackConfigGuestAccounts, map[string]any{ "enable": *cfg.GuestAccountsSettings.Enable, "allow_email_accounts": *cfg.GuestAccountsSettings.AllowEmailAccounts, "enforce_multifactor_authentication": *cfg.GuestAccountsSettings.EnforceMultifactorAuthentication, "isdefault_restrict_creation_to_domains": isDefault(*cfg.GuestAccountsSettings.RestrictCreationToDomains, ""), }) - ts.SendTelemetry(TrackConfigImageProxy, map[string]interface{}{ + ts.SendTelemetry(TrackConfigImageProxy, map[string]any{ "enable": *cfg.ImageProxySettings.Enable, "image_proxy_type": *cfg.ImageProxySettings.ImageProxyType, "isdefault_remote_image_proxy_url": isDefault(*cfg.ImageProxySettings.RemoteImageProxyURL, ""), "isdefault_remote_image_proxy_options": isDefault(*cfg.ImageProxySettings.RemoteImageProxyOptions, ""), }) - ts.SendTelemetry(TrackConfigBleve, map[string]interface{}{ + ts.SendTelemetry(TrackConfigBleve, map[string]any{ "enable_indexing": *cfg.BleveSettings.EnableIndexing, "enable_searching": *cfg.BleveSettings.EnableSearching, "enable_autocomplete": *cfg.BleveSettings.EnableAutocomplete, "bulk_indexing_batch_size": *cfg.BleveSettings.BatchSize, }) - ts.SendTelemetry(TrackConfigExport, map[string]interface{}{ + ts.SendTelemetry(TrackConfigExport, map[string]any{ "retention_days": *cfg.ExportSettings.RetentionDays, }) - // Convert feature flags to map[string]interface{} for sending + // Convert feature flags to map[string]any for sending flags := cfg.FeatureFlags.ToMap() - interfaceFlags := make(map[string]interface{}) + interfaceFlags := make(map[string]any) for k, v := range flags { interfaceFlags[k] = v } @@ -836,7 +836,7 @@ func (ts *TelemetryService) trackConfig() { func (ts *TelemetryService) trackLicense() { if license := ts.srv.License(); license != nil { - data := map[string]interface{}{ + data := map[string]any{ "customer_id": license.Customer.Id, "license_id": license.Id, "issued": license.IssuedAt, @@ -911,7 +911,7 @@ func (ts *TelemetryService) trackPlugins() { totalDisabledCount = -1 // -1 to indicate disabled or error } - ts.SendTelemetry(TrackPlugins, map[string]interface{}{ + ts.SendTelemetry(TrackPlugins, map[string]any{ "enabled_plugins": totalEnabledCount, "enabled_webapp_plugins": webappEnabledCount, "enabled_backend_plugins": backendEnabledCount, @@ -930,7 +930,7 @@ func (ts *TelemetryService) trackPlugins() { } func (ts *TelemetryService) trackServer() { - data := map[string]interface{}{ + data := map[string]any{ "edition": model.BuildEnterpriseReady, "version": model.CurrentVersion, "database_type": *ts.srv.Config().SqlSettings.DriverName, @@ -960,7 +960,7 @@ func (ts *TelemetryService) trackPermissions() { phase2Complete = true } - ts.SendTelemetry(TrackPermissionsGeneral, map[string]interface{}{ + ts.SendTelemetry(TrackPermissionsGeneral, map[string]any{ "phase_1_migration_complete": phase1Complete, "phase_2_migration_complete": phase2Complete, }) @@ -1038,7 +1038,7 @@ func (ts *TelemetryService) trackPermissions() { systemReadOnlyAdminCount = 0 } - ts.SendTelemetry(TrackPermissionsSystemScheme, map[string]interface{}{ + ts.SendTelemetry(TrackPermissionsSystemScheme, map[string]any{ "system_admin_permissions": systemAdminPermissions, "system_user_permissions": systemUserPermissions, "system_manager_permissions": systemManagerPermissions, @@ -1092,7 +1092,7 @@ func (ts *TelemetryService) trackPermissions() { count, _ := ts.dbStore.Team().AnalyticsGetTeamCountForScheme(scheme.Id) - ts.SendTelemetry(TrackPermissionsTeamSchemes, map[string]interface{}{ + ts.SendTelemetry(TrackPermissionsTeamSchemes, map[string]any{ "scheme_id": scheme.Id, "team_admin_permissions": teamAdminPermissions, "team_user_permissions": teamUserPermissions, @@ -1107,7 +1107,7 @@ func (ts *TelemetryService) trackPermissions() { } func (ts *TelemetryService) trackElasticsearch() { - data := map[string]interface{}{} + data := map[string]any{} for _, engine := range ts.searchEngine.GetActiveEngines() { if engine.GetVersion() != 0 && engine.GetName() == "elasticsearch" { @@ -1179,7 +1179,7 @@ func (ts *TelemetryService) trackGroups() { mlog.Debug("Could not get group_count_with_allow_reference", mlog.Err(err)) } - ts.SendTelemetry(TrackGroups, map[string]interface{}{ + ts.SendTelemetry(TrackGroups, map[string]any{ "group_count": groupCount, "ldap_group_count": ldapGroupCount, "custom_group_count": customGroupCount, @@ -1238,7 +1238,7 @@ func (ts *TelemetryService) trackChannelModeration() { mlog.Debug("Could not get use_channel_mentions_guest_disabled_count", mlog.Err(err)) } - ts.SendTelemetry(TrackChannelModeration, map[string]interface{}{ + ts.SendTelemetry(TrackChannelModeration, map[string]any{ "channel_scheme_count": channelSchemeCount, "create_post_user_disabled_count": createPostUser, @@ -1322,7 +1322,7 @@ func (ts *TelemetryService) trackWarnMetrics() { for key, value := range systemDataList { if strings.HasPrefix(key, model.WarnMetricStatusStorePrefix) { if _, ok := model.WarnMetricsTable[key]; ok { - ts.SendTelemetry(TrackWarnMetrics, map[string]interface{}{ + ts.SendTelemetry(TrackWarnMetrics, map[string]any{ key: value != "false", }) } @@ -1331,7 +1331,7 @@ func (ts *TelemetryService) trackWarnMetrics() { } func (ts *TelemetryService) trackPluginConfig(cfg *model.Config, marketplaceURL string) { - pluginConfigData := map[string]interface{}{ + pluginConfigData := map[string]any{ "enable_nps_survey": pluginSetting(&cfg.PluginSettings, model.PluginIdNPS, "enablesurvey", true), "enable": *cfg.PluginSettings.Enable, "enable_uploads": *cfg.PluginSettings.EnableUploads, diff --git a/services/telemetry/telemetry_test.go b/services/telemetry/telemetry_test.go index 3b6fc9d289..2367b8d20a 100644 --- a/services/telemetry/telemetry_test.go +++ b/services/telemetry/telemetry_test.go @@ -44,7 +44,7 @@ type testTelemetryPayload struct { UserId string Event string Timestamp time.Time - Properties map[string]interface{} + Properties map[string]any } Context struct { Library struct { @@ -59,10 +59,10 @@ type testBatch struct { UserId string Event string Timestamp time.Time - Properties map[string]interface{} + Properties map[string]any } -func assertPayload(t *testing.T, actual testTelemetryPayload, event string, properties map[string]interface{}) { +func assertPayload(t *testing.T, actual testTelemetryPayload, event string, properties map[string]any) { t.Helper() assert.NotEmpty(t, actual.MessageId) assert.False(t, actual.SentAt.IsZero()) @@ -352,7 +352,7 @@ func TestEnsureTelemetryID(t *testing.T) { func TestPluginSetting(t *testing.T) { settings := &model.PluginSettings{ - Plugins: map[string]map[string]interface{}{ + Plugins: map[string]map[string]any{ "test": { "foo": "bar", }, @@ -436,12 +436,12 @@ func TestRudderTelemetry(t *testing.T) { t.Run("Send", func(t *testing.T) { testValue := "test-send-value-6789" - service.SendTelemetry("Testing Telemetry", map[string]interface{}{ + service.SendTelemetry("Testing Telemetry", map[string]any{ "hey": testValue, }) select { case result := <-pchan: - assertPayload(t, result, "Testing Telemetry", map[string]interface{}{ + assertPayload(t, result, "Testing Telemetry", map[string]any{ "hey": testValue, }) case <-time.After(time.Second * 1): diff --git a/services/tracing/tracing.go b/services/tracing/tracing.go index 4226ef729e..d4687ec326 100644 --- a/services/tracing/tracing.go +++ b/services/tracing/tracing.go @@ -31,7 +31,7 @@ func (LogrusAdapter) Error(msg string) { } // Infof - logrus adapter for span info logging -func (LogrusAdapter) Infof(msg string, args ...interface{}) { +func (LogrusAdapter) Infof(msg string, args ...any) { // we ignore Info messages from opentracing } diff --git a/shared/i18n/i18n.go b/shared/i18n/i18n.go index 0168b751d0..42108b38b4 100644 --- a/shared/i18n/i18n.go +++ b/shared/i18n/i18n.go @@ -20,7 +20,7 @@ import ( const defaultLocale = "en" // TranslateFunc is the type of the translate functions -type TranslateFunc func(translationID string, args ...interface{}) string +type TranslateFunc func(translationID string, args ...any) string // T is the translate function using the default server language as fallback language var T TranslateFunc @@ -135,7 +135,7 @@ func GetSupportedLocales() map[string]string { func tfuncWithFallback(pref string) TranslateFunc { t, _ := i18n.Tfunc(pref) - return func(translationID string, args ...interface{}) string { + return func(translationID string, args ...any) string { if translated := t(translationID, args...); translated != translationID { return translated } @@ -147,21 +147,21 @@ func tfuncWithFallback(pref string) TranslateFunc { // TranslateAsHTML translates the translationID provided and return a // template.HTML object -func TranslateAsHTML(t TranslateFunc, translationID string, args map[string]interface{}) template.HTML { +func TranslateAsHTML(t TranslateFunc, translationID string, args map[string]any) template.HTML { message := t(translationID, escapeForHTML(args)) message = strings.Replace(message, "[[", "", -1) message = strings.Replace(message, "]]", "", -1) return template.HTML(message) } -func escapeForHTML(arg interface{}) interface{} { +func escapeForHTML(arg any) any { switch typedArg := arg.(type) { case string: return template.HTMLEscapeString(typedArg) case *string: return template.HTMLEscapeString(*typedArg) - case map[string]interface{}: - safeArg := make(map[string]interface{}, len(typedArg)) + case map[string]any: + safeArg := make(map[string]any, len(typedArg)) for key, value := range typedArg { safeArg[key] = escapeForHTML(value) } @@ -179,7 +179,7 @@ func escapeForHTML(arg interface{}) interface{} { // IdentityTfunc returns a translation function that don't translate, only // returns the same id func IdentityTfunc() TranslateFunc { - return func(translationID string, args ...interface{}) string { + return func(translationID string, args ...any) string { return translationID } } diff --git a/shared/i18n/i18n_test.go b/shared/i18n/i18n_test.go index 89a228d4e1..9f82338723 100644 --- a/shared/i18n/i18n_test.go +++ b/shared/i18n/i18n_test.go @@ -16,7 +16,7 @@ var htmlTestTranslationBundle *bundle.Bundle func init() { htmlTestTranslationBundle = bundle.New() - fooBold, _ := translation.NewTranslation(map[string]interface{}{ + fooBold, _ := translation.NewTranslation(map[string]any{ "id": "foo.bold", "translation": "

[[{{ .Foo }}]]

", }) @@ -24,7 +24,7 @@ func init() { } func TestTranslateAsHTML(t *testing.T) { - assert.EqualValues(t, "

<i>foo</i>

", TranslateAsHTML(TranslateFunc(htmlTestTranslationBundle.MustTfunc("en")), "foo.bold", map[string]interface{}{ + assert.EqualValues(t, "

<i>foo</i>

", TranslateAsHTML(TranslateFunc(htmlTestTranslationBundle.MustTfunc("en")), "foo.bold", map[string]any{ "Foo": "foo", })) } @@ -32,8 +32,8 @@ func TestTranslateAsHTML(t *testing.T) { func TestEscapeForHTML(t *testing.T) { stringForPointer := "abc" for name, tc := range map[string]struct { - In interface{} - Expected interface{} + In any + Expected any }{ "NoHTML": { In: "abc", @@ -48,11 +48,11 @@ func TestEscapeForHTML(t *testing.T) { Expected: "<b>abc</b>", }, "Map": { - In: map[string]interface{}{ + In: map[string]any{ "abc": "abc", "123": "123", }, - Expected: map[string]interface{}{ + Expected: map[string]any{ "abc": "abc", "123": "<b>123</b>", }, diff --git a/shared/markdown/inspect.go b/shared/markdown/inspect.go index 3c7f2d1c75..2c14412949 100644 --- a/shared/markdown/inspect.go +++ b/shared/markdown/inspect.go @@ -5,7 +5,7 @@ package markdown // Inspect traverses the markdown tree in depth-first order. If f returns true, Inspect invokes f // recursively for each child of the block or inline, followed by a call of f(nil). -func Inspect(markdown string, f func(interface{}) bool) { +func Inspect(markdown string, f func(any) bool) { document, referenceDefinitions := Parse(markdown) InspectBlock(document, func(block Block) bool { if !f(block) { diff --git a/shared/markdown/inspect_test.go b/shared/markdown/inspect_test.go index 56899381e7..8443ef6e8c 100644 --- a/shared/markdown/inspect_test.go +++ b/shared/markdown/inspect_test.go @@ -22,7 +22,7 @@ func TestInspect(t *testing.T) { visited := []string{} level := 0 - Inspect(markdown, func(blockOrInline interface{}) bool { + Inspect(markdown, func(blockOrInline any) bool { if blockOrInline == nil { level-- } else { @@ -67,7 +67,7 @@ Some bold text **Text for markdown?** to go with it. At the end, some more lines` for i := 0; i < b.N; i++ { - Inspect(text, func(_ interface{}) bool { + Inspect(text, func(_ any) bool { counterSink++ return true }) diff --git a/shared/markdown/text_range_test.go b/shared/markdown/text_range_test.go index 7909d4be60..f29bece326 100644 --- a/shared/markdown/text_range_test.go +++ b/shared/markdown/text_range_test.go @@ -99,7 +99,7 @@ func TestTextRanges(t *testing.T) { t.Run(name, func(t *testing.T) { var ranges []Range var values []string - Inspect(tc.Markdown, func(node interface{}) bool { + Inspect(tc.Markdown, func(node any) bool { if textNode, ok := node.(*Text); ok { ranges = append(ranges, textNode.Range) values = append(values, textNode.Text) diff --git a/shared/mlog/graphql.go b/shared/mlog/graphql.go index a09e069948..7f439f3010 100644 --- a/shared/mlog/graphql.go +++ b/shared/mlog/graphql.go @@ -18,6 +18,6 @@ func NewGraphQLLogger(logger *Logger) *GraphQLLogger { // LogPanic satisfies the graphql/log.Logger interface. // It converts the panic into an error. -func (l *GraphQLLogger) LogPanic(_ context.Context, value interface{}) { +func (l *GraphQLLogger) LogPanic(_ context.Context, value any) { l.logger.Error("Error while executing GraphQL query", Any("error", value)) } diff --git a/shared/templates/templates.go b/shared/templates/templates.go index 73e1b4a665..cfb62d3e80 100644 --- a/shared/templates/templates.go +++ b/shared/templates/templates.go @@ -27,7 +27,7 @@ type Container struct { // Data contains the data used to populate the template variables, it has Props // that can be of any type and HTML that only can be `template.HTML` types. type Data struct { - Props map[string]interface{} + Props map[string]any HTML map[string]template.HTML } diff --git a/shared/templates/templates_test.go b/shared/templates/templates_test.go index 40940e1a03..f847790cfe 100644 --- a/shared/templates/templates_test.go +++ b/shared/templates/templates_test.go @@ -73,7 +73,7 @@ func TestRender(t *testing.T) { mt := NewFromTemplate(tpl) data := Data{ - Props: map[string]interface{}{ + Props: map[string]any{ "Bar": "bar", }, } diff --git a/store/errors.go b/store/errors.go index 2387cb5a8e..82832a1a1b 100644 --- a/store/errors.go +++ b/store/errors.go @@ -10,12 +10,12 @@ import ( // ErrInvalidInput indicates an error that has occurred due to an invalid input. type ErrInvalidInput struct { - Entity string // The entity which was sent as the input. - Field string // The field of the entity which was invalid. - Value interface{} // The actual value of the field. + Entity string // The entity which was sent as the input. + Field string // The field of the entity which was invalid. + Value any // The actual value of the field. } -func NewErrInvalidInput(entity, field string, value interface{}) *ErrInvalidInput { +func NewErrInvalidInput(entity, field string, value any) *ErrInvalidInput { return &ErrInvalidInput{ Entity: entity, Field: field, @@ -27,7 +27,7 @@ func (e *ErrInvalidInput) Error() string { return fmt.Sprintf("invalid input: entity: %s field: %s value: %s", e.Entity, e.Field, e.Value) } -func (e *ErrInvalidInput) InvalidInputInfo() (entity string, field string, value interface{}) { +func (e *ErrInvalidInput) InvalidInputInfo() (entity string, field string, value any) { entity = e.Entity field = e.Field value = e.Value diff --git a/store/localcachelayer/layer.go b/store/localcachelayer/layer.go index 4ebb47180e..7b46386cf1 100644 --- a/store/localcachelayer/layer.go +++ b/store/localcachelayer/layer.go @@ -408,11 +408,11 @@ func (s *LocalCacheStore) doInvalidateCacheCluster(cache cache.Cache, key string } } -func (s *LocalCacheStore) doStandardAddToCache(cache cache.Cache, key string, value interface{}) { +func (s *LocalCacheStore) doStandardAddToCache(cache cache.Cache, key string, value any) { cache.SetWithDefaultExpiry(key, value) } -func (s *LocalCacheStore) doStandardReadCache(cache cache.Cache, key string, value interface{}) error { +func (s *LocalCacheStore) doStandardReadCache(cache cache.Cache, key string, value any) error { err := cache.Get(key, value) if err == nil { if s.metrics != nil { diff --git a/store/sqlstore/adapters.go b/store/sqlstore/adapters.go index c7b1e95632..31636a4686 100644 --- a/store/sqlstore/adapters.go +++ b/store/sqlstore/adapters.go @@ -51,7 +51,7 @@ func (str jsonKeyPath) Value() (driver.Value, error) { type TraceOnAdapter struct{} -func (t *TraceOnAdapter) Printf(format string, v ...interface{}) { +func (t *TraceOnAdapter) Printf(format string, v ...any) { originalString := fmt.Sprintf(format, v...) newString := strings.ReplaceAll(originalString, "\n", " ") newString = strings.ReplaceAll(newString, "\t", " ") diff --git a/store/sqlstore/bot_store.go b/store/sqlstore/bot_store.go index b2e20a6835..21e5711aaa 100644 --- a/store/sqlstore/bot_store.go +++ b/store/sqlstore/bot_store.go @@ -96,7 +96,7 @@ func (us SqlBotStore) GetAll(options *model.BotGetOptions) ([]*model.Bot, error) var conditions []string var conditionsSql string var additionalJoin string - var args []interface{} + var args []any if !options.IncludeDeleted { conditions = append(conditions, "b.DeleteAt = 0") diff --git a/store/sqlstore/channel_member_history_store.go b/store/sqlstore/channel_member_history_store.go index 5182e79658..77a2a8cf10 100644 --- a/store/sqlstore/channel_member_history_store.go +++ b/store/sqlstore/channel_member_history_store.go @@ -201,7 +201,7 @@ func (s SqlChannelMemberHistoryStore) DeleteOrphanedRows(limit int) (deleted int func (s SqlChannelMemberHistoryStore) PermanentDeleteBatch(endTime int64, limit int64) (int64, error) { var ( query string - args []interface{} + args []any err error ) diff --git a/store/sqlstore/channel_store.go b/store/sqlstore/channel_store.go index 4ecfc65915..60110e7074 100644 --- a/store/sqlstore/channel_store.go +++ b/store/sqlstore/channel_store.go @@ -56,8 +56,8 @@ type channelMember struct { MsgCountRoot int64 } -func NewMapFromChannelMemberModel(cm *model.ChannelMember) map[string]interface{} { - return map[string]interface{}{ +func NewMapFromChannelMemberModel(cm *model.ChannelMember) map[string]any { + return map[string]any{ "ChannelId": cm.ChannelId, "UserId": cm.UserId, "Roles": cm.ExplicitRoles, @@ -109,8 +109,8 @@ func channelMemberSliceColumns() []string { return []string{"ChannelId", "UserId", "Roles", "LastViewedAt", "MsgCount", "MsgCountRoot", "MentionCount", "MentionCountRoot", "NotifyProps", "LastUpdateAt", "SchemeUser", "SchemeAdmin", "SchemeGuest"} } -func channelMemberToSlice(member *model.ChannelMember) []interface{} { - resultSlice := []interface{}{} +func channelMemberToSlice(member *model.ChannelMember) []any { + resultSlice := []any{} resultSlice = append(resultSlice, member.ChannelId) resultSlice = append(resultSlice, member.UserId) resultSlice = append(resultSlice, member.ExplicitRoles) @@ -504,7 +504,7 @@ func (s SqlChannelStore) upsertPublicChannelT(transaction *sqlxTxWrapper, channe return nil } - vals := map[string]interface{}{ + vals := map[string]any{ "id": publicChannel.Id, "deleteat": publicChannel.DeleteAt, "teamid": publicChannel.TeamId, @@ -752,7 +752,7 @@ func (s SqlChannelStore) updateChannelT(transaction *sqlxTxWrapper, channel *mod if err != nil { if IsUniqueConstraintError(err, []string{"Name", "channels_name_teamid_key"}) { dupChannel := model.Channel{} - s.GetReplicaX().Get(&dupChannel, "SELECT * FROM Channels WHERE TeamId = :TeamId AND Name= :Name AND DeleteAt > 0", map[string]interface{}{"TeamId": channel.TeamId, "Name": channel.Name}) + s.GetReplicaX().Get(&dupChannel, "SELECT * FROM Channels WHERE TeamId = :TeamId AND Name= :Name AND DeleteAt > 0", map[string]any{"TeamId": channel.TeamId, "Name": channel.Name}) if dupChannel.DeleteAt > 0 { return nil, store.NewErrInvalidInput("Channel", "Id", channel.Id) } @@ -1356,7 +1356,7 @@ func (s SqlChannelStore) GetPublicChannelsForTeam(teamId string, offset int, lim } func (s SqlChannelStore) GetPublicChannelsByIdsForTeam(teamId string, channelIds []string) (model.ChannelList, error) { - props := make(map[string]interface{}) + props := make(map[string]any) props["teamId"] = teamId idQuery := "" @@ -2581,7 +2581,7 @@ func (s SqlChannelStore) UpdateLastViewedAtPost(unreadPost *model.Post, userID s unreadRoot = 0 } - params := map[string]interface{}{ + params := map[string]any{ "mentions": mentionCount, "mentionsroot": mentionCountRoot, "unreadcount": unread, @@ -3035,7 +3035,7 @@ func (s SqlChannelStore) AutocompleteInTeamForSearch(teamID string, userID strin var ( channels = model.ChannelList{} sql string - args []interface{} + args []any ) // build the like clause @@ -3302,7 +3302,7 @@ func (s SqlChannelStore) channelSearchQuery(opts *store.ChannelSearchOpts) sq.Se if likeTerm != "" { // Keep the number of likeTerms same as the number of columns // (c.Name, c.DisplayName, c.Purpose, c.Id?) - likeTerms := make([]interface{}, len(strings.Split(likeFields, ","))) + likeTerms := make([]any, len(strings.Split(likeFields, ","))) for i := 0; i < len(likeTerms); i++ { likeTerms[i] = likeTerm } @@ -4157,7 +4157,7 @@ func (s SqlChannelStore) GetTeamForChannel(channelID string) (*model.Team, error // b) those that are public channels in the given team. func (s SqlChannelStore) GetTopChannelsForTeamSince(teamID string, userID string, since int64, offset int, limit int) (*model.TopChannelList, error) { channels := make([]*model.TopChannel, 0) - var args []interface{} + var args []any postgresPropQuery := `AND (Posts.Props ->> 'from_bot' IS NULL OR Posts.Props ->> 'from_bot' = 'false')` mySqlPropsQuery := `AND (JSON_EXTRACT(Posts.Props, '$.from_bot') IS NULL OR JSON_EXTRACT(Posts.Props, '$.from_bot') = 'false')` @@ -4185,7 +4185,7 @@ func (s SqlChannelStore) GetTopChannelsForTeamSince(teamID string, userID string Posts.DeleteAt = 0 AND Posts.CreateAt > ? AND Posts.Type = ''` - args = []interface{}{since} + args = []any{since} if s.DriverName() == model.DatabaseDriverMysql { query += mySqlPropsQuery @@ -4257,7 +4257,7 @@ func (s SqlChannelStore) GetTopChannelsForTeamSince(teamID string, userID string // after the given timestamp within the given team (or across the workspace if no team is given). Excludes DM and GM channels. func (s SqlChannelStore) GetTopChannelsForUserSince(userID string, teamID string, since int64, offset int, limit int) (*model.TopChannelList, error) { channels := make([]*model.TopChannel, 0) - var args []interface{} + var args []any var query string query = ` @@ -4281,7 +4281,7 @@ func (s SqlChannelStore) GetTopChannelsForUserSince(userID string, teamID string AND (Channels.Type = 'O' OR Channels.Type = 'P') AND ChannelMembers.UserId = ?` - args = []interface{}{since, userID, userID} + args = []any{since, userID, userID} if teamID != "" { query += ` diff --git a/store/sqlstore/channel_store_categories.go b/store/sqlstore/channel_store_categories.go index 4b3479bbfc..0d2af6c487 100644 --- a/store/sqlstore/channel_store_categories.go +++ b/store/sqlstore/channel_store_categories.go @@ -17,7 +17,7 @@ import ( // dbSelecter is an interface used to enable some internal store methods // using both transaction and normal queries. type dbSelecter interface { - Select(i interface{}, query string, args ...interface{}) error + Select(i any, query string, args ...any) error } func (s SqlChannelStore) CreateInitialSidebarCategories(userId string, opts *store.SidebarCategorySearchOpts) (*model.OrderedSidebarCategories, error) { @@ -177,7 +177,7 @@ type userMembership struct { CategoryId string } -func (s SqlChannelStore) migrateMembershipToSidebar(transaction *sqlxTxWrapper, runningOrder *int64, sql string, args ...interface{}) ([]userMembership, error) { +func (s SqlChannelStore) migrateMembershipToSidebar(transaction *sqlxTxWrapper, runningOrder *int64, sql string, args ...any) ([]userMembership, error) { memberships := []userMembership{} if err := transaction.Select(&memberships, sql, args...); err != nil { return nil, err @@ -244,7 +244,7 @@ func (s SqlChannelStore) migrateFavoritesToSidebarT(transaction *sqlxTxWrapper, // MigrateFavoritesToSidebarChannels populates the SidebarChannels table by analyzing existing user preferences for favorites // **IMPORTANT** This function should only be called from the migration task and shouldn't be used by itself -func (s SqlChannelStore) MigrateFavoritesToSidebarChannels(lastUserId string, runningOrder int64) (map[string]interface{}, error) { +func (s SqlChannelStore) MigrateFavoritesToSidebarChannels(lastUserId string, runningOrder int64) (map[string]any, error) { transaction, err := s.GetMasterX().Beginx() if err != nil { return nil, err @@ -280,7 +280,7 @@ func (s SqlChannelStore) MigrateFavoritesToSidebarChannels(lastUserId string, ru return nil, nil } - data := make(map[string]interface{}) + data := make(map[string]any) data["UserId"] = userFavorites[len(userFavorites)-1].UserId data["SortOrder"] = runningOrder return data, nil @@ -370,7 +370,7 @@ func (s SqlChannelStore) CreateSidebarCategory(userId, teamId string, newCategor AND SidebarCategories.TeamId = ?` } - args := []interface{}{userId} + args := []any{userId} args = append(args, channelIdArgs...) args = append(args, teamId) _, err = transaction.Exec(deleteQuery, args...) diff --git a/store/sqlstore/compliance_store.go b/store/sqlstore/compliance_store.go index cf25f8cf7a..6e2ae38ac1 100644 --- a/store/sqlstore/compliance_store.go +++ b/store/sqlstore/compliance_store.go @@ -106,7 +106,7 @@ func (s SqlComplianceStore) Get(id string) (*model.Compliance, error) { func (s SqlComplianceStore) ComplianceExport(job *model.Compliance, cursor model.ComplianceExportCursor, limit int) ([]*model.CompliancePost, model.ComplianceExportCursor, error) { keywordQuery := "" - var argsKeywords []interface{} + var argsKeywords []any keywords := strings.Fields(strings.TrimSpace(strings.ToLower(strings.Replace(job.Keywords, ",", " ", -1)))) if len(keywords) > 0 { clauses := make([]string, len(keywords)) @@ -121,7 +121,7 @@ func (s SqlComplianceStore) ComplianceExport(job *model.Compliance, cursor model } emailQuery := "" - var argsEmails []interface{} + var argsEmails []any emails := strings.Fields(strings.TrimSpace(strings.ToLower(strings.Replace(job.Emails, ",", " ", -1)))) if len(emails) > 0 { clauses := make([]string, len(emails)) @@ -139,7 +139,7 @@ func (s SqlComplianceStore) ComplianceExport(job *model.Compliance, cursor model channelPosts := []*model.CompliancePost{} channelsQuery := "" - var argsChannelsQuery []interface{} + var argsChannelsQuery []any if !cursor.ChannelsQueryCompleted { if cursor.LastChannelsQueryPostCreateAt == 0 { cursor.LastChannelsQueryPostCreateAt = job.StartAt @@ -204,7 +204,7 @@ func (s SqlComplianceStore) ComplianceExport(job *model.Compliance, cursor model directMessagePosts := []*model.CompliancePost{} directMessagesQuery := "" - var argsDirectMessagesQuery []interface{} + var argsDirectMessagesQuery []any if !cursor.DirectMessagesQueryCompleted && len(channelPosts) < limit { if cursor.LastDirectMessagesQueryPostCreateAt == 0 { cursor.LastDirectMessagesQueryPostCreateAt = job.StartAt @@ -271,7 +271,7 @@ func (s SqlComplianceStore) ComplianceExport(job *model.Compliance, cursor model } func (s SqlComplianceStore) MessageExport(cursor model.MessageExportCursor, limit int) ([]*model.MessageExport, model.MessageExportCursor, error) { - var args []interface{} + var args []any args = append(args, model.ChannelTypeDirect, model.ChannelTypeGroup, cursor.LastPostUpdateAt, cursor.LastPostUpdateAt, cursor.LastPostId, limit) query := `SELECT diff --git a/store/sqlstore/file_info_store.go b/store/sqlstore/file_info_store.go index abbf82e58f..4a6eb7e655 100644 --- a/store/sqlstore/file_info_store.go +++ b/store/sqlstore/file_info_store.go @@ -168,7 +168,7 @@ func (fs SqlFileInfoStore) Upsert(info *model.FileInfo) (*model.FileInfo, error) queryString, args, err := fs.getQueryBuilder(). Update("FileInfo"). - SetMap(map[string]interface{}{ + SetMap(map[string]any{ "UpdateAt": info.UpdateAt, "DeleteAt": info.DeleteAt, "Path": info.Path, diff --git a/store/sqlstore/group_store.go b/store/sqlstore/group_store.go index b03ead29c2..add231364c 100644 --- a/store/sqlstore/group_store.go +++ b/store/sqlstore/group_store.go @@ -199,7 +199,7 @@ func (s *SqlGroupStore) checkUsersExist(userIDs []string) error { return nil } -func (s *SqlGroupStore) buildInsertGroupUsersQuery(groupId string, userIds []string) (query string, args []interface{}, err error) { +func (s *SqlGroupStore) buildInsertGroupUsersQuery(groupId string, userIds []string) (query string, args []any, err error) { if len(userIds) > 0 { builder := s.getQueryBuilder(). Insert("GroupMembers"). @@ -631,7 +631,7 @@ func (s *SqlGroupStore) GetGroupSyncable(groupID string, syncableID string, sync func (s *SqlGroupStore) getGroupSyncable(groupID string, syncableID string, syncableType model.GroupSyncableType) (*model.GroupSyncable, error) { var err error - var result interface{} + var result any switch syncableType { case model.GroupSyncableTypeTeam: @@ -1768,7 +1768,7 @@ func (s *SqlGroupStore) countTable(tableName string) (int64, error) { return s.countTableWithSelectAndWhere("COUNT(*)", tableName, nil) } -func (s *SqlGroupStore) countTableWithSelectAndWhere(selectStr, tableName string, whereStmt map[string]interface{}) (int64, error) { +func (s *SqlGroupStore) countTableWithSelectAndWhere(selectStr, tableName string, whereStmt map[string]any) (int64, error) { if whereStmt == nil { whereStmt = sq.Eq{"DeleteAt": 0} } @@ -1802,7 +1802,7 @@ func (s *SqlGroupStore) UpsertMembers(groupID string, userIDs []string) ([]*mode return members, err } -func (s *SqlGroupStore) buildUpsertMembersQuery(groupID string, userIDs []string) (members []*model.GroupMember, query string, args []interface{}, err error) { +func (s *SqlGroupStore) buildUpsertMembersQuery(groupID string, userIDs []string) (members []*model.GroupMember, query string, args []any, err error) { var retrievedGroup model.Group // Check Group exists if err = s.GetReplicaX().Get(&retrievedGroup, "SELECT * FROM UserGroups WHERE Id = ?", groupID); err != nil { @@ -1854,7 +1854,7 @@ func (s *SqlGroupStore) DeleteMembers(groupID string, userIDs []string) ([]*mode return members, err } -func (s *SqlGroupStore) buildDeleteMembersQuery(groupID string, userIDs []string) (members []*model.GroupMember, query string, args []interface{}, err error) { +func (s *SqlGroupStore) buildDeleteMembersQuery(groupID string, userIDs []string) (members []*model.GroupMember, query string, args []any, err error) { membersSelectQuery, membersSelectArgs, err := s.getQueryBuilder(). Select("*"). From("GroupMembers"). diff --git a/store/sqlstore/integrity.go b/store/sqlstore/integrity.go index a0a1f4396d..c72e9abfe6 100644 --- a/store/sqlstore/integrity.go +++ b/store/sqlstore/integrity.go @@ -17,7 +17,7 @@ type relationalCheckConfig struct { childIdAttr string canParentIdBeEmpty bool sortRecords bool - filter interface{} + filter any } func getOrphanedRecords(ss *SqlStore, cfg relationalCheckConfig) ([]model.OrphanedRecord, error) { diff --git a/store/sqlstore/post_store.go b/store/sqlstore/post_store.go index c2dd8f966f..bee37bf0b9 100644 --- a/store/sqlstore/post_store.go +++ b/store/sqlstore/post_store.go @@ -71,8 +71,8 @@ func postSliceColumnsWithTypes() []struct { } } -func postToSlice(post *model.Post) []interface{} { - return []interface{}{ +func postToSlice(post *model.Post) []any { + return []any{ post.Id, post.CreateAt, post.UpdateAt, @@ -233,7 +233,7 @@ func (s *SqlPostStore) SaveMultiple(posts []*model.Post) ([]*model.Post, int, er LastRootPostAt = GREATEST(:lastrootpostat, LastRootPostAt), TotalMsgCount = TotalMsgCount + :count, TotalMsgCountRoot = TotalMsgCountRoot + :countroot - WHERE Id = :channelid`, map[string]interface{}{ + WHERE Id = :channelid`, map[string]any{ "lastpostat": maxDateNewPosts[channelId], "lastrootpostat": maxDateNewRootPosts[channelId], "channelid": channelId, @@ -508,7 +508,7 @@ func (s *SqlPostStore) getFlaggedPosts(userId, channelId, teamId string, offset ORDER BY CreateAt DESC LIMIT ? OFFSET ?` - queryParams := []interface{}{userId, model.PreferenceCategoryFlaggedPost} + queryParams := []any{userId, model.PreferenceCategoryFlaggedPost} var channelClause, teamClause string channelClause, queryParams = s.buildFlaggedPostChannelFilterClause(channelId, queryParams) @@ -533,7 +533,7 @@ func (s *SqlPostStore) getFlaggedPosts(userId, channelId, teamId string, offset return pl, nil } -func (s *SqlPostStore) buildFlaggedPostTeamFilterClause(teamId string, queryParams []interface{}) (string, []interface{}) { +func (s *SqlPostStore) buildFlaggedPostTeamFilterClause(teamId string, queryParams []any) (string, []any) { if teamId == "" { return "", queryParams } @@ -541,7 +541,7 @@ func (s *SqlPostStore) buildFlaggedPostTeamFilterClause(teamId string, queryPara return "AND B.TeamId = ? OR B.TeamId = ''", append(queryParams, teamId) } -func (s *SqlPostStore) buildFlaggedPostChannelFilterClause(channelId string, queryParams []interface{}) (string, []interface{}) { +func (s *SqlPostStore) buildFlaggedPostChannelFilterClause(channelId string, queryParams []any) (string, []any) { if channelId == "" { return "", queryParams } @@ -930,7 +930,7 @@ func (s *SqlPostStore) permanentDelete(postId string) error { return errors.Wrapf(err, "failed to cleanup threads for Post with id=%s", postId) } - if _, err = transaction.NamedExec("DELETE FROM Posts WHERE Id = :id OR RootId = :rootid", map[string]interface{}{"id": postId, "rootid": postId}); err != nil { + if _, err = transaction.NamedExec("DELETE FROM Posts WHERE Id = :id OR RootId = :rootid", map[string]any{"id": postId, "rootid": postId}); err != nil { return errors.Wrapf(err, "failed to delete Post with id=%s", postId) } @@ -1250,7 +1250,7 @@ func (s *SqlPostStore) GetPostsSince(options model.GetPostsSinceOptions, allowFr replyCountQuery2 = `, (SELECT COUNT(*) FROM Posts WHERE Posts.RootId = (CASE WHEN cte.RootId = '' THEN cte.Id ELSE cte.RootId END) AND Posts.DeleteAt = 0) as ReplyCount` } var query string - var params []interface{} + var params []any // union of IDs and then join to get full posts is faster in mysql if s.DriverName() == model.DatabaseDriverMysql { @@ -1282,7 +1282,7 @@ func (s *SqlPostStore) GetPostsSince(options model.GetPostsSinceOptions, allowFr ) j ON p1.Id = j.Id ORDER BY CreateAt ` + order - params = []interface{}{options.Time, options.ChannelId, options.Time, options.ChannelId} + params = []any{options.Time, options.ChannelId, options.Time, options.ChannelId} } else if s.DriverName() == model.DatabaseDriverPostgres { query = `WITH cte AS (SELECT * @@ -1296,7 +1296,7 @@ func (s *SqlPostStore) GetPostsSince(options model.GetPostsSinceOptions, allowFr (SELECT *` + replyCountQuery1 + ` FROM Posts p1 WHERE id in (SELECT rootid FROM cte)) ORDER BY CreateAt ` + order - params = []interface{}{options.Time, options.ChannelId} + params = []any{options.Time, options.ChannelId} } err := s.GetReplicaX().Select(&posts, query, params...) if err != nil { @@ -2029,7 +2029,7 @@ func removeMysqlStopWordsFromTerms(terms string) (string, error) { // TODO: convert to squirrel HW func (s *SqlPostStore) AnalyticsUserCountsWithPostsByDay(teamId string) (model.AnalyticsRows, error) { - var args []interface{} + var args []any query := `SELECT DISTINCT DATE(FROM_UNIXTIME(Posts.CreateAt / 1000)) AS Name, @@ -2038,7 +2038,7 @@ func (s *SqlPostStore) AnalyticsUserCountsWithPostsByDay(teamId string) (model.A if teamId != "" { query += " INNER JOIN Channels ON Posts.ChannelId = Channels.Id AND Channels.TeamId = ? AND" - args = []interface{}{teamId} + args = []any{teamId} } else { query += " WHERE" } @@ -2056,7 +2056,7 @@ func (s *SqlPostStore) AnalyticsUserCountsWithPostsByDay(teamId string) (model.A if teamId != "" { query += " INNER JOIN Channels ON Posts.ChannelId = Channels.Id AND Channels.TeamId = ? AND" - args = []interface{}{teamId} + args = []any{teamId} } else { query += " WHERE" } @@ -2085,7 +2085,7 @@ func (s *SqlPostStore) AnalyticsUserCountsWithPostsByDay(teamId string) (model.A // TODO: convert to squirrel HW func (s *SqlPostStore) AnalyticsPostCountsByDay(options *model.AnalyticsPostCountsOptions) (model.AnalyticsRows, error) { - var args []interface{} + var args []any query := `SELECT DATE(FROM_UNIXTIME(Posts.CreateAt / 1000)) AS Name, @@ -2098,7 +2098,7 @@ func (s *SqlPostStore) AnalyticsPostCountsByDay(options *model.AnalyticsPostCoun if options.TeamId != "" { query += " INNER JOIN Channels ON Posts.ChannelId = Channels.Id AND Channels.TeamId = ? AND" - args = []interface{}{options.TeamId} + args = []any{options.TeamId} } else { query += " WHERE" } @@ -2121,7 +2121,7 @@ func (s *SqlPostStore) AnalyticsPostCountsByDay(options *model.AnalyticsPostCoun if options.TeamId != "" { query += " INNER JOIN Channels ON Posts.ChannelId = Channels.Id AND Channels.TeamId = ? AND" - args = []interface{}{options.TeamId} + args = []any{options.TeamId} } else { query += " WHERE" } diff --git a/store/sqlstore/reaction_store.go b/store/sqlstore/reaction_store.go index ce7a644410..e88840568c 100644 --- a/store/sqlstore/reaction_store.go +++ b/store/sqlstore/reaction_store.go @@ -296,7 +296,7 @@ func (s *SqlReactionStore) GetTopForTeamSince(teamID string, userID string, sinc // b) those created by the given user in DM or group channels. func (s *SqlReactionStore) GetTopForUserSince(userID string, teamID string, since int64, offset int, limit int) (*model.TopReactionList, error) { reactions := make([]*model.TopReaction, 0) - var args []interface{} + var args []any var query string if teamID != "" { @@ -320,7 +320,7 @@ func (s *SqlReactionStore) GetTopForUserSince(userID string, teamID string, sinc EmojiName ASC LIMIT ? OFFSET ?` - args = []interface{}{userID, teamID, since, limit + 1, offset} + args = []any{userID, teamID, since, limit + 1, offset} } else { query = ` SELECT @@ -339,7 +339,7 @@ func (s *SqlReactionStore) GetTopForUserSince(userID string, teamID string, sinc EmojiName ASC LIMIT ? OFFSET ?` - args = []interface{}{userID, since, limit + 1, offset} + args = []any{userID, since, limit + 1, offset} } if err := s.GetReplicaX().Select(&reactions, query, args...); err != nil { diff --git a/store/sqlstore/retention_policy_store.go b/store/sqlstore/retention_policy_store.go index 0f798c54e1..118a27691a 100644 --- a/store/sqlstore/retention_policy_store.go +++ b/store/sqlstore/retention_policy_store.go @@ -32,7 +32,7 @@ func newSqlRetentionPolicyStore(sqlStore *SqlStore, metrics einterfaces.MetricsI // executePossiblyEmptyQuery only executes the query if it is non-empty. This helps avoid // having to check for MySQL, which, unlike Postgres, does not allow empty queries. -func executePossiblyEmptyQuery(txn *sqlxTxWrapper, query string, args ...interface{}) (sql.Result, error) { +func executePossiblyEmptyQuery(txn *sqlxTxWrapper, query string, args ...any) (sql.Result, error) { if query == "" { return nil, nil } @@ -169,7 +169,7 @@ func (s *SqlRetentionPolicyStore) checkChannelsExist(channelIDs []string) error return nil } -func (s *SqlRetentionPolicyStore) buildInsertRetentionPoliciesChannelsQuery(policyID string, channelIDs []string) (query string, args []interface{}, err error) { +func (s *SqlRetentionPolicyStore) buildInsertRetentionPoliciesChannelsQuery(policyID string, channelIDs []string) (query string, args []any, err error) { if len(channelIDs) > 0 { builder := s.getQueryBuilder(). Insert("RetentionPoliciesChannels"). @@ -182,7 +182,7 @@ func (s *SqlRetentionPolicyStore) buildInsertRetentionPoliciesChannelsQuery(poli return } -func (s *SqlRetentionPolicyStore) buildInsertRetentionPoliciesTeamsQuery(policyID string, teamIDs []string) (query string, args []interface{}, err error) { +func (s *SqlRetentionPolicyStore) buildInsertRetentionPoliciesTeamsQuery(policyID string, teamIDs []string) (query string, args []any, err error) { if len(teamIDs) > 0 { builder := s.getQueryBuilder(). Insert("RetentionPoliciesTeams"). @@ -213,7 +213,7 @@ func (s *SqlRetentionPolicyStore) Patch(patch *model.RetentionPolicyWithTeamAndC } policyUpdateQuery := "" - policyUpdateArgs := []interface{}{} + policyUpdateArgs := []any{} if patch.DisplayName != "" || patch.PostDurationDays != nil { builder := s.getQueryBuilder().Update("RetentionPolicies") if patch.DisplayName != "" { @@ -231,9 +231,9 @@ func (s *SqlRetentionPolicyStore) Patch(patch *model.RetentionPolicyWithTeamAndC } channelsDeleteQuery := "" - channelsDeleteArgs := []interface{}{} + channelsDeleteArgs := []any{} channelsInsertQuery := "" - channelsInsertArgs := []interface{}{} + channelsInsertArgs := []any{} if patch.ChannelIDs != nil { channelsDeleteQuery, channelsDeleteArgs, err = s.getQueryBuilder(). Delete("RetentionPoliciesChannels"). @@ -250,9 +250,9 @@ func (s *SqlRetentionPolicyStore) Patch(patch *model.RetentionPolicyWithTeamAndC } teamsDeleteQuery := "" - teamsDeleteArgs := []interface{}{} + teamsDeleteArgs := []any{} teamsInsertQuery := "" - teamsInsertArgs := []interface{}{} + teamsInsertArgs := []any{} if patch.TeamIDs != nil { teamsDeleteQuery, teamsDeleteArgs, err = s.getQueryBuilder(). Delete("RetentionPoliciesTeams"). @@ -309,14 +309,14 @@ func (s *SqlRetentionPolicyStore) Patch(patch *model.RetentionPolicyWithTeamAndC return &newPolicy, nil } -func (s *SqlRetentionPolicyStore) buildGetPolicyQuery(id string) (string, []interface{}, error) { +func (s *SqlRetentionPolicyStore) buildGetPolicyQuery(id string) (string, []any, error) { return s.buildGetPoliciesQuery(id, 0, 1) } // buildGetPoliciesQuery builds a query to select information for the policy with the specified // ID, or, if `id` is the empty string, from all policies. The results returned will be sorted by // policy display name and ID. -func (s *SqlRetentionPolicyStore) buildGetPoliciesQuery(id string, offset, limit int) (string, []interface{}, error) { +func (s *SqlRetentionPolicyStore) buildGetPoliciesQuery(id string, offset, limit int) (string, []any, error) { rpcSubQuery := s.getQueryBuilder(). Select("RetentionPolicies.Id, COUNT(RetentionPoliciesChannels.ChannelId) AS Count"). From("RetentionPolicies"). diff --git a/store/sqlstore/sqlx_wrapper.go b/store/sqlstore/sqlx_wrapper.go index ef2236c121..95b274aae9 100644 --- a/store/sqlstore/sqlx_wrapper.go +++ b/store/sqlstore/sqlx_wrapper.go @@ -36,23 +36,23 @@ func (w *StoreTestWrapper) DriverName() string { } type Builder interface { - ToSql() (string, []interface{}, error) + ToSql() (string, []any, error) } // sqlxExecutor exposes sqlx operations. It is used to enable some internal store methods to // accept both transactions (*sqlxTxWrapper) and common db handlers (*sqlxDbWrapper). type sqlxExecutor interface { - Get(dest interface{}, query string, args ...interface{}) error - GetBuilder(dest interface{}, builder Builder) error - NamedExec(query string, arg interface{}) (sql.Result, error) - Exec(query string, args ...interface{}) (sql.Result, error) + Get(dest any, query string, args ...any) error + GetBuilder(dest any, builder Builder) error + NamedExec(query string, arg any) (sql.Result, error) + Exec(query string, args ...any) (sql.Result, error) ExecBuilder(builder Builder) (sql.Result, error) - ExecRaw(query string, args ...interface{}) (sql.Result, error) - NamedQuery(query string, arg interface{}) (*sqlx.Rows, error) - QueryRowX(query string, args ...interface{}) *sqlx.Row - QueryX(query string, args ...interface{}) (*sqlx.Rows, error) - Select(dest interface{}, query string, args ...interface{}) error - SelectBuilder(dest interface{}, builder Builder) error + ExecRaw(query string, args ...any) (sql.Result, error) + NamedQuery(query string, arg any) (*sqlx.Rows, error) + QueryRowX(query string, args ...any) *sqlx.Row + QueryX(query string, args ...any) (*sqlx.Rows, error) + Select(dest any, query string, args ...any) error + SelectBuilder(dest any, builder Builder) error } // namedParamRegex is used to capture all named parameters and convert them @@ -98,7 +98,7 @@ func (w *sqlxDBWrapper) BeginXWithIsolation(opts *sql.TxOptions) (*sqlxTxWrapper return newSqlxTxWrapper(tx, w.queryTimeout, w.trace), nil } -func (w *sqlxDBWrapper) Get(dest interface{}, query string, args ...interface{}) error { +func (w *sqlxDBWrapper) Get(dest any, query string, args ...any) error { query = w.DB.Rebind(query) ctx, cancel := context.WithTimeout(context.Background(), w.queryTimeout) defer cancel() @@ -112,7 +112,7 @@ func (w *sqlxDBWrapper) Get(dest interface{}, query string, args ...interface{}) return w.DB.GetContext(ctx, dest, query, args...) } -func (w *sqlxDBWrapper) GetBuilder(dest interface{}, builder Builder) error { +func (w *sqlxDBWrapper) GetBuilder(dest any, builder Builder) error { query, args, err := builder.ToSql() if err != nil { return err @@ -121,7 +121,7 @@ func (w *sqlxDBWrapper) GetBuilder(dest interface{}, builder Builder) error { return w.Get(dest, query, args...) } -func (w *sqlxDBWrapper) NamedExec(query string, arg interface{}) (sql.Result, error) { +func (w *sqlxDBWrapper) NamedExec(query string, arg any) (sql.Result, error) { if w.DB.DriverName() == model.DatabaseDriverPostgres { query = namedParamRegex.ReplaceAllStringFunc(query, strings.ToLower) } @@ -137,7 +137,7 @@ func (w *sqlxDBWrapper) NamedExec(query string, arg interface{}) (sql.Result, er return w.DB.NamedExecContext(ctx, query, arg) } -func (w *sqlxDBWrapper) Exec(query string, args ...interface{}) (sql.Result, error) { +func (w *sqlxDBWrapper) Exec(query string, args ...any) (sql.Result, error) { query = w.DB.Rebind(query) return w.ExecRaw(query, args...) @@ -152,7 +152,7 @@ func (w *sqlxDBWrapper) ExecBuilder(builder Builder) (sql.Result, error) { return w.Exec(query, args...) } -func (w *sqlxDBWrapper) ExecNoTimeout(query string, args ...interface{}) (sql.Result, error) { +func (w *sqlxDBWrapper) ExecNoTimeout(query string, args ...any) (sql.Result, error) { query = w.DB.Rebind(query) if w.trace { @@ -166,7 +166,7 @@ func (w *sqlxDBWrapper) ExecNoTimeout(query string, args ...interface{}) (sql.Re // ExecRaw is like Exec but without any rebinding of params. You need to pass // the exact param types of your target database. -func (w *sqlxDBWrapper) ExecRaw(query string, args ...interface{}) (sql.Result, error) { +func (w *sqlxDBWrapper) ExecRaw(query string, args ...any) (sql.Result, error) { ctx, cancel := context.WithTimeout(context.Background(), w.queryTimeout) defer cancel() @@ -179,7 +179,7 @@ func (w *sqlxDBWrapper) ExecRaw(query string, args ...interface{}) (sql.Result, return w.DB.ExecContext(ctx, query, args...) } -func (w *sqlxDBWrapper) NamedQuery(query string, arg interface{}) (*sqlx.Rows, error) { +func (w *sqlxDBWrapper) NamedQuery(query string, arg any) (*sqlx.Rows, error) { if w.DB.DriverName() == model.DatabaseDriverPostgres { query = namedParamRegex.ReplaceAllStringFunc(query, strings.ToLower) } @@ -195,7 +195,7 @@ func (w *sqlxDBWrapper) NamedQuery(query string, arg interface{}) (*sqlx.Rows, e return w.DB.NamedQueryContext(ctx, query, arg) } -func (w *sqlxDBWrapper) QueryRowX(query string, args ...interface{}) *sqlx.Row { +func (w *sqlxDBWrapper) QueryRowX(query string, args ...any) *sqlx.Row { query = w.DB.Rebind(query) ctx, cancel := context.WithTimeout(context.Background(), w.queryTimeout) defer cancel() @@ -209,7 +209,7 @@ func (w *sqlxDBWrapper) QueryRowX(query string, args ...interface{}) *sqlx.Row { return w.DB.QueryRowxContext(ctx, query, args...) } -func (w *sqlxDBWrapper) QueryX(query string, args ...interface{}) (*sqlx.Rows, error) { +func (w *sqlxDBWrapper) QueryX(query string, args ...any) (*sqlx.Rows, error) { query = w.DB.Rebind(query) ctx, cancel := context.WithTimeout(context.Background(), w.queryTimeout) defer cancel() @@ -223,7 +223,7 @@ func (w *sqlxDBWrapper) QueryX(query string, args ...interface{}) (*sqlx.Rows, e return w.DB.QueryxContext(ctx, query, args) } -func (w *sqlxDBWrapper) Select(dest interface{}, query string, args ...interface{}) error { +func (w *sqlxDBWrapper) Select(dest any, query string, args ...any) error { query = w.DB.Rebind(query) ctx, cancel := context.WithTimeout(context.Background(), w.queryTimeout) defer cancel() @@ -237,7 +237,7 @@ func (w *sqlxDBWrapper) Select(dest interface{}, query string, args ...interface return w.DB.SelectContext(ctx, dest, query, args...) } -func (w *sqlxDBWrapper) SelectBuilder(dest interface{}, builder Builder) error { +func (w *sqlxDBWrapper) SelectBuilder(dest any, builder Builder) error { query, args, err := builder.ToSql() if err != nil { return err @@ -260,7 +260,7 @@ func newSqlxTxWrapper(tx *sqlx.Tx, timeout time.Duration, trace bool) *sqlxTxWra } } -func (w *sqlxTxWrapper) Get(dest interface{}, query string, args ...interface{}) error { +func (w *sqlxTxWrapper) Get(dest any, query string, args ...any) error { query = w.Tx.Rebind(query) ctx, cancel := context.WithTimeout(context.Background(), w.queryTimeout) defer cancel() @@ -274,7 +274,7 @@ func (w *sqlxTxWrapper) Get(dest interface{}, query string, args ...interface{}) return w.Tx.GetContext(ctx, dest, query, args...) } -func (w *sqlxTxWrapper) GetBuilder(dest interface{}, builder Builder) error { +func (w *sqlxTxWrapper) GetBuilder(dest any, builder Builder) error { query, args, err := builder.ToSql() if err != nil { return err @@ -283,13 +283,13 @@ func (w *sqlxTxWrapper) GetBuilder(dest interface{}, builder Builder) error { return w.Get(dest, query, args...) } -func (w *sqlxTxWrapper) Exec(query string, args ...interface{}) (sql.Result, error) { +func (w *sqlxTxWrapper) Exec(query string, args ...any) (sql.Result, error) { query = w.Tx.Rebind(query) return w.ExecRaw(query, args...) } -func (w *sqlxTxWrapper) ExecNoTimeout(query string, args ...interface{}) (sql.Result, error) { +func (w *sqlxTxWrapper) ExecNoTimeout(query string, args ...any) (sql.Result, error) { query = w.Tx.Rebind(query) if w.trace { @@ -312,7 +312,7 @@ func (w *sqlxTxWrapper) ExecBuilder(builder Builder) (sql.Result, error) { // ExecRaw is like Exec but without any rebinding of params. You need to pass // the exact param types of your target database. -func (w *sqlxTxWrapper) ExecRaw(query string, args ...interface{}) (sql.Result, error) { +func (w *sqlxTxWrapper) ExecRaw(query string, args ...any) (sql.Result, error) { ctx, cancel := context.WithTimeout(context.Background(), w.queryTimeout) defer cancel() @@ -325,7 +325,7 @@ func (w *sqlxTxWrapper) ExecRaw(query string, args ...interface{}) (sql.Result, return w.Tx.ExecContext(ctx, query, args...) } -func (w *sqlxTxWrapper) NamedExec(query string, arg interface{}) (sql.Result, error) { +func (w *sqlxTxWrapper) NamedExec(query string, arg any) (sql.Result, error) { if w.Tx.DriverName() == model.DatabaseDriverPostgres { query = namedParamRegex.ReplaceAllStringFunc(query, strings.ToLower) } @@ -341,7 +341,7 @@ func (w *sqlxTxWrapper) NamedExec(query string, arg interface{}) (sql.Result, er return w.Tx.NamedExecContext(ctx, query, arg) } -func (w *sqlxTxWrapper) NamedQuery(query string, arg interface{}) (*sqlx.Rows, error) { +func (w *sqlxTxWrapper) NamedQuery(query string, arg any) (*sqlx.Rows, error) { if w.Tx.DriverName() == model.DatabaseDriverPostgres { query = namedParamRegex.ReplaceAllStringFunc(query, strings.ToLower) } @@ -385,7 +385,7 @@ func (w *sqlxTxWrapper) NamedQuery(query string, arg interface{}) (*sqlx.Rows, e return res.rows, res.err } -func (w *sqlxTxWrapper) QueryRowX(query string, args ...interface{}) *sqlx.Row { +func (w *sqlxTxWrapper) QueryRowX(query string, args ...any) *sqlx.Row { query = w.Tx.Rebind(query) ctx, cancel := context.WithTimeout(context.Background(), w.queryTimeout) defer cancel() @@ -399,7 +399,7 @@ func (w *sqlxTxWrapper) QueryRowX(query string, args ...interface{}) *sqlx.Row { return w.Tx.QueryRowxContext(ctx, query, args...) } -func (w *sqlxTxWrapper) QueryX(query string, args ...interface{}) (*sqlx.Rows, error) { +func (w *sqlxTxWrapper) QueryX(query string, args ...any) (*sqlx.Rows, error) { query = w.Tx.Rebind(query) ctx, cancel := context.WithTimeout(context.Background(), w.queryTimeout) defer cancel() @@ -413,7 +413,7 @@ func (w *sqlxTxWrapper) QueryX(query string, args ...interface{}) (*sqlx.Rows, e return w.Tx.QueryxContext(ctx, query, args) } -func (w *sqlxTxWrapper) Select(dest interface{}, query string, args ...interface{}) error { +func (w *sqlxTxWrapper) Select(dest any, query string, args ...any) error { query = w.Tx.Rebind(query) ctx, cancel := context.WithTimeout(context.Background(), w.queryTimeout) defer cancel() @@ -427,7 +427,7 @@ func (w *sqlxTxWrapper) Select(dest interface{}, query string, args ...interface return w.Tx.SelectContext(ctx, dest, query, args...) } -func (w *sqlxTxWrapper) SelectBuilder(dest interface{}, builder Builder) error { +func (w *sqlxTxWrapper) SelectBuilder(dest any, builder Builder) error { query, args, err := builder.ToSql() if err != nil { return err @@ -446,7 +446,7 @@ func removeSpace(r rune) rune { return r } -func printArgs(query string, dur time.Duration, args ...interface{}) { +func printArgs(query string, dur time.Duration, args ...any) { query = strings.Map(removeSpace, query) fields := make([]mlog.Field, 0, len(args)+1) fields = append(fields, mlog.Duration("duration", dur)) diff --git a/store/sqlstore/team_store.go b/store/sqlstore/team_store.go index b8035d46e1..5473781720 100644 --- a/store/sqlstore/team_store.go +++ b/store/sqlstore/team_store.go @@ -68,8 +68,8 @@ func teamMemberSliceColumns() []string { return []string{"TeamId", "UserId", "Roles", "DeleteAt", "SchemeUser", "SchemeAdmin", "SchemeGuest"} } -func teamMemberToSlice(member *model.TeamMember) []interface{} { - resultSlice := []interface{}{} +func teamMemberToSlice(member *model.TeamMember) []any { + resultSlice := []any{} resultSlice = append(resultSlice, member.TeamId) resultSlice = append(resultSlice, member.UserId) resultSlice = append(resultSlice, member.ExplicitRoles) @@ -1579,11 +1579,11 @@ func applyTeamMemberViewRestrictionsFilter(query sq.SelectBuilder, restrictions return query.Where("1 = 0") } - teams := make([]interface{}, len(restrictions.Teams)) + teams := make([]any, len(restrictions.Teams)) for i, v := range restrictions.Teams { teams[i] = v } - channels := make([]interface{}, len(restrictions.Channels)) + channels := make([]any, len(restrictions.Channels)) for i, v := range restrictions.Channels { channels[i] = v } @@ -1609,11 +1609,11 @@ func applyTeamMemberViewRestrictionsFilterForStats(query sq.SelectBuilder, restr return query.Where("1 = 0") } - teams := make([]interface{}, len(restrictions.Teams)) + teams := make([]any, len(restrictions.Teams)) for i, v := range restrictions.Teams { teams[i] = v } - channels := make([]interface{}, len(restrictions.Channels)) + channels := make([]any, len(restrictions.Channels)) for i, v := range restrictions.Channels { channels[i] = v } diff --git a/store/sqlstore/thread_store.go b/store/sqlstore/thread_store.go index 038d0264eb..04912c5c11 100644 --- a/store/sqlstore/thread_store.go +++ b/store/sqlstore/thread_store.go @@ -938,7 +938,7 @@ func (s *SqlThreadStore) GetThreadUnreadReplyCount(threadMembership *model.Threa // Top threads in all public channels and private channels userID is a member of. Returns a list of threads ranked by interactions. func (s *SqlThreadStore) GetTopThreadsForTeamSince(teamID string, userID string, since int64, offset int, limit int) (*model.TopThreadList, error) { - var args []interface{} + var args []any query := `select threads_list.PostId, threads_list.ReplyCount, @@ -1012,7 +1012,7 @@ func (s *SqlThreadStore) GetTopThreadsForTeamSince(teamID string, userID string, } func (s *SqlThreadStore) GetTopThreadsForUserSince(teamID string, userID string, since int64, offset int, limit int) (*model.TopThreadList, error) { - var args []interface{} + var args []any // gets all threads within the team which user follows. query := `select diff --git a/store/sqlstore/user_access_token_store.go b/store/sqlstore/user_access_token_store.go index 3b4f5b57e7..e6d4f811ed 100644 --- a/store/sqlstore/user_access_token_store.go +++ b/store/sqlstore/user_access_token_store.go @@ -174,7 +174,7 @@ func (s SqlUserAccessTokenStore) GetByUser(userId string, offset, limit int) ([] func (s SqlUserAccessTokenStore) Search(term string) ([]*model.UserAccessToken, error) { term = sanitizeSearchTerm(term, "\\") tokens := []*model.UserAccessToken{} - params := []interface{}{term, term, term} + params := []any{term, term, term} query := ` SELECT uat.* diff --git a/store/sqlstore/user_store.go b/store/sqlstore/user_store.go index 38d441001e..405172ad21 100644 --- a/store/sqlstore/user_store.go +++ b/store/sqlstore/user_store.go @@ -932,7 +932,7 @@ func (us SqlUserStore) GetProfilesByUsernames(usernames []string, viewRestrictio query = applyViewRestrictionsFilter(query, viewRestrictions, true) query = query. - Where(map[string]interface{}{ + Where(map[string]any{ "Username": usernames, }). OrderBy("u.Username ASC") @@ -1021,13 +1021,13 @@ func (us SqlUserStore) GetProfileByIds(ctx context.Context, userIds []string, op users := []*model.User{} query := us.usersQuery. - Where(map[string]interface{}{ + Where(map[string]any{ "u.Id": userIds, }). OrderBy("u.Username ASC") if options.Since > 0 { - query = query.Where(sq.Gt(map[string]interface{}{ + query = query.Where(sq.Gt(map[string]any{ "u.UpdateAt": options.Since, })) } @@ -1499,7 +1499,7 @@ func (us SqlUserStore) SearchNotInGroup(groupID string, term string, options *mo func generateSearchQuery(query sq.SelectBuilder, terms []string, fields []string, isPostgreSQL bool) sq.SelectBuilder { for _, term := range terms { searchFields := []string{} - termArgs := []interface{}{} + termArgs := []any{} for _, field := range fields { if isPostgreSQL { searchFields = append(searchFields, fmt.Sprintf("lower(%s) LIKE lower(?) escape '*' ", field)) @@ -1859,11 +1859,11 @@ func applyViewRestrictionsFilter(query sq.SelectBuilder, restrictions *model.Vie return query.Where("1 = 0") } - teams := make([]interface{}, len(restrictions.Teams)) + teams := make([]any, len(restrictions.Teams)) for i, v := range restrictions.Teams { teams[i] = v } - channels := make([]interface{}, len(restrictions.Channels)) + channels := make([]any, len(restrictions.Channels)) for i, v := range restrictions.Channels { channels[i] = v } diff --git a/store/sqlstore/utils.go b/store/sqlstore/utils.go index 160111aab5..d40694e418 100644 --- a/store/sqlstore/utils.go +++ b/store/sqlstore/utils.go @@ -33,9 +33,9 @@ func sanitizeSearchTerm(term string, escapeChar string) string { // Converts a list of strings into a list of query parameters and a named parameter map that can // be used as part of a SQL query. -func MapStringsToQueryParams(list []string, paramPrefix string) (string, map[string]interface{}) { +func MapStringsToQueryParams(list []string, paramPrefix string) (string, map[string]any) { var keys strings.Builder - params := make(map[string]interface{}, len(list)) + params := make(map[string]any, len(list)) for i, entry := range list { if keys.Len() > 0 { keys.WriteString(",") @@ -99,13 +99,13 @@ func isQuotedWord(s string) bool { // SET Col = JSON_SET(Col, `+argString+`) // WHERE Id=?`, args...) // after appending the Id param to the args slice. -func constructMySQLJSONArgs(props map[string]string) ([]interface{}, string) { +func constructMySQLJSONArgs(props map[string]string) ([]any, string) { if len(props) == 0 { return nil, "" } // Unpack the keys and values to pass to MySQL. - args := make([]interface{}, 0, len(props)) + args := make([]any, 0, len(props)) for k, v := range props { args = append(args, "$."+k, v) } @@ -118,17 +118,17 @@ func constructMySQLJSONArgs(props map[string]string) ([]interface{}, string) { return args, argString } -func makeStringArgs(params []string) []interface{} { - args := make([]interface{}, len(params)) +func makeStringArgs(params []string) []any { + args := make([]any, len(params)) for i, name := range params { args[i] = name } return args } -func constructArrayArgs(ids []string) (string, []interface{}) { +func constructArrayArgs(ids []string) (string, []any) { var placeholder strings.Builder - values := make([]interface{}, 0, len(ids)) + values := make([]any, 0, len(ids)) for _, entry := range ids { if placeholder.Len() > 0 { placeholder.WriteString(",") diff --git a/store/sqlstore/utils_test.go b/store/sqlstore/utils_test.go index 187244c40e..811ebf001a 100644 --- a/store/sqlstore/utils_test.go +++ b/store/sqlstore/utils_test.go @@ -35,7 +35,7 @@ func TestMapStringsToQueryParams(t *testing.T) { } var keys string -var params map[string]interface{} +var params map[string]any func BenchmarkMapStringsToQueryParams(b *testing.B) { b.Run("one item", func(b *testing.B) { @@ -108,7 +108,7 @@ func TestRemoveNonAlphaNumericUnquotedTerms(t *testing.T) { func TestMySQLJSONArgs(t *testing.T) { tests := []struct { props map[string]string - args []interface{} + args []any argString string }{ { @@ -117,7 +117,7 @@ func TestMySQLJSONArgs(t *testing.T) { "mobile": "android", "notify": "always", }, - args: []interface{}{"$.desktop", "linux", "$.mobile", "android", "$.notify", "always"}, + args: []any{"$.desktop", "linux", "$.mobile", "android", "$.notify", "always"}, argString: "?, ?, ?, ?, ?, ?", }, { diff --git a/store/store.go b/store/store.go index 801351add5..9feffccf27 100644 --- a/store/store.go +++ b/store/store.go @@ -14,7 +14,7 @@ import ( ) type StoreResult struct { - Data interface{} + Data any // NErr a temporary field used by the new code for the AppError migration. This will later become Err when the entire store is migrated. NErr error diff --git a/store/storetest/channel_store.go b/store/storetest/channel_store.go index a567ddff7d..bb2dae3451 100644 --- a/store/storetest/channel_store.go +++ b/store/storetest/channel_store.go @@ -30,14 +30,14 @@ type SqlStore interface { } type SqlXExecutor interface { - Get(dest interface{}, query string, args ...interface{}) error - NamedExec(query string, arg interface{}) (sql.Result, error) - Exec(query string, args ...interface{}) (sql.Result, error) - ExecRaw(query string, args ...interface{}) (sql.Result, error) - NamedQuery(query string, arg interface{}) (*sqlx.Rows, error) - QueryRowX(query string, args ...interface{}) *sqlx.Row - QueryX(query string, args ...interface{}) (*sqlx.Rows, error) - Select(dest interface{}, query string, args ...interface{}) error + Get(dest any, query string, args ...any) error + NamedExec(query string, arg any) (sql.Result, error) + Exec(query string, args ...any) (sql.Result, error) + ExecRaw(query string, args ...any) (sql.Result, error) + NamedQuery(query string, arg any) (*sqlx.Rows, error) + QueryRowX(query string, args ...any) *sqlx.Row + QueryX(query string, args ...any) (*sqlx.Rows, error) + Select(dest any, query string, args ...any) error } func cleanupChannels(t *testing.T, ss store.Store) { @@ -7337,7 +7337,7 @@ func testMaterializedPublicChannels(t *testing.T, ss store.Store, s SqlStore) { PublicChannels(Id, DeleteAt, TeamId, DisplayName, Name, Header, Purpose) VALUES (:id, :deleteat, :teamid, :displayname, :name, :header, :purpose); - `, map[string]interface{}{ + `, map[string]any{ "id": o3.Id, "deleteat": o3.DeleteAt, "teamid": o3.TeamId, @@ -7355,7 +7355,7 @@ func testMaterializedPublicChannels(t *testing.T, ss store.Store, s SqlStore) { Channels(Id, CreateAt, UpdateAt, DeleteAt, TeamId, Type, DisplayName, Name, Header, Purpose, LastPostAt, LastRootPostAt, TotalMsgCount, ExtraUpdateAt, CreatorId, TotalMsgCountRoot) VALUES (:id, :createat, :updateat, :deleteat, :teamid, :type, :displayname, :name, :header, :purpose, :lastpostat, :lastrootpostat, :totalmsgcount, :extraupdateat, :creatorid, 0); - `, map[string]interface{}{ + `, map[string]any{ "id": o3.Id, "createat": o3.CreateAt, "updateat": o3.UpdateAt, diff --git a/store/storetest/compliance_store.go b/store/storetest/compliance_store.go index a6fd060bec..b45bf3742d 100644 --- a/store/storetest/compliance_store.go +++ b/store/storetest/compliance_store.go @@ -1050,7 +1050,7 @@ func testDeleteExportMessage(t *testing.T, ss store.Store) { assert.Equal(t, postDeleteTime, *v.PostUpdateAt) assert.NotNil(t, v.PostProps) - props := map[string]interface{}{} + props := map[string]any{} e := json.Unmarshal([]byte(*v.PostProps), &props) require.NoError(t, e) @@ -1153,7 +1153,7 @@ func testDeleteAfterExportMessage(t *testing.T, ss store.Store) { assert.Equal(t, postDeleteTime, *v.PostUpdateAt) assert.NotNil(t, v.PostProps) - props := map[string]interface{}{} + props := map[string]any{} e := json.Unmarshal([]byte(*v.PostProps), &props) require.NoError(t, e) diff --git a/store/storetest/reaction_store.go b/store/storetest/reaction_store.go index 759826c89c..aa75a872ec 100644 --- a/store/storetest/reaction_store.go +++ b/store/storetest/reaction_store.go @@ -383,7 +383,7 @@ func testReactionGetForPostSince(t *testing.T, ss store.Store, s SqlStore) { } func forceUpdateAt(reaction *model.Reaction, updateAt int64, s SqlStore) error { - params := map[string]interface{}{ + params := map[string]any{ "userid": reaction.UserId, "postid": reaction.PostId, "emojiname": reaction.EmojiName, diff --git a/testlib/helper.go b/testlib/helper.go index 72418f7f41..c28d998bfd 100644 --- a/testlib/helper.go +++ b/testlib/helper.go @@ -270,7 +270,7 @@ func (h *MainHelper) SetReplicationLagForTesting(seconds int) error { return nil } -func (h *MainHelper) execOnEachReplica(query string, args ...interface{}) error { +func (h *MainHelper) execOnEachReplica(query string, args ...any) error { for _, replica := range h.SQLStore.ReplicaXs { _, err := replica.Exec(query, args...) if err != nil { diff --git a/utils/api.go b/utils/api.go index bd8a5f81ec..4680c66fb9 100644 --- a/utils/api.go +++ b/utils/api.go @@ -119,7 +119,7 @@ func RenderMobileError(config *model.Config, w http.ResponseWriter, err *model.A

`+i18n.T("error")+`

`+err.Message+`

- `+i18n.T("api.back_to_app", map[string]interface{}{"SiteName": config.TeamSettings.SiteName})+` + `+i18n.T("api.back_to_app", map[string]any{"SiteName": config.TeamSettings.SiteName})+` `) } diff --git a/utils/merge.go b/utils/merge.go index 84287b0023..073a3380b2 100644 --- a/utils/merge.go +++ b/utils/merge.go @@ -35,7 +35,7 @@ type MergeConfig struct { // retTS := ret.(testStruct) // return &retTS, nil // } -func Merge(base interface{}, patch interface{}, mergeConfig *MergeConfig) (interface{}, error) { +func Merge(base any, patch any, mergeConfig *MergeConfig) (any, error) { if reflect.TypeOf(base) != reflect.TypeOf(patch) { return nil, fmt.Errorf( "cannot merge different types. base type: %s, patch type: %s", diff --git a/utils/merge_test.go b/utils/merge_test.go index 3acb5ee8e6..956bbdf302 100644 --- a/utils/merge_test.go +++ b/utils/merge_test.go @@ -286,12 +286,12 @@ func TestMergeWithMaps(t *testing.T) { assert.Equal(t, 23, *merged["are belong"]["to us"]) }) - t.Run("merge map[string]interface{}", func(t *testing.T) { - m1 := map[string]interface{}{"this": map[string]*int{"second": newInt(99)}, + t.Run("merge map[string]any", func(t *testing.T) { + m1 := map[string]any{"this": map[string]*int{"second": newInt(99)}, "base": map[string]*int{"level": newInt(10)}} - m2 := map[string]interface{}{"this": map[string]*int{"second": newInt(77)}, + m2 := map[string]any{"this": map[string]*int{"second": newInt(77)}, "patch": map[string]*int{"level": newInt(15)}} - expected := map[string]interface{}{"this": map[string]*int{"second": newInt(77)}, + expected := map[string]any{"this": map[string]*int{"second": newInt(77)}, "patch": map[string]*int{"level": newInt(15)}} merged, err := mergeInterfaceMap(m1, m2) @@ -300,10 +300,10 @@ func TestMergeWithMaps(t *testing.T) { assert.Equal(t, expected, merged) }) - t.Run("merge map[string]interface{}, patch has nil keys -- /do/ overwrite base with nil", func(t *testing.T) { - m1 := map[string]interface{}{"this": map[string]*int{"second": newInt(99)}} - m2 := map[string]interface{}{"this": map[string]*int{"second": nil}} - expected := map[string]interface{}{"this": map[string]*int{"second": nil}} + t.Run("merge map[string]any, patch has nil keys -- /do/ overwrite base with nil", func(t *testing.T) { + m1 := map[string]any{"this": map[string]*int{"second": newInt(99)}} + m2 := map[string]any{"this": map[string]*int{"second": nil}} + expected := map[string]any{"this": map[string]*int{"second": nil}} merged, err := mergeInterfaceMap(m1, m2) require.NoError(t, err) @@ -311,12 +311,12 @@ func TestMergeWithMaps(t *testing.T) { assert.Equal(t, expected, merged) }) - t.Run("merge map[string]interface{}, patch has nil keys -- /do/ overwrite base with nil (more complex)", func(t *testing.T) { - m1 := map[string]interface{}{"this": map[string]*int{"second": newInt(99)}, + t.Run("merge map[string]any, patch has nil keys -- /do/ overwrite base with nil (more complex)", func(t *testing.T) { + m1 := map[string]any{"this": map[string]*int{"second": newInt(99)}, "base": map[string]*int{"level": newInt(10)}} - m2 := map[string]interface{}{"this": map[string]*int{"second": nil}, + m2 := map[string]any{"this": map[string]*int{"second": nil}, "base": nil, "patch": map[string]*int{"level": newInt(15)}} - expected := map[string]interface{}{"this": map[string]*int{"second": nil}, + expected := map[string]any{"this": map[string]*int{"second": nil}, "base": nil, "patch": map[string]*int{"level": newInt(15)}} merged, err := mergeInterfaceMap(m1, m2) @@ -326,9 +326,9 @@ func TestMergeWithMaps(t *testing.T) { }) t.Run("merge map[string]map[string]*int, base has nil vals -- overwrite base with patch", func(t *testing.T) { - m1 := map[string]interface{}{"base": nil} - m2 := map[string]interface{}{"base": map[string]*int{"level": newInt(10)}} - expected := map[string]interface{}{"base": map[string]*int{"level": newInt(10)}} + m1 := map[string]any{"base": nil} + m2 := map[string]any{"base": map[string]*int{"level": newInt(10)}} + expected := map[string]any{"base": map[string]*int{"level": newInt(10)}} merged, err := mergeInterfaceMap(m1, m2) require.NoError(t, err) @@ -337,10 +337,10 @@ func TestMergeWithMaps(t *testing.T) { }) t.Run("merge map[string]map[string]*int, base has nil vals -- overwrite base with patch (more complex)", func(t *testing.T) { - m1 := map[string]interface{}{"this": map[string]*int{"second": nil}, "base": nil} - m2 := map[string]interface{}{"this": map[string]*int{"second": newInt(77)}, + m1 := map[string]any{"this": map[string]*int{"second": nil}, "base": nil} + m2 := map[string]any{"this": map[string]*int{"second": newInt(77)}, "base": map[string]*int{"level": newInt(10)}, "patch": map[string]*int{"level": newInt(15)}} - expected := map[string]interface{}{"this": map[string]*int{"second": newInt(77)}, + expected := map[string]any{"this": map[string]*int{"second": newInt(77)}, "base": map[string]*int{"level": newInt(10)}, "patch": map[string]*int{"level": newInt(15)}} merged, err := mergeInterfaceMap(m1, m2) @@ -349,12 +349,12 @@ func TestMergeWithMaps(t *testing.T) { assert.Equal(t, expected, merged) }) - t.Run("merge map[string]interface{}, pointers are not copied - changes in base do not affect merged", func(t *testing.T) { - m1 := map[string]interface{}{"this": map[string]*int{"second": newInt(99)}, + t.Run("merge map[string]any, pointers are not copied - changes in base do not affect merged", func(t *testing.T) { + m1 := map[string]any{"this": map[string]*int{"second": newInt(99)}, "base": map[string]*int{"level": newInt(10)}, "are belong": map[string]*int{"to us": newInt(23)}} - m2 := map[string]interface{}{"this": map[string]*int{"second": newInt(99)}, + m2 := map[string]any{"this": map[string]*int{"second": newInt(99)}, "base": map[string]*int{"level": newInt(10)}, "are belong": map[string]*int{"to us": newInt(23)}} - expected := map[string]interface{}{"this": map[string]*int{"second": newInt(99)}, + expected := map[string]any{"this": map[string]*int{"second": newInt(99)}, "base": map[string]*int{"level": newInt(10)}, "are belong": map[string]*int{"to us": newInt(23)}} merged, err := mergeInterfaceMap(m1, m2) @@ -375,11 +375,11 @@ func TestMergeWithMaps(t *testing.T) { assert.Equal(t, 23, *merged["are belong"].(map[string]*int)["to us"]) }) - t.Run("merge map[string]interface{}, pointers are not copied - change in patch do not affect merged", func(t *testing.T) { - m1 := map[string]interface{}{"base": map[string]*int{"level": newInt(15)}} - m2 := map[string]interface{}{"this": map[string]*int{"second": newInt(99)}, + t.Run("merge map[string]any, pointers are not copied - change in patch do not affect merged", func(t *testing.T) { + m1 := map[string]any{"base": map[string]*int{"level": newInt(15)}} + m2 := map[string]any{"this": map[string]*int{"second": newInt(99)}, "patch": map[string]*int{"level": newInt(10)}, "are belong": map[string]*int{"to us": newInt(23)}} - expected := map[string]interface{}{"this": map[string]*int{"second": newInt(99)}, + expected := map[string]any{"this": map[string]*int{"second": newInt(99)}, "patch": map[string]*int{"level": newInt(10)}, "are belong": map[string]*int{"to us": newInt(23)}} merged, err := mergeInterfaceMap(m1, m2) @@ -1652,12 +1652,12 @@ func mergeMapOfMap(base, patch map[string]map[string]*int) (map[string]map[strin return retTS, nil } -func mergeInterfaceMap(base, patch map[string]interface{}) (map[string]interface{}, error) { +func mergeInterfaceMap(base, patch map[string]any) (map[string]any, error) { ret, err := utils.Merge(base, patch, nil) if err != nil { return nil, err } - retTS := ret.(map[string]interface{}) + retTS := ret.(map[string]any) return retTS, nil } diff --git a/web/context.go b/web/context.go index 4adc4f95df..292ba94619 100644 --- a/web/context.go +++ b/web/context.go @@ -254,11 +254,11 @@ func (c *Context) HandleEtag(etag string, routeName string, w http.ResponseWrite } func NewInvalidParamError(parameter string) *model.AppError { - err := model.NewAppError("Context", "api.context.invalid_body_param.app_error", map[string]interface{}{"Name": parameter}, "", http.StatusBadRequest) + err := model.NewAppError("Context", "api.context.invalid_body_param.app_error", map[string]any{"Name": parameter}, "", http.StatusBadRequest) return err } func NewInvalidURLParamError(parameter string) *model.AppError { - err := model.NewAppError("Context", "api.context.invalid_url_param.app_error", map[string]interface{}{"Name": parameter}, "", http.StatusBadRequest) + err := model.NewAppError("Context", "api.context.invalid_url_param.app_error", map[string]any{"Name": parameter}, "", http.StatusBadRequest) return err } func NewServerBusyError() *model.AppError { @@ -267,7 +267,7 @@ func NewServerBusyError() *model.AppError { } func NewInvalidRemoteIdError(parameter string) *model.AppError { - err := model.NewAppError("Context", "api.context.remote_id_invalid.app_error", map[string]interface{}{"RemoteId": parameter}, "", http.StatusBadRequest) + err := model.NewAppError("Context", "api.context.remote_id_invalid.app_error", map[string]any{"RemoteId": parameter}, "", http.StatusBadRequest) return err } diff --git a/web/unsupported_browser.go b/web/unsupported_browser.go index c0a7f41047..b38e72291b 100644 --- a/web/unsupported_browser.go +++ b/web/unsupported_browser.go @@ -47,7 +47,7 @@ type SystemBrowser struct { func renderUnsupportedBrowser(ctx *request.Context, r *http.Request) templates.Data { data := templates.Data{ - Props: map[string]interface{}{ + Props: map[string]any{ "DownloadAppOrUpgradeBrowserString": ctx.T("web.error.unsupported_browser.download_app_or_upgrade_browser"), "LearnMoreString": ctx.T("web.error.unsupported_browser.learn_more"), }, diff --git a/wsapi/status.go b/wsapi/status.go index 49c9fa887e..a6898ee9af 100644 --- a/wsapi/status.go +++ b/wsapi/status.go @@ -13,12 +13,12 @@ func (api *API) InitStatus() { api.Router.Handle("get_statuses_by_ids", api.APIWebSocketHandler(api.getStatusesByIds)) } -func (api *API) getStatuses(req *model.WebSocketRequest) (map[string]interface{}, *model.AppError) { +func (api *API) getStatuses(req *model.WebSocketRequest) (map[string]any, *model.AppError) { statusMap := api.App.GetAllStatuses() return model.StatusMapToInterfaceMap(statusMap), nil } -func (api *API) getStatusesByIds(req *model.WebSocketRequest) (map[string]interface{}, *model.AppError) { +func (api *API) getStatusesByIds(req *model.WebSocketRequest) (map[string]any, *model.AppError) { var userIds []string if userIds = model.ArrayFromInterface(req.Data["user_ids"]); len(userIds) == 0 { mlog.Debug("Error while parsing user_ids", mlog.String("data", model.StringInterfaceToJSON(req.Data))) diff --git a/wsapi/system.go b/wsapi/system.go index 274836ed37..e119505f80 100644 --- a/wsapi/system.go +++ b/wsapi/system.go @@ -11,8 +11,8 @@ func (api *API) InitSystem() { api.Router.Handle("ping", api.APIWebSocketHandler(ping)) } -func ping(req *model.WebSocketRequest) (map[string]interface{}, *model.AppError) { - data := map[string]interface{}{} +func ping(req *model.WebSocketRequest) (map[string]any, *model.AppError) { + data := map[string]any{} data["text"] = "pong" data["version"] = model.CurrentVersion data["server_time"] = model.GetMillis() diff --git a/wsapi/user.go b/wsapi/user.go index 245f8bef3d..e3f24dd397 100644 --- a/wsapi/user.go +++ b/wsapi/user.go @@ -12,7 +12,7 @@ func (api *API) InitUser() { api.Router.Handle("user_update_active_status", api.APIWebSocketHandler(api.userUpdateActiveStatus)) } -func (api *API) userTyping(req *model.WebSocketRequest) (map[string]interface{}, *model.AppError) { +func (api *API) userTyping(req *model.WebSocketRequest) (map[string]any, *model.AppError) { api.App.ExtendSessionExpiryIfNeeded(&req.Session) if api.App.Srv().Busy.IsBusy() { @@ -40,7 +40,7 @@ func (api *API) userTyping(req *model.WebSocketRequest) (map[string]interface{}, return nil, appErr } -func (api *API) userUpdateActiveStatus(req *model.WebSocketRequest) (map[string]interface{}, *model.AppError) { +func (api *API) userUpdateActiveStatus(req *model.WebSocketRequest) (map[string]any, *model.AppError) { var ok bool var userIsActive bool if userIsActive, ok = req.Data["user_is_active"].(bool); !ok { diff --git a/wsapi/websocket_handler.go b/wsapi/websocket_handler.go index 9f25325f01..53bd397955 100644 --- a/wsapi/websocket_handler.go +++ b/wsapi/websocket_handler.go @@ -12,13 +12,13 @@ import ( "github.com/mattermost/mattermost-server/v6/shared/mlog" ) -func (api *API) APIWebSocketHandler(wh func(*model.WebSocketRequest) (map[string]interface{}, *model.AppError)) webSocketHandler { +func (api *API) APIWebSocketHandler(wh func(*model.WebSocketRequest) (map[string]any, *model.AppError)) webSocketHandler { return webSocketHandler{api.App, wh} } type webSocketHandler struct { app *app.App - handlerFunc func(*model.WebSocketRequest) (map[string]interface{}, *model.AppError) + handlerFunc func(*model.WebSocketRequest) (map[string]any, *model.AppError) } func (wh webSocketHandler) ServeWebSocket(conn *app.WebConn, r *model.WebSocketRequest) { @@ -50,7 +50,7 @@ func (wh webSocketHandler) ServeWebSocket(conn *app.WebConn, r *model.WebSocketR r.T = conn.T r.Locale = conn.Locale - var data map[string]interface{} + var data map[string]any var err *model.AppError if data, err = wh.handlerFunc(r); err != nil { @@ -73,7 +73,7 @@ func (wh webSocketHandler) ServeWebSocket(conn *app.WebConn, r *model.WebSocketR } func NewInvalidWebSocketParamError(action string, name string) *model.AppError { - return model.NewAppError("websocket: "+action, "api.websocket_handler.invalid_param.app_error", map[string]interface{}{"Name": name}, "", http.StatusBadRequest) + return model.NewAppError("websocket: "+action, "api.websocket_handler.invalid_param.app_error", map[string]any{"Name": name}, "", http.StatusBadRequest) } func NewServerBusyWebSocketError(action string) *model.AppError {