From a5cc6d3bfc2c3c04070aba4e6989da76235b11d0 Mon Sep 17 00:00:00 2001 From: Lunny Xiao Date: Thu, 20 Oct 2022 13:39:58 +0800 Subject: [PATCH] Rule Sort --- models/git/protected_branch.go | 12 +++++++++--- models/git/protected_branch_list.go | 24 ++++++++++++++++++++++-- 2 files changed, 31 insertions(+), 5 deletions(-) diff --git a/models/git/protected_branch.go b/models/git/protected_branch.go index e7747917a3..d1037ab8b3 100644 --- a/models/git/protected_branch.go +++ b/models/git/protected_branch.go @@ -30,6 +30,7 @@ type ProtectedBranch struct { RepoID int64 `xorm:"UNIQUE(s)"` BranchName string `xorm:"UNIQUE(s)"` // a branch name or a glob match to branch name globRule glob.Glob `xorm:"-"` + isPlainName bool `xorm:"-"` CanPush bool `xorm:"NOT NULL DEFAULT false"` EnableWhitelist bool WhitelistUserIDs []int64 `xorm:"JSON TEXT"` @@ -60,14 +61,19 @@ func init() { db.RegisterModel(new(ProtectedBranch)) } +func (protectBranch *ProtectedBranch) loadGlob() { + if protectBranch.globRule == nil { + protectBranch.globRule = glob.MustCompile(protectBranch.BranchName, '/') + protectBranch.isPlainName = protectBranch.globRule.Match(protectBranch.BranchName) + } +} + // Match tests if branchName matches the rule func (protectBranch *ProtectedBranch) Match(branchName string) bool { if strings.EqualFold(protectBranch.BranchName, branchName) { return true } - if protectBranch.globRule == nil { - protectBranch.globRule = glob.MustCompile(protectBranch.BranchName, '/') - } + protectBranch.loadGlob() return protectBranch.globRule.Match(branchName) } diff --git a/models/git/protected_branch_list.go b/models/git/protected_branch_list.go index c9f4582f5e..7049b1c9f4 100644 --- a/models/git/protected_branch_list.go +++ b/models/git/protected_branch_list.go @@ -6,6 +6,7 @@ package git import ( "context" + "sort" "code.gitea.io/gitea/models/db" "code.gitea.io/gitea/modules/git" @@ -24,11 +25,30 @@ func (rules ProtectedBranchRules) GetFirstMatched(branchName string) *ProtectedB return nil } +func (rules ProtectedBranchRules) Sort() { + sort.Slice(rules, func(i, j int) bool { + rules[i].loadGlob() + rules[j].loadGlob() + if rules[i].isPlainName { + if !rules[j].isPlainName { + return true + } + } else if rules[j].isPlainName { + return true + } + return rules[i].CreatedUnix < rules[j].CreatedUnix + }) +} + // FindRepoProtectedBranchRules load all repository's protected rules func FindRepoProtectedBranchRules(ctx context.Context, repoID int64) (ProtectedBranchRules, error) { - var rules []*ProtectedBranch + var rules ProtectedBranchRules err := db.GetEngine(ctx).Where("repo_id = ?", repoID).Asc("created_unix").Find(&rules) - return rules, err + if err != nil { + return nil, err + } + rules.Sort() + return rules, nil } // FindAllMatchedBranches find all matched branches