diff --git a/integrations/pull_merge_test.go b/integrations/pull_merge_test.go index 65ccc93f9..b12323933 100644 --- a/integrations/pull_merge_test.go +++ b/integrations/pull_merge_test.go @@ -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]) diff --git a/integrations/repo_activity_test.go b/integrations/repo_activity_test.go index d3d2de4a2..40983cbe1 100644 --- a/integrations/repo_activity_test.go +++ b/integrations/repo_activity_test.go @@ -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") diff --git a/models/error.go b/models/error.go index fceee21fd..765b8fa6c 100644 --- a/models/error.go +++ b/models/error.go @@ -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) +} + // _________ __ // \_ ___ \ ____ _____ _____ ____ _____/ |_ // / \ \/ / _ \ / \ / \_/ __ \ / \ __\ diff --git a/models/fixtures/repo_unit.yml b/models/fixtures/repo_unit.yml index e9931453a..45229cce3 100644 --- a/models/fixtures/repo_unit.yml +++ b/models/fixtures/repo_unit.yml @@ -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 - diff --git a/models/migrations/migrations.go b/models/migrations/migrations.go index cbd09afab..90f286056 100644 --- a/models/migrations/migrations.go +++ b/models/migrations/migrations.go @@ -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 diff --git a/models/migrations/v54.go b/models/migrations/v54.go new file mode 100644 index 000000000..96c26739c --- /dev/null +++ b/models/migrations/v54.go @@ -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() +} diff --git a/models/pull.go b/models/pull.go index 47fc1dfb6..c9357e913 100644 --- a/models/pull.go +++ b/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,18 +335,62 @@ func (pr *PullRequest) Merge(doer *User, baseGitRepo *git.Repository) (err error return fmt.Errorf("git fetch [%s -> %s]: %s", headRepoPath, tmpBasePath, stderr) } - 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 { - return fmt.Errorf("git merge --no-ff --no-commit [%s]: %v - %s", tmpBasePath, err, 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 { + return fmt.Errorf("git merge --no-ff --no-commit [%s]: %v - %s", tmpBasePath, err, stderr) + } - sig := doer.NewGitSig() - 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 { - return fmt.Errorf("git commit [%s]: %v - %s", tmpBasePath, err, stderr) + sig := doer.NewGitSig() + 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", 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. @@ -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 } - l.PushFront(mergeCommit) + 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]) { diff --git a/models/repo.go b/models/repo.go index 29fd39ca9..a9e116d6b 100644 --- a/models/repo.go +++ b/models/repo.go @@ -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, diff --git a/models/repo_unit.go b/models/repo_unit.go index 5100ca1ce..49b62ec9c 100644 --- a/models/repo_unit.go +++ b/models/repo_unit.go @@ -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 diff --git a/modules/auth/repo_form.go b/modules/auth/repo_form.go index 221f7221a..634274c4e 100644 --- a/modules/auth/repo_form.go +++ b/modules/auth/repo_form.go @@ -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) +} + // __________ .__ // \______ \ ____ | | ____ _____ ______ ____ // | _// __ \| | _/ __ \\__ \ / ___// __ \ diff --git a/options/locale/locale_en-US.ini b/options/locale/locale_en-US.ini index 4e1cf42dd..4344a6577 100644 --- a/options/locale/locale_en-US.ini +++ b/options/locale/locale_en-US.ini @@ -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 {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 diff --git a/public/js/index.js b/public/js/index.js index 9104bf640..160be5b68 100644 --- a/public/js/index.js +++ b/public/js/index.js @@ -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(); } diff --git a/routers/api/v1/api.go b/routers/api/v1/api.go index 588a76361..8a300f995 100644 --- a/routers/api/v1/api.go +++ b/routers/api/v1/api.go @@ -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()) diff --git a/routers/api/v1/repo/pull.go b/routers/api/v1/repo/pull.go index 50b864e32..7e011219b 100644 --- a/routers/api/v1/repo/pull.go +++ b/routers/api/v1/repo/pull.go @@ -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 } diff --git a/routers/repo/issue.go b/routers/repo/issue.go index 530586a14..e4aecf152 100644 --- a/routers/repo/issue.go +++ b/routers/repo/issue.go @@ -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) } diff --git a/routers/repo/pull.go b/routers/repo/pull.go index 6162df965..9de826895 100644 --- a/routers/repo/pull.go +++ b/routers/repo/pull.go @@ -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 } diff --git a/routers/repo/setting.go b/routers/repo/setting.go index 8cb551707..342451b8a 100644 --- a/routers/repo/setting.go +++ b/routers/repo/setting.go @@ -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, + }, }) } diff --git a/routers/routes/routes.go b/routers/routes/routes.go index 4293cca6c..3e00f55eb 100644 --- a/routers/routes/routes.go +++ b/routers/routes/routes.go @@ -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) diff --git a/templates/repo/issue/view_content/pull.tmpl b/templates/repo/issue/view_content/pull.tmpl index 87de9c508..9bd51b7c3 100644 --- a/templates/repo/issue/view_content/pull.tmpl +++ b/templates/repo/issue/view_content/pull.tmpl @@ -38,15 +38,100 @@ {{$.i18n.Tr "repo.pulls.can_auto_merge_desc"}} {{if .IsRepositoryWriter}} -
-
-
- {{.CsrfTokenHtml}} - + +
+
+ {{end}} + {{if $prUnit.PullRequestsConfig.AllowRebase}} + + {{end}} + {{if $prUnit.PullRequestsConfig.AllowSquash}} + + {{end}} +
+ - -
+ + + {{else}} +
+ + {{$.i18n.Tr "repo.pulls.no_merge_desc"}} +
+
+ + {{$.i18n.Tr "repo.pulls.no_merge_helper"}} +
+ {{end}} {{end}} {{else}}
diff --git a/templates/repo/settings/options.tmpl b/templates/repo/settings/options.tmpl index 41a91ea26..3bc1a209f 100644 --- a/templates/repo/settings/options.tmpl +++ b/templates/repo/settings/options.tmpl @@ -192,14 +192,41 @@ {{if .Repository.CanEnablePulls}}
- + {{$pullRequestEnabled := .Repository.UnitEnabled $.UnitTypePullRequests}} + {{$prUnit := .Repository.MustGetUnit $.UnitTypePullRequests}}
- +
+
+
+
+ + +
+
+
+
+ + +
+
+
+
+ + +
+
+
+
+ + +
+
+
{{end}}