Browse Source

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
Lauris BH 2 years ago
parent
commit
0a5dc640a1

+ 43 - 0
integrations/editor_test.go

@@ -126,8 +126,51 @@ func testEditFile(t *testing.T, session *TestSession, user, repo, branch, filePa
126 126
 	return resp
127 127
 }
128 128
 
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
+
129 166
 func TestEditFile(t *testing.T) {
130 167
 	prepareTestEnv(t)
131 168
 	session := loginUser(t, "user2")
132 169
 	testEditFile(t, session, "user2", "repo1", "master", "README.md")
133 170
 }
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
+}

+ 4 - 0
integrations/pull_create_test.go

@@ -7,6 +7,7 @@ package integrations
7 7
 import (
8 8
 	"net/http"
9 9
 	"path"
10
+	"strings"
10 11
 	"testing"
11 12
 
12 13
 	"github.com/stretchr/testify/assert"
@@ -21,6 +22,9 @@ func testPullCreate(t *testing.T, session *TestSession, user, repo, branch strin
21 22
 	htmlDoc := NewHTMLParser(t, resp.Body)
22 23
 	link, exists := htmlDoc.doc.Find("button.ui.green.small.button").Parent().Attr("href")
23 24
 	assert.True(t, exists, "The template has changed")
25
+	if branch != "master" {
26
+		link = strings.Replace(link, ":master", ":"+branch, 1)
27
+	}
24 28
 
25 29
 	req = NewRequest(t, "GET", link)
26 30
 	resp = session.MakeRequest(t, req)

+ 56 - 0
integrations/pull_merge_test.go

@@ -32,6 +32,25 @@ func testPullMerge(t *testing.T, session *TestSession, user, repo, pullnum strin
32 32
 	return resp
33 33
 }
34 34
 
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
+
35 54
 func TestPullMerge(t *testing.T) {
36 55
 	prepareTestEnv(t)
37 56
 	session := loginUser(t, "user1")
@@ -46,3 +65,40 @@ func TestPullMerge(t *testing.T) {
46 65
 	assert.EqualValues(t, "pulls", elem[3])
47 66
 	testPullMerge(t, session, elem[1], elem[2], elem[4])
48 67
 }
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
+}

+ 0 - 59
routers/repo/branch.go

@@ -5,11 +5,8 @@
5 5
 package repo
6 6
 
7 7
 import (
8
-	"code.gitea.io/git"
9
-	"code.gitea.io/gitea/models"
10 8
 	"code.gitea.io/gitea/modules/base"
11 9
 	"code.gitea.io/gitea/modules/context"
12
-	"code.gitea.io/gitea/modules/log"
13 10
 )
14 11
 
15 12
 const (
@@ -33,59 +30,3 @@ func Branches(ctx *context.Context) {
33 30
 	ctx.Data["Branches"] = brs
34 31
 	ctx.HTML(200, tplBranch)
35 32
 }
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
-}

+ 10 - 8
routers/repo/issue.go

@@ -647,19 +647,21 @@ func ViewIssue(ctx *context.Context) {
647 647
 		pull := issue.PullRequest
648 648
 		canDelete := false
649 649
 
650
-		if ctx.IsSigned && pull.HeadBranch != "master" {
650
+		if ctx.IsSigned {
651 651
 			if err := pull.GetHeadRepo(); err != nil {
652 652
 				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
+				}
659 661
 			}
660 662
 		}
661 663
 
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)
663 665
 	}
664 666
 
665 667
 	ctx.Data["Participants"] = participants

+ 127 - 0
routers/repo/pull.go

@@ -757,3 +757,130 @@ func TriggerTask(ctx *context.Context) {
757 757
 	go models.AddTestPullRequestTask(pusher, repo.ID, branch, true)
758 758
 	ctx.Status(202)
759 759
 }
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
+}

+ 1 - 3
routers/routes/routes.go

@@ -562,9 +562,6 @@ func RegisterRoutes(m *macaron.Macaron) {
562 562
 			m.Get("/milestones", repo.Milestones)
563 563
 		}, context.RepoRef())
564 564
 
565
-		// m.Get("/branches", repo.Branches)
566
-		m.Post("/branches/:name/delete", reqSignIn, reqRepoWriter, repo.MustBeNotBare, repo.DeleteBranchPost)
567
-
568 565
 		m.Group("/wiki", func() {
569 566
 			m.Get("/?:page", repo.Wiki)
570 567
 			m.Get("/_pages", repo.WikiPages)
@@ -589,6 +586,7 @@ func RegisterRoutes(m *macaron.Macaron) {
589 586
 			m.Get("/commits", context.RepoRef(), repo.ViewPullCommits)
590 587
 			m.Get("/files", context.RepoRef(), repo.SetEditorconfigIfExists, repo.SetDiffViewStyle, repo.ViewPullFiles)
591 588
 			m.Post("/merge", reqRepoWriter, repo.MergePullRequest)
589
+			m.Post("/cleanup", context.RepoRef(), repo.CleanUpPullRequest)
592 590
 		}, repo.MustAllowPulls, context.CheckUnit(models.UnitTypePullRequests))
593 591
 
594 592
 		m.Group("", func() {