Skip to content

Commit 181dc5d

Browse files
committed
editor: remove out of sync branch before checkout again
If a branch was deleted from server, sometimes it is not reflected on local copy. Therefore, we need to remove the branch with same name if it is out of sync and then checkout to correct version.
1 parent ae4c470 commit 181dc5d

File tree

2 files changed

+31
-1
lines changed

2 files changed

+31
-1
lines changed

models/errors/repo.go

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -59,3 +59,16 @@ func IsMirrorNotExist(err error) bool {
5959
func (err MirrorNotExist) Error() string {
6060
return fmt.Sprintf("mirror does not exist [repo_id: %d]", err.RepoID)
6161
}
62+
63+
type BranchAlreadyExists struct {
64+
Name string
65+
}
66+
67+
func IsBranchAlreadyExists(err error) bool {
68+
_, ok := err.(BranchAlreadyExists)
69+
return ok
70+
}
71+
72+
func (err BranchAlreadyExists) Error() string {
73+
return fmt.Sprintf("branch already exists [name: %s]", err.Name)
74+
}

models/repo_editor.go

Lines changed: 18 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -21,6 +21,7 @@ import (
2121

2222
git "github.com/gogits/git-module"
2323

24+
"github.com/gogits/gogs/models/errors"
2425
"github.com/gogits/gogs/pkg/process"
2526
"github.com/gogits/gogs/pkg/setting"
2627
)
@@ -92,13 +93,29 @@ func (repo *Repository) UpdateRepoFile(doer *User, opts UpdateRepoFileOptions) (
9293
return fmt.Errorf("UpdateLocalCopyBranch [branch: %s]: %v", opts.OldBranch, err)
9394
}
9495

96+
repoPath := repo.RepoPath()
97+
localPath := repo.LocalCopyPath()
98+
9599
if opts.OldBranch != opts.NewBranch {
100+
// Directly return error if new branch already exists in the server
101+
if git.IsBranchExist(repoPath, opts.NewBranch) {
102+
return errors.BranchAlreadyExists{opts.NewBranch}
103+
}
104+
105+
// Otherwise, delete branch from local copy in case out of sync
106+
if git.IsBranchExist(localPath, opts.NewBranch) {
107+
if err = git.DeleteBranch(localPath, opts.NewBranch, git.DeleteBranchOptions{
108+
Force: true,
109+
}); err != nil {
110+
return fmt.Errorf("DeleteBranch [name: %s]: %v", opts.NewBranch, err)
111+
}
112+
}
113+
96114
if err := repo.CheckoutNewBranch(opts.OldBranch, opts.NewBranch); err != nil {
97115
return fmt.Errorf("CheckoutNewBranch [old_branch: %s, new_branch: %s]: %v", opts.OldBranch, opts.NewBranch, err)
98116
}
99117
}
100118

101-
localPath := repo.LocalCopyPath()
102119
oldFilePath := path.Join(localPath, opts.OldTreeName)
103120
filePath := path.Join(localPath, opts.NewTreeName)
104121
os.MkdirAll(path.Dir(filePath), os.ModePerm)

0 commit comments

Comments
 (0)