From 6487d0ca91c66cfe292301585901ac5f84f776e5 Mon Sep 17 00:00:00 2001 From: Agniva De Sarker Date: Tue, 22 Dec 2020 19:20:59 +0530 Subject: [PATCH] MM-31062: Rewrite empty string checks to be more idiomatic (#16587) https://mattermost.atlassian.net/browse/MM-31062 ```release-note NONE ``` --- api4/channel.go | 2 +- api4/config_test.go | 8 ++++---- api4/user.go | 8 ++++---- app/channel.go | 6 +++--- app/command.go | 12 ++++++------ app/login.go | 2 +- app/notification.go | 4 ++-- app/notification_email.go | 2 +- app/oauth.go | 6 +++--- app/team.go | 2 +- app/user.go | 2 +- app/webhook.go | 10 +++++----- model/command_webhook.go | 4 ++-- model/config.go | 4 ++-- model/file_info.go | 2 +- model/outgoing_webhook.go | 2 +- model/scheme.go | 6 +++--- model/search_params.go | 8 ++++---- store/localcachelayer/role_layer.go | 2 +- store/localcachelayer/scheme_layer.go | 2 +- store/sqlstore/audit_store.go | 2 +- store/sqlstore/group_store.go | 2 +- store/sqlstore/user_store.go | 2 +- web/handlers.go | 4 ++-- web/saml.go | 4 ++-- 25 files changed, 54 insertions(+), 54 deletions(-) diff --git a/api4/channel.go b/api4/channel.go index df262cb524..7b7ecef117 100644 --- a/api4/channel.go +++ b/api4/channel.go @@ -1447,7 +1447,7 @@ func addChannelMember(c *Context, w http.ResponseWriter, r *http.Request) { } postRootId, ok := props["post_root_id"].(string) - if ok && len(postRootId) != 0 && !model.IsValidId(postRootId) { + if ok && postRootId != "" && !model.IsValidId(postRootId) { c.SetInvalidParam("post_root_id") return } diff --git a/api4/config_test.go b/api4/config_test.go index 7b3dcbc889..944435cfbe 100644 --- a/api4/config_test.go +++ b/api4/config_test.go @@ -29,18 +29,18 @@ func TestGetConfig(t *testing.T) { require.NotEqual(t, "", cfg.TeamSettings.SiteName) - if *cfg.LdapSettings.BindPassword != model.FAKE_SETTING && len(*cfg.LdapSettings.BindPassword) != 0 { + if *cfg.LdapSettings.BindPassword != model.FAKE_SETTING && *cfg.LdapSettings.BindPassword != "" { require.FailNow(t, "did not sanitize properly") } require.Equal(t, model.FAKE_SETTING, *cfg.FileSettings.PublicLinkSalt, "did not sanitize properly") - if *cfg.FileSettings.AmazonS3SecretAccessKey != model.FAKE_SETTING && len(*cfg.FileSettings.AmazonS3SecretAccessKey) != 0 { + if *cfg.FileSettings.AmazonS3SecretAccessKey != model.FAKE_SETTING && *cfg.FileSettings.AmazonS3SecretAccessKey != "" { require.FailNow(t, "did not sanitize properly") } - if *cfg.EmailSettings.SMTPPassword != model.FAKE_SETTING && len(*cfg.EmailSettings.SMTPPassword) != 0 { + if *cfg.EmailSettings.SMTPPassword != model.FAKE_SETTING && *cfg.EmailSettings.SMTPPassword != "" { require.FailNow(t, "did not sanitize properly") } - if *cfg.GitLabSettings.Secret != model.FAKE_SETTING && len(*cfg.GitLabSettings.Secret) != 0 { + if *cfg.GitLabSettings.Secret != model.FAKE_SETTING && *cfg.GitLabSettings.Secret != "" { require.FailNow(t, "did not sanitize properly") } require.Equal(t, model.FAKE_SETTING, *cfg.SqlSettings.DataSource, "did not sanitize properly") diff --git a/api4/user.go b/api4/user.go index b4a9c2dbd2..f5aa8eafdb 100644 --- a/api4/user.go +++ b/api4/user.go @@ -559,7 +559,7 @@ func getFilteredUsersStats(c *Context, w http.ResponseWriter, r *http.Request) { } } channelRoles := []string{} - if channelRolesString != "" && len(channelID) != 0 { + if channelRolesString != "" && channelID != "" { channelRoles, rolesValid = model.CleanRoleNames(strings.Split(channelRolesString, ",")) if !rolesValid { c.SetInvalidParam("channelRoles") @@ -567,7 +567,7 @@ func getFilteredUsersStats(c *Context, w http.ResponseWriter, r *http.Request) { } } teamRoles := []string{} - if teamRolesString != "" && len(teamID) != 0 { + if teamRolesString != "" && teamID != "" { teamRoles, rolesValid = model.CleanRoleNames(strings.Split(teamRolesString, ",")) if !rolesValid { c.SetInvalidParam("teamRoles") @@ -673,7 +673,7 @@ func getUsers(c *Context, w http.ResponseWriter, r *http.Request) { } } channelRoles := []string{} - if channelRolesString != "" && len(inChannelId) != 0 { + if channelRolesString != "" && inChannelId != "" { channelRoles, rolesValid = model.CleanRoleNames(strings.Split(channelRolesString, ",")) if !rolesValid { c.SetInvalidParam("channelRoles") @@ -681,7 +681,7 @@ func getUsers(c *Context, w http.ResponseWriter, r *http.Request) { } } teamRoles := []string{} - if teamRolesString != "" && len(inTeamId) != 0 { + if teamRolesString != "" && inTeamId != "" { teamRoles, rolesValid = model.CleanRoleNames(strings.Split(teamRolesString, ",")) if !rolesValid { c.SetInvalidParam("teamRoles") diff --git a/app/channel.go b/app/channel.go index f3749a7bcc..07f43e9f8f 100644 --- a/app/channel.go +++ b/app/channel.go @@ -629,7 +629,7 @@ func (a *App) CreateChannelScheme(channel *model.Channel) (*model.Scheme, *model // DeleteChannelScheme deletes a channels scheme and sets its SchemeId to nil. func (a *App) DeleteChannelScheme(channel *model.Channel) (*model.Channel, *model.AppError) { - if channel.SchemeId != nil && len(*channel.SchemeId) != 0 { + if channel.SchemeId != nil && *channel.SchemeId != "" { if _, err := a.DeleteScheme(*channel.SchemeId); err != nil { return nil, err } @@ -784,7 +784,7 @@ func (a *App) GetSchemeRolesForChannel(channelId string) (guestRoleName, userRol return } - if channel.SchemeId != nil && len(*channel.SchemeId) != 0 { + if channel.SchemeId != nil && *channel.SchemeId != "" { var scheme *model.Scheme scheme, err = a.GetScheme(*channel.SchemeId) if err != nil { @@ -808,7 +808,7 @@ func (a *App) GetTeamSchemeChannelRoles(teamId string) (guestRoleName, userRoleN return } - if team.SchemeId != nil && len(*team.SchemeId) != 0 { + if team.SchemeId != nil && *team.SchemeId != "" { var scheme *model.Scheme scheme, err = a.GetScheme(*team.SchemeId) if err != nil { diff --git a/app/command.go b/app/command.go index 6c464709ea..811497c974 100644 --- a/app/command.go +++ b/app/command.go @@ -520,7 +520,7 @@ func (a *App) DoCommandRequest(cmd *model.Command, p url.Values) (*model.Command func (a *App) HandleCommandResponse(command *model.Command, args *model.CommandArgs, response *model.CommandResponse, builtIn bool) (*model.CommandResponse, *model.AppError) { trigger := "" - if len(args.Command) != 0 { + if args.Command != "" { parts := strings.Split(args.Command, " ") trigger = parts[0][1:] trigger = strings.ToLower(trigger) @@ -561,7 +561,7 @@ func (a *App) HandleCommandResponsePost(command *model.Command, args *model.Comm post.Type = response.Type post.SetProps(response.Props) - if len(response.ChannelId) != 0 { + if response.ChannelId != "" { _, err := a.GetChannelMember(response.ChannelId, args.UserId) if err != nil { err = model.NewAppError("HandleCommandResponsePost", "api.command.command_post.forbidden.app_error", nil, err.Error(), http.StatusForbidden) @@ -573,20 +573,20 @@ func (a *App) HandleCommandResponsePost(command *model.Command, args *model.Comm isBotPost := !builtIn if *a.Config().ServiceSettings.EnablePostUsernameOverride { - if len(command.Username) != 0 { + if command.Username != "" { post.AddProp("override_username", command.Username) isBotPost = true - } else if len(response.Username) != 0 { + } else if response.Username != "" { post.AddProp("override_username", response.Username) isBotPost = true } } if *a.Config().ServiceSettings.EnablePostIconOverride { - if len(command.IconURL) != 0 { + if command.IconURL != "" { post.AddProp("override_icon_url", command.IconURL) isBotPost = true - } else if len(response.IconURL) != 0 { + } else if response.IconURL != "" { post.AddProp("override_icon_url", response.IconURL) isBotPost = true } else { diff --git a/app/login.go b/app/login.go index 2ee7a6289a..28425fe1ce 100644 --- a/app/login.go +++ b/app/login.go @@ -122,7 +122,7 @@ func (a *App) GetUserForLogin(id, loginId string) (*model.User, *model.AppError) enableEmail := *a.Config().EmailSettings.EnableSignInWithEmail // If we are given a userID then fail if we can't find a user with that ID - if len(id) != 0 { + if id != "" { user, err := a.GetUser(id) if err != nil { if err.Id != MISSING_ACCOUNT_ERROR { diff --git a/app/notification.go b/app/notification.go index 65a093ee66..1e728ae0eb 100644 --- a/app/notification.go +++ b/app/notification.go @@ -780,10 +780,10 @@ func getMentionsEnabledFields(post *model.Post) model.StringArray { ret = append(ret, post.Message) for _, attachment := range post.Attachments() { - if len(attachment.Pretext) != 0 { + if attachment.Pretext != "" { ret = append(ret, attachment.Pretext) } - if len(attachment.Text) != 0 { + if attachment.Text != "" { ret = append(ret, attachment.Text) } } diff --git a/app/notification_email.go b/app/notification_email.go index e14eb794b5..efe995cfd6 100644 --- a/app/notification_email.go +++ b/app/notification_email.go @@ -314,7 +314,7 @@ func (a *App) generateHyperlinkForChannels(postMessage, teamName, teamURL string } func (s *Server) GetMessageForNotification(post *model.Post, translateFunc i18n.TranslateFunc) string { - if len(strings.TrimSpace(post.Message)) != 0 || len(post.FileIds) == 0 { + if strings.TrimSpace(post.Message) != "" || len(post.FileIds) == 0 { return post.Message } diff --git a/app/oauth.go b/app/oauth.go index cfb6eedf1a..f206399287 100644 --- a/app/oauth.go +++ b/app/oauth.go @@ -415,11 +415,11 @@ func (a *App) newSessionUpdateToken(appName string, accessData *model.AccessData func (a *App) GetOAuthLoginEndpoint(w http.ResponseWriter, r *http.Request, service, teamId, action, redirectTo, loginHint string, isMobile bool) (string, *model.AppError) { stateProps := map[string]string{} stateProps["action"] = action - if len(teamId) != 0 { + if teamId != "" { stateProps["team_id"] = teamId } - if len(redirectTo) != 0 { + if redirectTo != "" { stateProps["redirect_to"] = redirectTo } @@ -436,7 +436,7 @@ func (a *App) GetOAuthLoginEndpoint(w http.ResponseWriter, r *http.Request, serv func (a *App) GetOAuthSignupEndpoint(w http.ResponseWriter, r *http.Request, service, teamId string) (string, *model.AppError) { stateProps := map[string]string{} stateProps["action"] = model.OAUTH_ACTION_SIGNUP - if len(teamId) != 0 { + if teamId != "" { stateProps["team_id"] = teamId } diff --git a/app/team.go b/app/team.go index ff05d36f62..3bcb24fd11 100644 --- a/app/team.go +++ b/app/team.go @@ -342,7 +342,7 @@ func (a *App) GetSchemeRolesForTeam(teamId string) (string, string, string, *mod return "", "", "", err } - if team.SchemeId != nil && len(*team.SchemeId) != 0 { + if team.SchemeId != nil && *team.SchemeId != "" { scheme, err := a.GetScheme(*team.SchemeId) if err != nil { return "", "", "", err diff --git a/app/user.go b/app/user.go index 5d305a1c1c..f23e966375 100644 --- a/app/user.go +++ b/app/user.go @@ -1497,7 +1497,7 @@ func (a *App) SendPasswordReset(email string, siteURL string) (bool, *model.AppE return false, nil } - if user.AuthData != nil && len(*user.AuthData) != 0 { + if user.AuthData != nil && *user.AuthData != "" { return false, model.NewAppError("SendPasswordReset", "api.user.send_password_reset.sso.app_error", nil, "userId="+user.Id, http.StatusBadRequest) } diff --git a/app/webhook.go b/app/webhook.go index 0eaa5f9128..34e468376d 100644 --- a/app/webhook.go +++ b/app/webhook.go @@ -264,7 +264,7 @@ func (a *App) CreateWebhookPost(userId string, channel *model.Channel, text, ove } if *a.Config().ServiceSettings.EnablePostUsernameOverride { - if len(overrideUsername) != 0 { + if overrideUsername != "" { post.AddProp("override_username", overrideUsername) } else { post.AddProp("override_username", model.DEFAULT_WEBHOOK_USERNAME) @@ -272,10 +272,10 @@ func (a *App) CreateWebhookPost(userId string, channel *model.Channel, text, ove } if *a.Config().ServiceSettings.EnablePostIconOverride { - if len(overrideIconUrl) != 0 { + if overrideIconUrl != "" { post.AddProp("override_icon_url", overrideIconUrl) } - if len(overrideIconEmoji) != 0 { + if overrideIconEmoji != "" { post.AddProp("override_icon_emoji", overrideIconEmoji) } } @@ -445,7 +445,7 @@ func (a *App) CreateOutgoingWebhook(hook *model.OutgoingWebhook) (*model.Outgoin return nil, model.NewAppError("CreateOutgoingWebhook", "api.outgoing_webhook.disabled.app_error", nil, "", http.StatusNotImplemented) } - if len(hook.ChannelId) != 0 { + if hook.ChannelId != "" { channel, errCh := a.Srv().Store.Channel().Get(hook.ChannelId, true) if errCh != nil { var nfErr *store.ErrNotFound @@ -696,7 +696,7 @@ func (a *App) HandleIncomingWebhook(hookId string, req *model.IncomingWebhookReq var channel *model.Channel var cchan chan store.StoreResult - if len(channelName) != 0 { + if channelName != "" { if channelName[0] == '@' { result, nErr := a.Srv().Store.User().GetByUsername(channelName[1:]) if nErr != nil { diff --git a/model/command_webhook.go b/model/command_webhook.go index 42a16cc72b..3757ecc79a 100644 --- a/model/command_webhook.go +++ b/model/command_webhook.go @@ -53,11 +53,11 @@ func (o *CommandWebhook) IsValid() *AppError { return NewAppError("CommandWebhook.IsValid", "model.command_hook.channel_id.app_error", nil, "", http.StatusBadRequest) } - if len(o.RootId) != 0 && !IsValidId(o.RootId) { + if o.RootId != "" && !IsValidId(o.RootId) { return NewAppError("CommandWebhook.IsValid", "model.command_hook.root_id.app_error", nil, "", http.StatusBadRequest) } - if len(o.ParentId) != 0 && !IsValidId(o.ParentId) { + if o.ParentId != "" && !IsValidId(o.ParentId) { return NewAppError("CommandWebhook.IsValid", "model.command_hook.parent_id.app_error", nil, "", http.StatusBadRequest) } diff --git a/model/config.go b/model/config.go index a5a78af389..8e4553ff7d 100644 --- a/model/config.go +++ b/model/config.go @@ -3484,13 +3484,13 @@ func (s *ServiceSettings) isValid() *AppError { return NewAppError("Config.IsValid", "model.config.is_valid.login_attempts.app_error", nil, "", http.StatusBadRequest) } - if len(*s.SiteURL) != 0 { + if *s.SiteURL != "" { if _, err := url.ParseRequestURI(*s.SiteURL); err != nil { return NewAppError("Config.IsValid", "model.config.is_valid.site_url.app_error", nil, "", http.StatusBadRequest) } } - if len(*s.WebsocketURL) != 0 { + if *s.WebsocketURL != "" { if _, err := url.ParseRequestURI(*s.WebsocketURL); err != nil { return NewAppError("Config.IsValid", "model.config.is_valid.websocket_url.app_error", nil, "", http.StatusBadRequest) } diff --git a/model/file_info.go b/model/file_info.go index e22cc09e82..b1a4232032 100644 --- a/model/file_info.go +++ b/model/file_info.go @@ -114,7 +114,7 @@ func (fi *FileInfo) IsValid() *AppError { return NewAppError("FileInfo.IsValid", "model.file_info.is_valid.user_id.app_error", nil, "id="+fi.Id, http.StatusBadRequest) } - if len(fi.PostId) != 0 && !IsValidId(fi.PostId) { + if fi.PostId != "" && !IsValidId(fi.PostId) { return NewAppError("FileInfo.IsValid", "model.file_info.is_valid.post_id.app_error", nil, "id="+fi.Id, http.StatusBadRequest) } diff --git a/model/outgoing_webhook.go b/model/outgoing_webhook.go index d6cb213833..d637935c63 100644 --- a/model/outgoing_webhook.go +++ b/model/outgoing_webhook.go @@ -140,7 +140,7 @@ func (o *OutgoingWebhook) IsValid() *AppError { return NewAppError("OutgoingWebhook.IsValid", "model.outgoing_hook.is_valid.user_id.app_error", nil, "", http.StatusBadRequest) } - if len(o.ChannelId) != 0 && !IsValidId(o.ChannelId) { + if o.ChannelId != "" && !IsValidId(o.ChannelId) { return NewAppError("OutgoingWebhook.IsValid", "model.outgoing_hook.is_valid.channel_id.app_error", nil, "", http.StatusBadRequest) } diff --git a/model/scheme.go b/model/scheme.go index 55b7a5828e..a510418bfc 100644 --- a/model/scheme.go +++ b/model/scheme.go @@ -159,15 +159,15 @@ func (scheme *Scheme) IsValidForCreate() bool { } if scheme.Scope == SCHEME_SCOPE_CHANNEL { - if len(scheme.DefaultTeamAdminRole) != 0 { + if scheme.DefaultTeamAdminRole != "" { return false } - if len(scheme.DefaultTeamUserRole) != 0 { + if scheme.DefaultTeamUserRole != "" { return false } - if len(scheme.DefaultTeamGuestRole) != 0 { + if scheme.DefaultTeamGuestRole != "" { return false } } diff --git a/model/search_params.go b/model/search_params.go index d34c8865e9..bf562a6bed 100644 --- a/model/search_params.go +++ b/model/search_params.go @@ -214,7 +214,7 @@ func parseSearchFlags(input []string) ([]searchWord, []flag) { // and remove extra pound #s word = hashtagStart.ReplaceAllString(word, "#") - if len(word) != 0 { + if word != "" { words = append(words, searchWord{ word, exclude, @@ -345,9 +345,9 @@ func ParseSearchParams(text string, timeZoneOffset int) []*SearchParams { len(excludedPlainTerms) == 0 && len(excludedHashtagTerms) == 0 && (len(inChannels) != 0 || len(fromUsers) != 0 || len(excludedChannels) != 0 || len(excludedUsers) != 0 || - len(afterDate) != 0 || len(excludedAfterDate) != 0 || - len(beforeDate) != 0 || len(excludedBeforeDate) != 0 || - len(onDate) != 0 || len(excludedDate) != 0) { + afterDate != "" || excludedAfterDate != "" || + beforeDate != "" || excludedBeforeDate != "" || + onDate != "" || excludedDate != "") { paramsList = append(paramsList, &SearchParams{ Terms: "", ExcludedTerms: "", diff --git a/store/localcachelayer/role_layer.go b/store/localcachelayer/role_layer.go index da8bfdad8b..bc047d5a66 100644 --- a/store/localcachelayer/role_layer.go +++ b/store/localcachelayer/role_layer.go @@ -33,7 +33,7 @@ func (s *LocalCacheRoleStore) handleClusterInvalidateRolePermissions(msg *model. } func (s LocalCacheRoleStore) Save(role *model.Role) (*model.Role, error) { - if len(role.Name) != 0 { + if role.Name != "" { defer s.rootStore.doInvalidateCacheCluster(s.rootStore.roleCache, role.Name) defer s.rootStore.doClearCacheCluster(s.rootStore.rolePermissionsCache) } diff --git a/store/localcachelayer/scheme_layer.go b/store/localcachelayer/scheme_layer.go index bb213f8406..f9a5de8362 100644 --- a/store/localcachelayer/scheme_layer.go +++ b/store/localcachelayer/scheme_layer.go @@ -22,7 +22,7 @@ func (s *LocalCacheSchemeStore) handleClusterInvalidateScheme(msg *model.Cluster } func (s LocalCacheSchemeStore) Save(scheme *model.Scheme) (*model.Scheme, error) { - if len(scheme.Id) != 0 { + if scheme.Id != "" { defer s.rootStore.doInvalidateCacheCluster(s.rootStore.schemeCache, scheme.Id) } return s.SchemeStore.Save(scheme) diff --git a/store/sqlstore/audit_store.go b/store/sqlstore/audit_store.go index bcdf2ec7df..12278ac44a 100644 --- a/store/sqlstore/audit_store.go +++ b/store/sqlstore/audit_store.go @@ -57,7 +57,7 @@ func (s SqlAuditStore) Get(userId string, offset int, limit int) (model.Audits, Limit(uint64(limit)). Offset(uint64(offset)) - if len(userId) != 0 { + if userId != "" { query = query.Where(sq.Eq{"UserId": userId}) } diff --git a/store/sqlstore/group_store.go b/store/sqlstore/group_store.go index fb41d033bf..8600add275 100644 --- a/store/sqlstore/group_store.go +++ b/store/sqlstore/group_store.go @@ -91,7 +91,7 @@ func (s *SqlGroupStore) createIndexesIfNotExists() { } func (s *SqlGroupStore) Create(group *model.Group) (*model.Group, error) { - if len(group.Id) != 0 { + if group.Id != "" { return nil, store.NewErrInvalidInput("Group", "id", group.Id) } diff --git a/store/sqlstore/user_store.go b/store/sqlstore/user_store.go index 298de5020b..b82889e5f3 100644 --- a/store/sqlstore/user_store.go +++ b/store/sqlstore/user_store.go @@ -286,7 +286,7 @@ func (us SqlUserStore) UpdateAuthData(userId string, service string, authData *s AuthService = :AuthService, AuthData = :AuthData` - if len(email) != 0 { + if email != "" { query += ", Email = lower(:Email)" } diff --git a/web/handlers.go b/web/handlers.go index af8fa69e76..e7b242d98a 100644 --- a/web/handlers.go +++ b/web/handlers.go @@ -188,7 +188,7 @@ func (h Handler) ServeHTTP(w http.ResponseWriter, r *http.Request) { token, tokenLocation := app.ParseAuthTokenFromRequest(r) - if len(token) != 0 && tokenLocation != app.TokenLocationCloudHeader { + if token != "" && tokenLocation != app.TokenLocationCloudHeader { session, err := c.App.GetSession(token) if err != nil { c.Log.Info("Invalid session", mlog.Err(err)) @@ -210,7 +210,7 @@ func (h Handler) ServeHTTP(w http.ResponseWriter, r *http.Request) { } h.checkCSRFToken(c, r, token, tokenLocation, session) - } else if len(token) != 0 && c.App.Srv().License() != nil && *c.App.Srv().License().Features.Cloud && tokenLocation == app.TokenLocationCloudHeader { + } else if token != "" && c.App.Srv().License() != nil && *c.App.Srv().License().Features.Cloud && tokenLocation == app.TokenLocationCloudHeader { // Check to see if this provided token matches our CWS Token session, err := c.App.GetCloudSession(token) if err != nil { diff --git a/web/saml.go b/web/saml.go index 5d3f609351..2a5a09d33b 100644 --- a/web/saml.go +++ b/web/saml.go @@ -38,7 +38,7 @@ func loginWithSaml(c *Context, w http.ResponseWriter, r *http.Request) { relayProps := map[string]string{} relayState := "" - if len(action) != 0 { + if action != "" { relayProps["team_id"] = teamId relayProps["action"] = action if action == model.OAUTH_ACTION_EMAIL_TO_SSO { @@ -46,7 +46,7 @@ func loginWithSaml(c *Context, w http.ResponseWriter, r *http.Request) { } } - if len(redirectTo) != 0 { + if redirectTo != "" { relayProps["redirect_to"] = redirectTo }