@@ -34,6 +34,7 @@ type ProtectedBranch struct {
3434 RepoID int64 `xorm:"UNIQUE(s)"`
3535 Repo * repo_model.Repository `xorm:"-"`
3636 RuleName string `xorm:"'branch_name' UNIQUE(s)"` // a branch name or a glob match to branch name
37+ Priority int64 `xorm:"NOT NULL DEFAULT 0"`
3738 globRule glob.Glob `xorm:"-"`
3839 isPlainName bool `xorm:"-"`
3940 CanPush bool `xorm:"NOT NULL DEFAULT false"`
@@ -413,21 +414,52 @@ func UpdateProtectBranch(ctx context.Context, repo *repo_model.Repository, prote
413414 }
414415 protectBranch .ApprovalsWhitelistTeamIDs = whitelist
415416
416- // Make sure protectBranch.ID is not 0 for whitelists
417+ // Looks like it's a new rule
417418 if protectBranch .ID == 0 {
419+ // as it's a new rule and if priority was not set, we need to calc it.
420+ if protectBranch .Priority == 0 {
421+ var lowestPrio int64
422+ // because of mssql we can not use builder or save xorm syntax, so raw sql it is
423+ if _ , err := db .GetEngine (ctx ).SQL (`SELECT MAX(priority) FROM protected_branch WHERE repo_id = ?` , protectBranch .RepoID ).
424+ Get (& lowestPrio ); err != nil {
425+ return err
426+ }
427+ log .Trace ("Create new ProtectedBranch at repo[%d] and detect current lowest priority '%d'" , protectBranch .RepoID , lowestPrio )
428+ protectBranch .Priority = lowestPrio + 1
429+ }
430+
418431 if _ , err = db .GetEngine (ctx ).Insert (protectBranch ); err != nil {
419432 return fmt .Errorf ("Insert: %v" , err )
420433 }
421434 return nil
422435 }
423436
437+ // update the rule
424438 if _ , err = db .GetEngine (ctx ).ID (protectBranch .ID ).AllCols ().Update (protectBranch ); err != nil {
425439 return fmt .Errorf ("Update: %v" , err )
426440 }
427441
428442 return nil
429443}
430444
445+ func UpdateProtectBranchPriorities (ctx context.Context , repo * repo_model.Repository , ids []int64 ) error {
446+ prio := int64 (1 )
447+ return db .WithTx (ctx , func (ctx context.Context ) error {
448+ for _ , id := range ids {
449+ if _ , err := db .GetEngine (ctx ).
450+ ID (id ).Where ("repo_id = ?" , repo .ID ).
451+ Cols ("priority" ).
452+ Update (& ProtectedBranch {
453+ Priority : prio ,
454+ }); err != nil {
455+ return err
456+ }
457+ prio ++
458+ }
459+ return nil
460+ })
461+ }
462+
431463// updateApprovalWhitelist checks whether the user whitelist changed and returns a whitelist with
432464// the users from newWhitelist which have explicit read or write access to the repo.
433465func updateApprovalWhitelist (ctx context.Context , repo * repo_model.Repository , currentWhitelist , newWhitelist []int64 ) (whitelist []int64 , err error ) {
0 commit comments