support * not cross slash

This commit is contained in:
Lunny Xiao 2022-09-13 19:38:32 +08:00
parent 553869a7e2
commit aba5aada8b
No known key found for this signature in database
GPG key ID: C3B7C91B632F738A
2 changed files with 68 additions and 7 deletions

View file

@ -26,11 +26,11 @@ import (
// ProtectedBranch struct
type ProtectedBranch struct {
ID int64 `xorm:"pk autoincr"`
RepoID int64 `xorm:"UNIQUE(s)"`
BranchName string `xorm:"UNIQUE(s)"` // a branch name or a glob match to branch name
globRule glob.Glob `xorm:"-"`
CanPush bool `xorm:"NOT NULL DEFAULT false"`
ID int64 `xorm:"pk autoincr"`
RepoID int64 `xorm:"UNIQUE(s)"`
BranchName string `xorm:"UNIQUE(s)"` // a branch name or a glob match to branch name
globRule []glob.Glob `xorm:"-"`
CanPush bool `xorm:"NOT NULL DEFAULT false"`
EnableWhitelist bool
WhitelistUserIDs []int64 `xorm:"JSON TEXT"`
WhitelistTeamIDs []int64 `xorm:"JSON TEXT"`
@ -66,9 +66,21 @@ func (protectBranch *ProtectedBranch) Match(branchName string) bool {
return true
}
if protectBranch.globRule == nil {
protectBranch.globRule = glob.MustCompile(protectBranch.BranchName)
parts := strings.Split(protectBranch.BranchName, "/")
for _, part := range parts {
protectBranch.globRule = append(protectBranch.globRule, glob.MustCompile(part))
}
}
return protectBranch.globRule.Match(branchName)
fields := strings.Split(branchName, "/")
if len(fields) != len(protectBranch.globRule) {
return false
}
for i := 0; i < len(fields); i++ {
if !protectBranch.globRule[i].Match(fields[i]) {
return false
}
}
return true
}
// CanUserPush returns if some user could push to this protected branch

View file

@ -0,0 +1,49 @@
// Copyright 2022 The Gitea Authors. All rights reserved.
// Use of this source code is governed by a MIT-style
// license that can be found in the LICENSE file.
package git
import (
"fmt"
"testing"
"github.com/stretchr/testify/assert"
)
func TestBranchRuleMatch(t *testing.T) {
kases := []struct {
Rule string
BranchName string
ExpectedMatch bool
}{
{
Rule: "release/**",
BranchName: "release/v1.17",
ExpectedMatch: true,
},
{
Rule: "release/v*",
BranchName: "release/v1.16",
ExpectedMatch: true,
},
{
Rule: "*",
BranchName: "release/v1.16",
ExpectedMatch: false,
},
}
for _, kase := range kases {
pb := ProtectedBranch{BranchName: kase.Rule}
var should, infact string
if !kase.ExpectedMatch {
should = " not"
} else {
infact = " not"
}
assert.EqualValues(t, kase.ExpectedMatch, pb.Match(kase.BranchName),
fmt.Sprintf("%s should%s match %s but it is%s", kase.BranchName, should, kase.Rule, infact),
)
}
}