@@ -53,6 +53,7 @@ type ProtectedBranch struct {
5353func init () {
5454 db .RegisterModel (new (ProtectedBranch ))
5555 db .RegisterModel (new (DeletedBranch ))
56+ db .RegisterModel (new (RenamedBranch ))
5657}
5758
5859// IsProtected returns if the branch is protected
@@ -588,3 +589,83 @@ func RemoveOldDeletedBranches(ctx context.Context, olderThan time.Duration) {
588589 log .Error ("DeletedBranchesCleanup: %v" , err )
589590 }
590591}
592+
593+ // RenamedBranch provide renamed branch log
594+ // will check it when a branch can't be found
595+ type RenamedBranch struct {
596+ ID int64 `xorm:"pk autoincr"`
597+ RepoID int64 `xorm:"INDEX NOT NULL"`
598+ From string
599+ To string
600+ CreatedUnix timeutil.TimeStamp `xorm:"created"`
601+ }
602+
603+ // FindRenamedBranch check if a branch was renamed
604+ func FindRenamedBranch (repoID int64 , from string ) (branch * RenamedBranch , exist bool , err error ) {
605+ branch = & RenamedBranch {
606+ RepoID : repoID ,
607+ From : from ,
608+ }
609+ exist , err = db .GetEngine (db .DefaultContext ).Get (branch )
610+
611+ return
612+ }
613+
614+ // RenameBranch rename a branch
615+ func (repo * Repository ) RenameBranch (from , to string , gitAction func (isDefault bool ) error ) (err error ) {
616+ sess := db .NewSession (db .DefaultContext )
617+ defer sess .Close ()
618+ if err := sess .Begin (); err != nil {
619+ return err
620+ }
621+
622+ // 1. update default branch if needed
623+ isDefault := repo .DefaultBranch == from
624+ if isDefault {
625+ repo .DefaultBranch = to
626+ _ , err = sess .ID (repo .ID ).Cols ("default_branch" ).Update (repo )
627+ if err != nil {
628+ return err
629+ }
630+ }
631+
632+ // 2. Update protected branch if needed
633+ protectedBranch , err := getProtectedBranchBy (sess , repo .ID , from )
634+ if err != nil {
635+ return err
636+ }
637+
638+ if protectedBranch != nil {
639+ protectedBranch .BranchName = to
640+ _ , err = sess .ID (protectedBranch .ID ).Cols ("branch_name" ).Update (protectedBranch )
641+ if err != nil {
642+ return err
643+ }
644+ }
645+
646+ // 3. Update all not merged pull request base branch name
647+ _ , err = sess .Table (new (PullRequest )).Where ("base_repo_id=? AND base_branch=? AND has_merged=?" ,
648+ repo .ID , from , false ).
649+ Update (map [string ]interface {}{"base_branch" : to })
650+ if err != nil {
651+ return err
652+ }
653+
654+ // 4. do git action
655+ if err = gitAction (isDefault ); err != nil {
656+ return err
657+ }
658+
659+ // 5. insert renamed branch record
660+ renamedBranch := & RenamedBranch {
661+ RepoID : repo .ID ,
662+ From : from ,
663+ To : to ,
664+ }
665+ _ , err = sess .Insert (renamedBranch )
666+ if err != nil {
667+ return err
668+ }
669+
670+ return sess .Commit ()
671+ }
0 commit comments