Skip to content

Commit 0a5dc64

Browse files
lafrikslunny
authored andcommitted
Make branch deletion URL more like GitHub's, fixes #1397 (#1994)
* Make branch deletion URL more like GitHub's, fixes #1397 * Add PR branch deletion integration test * Do not allow deleting protected branch * Change http error code to 403 if user has no write rights to repository * Add check to not panic if forked repository has alrady been deleted
1 parent 6db387a commit 0a5dc64

File tree

7 files changed

+241
-70
lines changed

7 files changed

+241
-70
lines changed

integrations/editor_test.go

+43
Original file line numberDiff line numberDiff line change
@@ -126,8 +126,51 @@ func testEditFile(t *testing.T, session *TestSession, user, repo, branch, filePa
126126
return resp
127127
}
128128

129+
func testEditFileToNewBranch(t *testing.T, session *TestSession, user, repo, branch, targetBranch, filePath string) *TestResponse {
130+
131+
newContent := "Hello, World (Edited)\n"
132+
133+
// Get to the 'edit this file' page
134+
req := NewRequest(t, "GET", path.Join(user, repo, "_edit", branch, filePath))
135+
resp := session.MakeRequest(t, req)
136+
assert.EqualValues(t, http.StatusOK, resp.HeaderCode)
137+
138+
htmlDoc := NewHTMLParser(t, resp.Body)
139+
lastCommit := htmlDoc.GetInputValueByName("last_commit")
140+
assert.NotEmpty(t, lastCommit)
141+
142+
// Submit the edits
143+
req = NewRequestWithValues(t, "POST", path.Join(user, repo, "_edit", branch, filePath),
144+
map[string]string{
145+
"_csrf": htmlDoc.GetCSRF(),
146+
"last_commit": lastCommit,
147+
"tree_path": filePath,
148+
"content": newContent,
149+
"commit_choice": "commit-to-new-branch",
150+
"new_branch_name": targetBranch,
151+
},
152+
)
153+
req.Header.Add("Content-Type", "application/x-www-form-urlencoded")
154+
resp = session.MakeRequest(t, req)
155+
assert.EqualValues(t, http.StatusFound, resp.HeaderCode)
156+
157+
// Verify the change
158+
req = NewRequest(t, "GET", path.Join(user, repo, "raw", targetBranch, filePath))
159+
resp = session.MakeRequest(t, req)
160+
assert.EqualValues(t, http.StatusOK, resp.HeaderCode)
161+
assert.EqualValues(t, newContent, string(resp.Body))
162+
163+
return resp
164+
}
165+
129166
func TestEditFile(t *testing.T) {
130167
prepareTestEnv(t)
131168
session := loginUser(t, "user2")
132169
testEditFile(t, session, "user2", "repo1", "master", "README.md")
133170
}
171+
172+
func TestEditFileToNewBranch(t *testing.T) {
173+
prepareTestEnv(t)
174+
session := loginUser(t, "user2")
175+
testEditFileToNewBranch(t, session, "user2", "repo1", "master", "feature/test", "README.md")
176+
}

integrations/pull_create_test.go

+4
Original file line numberDiff line numberDiff line change
@@ -7,6 +7,7 @@ package integrations
77
import (
88
"net/http"
99
"path"
10+
"strings"
1011
"testing"
1112

1213
"github.com/stretchr/testify/assert"
@@ -21,6 +22,9 @@ func testPullCreate(t *testing.T, session *TestSession, user, repo, branch strin
2122
htmlDoc := NewHTMLParser(t, resp.Body)
2223
link, exists := htmlDoc.doc.Find("button.ui.green.small.button").Parent().Attr("href")
2324
assert.True(t, exists, "The template has changed")
25+
if branch != "master" {
26+
link = strings.Replace(link, ":master", ":"+branch, 1)
27+
}
2428

2529
req = NewRequest(t, "GET", link)
2630
resp = session.MakeRequest(t, req)

integrations/pull_merge_test.go

+56
Original file line numberDiff line numberDiff line change
@@ -32,6 +32,25 @@ func testPullMerge(t *testing.T, session *TestSession, user, repo, pullnum strin
3232
return resp
3333
}
3434

35+
func testPullCleanUp(t *testing.T, session *TestSession, user, repo, pullnum string) *TestResponse {
36+
req := NewRequest(t, "GET", path.Join(user, repo, "pulls", pullnum))
37+
resp := session.MakeRequest(t, req)
38+
assert.EqualValues(t, http.StatusOK, resp.HeaderCode)
39+
40+
// Click the little green button to craete a pull
41+
htmlDoc := NewHTMLParser(t, resp.Body)
42+
link, exists := htmlDoc.doc.Find(".comments .merge .delete-button").Attr("data-url")
43+
assert.True(t, exists, "The template has changed")
44+
req = NewRequestWithValues(t, "POST", link, map[string]string{
45+
"_csrf": htmlDoc.GetCSRF(),
46+
})
47+
req.Header.Add("Content-Type", "application/x-www-form-urlencoded")
48+
resp = session.MakeRequest(t, req)
49+
assert.EqualValues(t, http.StatusOK, resp.HeaderCode)
50+
51+
return resp
52+
}
53+
3554
func TestPullMerge(t *testing.T) {
3655
prepareTestEnv(t)
3756
session := loginUser(t, "user1")
@@ -46,3 +65,40 @@ func TestPullMerge(t *testing.T) {
4665
assert.EqualValues(t, "pulls", elem[3])
4766
testPullMerge(t, session, elem[1], elem[2], elem[4])
4867
}
68+
69+
func TestPullCleanUpAfterMerge(t *testing.T) {
70+
prepareTestEnv(t)
71+
session := loginUser(t, "user1")
72+
testRepoFork(t, session)
73+
testEditFileToNewBranch(t, session, "user1", "repo1", "master", "feature/test", "README.md")
74+
75+
resp := testPullCreate(t, session, "user1", "repo1", "feature/test")
76+
redirectedURL := resp.Headers["Location"]
77+
assert.NotEmpty(t, redirectedURL, "Redirected URL is not found")
78+
79+
elem := strings.Split(redirectedURL[0], "/")
80+
assert.EqualValues(t, "pulls", elem[3])
81+
testPullMerge(t, session, elem[1], elem[2], elem[4])
82+
83+
// Check PR branch deletion
84+
resp = testPullCleanUp(t, session, elem[1], elem[2], elem[4])
85+
respJSON := struct {
86+
Redirect string
87+
}{}
88+
DecodeJSON(t, resp, &respJSON)
89+
90+
assert.NotEmpty(t, respJSON.Redirect, "Redirected URL is not found")
91+
92+
elem = strings.Split(respJSON.Redirect, "/")
93+
assert.EqualValues(t, "pulls", elem[3])
94+
95+
// Check branch deletion result
96+
req := NewRequest(t, "GET", respJSON.Redirect)
97+
resp = session.MakeRequest(t, req)
98+
assert.EqualValues(t, http.StatusOK, resp.HeaderCode)
99+
100+
htmlDoc := NewHTMLParser(t, resp.Body)
101+
resultMsg := htmlDoc.doc.Find(".ui.message>p").Text()
102+
103+
assert.EqualValues(t, "user1/feature/test has been deleted.", resultMsg)
104+
}

routers/repo/branch.go

-59
Original file line numberDiff line numberDiff line change
@@ -5,11 +5,8 @@
55
package repo
66

77
import (
8-
"code.gitea.io/git"
9-
"code.gitea.io/gitea/models"
108
"code.gitea.io/gitea/modules/base"
119
"code.gitea.io/gitea/modules/context"
12-
"code.gitea.io/gitea/modules/log"
1310
)
1411

1512
const (
@@ -33,59 +30,3 @@ func Branches(ctx *context.Context) {
3330
ctx.Data["Branches"] = brs
3431
ctx.HTML(200, tplBranch)
3532
}
36-
37-
// DeleteBranchPost responses for delete merged branch
38-
func DeleteBranchPost(ctx *context.Context) {
39-
branchName := ctx.Params(":name")
40-
commitID := ctx.Query("commit")
41-
42-
defer func() {
43-
redirectTo := ctx.Query("redirect_to")
44-
if len(redirectTo) == 0 {
45-
redirectTo = ctx.Repo.RepoLink
46-
}
47-
48-
ctx.JSON(200, map[string]interface{}{
49-
"redirect": redirectTo,
50-
})
51-
}()
52-
53-
fullBranchName := ctx.Repo.Owner.Name + "/" + branchName
54-
55-
if !ctx.Repo.GitRepo.IsBranchExist(branchName) || branchName == "master" {
56-
ctx.Flash.Error(ctx.Tr("repo.branch.deletion_failed", fullBranchName))
57-
return
58-
}
59-
60-
if len(commitID) > 0 {
61-
branchCommitID, err := ctx.Repo.GitRepo.GetBranchCommitID(branchName)
62-
if err != nil {
63-
log.Error(4, "GetBranchCommitID: %v", err)
64-
return
65-
}
66-
67-
if branchCommitID != commitID {
68-
ctx.Flash.Error(ctx.Tr("repo.branch.delete_branch_has_new_commits", fullBranchName))
69-
return
70-
}
71-
}
72-
73-
if err := ctx.Repo.GitRepo.DeleteBranch(branchName, git.DeleteBranchOptions{
74-
Force: true,
75-
}); err != nil {
76-
log.Error(4, "DeleteBranch: %v", err)
77-
ctx.Flash.Error(ctx.Tr("repo.branch.deletion_failed", fullBranchName))
78-
return
79-
}
80-
81-
issueID := ctx.QueryInt64("issue_id")
82-
if issueID > 0 {
83-
if err := models.AddDeletePRBranchComment(ctx.User, ctx.Repo.Repository, issueID, branchName); err != nil {
84-
log.Error(4, "DeleteBranch: %v", err)
85-
ctx.Flash.Error(ctx.Tr("repo.branch.deletion_failed", fullBranchName))
86-
return
87-
}
88-
}
89-
90-
ctx.Flash.Success(ctx.Tr("repo.branch.deletion_success", fullBranchName))
91-
}

routers/repo/issue.go

+10-8
Original file line numberDiff line numberDiff line change
@@ -647,19 +647,21 @@ func ViewIssue(ctx *context.Context) {
647647
pull := issue.PullRequest
648648
canDelete := false
649649

650-
if ctx.IsSigned && pull.HeadBranch != "master" {
650+
if ctx.IsSigned {
651651
if err := pull.GetHeadRepo(); err != nil {
652652
log.Error(4, "GetHeadRepo: %v", err)
653-
} else if ctx.User.IsWriterOfRepo(pull.HeadRepo) {
654-
canDelete = true
655-
deleteBranchURL := pull.HeadRepo.Link() + "/branches/" + pull.HeadBranch + "/delete"
656-
ctx.Data["DeleteBranchLink"] = fmt.Sprintf("%s?commit=%s&redirect_to=%s&issue_id=%d",
657-
deleteBranchURL, pull.MergedCommitID, ctx.Data["Link"], issue.ID)
658-
653+
} else if pull.HeadRepo != nil && pull.HeadBranch != pull.HeadRepo.DefaultBranch && ctx.User.IsWriterOfRepo(pull.HeadRepo) {
654+
// Check if branch is not protected
655+
if protected, err := pull.HeadRepo.IsProtectedBranch(pull.HeadBranch); err != nil {
656+
log.Error(4, "IsProtectedBranch: %v", err)
657+
} else if !protected {
658+
canDelete = true
659+
ctx.Data["DeleteBranchLink"] = ctx.Repo.RepoLink + "/pulls/" + com.ToStr(issue.Index) + "/cleanup"
660+
}
659661
}
660662
}
661663

662-
ctx.Data["IsPullBranchDeletable"] = canDelete && git.IsBranchExist(pull.HeadRepo.RepoPath(), pull.HeadBranch)
664+
ctx.Data["IsPullBranchDeletable"] = canDelete && pull.HeadRepo != nil && git.IsBranchExist(pull.HeadRepo.RepoPath(), pull.HeadBranch)
663665
}
664666

665667
ctx.Data["Participants"] = participants

routers/repo/pull.go

+127
Original file line numberDiff line numberDiff line change
@@ -757,3 +757,130 @@ func TriggerTask(ctx *context.Context) {
757757
go models.AddTestPullRequestTask(pusher, repo.ID, branch, true)
758758
ctx.Status(202)
759759
}
760+
761+
// CleanUpPullRequest responses for delete merged branch when PR has been merged
762+
func CleanUpPullRequest(ctx *context.Context) {
763+
issue := checkPullInfo(ctx)
764+
if ctx.Written() {
765+
return
766+
}
767+
768+
pr, err := models.GetPullRequestByIssueID(issue.ID)
769+
if err != nil {
770+
if models.IsErrPullRequestNotExist(err) {
771+
ctx.Handle(404, "GetPullRequestByIssueID", nil)
772+
} else {
773+
ctx.Handle(500, "GetPullRequestByIssueID", err)
774+
}
775+
return
776+
}
777+
778+
// Allow cleanup only for merged PR
779+
if !pr.HasMerged {
780+
ctx.Handle(404, "CleanUpPullRequest", nil)
781+
return
782+
}
783+
784+
if err = pr.GetHeadRepo(); err != nil {
785+
ctx.Handle(500, "GetHeadRepo", err)
786+
return
787+
} else if pr.HeadRepo == nil {
788+
// Forked repository has already been deleted
789+
ctx.Handle(404, "CleanUpPullRequest", nil)
790+
return
791+
} else if pr.GetBaseRepo(); err != nil {
792+
ctx.Handle(500, "GetBaseRepo", err)
793+
return
794+
} else if pr.HeadRepo.GetOwner(); err != nil {
795+
ctx.Handle(500, "HeadRepo.GetOwner", err)
796+
return
797+
}
798+
799+
if !ctx.User.IsWriterOfRepo(pr.HeadRepo) {
800+
ctx.Handle(403, "CleanUpPullRequest", nil)
801+
return
802+
}
803+
804+
fullBranchName := pr.HeadRepo.Owner.Name + "/" + pr.HeadBranch
805+
806+
gitRepo, err := git.OpenRepository(pr.HeadRepo.RepoPath())
807+
if err != nil {
808+
ctx.Handle(500, fmt.Sprintf("OpenRepository[%s]", pr.HeadRepo.RepoPath()), err)
809+
return
810+
}
811+
812+
gitBaseRepo, err := git.OpenRepository(pr.BaseRepo.RepoPath())
813+
if err != nil {
814+
ctx.Handle(500, fmt.Sprintf("OpenRepository[%s]", pr.BaseRepo.RepoPath()), err)
815+
return
816+
}
817+
818+
defer func() {
819+
ctx.JSON(200, map[string]interface{}{
820+
"redirect": pr.BaseRepo.Link() + "/pulls/" + com.ToStr(issue.Index),
821+
})
822+
}()
823+
824+
if pr.HeadBranch == pr.HeadRepo.DefaultBranch || !gitRepo.IsBranchExist(pr.HeadBranch) {
825+
ctx.Flash.Error(ctx.Tr("repo.branch.deletion_failed", fullBranchName))
826+
return
827+
}
828+
829+
// Check if branch is not protected
830+
if protected, err := pr.HeadRepo.IsProtectedBranch(pr.HeadBranch); err != nil || protected {
831+
if err != nil {
832+
log.Error(4, "HeadRepo.IsProtectedBranch: %v", err)
833+
}
834+
ctx.Flash.Error(ctx.Tr("repo.branch.deletion_failed", fullBranchName))
835+
return
836+
}
837+
838+
// Check if branch has no new commits
839+
if len(pr.MergedCommitID) > 0 {
840+
branchCommitID, err := gitRepo.GetBranchCommitID(pr.HeadBranch)
841+
if err != nil {
842+
log.Error(4, "GetBranchCommitID: %v", err)
843+
ctx.Flash.Error(ctx.Tr("repo.branch.deletion_failed", fullBranchName))
844+
return
845+
}
846+
847+
commit, err := gitBaseRepo.GetCommit(pr.MergedCommitID)
848+
if err != nil {
849+
log.Error(4, "GetCommit: %v", err)
850+
ctx.Flash.Error(ctx.Tr("repo.branch.deletion_failed", fullBranchName))
851+
return
852+
}
853+
854+
isParent := false
855+
for i := 0; i < commit.ParentCount(); i++ {
856+
if parent, err := commit.Parent(i); err != nil {
857+
log.Error(4, "Parent: %v", err)
858+
ctx.Flash.Error(ctx.Tr("repo.branch.deletion_failed", fullBranchName))
859+
return
860+
} else if parent.ID.String() == branchCommitID {
861+
isParent = true
862+
break
863+
}
864+
}
865+
866+
if !isParent {
867+
ctx.Flash.Error(ctx.Tr("repo.branch.delete_branch_has_new_commits", fullBranchName))
868+
return
869+
}
870+
}
871+
872+
if err := gitRepo.DeleteBranch(pr.HeadBranch, git.DeleteBranchOptions{
873+
Force: true,
874+
}); err != nil {
875+
log.Error(4, "DeleteBranch: %v", err)
876+
ctx.Flash.Error(ctx.Tr("repo.branch.deletion_failed", fullBranchName))
877+
return
878+
}
879+
880+
if err := models.AddDeletePRBranchComment(ctx.User, pr.BaseRepo, issue.ID, pr.HeadBranch); err != nil {
881+
// Do not fail here as branch has already been deleted
882+
log.Error(4, "DeleteBranch: %v", err)
883+
}
884+
885+
ctx.Flash.Success(ctx.Tr("repo.branch.deletion_success", fullBranchName))
886+
}

routers/routes/routes.go

+1-3
Original file line numberDiff line numberDiff line change
@@ -562,9 +562,6 @@ func RegisterRoutes(m *macaron.Macaron) {
562562
m.Get("/milestones", repo.Milestones)
563563
}, context.RepoRef())
564564

565-
// m.Get("/branches", repo.Branches)
566-
m.Post("/branches/:name/delete", reqSignIn, reqRepoWriter, repo.MustBeNotBare, repo.DeleteBranchPost)
567-
568565
m.Group("/wiki", func() {
569566
m.Get("/?:page", repo.Wiki)
570567
m.Get("/_pages", repo.WikiPages)
@@ -589,6 +586,7 @@ func RegisterRoutes(m *macaron.Macaron) {
589586
m.Get("/commits", context.RepoRef(), repo.ViewPullCommits)
590587
m.Get("/files", context.RepoRef(), repo.SetEditorconfigIfExists, repo.SetDiffViewStyle, repo.ViewPullFiles)
591588
m.Post("/merge", reqRepoWriter, repo.MergePullRequest)
589+
m.Post("/cleanup", context.RepoRef(), repo.CleanUpPullRequest)
592590
}, repo.MustAllowPulls, context.CheckUnit(models.UnitTypePullRequests))
593591

594592
m.Group("", func() {

0 commit comments

Comments
 (0)