mirror of
https://codeberg.org/forgejo/forgejo.git
synced 2024-12-21 12:44:49 -05:00
Add Pull Request merge options - Ignore white-space for conflict checking, Rebase, Squash merge (#3188)
* Pull request options migration and UI in settings * Add ignore whitespace functionality * Fix settings if pull requests are disabled * Fix migration transaction * Merge with Rebase functionality * UI changes and related functionality for pull request merging button * Implement squash functionality * Fix rebase merging * Fix pull request merge tests * Add squash and rebase tests * Fix API method to reuse default message functions * Some refactoring and small fixes * Remove more hardcoded values from tests * Remove unneeded check from API method * Fix variable name and comment typo * Fix reset commit count after PR merge
This commit is contained in:
parent
a192f3052e
commit
8ac1501ad7
20 changed files with 529 additions and 44 deletions
|
@ -11,21 +11,23 @@ import (
|
|||
"strings"
|
||||
"testing"
|
||||
|
||||
"code.gitea.io/gitea/models"
|
||||
"code.gitea.io/gitea/modules/test"
|
||||
|
||||
"github.com/stretchr/testify/assert"
|
||||
)
|
||||
|
||||
func testPullMerge(t *testing.T, session *TestSession, user, repo, pullnum string) *httptest.ResponseRecorder {
|
||||
func testPullMerge(t *testing.T, session *TestSession, user, repo, pullnum string, mergeStyle models.MergeStyle) *httptest.ResponseRecorder {
|
||||
req := NewRequest(t, "GET", path.Join(user, repo, "pulls", pullnum))
|
||||
resp := session.MakeRequest(t, req, http.StatusOK)
|
||||
|
||||
// Click the little green button to create a pull
|
||||
htmlDoc := NewHTMLParser(t, resp.Body)
|
||||
link, exists := htmlDoc.doc.Find("form.ui.form>button.ui.green.button").Parent().Attr("action")
|
||||
link, exists := htmlDoc.doc.Find(".ui.form." + string(mergeStyle) + "-fields > form").Attr("action")
|
||||
assert.True(t, exists, "The template has changed")
|
||||
req = NewRequestWithValues(t, "POST", link, map[string]string{
|
||||
"_csrf": htmlDoc.GetCSRF(),
|
||||
"do": string(mergeStyle),
|
||||
})
|
||||
resp = session.MakeRequest(t, req, http.StatusFound)
|
||||
|
||||
|
@ -58,7 +60,34 @@ func TestPullMerge(t *testing.T) {
|
|||
|
||||
elem := strings.Split(test.RedirectURL(resp), "/")
|
||||
assert.EqualValues(t, "pulls", elem[3])
|
||||
testPullMerge(t, session, elem[1], elem[2], elem[4])
|
||||
testPullMerge(t, session, elem[1], elem[2], elem[4], models.MergeStyleMerge)
|
||||
}
|
||||
|
||||
func TestPullRebase(t *testing.T) {
|
||||
prepareTestEnv(t)
|
||||
session := loginUser(t, "user1")
|
||||
testRepoFork(t, session, "user2", "repo1", "user1", "repo1")
|
||||
testEditFile(t, session, "user1", "repo1", "master", "README.md", "Hello, World (Edited)\n")
|
||||
|
||||
resp := testPullCreate(t, session, "user1", "repo1", "master")
|
||||
|
||||
elem := strings.Split(test.RedirectURL(resp), "/")
|
||||
assert.EqualValues(t, "pulls", elem[3])
|
||||
testPullMerge(t, session, elem[1], elem[2], elem[4], models.MergeStyleRebase)
|
||||
}
|
||||
|
||||
func TestPullSquash(t *testing.T) {
|
||||
prepareTestEnv(t)
|
||||
session := loginUser(t, "user1")
|
||||
testRepoFork(t, session, "user2", "repo1", "user1", "repo1")
|
||||
testEditFile(t, session, "user1", "repo1", "master", "README.md", "Hello, World (Edited)\n")
|
||||
testEditFile(t, session, "user1", "repo1", "master", "README.md", "Hello, World (Edited!)\n")
|
||||
|
||||
resp := testPullCreate(t, session, "user1", "repo1", "master")
|
||||
|
||||
elem := strings.Split(test.RedirectURL(resp), "/")
|
||||
assert.EqualValues(t, "pulls", elem[3])
|
||||
testPullMerge(t, session, elem[1], elem[2], elem[4], models.MergeStyleSquash)
|
||||
}
|
||||
|
||||
func TestPullCleanUpAfterMerge(t *testing.T) {
|
||||
|
@ -71,7 +100,7 @@ func TestPullCleanUpAfterMerge(t *testing.T) {
|
|||
|
||||
elem := strings.Split(test.RedirectURL(resp), "/")
|
||||
assert.EqualValues(t, "pulls", elem[3])
|
||||
testPullMerge(t, session, elem[1], elem[2], elem[4])
|
||||
testPullMerge(t, session, elem[1], elem[2], elem[4], models.MergeStyleMerge)
|
||||
|
||||
// Check PR branch deletion
|
||||
resp = testPullCleanUp(t, session, elem[1], elem[2], elem[4])
|
||||
|
|
|
@ -9,6 +9,7 @@ import (
|
|||
"strings"
|
||||
"testing"
|
||||
|
||||
"code.gitea.io/gitea/models"
|
||||
"code.gitea.io/gitea/modules/test"
|
||||
|
||||
"github.com/stretchr/testify/assert"
|
||||
|
@ -24,7 +25,7 @@ func TestRepoActivity(t *testing.T) {
|
|||
resp := testPullCreate(t, session, "user1", "repo1", "master")
|
||||
elem := strings.Split(test.RedirectURL(resp), "/")
|
||||
assert.EqualValues(t, "pulls", elem[3])
|
||||
testPullMerge(t, session, elem[1], elem[2], elem[4])
|
||||
testPullMerge(t, session, elem[1], elem[2], elem[4], models.MergeStyleMerge)
|
||||
|
||||
testEditFileToNewBranch(t, session, "user1", "repo1", "master", "feat/better_readme", "README.md", "Hello, World (Edited Again)\n")
|
||||
testPullCreate(t, session, "user1", "repo1", "feat/better_readme")
|
||||
|
|
|
@ -878,6 +878,23 @@ func (err ErrPullRequestAlreadyExists) Error() string {
|
|||
err.ID, err.IssueID, err.HeadRepoID, err.BaseRepoID, err.HeadBranch, err.BaseBranch)
|
||||
}
|
||||
|
||||
// ErrInvalidMergeStyle represents an error if merging with disabled merge strategy
|
||||
type ErrInvalidMergeStyle struct {
|
||||
ID int64
|
||||
Style MergeStyle
|
||||
}
|
||||
|
||||
// IsErrInvalidMergeStyle checks if an error is a ErrInvalidMergeStyle.
|
||||
func IsErrInvalidMergeStyle(err error) bool {
|
||||
_, ok := err.(ErrInvalidMergeStyle)
|
||||
return ok
|
||||
}
|
||||
|
||||
func (err ErrInvalidMergeStyle) Error() string {
|
||||
return fmt.Sprintf("merge strategy is not allowed or is invalid [repo_id: %d, strategy: %s]",
|
||||
err.ID, err.Style)
|
||||
}
|
||||
|
||||
// _________ __
|
||||
// \_ ___ \ ____ _____ _____ ____ _____/ |_
|
||||
// / \ \/ / _ \ / \ / \_/ __ \ / \ __\
|
||||
|
|
|
@ -30,7 +30,7 @@
|
|||
id: 5
|
||||
repo_id: 1
|
||||
type: 3
|
||||
config: "{}"
|
||||
config: "{\"IgnoreWhitespaceConflicts\":false,\"AllowMerge\":true,\"AllowRebase\":true,\"AllowSquash\":true}"
|
||||
created_unix: 946684810
|
||||
|
||||
-
|
||||
|
@ -51,7 +51,7 @@
|
|||
id: 8
|
||||
repo_id: 3
|
||||
type: 3
|
||||
config: "{}"
|
||||
config: "{\"IgnoreWhitespaceConflicts\":true,\"AllowMerge\":true,\"AllowRebase\":false,\"AllowSquash\":false}"
|
||||
created_unix: 946684810
|
||||
|
||||
-
|
||||
|
|
|
@ -160,6 +160,8 @@ var migrations = []Migration{
|
|||
NewMigration("add lfs lock table", addLFSLock),
|
||||
// v53 -> v54
|
||||
NewMigration("add reactions", addReactions),
|
||||
// v54 -> v55
|
||||
NewMigration("add pull request options", addPullRequestOptions),
|
||||
}
|
||||
|
||||
// Migrate database to current version
|
||||
|
|
57
models/migrations/v54.go
Normal file
57
models/migrations/v54.go
Normal file
|
@ -0,0 +1,57 @@
|
|||
// Copyright 2017 The Gitea Authors. All rights reserved.
|
||||
// Use of this source code is governed by a MIT-style
|
||||
// license that can be found in the LICENSE file.
|
||||
|
||||
package migrations
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
|
||||
"code.gitea.io/gitea/modules/util"
|
||||
|
||||
"github.com/go-xorm/xorm"
|
||||
)
|
||||
|
||||
func addPullRequestOptions(x *xorm.Engine) error {
|
||||
// RepoUnit describes all units of a repository
|
||||
type RepoUnit struct {
|
||||
ID int64
|
||||
RepoID int64 `xorm:"INDEX(s)"`
|
||||
Type int `xorm:"INDEX(s)"`
|
||||
Config map[string]interface{} `xorm:"JSON"`
|
||||
CreatedUnix util.TimeStamp `xorm:"INDEX CREATED"`
|
||||
}
|
||||
|
||||
sess := x.NewSession()
|
||||
defer sess.Close()
|
||||
if err := sess.Begin(); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
//Updating existing issue units
|
||||
units := make([]*RepoUnit, 0, 100)
|
||||
if err := sess.Where("`type` = ?", V16UnitTypePRs).Find(&units); err != nil {
|
||||
return fmt.Errorf("Query repo units: %v", err)
|
||||
}
|
||||
for _, unit := range units {
|
||||
if unit.Config == nil {
|
||||
unit.Config = make(map[string]interface{})
|
||||
}
|
||||
if _, ok := unit.Config["IgnoreWhitespaceConflicts"]; !ok {
|
||||
unit.Config["IgnoreWhitespaceConflicts"] = false
|
||||
}
|
||||
if _, ok := unit.Config["AllowMerge"]; !ok {
|
||||
unit.Config["AllowMerge"] = true
|
||||
}
|
||||
if _, ok := unit.Config["AllowRebase"]; !ok {
|
||||
unit.Config["AllowRebase"] = true
|
||||
}
|
||||
if _, ok := unit.Config["AllowSquash"]; !ok {
|
||||
unit.Config["AllowSquash"] = true
|
||||
}
|
||||
if _, err := sess.ID(unit.ID).Cols("config").Update(unit); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
return sess.Commit()
|
||||
}
|
116
models/pull.go
116
models/pull.go
|
@ -16,6 +16,7 @@ import (
|
|||
|
||||
"code.gitea.io/git"
|
||||
"code.gitea.io/gitea/modules/base"
|
||||
"code.gitea.io/gitea/modules/cache"
|
||||
"code.gitea.io/gitea/modules/log"
|
||||
"code.gitea.io/gitea/modules/process"
|
||||
"code.gitea.io/gitea/modules/setting"
|
||||
|
@ -109,6 +110,28 @@ func (pr *PullRequest) loadIssue(e Engine) (err error) {
|
|||
return err
|
||||
}
|
||||
|
||||
// GetDefaultMergeMessage returns default message used when merging pull request
|
||||
func (pr *PullRequest) GetDefaultMergeMessage() string {
|
||||
if pr.HeadRepo == nil {
|
||||
var err error
|
||||
pr.HeadRepo, err = GetRepositoryByID(pr.HeadRepoID)
|
||||
if err != nil {
|
||||
log.Error(4, "GetRepositoryById[%d]: %v", pr.HeadRepoID, err)
|
||||
return ""
|
||||
}
|
||||
}
|
||||
return fmt.Sprintf("Merge branch '%s' of %s/%s into %s", pr.HeadBranch, pr.HeadUserName, pr.HeadRepo.Name, pr.BaseBranch)
|
||||
}
|
||||
|
||||
// GetDefaultSquashMessage returns default message used when squash and merging pull request
|
||||
func (pr *PullRequest) GetDefaultSquashMessage() string {
|
||||
if err := pr.LoadIssue(); err != nil {
|
||||
log.Error(4, "LoadIssue: %v", err)
|
||||
return ""
|
||||
}
|
||||
return fmt.Sprintf("%s (#%d)", pr.Issue.Title, pr.Issue.Index)
|
||||
}
|
||||
|
||||
// APIFormat assumes following fields have been assigned with valid values:
|
||||
// Required - Issue
|
||||
// Optional - Merger
|
||||
|
@ -232,15 +255,38 @@ func (pr *PullRequest) CanAutoMerge() bool {
|
|||
return pr.Status == PullRequestStatusMergeable
|
||||
}
|
||||
|
||||
// MergeStyle represents the approach to merge commits into base branch.
|
||||
type MergeStyle string
|
||||
|
||||
const (
|
||||
// MergeStyleMerge create merge commit
|
||||
MergeStyleMerge MergeStyle = "merge"
|
||||
// MergeStyleRebase rebase before merging
|
||||
MergeStyleRebase MergeStyle = "rebase"
|
||||
// MergeStyleSquash squash commits into single commit before merging
|
||||
MergeStyleSquash MergeStyle = "squash"
|
||||
)
|
||||
|
||||
// Merge merges pull request to base repository.
|
||||
// FIXME: add repoWorkingPull make sure two merges does not happen at same time.
|
||||
func (pr *PullRequest) Merge(doer *User, baseGitRepo *git.Repository) (err error) {
|
||||
func (pr *PullRequest) Merge(doer *User, baseGitRepo *git.Repository, mergeStyle MergeStyle, message string) (err error) {
|
||||
if err = pr.GetHeadRepo(); err != nil {
|
||||
return fmt.Errorf("GetHeadRepo: %v", err)
|
||||
} else if err = pr.GetBaseRepo(); err != nil {
|
||||
return fmt.Errorf("GetBaseRepo: %v", err)
|
||||
}
|
||||
|
||||
prUnit, err := pr.BaseRepo.GetUnit(UnitTypePullRequests)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
prConfig := prUnit.PullRequestsConfig()
|
||||
|
||||
// Check if merge style is correct and allowed
|
||||
if !prConfig.IsMergeStyleAllowed(mergeStyle) {
|
||||
return ErrInvalidMergeStyle{pr.BaseRepo.ID, mergeStyle}
|
||||
}
|
||||
|
||||
defer func() {
|
||||
go HookQueue.Add(pr.BaseRepo.ID)
|
||||
go AddTestPullRequestTask(doer, pr.BaseRepo.ID, pr.BaseBranch, false)
|
||||
|
@ -289,6 +335,8 @@ func (pr *PullRequest) Merge(doer *User, baseGitRepo *git.Repository) (err error
|
|||
return fmt.Errorf("git fetch [%s -> %s]: %s", headRepoPath, tmpBasePath, stderr)
|
||||
}
|
||||
|
||||
switch mergeStyle {
|
||||
case MergeStyleMerge:
|
||||
if _, stderr, err = process.GetManager().ExecDir(-1, tmpBasePath,
|
||||
fmt.Sprintf("PullRequest.Merge (git merge --no-ff --no-commit): %s", tmpBasePath),
|
||||
"git", "merge", "--no-ff", "--no-commit", "head_repo/"+pr.HeadBranch); err != nil {
|
||||
|
@ -299,9 +347,51 @@ func (pr *PullRequest) Merge(doer *User, baseGitRepo *git.Repository) (err error
|
|||
if _, stderr, err = process.GetManager().ExecDir(-1, tmpBasePath,
|
||||
fmt.Sprintf("PullRequest.Merge (git merge): %s", tmpBasePath),
|
||||
"git", "commit", fmt.Sprintf("--author='%s <%s>'", sig.Name, sig.Email),
|
||||
"-m", fmt.Sprintf("Merge branch '%s' of %s/%s into %s", pr.HeadBranch, pr.HeadUserName, pr.HeadRepo.Name, pr.BaseBranch)); err != nil {
|
||||
"-m", message); err != nil {
|
||||
return fmt.Errorf("git commit [%s]: %v - %s", tmpBasePath, err, stderr)
|
||||
}
|
||||
case MergeStyleRebase:
|
||||
// Checkout head branch
|
||||
if _, stderr, err = process.GetManager().ExecDir(-1, tmpBasePath,
|
||||
fmt.Sprintf("PullRequest.Merge (git checkout): %s", tmpBasePath),
|
||||
"git", "checkout", "-b", "head_repo_"+pr.HeadBranch, "head_repo/"+pr.HeadBranch); err != nil {
|
||||
return fmt.Errorf("git checkout: %s", stderr)
|
||||
}
|
||||
// Rebase before merging
|
||||
if _, stderr, err = process.GetManager().ExecDir(-1, tmpBasePath,
|
||||
fmt.Sprintf("PullRequest.Merge (git rebase): %s", tmpBasePath),
|
||||
"git", "rebase", "-q", pr.BaseBranch); err != nil {
|
||||
return fmt.Errorf("git rebase [%s -> %s]: %s", headRepoPath, tmpBasePath, stderr)
|
||||
}
|
||||
// Checkout base branch again
|
||||
if _, stderr, err = process.GetManager().ExecDir(-1, tmpBasePath,
|
||||
fmt.Sprintf("PullRequest.Merge (git checkout): %s", tmpBasePath),
|
||||
"git", "checkout", pr.BaseBranch); err != nil {
|
||||
return fmt.Errorf("git checkout: %s", stderr)
|
||||
}
|
||||
// Merge fast forward
|
||||
if _, stderr, err = process.GetManager().ExecDir(-1, tmpBasePath,
|
||||
fmt.Sprintf("PullRequest.Merge (git rebase): %s", tmpBasePath),
|
||||
"git", "merge", "--ff-only", "-q", "head_repo_"+pr.HeadBranch); err != nil {
|
||||
return fmt.Errorf("git merge --ff-only [%s -> %s]: %s", headRepoPath, tmpBasePath, stderr)
|
||||
}
|
||||
case MergeStyleSquash:
|
||||
// Merge with squash
|
||||
if _, stderr, err = process.GetManager().ExecDir(-1, tmpBasePath,
|
||||
fmt.Sprintf("PullRequest.Merge (git squash): %s", tmpBasePath),
|
||||
"git", "merge", "-q", "--squash", "head_repo/"+pr.HeadBranch); err != nil {
|
||||
return fmt.Errorf("git merge --squash [%s -> %s]: %s", headRepoPath, tmpBasePath, stderr)
|
||||
}
|
||||
sig := pr.Issue.Poster.NewGitSig()
|
||||
if _, stderr, err = process.GetManager().ExecDir(-1, tmpBasePath,
|
||||
fmt.Sprintf("PullRequest.Merge (git squash): %s", tmpBasePath),
|
||||
"git", "commit", fmt.Sprintf("--author='%s <%s>'", sig.Name, sig.Email),
|
||||
"-m", message); err != nil {
|
||||
return fmt.Errorf("git commit [%s]: %v - %s", tmpBasePath, err, stderr)
|
||||
}
|
||||
default:
|
||||
return ErrInvalidMergeStyle{pr.BaseRepo.ID, mergeStyle}
|
||||
}
|
||||
|
||||
// Push back to upstream.
|
||||
if _, stderr, err = process.GetManager().ExecDir(-1, tmpBasePath,
|
||||
|
@ -327,6 +417,9 @@ func (pr *PullRequest) Merge(doer *User, baseGitRepo *git.Repository) (err error
|
|||
log.Error(4, "MergePullRequestAction [%d]: %v", pr.ID, err)
|
||||
}
|
||||
|
||||
// Reset cached commit count
|
||||
cache.Remove(pr.Issue.Repo.GetCommitsCountCacheKey(pr.BaseBranch, true))
|
||||
|
||||
// Reload pull request information.
|
||||
if err = pr.LoadAttributes(); err != nil {
|
||||
log.Error(4, "LoadAttributes: %v", err)
|
||||
|
@ -349,7 +442,6 @@ func (pr *PullRequest) Merge(doer *User, baseGitRepo *git.Repository) (err error
|
|||
return nil
|
||||
}
|
||||
|
||||
// TODO: when squash commits, no need to append merge commit.
|
||||
// It is possible that head branch is not fully sync with base branch for merge commits,
|
||||
// so we need to get latest head commit and append merge commit manually
|
||||
// to avoid strange diff commits produced.
|
||||
|
@ -358,12 +450,14 @@ func (pr *PullRequest) Merge(doer *User, baseGitRepo *git.Repository) (err error
|
|||
log.Error(4, "GetBranchCommit: %v", err)
|
||||
return nil
|
||||
}
|
||||
if mergeStyle == MergeStyleMerge {
|
||||
l.PushFront(mergeCommit)
|
||||
}
|
||||
|
||||
p := &api.PushPayload{
|
||||
Ref: git.BranchPrefix + pr.BaseBranch,
|
||||
Before: pr.MergeBase,
|
||||
After: pr.MergedCommitID,
|
||||
After: mergeCommit.ID.String(),
|
||||
CompareURL: setting.AppURL + pr.BaseRepo.ComposeCompareURL(pr.MergeBase, pr.MergedCommitID),
|
||||
Commits: ListToPushCommits(l).ToAPIPayloadCommits(pr.BaseRepo.HTMLURL()),
|
||||
Repo: pr.BaseRepo.APIFormat(AccessModeNone),
|
||||
|
@ -563,9 +657,21 @@ func (pr *PullRequest) testPatch() (err error) {
|
|||
return fmt.Errorf("git read-tree --index-output=%s %s: %v - %s", indexTmpPath, pr.BaseBranch, err, stderr)
|
||||
}
|
||||
|
||||
prUnit, err := pr.BaseRepo.GetUnit(UnitTypePullRequests)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
prConfig := prUnit.PullRequestsConfig()
|
||||
|
||||
args := []string{"apply", "--check", "--cached"}
|
||||
if prConfig.IgnoreWhitespaceConflicts {
|
||||
args = append(args, "--ignore-whitespace")
|
||||
}
|
||||
args = append(args, patchPath)
|
||||
|
||||
_, stderr, err = process.GetManager().ExecDirEnv(-1, "", fmt.Sprintf("testPatch (git apply --check): %d", pr.BaseRepo.ID),
|
||||
[]string{"GIT_INDEX_FILE=" + indexTmpPath, "GIT_DIR=" + pr.BaseRepo.RepoPath()},
|
||||
"git", "apply", "--check", "--cached", patchPath)
|
||||
"git", args...)
|
||||
if err != nil {
|
||||
for i := range patchConflicts {
|
||||
if strings.Contains(stderr, patchConflicts[i]) {
|
||||
|
|
|
@ -427,6 +427,11 @@ func (repo *Repository) MustGetUnit(tp UnitType) *RepoUnit {
|
|||
Type: tp,
|
||||
Config: new(ExternalTrackerConfig),
|
||||
}
|
||||
} else if tp == UnitTypePullRequests {
|
||||
return &RepoUnit{
|
||||
Type: tp,
|
||||
Config: new(PullRequestsConfig),
|
||||
}
|
||||
}
|
||||
return &RepoUnit{
|
||||
Type: tp,
|
||||
|
|
|
@ -85,18 +85,44 @@ func (cfg *IssuesConfig) ToDB() ([]byte, error) {
|
|||
return json.Marshal(cfg)
|
||||
}
|
||||
|
||||
// PullRequestsConfig describes pull requests config
|
||||
type PullRequestsConfig struct {
|
||||
IgnoreWhitespaceConflicts bool
|
||||
AllowMerge bool
|
||||
AllowRebase bool
|
||||
AllowSquash bool
|
||||
}
|
||||
|
||||
// FromDB fills up a PullRequestsConfig from serialized format.
|
||||
func (cfg *PullRequestsConfig) FromDB(bs []byte) error {
|
||||
return json.Unmarshal(bs, &cfg)
|
||||
}
|
||||
|
||||
// ToDB exports a PullRequestsConfig to a serialized format.
|
||||
func (cfg *PullRequestsConfig) ToDB() ([]byte, error) {
|
||||
return json.Marshal(cfg)
|
||||
}
|
||||
|
||||
// IsMergeStyleAllowed returns if merge style is allowed
|
||||
func (cfg *PullRequestsConfig) IsMergeStyleAllowed(mergeStyle MergeStyle) bool {
|
||||
return mergeStyle == MergeStyleMerge && cfg.AllowMerge ||
|
||||
mergeStyle == MergeStyleRebase && cfg.AllowRebase ||
|
||||
mergeStyle == MergeStyleSquash && cfg.AllowSquash
|
||||
}
|
||||
|
||||
// BeforeSet is invoked from XORM before setting the value of a field of this object.
|
||||
func (r *RepoUnit) BeforeSet(colName string, val xorm.Cell) {
|
||||
switch colName {
|
||||
case "type":
|
||||
switch UnitType(Cell2Int64(val)) {
|
||||
case UnitTypeCode, UnitTypePullRequests, UnitTypeReleases,
|
||||
UnitTypeWiki:
|
||||
case UnitTypeCode, UnitTypeReleases, UnitTypeWiki:
|
||||
r.Config = new(UnitConfig)
|
||||
case UnitTypeExternalWiki:
|
||||
r.Config = new(ExternalWikiConfig)
|
||||
case UnitTypeExternalTracker:
|
||||
r.Config = new(ExternalTrackerConfig)
|
||||
case UnitTypePullRequests:
|
||||
r.Config = new(PullRequestsConfig)
|
||||
case UnitTypeIssues:
|
||||
r.Config = new(IssuesConfig)
|
||||
default:
|
||||
|
@ -116,8 +142,8 @@ func (r *RepoUnit) CodeConfig() *UnitConfig {
|
|||
}
|
||||
|
||||
// PullRequestsConfig returns config for UnitTypePullRequests
|
||||
func (r *RepoUnit) PullRequestsConfig() *UnitConfig {
|
||||
return r.Config.(*UnitConfig)
|
||||
func (r *RepoUnit) PullRequestsConfig() *PullRequestsConfig {
|
||||
return r.Config.(*PullRequestsConfig)
|
||||
}
|
||||
|
||||
// ReleasesConfig returns config for UnitTypeReleases
|
||||
|
|
|
@ -107,6 +107,10 @@ type RepoSettingForm struct {
|
|||
TrackerURLFormat string
|
||||
TrackerIssueStyle string
|
||||
EnablePulls bool
|
||||
PullsIgnoreWhitespace bool
|
||||
PullsAllowMerge bool
|
||||
PullsAllowRebase bool
|
||||
PullsAllowSquash bool
|
||||
EnableTimetracker bool
|
||||
AllowOnlyContributorsToTrackTime bool
|
||||
}
|
||||
|
@ -326,6 +330,25 @@ func (f *InitializeLabelsForm) Validate(ctx *macaron.Context, errs binding.Error
|
|||
return validate(errs, ctx.Data, f, ctx.Locale)
|
||||
}
|
||||
|
||||
// __________ .__ .__ __________ __
|
||||
// \______ \__ __| | | | \______ \ ____ ________ __ ____ _______/ |_
|
||||
// | ___/ | \ | | | | _// __ \/ ____/ | \_/ __ \ / ___/\ __\
|
||||
// | | | | / |_| |__ | | \ ___< <_| | | /\ ___/ \___ \ | |
|
||||
// |____| |____/|____/____/ |____|_ /\___ >__ |____/ \___ >____ > |__|
|
||||
// \/ \/ |__| \/ \/
|
||||
|
||||
// MergePullRequestForm form for merging Pull Request
|
||||
type MergePullRequestForm struct {
|
||||
Do string `binding:"Required;In(merge,rebase,squash)"`
|
||||
MergeTitleField string
|
||||
MergeMessageField string
|
||||
}
|
||||
|
||||
// Validate validates the fields
|
||||
func (f *MergePullRequestForm) Validate(ctx *macaron.Context, errs binding.Errors) binding.Errors {
|
||||
return validate(errs, ctx.Data, f, ctx.Locale)
|
||||
}
|
||||
|
||||
// __________ .__
|
||||
// \______ \ ____ | | ____ _____ ______ ____
|
||||
// | _// __ \| | _/ __ \\__ \ / ___// __ \
|
||||
|
|
|
@ -755,7 +755,12 @@ pulls.is_checking = "The conflict checking is still in progress; please refresh
|
|||
pulls.can_auto_merge_desc = This pull request can be merged automatically.
|
||||
pulls.cannot_auto_merge_desc = This pull request cannot be merged automatically because there are conflicts.
|
||||
pulls.cannot_auto_merge_helper = Please merge manually in order to resolve the conflicts.
|
||||
pulls.no_merge_desc = This pull request can not be merged as no merge options are enabled.
|
||||
pulls.no_merge_helper = To merge this pull request enable at least one merge option in repository settings or merge pull request manually.
|
||||
pulls.merge_pull_request = Merge Pull Request
|
||||
pulls.rebase_merge_pull_request = Rebase and Merge
|
||||
pulls.squash_merge_pull_request = Squash and Merge
|
||||
pulls.invalid_merge_option = You can not use this merge option for this pull request
|
||||
pulls.open_unmerged_pull_exists = `You cannot perform reopen operation because there is already an open pull request (#%d) from same repository with same merge information and is waiting for merging.`
|
||||
|
||||
milestones.new = New Milestone
|
||||
|
@ -894,6 +899,10 @@ settings.tracker_url_format_desc = You can use placeholder <code>{user} {repo} {
|
|||
settings.enable_timetracker = Enable time tracker
|
||||
settings.allow_only_contributors_to_track_time = Allow only contributors to track time
|
||||
settings.pulls_desc = Enable pull requests to accept public contributions
|
||||
settings.pulls.ignore_whitespace = Ignore changes in whitespace when checking conflicts
|
||||
settings.pulls.allow_merge_commits = Allow merge commits
|
||||
settings.pulls.allow_rebase_merge = Allow rebase to merge commits
|
||||
settings.pulls.allow_squash_commits = Allow to squash commits before merging
|
||||
settings.danger_zone = Danger Zone
|
||||
settings.new_owner_has_same_repo = The new owner already has a repository with same name. Please choose another name.
|
||||
settings.convert = Convert To Regular Repository
|
||||
|
|
|
@ -649,6 +649,28 @@ function initRepository() {
|
|||
$('#status').val($statusButton.data('status-val'));
|
||||
$('#comment-form').submit();
|
||||
});
|
||||
|
||||
// Pull Request merge button
|
||||
var $mergeButton = $('.merge-button > button');
|
||||
$mergeButton.on('click', function(e) {
|
||||
e.preventDefault();
|
||||
$('.' + $(this).data('do') + '-fields').show();
|
||||
$(this).parent().hide();
|
||||
});
|
||||
$('.merge-button > .dropdown').dropdown({
|
||||
onChange: function (text, value, $choice) {
|
||||
if ($choice.data('do')) {
|
||||
$mergeButton.find('.button-text').text($choice.text());
|
||||
$mergeButton.data('do', $choice.data('do'));
|
||||
}
|
||||
}
|
||||
});
|
||||
$('.merge-cancel').on('click', function(e) {
|
||||
e.preventDefault();
|
||||
$(this).closest('.form').hide();
|
||||
$mergeButton.parent().show();
|
||||
});
|
||||
|
||||
initReactionSelector();
|
||||
}
|
||||
|
||||
|
|
|
@ -477,7 +477,7 @@ func RegisterRoutes(m *macaron.Macaron) {
|
|||
m.Combo("").Get(repo.GetPullRequest).
|
||||
Patch(reqToken(), reqRepoWriter(), bind(api.EditPullRequestOption{}), repo.EditPullRequest)
|
||||
m.Combo("/merge").Get(repo.IsPullRequestMerged).
|
||||
Post(reqToken(), reqRepoWriter(), repo.MergePullRequest)
|
||||
Post(reqToken(), reqRepoWriter(), bind(auth.MergePullRequestForm{}), repo.MergePullRequest)
|
||||
})
|
||||
|
||||
}, mustAllowPulls, context.ReferencesGitRepo())
|
||||
|
|
|
@ -10,6 +10,7 @@ import (
|
|||
|
||||
"code.gitea.io/git"
|
||||
"code.gitea.io/gitea/models"
|
||||
"code.gitea.io/gitea/modules/auth"
|
||||
"code.gitea.io/gitea/modules/context"
|
||||
"code.gitea.io/gitea/modules/log"
|
||||
|
||||
|
@ -434,7 +435,7 @@ func IsPullRequestMerged(ctx *context.APIContext) {
|
|||
}
|
||||
|
||||
// MergePullRequest merges a PR given an index
|
||||
func MergePullRequest(ctx *context.APIContext) {
|
||||
func MergePullRequest(ctx *context.APIContext, form auth.MergePullRequestForm) {
|
||||
// swagger:operation POST /repos/{owner}/{repo}/pulls/{index}/merge repository repoMergePullRequest
|
||||
// ---
|
||||
// summary: Merge a pull request
|
||||
|
@ -497,7 +498,30 @@ func MergePullRequest(ctx *context.APIContext) {
|
|||
return
|
||||
}
|
||||
|
||||
if err := pr.Merge(ctx.User, ctx.Repo.GitRepo); err != nil {
|
||||
if len(form.Do) == 0 {
|
||||
form.Do = string(models.MergeStyleMerge)
|
||||
}
|
||||
|
||||
message := strings.TrimSpace(form.MergeTitleField)
|
||||
if len(message) == 0 {
|
||||
if models.MergeStyle(form.Do) == models.MergeStyleMerge {
|
||||
message = pr.GetDefaultMergeMessage()
|
||||
}
|
||||
if models.MergeStyle(form.Do) == models.MergeStyleSquash {
|
||||
message = pr.GetDefaultSquashMessage()
|
||||
}
|
||||
}
|
||||
|
||||
form.MergeMessageField = strings.TrimSpace(form.MergeMessageField)
|
||||
if len(form.MergeMessageField) > 0 {
|
||||
message += "\n\n" + form.MergeMessageField
|
||||
}
|
||||
|
||||
if err := pr.Merge(ctx.User, ctx.Repo.GitRepo, models.MergeStyle(form.Do), message); err != nil {
|
||||
if models.IsErrInvalidMergeStyle(err) {
|
||||
ctx.Status(405)
|
||||
return
|
||||
}
|
||||
ctx.Error(500, "Merge", err)
|
||||
return
|
||||
}
|
||||
|
|
|
@ -727,6 +727,26 @@ func ViewIssue(ctx *context.Context) {
|
|||
}
|
||||
}
|
||||
|
||||
prUnit, err := repo.GetUnit(models.UnitTypePullRequests)
|
||||
if err != nil {
|
||||
ctx.Handle(500, "GetUnit", err)
|
||||
return
|
||||
}
|
||||
prConfig := prUnit.PullRequestsConfig()
|
||||
|
||||
// Check correct values and select default
|
||||
if ms, ok := ctx.Data["MergeStyle"].(models.MergeStyle); !ok ||
|
||||
!prConfig.IsMergeStyleAllowed(ms) {
|
||||
if prConfig.AllowMerge {
|
||||
ctx.Data["MergeStyle"] = models.MergeStyleMerge
|
||||
} else if prConfig.AllowRebase {
|
||||
ctx.Data["MergeStyle"] = models.MergeStyleRebase
|
||||
} else if prConfig.AllowSquash {
|
||||
ctx.Data["MergeStyle"] = models.MergeStyleSquash
|
||||
} else {
|
||||
ctx.Data["MergeStyle"] = ""
|
||||
}
|
||||
}
|
||||
ctx.Data["IsPullBranchDeletable"] = canDelete && pull.HeadRepo != nil && git.IsBranchExist(pull.HeadRepo.RepoPath(), pull.HeadBranch)
|
||||
}
|
||||
|
||||
|
|
|
@ -495,7 +495,7 @@ func ViewPullFiles(ctx *context.Context) {
|
|||
}
|
||||
|
||||
// MergePullRequest response for merging pull request
|
||||
func MergePullRequest(ctx *context.Context) {
|
||||
func MergePullRequest(ctx *context.Context, form auth.MergePullRequestForm) {
|
||||
issue := checkPullInfo(ctx)
|
||||
if ctx.Written() {
|
||||
return
|
||||
|
@ -514,15 +514,42 @@ func MergePullRequest(ctx *context.Context) {
|
|||
}
|
||||
return
|
||||
}
|
||||
pr.Issue = issue
|
||||
|
||||
if !pr.CanAutoMerge() || pr.HasMerged {
|
||||
ctx.Handle(404, "MergePullRequest", nil)
|
||||
return
|
||||
}
|
||||
|
||||
if ctx.HasError() {
|
||||
ctx.Flash.Error(ctx.Data["ErrorMsg"].(string))
|
||||
ctx.Redirect(ctx.Repo.RepoLink + "/pulls/" + com.ToStr(pr.Index))
|
||||
return
|
||||
}
|
||||
|
||||
message := strings.TrimSpace(form.MergeTitleField)
|
||||
if len(message) == 0 {
|
||||
if models.MergeStyle(form.Do) == models.MergeStyleMerge {
|
||||
message = pr.GetDefaultMergeMessage()
|
||||
}
|
||||
if models.MergeStyle(form.Do) == models.MergeStyleSquash {
|
||||
message = pr.GetDefaultSquashMessage()
|
||||
}
|
||||
}
|
||||
|
||||
form.MergeMessageField = strings.TrimSpace(form.MergeMessageField)
|
||||
if len(form.MergeMessageField) > 0 {
|
||||
message += "\n\n" + form.MergeMessageField
|
||||
}
|
||||
|
||||
pr.Issue = issue
|
||||
pr.Issue.Repo = ctx.Repo.Repository
|
||||
if err = pr.Merge(ctx.User, ctx.Repo.GitRepo); err != nil {
|
||||
if err = pr.Merge(ctx.User, ctx.Repo.GitRepo, models.MergeStyle(form.Do), message); err != nil {
|
||||
if models.IsErrInvalidMergeStyle(err) {
|
||||
ctx.Flash.Error(ctx.Tr("repo.pulls.invalid_merge_option"))
|
||||
ctx.Redirect(ctx.Repo.RepoLink + "/pulls/" + com.ToStr(pr.Index))
|
||||
return
|
||||
}
|
||||
ctx.Handle(500, "Merge", err)
|
||||
return
|
||||
}
|
||||
|
|
|
@ -211,7 +211,12 @@ func SettingsPost(ctx *context.Context, form auth.RepoSettingForm) {
|
|||
units = append(units, models.RepoUnit{
|
||||
RepoID: repo.ID,
|
||||
Type: models.UnitTypePullRequests,
|
||||
Config: new(models.UnitConfig),
|
||||
Config: &models.PullRequestsConfig{
|
||||
IgnoreWhitespaceConflicts: form.PullsIgnoreWhitespace,
|
||||
AllowMerge: form.PullsAllowMerge,
|
||||
AllowRebase: form.PullsAllowRebase,
|
||||
AllowSquash: form.PullsAllowSquash,
|
||||
},
|
||||
})
|
||||
}
|
||||
|
||||
|
|
|
@ -627,7 +627,7 @@ func RegisterRoutes(m *macaron.Macaron) {
|
|||
m.Get(".diff", repo.DownloadPullDiff)
|
||||
m.Get("/commits", context.RepoRef(), repo.ViewPullCommits)
|
||||
m.Get("/files", context.RepoRef(), repo.SetEditorconfigIfExists, repo.SetDiffViewStyle, repo.ViewPullFiles)
|
||||
m.Post("/merge", reqRepoWriter, repo.MergePullRequest)
|
||||
m.Post("/merge", reqRepoWriter, bindIgnErr(auth.MergePullRequestForm{}), repo.MergePullRequest)
|
||||
m.Post("/cleanup", context.RepoRef(), repo.CleanUpPullRequest)
|
||||
}, repo.MustAllowPulls)
|
||||
|
||||
|
|
|
@ -38,16 +38,101 @@
|
|||
{{$.i18n.Tr "repo.pulls.can_auto_merge_desc"}}
|
||||
</div>
|
||||
{{if .IsRepositoryWriter}}
|
||||
{{$prUnit := .Repository.MustGetUnit $.UnitTypePullRequests}}
|
||||
{{if or $prUnit.PullRequestsConfig.AllowMerge $prUnit.PullRequestsConfig.AllowRebase $prUnit.PullRequestsConfig.AllowSquash}}
|
||||
<div class="ui divider"></div>
|
||||
<div>
|
||||
<form class="ui form" action="{{.Link}}/merge" method="post">
|
||||
{{if $prUnit.PullRequestsConfig.AllowMerge}}
|
||||
<div class="ui form merge-fields" style="display: none">
|
||||
<form action="{{.Link}}/merge" method="post">
|
||||
{{.CsrfTokenHtml}}
|
||||
<button class="ui green button">
|
||||
<span class="octicon octicon-git-merge"></span> {{$.i18n.Tr "repo.pulls.merge_pull_request"}}
|
||||
<div class="field">
|
||||
<input type="text" name="merge_title_field" value="{{.Issue.PullRequest.GetDefaultMergeMessage}}">
|
||||
</div>
|
||||
<div class="field">
|
||||
<textarea name="merge_message_field" rows="5" placeholder="{{$.i18n.Tr "repo.editor.commit_message_desc"}}"></textarea>
|
||||
</div>
|
||||
<button class="ui green button" type="submit" name="do" value="merge">
|
||||
{{$.i18n.Tr "repo.pulls.merge_pull_request"}}
|
||||
</button>
|
||||
<button class="ui button merge-cancel">
|
||||
{{$.i18n.Tr "cancel"}}
|
||||
</button>
|
||||
</form>
|
||||
</div>
|
||||
{{end}}
|
||||
{{if $prUnit.PullRequestsConfig.AllowRebase}}
|
||||
<div class="ui form rebase-fields" style="display: none">
|
||||
<form action="{{.Link}}/merge" method="post">
|
||||
{{.CsrfTokenHtml}}
|
||||
<button class="ui green button" type="submit" name="do" value="rebase">
|
||||
{{$.i18n.Tr "repo.pulls.rebase_merge_pull_request"}}
|
||||
</button>
|
||||
<button class="ui button merge-cancel">
|
||||
{{$.i18n.Tr "cancel"}}
|
||||
</button>
|
||||
</form>
|
||||
</div>
|
||||
{{end}}
|
||||
{{if $prUnit.PullRequestsConfig.AllowSquash}}
|
||||
<div class="ui form squash-fields" style="display: none">
|
||||
<form action="{{.Link}}/merge" method="post">
|
||||
{{.CsrfTokenHtml}}
|
||||
<div class="field">
|
||||
<input type="text" name="merge_title_field" value="{{.Issue.PullRequest.GetDefaultSquashMessage}}">
|
||||
</div>
|
||||
<div class="field">
|
||||
<textarea name="merge_message_field" rows="5" placeholder="{{$.i18n.Tr "repo.editor.commit_message_desc"}}"></textarea>
|
||||
</div>
|
||||
<button class="ui green button" type="submit" name="do" value="squash">
|
||||
{{$.i18n.Tr "repo.pulls.squash_merge_pull_request"}}
|
||||
</button>
|
||||
<button class="ui button merge-cancel">
|
||||
{{$.i18n.Tr "cancel"}}
|
||||
</button>
|
||||
</form>
|
||||
</div>
|
||||
{{end}}
|
||||
<div class="ui green buttons merge-button">
|
||||
<button class="ui button" data-do="{{.MergeStyle}}">
|
||||
<span class="octicon octicon-git-merge"></span>
|
||||
<span class="button-text">
|
||||
{{if eq .MergeStyle "merge"}}
|
||||
{{$.i18n.Tr "repo.pulls.merge_pull_request"}}
|
||||
{{end}}
|
||||
{{if eq .MergeStyle "rebase"}}
|
||||
{{$.i18n.Tr "repo.pulls.rebase_merge_pull_request"}}
|
||||
{{end}}
|
||||
{{if eq .MergeStyle "squash"}}
|
||||
{{$.i18n.Tr "repo.pulls.squash_merge_pull_request"}}
|
||||
{{end}}
|
||||
</span>
|
||||
</button>
|
||||
<div class="ui dropdown icon button">
|
||||
<i class="dropdown icon"></i>
|
||||
<div class="menu">
|
||||
{{if $prUnit.PullRequestsConfig.AllowMerge}}
|
||||
<div class="item{{if eq .MergeStyle "merge"}} active selected{{end}}" data-do="merge">{{$.i18n.Tr "repo.pulls.merge_pull_request"}}</div>
|
||||
{{end}}
|
||||
{{if $prUnit.PullRequestsConfig.AllowRebase}}
|
||||
<div class="item{{if eq .MergeStyle "rebase"}} active selected{{end}}" data-do="rebase">{{$.i18n.Tr "repo.pulls.rebase_merge_pull_request"}}</div>
|
||||
{{end}}
|
||||
{{if $prUnit.PullRequestsConfig.AllowSquash}}
|
||||
<div class="item{{if eq .MergeStyle "squash"}} active selected{{end}}" data-do="squash">{{$.i18n.Tr "repo.pulls.squash_merge_pull_request"}}</div>
|
||||
{{end}}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
{{else}}
|
||||
<div class="item text red">
|
||||
<span class="octicon octicon-x"></span>
|
||||
{{$.i18n.Tr "repo.pulls.no_merge_desc"}}
|
||||
</div>
|
||||
<div class="item text grey">
|
||||
<span class="octicon octicon-info"></span>
|
||||
{{$.i18n.Tr "repo.pulls.no_merge_helper"}}
|
||||
</div>
|
||||
{{end}}
|
||||
{{end}}
|
||||
{{else}}
|
||||
<div class="item text red">
|
||||
<span class="octicon octicon-x"></span>
|
||||
|
|
|
@ -192,14 +192,41 @@
|
|||
|
||||
{{if .Repository.CanEnablePulls}}
|
||||
<div class="ui divider"></div>
|
||||
|
||||
{{$pullRequestEnabled := .Repository.UnitEnabled $.UnitTypePullRequests}}
|
||||
{{$prUnit := .Repository.MustGetUnit $.UnitTypePullRequests}}
|
||||
<div class="inline field">
|
||||
<label>{{.i18n.Tr "repo.pulls"}}</label>
|
||||
<div class="ui checkbox">
|
||||
<input name="enable_pulls" type="checkbox" {{if .Repository.UnitEnabled $.UnitTypePullRequests}}checked{{end}}>
|
||||
<input class="enable-system" name="enable_pulls" type="checkbox" data-target="#pull_box" {{if $pullRequestEnabled}}checked{{end}}>
|
||||
<label>{{.i18n.Tr "repo.settings.pulls_desc"}}</label>
|
||||
</div>
|
||||
</div>
|
||||
<div class="field{{if not $pullRequestEnabled}} disabled{{end}}" id="pull_box">
|
||||
<div class="field">
|
||||
<div class="ui checkbox">
|
||||
<input name="pulls_ignore_whitespace" type="checkbox" {{if and $pullRequestEnabled ($prUnit.PullRequestsConfig.IgnoreWhitespaceConflicts)}}checked{{end}}>
|
||||
<label>{{.i18n.Tr "repo.settings.pulls.ignore_whitespace"}}</label>
|
||||
</div>
|
||||
</div>
|
||||
<div class="field">
|
||||
<div class="ui checkbox">
|
||||
<input name="pulls_allow_merge" type="checkbox" {{if or (not $pullRequestEnabled) ($prUnit.PullRequestsConfig.AllowMerge)}}checked{{end}}>
|
||||
<label>{{.i18n.Tr "repo.settings.pulls.allow_merge_commits"}}</label>
|
||||
</div>
|
||||
</div>
|
||||
<div class="field">
|
||||
<div class="ui checkbox">
|
||||
<input name="pulls_allow_rebase" type="checkbox" {{if or (not $pullRequestEnabled) ($prUnit.PullRequestsConfig.AllowRebase)}}checked{{end}}>
|
||||
<label>{{.i18n.Tr "repo.settings.pulls.allow_rebase_merge"}}</label>
|
||||
</div>
|
||||
</div>
|
||||
<div class="field">
|
||||
<div class="ui checkbox">
|
||||
<input name="pulls_allow_squash" type="checkbox" {{if or (not $pullRequestEnabled) ($prUnit.PullRequestsConfig.AllowSquash)}}checked{{end}}>
|
||||
<label>{{.i18n.Tr "repo.settings.pulls.allow_squash_commits"}}</label>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
{{end}}
|
||||
|
||||
<div class="ui divider"></div>
|
||||
|
|
Loading…
Reference in a new issue