Skip to content

Commit 477a1cc

Browse files
authored
Improve utils of slices (#22379)
- Move the file `compare.go` and `slice.go` to `slice.go`. - Fix `ExistsInSlice`, it's buggy - It uses `sort.Search`, so it assumes that the input slice is sorted. - It passes `func(i int) bool { return slice[i] == target })` to `sort.Search`, that's incorrect, check the doc of `sort.Search`. - Conbine `IsInt64InSlice(int64, []int64)` and `ExistsInSlice(string, []string)` to `SliceContains[T]([]T, T)`. - Conbine `IsSliceInt64Eq([]int64, []int64)` and `IsEqualSlice([]string, []string)` to `SliceSortedEqual[T]([]T, T)`. - Add `SliceEqual[T]([]T, T)` as a distinction from `SliceSortedEqual[T]([]T, T)`. - Redesign `RemoveIDFromList([]int64, int64) ([]int64, bool)` to `SliceRemoveAll[T]([]T, T) []T`. - Add `SliceContainsFunc[T]([]T, func(T) bool)` and `SliceRemoveAllFunc[T]([]T, func(T) bool)` for general use. - Add comments to explain why not `golang.org/x/exp/slices`. - Add unit tests.
1 parent dc5f2cf commit 477a1cc

File tree

22 files changed

+228
-182
lines changed

22 files changed

+228
-182
lines changed

cmd/admin.go

+1-1
Original file line numberDiff line numberDiff line change
@@ -950,7 +950,7 @@ func parseSMTPConfig(c *cli.Context, conf *smtp.Source) error {
950950
if c.IsSet("auth-type") {
951951
conf.Auth = c.String("auth-type")
952952
validAuthTypes := []string{"PLAIN", "LOGIN", "CRAM-MD5"}
953-
if !contains(validAuthTypes, strings.ToUpper(c.String("auth-type"))) {
953+
if !util.SliceContainsString(validAuthTypes, strings.ToUpper(c.String("auth-type"))) {
954954
return errors.New("Auth must be one of PLAIN/LOGIN/CRAM-MD5")
955955
}
956956
conf.Auth = c.String("auth-type")

cmd/dump.go

+1-10
Original file line numberDiff line numberDiff line change
@@ -409,15 +409,6 @@ func runDump(ctx *cli.Context) error {
409409
return nil
410410
}
411411

412-
func contains(slice []string, s string) bool {
413-
for _, v := range slice {
414-
if v == s {
415-
return true
416-
}
417-
}
418-
return false
419-
}
420-
421412
// addRecursiveExclude zips absPath to specified insidePath inside writer excluding excludeAbsPath
422413
func addRecursiveExclude(w archiver.Writer, insidePath, absPath string, excludeAbsPath []string, verbose bool) error {
423414
absPath, err := filepath.Abs(absPath)
@@ -438,7 +429,7 @@ func addRecursiveExclude(w archiver.Writer, insidePath, absPath string, excludeA
438429
currentAbsPath := path.Join(absPath, file.Name())
439430
currentInsidePath := path.Join(insidePath, file.Name())
440431
if file.IsDir() {
441-
if !contains(excludeAbsPath, currentAbsPath) {
432+
if !util.SliceContainsString(excludeAbsPath, currentAbsPath) {
442433
if err := addFile(w, currentInsidePath, currentAbsPath, false); err != nil {
443434
return err
444435
}

models/asymkey/ssh_key.go

+4-4
Original file line numberDiff line numberDiff line change
@@ -409,14 +409,14 @@ func SynchronizePublicKeys(usr *user_model.User, s *auth.Source, sshPublicKeys [
409409
sshKeySplit := strings.Split(v, " ")
410410
if len(sshKeySplit) > 1 {
411411
key := strings.Join(sshKeySplit[:2], " ")
412-
if !util.ExistsInSlice(key, providedKeys) {
412+
if !util.SliceContainsString(providedKeys, key) {
413413
providedKeys = append(providedKeys, key)
414414
}
415415
}
416416
}
417417

418418
// Check if Public Key sync is needed
419-
if util.IsEqualSlice(giteaKeys, providedKeys) {
419+
if util.SliceSortedEqual(giteaKeys, providedKeys) {
420420
log.Trace("synchronizePublicKeys[%s]: Public Keys are already in sync for %s (Source:%v/DB:%v)", s.Name, usr.Name, len(providedKeys), len(giteaKeys))
421421
return false
422422
}
@@ -425,7 +425,7 @@ func SynchronizePublicKeys(usr *user_model.User, s *auth.Source, sshPublicKeys [
425425
// Add new Public SSH Keys that doesn't already exist in DB
426426
var newKeys []string
427427
for _, key := range providedKeys {
428-
if !util.ExistsInSlice(key, giteaKeys) {
428+
if !util.SliceContainsString(giteaKeys, key) {
429429
newKeys = append(newKeys, key)
430430
}
431431
}
@@ -436,7 +436,7 @@ func SynchronizePublicKeys(usr *user_model.User, s *auth.Source, sshPublicKeys [
436436
// Mark keys from DB that no longer exist in the source for deletion
437437
var giteaKeysToDelete []string
438438
for _, giteaKey := range giteaKeys {
439-
if !util.ExistsInSlice(giteaKey, providedKeys) {
439+
if !util.SliceContainsString(providedKeys, giteaKey) {
440440
log.Trace("synchronizePublicKeys[%s]: Marking Public SSH Key for deletion for user %s: %v", s.Name, usr.Name, giteaKey)
441441
giteaKeysToDelete = append(giteaKeysToDelete, giteaKey)
442442
}

models/auth/oauth2.go

+2-2
Original file line numberDiff line numberDiff line change
@@ -69,13 +69,13 @@ func (app *OAuth2Application) ContainsRedirectURI(redirectURI string) bool {
6969
if ip != nil && ip.IsLoopback() {
7070
// strip port
7171
uri.Host = uri.Hostname()
72-
if util.IsStringInSlice(uri.String(), app.RedirectURIs, true) {
72+
if util.SliceContainsString(app.RedirectURIs, uri.String(), true) {
7373
return true
7474
}
7575
}
7676
}
7777
}
78-
return util.IsStringInSlice(redirectURI, app.RedirectURIs, true)
78+
return util.SliceContainsString(app.RedirectURIs, redirectURI, true)
7979
}
8080

8181
// Base32 characters, but lowercased.

models/git/branches.go

+4-4
Original file line numberDiff line numberDiff line change
@@ -342,7 +342,7 @@ func IsProtectedBranch(ctx context.Context, repoID int64, branchName string) (bo
342342
// updateApprovalWhitelist checks whether the user whitelist changed and returns a whitelist with
343343
// the users from newWhitelist which have explicit read or write access to the repo.
344344
func updateApprovalWhitelist(ctx context.Context, repo *repo_model.Repository, currentWhitelist, newWhitelist []int64) (whitelist []int64, err error) {
345-
hasUsersChanged := !util.IsSliceInt64Eq(currentWhitelist, newWhitelist)
345+
hasUsersChanged := !util.SliceSortedEqual(currentWhitelist, newWhitelist)
346346
if !hasUsersChanged {
347347
return currentWhitelist, nil
348348
}
@@ -363,7 +363,7 @@ func updateApprovalWhitelist(ctx context.Context, repo *repo_model.Repository, c
363363
// updateUserWhitelist checks whether the user whitelist changed and returns a whitelist with
364364
// the users from newWhitelist which have write access to the repo.
365365
func updateUserWhitelist(ctx context.Context, repo *repo_model.Repository, currentWhitelist, newWhitelist []int64) (whitelist []int64, err error) {
366-
hasUsersChanged := !util.IsSliceInt64Eq(currentWhitelist, newWhitelist)
366+
hasUsersChanged := !util.SliceSortedEqual(currentWhitelist, newWhitelist)
367367
if !hasUsersChanged {
368368
return currentWhitelist, nil
369369
}
@@ -392,7 +392,7 @@ func updateUserWhitelist(ctx context.Context, repo *repo_model.Repository, curre
392392
// updateTeamWhitelist checks whether the team whitelist changed and returns a whitelist with
393393
// the teams from newWhitelist which have write access to the repo.
394394
func updateTeamWhitelist(ctx context.Context, repo *repo_model.Repository, currentWhitelist, newWhitelist []int64) (whitelist []int64, err error) {
395-
hasTeamsChanged := !util.IsSliceInt64Eq(currentWhitelist, newWhitelist)
395+
hasTeamsChanged := !util.SliceSortedEqual(currentWhitelist, newWhitelist)
396396
if !hasTeamsChanged {
397397
return currentWhitelist, nil
398398
}
@@ -404,7 +404,7 @@ func updateTeamWhitelist(ctx context.Context, repo *repo_model.Repository, curre
404404

405405
whitelist = make([]int64, 0, len(teams))
406406
for i := range teams {
407-
if util.IsInt64InSlice(teams[i].ID, newWhitelist) {
407+
if util.SliceContains(newWhitelist, teams[i].ID) {
408408
whitelist = append(whitelist, teams[i].ID)
409409
}
410410
}

models/issues/assignees.go

+1-1
Original file line numberDiff line numberDiff line change
@@ -155,7 +155,7 @@ func MakeIDsFromAPIAssigneesToAdd(ctx context.Context, oneAssignee string, multi
155155
var requestAssignees []string
156156

157157
// Keeping the old assigning method for compatibility reasons
158-
if oneAssignee != "" && !util.IsStringInSlice(oneAssignee, multipleAssignees) {
158+
if oneAssignee != "" && !util.SliceContainsString(multipleAssignees, oneAssignee) {
159159
requestAssignees = append(requestAssignees, oneAssignee)
160160
}
161161

models/issues/issue.go

+2-2
Original file line numberDiff line numberDiff line change
@@ -1529,7 +1529,7 @@ func IsUserParticipantsOfIssue(user *user_model.User, issue *Issue) bool {
15291529
log.Error(err.Error())
15301530
return false
15311531
}
1532-
return util.IsInt64InSlice(user.ID, userIDs)
1532+
return util.SliceContains(userIDs, user.ID)
15331533
}
15341534

15351535
// UpdateIssueMentions updates issue-user relations for mentioned users.
@@ -2023,7 +2023,7 @@ func (issue *Issue) GetParticipantIDsByIssue(ctx context.Context) ([]int64, erro
20232023
Find(&userIDs); err != nil {
20242024
return nil, fmt.Errorf("get poster IDs: %w", err)
20252025
}
2026-
if !util.IsInt64InSlice(issue.PosterID, userIDs) {
2026+
if !util.SliceContains(userIDs, issue.PosterID) {
20272027
return append(userIDs, issue.PosterID), nil
20282028
}
20292029
return userIDs, nil

models/org_team.go

+7-14
Original file line numberDiff line numberDiff line change
@@ -398,20 +398,13 @@ func DeleteTeam(t *organization.Team) error {
398398
return fmt.Errorf("findProtectedBranches: %w", err)
399399
}
400400
for _, p := range protections {
401-
var matched1, matched2, matched3 bool
402-
if len(p.WhitelistTeamIDs) != 0 {
403-
p.WhitelistTeamIDs, matched1 = util.RemoveIDFromList(
404-
p.WhitelistTeamIDs, t.ID)
405-
}
406-
if len(p.ApprovalsWhitelistTeamIDs) != 0 {
407-
p.ApprovalsWhitelistTeamIDs, matched2 = util.RemoveIDFromList(
408-
p.ApprovalsWhitelistTeamIDs, t.ID)
409-
}
410-
if len(p.MergeWhitelistTeamIDs) != 0 {
411-
p.MergeWhitelistTeamIDs, matched3 = util.RemoveIDFromList(
412-
p.MergeWhitelistTeamIDs, t.ID)
413-
}
414-
if matched1 || matched2 || matched3 {
401+
lenIDs, lenApprovalIDs, lenMergeIDs := len(p.WhitelistTeamIDs), len(p.ApprovalsWhitelistTeamIDs), len(p.MergeWhitelistTeamIDs)
402+
p.WhitelistTeamIDs = util.SliceRemoveAll(p.WhitelistTeamIDs, t.ID)
403+
p.ApprovalsWhitelistTeamIDs = util.SliceRemoveAll(p.ApprovalsWhitelistTeamIDs, t.ID)
404+
p.MergeWhitelistTeamIDs = util.SliceRemoveAll(p.MergeWhitelistTeamIDs, t.ID)
405+
if lenIDs != len(p.WhitelistTeamIDs) ||
406+
lenApprovalIDs != len(p.ApprovalsWhitelistTeamIDs) ||
407+
lenMergeIDs != len(p.MergeWhitelistTeamIDs) {
415408
if _, err = sess.ID(p.ID).Cols(
416409
"whitelist_team_i_ds",
417410
"merge_whitelist_team_i_ds",

models/user.go

+7-14
Original file line numberDiff line numberDiff line change
@@ -141,20 +141,13 @@ func DeleteUser(ctx context.Context, u *user_model.User, purge bool) (err error)
141141
break
142142
}
143143
for _, p := range protections {
144-
var matched1, matched2, matched3 bool
145-
if len(p.WhitelistUserIDs) != 0 {
146-
p.WhitelistUserIDs, matched1 = util.RemoveIDFromList(
147-
p.WhitelistUserIDs, u.ID)
148-
}
149-
if len(p.ApprovalsWhitelistUserIDs) != 0 {
150-
p.ApprovalsWhitelistUserIDs, matched2 = util.RemoveIDFromList(
151-
p.ApprovalsWhitelistUserIDs, u.ID)
152-
}
153-
if len(p.MergeWhitelistUserIDs) != 0 {
154-
p.MergeWhitelistUserIDs, matched3 = util.RemoveIDFromList(
155-
p.MergeWhitelistUserIDs, u.ID)
156-
}
157-
if matched1 || matched2 || matched3 {
144+
lenIDs, lenApprovalIDs, lenMergeIDs := len(p.WhitelistUserIDs), len(p.ApprovalsWhitelistUserIDs), len(p.MergeWhitelistUserIDs)
145+
p.WhitelistUserIDs = util.SliceRemoveAll(p.WhitelistUserIDs, u.ID)
146+
p.ApprovalsWhitelistUserIDs = util.SliceRemoveAll(p.ApprovalsWhitelistUserIDs, u.ID)
147+
p.MergeWhitelistUserIDs = util.SliceRemoveAll(p.MergeWhitelistUserIDs, u.ID)
148+
if lenIDs != len(p.WhitelistUserIDs) ||
149+
lenApprovalIDs != len(p.ApprovalsWhitelistUserIDs) ||
150+
lenMergeIDs != len(p.MergeWhitelistUserIDs) {
158151
if _, err = e.ID(p.ID).Cols(
159152
"whitelist_user_i_ds",
160153
"merge_whitelist_user_i_ds",

modules/repository/init.go

+3-3
Original file line numberDiff line numberDiff line change
@@ -170,7 +170,7 @@ func LoadRepoConfig() {
170170
}
171171

172172
for _, f := range customFiles {
173-
if !util.IsStringInSlice(f, files, true) {
173+
if !util.SliceContainsString(files, f, true) {
174174
files = append(files, f)
175175
}
176176
}
@@ -200,12 +200,12 @@ func LoadRepoConfig() {
200200
// Filter out invalid names and promote preferred licenses.
201201
sortedLicenses := make([]string, 0, len(Licenses))
202202
for _, name := range setting.Repository.PreferredLicenses {
203-
if util.IsStringInSlice(name, Licenses, true) {
203+
if util.SliceContainsString(Licenses, name, true) {
204204
sortedLicenses = append(sortedLicenses, name)
205205
}
206206
}
207207
for _, name := range Licenses {
208-
if !util.IsStringInSlice(name, setting.Repository.PreferredLicenses, true) {
208+
if !util.SliceContainsString(setting.Repository.PreferredLicenses, name, true) {
209209
sortedLicenses = append(sortedLicenses, name)
210210
}
211211
}

modules/util/compare.go

-92
This file was deleted.

0 commit comments

Comments
 (0)