MM-31062: Rewrite empty string checks to be more idiomatic (#16587)

https://mattermost.atlassian.net/browse/MM-31062

```release-note
NONE
```
Этот коммит содержится в:
Agniva De Sarker
2020-12-22 19:20:59 +05:30
коммит произвёл GitHub
родитель 1a131b54af
Коммит 6487d0ca91
25 изменённых файлов: 54 добавлений и 54 удалений

Просмотреть файл

@@ -1447,7 +1447,7 @@ func addChannelMember(c *Context, w http.ResponseWriter, r *http.Request) {
}
postRootId, ok := props["post_root_id"].(string)
if ok && len(postRootId) != 0 && !model.IsValidId(postRootId) {
if ok && postRootId != "" && !model.IsValidId(postRootId) {
c.SetInvalidParam("post_root_id")
return
}

Просмотреть файл

@@ -29,18 +29,18 @@ func TestGetConfig(t *testing.T) {
require.NotEqual(t, "", cfg.TeamSettings.SiteName)
if *cfg.LdapSettings.BindPassword != model.FAKE_SETTING && len(*cfg.LdapSettings.BindPassword) != 0 {
if *cfg.LdapSettings.BindPassword != model.FAKE_SETTING && *cfg.LdapSettings.BindPassword != "" {
require.FailNow(t, "did not sanitize properly")
}
require.Equal(t, model.FAKE_SETTING, *cfg.FileSettings.PublicLinkSalt, "did not sanitize properly")
if *cfg.FileSettings.AmazonS3SecretAccessKey != model.FAKE_SETTING && len(*cfg.FileSettings.AmazonS3SecretAccessKey) != 0 {
if *cfg.FileSettings.AmazonS3SecretAccessKey != model.FAKE_SETTING && *cfg.FileSettings.AmazonS3SecretAccessKey != "" {
require.FailNow(t, "did not sanitize properly")
}
if *cfg.EmailSettings.SMTPPassword != model.FAKE_SETTING && len(*cfg.EmailSettings.SMTPPassword) != 0 {
if *cfg.EmailSettings.SMTPPassword != model.FAKE_SETTING && *cfg.EmailSettings.SMTPPassword != "" {
require.FailNow(t, "did not sanitize properly")
}
if *cfg.GitLabSettings.Secret != model.FAKE_SETTING && len(*cfg.GitLabSettings.Secret) != 0 {
if *cfg.GitLabSettings.Secret != model.FAKE_SETTING && *cfg.GitLabSettings.Secret != "" {
require.FailNow(t, "did not sanitize properly")
}
require.Equal(t, model.FAKE_SETTING, *cfg.SqlSettings.DataSource, "did not sanitize properly")

Просмотреть файл

@@ -559,7 +559,7 @@ func getFilteredUsersStats(c *Context, w http.ResponseWriter, r *http.Request) {
}
}
channelRoles := []string{}
if channelRolesString != "" && len(channelID) != 0 {
if channelRolesString != "" && channelID != "" {
channelRoles, rolesValid = model.CleanRoleNames(strings.Split(channelRolesString, ","))
if !rolesValid {
c.SetInvalidParam("channelRoles")
@@ -567,7 +567,7 @@ func getFilteredUsersStats(c *Context, w http.ResponseWriter, r *http.Request) {
}
}
teamRoles := []string{}
if teamRolesString != "" && len(teamID) != 0 {
if teamRolesString != "" && teamID != "" {
teamRoles, rolesValid = model.CleanRoleNames(strings.Split(teamRolesString, ","))
if !rolesValid {
c.SetInvalidParam("teamRoles")
@@ -673,7 +673,7 @@ func getUsers(c *Context, w http.ResponseWriter, r *http.Request) {
}
}
channelRoles := []string{}
if channelRolesString != "" && len(inChannelId) != 0 {
if channelRolesString != "" && inChannelId != "" {
channelRoles, rolesValid = model.CleanRoleNames(strings.Split(channelRolesString, ","))
if !rolesValid {
c.SetInvalidParam("channelRoles")
@@ -681,7 +681,7 @@ func getUsers(c *Context, w http.ResponseWriter, r *http.Request) {
}
}
teamRoles := []string{}
if teamRolesString != "" && len(inTeamId) != 0 {
if teamRolesString != "" && inTeamId != "" {
teamRoles, rolesValid = model.CleanRoleNames(strings.Split(teamRolesString, ","))
if !rolesValid {
c.SetInvalidParam("teamRoles")

Просмотреть файл

@@ -629,7 +629,7 @@ func (a *App) CreateChannelScheme(channel *model.Channel) (*model.Scheme, *model
// DeleteChannelScheme deletes a channels scheme and sets its SchemeId to nil.
func (a *App) DeleteChannelScheme(channel *model.Channel) (*model.Channel, *model.AppError) {
if channel.SchemeId != nil && len(*channel.SchemeId) != 0 {
if channel.SchemeId != nil && *channel.SchemeId != "" {
if _, err := a.DeleteScheme(*channel.SchemeId); err != nil {
return nil, err
}
@@ -784,7 +784,7 @@ func (a *App) GetSchemeRolesForChannel(channelId string) (guestRoleName, userRol
return
}
if channel.SchemeId != nil && len(*channel.SchemeId) != 0 {
if channel.SchemeId != nil && *channel.SchemeId != "" {
var scheme *model.Scheme
scheme, err = a.GetScheme(*channel.SchemeId)
if err != nil {
@@ -808,7 +808,7 @@ func (a *App) GetTeamSchemeChannelRoles(teamId string) (guestRoleName, userRoleN
return
}
if team.SchemeId != nil && len(*team.SchemeId) != 0 {
if team.SchemeId != nil && *team.SchemeId != "" {
var scheme *model.Scheme
scheme, err = a.GetScheme(*team.SchemeId)
if err != nil {

Просмотреть файл

@@ -520,7 +520,7 @@ func (a *App) DoCommandRequest(cmd *model.Command, p url.Values) (*model.Command
func (a *App) HandleCommandResponse(command *model.Command, args *model.CommandArgs, response *model.CommandResponse, builtIn bool) (*model.CommandResponse, *model.AppError) {
trigger := ""
if len(args.Command) != 0 {
if args.Command != "" {
parts := strings.Split(args.Command, " ")
trigger = parts[0][1:]
trigger = strings.ToLower(trigger)
@@ -561,7 +561,7 @@ func (a *App) HandleCommandResponsePost(command *model.Command, args *model.Comm
post.Type = response.Type
post.SetProps(response.Props)
if len(response.ChannelId) != 0 {
if response.ChannelId != "" {
_, err := a.GetChannelMember(response.ChannelId, args.UserId)
if err != nil {
err = model.NewAppError("HandleCommandResponsePost", "api.command.command_post.forbidden.app_error", nil, err.Error(), http.StatusForbidden)
@@ -573,20 +573,20 @@ func (a *App) HandleCommandResponsePost(command *model.Command, args *model.Comm
isBotPost := !builtIn
if *a.Config().ServiceSettings.EnablePostUsernameOverride {
if len(command.Username) != 0 {
if command.Username != "" {
post.AddProp("override_username", command.Username)
isBotPost = true
} else if len(response.Username) != 0 {
} else if response.Username != "" {
post.AddProp("override_username", response.Username)
isBotPost = true
}
}
if *a.Config().ServiceSettings.EnablePostIconOverride {
if len(command.IconURL) != 0 {
if command.IconURL != "" {
post.AddProp("override_icon_url", command.IconURL)
isBotPost = true
} else if len(response.IconURL) != 0 {
} else if response.IconURL != "" {
post.AddProp("override_icon_url", response.IconURL)
isBotPost = true
} else {

Просмотреть файл

@@ -122,7 +122,7 @@ func (a *App) GetUserForLogin(id, loginId string) (*model.User, *model.AppError)
enableEmail := *a.Config().EmailSettings.EnableSignInWithEmail
// If we are given a userID then fail if we can't find a user with that ID
if len(id) != 0 {
if id != "" {
user, err := a.GetUser(id)
if err != nil {
if err.Id != MISSING_ACCOUNT_ERROR {

Просмотреть файл

@@ -780,10 +780,10 @@ func getMentionsEnabledFields(post *model.Post) model.StringArray {
ret = append(ret, post.Message)
for _, attachment := range post.Attachments() {
if len(attachment.Pretext) != 0 {
if attachment.Pretext != "" {
ret = append(ret, attachment.Pretext)
}
if len(attachment.Text) != 0 {
if attachment.Text != "" {
ret = append(ret, attachment.Text)
}
}

Просмотреть файл

@@ -314,7 +314,7 @@ func (a *App) generateHyperlinkForChannels(postMessage, teamName, teamURL string
}
func (s *Server) GetMessageForNotification(post *model.Post, translateFunc i18n.TranslateFunc) string {
if len(strings.TrimSpace(post.Message)) != 0 || len(post.FileIds) == 0 {
if strings.TrimSpace(post.Message) != "" || len(post.FileIds) == 0 {
return post.Message
}

Просмотреть файл

@@ -415,11 +415,11 @@ func (a *App) newSessionUpdateToken(appName string, accessData *model.AccessData
func (a *App) GetOAuthLoginEndpoint(w http.ResponseWriter, r *http.Request, service, teamId, action, redirectTo, loginHint string, isMobile bool) (string, *model.AppError) {
stateProps := map[string]string{}
stateProps["action"] = action
if len(teamId) != 0 {
if teamId != "" {
stateProps["team_id"] = teamId
}
if len(redirectTo) != 0 {
if redirectTo != "" {
stateProps["redirect_to"] = redirectTo
}
@@ -436,7 +436,7 @@ func (a *App) GetOAuthLoginEndpoint(w http.ResponseWriter, r *http.Request, serv
func (a *App) GetOAuthSignupEndpoint(w http.ResponseWriter, r *http.Request, service, teamId string) (string, *model.AppError) {
stateProps := map[string]string{}
stateProps["action"] = model.OAUTH_ACTION_SIGNUP
if len(teamId) != 0 {
if teamId != "" {
stateProps["team_id"] = teamId
}

Просмотреть файл

@@ -342,7 +342,7 @@ func (a *App) GetSchemeRolesForTeam(teamId string) (string, string, string, *mod
return "", "", "", err
}
if team.SchemeId != nil && len(*team.SchemeId) != 0 {
if team.SchemeId != nil && *team.SchemeId != "" {
scheme, err := a.GetScheme(*team.SchemeId)
if err != nil {
return "", "", "", err

Просмотреть файл

@@ -1497,7 +1497,7 @@ func (a *App) SendPasswordReset(email string, siteURL string) (bool, *model.AppE
return false, nil
}
if user.AuthData != nil && len(*user.AuthData) != 0 {
if user.AuthData != nil && *user.AuthData != "" {
return false, model.NewAppError("SendPasswordReset", "api.user.send_password_reset.sso.app_error", nil, "userId="+user.Id, http.StatusBadRequest)
}

Просмотреть файл

@@ -264,7 +264,7 @@ func (a *App) CreateWebhookPost(userId string, channel *model.Channel, text, ove
}
if *a.Config().ServiceSettings.EnablePostUsernameOverride {
if len(overrideUsername) != 0 {
if overrideUsername != "" {
post.AddProp("override_username", overrideUsername)
} else {
post.AddProp("override_username", model.DEFAULT_WEBHOOK_USERNAME)
@@ -272,10 +272,10 @@ func (a *App) CreateWebhookPost(userId string, channel *model.Channel, text, ove
}
if *a.Config().ServiceSettings.EnablePostIconOverride {
if len(overrideIconUrl) != 0 {
if overrideIconUrl != "" {
post.AddProp("override_icon_url", overrideIconUrl)
}
if len(overrideIconEmoji) != 0 {
if overrideIconEmoji != "" {
post.AddProp("override_icon_emoji", overrideIconEmoji)
}
}
@@ -445,7 +445,7 @@ func (a *App) CreateOutgoingWebhook(hook *model.OutgoingWebhook) (*model.Outgoin
return nil, model.NewAppError("CreateOutgoingWebhook", "api.outgoing_webhook.disabled.app_error", nil, "", http.StatusNotImplemented)
}
if len(hook.ChannelId) != 0 {
if hook.ChannelId != "" {
channel, errCh := a.Srv().Store.Channel().Get(hook.ChannelId, true)
if errCh != nil {
var nfErr *store.ErrNotFound
@@ -696,7 +696,7 @@ func (a *App) HandleIncomingWebhook(hookId string, req *model.IncomingWebhookReq
var channel *model.Channel
var cchan chan store.StoreResult
if len(channelName) != 0 {
if channelName != "" {
if channelName[0] == '@' {
result, nErr := a.Srv().Store.User().GetByUsername(channelName[1:])
if nErr != nil {

Просмотреть файл

@@ -53,11 +53,11 @@ func (o *CommandWebhook) IsValid() *AppError {
return NewAppError("CommandWebhook.IsValid", "model.command_hook.channel_id.app_error", nil, "", http.StatusBadRequest)
}
if len(o.RootId) != 0 && !IsValidId(o.RootId) {
if o.RootId != "" && !IsValidId(o.RootId) {
return NewAppError("CommandWebhook.IsValid", "model.command_hook.root_id.app_error", nil, "", http.StatusBadRequest)
}
if len(o.ParentId) != 0 && !IsValidId(o.ParentId) {
if o.ParentId != "" && !IsValidId(o.ParentId) {
return NewAppError("CommandWebhook.IsValid", "model.command_hook.parent_id.app_error", nil, "", http.StatusBadRequest)
}

Просмотреть файл

@@ -3484,13 +3484,13 @@ func (s *ServiceSettings) isValid() *AppError {
return NewAppError("Config.IsValid", "model.config.is_valid.login_attempts.app_error", nil, "", http.StatusBadRequest)
}
if len(*s.SiteURL) != 0 {
if *s.SiteURL != "" {
if _, err := url.ParseRequestURI(*s.SiteURL); err != nil {
return NewAppError("Config.IsValid", "model.config.is_valid.site_url.app_error", nil, "", http.StatusBadRequest)
}
}
if len(*s.WebsocketURL) != 0 {
if *s.WebsocketURL != "" {
if _, err := url.ParseRequestURI(*s.WebsocketURL); err != nil {
return NewAppError("Config.IsValid", "model.config.is_valid.websocket_url.app_error", nil, "", http.StatusBadRequest)
}

Просмотреть файл

@@ -114,7 +114,7 @@ func (fi *FileInfo) IsValid() *AppError {
return NewAppError("FileInfo.IsValid", "model.file_info.is_valid.user_id.app_error", nil, "id="+fi.Id, http.StatusBadRequest)
}
if len(fi.PostId) != 0 && !IsValidId(fi.PostId) {
if fi.PostId != "" && !IsValidId(fi.PostId) {
return NewAppError("FileInfo.IsValid", "model.file_info.is_valid.post_id.app_error", nil, "id="+fi.Id, http.StatusBadRequest)
}

Просмотреть файл

@@ -140,7 +140,7 @@ func (o *OutgoingWebhook) IsValid() *AppError {
return NewAppError("OutgoingWebhook.IsValid", "model.outgoing_hook.is_valid.user_id.app_error", nil, "", http.StatusBadRequest)
}
if len(o.ChannelId) != 0 && !IsValidId(o.ChannelId) {
if o.ChannelId != "" && !IsValidId(o.ChannelId) {
return NewAppError("OutgoingWebhook.IsValid", "model.outgoing_hook.is_valid.channel_id.app_error", nil, "", http.StatusBadRequest)
}

Просмотреть файл

@@ -159,15 +159,15 @@ func (scheme *Scheme) IsValidForCreate() bool {
}
if scheme.Scope == SCHEME_SCOPE_CHANNEL {
if len(scheme.DefaultTeamAdminRole) != 0 {
if scheme.DefaultTeamAdminRole != "" {
return false
}
if len(scheme.DefaultTeamUserRole) != 0 {
if scheme.DefaultTeamUserRole != "" {
return false
}
if len(scheme.DefaultTeamGuestRole) != 0 {
if scheme.DefaultTeamGuestRole != "" {
return false
}
}

Просмотреть файл

@@ -214,7 +214,7 @@ func parseSearchFlags(input []string) ([]searchWord, []flag) {
// and remove extra pound #s
word = hashtagStart.ReplaceAllString(word, "#")
if len(word) != 0 {
if word != "" {
words = append(words, searchWord{
word,
exclude,
@@ -345,9 +345,9 @@ func ParseSearchParams(text string, timeZoneOffset int) []*SearchParams {
len(excludedPlainTerms) == 0 && len(excludedHashtagTerms) == 0 &&
(len(inChannels) != 0 || len(fromUsers) != 0 ||
len(excludedChannels) != 0 || len(excludedUsers) != 0 ||
len(afterDate) != 0 || len(excludedAfterDate) != 0 ||
len(beforeDate) != 0 || len(excludedBeforeDate) != 0 ||
len(onDate) != 0 || len(excludedDate) != 0) {
afterDate != "" || excludedAfterDate != "" ||
beforeDate != "" || excludedBeforeDate != "" ||
onDate != "" || excludedDate != "") {
paramsList = append(paramsList, &SearchParams{
Terms: "",
ExcludedTerms: "",

Просмотреть файл

@@ -33,7 +33,7 @@ func (s *LocalCacheRoleStore) handleClusterInvalidateRolePermissions(msg *model.
}
func (s LocalCacheRoleStore) Save(role *model.Role) (*model.Role, error) {
if len(role.Name) != 0 {
if role.Name != "" {
defer s.rootStore.doInvalidateCacheCluster(s.rootStore.roleCache, role.Name)
defer s.rootStore.doClearCacheCluster(s.rootStore.rolePermissionsCache)
}

Просмотреть файл

@@ -22,7 +22,7 @@ func (s *LocalCacheSchemeStore) handleClusterInvalidateScheme(msg *model.Cluster
}
func (s LocalCacheSchemeStore) Save(scheme *model.Scheme) (*model.Scheme, error) {
if len(scheme.Id) != 0 {
if scheme.Id != "" {
defer s.rootStore.doInvalidateCacheCluster(s.rootStore.schemeCache, scheme.Id)
}
return s.SchemeStore.Save(scheme)

Просмотреть файл

@@ -57,7 +57,7 @@ func (s SqlAuditStore) Get(userId string, offset int, limit int) (model.Audits,
Limit(uint64(limit)).
Offset(uint64(offset))
if len(userId) != 0 {
if userId != "" {
query = query.Where(sq.Eq{"UserId": userId})
}

Просмотреть файл

@@ -91,7 +91,7 @@ func (s *SqlGroupStore) createIndexesIfNotExists() {
}
func (s *SqlGroupStore) Create(group *model.Group) (*model.Group, error) {
if len(group.Id) != 0 {
if group.Id != "" {
return nil, store.NewErrInvalidInput("Group", "id", group.Id)
}

Просмотреть файл

@@ -286,7 +286,7 @@ func (us SqlUserStore) UpdateAuthData(userId string, service string, authData *s
AuthService = :AuthService,
AuthData = :AuthData`
if len(email) != 0 {
if email != "" {
query += ", Email = lower(:Email)"
}

Просмотреть файл

@@ -188,7 +188,7 @@ func (h Handler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
token, tokenLocation := app.ParseAuthTokenFromRequest(r)
if len(token) != 0 && tokenLocation != app.TokenLocationCloudHeader {
if token != "" && tokenLocation != app.TokenLocationCloudHeader {
session, err := c.App.GetSession(token)
if err != nil {
c.Log.Info("Invalid session", mlog.Err(err))
@@ -210,7 +210,7 @@ func (h Handler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
}
h.checkCSRFToken(c, r, token, tokenLocation, session)
} else if len(token) != 0 && c.App.Srv().License() != nil && *c.App.Srv().License().Features.Cloud && tokenLocation == app.TokenLocationCloudHeader {
} else if token != "" && c.App.Srv().License() != nil && *c.App.Srv().License().Features.Cloud && tokenLocation == app.TokenLocationCloudHeader {
// Check to see if this provided token matches our CWS Token
session, err := c.App.GetCloudSession(token)
if err != nil {

Просмотреть файл

@@ -38,7 +38,7 @@ func loginWithSaml(c *Context, w http.ResponseWriter, r *http.Request) {
relayProps := map[string]string{}
relayState := ""
if len(action) != 0 {
if action != "" {
relayProps["team_id"] = teamId
relayProps["action"] = action
if action == model.OAUTH_ACTION_EMAIL_TO_SSO {
@@ -46,7 +46,7 @@ func loginWithSaml(c *Context, w http.ResponseWriter, r *http.Request) {
}
}
if len(redirectTo) != 0 {
if redirectTo != "" {
relayProps["redirect_to"] = redirectTo
}