MM-52532: Fix golangci warnings (#23709)

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

- Replace golint with revive
- Add makezero linter
- Fix all the required linter failures

Some issues in enterprise and public modules
are yet to be fixed. We send this to expediate things.
Этот коммит содержится в:
Agniva De Sarker
2023-06-13 14:08:36 +05:30
коммит произвёл GitHub
родитель 62a3ee8adc
Коммит c249ba4a66
49 изменённых файлов: 145 добавлений и 140 удалений

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

@@ -1061,8 +1061,8 @@ func getGroups(c *Context, w http.ResponseWriter, r *http.Request) {
}
var (
groups = []*model.Group{}
canSee bool = true
groups = []*model.Group{}
canSee = true
)
if opts.FilterHasMember != "" {

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

@@ -811,10 +811,10 @@ func possibleAtMentions(message string) []string {
// is a special character for usernames (dot, dash or underscore). If not, it
// returns the same string.
func trimUsernameSpecialChar(word string) (string, bool) {
len := len(word)
l := len(word)
if len > 0 && strings.LastIndexAny(word, usernameSpecialChars) == (len-1) {
return word[:len-1], true
if l > 0 && strings.LastIndexAny(word, usernameSpecialChars) == (l-1) {
return word[:l-1], true
}
return word, false

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

@@ -894,7 +894,7 @@ func (es *Service) InvalidateVerifyEmailTokensForUser(userID string) *model.AppE
return model.NewAppError("InvalidateVerifyEmailTokensForUser", "api.user.invalidate_verify_email_tokens.error", nil, "", http.StatusInternalServerError).Wrap(err)
}
var appErr *model.AppError = nil
var appErr *model.AppError
for _, token := range tokens {
tokenExtra := struct {
UserId string

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

@@ -315,7 +315,7 @@ func (a *App) findTeamIdForFilename(post *model.Post, id, filename string) strin
}
var fileMigrationLock sync.Mutex
var oldFilenameMatchExp *regexp.Regexp = regexp.MustCompile(`^\/([a-z\d]{26})\/([a-z\d]{26})\/([a-z\d]{26})\/([^\/]+)$`)
var oldFilenameMatchExp = regexp.MustCompile(`^\/([a-z\d]{26})\/([a-z\d]{26})\/([a-z\d]{26})\/([^\/]+)$`)
// Parse the path from the Filename of the form /{channelID}/{userID}/{uid}/{nameWithExtension}
func parseOldFilenames(filenames []string, channelID, userID string) [][]string {

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

@@ -25,7 +25,7 @@ func (a *App) removeInaccessibleContentFromFilesSlice(files []*model.FileInfo) (
return 0, nil
}
var firstInaccessibleFileTime int64 = 0
var firstInaccessibleFileTime int64
for _, file := range files {
if createAt := file.CreateAt; createAt < lastAccessibleFileTime {
file.MakeContentInaccessible()
@@ -143,7 +143,7 @@ func (a *App) getFilteredAccessibleFiles(files []*model.FileInfo, options filter
return files, 0, nil
}
if bounds.noAccessible() {
var firstInaccessibleFileTime int64 = 0
var firstInaccessibleFileTime int64
if lenFiles > 0 {
firstFileCreatedAt := files[0].CreateAt
lastFileCreatedAt := files[len(files)-1].CreateAt
@@ -194,7 +194,7 @@ func linearFilterFileList(fileList *model.FileInfoList, earliestAccessibleTime i
// this is the slower fallback that is still safe
// if we can not assume files are ordered by CreatedAt
func linearFilterFilesSlice(files []*model.FileInfo, earliestAccessibleTime int64) ([]*model.FileInfo, int64) {
var firstInaccessibleFileTime int64 = 0
var firstInaccessibleFileTime int64
n := 0
for i := range files {
if createAt := files[i].CreateAt; createAt >= earliestAccessibleTime {

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

@@ -282,7 +282,7 @@ func updateRole(a *App, sc *model.SchemeConveyor, roleCreatedName, defaultRoleNa
_, err = a.UpdateRole(roleCreated)
if err != nil {
return errors.New(fmt.Sprintf("%v: %v\n", err.Message, err.DetailedError))
return fmt.Errorf("failed to update role: %w", err)
}
return nil

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

@@ -141,7 +141,7 @@ func (ps *PlatformService) GetLogsSkipSend(page, perPage int, logFilter *model.L
var lineCount int
const searchPos = -1
b := make([]byte, 1)
var endOffset int64 = 0
var endOffset int64
// if the file exists and it's last byte is '\n' - skip it
var stat os.FileInfo

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

@@ -442,7 +442,7 @@ func (h *Hub) Start() {
})
continue
}
var latestActivity int64 = 0
var latestActivity int64
for _, conn := range conns {
if !conn.active {
continue

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

@@ -3,7 +3,7 @@
package app
var mattermostPluginPublicKey []byte = []byte(`-----BEGIN PGP PUBLIC KEY BLOCK-----
var mattermostPluginPublicKey = []byte(`-----BEGIN PGP PUBLIC KEY BLOCK-----
mQINBF3YTiEBEACgkhnZ5+xylKZhLVj193b6d/rSQuCU/zwWeZJnqyR8wRsPotXO
CMXOUM9bTTaGfItCP9KlPPcyrshNEIgqcqhB6TSKkWSyrV5XS95Opd9Esbjw1VZq

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

@@ -124,7 +124,7 @@ func linearFilterPostList(postList *model.PostList, earliestAccessibleTime int64
// this is the slower fallback that is still safe if we can not
// assume posts are ordered by CreatedAt
func linearFilterPostsSlice(posts []*model.Post, earliestAccessibleTime int64) ([]*model.Post, int64) {
var firstInaccessiblePostTime int64 = 0
var firstInaccessiblePostTime int64
n := 0
for i := range posts {
if createAt := posts[i].CreateAt; createAt >= earliestAccessibleTime {
@@ -243,7 +243,7 @@ func (a *App) getFilteredAccessiblePosts(posts []*model.Post, options filterPost
return posts, 0, nil
}
if bounds.noAccessible() {
var firstInaccessiblePostTime int64 = 0
var firstInaccessiblePostTime int64
if lenPosts > 0 {
firstPostCreatedAt := posts[0].CreateAt
lastPostCreatedAt := posts[len(posts)-1].CreateAt

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

@@ -234,7 +234,7 @@ func (a *App) createOnboardingLinkedBoard(c request.CTX, teamId string) (*fb_mod
return nil, appErr
}
var template *fb_model.Board = nil
var template *fb_model.Board
for _, t := range templates {
v := t.Properties["trackingTemplateId"]
if v == welcomeToBoardsTemplateId {

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

@@ -727,7 +727,7 @@ func TestSanitizeTeam(t *testing.T) {
}
copyTeam := func() *model.Team {
copy := &model.Team{}
copy := &model.Team{} //nolint:revive
*copy = *team
return copy
}

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

@@ -1513,7 +1513,7 @@ func (a *App) InvalidatePasswordRecoveryTokensForUser(userID string) *model.AppE
return model.NewAppError("InvalidatePasswordRecoveryTokensForUser", "api.user.invalidate_password_recovery_tokens.error", nil, "", http.StatusInternalServerError).Wrap(err)
}
var appErr *model.AppError = nil
var appErr *model.AppError
for _, token := range tokens {
tokenExtra := struct {
UserId string

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

@@ -111,24 +111,24 @@ func TestAdjustProfileImage(t *testing.T) {
th := Setup(t).InitBasic()
defer th.TearDown()
_, err := th.App.AdjustImage(bytes.NewReader([]byte{}))
require.NotNil(t, err)
_, appErr := th.App.AdjustImage(bytes.NewReader([]byte{}))
require.NotNil(t, appErr)
// test image isn't the correct dimensions
// it should be adjusted
testjpg, error := testutils.ReadTestFile("testjpg.jpg")
require.NoError(t, error)
adjusted, err := th.App.AdjustImage(bytes.NewReader(testjpg))
require.Nil(t, err)
testjpg, err := testutils.ReadTestFile("testjpg.jpg")
require.NoError(t, err)
adjusted, appErr := th.App.AdjustImage(bytes.NewReader(testjpg))
require.Nil(t, appErr)
assert.True(t, adjusted.Len() > 0)
assert.NotEqual(t, testjpg, adjusted)
// default image should not require adjustment
user := th.BasicUser
image, err := th.App.GetDefaultProfileImage(user)
require.Nil(t, err)
image2, err := th.App.AdjustImage(bytes.NewReader(image))
require.Nil(t, err)
image, appErr := th.App.GetDefaultProfileImage(user)
require.Nil(t, appErr)
image2, appErr := th.App.AdjustImage(bytes.NewReader(image))
require.Nil(t, appErr)
assert.Equal(t, image, image2.Bytes())
}

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

@@ -33,7 +33,7 @@ func MakeWorker(jobServer *jobs.JobServer, app AppIface, store store.Store) mode
jobServer.HandleJobPanic(job)
var err error
var fromTS int64 = 0
var fromTS int64
var toTS int64 = model.GetMillis()
if fromStr, ok := job.Data["from"]; ok {
if fromTS, err = strconv.ParseInt(fromStr, 10, 64); err != nil {

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

@@ -14,7 +14,7 @@ type Scheduler struct {
*jobs.PeriodicScheduler
}
func (scheduler *Scheduler) NextScheduleTime(cfg *model.Config, now time.Time, pendingJobs bool, lastSuccessfulJob *model.Job) *time.Time {
func (scheduler *Scheduler) NextScheduleTime(cfg *model.Config, _ time.Time, pendingJobs bool, lastSuccessfulJob *model.Job) *time.Time {
nextTime := time.Now().Add(time.Duration(*cfg.AnnouncementSettings.NoticesFetchFrequency) * time.Second)
return &nextTime
}

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

@@ -47,7 +47,7 @@ func (s LocalCacheTermsOfServiceStore) Save(termsOfService *model.TermsOfService
func (s LocalCacheTermsOfServiceStore) GetLatest(allowFromCache bool) (*model.TermsOfService, error) {
if allowFromCache {
if len, err := s.rootStore.termsOfServiceCache.Len(); err == nil && len != 0 {
if l, err := s.rootStore.termsOfServiceCache.Len(); err == nil && l != 0 {
var cacheItem *model.TermsOfService
if err := s.rootStore.doStandardReadCache(s.rootStore.termsOfServiceCache, LatestKey, &cacheItem); err == nil {
return cacheItem, nil

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

@@ -301,7 +301,7 @@ func (th *SearchTestHelper) createDirectChannel(teamID, name, displayName string
}
func (th *SearchTestHelper) createGroupChannel(teamID, displayName string, users []*model.User) (*model.Channel, error) {
userIDS := make([]string, len(users))
userIDS := make([]string, 0, len(users))
for _, user := range users {
userIDS = append(userIDS, user.Id)
}
@@ -464,7 +464,7 @@ func (th *SearchTestHelper) assertUsersMatchInAnyOrder(t *testing.T, expected, a
func (th *SearchTestHelper) checkPostInSearchResults(t *testing.T, postID string, searchResults map[string]*model.Post) {
t.Helper()
postIDS := make([]string, len(searchResults))
postIDS := make([]string, 0, len(searchResults))
for ID := range searchResults {
postIDS = append(postIDS, ID)
}
@@ -473,7 +473,7 @@ func (th *SearchTestHelper) checkPostInSearchResults(t *testing.T, postID string
func (th *SearchTestHelper) checkFileInfoInSearchResults(t *testing.T, fileID string, searchResults map[string]*model.FileInfo) {
t.Helper()
fileIDS := make([]string, len(searchResults))
fileIDS := make([]string, 0, len(searchResults))
for ID := range searchResults {
fileIDS = append(fileIDS, ID)
}

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

@@ -355,13 +355,13 @@ func testReactionGetForPostSince(t *testing.T, ss store.Store, s SqlStore) {
}
for _, reaction := range reactions {
delete := reaction.DeleteAt
del := reaction.DeleteAt
update := reaction.UpdateAt
_, err := ss.Reaction().Save(reaction)
require.NoError(t, err)
if delete > 0 {
if del > 0 {
_, err = ss.Reaction().Delete(reaction)
require.NoError(t, err)
}

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

@@ -458,7 +458,7 @@ func testRetentionPolicyStoreAddChannels(t *testing.T, ss store.Store, s SqlStor
err := ss.RetentionPolicy().AddChannels(policy.ID, channelIDs)
require.NoError(t, err)
// verify that the channels were actually added
copy := copyRetentionPolicyWithTeamAndChannelIds(policy)
copy := copyRetentionPolicyWithTeamAndChannelIds(policy) //nolint:revive
copy.ChannelIDs = append(copy.ChannelIDs, channelIDs...)
checkRetentionPolicyLikeThisExists(t, ss, copy)
restoreRetentionPolicy(t, ss, policy)
@@ -492,7 +492,7 @@ func testRetentionPolicyStoreRemoveChannels(t *testing.T, ss store.Store, s SqlS
err := ss.RetentionPolicy().RemoveChannels(policy.ID, []string{channelID})
require.NoError(t, err)
// verify that the channel was actually removed
copy := copyRetentionPolicyWithTeamAndChannelIds(policy)
copy := copyRetentionPolicyWithTeamAndChannelIds(policy) //nolint:revive
copy.ChannelIDs = make([]string, 0)
for _, oldChannelID := range policy.ChannelIDs {
if oldChannelID != channelID {
@@ -554,7 +554,7 @@ func testRetentionPolicyStoreAddTeams(t *testing.T, ss store.Store, s SqlStore)
err := ss.RetentionPolicy().AddTeams(policy.ID, teamIDs)
require.NoError(t, err)
// verify that the teams were actually added
copy := copyRetentionPolicyWithTeamAndChannelIds(policy)
copy := copyRetentionPolicyWithTeamAndChannelIds(policy) //nolint:revive
copy.TeamIDs = append(copy.TeamIDs, teamIDs...)
checkRetentionPolicyLikeThisExists(t, ss, copy)
restoreRetentionPolicy(t, ss, policy)
@@ -588,7 +588,7 @@ func testRetentionPolicyStoreRemoveTeams(t *testing.T, ss store.Store, s SqlStor
err := ss.RetentionPolicy().RemoveTeams(policy.ID, []string{teamID})
require.NoError(t, err)
// verify that the team was actually removed
copy := copyRetentionPolicyWithTeamAndChannelIds(policy)
copy := copyRetentionPolicyWithTeamAndChannelIds(policy) //nolint:revive
copy.TeamIDs = make([]string, 0)
for _, oldTeamID := range policy.TeamIDs {
if oldTeamID != teamID {

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

@@ -123,8 +123,8 @@ func UpdateAssetsSubpathInDir(subpath, directory string) error {
if err != nil {
return errors.Wrapf(err, "failed to open %s", walkPath)
}
new := strings.Replace(string(old), pathToReplace, newPath, -1)
if err = os.WriteFile(walkPath, []byte(new), 0); err != nil {
n := strings.Replace(string(old), pathToReplace, newPath, -1)
if err = os.WriteFile(walkPath, []byte(n), 0); err != nil {
return errors.Wrapf(err, "failed to update %s with subpath %s", walkPath, subpath)
}
}