@@ -411,19 +411,51 @@ func UpdateProtectBranch(ctx context.Context, repo *repo_model.Repository, prote
411411 }
412412 protectBranch .ApprovalsWhitelistTeamIDs = whitelist
413413
414- // Make sure protectBranch.ID is not 0 for whitelists
415- if protectBranch .ID == 0 {
416- if _ , err = db .GetEngine (ctx ).Insert (protectBranch ); err != nil {
417- return fmt .Errorf ("Insert: %v" , err )
414+ return db .WithTx (ctx , func (ctx context.Context ) error {
415+ // Looks like it's a new rule
416+ if protectBranch .ID == 0 {
417+ // as it's a new rule and if priority was not set, we need to calc it.
418+ if protectBranch .Priority == 0 {
419+ var lowestPrio int64
420+ db .GetEngine (ctx ).Table (protectBranch ).
421+ Select ("MAX(priority)" ).
422+ Where ("repo_id = ?" , protectBranch .RepoID ).
423+ Get (& lowestPrio )
424+ log .Trace ("Create new ProtectedBranch at repo[%d] and detect current lowest priority '%d'" , protectBranch .RepoID , lowestPrio )
425+ protectBranch .Priority = lowestPrio + 1
426+ }
427+
428+ if _ , err = db .GetEngine (ctx ).Insert (protectBranch ); err != nil {
429+ return fmt .Errorf ("Insert: %v" , err )
430+ }
431+ return nil
418432 }
419- return nil
420- }
421433
422- if _ , err = db .GetEngine (ctx ).ID (protectBranch .ID ).AllCols ().Update (protectBranch ); err != nil {
423- return fmt .Errorf ("Update: %v" , err )
424- }
434+ // update the rule
435+ if _ , err = db .GetEngine (ctx ).ID (protectBranch .ID ).AllCols ().Update (protectBranch ); err != nil {
436+ return fmt .Errorf ("Update: %v" , err )
437+ }
425438
426- return nil
439+ return nil
440+ })
441+ }
442+
443+ func UpdateProtectBranchPriorities (ctx context.Context , repo * repo_model.Repository , ids []int64 ) error {
444+ prio := int64 (1 )
445+ return db .WithTx (ctx , func (ctx context.Context ) error {
446+ for _ , id := range ids {
447+ if _ , err := db .GetEngine (ctx ).
448+ ID (id ).Where ("repo_id = ?" , repo .ID ).
449+ Cols ("priority" ).
450+ Update (& ProtectedBranch {
451+ Priority : prio ,
452+ }); err != nil {
453+ return err
454+ }
455+ prio ++
456+ }
457+ return nil
458+ })
427459}
428460
429461// updateApprovalWhitelist checks whether the user whitelist changed and returns a whitelist with
0 commit comments