@@ -575,6 +575,8 @@ func CanDeleteBranch(ctx context.Context, repo *repo_model.Repository, branchNam
575575
576576// DeleteBranch delete branch
577577func DeleteBranch (ctx context.Context , doer * user_model.User , repo * repo_model.Repository , gitRepo * git.Repository , branchName string , pr * issues_model.PullRequest ) error {
578+ var branchCommit * git.Commit
579+ branchExistsInGit := false
578580 err := repo .MustNotBeArchived ()
579581 if err != nil {
580582 return err
@@ -584,41 +586,49 @@ func DeleteBranch(ctx context.Context, doer *user_model.User, repo *repo_model.R
584586 return err
585587 }
586588
587- rawBranch , err := git_model .GetBranch (ctx , repo .ID , branchName )
588- if err != nil && ! git_model .IsErrBranchNotExist (err ) {
589- return fmt .Errorf ("GetBranch: %vc" , err )
590- }
591-
592- // database branch record not exist or it's a deleted branch
593- notExist := git_model .IsErrBranchNotExist (err ) || rawBranch .IsDeleted
589+ if err := db .WithTx (ctx , func (ctx context.Context ) error {
590+ branchExistsInDB , err := git_model .IsBranchExist (ctx , repo .ID , branchName )
591+ if err != nil {
592+ return fmt .Errorf ("GetBranch: %vc" , err )
593+ }
594594
595- branchCommit , err := gitRepo .GetBranchCommit (branchName )
596- if err != nil && ! errors .Is (err , util .ErrNotExist ) {
597- return err
598- }
595+ branchCommit , err = gitRepo .GetBranchCommit (branchName )
596+ if err != nil && ! errors .Is (err , util .ErrNotExist ) {
597+ return err
598+ }
599+ branchExistsInGit = branchCommit != nil
599600
600- if err := db .WithTx (ctx , func (ctx context.Context ) error {
601- if ! notExist {
601+ if ! branchExistsInDB {
602+ if branchExistsInGit {
603+ err := gitrepo .DeleteBranch (ctx , repo , branchName , true )
604+ return err
605+ } else {
606+ return git.ErrBranchNotExist {
607+ Name : branchName ,
608+ }
609+ }
610+ } else {
602611 if err := git_model .AddDeletedBranch (ctx , repo .ID , branchName , doer .ID ); err != nil {
603612 return err
604613 }
605- }
606614
607- if pr != nil {
608- if err := issues_model .AddDeletePRBranchComment (ctx , doer , pr .BaseRepo , pr .Issue .ID , pr .HeadBranch ); err != nil {
609- return fmt .Errorf ("DeleteBranch: %v" , err )
615+ if pr != nil {
616+ if err := issues_model .AddDeletePRBranchComment (ctx , doer , pr .BaseRepo , pr .Issue .ID , pr .HeadBranch ); err != nil {
617+ return fmt .Errorf ("DeleteBranch: %v" , err )
618+ }
610619 }
611- }
612- if branchCommit == nil {
613- return nil
614- }
615620
616- return gitrepo .DeleteBranch (ctx , repo , branchName , true )
621+ if branchExistsInGit {
622+ return gitrepo .DeleteBranch (ctx , repo , branchName , true )
623+ } else {
624+ return nil
625+ }
626+ }
617627 }); err != nil {
618628 return err
619629 }
620630
621- if branchCommit == nil {
631+ if ! branchExistsInGit {
622632 return nil
623633 }
624634
0 commit comments