From 94c24eea20c2e19dbf187771244bab3c4364d729 Mon Sep 17 00:00:00 2001 From: Madhav Hugar <16546715+madhavhugar@users.noreply.github.com> Date: Mon, 25 Jan 2021 11:15:17 +0100 Subject: [PATCH] Fix empty string comparison issues in the codebase (#16686) Automatic Merge --- api4/channel.go | 8 +-- api4/command.go | 2 +- api4/config.go | 2 +- api4/file.go | 4 +- api4/file_test.go | 2 +- api4/group.go | 2 +- api4/ldap.go | 2 +- api4/openGraph.go | 2 +- api4/post.go | 20 +++--- api4/reaction.go | 2 +- api4/system.go | 2 +- api4/team.go | 4 +- api4/user.go | 62 +++++++++---------- api4/user_local.go | 14 ++--- api4/webhook.go | 6 +- api4/websocket.go | 2 +- app/admin.go | 2 +- app/app.go | 2 +- app/brand.go | 4 +- app/channel.go | 16 ++--- app/email.go | 4 +- app/emoji.go | 8 +-- app/file.go | 4 +- app/import_functions.go | 14 ++--- app/import_validators.go | 14 ++--- app/integration_action_test.go | 2 +- app/login.go | 6 +- app/notification.go | 8 +-- app/oauth.go | 10 +-- app/permissions.go | 4 +- app/plugin_api.go | 2 +- app/plugin_api_test.go | 16 ++--- app/post.go | 6 +- app/security_update_check.go | 2 +- app/slashcommands/command_channel_header.go | 2 +- app/slashcommands/command_channel_purpose.go | 2 +- app/slashcommands/command_channel_rename.go | 2 +- app/slashcommands/command_code.go | 2 +- app/slashcommands/command_echo.go | 2 +- app/slashcommands/command_groupmsg.go | 2 +- app/slashcommands/command_loadtest.go | 4 +- app/slashcommands/command_msg.go | 2 +- app/slashcommands/command_mute.go | 2 +- app/slashcommands/command_remove.go | 2 +- app/slashcommands/command_shrug.go | 2 +- app/svg.go | 2 +- app/team.go | 8 +-- app/user.go | 8 +-- app/web_hub.go | 2 +- app/webhook.go | 6 +- cmd/mattermost/commands/user.go | 6 +- config/utils.go | 2 +- jobs/jobs.go | 2 +- migrations/advanced_permissions_phase_2.go | 2 +- model/access.go | 6 +- model/authorize.go | 8 +-- model/bot.go | 2 +- model/client4.go | 26 ++++---- model/cluster_discovery.go | 12 ++-- model/command.go | 2 +- model/compliance.go | 2 +- model/config.go | 64 ++++++++++---------- model/emoji.go | 2 +- model/group.go | 2 +- model/guest_invite.go | 2 +- model/license.go | 2 +- model/oauth.go | 8 +-- model/outgoing_webhook.go | 8 +-- model/plugin_key_value.go | 4 +- model/post.go | 8 +-- model/preference.go | 2 +- model/reaction.go | 2 +- model/role.go | 4 +- model/scheme.go | 2 +- model/search_params.go | 8 +-- model/session.go | 2 +- model/team.go | 6 +- model/user.go | 26 ++++---- model/utils.go | 4 +- plugin/helpers_plugin.go | 4 +- services/filesstore/s3store.go | 6 +- services/mailservice/mail.go | 6 +- services/mailservice/mail_test.go | 4 +- services/mfa/mfa.go | 2 +- services/searchengine/bleveengine/search.go | 8 +-- services/telemetry/telemetry.go | 2 +- store/sqlstore/channel_store.go | 12 ++-- store/sqlstore/command_store.go | 4 +- store/sqlstore/command_webhook_store.go | 2 +- store/sqlstore/file_info_store.go | 12 ++-- store/sqlstore/group_store.go | 6 +- store/sqlstore/oauth_store.go | 2 +- store/sqlstore/post_store.go | 44 +++++++------- store/sqlstore/role_store.go | 2 +- store/sqlstore/scheme_store.go | 6 +- store/sqlstore/session_store.go | 2 +- store/sqlstore/store.go | 2 +- store/sqlstore/team_store.go | 6 +- store/sqlstore/terms_of_service_store.go | 2 +- store/sqlstore/user_store.go | 2 +- store/sqlstore/webhook_store.go | 18 +++--- utils/utils.go | 6 +- web/context.go | 20 +++--- web/handlers.go | 2 +- web/oauth.go | 10 +-- web/oauth_test.go | 6 +- web/saml.go | 2 +- 107 files changed, 368 insertions(+), 368 deletions(-) diff --git a/api4/channel.go b/api4/channel.go index f8377946fe..3591401597 100644 --- a/api4/channel.go +++ b/api4/channel.go @@ -173,13 +173,13 @@ func updateChannel(c *Context, w http.ResponseWriter, r *http.Request) { return } - if len(channel.Type) > 0 && channel.Type != oldChannel.Type { + if channel.Type != "" && channel.Type != oldChannel.Type { c.Err = model.NewAppError("updateChannel", "api.channel.update_channel.typechange.app_error", nil, "", http.StatusBadRequest) return } if oldChannel.Name == model.DEFAULT_CHANNEL { - if len(channel.Name) > 0 && channel.Name != oldChannel.Name { + if channel.Name != "" && channel.Name != oldChannel.Name { c.Err = model.NewAppError("updateChannel", "api.channel.update_channel.tried.app_error", map[string]interface{}{"Channel": model.DEFAULT_CHANNEL}, "", http.StatusBadRequest) return } @@ -190,11 +190,11 @@ func updateChannel(c *Context, w http.ResponseWriter, r *http.Request) { oldChannelDisplayName := oldChannel.DisplayName - if len(channel.DisplayName) > 0 { + if channel.DisplayName != "" { oldChannel.DisplayName = channel.DisplayName } - if len(channel.Name) > 0 { + if channel.Name != "" { oldChannel.Name = channel.Name auditRec.AddMeta("new_channel_name", oldChannel.Name) } diff --git a/api4/command.go b/api4/command.go index 32d9fc28b9..58d835840e 100644 --- a/api4/command.go +++ b/api4/command.go @@ -216,7 +216,7 @@ func listCommands(c *Context, w http.ResponseWriter, r *http.Request) { customOnly, _ := strconv.ParseBool(r.URL.Query().Get("custom_only")) teamId := r.URL.Query().Get("team_id") - if len(teamId) == 0 { + if teamId == "" { c.SetInvalidParam("team_id") return } diff --git a/api4/config.go b/api4/config.go index 7f9e9d56a2..6795956f2d 100644 --- a/api4/config.go +++ b/api4/config.go @@ -181,7 +181,7 @@ func getClientConfig(c *Context, w http.ResponseWriter, r *http.Request) { } var config map[string]string - if len(c.App.Session().UserId) == 0 { + if c.App.Session().UserId == "" { config = c.App.LimitedClientConfigWithComputed() } else { config = c.App.ClientConfigWithComputed() diff --git a/api4/file.go b/api4/file.go index c3ce6d2b34..eb68d8b26b 100644 --- a/api4/file.go +++ b/api4/file.go @@ -565,7 +565,7 @@ func getFileLink(c *Context, w http.ResponseWriter, r *http.Request) { return } - if len(info.PostId) == 0 { + if info.PostId == "" { c.Err = model.NewAppError("getPublicLink", "api.file.get_public_link.no_post.app_error", nil, "file_id="+info.Id, http.StatusBadRequest) return } @@ -658,7 +658,7 @@ func getPublicFile(c *Context, w http.ResponseWriter, r *http.Request) { hash := r.URL.Query().Get("h") - if len(hash) == 0 { + if hash == "" { c.Err = model.NewAppError("getPublicFile", "api.file.get_file.public_invalid.app_error", nil, "", http.StatusBadRequest) utils.RenderWebAppError(c.App.Config(), w, r, c.Err, c.App.AsymmetricSigningKey()) return diff --git a/api4/file_test.go b/api4/file_test.go index 9bcfb17a6f..62dba6d945 100644 --- a/api4/file_test.go +++ b/api4/file_test.go @@ -67,7 +67,7 @@ func testDoUploadFileRequest(t testing.TB, c *model.Client4, url string, blob [] req.ContentLength = contentLength } req.Header.Set("Content-Type", contentType) - if len(c.AuthToken) > 0 { + if c.AuthToken != "" { req.Header.Set(model.HEADER_AUTH, c.AuthType+" "+c.AuthToken) } diff --git a/api4/group.go b/api4/group.go index 8134d67c97..6315288f83 100644 --- a/api4/group.go +++ b/api4/group.go @@ -792,7 +792,7 @@ func getGroups(c *Context, w http.ResponseWriter, r *http.Request) { } sinceString := r.URL.Query().Get("since") - if len(sinceString) > 0 { + if sinceString != "" { since, parseError := strconv.ParseInt(sinceString, 10, 64) if parseError != nil { c.SetInvalidParam("since") diff --git a/api4/ldap.go b/api4/ldap.go index e8d6570504..69f867b8fd 100644 --- a/api4/ldap.go +++ b/api4/ldap.go @@ -271,7 +271,7 @@ func unlinkLdapGroup(c *Context, w http.ResponseWriter, r *http.Request) { func migrateIdLdap(c *Context, w http.ResponseWriter, r *http.Request) { props := model.StringInterfaceFromJson(r.Body) toAttribute, ok := props["toAttribute"].(string) - if !ok || len(toAttribute) == 0 { + if !ok || toAttribute == "" { c.SetInvalidParam("toAttribute") return } diff --git a/api4/openGraph.go b/api4/openGraph.go index eed7db7217..45b20c4de4 100644 --- a/api4/openGraph.go +++ b/api4/openGraph.go @@ -41,7 +41,7 @@ func getOpenGraphMetadata(c *Context, w http.ResponseWriter, r *http.Request) { url := "" ok := false - if url, ok = props["url"].(string); len(url) == 0 || !ok { + if url, ok = props["url"].(string); url == "" || !ok { c.SetInvalidParam("url") return } diff --git a/api4/post.go b/api4/post.go index 5a321907ea..efeaeaa4b7 100644 --- a/api4/post.go +++ b/api4/post.go @@ -136,13 +136,13 @@ func getPostsForChannel(c *Context, w http.ResponseWriter, r *http.Request) { } afterPost := r.URL.Query().Get("after") - if len(afterPost) > 0 && !model.IsValidId(afterPost) { + if afterPost != "" && !model.IsValidId(afterPost) { c.SetInvalidParam("after") return } beforePost := r.URL.Query().Get("before") - if len(beforePost) > 0 && !model.IsValidId(beforePost) { + if beforePost != "" && !model.IsValidId(beforePost) { c.SetInvalidParam("before") return } @@ -150,7 +150,7 @@ func getPostsForChannel(c *Context, w http.ResponseWriter, r *http.Request) { sinceString := r.URL.Query().Get("since") var since int64 var parseError error - if len(sinceString) > 0 { + if sinceString != "" { since, parseError = strconv.ParseInt(sinceString, 10, 64) if parseError != nil { c.SetInvalidParam("since") @@ -175,7 +175,7 @@ func getPostsForChannel(c *Context, w http.ResponseWriter, r *http.Request) { if since > 0 { list, err = c.App.GetPostsSince(model.GetPostsSinceOptions{ChannelId: channelId, Time: since, SkipFetchThreads: skipFetchThreads, CollapsedThreads: collapsedThreads, CollapsedThreadsExtended: collapsedThreadsExtended}) - } else if len(afterPost) > 0 { + } else if afterPost != "" { etag = c.App.GetPostsEtag(channelId, collapsedThreads) if c.HandleEtag(etag, "Get Posts After", w, r) { @@ -183,7 +183,7 @@ func getPostsForChannel(c *Context, w http.ResponseWriter, r *http.Request) { } list, err = c.App.GetPostsAfterPost(model.GetPostsOptions{ChannelId: channelId, PostId: afterPost, Page: page, PerPage: perPage, SkipFetchThreads: skipFetchThreads, CollapsedThreads: collapsedThreads}) - } else if len(beforePost) > 0 { + } else if beforePost != "" { etag = c.App.GetPostsEtag(channelId, collapsedThreads) if c.HandleEtag(etag, "Get Posts Before", w, r) { @@ -206,7 +206,7 @@ func getPostsForChannel(c *Context, w http.ResponseWriter, r *http.Request) { return } - if len(etag) > 0 { + if etag != "" { w.Header().Set(model.HEADER_ETAG_SERVER, etag) } @@ -269,7 +269,7 @@ func getPostsForChannelAroundLastUnread(c *Context, w http.ResponseWriter, r *ht clientPostList := c.App.PreparePostListForClient(postList) - if len(etag) > 0 { + if etag != "" { w.Header().Set(model.HEADER_ETAG_SERVER, etag) } w.Write([]byte(clientPostList.ToJson())) @@ -292,9 +292,9 @@ func getFlaggedPostsForUser(c *Context, w http.ResponseWriter, r *http.Request) var posts *model.PostList var err *model.AppError - if len(channelId) > 0 { + if channelId != "" { posts, err = c.App.GetFlaggedPostsForChannel(c.Params.UserId, channelId, c.Params.Page, c.Params.PerPage) - } else if len(teamId) > 0 { + } else if teamId != "" { posts, err = c.App.GetFlaggedPostsForTeam(c.Params.UserId, teamId, c.Params.Page, c.Params.PerPage) } else { posts, err = c.App.GetFlaggedPosts(c.Params.UserId, c.Params.Page, c.Params.PerPage) @@ -476,7 +476,7 @@ func searchPosts(c *Context, w http.ResponseWriter, r *http.Request) { return } - if params.Terms == nil || len(*params.Terms) == 0 { + if params.Terms == nil || *params.Terms == "" { c.SetInvalidParam("terms") return } diff --git a/api4/reaction.go b/api4/reaction.go index 70c00ebf97..eb2ea8902e 100644 --- a/api4/reaction.go +++ b/api4/reaction.go @@ -23,7 +23,7 @@ func saveReaction(c *Context, w http.ResponseWriter, r *http.Request) { return } - if !model.IsValidId(reaction.UserId) || !model.IsValidId(reaction.PostId) || len(reaction.EmojiName) == 0 || len(reaction.EmojiName) > model.EMOJI_NAME_MAX_LENGTH { + if !model.IsValidId(reaction.UserId) || !model.IsValidId(reaction.PostId) || reaction.EmojiName == "" || len(reaction.EmojiName) > model.EMOJI_NAME_MAX_LENGTH { c.Err = model.NewAppError("saveReaction", "api.reaction.save_reaction.invalid.app_error", nil, "", http.StatusBadRequest) return } diff --git a/api4/system.go b/api4/system.go index f482114dfd..b448d0d262 100644 --- a/api4/system.go +++ b/api4/system.go @@ -413,7 +413,7 @@ func getRedirectLocation(c *Context, w http.ResponseWriter, r *http.Request) { } url := r.URL.Query().Get("url") - if len(url) == 0 { + if url == "" { c.SetInvalidParam("url") return } diff --git a/api4/team.go b/api4/team.go index f766d399be..2d8d2dbb39 100644 --- a/api4/team.go +++ b/api4/team.go @@ -657,9 +657,9 @@ func addUserToTeamFromInvite(c *Context, w http.ResponseWriter, r *http.Request) defer c.LogAuditRec(auditRec) auditRec.AddMeta("invite_id", inviteId) - if len(tokenId) > 0 { + if tokenId != "" { member, err = c.App.AddTeamMemberByToken(c.App.Session().UserId, tokenId) - } else if len(inviteId) > 0 { + } else if inviteId != "" { if c.App.Session().Props[model.SESSION_PROP_IS_GUEST] == "true" { c.Err = model.NewAppError("addUserToTeamFromInvite", "api.team.add_user_to_team_from_invite.guest.app_error", nil, "", http.StatusForbidden) return diff --git a/api4/user.go b/api4/user.go index 23ae2f2198..eebd229392 100644 --- a/api4/user.go +++ b/api4/user.go @@ -122,7 +122,7 @@ func createUser(c *Context, w http.ResponseWriter, r *http.Request) { var ruser *model.User var err *model.AppError - if len(tokenId) > 0 { + if tokenId != "" { token, nErr := c.App.Srv().Store.Token().GetByToken(tokenId) if nErr != nil { var status int @@ -148,7 +148,7 @@ func createUser(c *Context, w http.ResponseWriter, r *http.Request) { } } ruser, err = c.App.CreateUserWithToken(user, token) - } else if len(inviteId) > 0 { + } else if inviteId != "" { ruser, err = c.App.CreateUserWithInviteId(user, inviteId, redirect) } else if c.IsSystemAdmin() { ruser, err = c.App.CreateUserAsAdmin(user, redirect) @@ -431,7 +431,7 @@ func setProfileImage(c *Context, w http.ResponseWriter, r *http.Request) { return } - if len(*c.App.Config().FileSettings.DriverName) == 0 { + if *c.App.Config().FileSettings.DriverName == "" { c.Err = model.NewAppError("uploadProfileImage", "api.user.upload_profile_user.storage.app_error", nil, "", http.StatusNotImplemented) return } @@ -491,7 +491,7 @@ func setDefaultProfileImage(c *Context, w http.ResponseWriter, r *http.Request) return } - if len(*c.App.Config().FileSettings.DriverName) == 0 { + if *c.App.Config().FileSettings.DriverName == "" { c.Err = model.NewAppError("setDefaultProfileImage", "api.user.upload_profile_user.storage.app_error", nil, "", http.StatusNotImplemented) return } @@ -633,7 +633,7 @@ func getUsers(c *Context, w http.ResponseWriter, r *http.Request) { channelRolesString := r.URL.Query().Get("channel_roles") teamRolesString := r.URL.Query().Get("team_roles") - if len(notInChannelId) > 0 && len(inTeamId) == 0 { + if notInChannelId != "" && inTeamId == "" { c.SetInvalidUrlParam("team_id") return } @@ -726,14 +726,14 @@ func getUsers(c *Context, w http.ResponseWriter, r *http.Request) { } profiles, err = c.App.GetUsersWithoutTeamPage(userGetOptions, c.IsSystemAdmin()) - } else if len(notInChannelId) > 0 { + } else if notInChannelId != "" { if !c.App.SessionHasPermissionToChannel(*c.App.Session(), notInChannelId, model.PERMISSION_READ_CHANNEL) { c.SetPermissionError(model.PERMISSION_READ_CHANNEL) return } profiles, err = c.App.GetUsersNotInChannelPage(inTeamId, notInChannelId, groupConstrainedBool, c.Params.Page, c.Params.PerPage, c.IsSystemAdmin(), restrictions) - } else if len(notInTeamId) > 0 { + } else if notInTeamId != "" { if !c.App.SessionHasPermissionToTeam(*c.App.Session(), notInTeamId, model.PERMISSION_VIEW_TEAM) { c.SetPermissionError(model.PERMISSION_VIEW_TEAM) return @@ -745,7 +745,7 @@ func getUsers(c *Context, w http.ResponseWriter, r *http.Request) { } profiles, err = c.App.GetUsersNotInTeamPage(notInTeamId, groupConstrainedBool, c.Params.Page, c.Params.PerPage, c.IsSystemAdmin(), restrictions) - } else if len(inTeamId) > 0 { + } else if inTeamId != "" { if !c.App.SessionHasPermissionToTeam(*c.App.Session(), inTeamId, model.PERMISSION_VIEW_TEAM) { c.SetPermissionError(model.PERMISSION_VIEW_TEAM) return @@ -762,7 +762,7 @@ func getUsers(c *Context, w http.ResponseWriter, r *http.Request) { } profiles, err = c.App.GetUsersInTeamPage(userGetOptions, c.IsSystemAdmin()) } - } else if len(inChannelId) > 0 { + } else if inChannelId != "" { if !c.App.SessionHasPermissionToChannel(*c.App.Session(), inChannelId, model.PERMISSION_READ_CHANNEL) { c.SetPermissionError(model.PERMISSION_READ_CHANNEL) return @@ -772,7 +772,7 @@ func getUsers(c *Context, w http.ResponseWriter, r *http.Request) { } else { profiles, err = c.App.GetUsersInChannelPage(userGetOptions, c.IsSystemAdmin()) } - } else if len(inGroupId) > 0 { + } else if inGroupId != "" { if c.App.Srv().License() == nil || !*c.App.Srv().License().Features.LDAPGroups { c.Err = model.NewAppError("Api4.getUsersInGroup", "api.ldap_groups.license_error", nil, "", http.StatusNotImplemented) return @@ -802,7 +802,7 @@ func getUsers(c *Context, w http.ResponseWriter, r *http.Request) { return } - if len(etag) > 0 { + if etag != "" { w.Header().Set(model.HEADER_ETAG_SERVER, etag) } c.App.UpdateLastActivityAtIfNeeded(*c.App.Session()) @@ -823,7 +823,7 @@ func getUsersByIds(c *Context, w http.ResponseWriter, r *http.Request) { IsAdmin: c.IsSystemAdmin(), } - if len(sinceString) > 0 { + if sinceString != "" { since, parseError := strconv.ParseInt(sinceString, 10, 64) if parseError != nil { c.SetInvalidParam("since") @@ -890,7 +890,7 @@ func searchUsers(c *Context, w http.ResponseWriter, r *http.Request) { return } - if len(props.Term) == 0 { + if props.Term == "" { c.SetInvalidParam("term") return } @@ -996,14 +996,14 @@ func autocompleteUsers(c *Context, w http.ResponseWriter, r *http.Request) { options.AllowFullNames = *c.App.Config().PrivacySettings.ShowFullName } - if len(channelId) > 0 { + if channelId != "" { if !c.App.SessionHasPermissionToChannel(*c.App.Session(), channelId, model.PERMISSION_READ_CHANNEL) { c.SetPermissionError(model.PERMISSION_READ_CHANNEL) return } } - if len(teamId) > 0 { + if teamId != "" { if !c.App.SessionHasPermissionToTeam(*c.App.Session(), teamId, model.PERMISSION_VIEW_TEAM) { c.SetPermissionError(model.PERMISSION_VIEW_TEAM) return @@ -1019,11 +1019,11 @@ func autocompleteUsers(c *Context, w http.ResponseWriter, r *http.Request) { return } - if len(channelId) > 0 { + if channelId != "" { // We're using the channelId to search for users inside that channel and the team // to get the not in channel list. Also we want to include the DM and GM users for // that team which could only be obtained having the team id. - if len(teamId) == 0 { + if teamId == "" { c.Err = model.NewAppError("autocompleteUser", "api.user.autocomplete_users.missing_team_id.app_error", nil, @@ -1040,7 +1040,7 @@ func autocompleteUsers(c *Context, w http.ResponseWriter, r *http.Request) { autocomplete.Users = result.InChannel autocomplete.OutOfChannel = result.OutOfChannel - } else if len(teamId) > 0 { + } else if teamId != "" { result, err := c.App.AutocompleteUsersInTeam(teamId, name, options) if err != nil { c.Err = err @@ -1432,7 +1432,7 @@ func checkUserMfa(c *Context, w http.ResponseWriter, r *http.Request) { props := model.MapFromJson(r.Body) loginId := props["login_id"] - if len(loginId) == 0 { + if loginId == "" { c.SetInvalidParam("login_id") return } @@ -1488,7 +1488,7 @@ func updateUserMfa(c *Context, w http.ResponseWriter, r *http.Request) { code := "" if activate { code, ok = props["code"].(string) - if !ok || len(code) == 0 { + if !ok || code == "" { c.SetInvalidParam("code") return } @@ -1576,7 +1576,7 @@ func updatePassword(c *Context, w http.ResponseWriter, r *http.Request) { } else { if c.Params.UserId == c.App.Session().UserId { currentPassword := props["current_password"] - if len(currentPassword) <= 0 { + if currentPassword == "" { c.SetInvalidParam("current_password") return } @@ -1634,7 +1634,7 @@ func sendPasswordReset(c *Context, w http.ResponseWriter, r *http.Request) { email := props["email"] email = strings.ToLower(email) - if len(email) == 0 { + if email == "" { c.SetInvalidParam("email") return } @@ -1735,7 +1735,7 @@ func login(c *Context, w http.ResponseWriter, r *http.Request) { certPem, certSubject, certEmail := c.App.CheckForClientSideCert(r) mlog.Debug("Client Cert", mlog.String("cert_subject", certSubject), mlog.String("cert_email", certEmail)) - if len(certPem) == 0 || len(certEmail) == 0 { + if certPem == "" || certEmail == "" { c.Err = model.NewAppError("ClientSideCertMissing", "api.user.login.client_side_cert.certificate.app_error", nil, "", http.StatusBadRequest) return } @@ -1984,7 +1984,7 @@ func attachDeviceId(c *Context, w http.ResponseWriter, r *http.Request) { props := model.MapFromJson(r.Body) deviceId := props["device_id"] - if len(deviceId) == 0 { + if deviceId == "" { c.SetInvalidParam("device_id") return } @@ -2095,7 +2095,7 @@ func sendVerificationEmail(c *Context, w http.ResponseWriter, r *http.Request) { email := props["email"] email = strings.ToLower(email) - if len(email) == 0 { + if email == "" { c.SetInvalidParam("email") return } @@ -2238,7 +2238,7 @@ func searchUserAccessTokens(c *Context, w http.ResponseWriter, r *http.Request) return } - if len(props.Term) == 0 { + if props.Term == "" { c.SetInvalidParam("term") return } @@ -2709,7 +2709,7 @@ func migrateAuthToLDAP(c *Context, w http.ResponseWriter, r *http.Request) { c.SetInvalidParam("from") return } - if len(from) == 0 || (from != "email" && from != "gitlab" && from != "saml" && from != "google" && from != "office365") { + if from == "" || (from != "email" && from != "gitlab" && from != "saml" && from != "google" && from != "office365") { c.SetInvalidParam("from") return } @@ -2768,7 +2768,7 @@ func migrateAuthToSaml(c *Context, w http.ResponseWriter, r *http.Request) { c.SetInvalidParam("from") return } - if len(from) == 0 || (from != "email" && from != "gitlab" && from != "ldap" && from != "google" && from != "office365") { + if from == "" || (from != "email" && from != "gitlab" && from != "ldap" && from != "google" && from != "office365") { c.SetInvalidParam("from") return } @@ -2840,7 +2840,7 @@ func getThreadsForUser(c *Context, w http.ResponseWriter, r *http.Request) { } sinceString := r.URL.Query().Get("since") - if len(sinceString) > 0 { + if sinceString != "" { since, parseError := strconv.ParseUint(sinceString, 10, 64) if parseError != nil { c.SetInvalidParam("since") @@ -2850,7 +2850,7 @@ func getThreadsForUser(c *Context, w http.ResponseWriter, r *http.Request) { } pageString := r.URL.Query().Get("page") - if len(pageString) > 0 { + if pageString != "" { page, parseError := strconv.ParseUint(pageString, 10, 64) if parseError != nil { c.SetInvalidParam("page") @@ -2860,7 +2860,7 @@ func getThreadsForUser(c *Context, w http.ResponseWriter, r *http.Request) { } pageSizeString := r.URL.Query().Get("pageSize") - if len(pageString) > 0 { + if pageString != "" { pageSize, parseError := strconv.ParseUint(pageSizeString, 10, 64) if parseError != nil { c.SetInvalidParam("pageSize") diff --git a/api4/user_local.go b/api4/user_local.go index de0294389d..58f2c94c90 100644 --- a/api4/user_local.go +++ b/api4/user_local.go @@ -54,7 +54,7 @@ func localGetUsers(c *Context, w http.ResponseWriter, r *http.Request) { role := r.URL.Query().Get("role") sort := r.URL.Query().Get("sort") - if len(notInChannelId) > 0 && len(inTeamId) == 0 { + if notInChannelId != "" && inTeamId == "" { c.SetInvalidUrlParam("team_id") return } @@ -102,16 +102,16 @@ func localGetUsers(c *Context, w http.ResponseWriter, r *http.Request) { if withoutTeamBool, _ := strconv.ParseBool(withoutTeam); withoutTeamBool { profiles, err = c.App.GetUsersWithoutTeamPage(userGetOptions, c.IsSystemAdmin()) - } else if len(notInChannelId) > 0 { + } else if notInChannelId != "" { profiles, err = c.App.GetUsersNotInChannelPage(inTeamId, notInChannelId, groupConstrainedBool, c.Params.Page, c.Params.PerPage, c.IsSystemAdmin(), nil) - } else if len(notInTeamId) > 0 { + } else if notInTeamId != "" { etag = c.App.GetUsersNotInTeamEtag(inTeamId, "") if c.HandleEtag(etag, "Get Users Not in Team", w, r) { return } profiles, err = c.App.GetUsersNotInTeamPage(notInTeamId, groupConstrainedBool, c.Params.Page, c.Params.PerPage, c.IsSystemAdmin(), nil) - } else if len(inTeamId) > 0 { + } else if inTeamId != "" { if sort == "last_activity_at" { profiles, err = c.App.GetRecentlyActiveUsersForTeamPage(inTeamId, c.Params.Page, c.Params.PerPage, c.IsSystemAdmin(), nil) } else if sort == "create_at" { @@ -123,7 +123,7 @@ func localGetUsers(c *Context, w http.ResponseWriter, r *http.Request) { } profiles, err = c.App.GetUsersInTeamPage(userGetOptions, c.IsSystemAdmin()) } - } else if len(inChannelId) > 0 { + } else if inChannelId != "" { if sort == "status" { profiles, err = c.App.GetUsersInChannelPageByStatus(userGetOptions, c.IsSystemAdmin()) } else { @@ -138,7 +138,7 @@ func localGetUsers(c *Context, w http.ResponseWriter, r *http.Request) { return } - if len(etag) > 0 { + if etag != "" { w.Header().Set(model.HEADER_ETAG_SERVER, etag) } w.Write([]byte(model.UserListToJson(profiles))) @@ -158,7 +158,7 @@ func localGetUsersByIds(c *Context, w http.ResponseWriter, r *http.Request) { IsAdmin: c.IsSystemAdmin(), } - if len(sinceString) > 0 { + if sinceString != "" { since, parseError := strconv.ParseInt(sinceString, 10, 64) if parseError != nil { c.SetInvalidParam("since") diff --git a/api4/webhook.go b/api4/webhook.go index b0b36a36f7..9fb4aa8be4 100644 --- a/api4/webhook.go +++ b/api4/webhook.go @@ -173,7 +173,7 @@ func getIncomingHooks(c *Context, w http.ResponseWriter, r *http.Request) { var hooks []*model.IncomingWebhook var err *model.AppError - if len(teamId) > 0 { + if teamId != "" { if !c.App.SessionHasPermissionToTeam(*c.App.Session(), teamId, model.PERMISSION_MANAGE_INCOMING_WEBHOOKS) { c.SetPermissionError(model.PERMISSION_MANAGE_INCOMING_WEBHOOKS) return @@ -436,7 +436,7 @@ func getOutgoingHooks(c *Context, w http.ResponseWriter, r *http.Request) { var hooks []*model.OutgoingWebhook var err *model.AppError - if len(channelId) > 0 { + if channelId != "" { if !c.App.SessionHasPermissionToChannel(*c.App.Session(), channelId, model.PERMISSION_MANAGE_OUTGOING_WEBHOOKS) { c.SetPermissionError(model.PERMISSION_MANAGE_OUTGOING_WEBHOOKS) return @@ -448,7 +448,7 @@ func getOutgoingHooks(c *Context, w http.ResponseWriter, r *http.Request) { } hooks, err = c.App.GetOutgoingWebhooksForChannelPageByUser(channelId, userId, c.Params.Page, c.Params.PerPage) - } else if len(teamId) > 0 { + } else if teamId != "" { if !c.App.SessionHasPermissionToTeam(*c.App.Session(), teamId, model.PERMISSION_MANAGE_OUTGOING_WEBHOOKS) { c.SetPermissionError(model.PERMISSION_MANAGE_OUTGOING_WEBHOOKS) return diff --git a/api4/websocket.go b/api4/websocket.go index 3e1ee16238..c9d1277d12 100644 --- a/api4/websocket.go +++ b/api4/websocket.go @@ -31,7 +31,7 @@ func connectWebSocket(c *Context, w http.ResponseWriter, r *http.Request) { wc := c.App.NewWebConn(ws, *c.App.Session(), c.App.T, "") - if len(c.App.Session().UserId) > 0 { + if c.App.Session().UserId != "" { c.App.HubRegister(wc) } diff --git a/app/admin.go b/app/admin.go index 2ac062613f..cb6f8c6755 100644 --- a/app/admin.go +++ b/app/admin.go @@ -204,7 +204,7 @@ func (a *App) TestSiteURL(siteURL string) *model.AppError { } func (a *App) TestEmail(userId string, cfg *model.Config) *model.AppError { - if len(*cfg.EmailSettings.SMTPServer) == 0 { + if *cfg.EmailSettings.SMTPServer == "" { return model.NewAppError("testEmail", "api.admin.test_email.missing_server", nil, utils.T("api.context.invalid_param.app_error", map[string]interface{}{"Name": "SMTPServer"}), http.StatusBadRequest) } diff --git a/app/app.go b/app/app.go index 2578286f8b..0be32d7cc9 100644 --- a/app/app.go +++ b/app/app.go @@ -454,7 +454,7 @@ func (a *App) NotifyAndSetWarnMetricAck(warnMetricId string, sender *model.User, } if !forceAck { - if len(*a.Config().EmailSettings.SMTPServer) == 0 { + if *a.Config().EmailSettings.SMTPServer == "" { return model.NewAppError("NotifyAndSetWarnMetricAck", "api.email.send_warn_metric_ack.missing_server.app_error", nil, utils.T("api.context.invalid_param.app_error", map[string]interface{}{"Name": "SMTPServer"}), http.StatusInternalServerError) } T := utils.GetUserTranslations(sender.Locale) diff --git a/app/brand.go b/app/brand.go index 4853af9cf1..014f0e53a3 100644 --- a/app/brand.go +++ b/app/brand.go @@ -22,7 +22,7 @@ const ( ) func (a *App) SaveBrandImage(imageData *multipart.FileHeader) *model.AppError { - if len(*a.Config().FileSettings.DriverName) == 0 { + if *a.Config().FileSettings.DriverName == "" { return model.NewAppError("SaveBrandImage", "api.admin.upload_brand_image.storage.app_error", nil, "", http.StatusNotImplemented) } @@ -69,7 +69,7 @@ func (a *App) SaveBrandImage(imageData *multipart.FileHeader) *model.AppError { } func (a *App) GetBrandImage() ([]byte, *model.AppError) { - if len(*a.Config().FileSettings.DriverName) == 0 { + if *a.Config().FileSettings.DriverName == "" { return nil, model.NewAppError("GetBrandImage", "api.admin.get_brand_image.storage.app_error", nil, "", http.StatusNotImplemented) } diff --git a/app/channel.go b/app/channel.go index c011dcaf07..aa1f4c1bda 100644 --- a/app/channel.go +++ b/app/channel.go @@ -175,7 +175,7 @@ func (a *App) CreateChannelWithUser(channel *model.Channel, userId string) (*mod return nil, model.NewAppError("CreateChannelWithUser", "api.channel.create_channel.direct_channel.app_error", nil, "", http.StatusBadRequest) } - if len(channel.TeamId) == 0 { + if channel.TeamId == "" { return nil, model.NewAppError("CreateChannelWithUser", "app.channel.create_channel.no_team_id.app_error", nil, "", http.StatusBadRequest) } @@ -839,7 +839,7 @@ func (a *App) GetChannelModerationsForChannel(channel *model.Channel) ([]*model. } var guestRole *model.Role - if len(guestRoleName) > 0 { + if guestRoleName != "" { guestRole, err = a.GetRoleByName(guestRoleName) if err != nil { return nil, err @@ -856,7 +856,7 @@ func (a *App) GetChannelModerationsForChannel(channel *model.Channel) ([]*model. } var higherScopedGuestRole *model.Role - if len(higherScopedGuestRoleName) > 0 { + if higherScopedGuestRoleName != "" { higherScopedGuestRole, err = a.GetRoleByName(higherScopedGuestRoleName) if err != nil { return nil, err @@ -879,7 +879,7 @@ func (a *App) PatchChannelModerationsForChannel(channel *model.Channel, channelM } var higherScopedGuestRole *model.Role - if len(higherScopedGuestRoleName) > 0 { + if higherScopedGuestRoleName != "" { higherScopedGuestRole, err = a.GetRoleByName(higherScopedGuestRoleName) if err != nil { return nil, err @@ -904,7 +904,7 @@ func (a *App) PatchChannelModerationsForChannel(channel *model.Channel, channelM var scheme *model.Scheme // Channel has no scheme so create one - if channel.SchemeId == nil || len(*channel.SchemeId) == 0 { + if channel.SchemeId == nil || *channel.SchemeId == "" { scheme, err = a.CreateChannelScheme(channel) if err != nil { return nil, err @@ -936,7 +936,7 @@ func (a *App) PatchChannelModerationsForChannel(channel *model.Channel, channelM } var guestRole *model.Role - if len(guestRoleName) > 0 { + if guestRoleName != "" { guestRole, err = a.GetRoleByName(guestRoleName) if err != nil { return nil, err @@ -2554,11 +2554,11 @@ func (a *App) ViewChannel(view *model.ChannelView, userId string, currentSession channelIds := []string{} - if len(view.ChannelId) > 0 { + if view.ChannelId != "" { channelIds = append(channelIds, view.ChannelId) } - if len(view.PrevChannelId) > 0 { + if view.PrevChannelId != "" { channelIds = append(channelIds, view.PrevChannelId) } diff --git a/app/email.go b/app/email.go index 88d0de35ed..fb773165ba 100644 --- a/app/email.go +++ b/app/email.go @@ -341,7 +341,7 @@ func (es *EmailService) SendInviteEmails(team *model.Team, senderName string, se } for _, invite := range invites { - if len(invite) > 0 { + if invite != "" { subject := utils.T("api.templates.invite_subject", map[string]interface{}{"SenderName": senderName, "TeamDisplayName": team.DisplayName, @@ -400,7 +400,7 @@ func (es *EmailService) sendGuestInviteEmails(team *model.Team, channels []*mode } for _, invite := range invites { - if len(invite) > 0 { + if invite != "" { subject := utils.T("api.templates.invite_guest_subject", map[string]interface{}{"SenderName": senderName, "TeamDisplayName": team.DisplayName, diff --git a/app/emoji.go b/app/emoji.go index 5fca22b9e7..458c23f916 100644 --- a/app/emoji.go +++ b/app/emoji.go @@ -39,7 +39,7 @@ func (a *App) CreateEmoji(sessionUserId string, emoji *model.Emoji, multiPartIma return nil, model.NewAppError("UploadEmojiImage", "api.emoji.disabled.app_error", nil, "", http.StatusNotImplemented) } - if len(*a.Config().FileSettings.DriverName) == 0 { + if *a.Config().FileSettings.DriverName == "" { return nil, model.NewAppError("GetEmoji", "api.emoji.storage.app_error", nil, "", http.StatusNotImplemented) } @@ -96,7 +96,7 @@ func (a *App) UploadEmojiImage(id string, imageData *multipart.FileHeader) *mode return model.NewAppError("UploadEmojiImage", "api.emoji.disabled.app_error", nil, "", http.StatusNotImplemented) } - if len(*a.Config().FileSettings.DriverName) == 0 { + if *a.Config().FileSettings.DriverName == "" { return model.NewAppError("UploadEmojiImage", "api.emoji.storage.app_error", nil, "", http.StatusNotImplemented) } @@ -181,7 +181,7 @@ func (a *App) GetEmoji(emojiId string) (*model.Emoji, *model.AppError) { return nil, model.NewAppError("GetEmoji", "api.emoji.disabled.app_error", nil, "", http.StatusNotImplemented) } - if len(*a.Config().FileSettings.DriverName) == 0 { + if *a.Config().FileSettings.DriverName == "" { return nil, model.NewAppError("GetEmoji", "api.emoji.storage.app_error", nil, "", http.StatusNotImplemented) } @@ -204,7 +204,7 @@ func (a *App) GetEmojiByName(emojiName string) (*model.Emoji, *model.AppError) { return nil, model.NewAppError("GetEmojiByName", "api.emoji.disabled.app_error", nil, "", http.StatusNotImplemented) } - if len(*a.Config().FileSettings.DriverName) == 0 { + if *a.Config().FileSettings.DriverName == "" { return nil, model.NewAppError("GetEmojiByName", "api.emoji.storage.app_error", nil, "", http.StatusNotImplemented) } diff --git a/app/file.go b/app/file.go index 7acf234be3..2ebf66b7e0 100644 --- a/app/file.go +++ b/app/file.go @@ -498,7 +498,7 @@ func (a *App) UploadMultipartFiles(teamId string, channelId string, userId strin // the same length. clientIds should either not be provided or have the same length as files and filenames. // The provided files should be closed by the caller so that they are not leaked. func (a *App) UploadFiles(teamId string, channelId string, userId string, files []io.ReadCloser, filenames []string, clientIds []string, now time.Time) (*model.FileUploadResponse, *model.AppError) { - if len(*a.Config().FileSettings.DriverName) == 0 { + if *a.Config().FileSettings.DriverName == "" { return nil, model.NewAppError("UploadFiles", "api.file.upload_file.storage.app_error", nil, "", http.StatusNotImplemented) } @@ -703,7 +703,7 @@ func (a *App) UploadFileX(channelId, name string, input io.Reader, o(t) } - if len(*a.Config().FileSettings.DriverName) == 0 { + if *a.Config().FileSettings.DriverName == "" { return nil, t.newAppError("api.file.upload_file.storage.app_error", "", http.StatusNotImplemented) } diff --git a/app/import_functions.go b/app/import_functions.go index c8da7ff89b..37d0ab86da 100644 --- a/app/import_functions.go +++ b/app/import_functions.go @@ -52,7 +52,7 @@ func (a *App) importScheme(data *SchemeImportData, dryRun bool) *model.AppError scheme.Description = *data.Description } - if len(scheme.Id) == 0 { + if scheme.Id == "" { scheme, err = a.CreateScheme(scheme) } else { scheme, err = a.UpdateScheme(scheme) @@ -146,7 +146,7 @@ func (a *App) importRole(data *RoleImportData, dryRun bool, isSchemeRole bool) * role.SchemeManaged = false } - if len(role.Id) == 0 { + if role.Id == "" { _, err = a.CreateRole(role) } else { _, err = a.UpdateRole(role) @@ -406,7 +406,7 @@ func (a *App) importUser(data *UserImportData, dryRun bool) *model.AppError { roles = *data.Roles hasUserRolesChanged = true } - } else if len(user.Roles) == 0 { + } else if user.Roles == "" { // Set SYSTEM_USER roles on newly created users by default. if user.Roles != model.SYSTEM_USER_ROLE_ID { roles = model.SYSTEM_USER_ROLE_ID @@ -497,7 +497,7 @@ func (a *App) importUser(data *UserImportData, dryRun bool) *model.AppError { return err } } - if len(password) > 0 { + if password != "" { if err = a.UpdatePassword(user, password); err != nil { return err } @@ -1078,7 +1078,7 @@ func (a *App) importReplies(data []ReplyImportData, post *model.Post, teamId str reply.FileIds = append(reply.FileIds, fileID) } - if len(reply.Id) == 0 { + if reply.Id == "" { postsForCreateList = append(postsForCreateList, reply) } else { postsForOverwriteList = append(postsForOverwriteList, reply) @@ -1333,7 +1333,7 @@ func (a *App) importMultiplePostLines(lines []LineImportWorkerData, dryRun bool) post.FileIds = append(post.FileIds, fileID) } - if len(post.Id) == 0 { + if post.Id == "" { postsForCreateList = append(postsForCreateList, post) postsForCreateMap[getPostStrID(post)] = line.LineNumber } else { @@ -1629,7 +1629,7 @@ func (a *App) importMultipleDirectPostLines(lines []LineImportWorkerData, dryRun post.FileIds = append(post.FileIds, fileID) } - if len(post.Id) == 0 { + if post.Id == "" { postsForCreateList = append(postsForCreateList, post) postsForCreateMap[getPostStrID(post)] = line.LineNumber } else { diff --git a/app/import_validators.go b/app/import_validators.go index fd6229b893..e8309c6ccd 100644 --- a/app/import_validators.go +++ b/app/import_validators.go @@ -36,7 +36,7 @@ func validateSchemeImportData(data *SchemeImportData) *model.AppError { return model.NewAppError("BulkImport", "app.import.validate_scheme_import_data.name_invalid.error", nil, "", http.StatusBadRequest) } - if data.DisplayName == nil || len(*data.DisplayName) == 0 || len(*data.DisplayName) > model.SCHEME_DISPLAY_NAME_MAX_LENGTH { + if data.DisplayName == nil || *data.DisplayName == "" || len(*data.DisplayName) > model.SCHEME_DISPLAY_NAME_MAX_LENGTH { return model.NewAppError("BulkImport", "app.import.validate_scheme_import_data.display_name_invalid.error", nil, "", http.StatusBadRequest) } @@ -89,7 +89,7 @@ func validateRoleImportData(data *RoleImportData) *model.AppError { return model.NewAppError("BulkImport", "app.import.validate_role_import_data.name_invalid.error", nil, "", http.StatusBadRequest) } - if data.DisplayName == nil || len(*data.DisplayName) == 0 || len(*data.DisplayName) > model.ROLE_DISPLAY_NAME_MAX_LENGTH { + if data.DisplayName == nil || *data.DisplayName == "" || len(*data.DisplayName) > model.ROLE_DISPLAY_NAME_MAX_LENGTH { return model.NewAppError("BulkImport", "app.import.validate_role_import_data.display_name_invalid.error", nil, "", http.StatusBadRequest) } @@ -207,7 +207,7 @@ func validateUserImportData(data *UserImportData) *model.AppError { if data.Email == nil { return model.NewAppError("BulkImport", "app.import.validate_user_import_data.email_missing.error", nil, "", http.StatusBadRequest) - } else if len(*data.Email) == 0 || len(*data.Email) > model.USER_EMAIL_MAX_LENGTH { + } else if *data.Email == "" || len(*data.Email) > model.USER_EMAIL_MAX_LENGTH { return model.NewAppError("BulkImport", "app.import.validate_user_import_data.email_length.error", nil, "", http.StatusBadRequest) } @@ -223,14 +223,14 @@ func validateUserImportData(data *UserImportData) *model.AppError { if str == nil { return true } - return len(*str) == 0 + return *str == "" } if (!blank(data.AuthService) && blank(data.AuthData)) || (blank(data.AuthService) && !blank(data.AuthData)) { return model.NewAppError("BulkImport", "app.import.validate_user_import_data.auth_data_and_service_dependency.error", nil, "", http.StatusBadRequest) } - if data.Password != nil && len(*data.Password) == 0 { + if data.Password != nil && *data.Password == "" { return model.NewAppError("BulkImport", "app.import.validate_user_import_data.password_length.error", nil, "", http.StatusBadRequest) } @@ -565,7 +565,7 @@ func validateEmojiImportData(data *EmojiImportData) *model.AppError { return model.NewAppError("BulkImport", "app.import.validate_emoji_import_data.empty.error", nil, "", http.StatusBadRequest) } - if data.Name == nil || len(*data.Name) == 0 { + if data.Name == nil || *data.Name == "" { return model.NewAppError("BulkImport", "app.import.validate_emoji_import_data.name_missing.error", nil, "", http.StatusBadRequest) } @@ -573,7 +573,7 @@ func validateEmojiImportData(data *EmojiImportData) *model.AppError { return err } - if data.Image == nil || len(*data.Image) == 0 { + if data.Image == nil || *data.Image == "" { return model.NewAppError("BulkImport", "app.import.validate_emoji_import_data.image_missing.error", nil, "", http.StatusBadRequest) } diff --git a/app/integration_action_test.go b/app/integration_action_test.go index 4ee0922251..59169d5670 100644 --- a/app/integration_action_test.go +++ b/app/integration_action_test.go @@ -116,7 +116,7 @@ func TestPostAction(t *testing.T) { assert.Equal(t, request.TeamId, th.BasicTeam.Id) assert.Equal(t, request.TeamName, th.BasicTeam.Name) } - assert.True(t, len(request.TriggerId) > 0) + assert.True(t, request.TriggerId != "") if request.Type == model.POST_ACTION_TYPE_SELECT { assert.Equal(t, request.DataSource, "some_source") assert.Equal(t, request.Context["selected_option"], "selected") diff --git a/app/login.go b/app/login.go index 71bb8a7149..9484f62c73 100644 --- a/app/login.go +++ b/app/login.go @@ -29,7 +29,7 @@ func (a *App) CheckForClientSideCert(r *http.Request) (string, string, string) { subject := r.Header.Get("X-SSL-Client-Cert-Subject-DN") // mapped to $ssl_client_s_dn from nginx email := "" - if len(subject) > 0 { + if subject != "" { for _, v := range strings.Split(subject, "/") { kv := strings.Split(v, "=") if len(kv) == 2 && kv[0] == "emailAddress" { @@ -53,7 +53,7 @@ func (a *App) AuthenticateUserForLogin(id, loginId, password, mfaToken, cwsToken } }() - if len(password) == 0 && !IsCWSLogin(a, cwsToken) { + if password == "" && !IsCWSLogin(a, cwsToken) { return nil, model.NewAppError("AuthenticateUserForLogin", "api.user.login.blank_pwd.app_error", nil, "", http.StatusBadRequest) } @@ -175,7 +175,7 @@ func (a *App) DoLogin(w http.ResponseWriter, r *http.Request, user *model.User, }} session.GenerateCSRF() - if len(deviceId) > 0 { + if deviceId != "" { a.SetSessionExpireInDays(session, *a.Config().ServiceSettings.SessionLengthMobileInDays) // A special case where we logout of all other sessions with the same Id diff --git a/app/notification.go b/app/notification.go index 5997f5e52e..6935c38a5d 100644 --- a/app/notification.go +++ b/app/notification.go @@ -123,7 +123,7 @@ func (a *App) SendNotifications(post *model.Post, team *model.Team, channel *mod } // get users that have comment thread mentions enabled - if len(post.RootId) > 0 && parentPostList != nil { + if post.RootId != "" && parentPostList != nil { for _, threadPost := range parentPostList.Posts { profile := profileMap[threadPost.UserId] if profile != nil && (profile.NotifyProps[model.COMMENTS_NOTIFY_PROP] == model.COMMENTS_NOTIFY_ANY || (profile.NotifyProps[model.COMMENTS_NOTIFY_PROP] == model.COMMENTS_NOTIFY_ROOT && threadPost.Id == parentPostList.Order[0])) { @@ -596,7 +596,7 @@ func makeOutOfChannelMentionPost(sender *model.User, post *model.Post, outOfChan } if len(outOfGroupsUsers) == 1 { - if len(message) > 0 { + if message != "" { message += "\n" } @@ -606,7 +606,7 @@ func makeOutOfChannelMentionPost(sender *model.User, post *model.Post, outOfChan } else if len(outOfGroupsUsers) > 1 { preliminary, final := splitAtFinal(ogUsernames) - if len(message) > 0 { + if message != "" { message += "\n" } @@ -1084,7 +1084,7 @@ func (m *ExplicitMentions) processText(text string, keywords map[string][]string foundWithoutSuffix := false wordWithoutSuffix := word - for len(wordWithoutSuffix) > 0 && strings.LastIndexAny(wordWithoutSuffix, ".-:_") == (len(wordWithoutSuffix)-1) { + for wordWithoutSuffix != "" && strings.LastIndexAny(wordWithoutSuffix, ".-:_") == (len(wordWithoutSuffix)-1) { wordWithoutSuffix = wordWithoutSuffix[0 : len(wordWithoutSuffix)-1] if m.checkForMention(wordWithoutSuffix, keywords, groups) { diff --git a/app/oauth.go b/app/oauth.go index 11768a4320..9126247371 100644 --- a/app/oauth.go +++ b/app/oauth.go @@ -173,7 +173,7 @@ func (a *App) AllowOAuthAppAccessToUser(userId string, authRequest *model.Author return "", model.NewAppError("AllowOAuthAppAccessToUser", "api.oauth.allow_oauth.turn_off.app_error", nil, "", http.StatusNotImplemented) } - if len(authRequest.Scope) == 0 { + if authRequest.Scope == "" { authRequest.Scope = model.DEFAULT_SCOPE } @@ -619,7 +619,7 @@ func (a *App) LoginByOAuth(service string, userData io.Reader, teamId string, to if err = a.UpdateOAuthUserAttrs(bytes.NewReader(buf.Bytes()), user, provider, service, tokenUser); err != nil { return nil, err } - if len(teamId) > 0 { + if teamId != "" { err = a.AddUserToTeamByTeamId(teamId, user) } } @@ -763,11 +763,11 @@ func (a *App) GetAuthorizationCode(w http.ResponseWriter, r *http.Request, servi authUrl := endpoint + "?response_type=code&client_id=" + clientId + "&redirect_uri=" + url.QueryEscape(redirectUri) + "&state=" + url.QueryEscape(state) - if len(scope) > 0 { + if scope != "" { authUrl += "&scope=" + utils.UrlEncode(scope) } - if len(loginHint) > 0 { + if loginHint != "" { authUrl += "&login_hint=" + utils.UrlEncode(loginHint) } @@ -865,7 +865,7 @@ func (a *App) AuthorizeOAuthUser(w http.ResponseWriter, r *http.Request, service return nil, "", stateProps, nil, model.NewAppError("AuthorizeOAuthUser", "api.user.authorize_oauth_user.bad_token.app_error", nil, "token_type="+ar.TokenType+", response_body="+buf.String(), http.StatusInternalServerError) } - if len(ar.AccessToken) == 0 { + if ar.AccessToken == "" { return nil, "", stateProps, nil, model.NewAppError("AuthorizeOAuthUser", "api.user.authorize_oauth_user.missing.app_error", nil, "response_body="+buf.String(), http.StatusInternalServerError) } diff --git a/app/permissions.go b/app/permissions.go index 295a047b89..8863290184 100644 --- a/app/permissions.go +++ b/app/permissions.go @@ -95,7 +95,7 @@ func (a *App) ExportPermissions(w io.Writer) error { roles := []*model.Role{} for _, roleName := range roleNames { - if len(roleName) == 0 { + if roleName == "" { continue } role, err := a.GetRoleByName(roleName) @@ -206,7 +206,7 @@ func (a *App) ImportPermissions(jsonl io.Reader) error { {schemeCreated.DefaultChannelGuestRole, schemeIn.DefaultChannelGuestRole}, } for _, roleNameTuple := range roleNameTuples { - if len(roleNameTuple[0]) == 0 || len(roleNameTuple[1]) == 0 { + if roleNameTuple[0] == "" || roleNameTuple[1] == "" { continue } diff --git a/app/plugin_api.go b/app/plugin_api.go index cdc92c2b88..3b292795ad 100644 --- a/app/plugin_api.go +++ b/app/plugin_api.go @@ -654,7 +654,7 @@ func (api *PluginAPI) GetFileLink(fileId string) (string, *model.AppError) { return "", err } - if len(info.PostId) == 0 { + if info.PostId == "" { return "", model.NewAppError("GetFileLink", "plugin_api.get_file_link.no_post.app_error", nil, "file_id="+info.Id, http.StatusBadRequest) } diff --git a/app/plugin_api_test.go b/app/plugin_api_test.go index e1cc4e7b40..09400ee14d 100644 --- a/app/plugin_api_test.go +++ b/app/plugin_api_test.go @@ -1296,21 +1296,21 @@ func TestPluginAPIGetConfig(t *testing.T) { api := th.SetupPluginAPI() config := api.GetConfig() - if config.LdapSettings.BindPassword != nil && len(*config.LdapSettings.BindPassword) > 0 { + if config.LdapSettings.BindPassword != nil && *config.LdapSettings.BindPassword != "" { assert.Equal(t, *config.LdapSettings.BindPassword, model.FAKE_SETTING) } assert.Equal(t, *config.FileSettings.PublicLinkSalt, model.FAKE_SETTING) - if len(*config.FileSettings.AmazonS3SecretAccessKey) > 0 { + if *config.FileSettings.AmazonS3SecretAccessKey != "" { assert.Equal(t, *config.FileSettings.AmazonS3SecretAccessKey, model.FAKE_SETTING) } - if config.EmailSettings.SMTPPassword != nil && len(*config.EmailSettings.SMTPPassword) > 0 { + if config.EmailSettings.SMTPPassword != nil && *config.EmailSettings.SMTPPassword != "" { assert.Equal(t, *config.EmailSettings.SMTPPassword, model.FAKE_SETTING) } - if len(*config.GitLabSettings.Secret) > 0 { + if *config.GitLabSettings.Secret != "" { assert.Equal(t, *config.GitLabSettings.Secret, model.FAKE_SETTING) } @@ -1333,21 +1333,21 @@ func TestPluginAPIGetUnsanitizedConfig(t *testing.T) { api := th.SetupPluginAPI() config := api.GetUnsanitizedConfig() - if config.LdapSettings.BindPassword != nil && len(*config.LdapSettings.BindPassword) > 0 { + if config.LdapSettings.BindPassword != nil && *config.LdapSettings.BindPassword != "" { assert.NotEqual(t, *config.LdapSettings.BindPassword, model.FAKE_SETTING) } assert.NotEqual(t, *config.FileSettings.PublicLinkSalt, model.FAKE_SETTING) - if len(*config.FileSettings.AmazonS3SecretAccessKey) > 0 { + if *config.FileSettings.AmazonS3SecretAccessKey != "" { assert.NotEqual(t, *config.FileSettings.AmazonS3SecretAccessKey, model.FAKE_SETTING) } - if config.EmailSettings.SMTPPassword != nil && len(*config.EmailSettings.SMTPPassword) > 0 { + if config.EmailSettings.SMTPPassword != nil && *config.EmailSettings.SMTPPassword != "" { assert.NotEqual(t, *config.EmailSettings.SMTPPassword, model.FAKE_SETTING) } - if len(*config.GitLabSettings.Secret) > 0 { + if *config.GitLabSettings.Secret != "" { assert.NotEqual(t, *config.GitLabSettings.Secret, model.FAKE_SETTING) } diff --git a/app/post.go b/app/post.go index 2ab13a5b7f..f97c707f09 100644 --- a/app/post.go +++ b/app/post.go @@ -182,7 +182,7 @@ func (a *App) CreatePost(post *model.Post, channel *model.Channel, triggerWebhoo post.SanitizeProps() var pchan chan store.StoreResult - if len(post.RootId) > 0 { + if post.RootId != "" { pchan = make(chan store.StoreResult, 1) go func() { r, pErr := a.Srv().Store.Post().Get(post.RootId, false, false, false) @@ -242,7 +242,7 @@ func (a *App) CreatePost(post *model.Post, channel *model.Channel, triggerWebhoo } rootPost := parentPostList.Posts[post.RootId] - if len(rootPost.RootId) > 0 { + if rootPost.RootId != "" { return nil, model.NewAppError("createPost", "api.post.create_post.root_id.app_error", nil, "", http.StatusBadRequest) } @@ -439,7 +439,7 @@ func (a *App) FillInPostProps(post *model.Post, channel *model.Channel) *model.A func (a *App) handlePostEvents(post *model.Post, user *model.User, channel *model.Channel, triggerWebhooks bool, parentPostList *model.PostList, setOnline bool) error { var team *model.Team - if len(channel.TeamId) > 0 { + if channel.TeamId != "" { t, err := a.Srv().Store.Team().Get(channel.TeamId) if err != nil { return err diff --git a/app/security_update_check.go b/app/security_update_check.go index c36a3f6b7f..a56f96365a 100644 --- a/app/security_update_check.go +++ b/app/security_update_check.go @@ -55,7 +55,7 @@ func (s *Server) DoSecurityUpdateCheck() { v.Set(PropSecurityDatabase, *s.Config().SqlSettings.DriverName) v.Set(PropSecurityOS, runtime.GOOS) - if len(props[model.SYSTEM_RAN_UNIT_TESTS]) > 0 { + if props[model.SYSTEM_RAN_UNIT_TESTS] != "" { v.Set(PropSecurityUnitTests, "1") } else { v.Set(PropSecurityUnitTests, "0") diff --git a/app/slashcommands/command_channel_header.go b/app/slashcommands/command_channel_header.go index a6c4a7f939..95aeccbbcd 100644 --- a/app/slashcommands/command_channel_header.go +++ b/app/slashcommands/command_channel_header.go @@ -79,7 +79,7 @@ func (*HeaderProvider) DoCommand(a *app.App, args *model.CommandArgs, message st } } - if len(message) == 0 { + if message == "" { return &model.CommandResponse{ Text: args.T("api.command_channel_header.message.app_error"), ResponseType: model.COMMAND_RESPONSE_TYPE_EPHEMERAL, diff --git a/app/slashcommands/command_channel_purpose.go b/app/slashcommands/command_channel_purpose.go index 8c98d0ebdd..c0e58a433a 100644 --- a/app/slashcommands/command_channel_purpose.go +++ b/app/slashcommands/command_channel_purpose.go @@ -66,7 +66,7 @@ func (*PurposeProvider) DoCommand(a *app.App, args *model.CommandArgs, message s } } - if len(message) == 0 { + if message == "" { return &model.CommandResponse{ Text: args.T("api.command_channel_purpose.message.app_error"), ResponseType: model.COMMAND_RESPONSE_TYPE_EPHEMERAL, diff --git a/app/slashcommands/command_channel_rename.go b/app/slashcommands/command_channel_rename.go index aa6a37c548..d5328ba36b 100644 --- a/app/slashcommands/command_channel_rename.go +++ b/app/slashcommands/command_channel_rename.go @@ -66,7 +66,7 @@ func (*RenameProvider) DoCommand(a *app.App, args *model.CommandArgs, message st return &model.CommandResponse{Text: args.T("api.command_channel_rename.direct_group.app_error"), ResponseType: model.COMMAND_RESPONSE_TYPE_EPHEMERAL} } - if len(message) == 0 { + if message == "" { return &model.CommandResponse{ Text: args.T("api.command_channel_rename.message.app_error"), ResponseType: model.COMMAND_RESPONSE_TYPE_EPHEMERAL, diff --git a/app/slashcommands/command_code.go b/app/slashcommands/command_code.go index 8d908e98e2..1a030c123a 100644 --- a/app/slashcommands/command_code.go +++ b/app/slashcommands/command_code.go @@ -38,7 +38,7 @@ func (*CodeProvider) GetCommand(a *app.App, T goi18n.TranslateFunc) *model.Comma } func (*CodeProvider) DoCommand(a *app.App, args *model.CommandArgs, message string) *model.CommandResponse { - if len(message) == 0 { + if message == "" { return &model.CommandResponse{Text: args.T("api.command_code.message.app_error"), ResponseType: model.COMMAND_RESPONSE_TYPE_EPHEMERAL} } rmsg := " " + strings.Join(strings.Split(message, "\n"), "\n ") diff --git a/app/slashcommands/command_echo.go b/app/slashcommands/command_echo.go index b21e87e583..a0315e654e 100644 --- a/app/slashcommands/command_echo.go +++ b/app/slashcommands/command_echo.go @@ -43,7 +43,7 @@ func (*EchoProvider) GetCommand(a *app.App, T goi18n.TranslateFunc) *model.Comma } func (*EchoProvider) DoCommand(a *app.App, args *model.CommandArgs, message string) *model.CommandResponse { - if len(message) == 0 { + if message == "" { return &model.CommandResponse{Text: args.T("api.command_echo.message.app_error"), ResponseType: model.COMMAND_RESPONSE_TYPE_EPHEMERAL} } diff --git a/app/slashcommands/command_groupmsg.go b/app/slashcommands/command_groupmsg.go index 7a871db1a0..eec8c4d8b8 100644 --- a/app/slashcommands/command_groupmsg.go +++ b/app/slashcommands/command_groupmsg.go @@ -122,7 +122,7 @@ func (*groupmsgProvider) DoCommand(a *app.App, args *model.CommandArgs, message } } - if len(parsedMessage) > 0 { + if parsedMessage != "" { post := &model.Post{} post.Message = parsedMessage post.ChannelId = groupChannel.Id diff --git a/app/slashcommands/command_loadtest.go b/app/slashcommands/command_loadtest.go index c2c347de27..a0eab1917b 100644 --- a/app/slashcommands/command_loadtest.go +++ b/app/slashcommands/command_loadtest.go @@ -459,7 +459,7 @@ func (*LoadTestProvider) PostCommand(a *app.App, args *model.CommandArgs, messag func (*LoadTestProvider) UrlCommand(a *app.App, args *model.CommandArgs, message string) (*model.CommandResponse, error) { url := strings.TrimSpace(strings.TrimPrefix(message, "url")) - if len(url) == 0 { + if url == "" { return &model.CommandResponse{Text: "Command must contain a url", ResponseType: model.COMMAND_RESPONSE_TYPE_EPHEMERAL}, nil } @@ -513,7 +513,7 @@ func (*LoadTestProvider) UrlCommand(a *app.App, args *model.CommandArgs, message func (*LoadTestProvider) JsonCommand(a *app.App, args *model.CommandArgs, message string) (*model.CommandResponse, error) { url := strings.TrimSpace(strings.TrimPrefix(message, "json")) - if len(url) == 0 { + if url == "" { return &model.CommandResponse{Text: "Command must contain a url", ResponseType: model.COMMAND_RESPONSE_TYPE_EPHEMERAL}, nil } diff --git a/app/slashcommands/command_msg.go b/app/slashcommands/command_msg.go index 5edf6b0104..2f9bdc1de0 100644 --- a/app/slashcommands/command_msg.go +++ b/app/slashcommands/command_msg.go @@ -96,7 +96,7 @@ func (*msgProvider) DoCommand(a *app.App, args *model.CommandArgs, message strin targetChannelId = channel.Id } - if len(parsedMessage) > 0 { + if parsedMessage != "" { post := &model.Post{} post.Message = parsedMessage post.ChannelId = targetChannelId diff --git a/app/slashcommands/command_mute.go b/app/slashcommands/command_mute.go index 18c708af7b..2e8eef497e 100644 --- a/app/slashcommands/command_mute.go +++ b/app/slashcommands/command_mute.go @@ -54,7 +54,7 @@ func (*MuteProvider) DoCommand(a *app.App, args *model.CommandArgs, message stri channelName = splitMessage[0] } - if len(channelName) > 0 && len(message) > 0 { + if channelName != "" && message != "" { channel, _ = a.Srv().Store.Channel().GetByName(channel.TeamId, channelName, true) if channel == nil { diff --git a/app/slashcommands/command_remove.go b/app/slashcommands/command_remove.go index 054b6bee24..4950b51fb8 100644 --- a/app/slashcommands/command_remove.go +++ b/app/slashcommands/command_remove.go @@ -96,7 +96,7 @@ func doCommand(a *app.App, args *model.CommandArgs, message string) *model.Comma } } - if len(message) == 0 { + if message == "" { return &model.CommandResponse{ Text: args.T("api.command_remove.message.app_error"), ResponseType: model.COMMAND_RESPONSE_TYPE_EPHEMERAL, diff --git a/app/slashcommands/command_shrug.go b/app/slashcommands/command_shrug.go index 0793f8ecb9..8e226d381f 100644 --- a/app/slashcommands/command_shrug.go +++ b/app/slashcommands/command_shrug.go @@ -37,7 +37,7 @@ func (*ShrugProvider) GetCommand(a *app.App, T goi18n.TranslateFunc) *model.Comm func (*ShrugProvider) DoCommand(a *app.App, args *model.CommandArgs, message string) *model.CommandResponse { rmsg := `¯\\\_(ツ)\_/¯` - if len(message) > 0 { + if message != "" { rmsg = message + " " + rmsg } diff --git a/app/svg.go b/app/svg.go index a5825a6f3c..7fdc4472c5 100644 --- a/app/svg.go +++ b/app/svg.go @@ -39,7 +39,7 @@ func parseSVG(svgReader io.Reader) (SVGInfo, error) { if viewBoxMatches := viewBoxPattern.FindStringSubmatch(parsedSVG.ViewBox); len(viewBoxMatches) == 5 { svgInfo.Width, _ = strconv.Atoi(viewBoxMatches[3]) svgInfo.Height, _ = strconv.Atoi(viewBoxMatches[4]) - } else if len(parsedSVG.Width) > 0 && len(parsedSVG.Height) > 0 { + } else if parsedSVG.Width != "" && parsedSVG.Height != "" { widthMatches := dimensionPattern.FindStringSubmatch(parsedSVG.Width) heightMatches := dimensionPattern.FindStringSubmatch(parsedSVG.Height) if len(widthMatches) == 2 && len(heightMatches) == 2 { diff --git a/app/team.go b/app/team.go index 29d7bbb484..ba4dee4f17 100644 --- a/app/team.go +++ b/app/team.go @@ -1840,7 +1840,7 @@ func (a *App) GetTeamIdFromQuery(query url.Values) (string, *model.AppError) { tokenId := query.Get("t") inviteId := query.Get("id") - if len(tokenId) > 0 { + if tokenId != "" { token, err := a.Srv().Store.Token().GetByToken(tokenId) if err != nil { return "", model.NewAppError("GetTeamIdFromQuery", "api.oauth.singup_with_oauth.invalid_link.app_error", nil, "", http.StatusBadRequest) @@ -1859,7 +1859,7 @@ func (a *App) GetTeamIdFromQuery(query url.Values) (string, *model.AppError) { return tokenData["teamId"], nil } - if len(inviteId) > 0 { + if inviteId != "" { team, err := a.Srv().Store.Team().GetByInviteId(inviteId) if err == nil { return team.Id, nil @@ -1897,7 +1897,7 @@ func (a *App) SanitizeTeams(session model.Session, teams []*model.Team) []*model } func (a *App) GetTeamIcon(team *model.Team) ([]byte, *model.AppError) { - if len(*a.Config().FileSettings.DriverName) == 0 { + if *a.Config().FileSettings.DriverName == "" { return nil, model.NewAppError("GetTeamIcon", "api.team.get_team_icon.filesettings_no_driver.app_error", nil, "", http.StatusNotImplemented) } @@ -1926,7 +1926,7 @@ func (a *App) SetTeamIconFromMultiPartFile(teamId string, file multipart.File) * return model.NewAppError("SetTeamIcon", "api.team.set_team_icon.get_team.app_error", nil, getTeamErr.Error(), http.StatusBadRequest) } - if len(*a.Config().FileSettings.DriverName) == 0 { + if *a.Config().FileSettings.DriverName == "" { return model.NewAppError("setTeamIcon", "api.team.set_team_icon.storage.app_error", nil, "", http.StatusNotImplemented) } diff --git a/app/user.go b/app/user.go index 5553d025e2..6095dfb068 100644 --- a/app/user.go +++ b/app/user.go @@ -393,7 +393,7 @@ func (a *App) CreateOAuthUser(service string, userData io.Reader, teamId string, return nil, err } - if len(teamId) > 0 { + if teamId != "" { err = a.AddUserToTeamByTeamId(teamId, user) if err != nil { return nil, err @@ -410,7 +410,7 @@ func (a *App) CreateOAuthUser(service string, userData io.Reader, teamId string, // CheckEmailDomain checks that an email domain matches a list of space-delimited domains as a string. func CheckEmailDomain(email string, domains string) bool { - if len(domains) == 0 { + if domains == "" { return true } @@ -762,7 +762,7 @@ func (a *App) ActivateMfa(userId, token string) *model.AppError { } } - if len(user.AuthService) > 0 && user.AuthService != model.USER_AUTH_SERVICE_LDAP { + if user.AuthService != "" && user.AuthService != model.USER_AUTH_SERVICE_LDAP { return model.NewAppError("ActivateMfa", "api.user.activate_mfa.email_and_ldap_only.app_error", nil, "", http.StatusBadRequest) } @@ -873,7 +873,7 @@ func getFont(initialFont string) (*truetype.Font, error) { } func (a *App) GetProfileImage(user *model.User) ([]byte, bool, *model.AppError) { - if len(*a.Config().FileSettings.DriverName) == 0 { + if *a.Config().FileSettings.DriverName == "" { img, appErr := a.GetDefaultProfileImage(user) if appErr != nil { return nil, false, appErr diff --git a/app/web_hub.go b/app/web_hub.go index 9bf17b3d98..c359bccc4c 100644 --- a/app/web_hub.go +++ b/app/web_hub.go @@ -435,7 +435,7 @@ func (h *Hub) Start() { connIndex.Remove(webConn) atomic.StoreInt64(&h.connectionCount, int64(len(connIndex.All()))) - if len(webConn.UserId) == 0 { + if webConn.UserId == "" { continue } diff --git a/app/webhook.go b/app/webhook.go index 99e979daca..a6973529c4 100644 --- a/app/webhook.go +++ b/app/webhook.go @@ -51,7 +51,7 @@ func (a *App) handleWebhookEvents(post *model.Post, team *model.Team, channel *m relevantHooks := []*model.OutgoingWebhook{} for _, hook := range hooks { - if hook.ChannelId == post.ChannelId || len(hook.ChannelId) == 0 { + if hook.ChannelId == post.ChannelId || hook.ChannelId == "" { if hook.ChannelId == post.ChannelId && len(hook.TriggerWords) == 0 { relevantHooks = append(relevantHooks, hook) triggerWord = "" @@ -503,7 +503,7 @@ func (a *App) UpdateOutgoingWebhook(oldHook, updatedHook *model.OutgoingWebhook) return nil, model.NewAppError("UpdateOutgoingWebhook", "api.outgoing_webhook.disabled.app_error", nil, "", http.StatusNotImplemented) } - if len(updatedHook.ChannelId) > 0 { + if updatedHook.ChannelId != "" { channel, err := a.GetChannel(updatedHook.ChannelId) if err != nil { return nil, err @@ -658,7 +658,7 @@ func (a *App) HandleIncomingWebhook(hookId string, req *model.IncomingWebhookReq } text := req.Text - if len(text) == 0 && req.Attachments == nil { + if text == "" && req.Attachments == nil { return model.NewAppError("HandleIncomingWebhook", "web.incoming_webhook.text.app_error", nil, "", http.StatusBadRequest) } diff --git a/cmd/mattermost/commands/user.go b/cmd/mattermost/commands/user.go index edb21f8f3f..4b14dde237 100644 --- a/cmd/mattermost/commands/user.go +++ b/cmd/mattermost/commands/user.go @@ -843,7 +843,7 @@ func migrateAuthToLdapCmdF(command *cobra.Command, args []string) error { fromAuth := args[0] matchField := args[2] - if len(fromAuth) == 0 || (fromAuth != "email" && fromAuth != "gitlab" && fromAuth != "saml") { + if fromAuth == "" || (fromAuth != "email" && fromAuth != "gitlab" && fromAuth != "saml") { return errors.New("Invalid from_auth argument") } @@ -852,7 +852,7 @@ func migrateAuthToLdapCmdF(command *cobra.Command, args []string) error { fromAuth = "" } - if len(matchField) == 0 || (matchField != "email" && matchField != "username") { + if matchField == "" || (matchField != "email" && matchField != "username") { return errors.New("Invalid match_field argument") } @@ -903,7 +903,7 @@ func migrateAuthToSamlCmdF(command *cobra.Command, args []string) error { fromAuth := args[0] - if len(fromAuth) == 0 || (fromAuth != "email" && fromAuth != "gitlab" && fromAuth != "ldap") { + if fromAuth == "" || (fromAuth != "email" && fromAuth != "gitlab" && fromAuth != "ldap") { return errors.New("Invalid from_auth argument") } diff --git a/config/utils.go b/config/utils.go index 5424802a00..927443dfdb 100644 --- a/config/utils.go +++ b/config/utils.go @@ -131,7 +131,7 @@ func FixInvalidLocales(cfg *model.Config) bool { changed = true } - if len(*cfg.LocalizationSettings.AvailableLocales) > 0 { + if *cfg.LocalizationSettings.AvailableLocales != "" { isDefaultClientLocaleInAvailableLocales := false for _, word := range strings.Split(*cfg.LocalizationSettings.AvailableLocales, ",") { if _, ok := locales[word]; !ok { diff --git a/jobs/jobs.go b/jobs/jobs.go index d4638f1cb5..3ec225f3ee 100644 --- a/jobs/jobs.go +++ b/jobs/jobs.go @@ -115,7 +115,7 @@ func (srv *JobServer) SetJobError(job *model.Job, jobError *model.AppError) *mod job.Data = make(map[string]string) } job.Data["error"] = jobError.Message - if len(jobError.DetailedError) > 0 { + if jobError.DetailedError != "" { job.Data["error"] += " — " + jobError.DetailedError } updated, err := srv.Store.Job().UpdateOptimistically(job, model.JOB_STATUS_IN_PROGRESS) diff --git a/migrations/advanced_permissions_phase_2.go b/migrations/advanced_permissions_phase_2.go index c2a40cac3f..e0c91a29e9 100644 --- a/migrations/advanced_permissions_phase_2.go +++ b/migrations/advanced_permissions_phase_2.go @@ -55,7 +55,7 @@ func (p *AdvancedPermissionsPhase2Progress) IsValid() bool { func (worker *Worker) runAdvancedPermissionsPhase2Migration(lastDone string) (bool, string, *model.AppError) { var progress *AdvancedPermissionsPhase2Progress - if len(lastDone) == 0 { + if lastDone == "" { // Haven't started the migration yet. progress = new(AdvancedPermissionsPhase2Progress) progress.CurrentTable = "TeamMembers" diff --git a/model/access.go b/model/access.go index d6b06f4dfb..6b60ea9e45 100644 --- a/model/access.go +++ b/model/access.go @@ -38,11 +38,11 @@ type AccessResponse struct { // correctly. func (ad *AccessData) IsValid() *AppError { - if len(ad.ClientId) == 0 || len(ad.ClientId) > 26 { + if ad.ClientId == "" || len(ad.ClientId) > 26 { return NewAppError("AccessData.IsValid", "model.access.is_valid.client_id.app_error", nil, "", http.StatusBadRequest) } - if len(ad.UserId) == 0 || len(ad.UserId) > 26 { + if ad.UserId == "" || len(ad.UserId) > 26 { return NewAppError("AccessData.IsValid", "model.access.is_valid.user_id.app_error", nil, "", http.StatusBadRequest) } @@ -54,7 +54,7 @@ func (ad *AccessData) IsValid() *AppError { return NewAppError("AccessData.IsValid", "model.access.is_valid.refresh_token.app_error", nil, "", http.StatusBadRequest) } - if len(ad.RedirectUri) == 0 || len(ad.RedirectUri) > 256 || !IsValidHttpUrl(ad.RedirectUri) { + if ad.RedirectUri == "" || len(ad.RedirectUri) > 256 || !IsValidHttpUrl(ad.RedirectUri) { return NewAppError("AccessData.IsValid", "model.access.is_valid.redirect_uri.app_error", nil, "", http.StatusBadRequest) } diff --git a/model/authorize.go b/model/authorize.go index 0191a6705b..f2a8e8dcdf 100644 --- a/model/authorize.go +++ b/model/authorize.go @@ -47,7 +47,7 @@ func (ad *AuthData) IsValid() *AppError { return NewAppError("AuthData.IsValid", "model.authorize.is_valid.user_id.app_error", nil, "", http.StatusBadRequest) } - if len(ad.Code) == 0 || len(ad.Code) > 128 { + if ad.Code == "" || len(ad.Code) > 128 { return NewAppError("AuthData.IsValid", "model.authorize.is_valid.auth_code.app_error", nil, "client_id="+ad.ClientId, http.StatusBadRequest) } @@ -82,11 +82,11 @@ func (ar *AuthorizeRequest) IsValid() *AppError { return NewAppError("AuthData.IsValid", "model.authorize.is_valid.client_id.app_error", nil, "", http.StatusBadRequest) } - if len(ar.ResponseType) == 0 { + if ar.ResponseType == "" { return NewAppError("AuthData.IsValid", "model.authorize.is_valid.response_type.app_error", nil, "", http.StatusBadRequest) } - if len(ar.RedirectUri) == 0 || len(ar.RedirectUri) > 256 || !IsValidHttpUrl(ar.RedirectUri) { + if ar.RedirectUri == "" || len(ar.RedirectUri) > 256 || !IsValidHttpUrl(ar.RedirectUri) { return NewAppError("AuthData.IsValid", "model.authorize.is_valid.redirect_uri.app_error", nil, "client_id="+ar.ClientId, http.StatusBadRequest) } @@ -110,7 +110,7 @@ func (ad *AuthData) PreSave() { ad.CreateAt = GetMillis() } - if len(ad.Scope) == 0 { + if ad.Scope == "" { ad.Scope = DEFAULT_SCOPE } } diff --git a/model/bot.go b/model/bot.go index fb46be495c..23d1c5b7d0 100644 --- a/model/bot.go +++ b/model/bot.go @@ -82,7 +82,7 @@ func (b *Bot) IsValid() *AppError { return NewAppError("Bot.IsValid", "model.bot.is_valid.description.app_error", b.Trace(), "", http.StatusBadRequest) } - if len(b.OwnerId) == 0 || utf8.RuneCountInString(b.OwnerId) > BOT_CREATOR_ID_MAX_RUNES { + if b.OwnerId == "" || utf8.RuneCountInString(b.OwnerId) > BOT_CREATOR_ID_MAX_RUNES { return NewAppError("Bot.IsValid", "model.bot.is_valid.creator_id.app_error", b.Trace(), "", http.StatusBadRequest) } diff --git a/model/client4.go b/model/client4.go index 4d715ac39c..f5787f5b80 100644 --- a/model/client4.go +++ b/model/client4.go @@ -584,11 +584,11 @@ func (c *Client4) doApiRequestReader(method, url string, data io.Reader, etag st return nil, NewAppError(url, "model.client.connecting.app_error", nil, err.Error(), http.StatusBadRequest) } - if len(etag) > 0 { + if etag != "" { rq.Header.Set(HEADER_ETAG_CLIENT, etag) } - if len(c.AuthToken) > 0 { + if c.AuthToken != "" { rq.Header.Set(HEADER_AUTH, c.AuthType+" "+c.AuthToken) } @@ -629,7 +629,7 @@ func (c *Client4) doUploadFile(url string, body io.Reader, contentType string, c } rq.Header.Set("Content-Type", contentType) - if len(c.AuthToken) > 0 { + if c.AuthToken != "" { rq.Header.Set(HEADER_AUTH, c.AuthType+" "+c.AuthToken) } @@ -653,7 +653,7 @@ func (c *Client4) DoEmojiUploadFile(url string, data []byte, contentType string) } rq.Header.Set("Content-Type", contentType) - if len(c.AuthToken) > 0 { + if c.AuthToken != "" { rq.Header.Set(HEADER_AUTH, c.AuthType+" "+c.AuthToken) } @@ -677,7 +677,7 @@ func (c *Client4) DoUploadImportTeam(url string, data []byte, contentType string } rq.Header.Set("Content-Type", contentType) - if len(c.AuthToken) > 0 { + if c.AuthToken != "" { rq.Header.Set(HEADER_AUTH, c.AuthType+" "+c.AuthToken) } @@ -1490,7 +1490,7 @@ func (c *Client4) SetProfileImage(userId string, data []byte) (bool, *Response) } rq.Header.Set("Content-Type", writer.FormDataContentType()) - if len(c.AuthToken) > 0 { + if c.AuthToken != "" { rq.Header.Set(HEADER_AUTH, c.AuthType+" "+c.AuthToken) } @@ -1739,7 +1739,7 @@ func (c *Client4) SetBotIconImage(botUserId string, data []byte) (bool, *Respons } rq.Header.Set("Content-Type", writer.FormDataContentType()) - if len(c.AuthToken) > 0 { + if c.AuthToken != "" { rq.Header.Set(HEADER_AUTH, c.AuthType+" "+c.AuthToken) } @@ -2273,7 +2273,7 @@ func (c *Client4) SetTeamIcon(teamId string, data []byte) (bool, *Response) { } rq.Header.Set("Content-Type", writer.FormDataContentType()) - if len(c.AuthToken) > 0 { + if c.AuthToken != "" { rq.Header.Set(HEADER_AUTH, c.AuthType+" "+c.AuthToken) } @@ -3471,7 +3471,7 @@ func (c *Client4) UploadLicenseFile(data []byte) (bool, *Response) { } rq.Header.Set("Content-Type", writer.FormDataContentType()) - if len(c.AuthToken) > 0 { + if c.AuthToken != "" { rq.Header.Set(HEADER_AUTH, c.AuthType+" "+c.AuthToken) } @@ -3878,7 +3878,7 @@ func (c *Client4) DownloadComplianceReport(reportId string) ([]byte, *Response) return nil, &Response{Error: NewAppError("DownloadComplianceReport", "model.client.connecting.app_error", nil, err.Error(), http.StatusBadRequest)} } - if len(c.AuthToken) > 0 { + if c.AuthToken != "" { rq.Header.Set(HEADER_AUTH, "BEARER "+c.AuthToken) } @@ -4248,7 +4248,7 @@ func (c *Client4) UploadBrandImage(data []byte) (bool, *Response) { } rq.Header.Set("Content-Type", writer.FormDataContentType()) - if len(c.AuthToken) > 0 { + if c.AuthToken != "" { rq.Header.Set(HEADER_AUTH, c.AuthType+" "+c.AuthToken) } @@ -4403,7 +4403,7 @@ func (c *Client4) GetOAuthAccessToken(data url.Values) (*AccessResponse, *Respon } rq.Header.Set("Content-Type", "application/x-www-form-urlencoded") - if len(c.AuthToken) > 0 { + if c.AuthToken != "" { rq.Header.Set(HEADER_AUTH, c.AuthType+" "+c.AuthToken) } @@ -5042,7 +5042,7 @@ func (c *Client4) uploadPlugin(file io.Reader, force bool) (*Manifest, *Response } rq.Header.Set("Content-Type", writer.FormDataContentType()) - if len(c.AuthToken) > 0 { + if c.AuthToken != "" { rq.Header.Set(HEADER_AUTH, c.AuthType+" "+c.AuthToken) } diff --git a/model/cluster_discovery.go b/model/cluster_discovery.go index f6c9275a9d..758e498060 100644 --- a/model/cluster_discovery.go +++ b/model/cluster_discovery.go @@ -39,7 +39,7 @@ func (o *ClusterDiscovery) PreSave() { func (o *ClusterDiscovery) AutoFillHostname() { // attempt to set the hostname from the OS - if len(o.Hostname) == 0 { + if o.Hostname == "" { if hn, err := os.Hostname(); err == nil { o.Hostname = hn } @@ -48,8 +48,8 @@ func (o *ClusterDiscovery) AutoFillHostname() { func (o *ClusterDiscovery) AutoFillIpAddress(iface string, ipAddress string) { // attempt to set the hostname to the first non-local IP address - if len(o.Hostname) == 0 { - if len(ipAddress) > 0 { + if o.Hostname == "" { + if ipAddress != "" { o.Hostname = ipAddress } else { o.Hostname = GetServerIpAddress(iface) @@ -93,15 +93,15 @@ func (o *ClusterDiscovery) IsValid() *AppError { return NewAppError("ClusterDiscovery.IsValid", "model.cluster.is_valid.id.app_error", nil, "", http.StatusBadRequest) } - if len(o.ClusterName) == 0 { + if o.ClusterName == "" { return NewAppError("ClusterDiscovery.IsValid", "model.cluster.is_valid.name.app_error", nil, "", http.StatusBadRequest) } - if len(o.Type) == 0 { + if o.Type == "" { return NewAppError("ClusterDiscovery.IsValid", "model.cluster.is_valid.type.app_error", nil, "", http.StatusBadRequest) } - if len(o.Hostname) == 0 { + if o.Hostname == "" { return NewAppError("ClusterDiscovery.IsValid", "model.cluster.is_valid.hostname.app_error", nil, "", http.StatusBadRequest) } diff --git a/model/command.go b/model/command.go index 0013046bba..59a4eee4d1 100644 --- a/model/command.go +++ b/model/command.go @@ -105,7 +105,7 @@ func (o *Command) IsValid() *AppError { return NewAppError("Command.IsValid", "model.command.is_valid.trigger.app_error", nil, "", http.StatusBadRequest) } - if len(o.URL) == 0 || len(o.URL) > 1024 { + if o.URL == "" || len(o.URL) > 1024 { return NewAppError("Command.IsValid", "model.command.is_valid.url.app_error", nil, "", http.StatusBadRequest) } diff --git a/model/compliance.go b/model/compliance.go index 2bb32de9d1..d267e0dc5e 100644 --- a/model/compliance.go +++ b/model/compliance.go @@ -84,7 +84,7 @@ func (c *Compliance) IsValid() *AppError { return NewAppError("Compliance.IsValid", "model.compliance.is_valid.create_at.app_error", nil, "", http.StatusBadRequest) } - if len(c.Desc) > 512 || len(c.Desc) == 0 { + if len(c.Desc) > 512 || c.Desc == "" { return NewAppError("Compliance.IsValid", "model.compliance.is_valid.desc.app_error", nil, "", http.StatusBadRequest) } diff --git a/model/config.go b/model/config.go index 1e1167b565..7211b21679 100644 --- a/model/config.go +++ b/model/config.go @@ -1117,7 +1117,7 @@ func (s *SqlSettings) SetDefaults(isUpdate bool) { if isUpdate { // When updating an existing configuration, ensure an encryption key has been specified. - if s.AtRestEncryptKey == nil || len(*s.AtRestEncryptKey) == 0 { + if s.AtRestEncryptKey == nil || *s.AtRestEncryptKey == "" { s.AtRestEncryptKey = NewString(NewRandomString(32)) } } else { @@ -1383,7 +1383,7 @@ func (s *FileSettings) SetDefaults(isUpdate bool) { if isUpdate { // When updating an existing configuration, ensure link salt has been specified. - if s.PublicLinkSalt == nil || len(*s.PublicLinkSalt) == 0 { + if s.PublicLinkSalt == nil || *s.PublicLinkSalt == "" { s.PublicLinkSalt = NewString(NewRandomString(32)) } } else { @@ -1416,7 +1416,7 @@ func (s *FileSettings) SetDefaults(isUpdate bool) { s.AmazonS3Region = NewString("") } - if s.AmazonS3Endpoint == nil || len(*s.AmazonS3Endpoint) == 0 { + if s.AmazonS3Endpoint == nil || *s.AmazonS3Endpoint == "" { // Defaults to "s3.amazonaws.com" s.AmazonS3Endpoint = NewString("s3.amazonaws.com") } @@ -1529,11 +1529,11 @@ func (s *EmailSettings) SetDefaults(isUpdate bool) { s.SMTPPassword = NewString("") } - if s.SMTPServer == nil || len(*s.SMTPServer) == 0 { + if s.SMTPServer == nil || *s.SMTPServer == "" { s.SMTPServer = NewString("localhost") } - if s.SMTPPort == nil || len(*s.SMTPPort) == 0 { + if s.SMTPPort == nil || *s.SMTPPort == "" { s.SMTPPort = NewString("10025") } @@ -3114,7 +3114,7 @@ func (o *Config) SetDefaults() { } func (o *Config) IsValid() *AppError { - if len(*o.ServiceSettings.SiteURL) == 0 && *o.EmailSettings.EnableEmailBatching { + if *o.ServiceSettings.SiteURL == "" && *o.EmailSettings.EnableEmailBatching { return NewAppError("Config.IsValid", "model.config.is_valid.site_url_email_batching.app_error", nil, "", http.StatusBadRequest) } @@ -3122,7 +3122,7 @@ func (o *Config) IsValid() *AppError { return NewAppError("Config.IsValid", "model.config.is_valid.cluster_email_batching.app_error", nil, "", http.StatusBadRequest) } - if len(*o.ServiceSettings.SiteURL) == 0 && *o.ServiceSettings.AllowCookiesForSubdomains { + if *o.ServiceSettings.SiteURL == "" && *o.ServiceSettings.AllowCookiesForSubdomains { return NewAppError("Config.IsValid", "model.config.is_valid.allow_cookies_for_subdomains.app_error", nil, "", http.StatusBadRequest) } @@ -3245,7 +3245,7 @@ func (s *SqlSettings) isValid() *AppError { return NewAppError("Config.IsValid", "model.config.is_valid.sql_query_timeout.app_error", nil, "", http.StatusBadRequest) } - if len(*s.DataSource) == 0 { + if *s.DataSource == "" { return NewAppError("Config.IsValid", "model.config.is_valid.sql_data_src.app_error", nil, "", http.StatusBadRequest) } @@ -3374,47 +3374,47 @@ func (s *LdapSettings) isValid() *AppError { func (s *SamlSettings) isValid() *AppError { if *s.Enable { - if len(*s.IdpUrl) == 0 || !IsValidHttpUrl(*s.IdpUrl) { + if *s.IdpUrl == "" || !IsValidHttpUrl(*s.IdpUrl) { return NewAppError("Config.IsValid", "model.config.is_valid.saml_idp_url.app_error", nil, "", http.StatusBadRequest) } - if len(*s.IdpDescriptorUrl) == 0 || !IsValidHttpUrl(*s.IdpDescriptorUrl) { + if *s.IdpDescriptorUrl == "" || !IsValidHttpUrl(*s.IdpDescriptorUrl) { return NewAppError("Config.IsValid", "model.config.is_valid.saml_idp_descriptor_url.app_error", nil, "", http.StatusBadRequest) } - if len(*s.IdpCertificateFile) == 0 { + if *s.IdpCertificateFile == "" { return NewAppError("Config.IsValid", "model.config.is_valid.saml_idp_cert.app_error", nil, "", http.StatusBadRequest) } - if len(*s.EmailAttribute) == 0 { + if *s.EmailAttribute == "" { return NewAppError("Config.IsValid", "model.config.is_valid.saml_email_attribute.app_error", nil, "", http.StatusBadRequest) } - if len(*s.UsernameAttribute) == 0 { + if *s.UsernameAttribute == "" { return NewAppError("Config.IsValid", "model.config.is_valid.saml_username_attribute.app_error", nil, "", http.StatusBadRequest) } - if len(*s.ServiceProviderIdentifier) == 0 { + if *s.ServiceProviderIdentifier == "" { return NewAppError("Config.IsValid", "model.config.is_valid.saml_spidentifier_attribute.app_error", nil, "", http.StatusBadRequest) } if *s.Verify { - if len(*s.AssertionConsumerServiceURL) == 0 || !IsValidHttpUrl(*s.AssertionConsumerServiceURL) { + if *s.AssertionConsumerServiceURL == "" || !IsValidHttpUrl(*s.AssertionConsumerServiceURL) { return NewAppError("Config.IsValid", "model.config.is_valid.saml_assertion_consumer_service_url.app_error", nil, "", http.StatusBadRequest) } } if *s.Encrypt { - if len(*s.PrivateKeyFile) == 0 { + if *s.PrivateKeyFile == "" { return NewAppError("Config.IsValid", "model.config.is_valid.saml_private_key.app_error", nil, "", http.StatusBadRequest) } - if len(*s.PublicCertificateFile) == 0 { + if *s.PublicCertificateFile == "" { return NewAppError("Config.IsValid", "model.config.is_valid.saml_public_cert.app_error", nil, "", http.StatusBadRequest) } } - if len(*s.EmailAttribute) == 0 { + if *s.EmailAttribute == "" { return NewAppError("Config.IsValid", "model.config.is_valid.saml_email_attribute.app_error", nil, "", http.StatusBadRequest) } @@ -3425,7 +3425,7 @@ func (s *SamlSettings) isValid() *AppError { return NewAppError("Config.IsValid", "model.config.is_valid.saml_canonical_algorithm.app_error", nil, "", http.StatusBadRequest) } - if len(*s.GuestAttribute) > 0 { + if *s.GuestAttribute != "" { if !(strings.Contains(*s.GuestAttribute, "=")) { return NewAppError("Config.IsValid", "model.config.is_valid.saml_guest_attribute.app_error", nil, "", http.StatusBadRequest) } @@ -3434,7 +3434,7 @@ func (s *SamlSettings) isValid() *AppError { } } - if len(*s.AdminAttribute) > 0 { + if *s.AdminAttribute != "" { if !(strings.Contains(*s.AdminAttribute, "=")) { return NewAppError("Config.IsValid", "model.config.is_valid.saml_admin_attribute.app_error", nil, "", http.StatusBadRequest) } @@ -3535,7 +3535,7 @@ func (s *ServiceSettings) isValid() *AppError { func (s *ElasticsearchSettings) isValid() *AppError { if *s.EnableIndexing { - if len(*s.ConnectionUrl) == 0 { + if *s.ConnectionUrl == "" { return NewAppError("Config.IsValid", "model.config.is_valid.elastic_search.connection_url.app_error", nil, "", http.StatusBadRequest) } } @@ -3573,7 +3573,7 @@ func (s *ElasticsearchSettings) isValid() *AppError { func (bs *BleveSettings) isValid() *AppError { if *bs.EnableIndexing { - if len(*bs.IndexDir) == 0 { + if *bs.IndexDir == "" { return NewAppError("Config.IsValid", "model.config.is_valid.bleve_search.filename.app_error", nil, "", http.StatusBadRequest) } } else { @@ -3608,7 +3608,7 @@ func (s *DataRetentionSettings) isValid() *AppError { } func (s *LocalizationSettings) isValid() *AppError { - if len(*s.AvailableLocales) > 0 { + if *s.AvailableLocales != "" { if !strings.Contains(*s.AvailableLocales, *s.DefaultClientLocale) { return NewAppError("Config.IsValid", "model.config.is_valid.localization.available_locales.app_error", nil, "", http.StatusBadRequest) } @@ -3703,33 +3703,33 @@ func (o *Config) GetSanitizeOptions() map[string]bool { } func (o *Config) Sanitize() { - if o.LdapSettings.BindPassword != nil && len(*o.LdapSettings.BindPassword) > 0 { + if o.LdapSettings.BindPassword != nil && *o.LdapSettings.BindPassword != "" { *o.LdapSettings.BindPassword = FAKE_SETTING } *o.FileSettings.PublicLinkSalt = FAKE_SETTING - if len(*o.FileSettings.AmazonS3SecretAccessKey) > 0 { + if *o.FileSettings.AmazonS3SecretAccessKey != "" { *o.FileSettings.AmazonS3SecretAccessKey = FAKE_SETTING } - if o.EmailSettings.SMTPPassword != nil && len(*o.EmailSettings.SMTPPassword) > 0 { + if o.EmailSettings.SMTPPassword != nil && *o.EmailSettings.SMTPPassword != "" { *o.EmailSettings.SMTPPassword = FAKE_SETTING } - if len(*o.GitLabSettings.Secret) > 0 { + if *o.GitLabSettings.Secret != "" { *o.GitLabSettings.Secret = FAKE_SETTING } - if o.GoogleSettings.Secret != nil && len(*o.GoogleSettings.Secret) > 0 { + if o.GoogleSettings.Secret != nil && *o.GoogleSettings.Secret != "" { *o.GoogleSettings.Secret = FAKE_SETTING } - if o.Office365Settings.Secret != nil && len(*o.Office365Settings.Secret) > 0 { + if o.Office365Settings.Secret != nil && *o.Office365Settings.Secret != "" { *o.Office365Settings.Secret = FAKE_SETTING } - if o.OpenIdSettings.Secret != nil && len(*o.OpenIdSettings.Secret) > 0 { + if o.OpenIdSettings.Secret != nil && *o.OpenIdSettings.Secret != "" { *o.OpenIdSettings.Secret = FAKE_SETTING } @@ -3746,11 +3746,11 @@ func (o *Config) Sanitize() { o.SqlSettings.DataSourceSearchReplicas[i] = FAKE_SETTING } - if o.MessageExportSettings.GlobalRelaySettings.SmtpPassword != nil && len(*o.MessageExportSettings.GlobalRelaySettings.SmtpPassword) > 0 { + if o.MessageExportSettings.GlobalRelaySettings.SmtpPassword != nil && *o.MessageExportSettings.GlobalRelaySettings.SmtpPassword != "" { *o.MessageExportSettings.GlobalRelaySettings.SmtpPassword = FAKE_SETTING } - if o.ServiceSettings.GfycatApiSecret != nil && len(*o.ServiceSettings.GfycatApiSecret) > 0 { + if o.ServiceSettings.GfycatApiSecret != nil && *o.ServiceSettings.GfycatApiSecret != "" { *o.ServiceSettings.GfycatApiSecret = FAKE_SETTING } diff --git a/model/emoji.go b/model/emoji.go index aeee9b3838..1ac3d12238 100644 --- a/model/emoji.go +++ b/model/emoji.go @@ -57,7 +57,7 @@ func (emoji *Emoji) IsValid() *AppError { } func IsValidEmojiName(name string) *AppError { - if len(name) == 0 || len(name) > EMOJI_NAME_MAX_LENGTH || !IsValidAlphaNumHyphenUnderscore(name, false) || inSystemEmoji(name) { + if name == "" || len(name) > EMOJI_NAME_MAX_LENGTH || !IsValidAlphaNumHyphenUnderscore(name, false) || inSystemEmoji(name) { return NewAppError("Emoji.IsValid", "model.emoji.name.app_error", nil, "", http.StatusBadRequest) } diff --git a/model/group.go b/model/group.go index 49783c83da..c70b7aa150 100644 --- a/model/group.go +++ b/model/group.go @@ -139,7 +139,7 @@ func (group *Group) IsValidForCreate() *AppError { return NewAppError("Group.IsValidForCreate", "model.group.source.app_error", nil, "", http.StatusBadRequest) } - if len(group.RemoteId) > GroupRemoteIDMaxLength || (len(group.RemoteId) == 0 && group.requiresRemoteId()) { + if len(group.RemoteId) > GroupRemoteIDMaxLength || (group.RemoteId == "" && group.requiresRemoteId()) { return NewAppError("Group.IsValidForCreate", "model.group.remote_id.app_error", nil, "", http.StatusBadRequest) } diff --git a/model/guest_invite.go b/model/guest_invite.go index 3cdd4893c5..ac803a5d36 100644 --- a/model/guest_invite.go +++ b/model/guest_invite.go @@ -23,7 +23,7 @@ func (i *GuestsInvite) IsValid() *AppError { } for _, email := range i.Emails { - if len(email) > USER_EMAIL_MAX_LENGTH || len(email) == 0 || !IsValidEmail(email) { + if len(email) > USER_EMAIL_MAX_LENGTH || email == "" || !IsValidEmail(email) { return NewAppError("GuestsInvite.IsValid", "model.guest.is_valid.email.app_error", nil, "email="+email, http.StatusBadRequest) } } diff --git a/model/license.go b/model/license.go index 1b324ad660..b4a294ee71 100644 --- a/model/license.go +++ b/model/license.go @@ -296,7 +296,7 @@ func (lr *LicenseRecord) IsValid() *AppError { return NewAppError("LicenseRecord.IsValid", "model.license_record.is_valid.create_at.app_error", nil, "", http.StatusBadRequest) } - if len(lr.Bytes) == 0 || len(lr.Bytes) > 10000 { + if lr.Bytes == "" || len(lr.Bytes) > 10000 { return NewAppError("LicenseRecord.IsValid", "model.license_record.is_valid.create_at.app_error", nil, "", http.StatusBadRequest) } diff --git a/model/oauth.go b/model/oauth.go index 4a345a6e08..0719811626 100644 --- a/model/oauth.go +++ b/model/oauth.go @@ -53,11 +53,11 @@ func (a *OAuthApp) IsValid() *AppError { return NewAppError("OAuthApp.IsValid", "model.oauth.is_valid.creator_id.app_error", nil, "app_id="+a.Id, http.StatusBadRequest) } - if len(a.ClientSecret) == 0 || len(a.ClientSecret) > 128 { + if a.ClientSecret == "" || len(a.ClientSecret) > 128 { return NewAppError("OAuthApp.IsValid", "model.oauth.is_valid.client_secret.app_error", nil, "app_id="+a.Id, http.StatusBadRequest) } - if len(a.Name) == 0 || len(a.Name) > 64 { + if a.Name == "" || len(a.Name) > 64 { return NewAppError("OAuthApp.IsValid", "model.oauth.is_valid.name.app_error", nil, "app_id="+a.Id, http.StatusBadRequest) } @@ -71,7 +71,7 @@ func (a *OAuthApp) IsValid() *AppError { } } - if len(a.Homepage) == 0 || len(a.Homepage) > 256 || !IsValidHttpUrl(a.Homepage) { + if a.Homepage == "" || len(a.Homepage) > 256 || !IsValidHttpUrl(a.Homepage) { return NewAppError("OAuthApp.IsValid", "model.oauth.is_valid.homepage.app_error", nil, "app_id="+a.Id, http.StatusBadRequest) } @@ -79,7 +79,7 @@ func (a *OAuthApp) IsValid() *AppError { return NewAppError("OAuthApp.IsValid", "model.oauth.is_valid.description.app_error", nil, "app_id="+a.Id, http.StatusBadRequest) } - if len(a.IconURL) > 0 { + if a.IconURL != "" { if len(a.IconURL) > 512 || !IsValidHttpUrl(a.IconURL) { return NewAppError("OAuthApp.IsValid", "model.oauth.is_valid.icon_url.app_error", nil, "app_id="+a.Id, http.StatusBadRequest) } diff --git a/model/outgoing_webhook.go b/model/outgoing_webhook.go index d637935c63..0d7a88fb80 100644 --- a/model/outgoing_webhook.go +++ b/model/outgoing_webhook.go @@ -154,7 +154,7 @@ func (o *OutgoingWebhook) IsValid() *AppError { if len(o.TriggerWords) != 0 { for _, triggerWord := range o.TriggerWords { - if len(triggerWord) == 0 { + if triggerWord == "" { return NewAppError("OutgoingWebhook.IsValid", "model.outgoing_hook.is_valid.trigger_words.app_error", nil, "", http.StatusBadRequest) } } @@ -215,7 +215,7 @@ func (o *OutgoingWebhook) PreUpdate() { } func (o *OutgoingWebhook) TriggerWordExactMatch(word string) bool { - if len(word) == 0 { + if word == "" { return false } @@ -229,7 +229,7 @@ func (o *OutgoingWebhook) TriggerWordExactMatch(word string) bool { } func (o *OutgoingWebhook) TriggerWordStartsWith(word string) bool { - if len(word) == 0 { + if word == "" { return false } @@ -243,7 +243,7 @@ func (o *OutgoingWebhook) TriggerWordStartsWith(word string) bool { } func (o *OutgoingWebhook) GetTriggerWord(word string, isExactMatch bool) (triggerWord string) { - if len(word) == 0 { + if word == "" { return } diff --git a/model/plugin_key_value.go b/model/plugin_key_value.go index cd5406ea9d..73ef2d2321 100644 --- a/model/plugin_key_value.go +++ b/model/plugin_key_value.go @@ -21,11 +21,11 @@ type PluginKeyValue struct { } func (kv *PluginKeyValue) IsValid() *AppError { - if len(kv.PluginId) == 0 || utf8.RuneCountInString(kv.PluginId) > KEY_VALUE_PLUGIN_ID_MAX_RUNES { + if kv.PluginId == "" || utf8.RuneCountInString(kv.PluginId) > KEY_VALUE_PLUGIN_ID_MAX_RUNES { return NewAppError("PluginKeyValue.IsValid", "model.plugin_key_value.is_valid.plugin_id.app_error", map[string]interface{}{"Max": KEY_VALUE_KEY_MAX_RUNES, "Min": 0}, "key="+kv.Key, http.StatusBadRequest) } - if len(kv.Key) == 0 || utf8.RuneCountInString(kv.Key) > KEY_VALUE_KEY_MAX_RUNES { + if kv.Key == "" || utf8.RuneCountInString(kv.Key) > KEY_VALUE_KEY_MAX_RUNES { return NewAppError("PluginKeyValue.IsValid", "model.plugin_key_value.is_valid.key.app_error", map[string]interface{}{"Max": KEY_VALUE_KEY_MAX_RUNES, "Min": 0}, "key="+kv.Key, http.StatusBadRequest) } diff --git a/model/post.go b/model/post.go index 5d59bc58c5..f6da3a9cf3 100644 --- a/model/post.go +++ b/model/post.go @@ -277,19 +277,19 @@ func (o *Post) IsValid(maxPostSize int) *AppError { return NewAppError("Post.IsValid", "model.post.is_valid.channel_id.app_error", nil, "", http.StatusBadRequest) } - if !(IsValidId(o.RootId) || len(o.RootId) == 0) { + if !(IsValidId(o.RootId) || o.RootId == "") { return NewAppError("Post.IsValid", "model.post.is_valid.root_id.app_error", nil, "", http.StatusBadRequest) } - if !(IsValidId(o.ParentId) || len(o.ParentId) == 0) { + if !(IsValidId(o.ParentId) || o.ParentId == "") { return NewAppError("Post.IsValid", "model.post.is_valid.parent_id.app_error", nil, "", http.StatusBadRequest) } - if len(o.ParentId) == 26 && len(o.RootId) == 0 { + if len(o.ParentId) == 26 && o.RootId == "" { return NewAppError("Post.IsValid", "model.post.is_valid.root_parent.app_error", nil, "", http.StatusBadRequest) } - if !(len(o.OriginalId) == 26 || len(o.OriginalId) == 0) { + if !(len(o.OriginalId) == 26 || o.OriginalId == "") { return NewAppError("Post.IsValid", "model.post.is_valid.original_id.app_error", nil, "", http.StatusBadRequest) } diff --git a/model/preference.go b/model/preference.go index 3cb6ec98d6..d6a0719e0b 100644 --- a/model/preference.go +++ b/model/preference.go @@ -75,7 +75,7 @@ func (o *Preference) IsValid() *AppError { return NewAppError("Preference.IsValid", "model.preference.is_valid.id.app_error", nil, "user_id="+o.UserId, http.StatusBadRequest) } - if len(o.Category) == 0 || len(o.Category) > 32 { + if o.Category == "" || len(o.Category) > 32 { return NewAppError("Preference.IsValid", "model.preference.is_valid.category.app_error", nil, "category="+o.Category, http.StatusBadRequest) } diff --git a/model/reaction.go b/model/reaction.go index b90a1b2aec..1c4706860b 100644 --- a/model/reaction.go +++ b/model/reaction.go @@ -73,7 +73,7 @@ func (o *Reaction) IsValid() *AppError { validName := regexp.MustCompile(`^[a-zA-Z0-9\-\+_]+$`) - if len(o.EmojiName) == 0 || len(o.EmojiName) > EMOJI_NAME_MAX_LENGTH || !validName.MatchString(o.EmojiName) { + if o.EmojiName == "" || len(o.EmojiName) > EMOJI_NAME_MAX_LENGTH || !validName.MatchString(o.EmojiName) { return NewAppError("Reaction.IsValid", "model.reaction.is_valid.emoji_name.app_error", nil, "emoji_name="+o.EmojiName, http.StatusBadRequest) } diff --git a/model/role.go b/model/role.go index b8bf894c2c..3a6c8a41d2 100644 --- a/model/role.go +++ b/model/role.go @@ -482,7 +482,7 @@ func (r *Role) IsValidWithoutId() bool { return false } - if len(r.DisplayName) == 0 || len(r.DisplayName) > ROLE_DISPLAY_NAME_MAX_LENGTH { + if r.DisplayName == "" || len(r.DisplayName) > ROLE_DISPLAY_NAME_MAX_LENGTH { return false } @@ -526,7 +526,7 @@ func CleanRoleNames(roleNames []string) ([]string, bool) { } func IsValidRoleName(roleName string) bool { - if len(roleName) <= 0 || len(roleName) > ROLE_NAME_MAX_LENGTH { + if roleName == "" || len(roleName) > ROLE_NAME_MAX_LENGTH { return false } diff --git a/model/scheme.go b/model/scheme.go index a510418bfc..b5bbf34abc 100644 --- a/model/scheme.go +++ b/model/scheme.go @@ -114,7 +114,7 @@ func (scheme *Scheme) IsValid() bool { } func (scheme *Scheme) IsValidForCreate() bool { - if len(scheme.DisplayName) == 0 || len(scheme.DisplayName) > SCHEME_DISPLAY_NAME_MAX_LENGTH { + if scheme.DisplayName == "" || len(scheme.DisplayName) > SCHEME_DISPLAY_NAME_MAX_LENGTH { return false } diff --git a/model/search_params.go b/model/search_params.go index 3a5bf8416c..41a2db2aba 100644 --- a/model/search_params.go +++ b/model/search_params.go @@ -312,7 +312,7 @@ func ParseSearchParams(text string, timeZoneOffset int) []*SearchParams { paramsList := []*SearchParams{} - if len(plainTerms) > 0 || len(excludedPlainTerms) > 0 { + if plainTerms != "" || excludedPlainTerms != "" { paramsList = append(paramsList, &SearchParams{ Terms: plainTerms, ExcludedTerms: excludedPlainTerms, @@ -333,7 +333,7 @@ func ParseSearchParams(text string, timeZoneOffset int) []*SearchParams { }) } - if len(hashtagTerms) > 0 || len(excludedHashtagTerms) > 0 { + if hashtagTerms != "" || excludedHashtagTerms != "" { paramsList = append(paramsList, &SearchParams{ Terms: hashtagTerms, ExcludedTerms: excludedHashtagTerms, @@ -355,8 +355,8 @@ func ParseSearchParams(text string, timeZoneOffset int) []*SearchParams { } // special case for when no terms are specified but we still have a filter - if len(plainTerms) == 0 && len(hashtagTerms) == 0 && - len(excludedPlainTerms) == 0 && len(excludedHashtagTerms) == 0 && + if plainTerms == "" && hashtagTerms == "" && + excludedPlainTerms == "" && excludedHashtagTerms == "" && (len(inChannels) != 0 || len(fromUsers) != 0 || len(excludedChannels) != 0 || len(excludedUsers) != 0 || len(extensions) != 0 || len(excludedExtensions) != 0 || diff --git a/model/session.go b/model/session.go index d72401da4d..d56daf2169 100644 --- a/model/session.go +++ b/model/session.go @@ -155,7 +155,7 @@ func (s *Session) GetTeamByTeamId(teamId string) *TeamMember { } func (s *Session) IsMobileApp() bool { - return len(s.DeviceId) > 0 || s.IsMobile() + return s.DeviceId != "" || s.IsMobile() } func (s *Session) IsMobile() bool { diff --git a/model/team.go b/model/team.go index 381eb8bb9f..bb254fa21a 100644 --- a/model/team.go +++ b/model/team.go @@ -152,7 +152,7 @@ func (o *Team) IsValid() *AppError { return NewAppError("Team.IsValid", "model.team.is_valid.email.app_error", nil, "id="+o.Id, http.StatusBadRequest) } - if len(o.Email) > 0 && !IsValidEmail(o.Email) { + if o.Email != "" && !IsValidEmail(o.Email) { return NewAppError("Team.IsValid", "model.team.is_valid.email.app_error", nil, "id="+o.Id, http.StatusBadRequest) } @@ -168,7 +168,7 @@ func (o *Team) IsValid() *AppError { return NewAppError("Team.IsValid", "model.team.is_valid.description.app_error", nil, "id="+o.Id, http.StatusBadRequest) } - if len(o.InviteId) == 0 { + if o.InviteId == "" { return NewAppError("Team.IsValid", "model.team.is_valid.invite_id.app_error", nil, "id="+o.Id, http.StatusBadRequest) } @@ -208,7 +208,7 @@ func (o *Team) PreSave() { o.Description = SanitizeUnicode(o.Description) o.CompanyName = SanitizeUnicode(o.CompanyName) - if len(o.InviteId) == 0 { + if o.InviteId == "" { o.InviteId = NewId() } } diff --git a/model/user.go b/model/user.go index 2d7f422ed7..a47265b813 100644 --- a/model/user.go +++ b/model/user.go @@ -274,7 +274,7 @@ func (u *User) IsValid() *AppError { return InvalidUserError("username", u.Id) } - if len(u.Email) > USER_EMAIL_MAX_LENGTH || len(u.Email) == 0 || !IsValidEmail(u.Email) { + if len(u.Email) > USER_EMAIL_MAX_LENGTH || u.Email == "" || !IsValidEmail(u.Email) { return InvalidUserError("email", u.Id) } @@ -298,11 +298,11 @@ func (u *User) IsValid() *AppError { return InvalidUserError("auth_data", u.Id) } - if u.AuthData != nil && len(*u.AuthData) > 0 && len(u.AuthService) == 0 { + if u.AuthData != nil && *u.AuthData != "" && u.AuthService == "" { return InvalidUserError("auth_data_type", u.Id) } - if len(u.Password) > 0 && u.AuthData != nil && len(*u.AuthData) > 0 { + if u.Password != "" && u.AuthData != nil && *u.AuthData != "" { return InvalidUserError("auth_data_pwd", u.Id) } @@ -381,7 +381,7 @@ func (u *User) PreSave() { u.Timezone = timezones.DefaultUserTimezone() } - if len(u.Password) > 0 { + if u.Password != "" { u.Password = HashPassword(u.Password) } } @@ -414,7 +414,7 @@ func (u *User) PreUpdate() { splitKeys := strings.Split(u.NotifyProps[MENTION_KEYS_NOTIFY_PROP], ",") goodKeys := []string{} for _, key := range splitKeys { - if len(key) > 0 { + if key != "" { goodKeys = append(goodKeys, strings.ToLower(key)) } } @@ -597,11 +597,11 @@ func (u *User) AddNotifyProp(key string, value string) { } func (u *User) GetFullName() string { - if len(u.FirstName) > 0 && len(u.LastName) > 0 { + if u.FirstName != "" && u.LastName != "" { return u.FirstName + " " + u.LastName - } else if len(u.FirstName) > 0 { + } else if u.FirstName != "" { return u.FirstName - } else if len(u.LastName) > 0 { + } else if u.LastName != "" { return u.LastName } else { return "" @@ -612,13 +612,13 @@ func (u *User) getDisplayName(baseName, nameFormat string) string { displayName := baseName if nameFormat == SHOW_NICKNAME_FULLNAME { - if len(u.Nickname) > 0 { + if u.Nickname != "" { displayName = u.Nickname - } else if fullName := u.GetFullName(); len(fullName) > 0 { + } else if fullName := u.GetFullName(); fullName != "" { displayName = fullName } } else if nameFormat == SHOW_FULLNAME { - if fullName := u.GetFullName(); len(fullName) > 0 { + if fullName := u.GetFullName(); fullName != "" { displayName = fullName } } @@ -768,7 +768,7 @@ func HashPassword(password string) string { // ComparePassword compares the hash func ComparePassword(hash string, password string) bool { - if len(password) == 0 || len(hash) == 0 { + if password == "" || hash == "" { return false } @@ -881,7 +881,7 @@ func (u *UserWithGroups) GetGroupIDs() []string { return nil } trimmed := strings.TrimSpace(*u.GroupIDs) - if len(trimmed) == 0 { + if trimmed == "" { return nil } return strings.Split(trimmed, ",") diff --git a/model/utils.go b/model/utils.go index 8edae138e2..1904024976 100644 --- a/model/utils.go +++ b/model/utils.go @@ -335,7 +335,7 @@ func StringFromJson(data io.Reader) string { func GetServerIpAddress(iface string) string { var addrs []net.Addr - if len(iface) == 0 { + if iface == "" { var err error addrs, err = net.InterfaceAddrs() if err != nil { @@ -495,7 +495,7 @@ func IsFileExtImage(ext string) bool { func GetImageMimeType(ext string) string { ext = strings.ToLower(ext) - if len(IMAGE_MIME_TYPES[ext]) == 0 { + if IMAGE_MIME_TYPES[ext] == "" { return "image" } return IMAGE_MIME_TYPES[ext] diff --git a/plugin/helpers_plugin.go b/plugin/helpers_plugin.go index 1bb9e4705e..6fa0c48db6 100644 --- a/plugin/helpers_plugin.go +++ b/plugin/helpers_plugin.go @@ -59,11 +59,11 @@ func (p *HelpersImpl) ensureServerVersion(required string) error { // GetPluginAssetURL implements GetPluginAssetURL. func (p *HelpersImpl) GetPluginAssetURL(pluginID, asset string) (string, error) { - if len(pluginID) == 0 { + if pluginID == "" { return "", errors.New("empty pluginID provided") } - if len(asset) == 0 { + if asset == "" { return "", errors.New("empty asset name provided") } diff --git a/services/filesstore/s3store.go b/services/filesstore/s3store.go index 2b00bc6e11..3b96d1daa1 100644 --- a/services/filesstore/s3store.go +++ b/services/filesstore/s3store.go @@ -352,7 +352,7 @@ func getPathsFromObjectInfos(in <-chan s3.ObjectInfo) <-chan s3.ObjectInfo { func (b *S3FileBackend) ListDirectory(path string) ([]string, error) { path = filepath.Join(b.pathPrefix, path) - if !strings.HasSuffix(path, "/") && len(path) > 0 { + if !strings.HasSuffix(path, "/") && path != "" { // s3Clnt returns only the path itself when "/" is not present // appending "/" to make it consistent across all filesstores path = path + "/" @@ -408,12 +408,12 @@ func s3PutOptions(encrypted bool, contentType string) s3.PutObjectOptions { } func CheckMandatoryS3Fields(settings *model.FileSettings) error { - if settings.AmazonS3Bucket == nil || len(*settings.AmazonS3Bucket) == 0 { + if settings.AmazonS3Bucket == nil || *settings.AmazonS3Bucket == "" { return errors.New("missing s3 bucket settings") } // if S3 endpoint is not set call the set defaults to set that - if settings.AmazonS3Endpoint == nil || len(*settings.AmazonS3Endpoint) == 0 { + if settings.AmazonS3Endpoint == nil || *settings.AmazonS3Endpoint == "" { settings.SetDefaults(true) } diff --git a/services/mailservice/mail.go b/services/mailservice/mail.go index ab0a55c5c0..ef7394cfce 100644 --- a/services/mailservice/mail.go +++ b/services/mailservice/mail.go @@ -273,7 +273,7 @@ func SendMailUsingConfig(to, subject, htmlBody string, config *model.Config, ena // allows for sending an email with attachments and differing MIME/SMTP recipients func sendMailUsingConfigAdvanced(mail mailData, config *model.Config, enableComplianceFeatures bool) *model.AppError { - if len(*config.EmailSettings.SMTPServer) == 0 { + if *config.EmailSettings.SMTPServer == "" { return nil } @@ -324,11 +324,11 @@ func SendMail(c smtpClient, mail mailData, fileBackend filesstore.FileBackend, d "Precedence": {"bulk"}, } - if len(mail.replyTo.Address) > 0 { + if mail.replyTo.Address != "" { headers["Reply-To"] = []string{mail.replyTo.String()} } - if len(mail.cc) > 0 { + if mail.cc != "" { headers["CC"] = []string{mail.cc} } diff --git a/services/mailservice/mail_test.go b/services/mailservice/mail_test.go index be7e237aa0..64515ebe03 100644 --- a/services/mailservice/mail_test.go +++ b/services/mailservice/mail_test.go @@ -424,10 +424,10 @@ func TestSendMail(t *testing.T) { mail := mailData{"", "", mail.Address{}, "", tc.replyTo, "", "", nil, nil, nil} appErr = SendMail(mocm, mail, mockBackend, time.Now()) require.Nil(t, appErr) - if len(tc.contains) > 0 { + if tc.contains != "" { require.Contains(t, string(mocm.data), tc.contains) } - if len(tc.notContains) > 0 { + if tc.notContains != "" { require.NotContains(t, string(mocm.data), tc.notContains) } mocm.data = []byte{} diff --git a/services/mfa/mfa.go b/services/mfa/mfa.go index 2748f0be7a..6b87b07ddb 100644 --- a/services/mfa/mfa.go +++ b/services/mfa/mfa.go @@ -43,7 +43,7 @@ func getIssuerFromUrl(uri string) string { issuer := "Mattermost" siteUrl := strings.TrimSpace(uri) - if len(siteUrl) > 0 { + if siteUrl != "" { siteUrl = strings.TrimPrefix(siteUrl, "https://") siteUrl = strings.TrimPrefix(siteUrl, "http://") issuer = strings.TrimPrefix(siteUrl, "www.") diff --git a/services/searchengine/bleveengine/search.go b/services/searchengine/bleveengine/search.go index a0ff5bb357..190f5c9e91 100644 --- a/services/searchengine/bleveengine/search.go +++ b/services/searchengine/bleveengine/search.go @@ -159,7 +159,7 @@ func (b *BleveEngine) SearchPosts(channels *model.ChannelList, searchParams []*m notTermQueries = append(notTermQueries, hashtagQ) } } else { - if len(params.Terms) > 0 { + if params.Terms != "" { terms := []string{} for _, term := range strings.Split(params.Terms, " ") { if strings.HasSuffix(term, "*") { @@ -179,7 +179,7 @@ func (b *BleveEngine) SearchPosts(channels *model.ChannelList, searchParams []*m } } - if len(params.ExcludedTerms) > 0 { + if params.ExcludedTerms != "" { messageQ := bleve.NewMatchQuery(params.ExcludedTerms) messageQ.SetField("Message") messageQ.SetOperator(termOperator) @@ -654,7 +654,7 @@ func (b *BleveEngine) SearchFiles(channels *model.ChannelList, searchParams []*m } } - if len(params.Terms) > 0 { + if params.Terms != "" { terms := []string{} for _, term := range strings.Split(params.Terms, " ") { if strings.HasSuffix(term, "*") { @@ -679,7 +679,7 @@ func (b *BleveEngine) SearchFiles(channels *model.ChannelList, searchParams []*m } } - if len(params.ExcludedTerms) > 0 { + if params.ExcludedTerms != "" { nameQ := bleve.NewMatchQuery(params.ExcludedTerms) nameQ.SetField("Name") nameQ.SetOperator(termOperator) diff --git a/services/telemetry/telemetry.go b/services/telemetry/telemetry.go index c77ab3dfec..54050b3a13 100644 --- a/services/telemetry/telemetry.go +++ b/services/telemetry/telemetry.go @@ -126,7 +126,7 @@ func (ts *TelemetryService) ensureTelemetryID() { } id := props[model.SYSTEM_TELEMETRY_ID] - if len(id) == 0 { + if id == "" { id = model.NewId() systemID := &model.System{Name: model.SYSTEM_TELEMETRY_ID, Value: id} ts.dbStore.System().Save(systemID) diff --git a/store/sqlstore/channel_store.go b/store/sqlstore/channel_store.go index a8e338a220..23b4ad6ddf 100644 --- a/store/sqlstore/channel_store.go +++ b/store/sqlstore/channel_store.go @@ -623,7 +623,7 @@ func (s SqlChannelStore) SaveDirectChannel(directchannel *model.Channel, member1 } func (s SqlChannelStore) saveChannelT(transaction *gorp.Transaction, channel *model.Channel, maxChannelsPerTeam int64) (*model.Channel, error) { - if len(channel.Id) > 0 { + if channel.Id != "" { return nil, store.NewErrInvalidInput("Channel", "Id", channel.Id) } @@ -1031,7 +1031,7 @@ func (s SqlChannelStore) getAllChannelsQuery(opts store.ChannelSearchOpts, forCo query = query.Where(sq.Eq{"c.DeleteAt": int(0)}) } - if len(opts.NotAssociatedToGroup) > 0 { + if opts.NotAssociatedToGroup != "" { query = query.Where("c.Id NOT IN (SELECT ChannelId FROM GroupChannels WHERE GroupChannels.GroupId = ? AND GroupChannels.DeleteAt = 0)", opts.NotAssociatedToGroup) } @@ -1142,7 +1142,7 @@ func (s SqlChannelStore) GetPublicChannelsByIdsForTeam(teamId string, channelIds idQuery := "" for index, channelId := range channelIds { - if len(idQuery) > 0 { + if idQuery != "" { idQuery += ", " } @@ -2335,7 +2335,7 @@ func (s SqlChannelStore) GetForPost(postId string) (*model.Channel, error) { func (s SqlChannelStore) AnalyticsTypeCount(teamId string, channelType string) (int64, error) { query := "SELECT COUNT(Id) AS Value FROM Channels WHERE Type = :ChannelType" - if len(teamId) > 0 { + if teamId != "" { query += " AND TeamId = :TeamId" } @@ -2349,7 +2349,7 @@ func (s SqlChannelStore) AnalyticsTypeCount(teamId string, channelType string) ( func (s SqlChannelStore) AnalyticsDeletedTypeCount(teamId string, channelType string) (int64, error) { query := "SELECT COUNT(Id) AS Value FROM Channels WHERE Type = :ChannelType AND DeleteAt > 0" - if len(teamId) > 0 { + if teamId != "" { query += " AND TeamId = :TeamId" } @@ -2681,7 +2681,7 @@ func (s SqlChannelStore) channelSearchQuery(term string, opts store.ChannelSearc query = query.Where(sq.NotEq{"c.Name": opts.ExcludeChannelNames}) } - if len(opts.NotAssociatedToGroup) > 0 { + if opts.NotAssociatedToGroup != "" { query = query.Where("c.Id NOT IN (SELECT ChannelId FROM GroupChannels WHERE GroupChannels.GroupId = ? AND GroupChannels.DeleteAt = 0)", opts.NotAssociatedToGroup) } diff --git a/store/sqlstore/command_store.go b/store/sqlstore/command_store.go index b920249472..c9c69a8937 100644 --- a/store/sqlstore/command_store.go +++ b/store/sqlstore/command_store.go @@ -54,7 +54,7 @@ func (s SqlCommandStore) createIndexesIfNotExists() { } func (s SqlCommandStore) Save(command *model.Command) (*model.Command, error) { - if len(command.Id) > 0 { + if command.Id != "" { return nil, store.NewErrInvalidInput("Command", "CommandId", command.Id) } @@ -193,7 +193,7 @@ func (s SqlCommandStore) AnalyticsCommandCount(teamId string) (int64, error) { From("Commands"). Where(sq.Eq{"DeleteAt": 0}) - if len(teamId) > 0 { + if teamId != "" { query = query.Where(sq.Eq{"TeamId": teamId}) } diff --git a/store/sqlstore/command_webhook_store.go b/store/sqlstore/command_webhook_store.go index 89c843fec9..7d2a82f516 100644 --- a/store/sqlstore/command_webhook_store.go +++ b/store/sqlstore/command_webhook_store.go @@ -39,7 +39,7 @@ func (s SqlCommandWebhookStore) createIndexesIfNotExists() { } func (s SqlCommandWebhookStore) Save(webhook *model.CommandWebhook) (*model.CommandWebhook, error) { - if len(webhook.Id) > 0 { + if webhook.Id != "" { return nil, store.NewErrInvalidInput("CommandWebhook", "id", webhook.Id) } diff --git a/store/sqlstore/file_info_store.go b/store/sqlstore/file_info_store.go index 07e9c2b4e5..56a3d9e4e5 100644 --- a/store/sqlstore/file_info_store.go +++ b/store/sqlstore/file_info_store.go @@ -476,31 +476,31 @@ func (fs SqlFileInfoStore) Search(paramsList []*model.SearchParams, userId, team } // handle after: before: on: filters - if len(params.OnDate) > 0 { + if params.OnDate != "" { onDateStart, onDateEnd := params.GetOnDateMillis() query = query.Where(sq.Expr("FI.CreateAt BETWEEN ? AND ?", strconv.FormatInt(onDateStart, 10), strconv.FormatInt(onDateEnd, 10))) } else { - if len(params.ExcludedDate) > 0 { + if params.ExcludedDate != "" { excludedDateStart, excludedDateEnd := params.GetExcludedDateMillis() query = query.Where(sq.Expr("FI.CreateAt NOT BETWEEN ? AND ?", strconv.FormatInt(excludedDateStart, 10), strconv.FormatInt(excludedDateEnd, 10))) } - if len(params.AfterDate) > 0 { + if params.AfterDate != "" { afterDate := params.GetAfterDateMillis() query = query.Where(sq.GtOrEq{"FI.CreateAt": strconv.FormatInt(afterDate, 10)}) } - if len(params.BeforeDate) > 0 { + if params.BeforeDate != "" { beforeDate := params.GetBeforeDateMillis() query = query.Where(sq.LtOrEq{"FI.CreateAt": strconv.FormatInt(beforeDate, 10)}) } - if len(params.ExcludedAfterDate) > 0 { + if params.ExcludedAfterDate != "" { afterDate := params.GetExcludedAfterDateMillis() query = query.Where(sq.Lt{"FI.CreateAt": strconv.FormatInt(afterDate, 10)}) } - if len(params.ExcludedBeforeDate) > 0 { + if params.ExcludedBeforeDate != "" { beforeDate := params.GetExcludedBeforeDateMillis() query = query.Where(sq.Gt{"FI.CreateAt": strconv.FormatInt(beforeDate, 10)}) } diff --git a/store/sqlstore/group_store.go b/store/sqlstore/group_store.go index 8600add275..0a53c54805 100644 --- a/store/sqlstore/group_store.go +++ b/store/sqlstore/group_store.go @@ -986,7 +986,7 @@ func (s *SqlGroupStore) groupsBySyncableBaseQuery(st model.GroupSyncableType, t query = query.Where("ug.AllowReference = true") } - if len(opts.Q) > 0 { + if opts.Q != "" { pattern := fmt.Sprintf("%%%s%%", sanitizeSearchTerm(opts.Q, "\\")) operatorKeyword := "ILIKE" if s.DriverName() == model.DATABASE_DRIVER_MYSQL { @@ -1051,7 +1051,7 @@ func (s *SqlGroupStore) getGroupsAssociatedToChannelsByTeam(st model.GroupSyncab query = query.Where("ug.AllowReference = true") } - if len(opts.Q) > 0 { + if opts.Q != "" { pattern := fmt.Sprintf("%%%s%%", sanitizeSearchTerm(opts.Q, "\\")) operatorKeyword := "ILIKE" if s.DriverName() == model.DATABASE_DRIVER_MYSQL { @@ -1171,7 +1171,7 @@ func (s *SqlGroupStore) GetGroups(page, perPage int, opts model.GroupSearchOpts) groupsQuery = groupsQuery.Where("g.AllowReference = true") } - if len(opts.Q) > 0 { + if opts.Q != "" { pattern := fmt.Sprintf("%%%s%%", sanitizeSearchTerm(opts.Q, "\\")) operatorKeyword := "ILIKE" if s.DriverName() == model.DATABASE_DRIVER_MYSQL { diff --git a/store/sqlstore/oauth_store.go b/store/sqlstore/oauth_store.go index d2a231e9fa..a1dc48285d 100644 --- a/store/sqlstore/oauth_store.go +++ b/store/sqlstore/oauth_store.go @@ -62,7 +62,7 @@ func (as SqlOAuthStore) createIndexesIfNotExists() { } func (as SqlOAuthStore) SaveApp(app *model.OAuthApp) (*model.OAuthApp, error) { - if len(app.Id) > 0 { + if app.Id != "" { return nil, store.NewErrInvalidInput("OAuthApp", "Id", app.Id) } diff --git a/store/sqlstore/post_store.go b/store/sqlstore/post_store.go index fdcd0543b7..ab21d0f001 100644 --- a/store/sqlstore/post_store.go +++ b/store/sqlstore/post_store.go @@ -114,7 +114,7 @@ func (s *SqlPostStore) SaveMultiple(posts []*model.Post) ([]*model.Post, int, er rootIds := make(map[string]int) maxDateRootIds := make(map[string]int64) for idx, post := range posts { - if len(post.Id) > 0 { + if post.Id != "" { return nil, idx, store.NewErrInvalidInput("Post", "id", post.Id) } post.PreSave() @@ -140,7 +140,7 @@ func (s *SqlPostStore) SaveMultiple(posts []*model.Post) ([]*model.Post, int, er } } - if len(post.RootId) == 0 { + if post.RootId == "" { continue } @@ -199,7 +199,7 @@ func (s *SqlPostStore) SaveMultiple(posts []*model.Post) ([]*model.Post, int, er unknownRepliesPosts := []*model.Post{} for _, post := range posts { - if len(post.RootId) == 0 { + if post.RootId == "" { count, ok := rootIds[post.Id] if ok { post.ReplyCount += int64(count) @@ -285,7 +285,7 @@ func (s *SqlPostStore) Update(newPost *model.Post, oldPost *model.Post) (*model. time := model.GetMillis() s.GetMaster().Exec("UPDATE Channels SET LastPostAt = :LastPostAt WHERE Id = :ChannelId AND LastPostAt < :LastPostAt", map[string]interface{}{"LastPostAt": time, "ChannelId": newPost.ChannelId}) - if len(newPost.RootId) > 0 { + if newPost.RootId != "" { s.GetMaster().Exec("UPDATE Posts SET UpdateAt = :UpdateAt WHERE Id = :RootId AND UpdateAt < :UpdateAt", map[string]interface{}{"UpdateAt": time, "RootId": newPost.RootId}) s.GetMaster().Exec("UPDATE Threads SET LastReplyAt = :UpdateAt WHERE PostId = :RootId", map[string]interface{}{"UpdateAt": time, "RootId": newPost.RootId}) } @@ -319,7 +319,7 @@ func (s *SqlPostStore) OverwriteMultiple(posts []*model.Post) ([]*model.Post, in return nil, idx, errors.Wrap(err, "failed to update Post") } - if len(post.RootId) > 0 { + if post.RootId != "" { tx.Exec("UPDATE Threads SET LastReplyAt = :UpdateAt WHERE PostId = :RootId", map[string]interface{}{"UpdateAt": updateAt, "RootId": post.Id}) } } @@ -425,7 +425,7 @@ func (s *SqlPostStore) GetFlaggedPostsForChannel(userId, channelId string, offse return pl, nil } func (s *SqlPostStore) getPostWithCollapsedThreads(id string, extended bool) (*model.PostList, error) { - if len(id) == 0 { + if id == "" { return nil, store.NewErrInvalidInput("Post", "id", id) } @@ -460,7 +460,7 @@ func (s *SqlPostStore) Get(id string, skipFetchThreads, collapsedThreads, collap } pl := model.NewPostList() - if len(id) == 0 { + if id == "" { return nil, store.NewErrInvalidInput("Post", "id", id) } @@ -483,7 +483,7 @@ func (s *SqlPostStore) Get(id string, skipFetchThreads, collapsedThreads, collap rootId = post.Id } - if len(rootId) == 0 { + if rootId == "" { return nil, errors.Wrapf(err, "invalid rootId with value=%s", rootId) } @@ -1247,7 +1247,7 @@ var specialSearchChar = []string{ func (s *SqlPostStore) buildCreateDateFilterClause(params *model.SearchParams, queryParams map[string]interface{}) (string, map[string]interface{}) { searchQuery := "" // handle after: before: on: filters - if len(params.OnDate) > 0 { + if params.OnDate != "" { onDateStart, onDateEnd := params.GetOnDateMillis() queryParams["OnDateStart"] = strconv.FormatInt(onDateStart, 10) queryParams["OnDateEnd"] = strconv.FormatInt(onDateEnd, 10) @@ -1256,7 +1256,7 @@ func (s *SqlPostStore) buildCreateDateFilterClause(params *model.SearchParams, q searchQuery += "AND CreateAt BETWEEN :OnDateStart AND :OnDateEnd " } else { - if len(params.ExcludedDate) > 0 { + if params.ExcludedDate != "" { excludedDateStart, excludedDateEnd := params.GetExcludedDateMillis() queryParams["ExcludedDateStart"] = strconv.FormatInt(excludedDateStart, 10) queryParams["ExcludedDateEnd"] = strconv.FormatInt(excludedDateEnd, 10) @@ -1264,7 +1264,7 @@ func (s *SqlPostStore) buildCreateDateFilterClause(params *model.SearchParams, q searchQuery += "AND CreateAt NOT BETWEEN :ExcludedDateStart AND :ExcludedDateEnd " } - if len(params.AfterDate) > 0 { + if params.AfterDate != "" { afterDate := params.GetAfterDateMillis() queryParams["AfterDate"] = strconv.FormatInt(afterDate, 10) @@ -1272,7 +1272,7 @@ func (s *SqlPostStore) buildCreateDateFilterClause(params *model.SearchParams, q searchQuery += "AND CreateAt >= :AfterDate " } - if len(params.BeforeDate) > 0 { + if params.BeforeDate != "" { beforeDate := params.GetBeforeDateMillis() queryParams["BeforeDate"] = strconv.FormatInt(beforeDate, 10) @@ -1280,14 +1280,14 @@ func (s *SqlPostStore) buildCreateDateFilterClause(params *model.SearchParams, q searchQuery += "AND CreateAt <= :BeforeDate " } - if len(params.ExcludedAfterDate) > 0 { + if params.ExcludedAfterDate != "" { afterDate := params.GetExcludedAfterDateMillis() queryParams["ExcludedAfterDate"] = strconv.FormatInt(afterDate, 10) searchQuery += "AND CreateAt < :ExcludedAfterDate " } - if len(params.ExcludedBeforeDate) > 0 { + if params.ExcludedBeforeDate != "" { beforeDate := params.GetExcludedBeforeDateMillis() queryParams["ExcludedBeforeDate"] = strconv.FormatInt(beforeDate, 10) @@ -1387,7 +1387,7 @@ func (s *SqlPostStore) search(teamId string, userId string, params *model.Search if params.Terms == "" && params.ExcludedTerms == "" && len(params.InChannels) == 0 && len(params.ExcludedChannels) == 0 && len(params.FromUsers) == 0 && len(params.ExcludedUsers) == 0 && - len(params.OnDate) == 0 && len(params.AfterDate) == 0 && len(params.BeforeDate) == 0 { + params.OnDate == "" && params.AfterDate == "" && params.BeforeDate == "" { return list, nil } @@ -1576,7 +1576,7 @@ func (s *SqlPostStore) AnalyticsUserCountsWithPostsByDay(teamId string) (model.A COUNT(DISTINCT Posts.UserId) AS Value FROM Posts` - if len(teamId) > 0 { + if teamId != "" { query += " INNER JOIN Channels ON Posts.ChannelId = Channels.Id AND Channels.TeamId = :TeamId AND" } else { query += " WHERE" @@ -1593,7 +1593,7 @@ func (s *SqlPostStore) AnalyticsUserCountsWithPostsByDay(teamId string) (model.A TO_CHAR(DATE(TO_TIMESTAMP(Posts.CreateAt / 1000)), 'YYYY-MM-DD') AS Name, COUNT(DISTINCT Posts.UserId) AS Value FROM Posts` - if len(teamId) > 0 { + if teamId != "" { query += " INNER JOIN Channels ON Posts.ChannelId = Channels.Id AND Channels.TeamId = :TeamId AND" } else { query += " WHERE" @@ -1631,7 +1631,7 @@ func (s *SqlPostStore) AnalyticsPostCountsByDay(options *model.AnalyticsPostCoun query += " INNER JOIN Bots ON Posts.UserId = Bots.Userid" } - if len(options.TeamId) > 0 { + if options.TeamId != "" { query += " INNER JOIN Channels ON Posts.ChannelId = Channels.Id AND Channels.TeamId = :TeamId AND" } else { query += " WHERE" @@ -1653,7 +1653,7 @@ func (s *SqlPostStore) AnalyticsPostCountsByDay(options *model.AnalyticsPostCoun query += " INNER JOIN Bots ON Posts.UserId = Bots.Userid" } - if len(options.TeamId) > 0 { + if options.TeamId != "" { query += " INNER JOIN Channels ON Posts.ChannelId = Channels.Id AND Channels.TeamId = :TeamId AND" } else { query += " WHERE" @@ -1688,7 +1688,7 @@ func (s *SqlPostStore) AnalyticsPostCount(teamId string, mustHaveFile bool, must Select("COUNT(p.Id) AS Value"). From("Posts p") - if len(teamId) > 0 { + if teamId != "" { query = query. Join("Channels c ON (c.Id = p.ChannelId)"). Where(sq.Eq{"c.TeamId": teamId}) @@ -2103,7 +2103,7 @@ func (s *SqlPostStore) cleanupThreads(postId, rootId, userId string, permanent b } return nil } - if len(rootId) > 0 { + if rootId != "" { thread, err := s.Thread().Get(rootId) if err != nil { if err != sql.ErrNoRows { @@ -2125,7 +2125,7 @@ func (s *SqlPostStore) updateThreadsFromPosts(transaction *gorp.Transaction, pos var rootIds []string for _, post := range posts { // skip if post is not a part of a thread - if len(post.RootId) == 0 { + if post.RootId == "" { continue } rootIds = append(rootIds, post.RootId) diff --git a/store/sqlstore/role_store.go b/store/sqlstore/role_store.go index 09473fe898..b037b05c9f 100644 --- a/store/sqlstore/role_store.go +++ b/store/sqlstore/role_store.go @@ -102,7 +102,7 @@ func (s *SqlRoleStore) Save(role *model.Role) (*model.Role, error) { return nil, store.NewErrInvalidInput("Role", "", fmt.Sprintf("%v", role)) } - if len(role.Id) == 0 { + if role.Id == "" { transaction, err := s.GetMaster().Begin() if err != nil { return nil, errors.Wrap(err, "begin_transaction") diff --git a/store/sqlstore/scheme_store.go b/store/sqlstore/scheme_store.go index 9164dd7115..cd13bad1dc 100644 --- a/store/sqlstore/scheme_store.go +++ b/store/sqlstore/scheme_store.go @@ -47,7 +47,7 @@ func (s SqlSchemeStore) createIndexesIfNotExists() { } func (s *SqlSchemeStore) Save(scheme *model.Scheme) (*model.Scheme, error) { - if len(scheme.Id) == 0 { + if scheme.Id == "" { transaction, err := s.GetMaster().Begin() if err != nil { return nil, errors.Wrap(err, "begin_transaction") @@ -213,7 +213,7 @@ func (s *SqlSchemeStore) createScheme(scheme *model.Scheme, transaction *gorp.Tr } scheme.Id = model.NewId() - if len(scheme.Name) == 0 { + if scheme.Name == "" { scheme.Name = model.NewId() } scheme.CreateAt = model.GetMillis() @@ -332,7 +332,7 @@ func (s *SqlSchemeStore) GetAllPage(scope string, offset int, limit int) ([]*mod var schemes []*model.Scheme scopeClause := "" - if len(scope) > 0 { + if scope != "" { scopeClause = " AND Scope=:Scope " } diff --git a/store/sqlstore/session_store.go b/store/sqlstore/session_store.go index 597136b811..c670c729e4 100644 --- a/store/sqlstore/session_store.go +++ b/store/sqlstore/session_store.go @@ -49,7 +49,7 @@ func (me SqlSessionStore) createIndexesIfNotExists() { } func (me SqlSessionStore) Save(session *model.Session) (*model.Session, error) { - if len(session.Id) > 0 { + if session.Id != "" { return nil, store.NewErrInvalidInput("Session", "id", session.Id) } session.PreSave() diff --git a/store/sqlstore/store.go b/store/sqlstore/store.go index 082e892cd2..e5a1385d3e 100644 --- a/store/sqlstore/store.go +++ b/store/sqlstore/store.go @@ -424,7 +424,7 @@ func (ss *SqlStore) MarkSystemRanUnitTests() { } unitTests := props[model.SYSTEM_RAN_UNIT_TESTS] - if len(unitTests) == 0 { + if unitTests == "" { systemTests := &model.System{Name: model.SYSTEM_RAN_UNIT_TESTS, Value: "1"} ss.System().Save(systemTests) } diff --git a/store/sqlstore/team_store.go b/store/sqlstore/team_store.go index 22473222d1..5d2faf5048 100644 --- a/store/sqlstore/team_store.go +++ b/store/sqlstore/team_store.go @@ -250,7 +250,7 @@ func (s SqlTeamStore) createIndexesIfNotExists() { // Save adds the team to the database if a team with the same name does not already // exist in the database. It returns the team added if the operation is successful. func (s SqlTeamStore) Save(team *model.Team) (*model.Team, error) { - if len(team.Id) > 0 { + if team.Id != "" { return nil, store.NewErrInvalidInput("Team", "id", team.Id) } @@ -335,7 +335,7 @@ func (s SqlTeamStore) GetByInviteId(inviteId string) (*model.Team, error) { return nil, store.NewErrNotFound("Team", fmt.Sprintf("inviteId=%s", inviteId)) } - if len(inviteId) == 0 || team.InviteId != inviteId { + if inviteId == "" || team.InviteId != inviteId { return nil, store.NewErrNotFound("Team", fmt.Sprintf("inviteId=%s", inviteId)) } return &team, nil @@ -405,7 +405,7 @@ func (s SqlTeamStore) teamSearchQuery(term string, opts *model.TeamSearch, count } } - if len(term) > 0 { + if term != "" { term = sanitizeSearchTerm(term, "\\") term = wildcardSearchTerm(term) diff --git a/store/sqlstore/terms_of_service_store.go b/store/sqlstore/terms_of_service_store.go index 32dd6f6026..ad17d5b754 100644 --- a/store/sqlstore/terms_of_service_store.go +++ b/store/sqlstore/terms_of_service_store.go @@ -35,7 +35,7 @@ func (s SqlTermsOfServiceStore) createIndexesIfNotExists() { } func (s SqlTermsOfServiceStore) Save(termsOfService *model.TermsOfService) (*model.TermsOfService, error) { - if len(termsOfService.Id) > 0 { + if termsOfService.Id != "" { return nil, store.NewErrInvalidInput("TermsOfService", "Id", termsOfService.Id) } diff --git a/store/sqlstore/user_store.go b/store/sqlstore/user_store.go index 861ceffdde..753dd0cbe4 100644 --- a/store/sqlstore/user_store.go +++ b/store/sqlstore/user_store.go @@ -99,7 +99,7 @@ func (us SqlUserStore) createIndexesIfNotExists() { } func (us SqlUserStore) Save(user *model.User) (*model.User, error) { - if len(user.Id) > 0 { + if user.Id != "" { return nil, store.NewErrInvalidInput("User", "id", user.Id) } diff --git a/store/sqlstore/webhook_store.go b/store/sqlstore/webhook_store.go index da611cd707..beca775fb2 100644 --- a/store/sqlstore/webhook_store.go +++ b/store/sqlstore/webhook_store.go @@ -77,7 +77,7 @@ func (s SqlWebhookStore) InvalidateWebhookCache(webhookId string) { func (s SqlWebhookStore) SaveIncoming(webhook *model.IncomingWebhook) (*model.IncomingWebhook, error) { - if len(webhook.Id) > 0 { + if webhook.Id != "" { return nil, store.NewErrInvalidInput("IncomingWebhook", "id", webhook.Id) } @@ -154,7 +154,7 @@ func (s SqlWebhookStore) GetIncomingListByUser(userId string, offset, limit int) From("IncomingWebhooks"). Where(sq.Eq{"DeleteAt": int(0)}).Limit(uint64(limit)).Offset(uint64(offset)) - if len(userId) > 0 { + if userId != "" { query = query.Where(sq.Eq{"UserId": userId}) } @@ -182,7 +182,7 @@ func (s SqlWebhookStore) GetIncomingByTeamByUser(teamId string, userId string, o sq.Eq{"DeleteAt": int(0)}, }).Limit(uint64(limit)).Offset(uint64(offset)) - if len(userId) > 0 { + if userId != "" { query = query.Where(sq.Eq{"UserId": userId}) } @@ -213,7 +213,7 @@ func (s SqlWebhookStore) GetIncomingByChannel(channelId string) ([]*model.Incomi } func (s SqlWebhookStore) SaveOutgoing(webhook *model.OutgoingWebhook) (*model.OutgoingWebhook, error) { - if len(webhook.Id) > 0 { + if webhook.Id != "" { return nil, store.NewErrInvalidInput("OutgoingWebhook", "id", webhook.Id) } @@ -254,7 +254,7 @@ func (s SqlWebhookStore) GetOutgoingListByUser(userId string, offset, limit int) sq.Eq{"DeleteAt": int(0)}, }).Limit(uint64(limit)).Offset(uint64(offset)) - if len(userId) > 0 { + if userId != "" { query = query.Where(sq.Eq{"CreatorId": userId}) } @@ -286,7 +286,7 @@ func (s SqlWebhookStore) GetOutgoingByChannelByUser(channelId string, userId str sq.Eq{"DeleteAt": int(0)}, }) - if len(userId) > 0 { + if userId != "" { query = query.Where(sq.Eq{"CreatorId": userId}) } if limit >= 0 && offset >= 0 { @@ -320,7 +320,7 @@ func (s SqlWebhookStore) GetOutgoingByTeamByUser(teamId string, userId string, o sq.Eq{"DeleteAt": int(0)}, }) - if len(userId) > 0 { + if userId != "" { query = query.Where(sq.Eq{"CreatorId": userId}) } if limit >= 0 && offset >= 0 { @@ -391,7 +391,7 @@ func (s SqlWebhookStore) AnalyticsIncomingCount(teamId string) (int64, error) { WHERE DeleteAt = 0` - if len(teamId) > 0 { + if teamId != "" { query += " AND TeamId = :TeamId" } @@ -412,7 +412,7 @@ func (s SqlWebhookStore) AnalyticsOutgoingCount(teamId string) (int64, error) { WHERE DeleteAt = 0` - if len(teamId) > 0 { + if teamId != "" { query += " AND TeamId = :TeamId" } diff --git a/utils/utils.go b/utils/utils.go index 5135dbfc07..fe114ee7a0 100644 --- a/utils/utils.go +++ b/utils/utils.go @@ -99,19 +99,19 @@ func GetIpAddress(r *http.Request, trustedProxyIPHeader []string) string { for _, proxyHeader := range trustedProxyIPHeader { header := r.Header.Get(proxyHeader) - if len(header) > 0 { + if header != "" { addresses := strings.Fields(header) if len(addresses) > 0 { address = strings.TrimRight(addresses[0], ",") } } - if len(address) > 0 { + if address != "" { return address } } - if len(address) == 0 { + if address == "" { address, _, _ = net.SplitHostPort(r.RemoteAddr) } diff --git a/web/context.go b/web/context.go index e4b5c8d084..3264f29142 100644 --- a/web/context.go +++ b/web/context.go @@ -74,7 +74,7 @@ func (c *Context) LogAudit(extraInfo string) { func (c *Context) LogAuditWithUserId(userId, extraInfo string) { - if len(c.App.Session().UserId) > 0 { + if c.App.Session().UserId != "" { extraInfo = strings.TrimSpace(extraInfo + " session_user=" + c.App.Session().UserId) } @@ -117,7 +117,7 @@ func (c *Context) SessionRequired() { return } - if len(c.App.Session().UserId) == 0 { + if c.App.Session().UserId == "" { c.Err = model.NewAppError("", "api.context.session_expired.app_error", nil, "UserRequired", http.StatusUnauthorized) return } @@ -214,7 +214,7 @@ func (c *Context) SetCommandNotFoundError() { func (c *Context) HandleEtag(etag string, routeName string, w http.ResponseWriter, r *http.Request) bool { metrics := c.App.Metrics() - if et := r.Header.Get(model.HEADER_ETAG_CLIENT); len(etag) > 0 { + if et := r.Header.Get(model.HEADER_ETAG_CLIENT); etag != "" { if et == etag { w.Header().Set(model.HEADER_ETAG_SERVER, etag) w.WriteHeader(http.StatusNotModified) @@ -299,7 +299,7 @@ func (c *Context) RequireInviteId() *Context { return c } - if len(c.Params.InviteId) == 0 { + if c.Params.InviteId == "" { c.SetInvalidUrlParam("invite_id") } return c @@ -412,7 +412,7 @@ func (c *Context) RequireFilename() *Context { return c } - if len(c.Params.Filename) == 0 { + if c.Params.Filename == "" { c.SetInvalidUrlParam("filename") } @@ -424,7 +424,7 @@ func (c *Context) RequirePluginId() *Context { return c } - if len(c.Params.PluginId) == 0 { + if c.Params.PluginId == "" { c.SetInvalidUrlParam("plugin_id") } @@ -506,7 +506,7 @@ func (c *Context) RequireService() *Context { return c } - if len(c.Params.Service) == 0 { + if c.Params.Service == "" { c.SetInvalidUrlParam("service") } @@ -532,7 +532,7 @@ func (c *Context) RequireEmojiName() *Context { validName := regexp.MustCompile(`^[a-zA-Z0-9\-\+_]+$`) - if len(c.Params.EmojiName) == 0 || len(c.Params.EmojiName) > model.EMOJI_NAME_MAX_LENGTH || !validName.MatchString(c.Params.EmojiName) { + if c.Params.EmojiName == "" || len(c.Params.EmojiName) > model.EMOJI_NAME_MAX_LENGTH || !validName.MatchString(c.Params.EmojiName) { c.SetInvalidUrlParam("emoji_name") } @@ -578,7 +578,7 @@ func (c *Context) RequireJobType() *Context { return c } - if len(c.Params.JobType) == 0 || len(c.Params.JobType) > 32 { + if c.Params.JobType == "" || len(c.Params.JobType) > 32 { c.SetInvalidUrlParam("job_type") } return c @@ -634,7 +634,7 @@ func (c *Context) RequireRemoteId() *Context { return c } - if len(c.Params.RemoteId) == 0 { + if c.Params.RemoteId == "" { c.SetInvalidUrlParam("remote_id") } return c diff --git a/web/handlers.go b/web/handlers.go index ba62aa2fa0..c2a718558c 100644 --- a/web/handlers.go +++ b/web/handlers.go @@ -284,7 +284,7 @@ func (h Handler) ServeHTTP(w http.ResponseWriter, r *http.Request) { c.Err.IsOAuth = false } - if IsApiCall(c.App, r) || IsWebhookCall(c.App, r) || IsOAuthApiCall(c.App, r) || len(r.Header.Get("X-Mobile-App")) > 0 { + if IsApiCall(c.App, r) || IsWebhookCall(c.App, r) || IsOAuthApiCall(c.App, r) || r.Header.Get("X-Mobile-App") != "" { w.WriteHeader(c.Err.StatusCode) w.Write([]byte(c.Err.ToJson())) } else { diff --git a/web/oauth.go b/web/oauth.go index bd4c2e8ad9..2772acfb91 100644 --- a/web/oauth.go +++ b/web/oauth.go @@ -133,7 +133,7 @@ func authorizeOAuthPage(c *Context, w http.ResponseWriter, r *http.Request) { } // here we should check if the user is logged in - if len(c.App.Session().UserId) == 0 { + if c.App.Session().UserId == "" { if loginHint == model.USER_AUTH_SERVICE_SAML { http.Redirect(w, r, c.GetSiteURLHeader()+"/login/sso/saml?redirect_to="+url.QueryEscape(r.RequestURI), http.StatusFound) } else { @@ -190,12 +190,12 @@ func getAccessToken(c *Context, w http.ResponseWriter, r *http.Request) { grantType := r.FormValue("grant_type") switch grantType { case model.ACCESS_TOKEN_GRANT_TYPE: - if len(code) == 0 { + if code == "" { c.Err = model.NewAppError("getAccessToken", "api.oauth.get_access_token.missing_code.app_error", nil, "", http.StatusBadRequest) return } case model.REFRESH_TOKEN_GRANT_TYPE: - if len(refreshToken) == 0 { + if refreshToken == "" { c.Err = model.NewAppError("getAccessToken", "api.oauth.get_access_token.missing_refresh_token.app_error", nil, "", http.StatusBadRequest) return } @@ -211,7 +211,7 @@ func getAccessToken(c *Context, w http.ResponseWriter, r *http.Request) { } secret := r.FormValue("client_secret") - if len(secret) == 0 { + if secret == "" { c.Err = model.NewAppError("getAccessToken", "api.oauth.get_access_token.bad_client_secret.app_error", nil, "", http.StatusBadRequest) return } @@ -258,7 +258,7 @@ func completeOAuth(c *Context, w http.ResponseWriter, r *http.Request) { } code := r.URL.Query().Get("code") - if len(code) == 0 { + if code == "" { utils.RenderWebError(c.App.Config(), w, r, http.StatusTemporaryRedirect, url.Values{ "type": []string{"oauth_missing_code"}, "service": []string{strings.Title(service)}, diff --git a/web/oauth_test.go b/web/oauth_test.go index 7503c107be..5fa542a0c7 100644 --- a/web/oauth_test.go +++ b/web/oauth_test.go @@ -91,13 +91,13 @@ func TestAuthorizeOAuthApp(t *testing.T) { authRequest.ResponseType = model.IMPLICIT_RESPONSE_TYPE ruri, resp = ApiClient.AuthorizeOAuthApp(authRequest) require.Nil(t, resp.Error) - require.False(t, len(ruri) == 0, "redirect url should be set") + require.False(t, ruri == "", "redirect url should be set") ru, _ = url.Parse(ruri) require.NotNil(t, ru, "redirect url unparseable") values, err := url.ParseQuery(ru.Fragment) require.Nil(t, err) - assert.False(t, len(values.Get("access_token")) == 0, "access_token not returned") + assert.False(t, values.Get("access_token") == "", "access_token not returned") assert.Equal(t, authRequest.State, values.Get("state"), "returned state doesn't match") oldToken := ApiClient.AuthToken @@ -526,7 +526,7 @@ func HttpGet(url string, httpClient *http.Client, authToken string, followRedire rq, _ := http.NewRequest("GET", url, nil) rq.Close = true - if len(authToken) > 0 { + if authToken != "" { rq.Header.Set(model.HEADER_AUTH, authToken) } diff --git a/web/saml.go b/web/saml.go index 5f80835715..343faa32aa 100644 --- a/web/saml.go +++ b/web/saml.go @@ -84,7 +84,7 @@ func completeSaml(c *Context, w http.ResponseWriter, r *http.Request) { relayState := r.FormValue("RelayState") relayProps := make(map[string]string) - if len(relayState) > 0 { + if relayState != "" { stateStr := "" b, err := b64.StdEncoding.DecodeString(relayState) if err != nil {