From 38a27df111fbb00689c267edef09858f4345caab Mon Sep 17 00:00:00 2001 From: 6543 <6543@obermui.de> Date: Wed, 15 Jan 2020 17:27:28 +0100 Subject: [PATCH 01/35] add Divergence --- routers/repo/pull.go | 7 +++++++ 1 file changed, 7 insertions(+) diff --git a/routers/repo/pull.go b/routers/repo/pull.go index 901ab48856f3..1c64defb44a4 100644 --- a/routers/repo/pull.go +++ b/routers/repo/pull.go @@ -342,6 +342,13 @@ func PrepareViewPullInfo(ctx *context.Context, issue *models.Issue) *git.Compare setMergeTarget(ctx, pull) + divergence, divergenceError := repofiles.CountDivergingCommits(repo, pull.HeadBranch) + if divergenceError != nil { + ctx.ServerError("CountDivergingCommits", divergenceError) + return nil + } + ctx.Data["Divergence"] = divergence + if err := pull.LoadProtectedBranch(); err != nil { ctx.ServerError("GetLatestCommitStatus", err) return nil From 2c7fc319d432ccf0f67a3c283e7d5c119cbc8f1a Mon Sep 17 00:00:00 2001 From: 6543 <6543@obermui.de> Date: Wed, 15 Jan 2020 17:39:01 +0100 Subject: [PATCH 02/35] add Update Button --- options/locale/locale_en-US.ini | 1 + templates/repo/issue/view_content/pull.tmpl | 7 +++++++ web_src/less/_repository.less | 3 +++ 3 files changed, 11 insertions(+) diff --git a/options/locale/locale_en-US.ini b/options/locale/locale_en-US.ini index 60df796e07d0..2075f98d26a6 100644 --- a/options/locale/locale_en-US.ini +++ b/options/locale/locale_en-US.ini @@ -1082,6 +1082,7 @@ pulls.open_unmerged_pull_exists = `You cannot perform a reopen operation because pulls.status_checking = Some checks are pending pulls.status_checks_success = All checks were successful pulls.status_checks_error = Some checks failed +pulls.update_branch = Update Branch milestones.new = New Milestone milestones.open_tab = %d Open diff --git a/templates/repo/issue/view_content/pull.tmpl b/templates/repo/issue/view_content/pull.tmpl index 115ea2d119ec..7249c58c8d1f 100644 --- a/templates/repo/issue/view_content/pull.tmpl +++ b/templates/repo/issue/view_content/pull.tmpl @@ -269,6 +269,13 @@ + {{if gt .Divergence.Behind 0}} +
+ +
+ {{end}} {{else}}
diff --git a/web_src/less/_repository.less b/web_src/less/_repository.less index 27a0698f7b6c..ed87131e66bd 100644 --- a/web_src/less/_repository.less +++ b/web_src/less/_repository.less @@ -655,6 +655,9 @@ .icon-octicon { padding-left: 2px; } + .update-button { + float: right; + } } .review-item { From 26d686fe080ed2a9b7aa27534a916ebe731ac287 Mon Sep 17 00:00:00 2001 From: 6543 <6543@obermui.de> Date: Thu, 16 Jan 2020 01:51:03 +0100 Subject: [PATCH 03/35] first working version --- routers/repo/pull.go | 69 +++++++++++ routers/routes/routes.go | 1 + services/pull/update.go | 259 +++++++++++++++++++++++++++++++++++++++ web_src/js/index.js | 11 ++ 4 files changed, 340 insertions(+) create mode 100644 services/pull/update.go diff --git a/routers/repo/pull.go b/routers/repo/pull.go index 1c64defb44a4..eb7b7ed11ac1 100644 --- a/routers/repo/pull.go +++ b/routers/repo/pull.go @@ -594,6 +594,75 @@ func ViewPullFiles(ctx *context.Context) { ctx.HTML(200, tplPullFiles) } +// UpdatePullRequest merge master into PR +func UpdatePullRequest(ctx *context.Context) { + + issue := checkPullInfo(ctx) + if ctx.Written() { + return + } + if issue.IsClosed { + ctx.NotFound("MergePullRequest", nil) + return + } + + if issue.PullRequest.HasMerged { + ctx.NotFound("MergePullRequest", nil) + return + } + + if err := issue.PullRequest.LoadBaseRepo(); err != nil { + ctx.InternalServerError(err) + return + } + if err := issue.PullRequest.LoadHeadRepo(); err != nil { + ctx.InternalServerError(err) + return + } + + headRepoPerm, err := models.GetUserRepoPermission(issue.PullRequest.HeadRepo, ctx.User) + if err != nil { + ctx.ServerError("GetUserRepoPermission", err) + return + } + + allowedUpdate, err := pull_service.IsUserAllowedToUpdate(issue.PullRequest, headRepoPerm, ctx.User) + if err != nil { + ctx.ServerError("IsUserAllowedToMerge", err) + return + } + + // ToDo: add check if maintainers are allowed to change branch ... (need migration & co) + if !allowedUpdate { + ctx.Flash.Error(ctx.Tr("repo.pulls.update_not_allowed")) + ctx.Redirect(ctx.Repo.RepoLink + "/pulls/" + com.ToStr(issue.Index)) + return + } + + // default merge commit message + message := fmt.Sprintf("Merge branch '%s' into %s", issue.PullRequest.BaseBranch, issue.PullRequest.HeadBranch) + + if err = pull_service.Update(issue.PullRequest, ctx.User, message); err != nil { + sanitize := func(x string) string { + runes := []rune(x) + + if len(runes) > 512 { + x = "..." + string(runes[len(runes)-512:]) + } + + return strings.Replace(html.EscapeString(x), "\n", "
", -1) + } + if models.IsErrMergeConflicts(err) { + conflictError := err.(models.ErrMergeConflicts) + ctx.Flash.Error(ctx.Tr("repo.pulls.merge_conflict", sanitize(conflictError.StdErr), sanitize(conflictError.StdOut))) + ctx.Redirect(ctx.Repo.RepoLink + "/pulls/" + com.ToStr(issue.Index)) + return + } + ctx.ServerError("Update", err) + return + } +} + // MergePullRequest response for merging pull request func MergePullRequest(ctx *context.Context, form auth.MergePullRequestForm) { issue := checkPullInfo(ctx) diff --git a/routers/routes/routes.go b/routers/routes/routes.go index 58a2da82fcca..7e81f55de60f 100644 --- a/routers/routes/routes.go +++ b/routers/routes/routes.go @@ -855,6 +855,7 @@ func RegisterRoutes(m *macaron.Macaron) { m.Get(".patch", repo.DownloadPullPatch) m.Get("/commits", context.RepoRef(), repo.ViewPullCommits) m.Post("/merge", context.RepoMustNotBeArchived(), reqRepoPullsWriter, bindIgnErr(auth.MergePullRequestForm{}), repo.MergePullRequest) + m.Post("/update", repo.UpdatePullRequest) m.Post("/cleanup", context.RepoMustNotBeArchived(), context.RepoRef(), repo.CleanUpPullRequest) m.Group("/files", func() { m.Get("", context.RepoRef(), repo.SetEditorconfigIfExists, repo.SetDiffViewStyle, repo.SetWhitespaceBehavior, repo.ViewPullFiles) diff --git a/services/pull/update.go b/services/pull/update.go new file mode 100644 index 000000000000..7865123acb22 --- /dev/null +++ b/services/pull/update.go @@ -0,0 +1,259 @@ +// Copyright 2020 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 pull + +import ( + "fmt" + "io/ioutil" + "os" + "path/filepath" + "strings" + "time" + + "code.gitea.io/gitea/models" + "code.gitea.io/gitea/modules/git" + "code.gitea.io/gitea/modules/log" + "code.gitea.io/gitea/modules/setting" + + "github.com/mcuadros/go-version" +) + +// Update ToDo wip ... +func Update(pull *models.PullRequest, doer *models.User, message string) (err error) { + binVersion, err := git.BinVersion() + if err != nil { + log.Error("git.BinVersion: %v", err) + return fmt.Errorf("Unable to get git version: %v", err) + } + + //use merge functions but switch repo's and branches + pr := &models.PullRequest{ + HeadRepoID: pull.BaseRepoID, + BaseRepoID: pull.HeadRepoID, + HeadBranch: pull.BaseBranch, + BaseBranch: pull.HeadBranch, + } + + if err = pr.LoadHeadRepo(); err != nil { + log.Error("LoadHeadRepo: %v", err) + return fmt.Errorf("LoadHeadRepo: %v", err) + } else if err = pr.LoadBaseRepo(); err != nil { + log.Error("LoadBaseRepo: %v", err) + return fmt.Errorf("LoadBaseRepo: %v", err) + } + + // Clone base repo. + tmpBasePath, err := createTemporaryRepo(pr) + if err != nil { + log.Error("CreateTemporaryPath: %v", err) + return err + } + defer func() { + if err := models.RemoveTemporaryPath(tmpBasePath); err != nil { + log.Error("Merge: RemoveTemporaryPath: %s", err) + } + }() + + baseBranch := "base" + trackingBranch := "tracking" + + var outbuf, errbuf strings.Builder + + // Enable sparse-checkout + sparseCheckoutList, err := getDiffTree(tmpBasePath, baseBranch, trackingBranch) + if err != nil { + log.Error("getDiffTree(%s, %s, %s): %v", tmpBasePath, baseBranch, trackingBranch, err) + return fmt.Errorf("getDiffTree: %v", err) + } + + infoPath := filepath.Join(tmpBasePath, ".git", "info") + if err := os.MkdirAll(infoPath, 0700); err != nil { + log.Error("Unable to create .git/info in %s: %v", tmpBasePath, err) + return fmt.Errorf("Unable to create .git/info in tmpBasePath: %v", err) + } + + sparseCheckoutListPath := filepath.Join(infoPath, "sparse-checkout") + if err := ioutil.WriteFile(sparseCheckoutListPath, []byte(sparseCheckoutList), 0600); err != nil { + log.Error("Unable to write .git/info/sparse-checkout file in %s: %v", tmpBasePath, err) + return fmt.Errorf("Unable to write .git/info/sparse-checkout file in tmpBasePath: %v", err) + } + + var gitConfigCommand func() *git.Command + if version.Compare(binVersion, "1.8.0", ">=") { + gitConfigCommand = func() *git.Command { + return git.NewCommand("config", "--local") + } + } else { + gitConfigCommand = func() *git.Command { + return git.NewCommand("config") + } + } + + // Switch off LFS process (set required, clean and smudge here also) + if err := gitConfigCommand().AddArguments("filter.lfs.process", "").RunInDirPipeline(tmpBasePath, &outbuf, &errbuf); err != nil { + log.Error("git config [filter.lfs.process -> <> ]: %v\n%s\n%s", err, outbuf.String(), errbuf.String()) + return fmt.Errorf("git config [filter.lfs.process -> <> ]: %v\n%s\n%s", err, outbuf.String(), errbuf.String()) + } + outbuf.Reset() + errbuf.Reset() + + if err := gitConfigCommand().AddArguments("filter.lfs.required", "false").RunInDirPipeline(tmpBasePath, &outbuf, &errbuf); err != nil { + log.Error("git config [filter.lfs.required -> ]: %v\n%s\n%s", err, outbuf.String(), errbuf.String()) + return fmt.Errorf("git config [filter.lfs.required -> ]: %v\n%s\n%s", err, outbuf.String(), errbuf.String()) + } + outbuf.Reset() + errbuf.Reset() + + if err := gitConfigCommand().AddArguments("filter.lfs.clean", "").RunInDirPipeline(tmpBasePath, &outbuf, &errbuf); err != nil { + log.Error("git config [filter.lfs.clean -> <> ]: %v\n%s\n%s", err, outbuf.String(), errbuf.String()) + return fmt.Errorf("git config [filter.lfs.clean -> <> ]: %v\n%s\n%s", err, outbuf.String(), errbuf.String()) + } + outbuf.Reset() + errbuf.Reset() + + if err := gitConfigCommand().AddArguments("filter.lfs.smudge", "").RunInDirPipeline(tmpBasePath, &outbuf, &errbuf); err != nil { + log.Error("git config [filter.lfs.smudge -> <> ]: %v\n%s\n%s", err, outbuf.String(), errbuf.String()) + return fmt.Errorf("git config [filter.lfs.smudge -> <> ]: %v\n%s\n%s", err, outbuf.String(), errbuf.String()) + } + outbuf.Reset() + errbuf.Reset() + + if err := gitConfigCommand().AddArguments("core.sparseCheckout", "true").RunInDirPipeline(tmpBasePath, &outbuf, &errbuf); err != nil { + log.Error("git config [core.sparseCheckout -> true ]: %v\n%s\n%s", err, outbuf.String(), errbuf.String()) + return fmt.Errorf("git config [core.sparsecheckout -> true]: %v\n%s\n%s", err, outbuf.String(), errbuf.String()) + } + outbuf.Reset() + errbuf.Reset() + + // Read base branch index + if err := git.NewCommand("read-tree", "HEAD").RunInDirPipeline(tmpBasePath, &outbuf, &errbuf); err != nil { + log.Error("git read-tree HEAD: %v\n%s\n%s", err, outbuf.String(), errbuf.String()) + return fmt.Errorf("Unable to read base branch in to the index: %v\n%s\n%s", err, outbuf.String(), errbuf.String()) + } + outbuf.Reset() + errbuf.Reset() + + // Determine if we should sign + signArg := "" + if version.Compare(binVersion, "1.7.9", ">=") { + sign, keyID, _ := pr.SignMerge(doer, tmpBasePath, "HEAD", trackingBranch) + if sign { + signArg = "-S" + keyID + } else if version.Compare(binVersion, "2.0.0", ">=") { + signArg = "--no-gpg-sign" + } + } + + sig := doer.NewGitSig() + commitTimeStr := time.Now().Format(time.RFC3339) + + // Because this may call hooks we should pass in the environment + env := append(os.Environ(), + "GIT_AUTHOR_NAME="+sig.Name, + "GIT_AUTHOR_EMAIL="+sig.Email, + "GIT_AUTHOR_DATE="+commitTimeStr, + "GIT_COMMITTER_NAME="+sig.Name, + "GIT_COMMITTER_EMAIL="+sig.Email, + "GIT_COMMITTER_DATE="+commitTimeStr, + ) + + // Merge commits. + cmd := git.NewCommand("merge", "--no-ff", "--no-commit", trackingBranch) + if err := runMergeCommand(pr, models.MergeStyleMerge, cmd, tmpBasePath); err != nil { + log.Error("Unable to merge tracking into base: %v", err) + return err + } + + if err := commitAndSignNoAuthor(pr, message, signArg, tmpBasePath, env); err != nil { + log.Error("Unable to make final commit: %v", err) + return err + } + + // OK we should cache our current head and origin/headbranch + mergeHeadSHA, err := git.GetFullCommitID(tmpBasePath, "HEAD") + if err != nil { + return fmt.Errorf("Failed to get full commit id for HEAD: %v", err) + } + mergeBaseSHA, err := git.GetFullCommitID(tmpBasePath, "original_"+baseBranch) + if err != nil { + return fmt.Errorf("Failed to get full commit id for origin/%s: %v", pr.BaseBranch, err) + } + + // Now it's questionable about where this should go - either after or before the push + // I think in the interests of data safety - failures to push to the lfs should prevent + // the merge as you can always remerge. + if setting.LFS.StartServer { + if err := LFSPush(tmpBasePath, mergeHeadSHA, mergeBaseSHA, pr); err != nil { + return err + } + } + + var headUser *models.User + err = pr.HeadRepo.GetOwner() + if err != nil { + if !models.IsErrUserNotExist(err) { + log.Error("Can't find user: %d for head repository - %v", pr.HeadRepo.OwnerID, err) + return err + } + log.Error("Can't find user: %d for head repository - defaulting to doer: %s - %v", pr.HeadRepo.OwnerID, doer.Name, err) + headUser = doer + } else { + headUser = pr.HeadRepo.Owner + } + + env = models.FullPushingEnvironment( + headUser, + doer, + pr.BaseRepo, + pr.BaseRepo.Name, + pr.ID, + ) + + // Push back to upstream. + if err := git.NewCommand("push", "origin", baseBranch+":"+pr.BaseBranch).RunInDirTimeoutEnvPipeline(env, -1, tmpBasePath, &outbuf, &errbuf); err != nil { + if strings.Contains(errbuf.String(), "non-fast-forward") { + return models.ErrMergePushOutOfDate{ + Style: models.MergeStyleMerge, + StdOut: outbuf.String(), + StdErr: errbuf.String(), + Err: err, + } + } + return fmt.Errorf("git push: %s", errbuf.String()) + } + outbuf.Reset() + errbuf.Reset() + + //notification.NotifyPullRequestUpdated(pr, doer) + //trigger hooks and co .. + + return nil +} + +// IsUserAllowedToUpdate check if user is allowed to update PR with given permissions and branch protections +func IsUserAllowedToUpdate(pull *models.PullRequest, p models.Permission, user *models.User) (bool, error) { + if p.IsAdmin() { + return true, nil + } + if !p.CanWrite(models.UnitTypeCode) { + return false, nil + } + pr := &models.PullRequest{ + HeadRepoID: pull.BaseRepoID, + BaseRepoID: pull.HeadRepoID, + HeadBranch: pull.BaseBranch, + BaseBranch: pull.HeadBranch, + } + err := pr.LoadProtectedBranch() + if err != nil { + return false, err + } + + if pr.ProtectedBranch == nil || pr.ProtectedBranch.IsUserMergeWhitelisted(user.ID) { + return true, nil + } + + return false, nil +} diff --git a/web_src/js/index.js b/web_src/js/index.js index 7c3749c08b72..189592171e7d 100644 --- a/web_src/js/index.js +++ b/web_src/js/index.js @@ -1037,6 +1037,17 @@ function initRepository() { $('#comment-form').submit(); }); + // Pull Request update button + const $updatePRButton = $('#update-button'); + $updatePRButton.on('click', () => { + $.post(`${window.location}/update`, { + _csrf: csrf + }).success(() => { + // eslint-disable-next-line no-restricted-globals + location.reload(); + }); + }); + // Pull Request merge button const $mergeButton = $('.merge-button > button'); $mergeButton.on('click', function (e) { From d8522ac21815048152a5551e4847137e50d622e8 Mon Sep 17 00:00:00 2001 From: 6543 <6543@obermui.de> Date: Thu, 16 Jan 2020 02:11:03 +0100 Subject: [PATCH 04/35] re-use code --- services/pull/update.go | 17 +---------------- 1 file changed, 1 insertion(+), 16 deletions(-) diff --git a/services/pull/update.go b/services/pull/update.go index 7865123acb22..475187223cc9 100644 --- a/services/pull/update.go +++ b/services/pull/update.go @@ -234,26 +234,11 @@ func Update(pull *models.PullRequest, doer *models.User, message string) (err er // IsUserAllowedToUpdate check if user is allowed to update PR with given permissions and branch protections func IsUserAllowedToUpdate(pull *models.PullRequest, p models.Permission, user *models.User) (bool, error) { - if p.IsAdmin() { - return true, nil - } - if !p.CanWrite(models.UnitTypeCode) { - return false, nil - } pr := &models.PullRequest{ HeadRepoID: pull.BaseRepoID, BaseRepoID: pull.HeadRepoID, HeadBranch: pull.BaseBranch, BaseBranch: pull.HeadBranch, } - err := pr.LoadProtectedBranch() - if err != nil { - return false, err - } - - if pr.ProtectedBranch == nil || pr.ProtectedBranch.IsUserMergeWhitelisted(user.ID) { - return true, nil - } - - return false, nil + return IsUserAllowedToMerge(pr, p, user) } From efe6982a70f35698757c8b14421f9067a9aca95d Mon Sep 17 00:00:00 2001 From: 6543 <6543@obermui.de> Date: Thu, 16 Jan 2020 11:18:17 +0100 Subject: [PATCH 05/35] split raw merge commands and db-change functions (notify, cache, ...) --- services/pull/merge.go | 100 ++++++++++++++++++++++------------------- 1 file changed, 55 insertions(+), 45 deletions(-) diff --git a/services/pull/merge.go b/services/pull/merge.go index f6f0abe8362c..7bcdc7ac8485 100644 --- a/services/pull/merge.go +++ b/services/pull/merge.go @@ -33,11 +33,6 @@ import ( // Caller should check PR is ready to be merged (review and status checks) // FIXME: add repoWorkingPull make sure two merges does not happen at same time. func Merge(pr *models.PullRequest, doer *models.User, baseGitRepo *git.Repository, mergeStyle models.MergeStyle, message string) (err error) { - binVersion, err := git.BinVersion() - if err != nil { - log.Error("git.BinVersion: %v", err) - return fmt.Errorf("Unable to get git version: %v", err) - } if err = pr.GetHeadRepo(); err != nil { log.Error("GetHeadRepo: %v", err) @@ -63,6 +58,61 @@ func Merge(pr *models.PullRequest, doer *models.User, baseGitRepo *git.Repositor go AddTestPullRequestTask(doer, pr.BaseRepo.ID, pr.BaseBranch, false, "", "") }() + if err := rawMerge(pr, doer, mergeStyle, message); err != nil { + return err + } + + pr.MergedCommitID, err = baseGitRepo.GetBranchCommitID(pr.BaseBranch) + if err != nil { + return fmt.Errorf("GetBranchCommit: %v", err) + } + + pr.MergedUnix = timeutil.TimeStampNow() + pr.Merger = doer + pr.MergerID = doer.ID + + if err = pr.SetMerged(); err != nil { + log.Error("setMerged [%d]: %v", pr.ID, err) + } + + notification.NotifyMergePullRequest(pr, doer, baseGitRepo) + + // Reset cached commit count + cache.Remove(pr.Issue.Repo.GetCommitsCountCacheKey(pr.BaseBranch, true)) + + // Resolve cross references + refs, err := pr.ResolveCrossReferences() + if err != nil { + log.Error("ResolveCrossReferences: %v", err) + return nil + } + + for _, ref := range refs { + if err = ref.LoadIssue(); err != nil { + return err + } + if err = ref.Issue.LoadRepo(); err != nil { + return err + } + close := (ref.RefAction == references.XRefActionCloses) + if close != ref.Issue.IsClosed { + if err = issue_service.ChangeStatus(ref.Issue, doer, close); err != nil { + return err + } + } + } + + return nil +} + +// rawMerge perform the merge operation without changing any pull information in database +func rawMerge(pr *models.PullRequest, doer *models.User, mergeStyle models.MergeStyle, message string) (err error) { + binVersion, err := git.BinVersion() + if err != nil { + log.Error("git.BinVersion: %v", err) + return fmt.Errorf("Unable to get git version: %v", err) + } + // Clone base repo. tmpBasePath, err := createTemporaryRepo(pr) if err != nil { @@ -337,46 +387,6 @@ func Merge(pr *models.PullRequest, doer *models.User, baseGitRepo *git.Repositor outbuf.Reset() errbuf.Reset() - pr.MergedCommitID, err = baseGitRepo.GetBranchCommitID(pr.BaseBranch) - if err != nil { - return fmt.Errorf("GetBranchCommit: %v", err) - } - - pr.MergedUnix = timeutil.TimeStampNow() - pr.Merger = doer - pr.MergerID = doer.ID - - if err = pr.SetMerged(); err != nil { - log.Error("setMerged [%d]: %v", pr.ID, err) - } - - notification.NotifyMergePullRequest(pr, doer, baseGitRepo) - - // Reset cached commit count - cache.Remove(pr.Issue.Repo.GetCommitsCountCacheKey(pr.BaseBranch, true)) - - // Resolve cross references - refs, err := pr.ResolveCrossReferences() - if err != nil { - log.Error("ResolveCrossReferences: %v", err) - return nil - } - - for _, ref := range refs { - if err = ref.LoadIssue(); err != nil { - return err - } - if err = ref.Issue.LoadRepo(); err != nil { - return err - } - close := (ref.RefAction == references.XRefActionCloses) - if close != ref.Issue.IsClosed { - if err = issue_service.ChangeStatus(ref.Issue, doer, close); err != nil { - return err - } - } - } - return nil } From 328ecc3cefd8ffe39047dfeccb6ab7501ebf7a4c Mon Sep 17 00:00:00 2001 From: 6543 <6543@obermui.de> Date: Thu, 16 Jan 2020 11:19:28 +0100 Subject: [PATCH 06/35] use rawMerge (remove redundant code) --- services/pull/update.go | 195 +--------------------------------------- 1 file changed, 1 insertion(+), 194 deletions(-) diff --git a/services/pull/update.go b/services/pull/update.go index 475187223cc9..9b9d160e8957 100644 --- a/services/pull/update.go +++ b/services/pull/update.go @@ -6,28 +6,13 @@ package pull import ( "fmt" - "io/ioutil" - "os" - "path/filepath" - "strings" - "time" "code.gitea.io/gitea/models" - "code.gitea.io/gitea/modules/git" "code.gitea.io/gitea/modules/log" - "code.gitea.io/gitea/modules/setting" - - "github.com/mcuadros/go-version" ) // Update ToDo wip ... func Update(pull *models.PullRequest, doer *models.User, message string) (err error) { - binVersion, err := git.BinVersion() - if err != nil { - log.Error("git.BinVersion: %v", err) - return fmt.Errorf("Unable to get git version: %v", err) - } - //use merge functions but switch repo's and branches pr := &models.PullRequest{ HeadRepoID: pull.BaseRepoID, @@ -44,187 +29,9 @@ func Update(pull *models.PullRequest, doer *models.User, message string) (err er return fmt.Errorf("LoadBaseRepo: %v", err) } - // Clone base repo. - tmpBasePath, err := createTemporaryRepo(pr) - if err != nil { - log.Error("CreateTemporaryPath: %v", err) + if err := rawMerge(pr, doer, models.MergeStyleMerge, message); err != nil { return err } - defer func() { - if err := models.RemoveTemporaryPath(tmpBasePath); err != nil { - log.Error("Merge: RemoveTemporaryPath: %s", err) - } - }() - - baseBranch := "base" - trackingBranch := "tracking" - - var outbuf, errbuf strings.Builder - - // Enable sparse-checkout - sparseCheckoutList, err := getDiffTree(tmpBasePath, baseBranch, trackingBranch) - if err != nil { - log.Error("getDiffTree(%s, %s, %s): %v", tmpBasePath, baseBranch, trackingBranch, err) - return fmt.Errorf("getDiffTree: %v", err) - } - - infoPath := filepath.Join(tmpBasePath, ".git", "info") - if err := os.MkdirAll(infoPath, 0700); err != nil { - log.Error("Unable to create .git/info in %s: %v", tmpBasePath, err) - return fmt.Errorf("Unable to create .git/info in tmpBasePath: %v", err) - } - - sparseCheckoutListPath := filepath.Join(infoPath, "sparse-checkout") - if err := ioutil.WriteFile(sparseCheckoutListPath, []byte(sparseCheckoutList), 0600); err != nil { - log.Error("Unable to write .git/info/sparse-checkout file in %s: %v", tmpBasePath, err) - return fmt.Errorf("Unable to write .git/info/sparse-checkout file in tmpBasePath: %v", err) - } - - var gitConfigCommand func() *git.Command - if version.Compare(binVersion, "1.8.0", ">=") { - gitConfigCommand = func() *git.Command { - return git.NewCommand("config", "--local") - } - } else { - gitConfigCommand = func() *git.Command { - return git.NewCommand("config") - } - } - - // Switch off LFS process (set required, clean and smudge here also) - if err := gitConfigCommand().AddArguments("filter.lfs.process", "").RunInDirPipeline(tmpBasePath, &outbuf, &errbuf); err != nil { - log.Error("git config [filter.lfs.process -> <> ]: %v\n%s\n%s", err, outbuf.String(), errbuf.String()) - return fmt.Errorf("git config [filter.lfs.process -> <> ]: %v\n%s\n%s", err, outbuf.String(), errbuf.String()) - } - outbuf.Reset() - errbuf.Reset() - - if err := gitConfigCommand().AddArguments("filter.lfs.required", "false").RunInDirPipeline(tmpBasePath, &outbuf, &errbuf); err != nil { - log.Error("git config [filter.lfs.required -> ]: %v\n%s\n%s", err, outbuf.String(), errbuf.String()) - return fmt.Errorf("git config [filter.lfs.required -> ]: %v\n%s\n%s", err, outbuf.String(), errbuf.String()) - } - outbuf.Reset() - errbuf.Reset() - - if err := gitConfigCommand().AddArguments("filter.lfs.clean", "").RunInDirPipeline(tmpBasePath, &outbuf, &errbuf); err != nil { - log.Error("git config [filter.lfs.clean -> <> ]: %v\n%s\n%s", err, outbuf.String(), errbuf.String()) - return fmt.Errorf("git config [filter.lfs.clean -> <> ]: %v\n%s\n%s", err, outbuf.String(), errbuf.String()) - } - outbuf.Reset() - errbuf.Reset() - - if err := gitConfigCommand().AddArguments("filter.lfs.smudge", "").RunInDirPipeline(tmpBasePath, &outbuf, &errbuf); err != nil { - log.Error("git config [filter.lfs.smudge -> <> ]: %v\n%s\n%s", err, outbuf.String(), errbuf.String()) - return fmt.Errorf("git config [filter.lfs.smudge -> <> ]: %v\n%s\n%s", err, outbuf.String(), errbuf.String()) - } - outbuf.Reset() - errbuf.Reset() - - if err := gitConfigCommand().AddArguments("core.sparseCheckout", "true").RunInDirPipeline(tmpBasePath, &outbuf, &errbuf); err != nil { - log.Error("git config [core.sparseCheckout -> true ]: %v\n%s\n%s", err, outbuf.String(), errbuf.String()) - return fmt.Errorf("git config [core.sparsecheckout -> true]: %v\n%s\n%s", err, outbuf.String(), errbuf.String()) - } - outbuf.Reset() - errbuf.Reset() - - // Read base branch index - if err := git.NewCommand("read-tree", "HEAD").RunInDirPipeline(tmpBasePath, &outbuf, &errbuf); err != nil { - log.Error("git read-tree HEAD: %v\n%s\n%s", err, outbuf.String(), errbuf.String()) - return fmt.Errorf("Unable to read base branch in to the index: %v\n%s\n%s", err, outbuf.String(), errbuf.String()) - } - outbuf.Reset() - errbuf.Reset() - - // Determine if we should sign - signArg := "" - if version.Compare(binVersion, "1.7.9", ">=") { - sign, keyID, _ := pr.SignMerge(doer, tmpBasePath, "HEAD", trackingBranch) - if sign { - signArg = "-S" + keyID - } else if version.Compare(binVersion, "2.0.0", ">=") { - signArg = "--no-gpg-sign" - } - } - - sig := doer.NewGitSig() - commitTimeStr := time.Now().Format(time.RFC3339) - - // Because this may call hooks we should pass in the environment - env := append(os.Environ(), - "GIT_AUTHOR_NAME="+sig.Name, - "GIT_AUTHOR_EMAIL="+sig.Email, - "GIT_AUTHOR_DATE="+commitTimeStr, - "GIT_COMMITTER_NAME="+sig.Name, - "GIT_COMMITTER_EMAIL="+sig.Email, - "GIT_COMMITTER_DATE="+commitTimeStr, - ) - - // Merge commits. - cmd := git.NewCommand("merge", "--no-ff", "--no-commit", trackingBranch) - if err := runMergeCommand(pr, models.MergeStyleMerge, cmd, tmpBasePath); err != nil { - log.Error("Unable to merge tracking into base: %v", err) - return err - } - - if err := commitAndSignNoAuthor(pr, message, signArg, tmpBasePath, env); err != nil { - log.Error("Unable to make final commit: %v", err) - return err - } - - // OK we should cache our current head and origin/headbranch - mergeHeadSHA, err := git.GetFullCommitID(tmpBasePath, "HEAD") - if err != nil { - return fmt.Errorf("Failed to get full commit id for HEAD: %v", err) - } - mergeBaseSHA, err := git.GetFullCommitID(tmpBasePath, "original_"+baseBranch) - if err != nil { - return fmt.Errorf("Failed to get full commit id for origin/%s: %v", pr.BaseBranch, err) - } - - // Now it's questionable about where this should go - either after or before the push - // I think in the interests of data safety - failures to push to the lfs should prevent - // the merge as you can always remerge. - if setting.LFS.StartServer { - if err := LFSPush(tmpBasePath, mergeHeadSHA, mergeBaseSHA, pr); err != nil { - return err - } - } - - var headUser *models.User - err = pr.HeadRepo.GetOwner() - if err != nil { - if !models.IsErrUserNotExist(err) { - log.Error("Can't find user: %d for head repository - %v", pr.HeadRepo.OwnerID, err) - return err - } - log.Error("Can't find user: %d for head repository - defaulting to doer: %s - %v", pr.HeadRepo.OwnerID, doer.Name, err) - headUser = doer - } else { - headUser = pr.HeadRepo.Owner - } - - env = models.FullPushingEnvironment( - headUser, - doer, - pr.BaseRepo, - pr.BaseRepo.Name, - pr.ID, - ) - - // Push back to upstream. - if err := git.NewCommand("push", "origin", baseBranch+":"+pr.BaseBranch).RunInDirTimeoutEnvPipeline(env, -1, tmpBasePath, &outbuf, &errbuf); err != nil { - if strings.Contains(errbuf.String(), "non-fast-forward") { - return models.ErrMergePushOutOfDate{ - Style: models.MergeStyleMerge, - StdOut: outbuf.String(), - StdErr: errbuf.String(), - Err: err, - } - } - return fmt.Errorf("git push: %s", errbuf.String()) - } - outbuf.Reset() - errbuf.Reset() //notification.NotifyPullRequestUpdated(pr, doer) //trigger hooks and co .. From 9249d47ba456fc8a2ca691d061c69b44942ae981 Mon Sep 17 00:00:00 2001 From: 6543 <6543@obermui.de> Date: Thu, 16 Jan 2020 13:37:13 +0100 Subject: [PATCH 07/35] own function to get Diverging of PRs --- routers/repo/pull.go | 2 +- services/pull/update.go | 81 +++++++++++++++++++++++++++++++++++++++++ 2 files changed, 82 insertions(+), 1 deletion(-) diff --git a/routers/repo/pull.go b/routers/repo/pull.go index eb7b7ed11ac1..7db65e322894 100644 --- a/routers/repo/pull.go +++ b/routers/repo/pull.go @@ -342,7 +342,7 @@ func PrepareViewPullInfo(ctx *context.Context, issue *models.Issue) *git.Compare setMergeTarget(ctx, pull) - divergence, divergenceError := repofiles.CountDivergingCommits(repo, pull.HeadBranch) + divergence, divergenceError := pull_service.GetDiverging(pull) if divergenceError != nil { ctx.ServerError("CountDivergingCommits", divergenceError) return nil diff --git a/services/pull/update.go b/services/pull/update.go index 9b9d160e8957..48c499e34c4c 100644 --- a/services/pull/update.go +++ b/services/pull/update.go @@ -6,8 +6,11 @@ package pull import ( "fmt" + "strconv" + "strings" "code.gitea.io/gitea/models" + "code.gitea.io/gitea/modules/git" "code.gitea.io/gitea/modules/log" ) @@ -29,6 +32,17 @@ func Update(pull *models.PullRequest, doer *models.User, message string) (err er return fmt.Errorf("LoadBaseRepo: %v", err) } + diffCount, err := GetDiverging(pull) + if err != nil { + return err + } else if diffCount.Behind == 0 { + return fmt.Errorf("HeadBranch of PR %d is up to date", pull.Index) + } + + defer func() { + go AddTestPullRequestTask(doer, pr.HeadRepo.ID, pr.HeadBranch, false, "", "") + }() + if err := rawMerge(pr, doer, models.MergeStyleMerge, message); err != nil { return err } @@ -49,3 +63,70 @@ func IsUserAllowedToUpdate(pull *models.PullRequest, p models.Permission, user * } return IsUserAllowedToMerge(pr, p, user) } + +// GetDiverging determines how many commits a PR is ahead or behind the PR base branch +func GetDiverging(pr *models.PullRequest) (*git.DivergeObject, error) { + log.Trace("PushToBaseRepo[%d]: pushing commits to base repo '%s'", pr.BaseRepoID, pr.GetGitRefName()) + + if pr.BaseRepo == nil { + if err := pr.LoadBaseRepo(); err != nil { + return nil, err + } + } + if pr.HeadRepo == nil { + if err := pr.LoadHeadRepo(); err != nil { + return nil, err + } + } + + headRepoPath := pr.HeadRepo.RepoPath() + headGitRepo, err := git.OpenRepository(headRepoPath) + if err != nil { + return nil, fmt.Errorf("OpenRepository: %v", err) + } + defer headGitRepo.Close() + + if pr.BaseRepoID == pr.HeadRepoID { + diff, err := git.GetDivergingCommits(pr.HeadRepo.RepoPath(), pr.BaseBranch, pr.HeadBranch) + return &diff, err + } + + tmpRemoteName := fmt.Sprintf("tmp-pull-%d-base", pr.ID) + if err = headGitRepo.AddRemote(tmpRemoteName, pr.BaseRepo.RepoPath(), true); err != nil { + return nil, fmt.Errorf("headGitRepo.AddRemote: %v", err) + } + // Make sure to remove the remote even if the push fails + defer func() { + if err := headGitRepo.RemoveRemote(tmpRemoteName); err != nil { + log.Error("CountDiverging: RemoveRemote: %s", err) + } + }() + + // $(git rev-list --count tmp-pull-1-base/master..feature) commits ahead of master + ahead, errorAhead := checkDivergence(headRepoPath, fmt.Sprintf("%s/%s", tmpRemoteName, pr.BaseBranch), pr.HeadBranch) + if errorAhead != nil { + return &git.DivergeObject{}, errorAhead + } + + // $(git rev-list --count feature..tmp-pull-1-base/master) commits behind master + behind, errorBehind := checkDivergence(headRepoPath, pr.HeadBranch, fmt.Sprintf("%s/%s", tmpRemoteName, pr.BaseBranch)) + if errorBehind != nil { + return &git.DivergeObject{}, errorBehind + } + + return &git.DivergeObject{ahead, behind}, nil +} + +func checkDivergence(repoPath string, baseBranch string, targetBranch string) (int, error) { + branches := fmt.Sprintf("%s..%s", baseBranch, targetBranch) + cmd := git.NewCommand("rev-list", "--count", branches) + stdout, err := cmd.RunInDir(repoPath) + if err != nil { + return -1, err + } + outInteger, errInteger := strconv.Atoi(strings.Trim(stdout, "\n")) + if errInteger != nil { + return -1, errInteger + } + return outInteger, nil +} From 454ee44ecab38f61974c2fc193839d33407152d5 Mon Sep 17 00:00:00 2001 From: 6543 <6543@obermui.de> Date: Thu, 16 Jan 2020 13:40:35 +0100 Subject: [PATCH 08/35] use FlashError --- routers/repo/pull.go | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/routers/repo/pull.go b/routers/repo/pull.go index 7db65e322894..139c62671b3f 100644 --- a/routers/repo/pull.go +++ b/routers/repo/pull.go @@ -658,8 +658,8 @@ func UpdatePullRequest(ctx *context.Context) { ctx.Redirect(ctx.Repo.RepoLink + "/pulls/" + com.ToStr(issue.Index)) return } - ctx.ServerError("Update", err) - return + ctx.Flash.Error(err.Error()) + ctx.Redirect(ctx.Repo.RepoLink + "/pulls/" + com.ToStr(issue.Index)) } } From 5d5d919c0f3e078509b5791114bce7660b0baf50 Mon Sep 17 00:00:00 2001 From: 6543 <6543@obermui.de> Date: Thu, 16 Jan 2020 14:17:33 +0100 Subject: [PATCH 09/35] correct Error Msg --- routers/repo/pull.go | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/routers/repo/pull.go b/routers/repo/pull.go index 139c62671b3f..e2a29b2e32a1 100644 --- a/routers/repo/pull.go +++ b/routers/repo/pull.go @@ -344,13 +344,13 @@ func PrepareViewPullInfo(ctx *context.Context, issue *models.Issue) *git.Compare divergence, divergenceError := pull_service.GetDiverging(pull) if divergenceError != nil { - ctx.ServerError("CountDivergingCommits", divergenceError) + ctx.ServerError("GetDiverging", divergenceError) return nil } ctx.Data["Divergence"] = divergence if err := pull.LoadProtectedBranch(); err != nil { - ctx.ServerError("GetLatestCommitStatus", err) + ctx.ServerError("LoadProtectedBranch", err) return nil } ctx.Data["EnableStatusCheck"] = pull.ProtectedBranch != nil && pull.ProtectedBranch.EnableStatusCheck From 3c6157b360389820be7684e559e12c955c3da7e0 Mon Sep 17 00:00:00 2001 From: 6543 <6543@obermui.de> Date: Thu, 16 Jan 2020 15:28:50 +0100 Subject: [PATCH 10/35] hook is triggerd ... so remove comment --- services/pull/update.go | 3 --- 1 file changed, 3 deletions(-) diff --git a/services/pull/update.go b/services/pull/update.go index 48c499e34c4c..07bb5e4b28aa 100644 --- a/services/pull/update.go +++ b/services/pull/update.go @@ -47,9 +47,6 @@ func Update(pull *models.PullRequest, doer *models.User, message string) (err er return err } - //notification.NotifyPullRequestUpdated(pr, doer) - //trigger hooks and co .. - return nil } From 88fa4c5430b8e0686efd0c20587c769d8760f6c6 Mon Sep 17 00:00:00 2001 From: 6543 <6543@obermui.de> Date: Thu, 16 Jan 2020 15:42:34 +0100 Subject: [PATCH 11/35] add "branch2" to "user2/repo1" because it unit-test "TestPullView_ReviewerMissed" use it but dont exist jet :/ --- .../5c/050d3b6d2db231ab1f64e324f1b6b9a0b181c2 | Bin 0 -> 833 bytes .../7c/4df115542e05c700f297519e906fd63c9c9804 | Bin 0 -> 54 bytes .../a7/57c0ea621e63d0fd6fc353a175fdc7199e5d1d | Bin 0 -> 61 bytes .../user2/repo1.git/refs/heads/branch2 | 1 + .../user2/repo1.git/refs/pull/2/head | 1 + 5 files changed, 2 insertions(+) create mode 100644 integrations/gitea-repositories-meta/user2/repo1.git/objects/5c/050d3b6d2db231ab1f64e324f1b6b9a0b181c2 create mode 100644 integrations/gitea-repositories-meta/user2/repo1.git/objects/7c/4df115542e05c700f297519e906fd63c9c9804 create mode 100644 integrations/gitea-repositories-meta/user2/repo1.git/objects/a7/57c0ea621e63d0fd6fc353a175fdc7199e5d1d create mode 100644 integrations/gitea-repositories-meta/user2/repo1.git/refs/heads/branch2 create mode 100644 integrations/gitea-repositories-meta/user2/repo1.git/refs/pull/2/head diff --git a/integrations/gitea-repositories-meta/user2/repo1.git/objects/5c/050d3b6d2db231ab1f64e324f1b6b9a0b181c2 b/integrations/gitea-repositories-meta/user2/repo1.git/objects/5c/050d3b6d2db231ab1f64e324f1b6b9a0b181c2 new file mode 100644 index 0000000000000000000000000000000000000000..c0cb626359e600503128d5c65213dd0fcb1c1fcf GIT binary patch literal 833 zcmV-H1HSxt0gY41vf@Sn%h_MicPepvZFg1PRJ?*0zzZ16&2BFk?+XU}^?5V7<}fq6jgcr3p#+l!~A8y&J#%JO}>%$^UdoHa5@luQdAs z7y)5M`c`?cfeeHc`BiMrem_z4#Z(sH&!15At$6_M)&+sNJ;#r+$4d`gIRSeT~dGqh!M1d;D_H44<0IfA% z{pwSywwLMNcl7Af!XB1~Q@ztT>FQkfb~#`%HXP}sux3o$9vvyb`IDfe%=#(j`W58j z^>m%um?fTXsMdzH(EILi501YC%=k&9lZM{vO54?VOd?}84-~LA1hK6eEf1YUN70zy z!{}+)DHvM0q=ZR2)JCp6bd00u*x_}(tDVN~diC(UI6IXBQU~X7yK6M2*Dr-#mgKeA zd(I%;>Kc_j!ciW3E$n))DeKu9%)D7WTgB!&L{(I@6!7fevzD(+>8m?^8qyML{Vj_M z^4SSt%1xJ*#*@Um!(s+Of@kG%uULZNXim~4j1mgyp-pZ3pI&r&~3 KjKQ-*P#yphauiYk literal 0 HcmV?d00001 diff --git a/integrations/gitea-repositories-meta/user2/repo1.git/objects/a7/57c0ea621e63d0fd6fc353a175fdc7199e5d1d b/integrations/gitea-repositories-meta/user2/repo1.git/objects/a7/57c0ea621e63d0fd6fc353a175fdc7199e5d1d new file mode 100644 index 0000000000000000000000000000000000000000..c3111a08b847838e2f8aac8f97e9ab2dad37bad9 GIT binary patch literal 61 zcmV-D0K)%x0ZYosPf{>7Wl&ZqN-fAY=A|ekXC&sO Tr-DV3iW2jZGmN+Zc=HrE6jK^Y literal 0 HcmV?d00001 diff --git a/integrations/gitea-repositories-meta/user2/repo1.git/refs/heads/branch2 b/integrations/gitea-repositories-meta/user2/repo1.git/refs/heads/branch2 new file mode 100644 index 000000000000..38c6ece20765 --- /dev/null +++ b/integrations/gitea-repositories-meta/user2/repo1.git/refs/heads/branch2 @@ -0,0 +1 @@ +5c050d3b6d2db231ab1f64e324f1b6b9a0b181c2 diff --git a/integrations/gitea-repositories-meta/user2/repo1.git/refs/pull/2/head b/integrations/gitea-repositories-meta/user2/repo1.git/refs/pull/2/head new file mode 100644 index 000000000000..98593d653703 --- /dev/null +++ b/integrations/gitea-repositories-meta/user2/repo1.git/refs/pull/2/head @@ -0,0 +1 @@ +4a357436d925b5c974181ff12a994538ddc5a269 From 77767380e6a990be78dd8e1ed7d4e413d73a7574 Mon Sep 17 00:00:00 2001 From: 6543 <6543@obermui.de> Date: Thu, 16 Jan 2020 15:53:31 +0100 Subject: [PATCH 12/35] move GetPerm to IsUserAllowedToUpdate --- routers/repo/pull.go | 8 +------- services/pull/update.go | 9 +++++++-- 2 files changed, 8 insertions(+), 9 deletions(-) diff --git a/routers/repo/pull.go b/routers/repo/pull.go index e2a29b2e32a1..2c85d2887be4 100644 --- a/routers/repo/pull.go +++ b/routers/repo/pull.go @@ -620,13 +620,7 @@ func UpdatePullRequest(ctx *context.Context) { return } - headRepoPerm, err := models.GetUserRepoPermission(issue.PullRequest.HeadRepo, ctx.User) - if err != nil { - ctx.ServerError("GetUserRepoPermission", err) - return - } - - allowedUpdate, err := pull_service.IsUserAllowedToUpdate(issue.PullRequest, headRepoPerm, ctx.User) + allowedUpdate, err := pull_service.IsUserAllowedToUpdate(issue.PullRequest, ctx.User) if err != nil { ctx.ServerError("IsUserAllowedToMerge", err) return diff --git a/services/pull/update.go b/services/pull/update.go index 07bb5e4b28aa..ea6b4c1ac565 100644 --- a/services/pull/update.go +++ b/services/pull/update.go @@ -51,14 +51,19 @@ func Update(pull *models.PullRequest, doer *models.User, message string) (err er } // IsUserAllowedToUpdate check if user is allowed to update PR with given permissions and branch protections -func IsUserAllowedToUpdate(pull *models.PullRequest, p models.Permission, user *models.User) (bool, error) { +func IsUserAllowedToUpdate(pull *models.PullRequest, user *models.User) (bool, error) { + headRepoPerm, err := models.GetUserRepoPermission(pull.HeadRepo, user) + if err != nil { + return false, err + } + pr := &models.PullRequest{ HeadRepoID: pull.BaseRepoID, BaseRepoID: pull.HeadRepoID, HeadBranch: pull.BaseBranch, BaseBranch: pull.HeadBranch, } - return IsUserAllowedToMerge(pr, p, user) + return IsUserAllowedToMerge(pr, headRepoPerm, user) } // GetDiverging determines how many commits a PR is ahead or behind the PR base branch From e3adbd274143a97dc4a268a7e6ff0e0ff4e7fd8f Mon Sep 17 00:00:00 2001 From: 6543 <6543@obermui.de> Date: Thu, 16 Jan 2020 16:30:25 +0100 Subject: [PATCH 13/35] add Flash Success MSG --- options/locale/locale_en-US.ini | 1 + routers/repo/pull.go | 2 ++ 2 files changed, 3 insertions(+) diff --git a/options/locale/locale_en-US.ini b/options/locale/locale_en-US.ini index 2075f98d26a6..261a4996bfb3 100644 --- a/options/locale/locale_en-US.ini +++ b/options/locale/locale_en-US.ini @@ -1083,6 +1083,7 @@ pulls.status_checking = Some checks are pending pulls.status_checks_success = All checks were successful pulls.status_checks_error = Some checks failed pulls.update_branch = Update Branch +pulls.update_branch_success = Update Branch was successful milestones.new = New Milestone milestones.open_tab = %d Open diff --git a/routers/repo/pull.go b/routers/repo/pull.go index 2c85d2887be4..a89ce79873d5 100644 --- a/routers/repo/pull.go +++ b/routers/repo/pull.go @@ -655,6 +655,8 @@ func UpdatePullRequest(ctx *context.Context) { ctx.Flash.Error(err.Error()) ctx.Redirect(ctx.Repo.RepoLink + "/pulls/" + com.ToStr(issue.Index)) } + ctx.Flash.Success(ctx.Tr("repo.pulls.update_branch_success")) + ctx.Redirect(ctx.Repo.RepoLink + "/pulls/" + com.ToStr(issue.Index)) } // MergePullRequest response for merging pull request From 05c0c1b71f79cab4b611b3f6061460755dd89dba Mon Sep 17 00:00:00 2001 From: 6543 <6543@obermui.de> Date: Thu, 16 Jan 2020 16:47:30 +0100 Subject: [PATCH 14/35] imprufe code - remove useless js chage --- routers/routes/routes.go | 2 +- templates/repo/issue/view_content/pull.tmpl | 11 +++++++---- web_src/js/index.js | 11 ----------- 3 files changed, 8 insertions(+), 16 deletions(-) diff --git a/routers/routes/routes.go b/routers/routes/routes.go index 7e81f55de60f..057fd7328b74 100644 --- a/routers/routes/routes.go +++ b/routers/routes/routes.go @@ -855,7 +855,7 @@ func RegisterRoutes(m *macaron.Macaron) { m.Get(".patch", repo.DownloadPullPatch) m.Get("/commits", context.RepoRef(), repo.ViewPullCommits) m.Post("/merge", context.RepoMustNotBeArchived(), reqRepoPullsWriter, bindIgnErr(auth.MergePullRequestForm{}), repo.MergePullRequest) - m.Post("/update", repo.UpdatePullRequest) + m.Post("/update", ignSignInAndCsrf, repo.UpdatePullRequest) m.Post("/cleanup", context.RepoMustNotBeArchived(), context.RepoRef(), repo.CleanUpPullRequest) m.Group("/files", func() { m.Get("", context.RepoRef(), repo.SetEditorconfigIfExists, repo.SetDiffViewStyle, repo.SetWhitespaceBehavior, repo.ViewPullFiles) diff --git a/templates/repo/issue/view_content/pull.tmpl b/templates/repo/issue/view_content/pull.tmpl index 7249c58c8d1f..4a416c0860e4 100644 --- a/templates/repo/issue/view_content/pull.tmpl +++ b/templates/repo/issue/view_content/pull.tmpl @@ -269,11 +269,14 @@
- {{if gt .Divergence.Behind 0}} + {{if and .Divergence (gt .Divergence.Behind 0)}}
- +
+ {{.CsrfTokenHtml}} + +
{{end}} {{else}} diff --git a/web_src/js/index.js b/web_src/js/index.js index 189592171e7d..7c3749c08b72 100644 --- a/web_src/js/index.js +++ b/web_src/js/index.js @@ -1037,17 +1037,6 @@ function initRepository() { $('#comment-form').submit(); }); - // Pull Request update button - const $updatePRButton = $('#update-button'); - $updatePRButton.on('click', () => { - $.post(`${window.location}/update`, { - _csrf: csrf - }).success(() => { - // eslint-disable-next-line no-restricted-globals - location.reload(); - }); - }); - // Pull Request merge button const $mergeButton = $('.merge-button > button'); $mergeButton.on('click', function (e) { From f7d924a704999772957c6876752ec4465893f5fa Mon Sep 17 00:00:00 2001 From: 6543 <6543@obermui.de> Date: Thu, 16 Jan 2020 17:11:39 +0100 Subject: [PATCH 15/35] fix-lint --- services/pull/update.go | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/services/pull/update.go b/services/pull/update.go index ea6b4c1ac565..72af2fa45bf4 100644 --- a/services/pull/update.go +++ b/services/pull/update.go @@ -116,7 +116,8 @@ func GetDiverging(pr *models.PullRequest) (*git.DivergeObject, error) { return &git.DivergeObject{}, errorBehind } - return &git.DivergeObject{ahead, behind}, nil + diffCount := git.DivergeObject{ahead, behind} + return &diffCount, nil } func checkDivergence(repoPath string, baseBranch string, targetBranch string) (int, error) { From e2f96d945d318770234091fd3b5e3f9e40bd0f51 Mon Sep 17 00:00:00 2001 From: 6543 <6543@obermui.de> Date: Thu, 16 Jan 2020 19:13:58 +0100 Subject: [PATCH 16/35] TEST: add PullRequest ID:5 Repo: user2/repo1 Base: branch1 Head: pr-to-update --- integrations/api_issue_test.go | 6 +++--- .../94/922e1295c678267de1193b7b84ad8a086c27f9 | Bin 0 -> 54 bytes .../98/5f0301dba5e7b34be866819cd15ad3d8f508ee | Bin 0 -> 842 bytes .../a6/9277c81e90b98a7c0ab25b042a6e296da8eb9a | Bin 0 -> 76 bytes .../user2/repo1.git/refs/heads/branch2 | 2 +- .../user2/repo1.git/refs/heads/pr-to-update | 1 + integrations/repo_activity_test.go | 4 ++-- models/fixtures/issue.yml | 12 ++++++++++++ models/fixtures/pull_request.yml | 15 ++++++++++++++- models/fixtures/repository.yml | 2 +- models/issue_test.go | 8 ++++---- models/issue_user_test.go | 2 +- models/pull_test.go | 18 ++++++++++-------- 13 files changed, 49 insertions(+), 21 deletions(-) create mode 100644 integrations/gitea-repositories-meta/user2/repo1.git/objects/94/922e1295c678267de1193b7b84ad8a086c27f9 create mode 100644 integrations/gitea-repositories-meta/user2/repo1.git/objects/98/5f0301dba5e7b34be866819cd15ad3d8f508ee create mode 100644 integrations/gitea-repositories-meta/user2/repo1.git/objects/a6/9277c81e90b98a7c0ab25b042a6e296da8eb9a create mode 100644 integrations/gitea-repositories-meta/user2/repo1.git/refs/heads/pr-to-update diff --git a/integrations/api_issue_test.go b/integrations/api_issue_test.go index ce1c4b7d33fc..906dbb2dc7ed 100644 --- a/integrations/api_issue_test.go +++ b/integrations/api_issue_test.go @@ -134,7 +134,7 @@ func TestAPISearchIssue(t *testing.T) { var apiIssues []*api.Issue DecodeJSON(t, resp, &apiIssues) - assert.Len(t, apiIssues, 8) + assert.Len(t, apiIssues, 9) query := url.Values{} query.Add("token", token) @@ -142,7 +142,7 @@ func TestAPISearchIssue(t *testing.T) { req = NewRequest(t, "GET", link.String()) resp = session.MakeRequest(t, req, http.StatusOK) DecodeJSON(t, resp, &apiIssues) - assert.Len(t, apiIssues, 8) + assert.Len(t, apiIssues, 9) query.Add("state", "closed") link.RawQuery = query.Encode() @@ -163,5 +163,5 @@ func TestAPISearchIssue(t *testing.T) { req = NewRequest(t, "GET", link.String()) resp = session.MakeRequest(t, req, http.StatusOK) DecodeJSON(t, resp, &apiIssues) - assert.Len(t, apiIssues, 0) + assert.Len(t, apiIssues, 1) } diff --git a/integrations/gitea-repositories-meta/user2/repo1.git/objects/94/922e1295c678267de1193b7b84ad8a086c27f9 b/integrations/gitea-repositories-meta/user2/repo1.git/objects/94/922e1295c678267de1193b7b84ad8a086c27f9 new file mode 100644 index 0000000000000000000000000000000000000000..60692df6ec48948b93f23166b72d863bb7a09950 GIT binary patch literal 54 zcmV-60LlM&0V^p=O;s>9XD~D{Ff%bx2y%6F@paY9O<`Czsr-c8gq>YAT$`d)EZH(=IVQ`QO5`!e@)eVdxst)0k(q*}vSq%L5r_iMfj@up-z3Llzchc8 z_%FZ+lENqgloUWi212U%Rcyxp-%&s7sj0#5KXKI0rUx$P3kc1#hoWns|I#TyfyTG= zBSJ?Nq2<)*I{yf}DQ;7hPG3kh6;eDQ91ejy=qJ?ibw3rpp{0zcc_?SCjsiu`Fj*+H zUp}(cK)vrn6jqA97nyX_ks1vT(Fv9CB83d*OggAf^;8u0O@pUF=kZ8^UX3P`4awy} zawkUIw!@g<{JbmORZLCQv^v(%iaPSjA!ccHR4T6kturyiLcaRrQ`k z>bRcvX~jn6@;nZ@Yqozm{ijDbA!=<|;Jf+trek&zQ~b!+Wp{rhka!)fEjnkDX}>n; zt4Ce_=6n)wnjjfLyV*}uYr-dtxtU10*1B6RPlj_PH2u7NQ((}irliv@Q(vj!h&$2( zq=tt*?!PTIZhWa+v^%Mpz?p-%a?KlAOzoU}PMCveup|m}R)4L(EU(A~r_E2CnhQNXDO{KUs9x_+y+2HRA+drsIL zx>u;X=%9ad!yp{q@|DhVS{!8hO74EjVW5*R-JyBRyCoUFl{JIT=Nr6dw_hV~^u`?ra*|TdCj0l}Gcs
l4NIIDvDG~aEKvftHTq2I7s9iVJ9Nv!ac&!038jL} zQfb@{jfQT=ho7v^g&m&6kUDnsZ1wP+1{C0UMR|ud+)2+2>qQwG`*2f&M$~Cz#X~a8 zcot5#dnUhp=JTGEi6*H>+e>#OJ{3~_Sn`IknN^v&etb~iqfuXk`u9z`r~TKLs6J~k UcrINh0J6+wHsg}|2keej8qMsY6aWAK literal 0 HcmV?d00001 diff --git a/integrations/gitea-repositories-meta/user2/repo1.git/objects/a6/9277c81e90b98a7c0ab25b042a6e296da8eb9a b/integrations/gitea-repositories-meta/user2/repo1.git/objects/a6/9277c81e90b98a7c0ab25b042a6e296da8eb9a new file mode 100644 index 0000000000000000000000000000000000000000..887669883b75550827b0fa1e0f499a8b085e4eed GIT binary patch literal 76 zcmV-S0JHyi0ZYosPf{>9Vo+8nN-fAY=A|ekXC&sO ir-DV3iW2jZGmN+rfx?Lj#i_~pKt_IEDi;6+g&FhS2q5GD literal 0 HcmV?d00001 diff --git a/integrations/gitea-repositories-meta/user2/repo1.git/refs/heads/branch2 b/integrations/gitea-repositories-meta/user2/repo1.git/refs/heads/branch2 index 38c6ece20765..5add7256cd9e 100644 --- a/integrations/gitea-repositories-meta/user2/repo1.git/refs/heads/branch2 +++ b/integrations/gitea-repositories-meta/user2/repo1.git/refs/heads/branch2 @@ -1 +1 @@ -5c050d3b6d2db231ab1f64e324f1b6b9a0b181c2 +985f0301dba5e7b34be866819cd15ad3d8f508ee diff --git a/integrations/gitea-repositories-meta/user2/repo1.git/refs/heads/pr-to-update b/integrations/gitea-repositories-meta/user2/repo1.git/refs/heads/pr-to-update new file mode 100644 index 000000000000..38c6ece20765 --- /dev/null +++ b/integrations/gitea-repositories-meta/user2/repo1.git/refs/heads/pr-to-update @@ -0,0 +1 @@ +5c050d3b6d2db231ab1f64e324f1b6b9a0b181c2 diff --git a/integrations/repo_activity_test.go b/integrations/repo_activity_test.go index cec5c79c4d20..e21f27893dc9 100644 --- a/integrations/repo_activity_test.go +++ b/integrations/repo_activity_test.go @@ -56,9 +56,9 @@ func TestRepoActivity(t *testing.T) { list = htmlDoc.doc.Find("#merged-pull-requests").Next().Find("p.desc") assert.Len(t, list.Nodes, 1) - // Should be 2 merged proposed pull requests + // Should be 3 merged proposed pull requests list = htmlDoc.doc.Find("#proposed-pull-requests").Next().Find("p.desc") - assert.Len(t, list.Nodes, 2) + assert.Len(t, list.Nodes, 3) // Should be 3 new issues list = htmlDoc.doc.Find("#new-issues").Next().Find("p.desc") diff --git a/models/fixtures/issue.yml b/models/fixtures/issue.yml index ecee7499f6f0..e52a23a46b4e 100644 --- a/models/fixtures/issue.yml +++ b/models/fixtures/issue.yml @@ -122,3 +122,15 @@ created_unix: 946684830 updated_unix: 999307200 deadline_unix: 1019307200 + +- + id: 11 + repo_id: 1 + index: 5 + poster_id: 1 + name: pull5 + content: content for the a pull request + is_closed: false + is_pull: true + created_unix: 1579194806 + updated_unix: 1579194806 diff --git a/models/fixtures/pull_request.yml b/models/fixtures/pull_request.yml index e8d81a0007aa..da9566bc481e 100644 --- a/models/fixtures/pull_request.yml +++ b/models/fixtures/pull_request.yml @@ -49,4 +49,17 @@ head_branch: branch1 base_branch: master merge_base: abcdef1234567890 - has_merged: false \ No newline at end of file + has_merged: false + +- + id: 5 # this PR is outdated (one commit behind branch1 ) + type: 0 # gitea pull request + status: 2 # mergable + issue_id: 11 + index: 5 + head_repo_id: 1 + base_repo_id: 1 + head_branch: pr-to-update + base_branch: branch1 + merge_base: 1234567890abcdef + has_merged: false diff --git a/models/fixtures/repository.yml b/models/fixtures/repository.yml index a68e63e309ee..05989d903098 100644 --- a/models/fixtures/repository.yml +++ b/models/fixtures/repository.yml @@ -7,7 +7,7 @@ is_private: false num_issues: 2 num_closed_issues: 1 - num_pulls: 2 + num_pulls: 3 num_closed_pulls: 0 num_milestones: 3 num_closed_milestones: 1 diff --git a/models/issue_test.go b/models/issue_test.go index ec4867d075f7..d65345a508a1 100644 --- a/models/issue_test.go +++ b/models/issue_test.go @@ -276,8 +276,8 @@ func TestIssue_SearchIssueIDsByKeyword(t *testing.T) { total, ids, err = SearchIssueIDsByKeyword("for", []int64{1}, 10, 0) assert.NoError(t, err) - assert.EqualValues(t, 4, total) - assert.EqualValues(t, []int64{1, 2, 3, 5}, ids) + assert.EqualValues(t, 5, total) + assert.EqualValues(t, []int64{1, 2, 3, 5, 11}, ids) // issue1's comment id 2 total, ids, err = SearchIssueIDsByKeyword("good", []int64{1}, 10, 0) @@ -305,8 +305,8 @@ func testInsertIssue(t *testing.T, title, content string) { assert.True(t, has) assert.EqualValues(t, issue.Title, newIssue.Title) assert.EqualValues(t, issue.Content, newIssue.Content) - // there are 4 issues and max index is 4 on repository 1, so this one should 5 - assert.EqualValues(t, 5, newIssue.Index) + // there are 5 issues and max index is 5 on repository 1, so this one should 6 + assert.EqualValues(t, 6, newIssue.Index) _, err = x.ID(issue.ID).Delete(new(Issue)) assert.NoError(t, err) diff --git a/models/issue_user_test.go b/models/issue_user_test.go index a57ab33f9ec1..01e0bdc6444f 100644 --- a/models/issue_user_test.go +++ b/models/issue_user_test.go @@ -17,7 +17,7 @@ func Test_newIssueUsers(t *testing.T) { newIssue := &Issue{ RepoID: repo.ID, PosterID: 4, - Index: 5, + Index: 6, Title: "newTestIssueTitle", Content: "newTestIssueContent", } diff --git a/models/pull_test.go b/models/pull_test.go index 9c27b603aa53..6ceeae665376 100644 --- a/models/pull_test.go +++ b/models/pull_test.go @@ -61,10 +61,11 @@ func TestPullRequestsNewest(t *testing.T) { Labels: []string{}, }) assert.NoError(t, err) - assert.Equal(t, int64(2), count) - if assert.Len(t, prs, 2) { - assert.Equal(t, int64(2), prs[0].ID) - assert.Equal(t, int64(1), prs[1].ID) + assert.EqualValues(t, 3, count) + if assert.Len(t, prs, 3) { + assert.EqualValues(t, 5, prs[0].ID) + assert.EqualValues(t, 2, prs[1].ID) + assert.EqualValues(t, 1, prs[2].ID) } } @@ -77,10 +78,11 @@ func TestPullRequestsOldest(t *testing.T) { Labels: []string{}, }) assert.NoError(t, err) - assert.Equal(t, int64(2), count) - if assert.Len(t, prs, 2) { - assert.Equal(t, int64(1), prs[0].ID) - assert.Equal(t, int64(2), prs[1].ID) + assert.EqualValues(t, 3, count) + if assert.Len(t, prs, 3) { + assert.EqualValues(t, 1, prs[0].ID) + assert.EqualValues(t, 2, prs[1].ID) + assert.EqualValues(t, 5, prs[2].ID) } } From 8bad5d297a490f572a9aa20635e58928d6b6149e Mon Sep 17 00:00:00 2001 From: 6543 <6543@obermui.de> Date: Thu, 16 Jan 2020 19:17:29 +0100 Subject: [PATCH 17/35] correct comments --- services/pull/update.go | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/services/pull/update.go b/services/pull/update.go index 72af2fa45bf4..57388a9bcbaa 100644 --- a/services/pull/update.go +++ b/services/pull/update.go @@ -14,9 +14,9 @@ import ( "code.gitea.io/gitea/modules/log" ) -// Update ToDo wip ... +// Update updates pull request with base branch. func Update(pull *models.PullRequest, doer *models.User, message string) (err error) { - //use merge functions but switch repo's and branches + //use merge functions but switch repo's and branche's pr := &models.PullRequest{ HeadRepoID: pull.BaseRepoID, BaseRepoID: pull.HeadRepoID, From 143d8e8fb19d16a7ee19588b204b4925188d51b5 Mon Sep 17 00:00:00 2001 From: 6543 <6543@obermui.de> Date: Thu, 16 Jan 2020 19:57:04 +0100 Subject: [PATCH 18/35] make PR5 outdated --- .../62/fb502a7172d4453f0322a2cc85bddffa57f07a | Bin 0 -> 839 bytes .../6a/a3a5385611c5eb8986c9961a9c34a93cbaadfb | Bin 0 -> 86 bytes .../b2/60587271671842af0b036e4fe643c9d45b7ddd | Bin 0 -> 20 bytes .../user2/repo1.git/refs/heads/pr-to-update | 2 +- .../user2/repo1.git/refs/pull/5/head | 1 + 5 files changed, 2 insertions(+), 1 deletion(-) create mode 100644 integrations/gitea-repositories-meta/user2/repo1.git/objects/62/fb502a7172d4453f0322a2cc85bddffa57f07a create mode 100644 integrations/gitea-repositories-meta/user2/repo1.git/objects/6a/a3a5385611c5eb8986c9961a9c34a93cbaadfb create mode 100644 integrations/gitea-repositories-meta/user2/repo1.git/objects/b2/60587271671842af0b036e4fe643c9d45b7ddd create mode 100644 integrations/gitea-repositories-meta/user2/repo1.git/refs/pull/5/head diff --git a/integrations/gitea-repositories-meta/user2/repo1.git/objects/62/fb502a7172d4453f0322a2cc85bddffa57f07a b/integrations/gitea-repositories-meta/user2/repo1.git/objects/62/fb502a7172d4453f0322a2cc85bddffa57f07a new file mode 100644 index 0000000000000000000000000000000000000000..ee494a8ca8c4a75d3d5ee3d519428e0a5b0a50d9 GIT binary patch literal 839 zcmV-N1GxNn0gaPMui{n|gtPXqxOD~_jax4S>{;B`;Nj|i5^;eev z02Id~nj|6Oz>cIyl1P6AoATdxl+SXkO7Q2;lhmVT0{dtKPdl2TAGqqTKLH3(Il3x| zq9lvre5h2Ft-WRpA6I#IT|`+!eflKHZtohMdJr47951PJQm&M#m|{Zf4FS@YqOiw3 zZjN}CUHQIszE>c1OT+r8>``S=V0XLqG8N>;Ch3op6kNq1xRP0@wqXT`?Z!;p*63y~U|(JF3dQgK-~AW-v4`Ff%bxaLdd|)eX-NXV{bwQB;^N;k2HcInV!@^T{jG swRfRvf?OS4d|mZ&Qy7+qA9$4{mwe%G{^8(-rGJl0&Wn`=07oVsJ1R;hi2wiq literal 0 HcmV?d00001 diff --git a/integrations/gitea-repositories-meta/user2/repo1.git/objects/b2/60587271671842af0b036e4fe643c9d45b7ddd b/integrations/gitea-repositories-meta/user2/repo1.git/objects/b2/60587271671842af0b036e4fe643c9d45b7ddd new file mode 100644 index 0000000000000000000000000000000000000000..9182ac038166ac30f7f550603dc8b87c1b102bc9 GIT binary patch literal 20 bcmb Date: Thu, 16 Jan 2020 20:03:22 +0100 Subject: [PATCH 19/35] fix Tests --- modules/indexer/issues/indexer_test.go | 4 ++-- services/pull/update.go | 12 ++++-------- 2 files changed, 6 insertions(+), 10 deletions(-) diff --git a/modules/indexer/issues/indexer_test.go b/modules/indexer/issues/indexer_test.go index 4028a6c8b518..8a54c200ff2e 100644 --- a/modules/indexer/issues/indexer_test.go +++ b/modules/indexer/issues/indexer_test.go @@ -65,7 +65,7 @@ func TestBleveSearchIssues(t *testing.T) { ids, err = SearchIssuesByKeyword([]int64{1}, "for") assert.NoError(t, err) - assert.EqualValues(t, []int64{1, 2, 3, 5}, ids) + assert.EqualValues(t, []int64{1, 2, 3, 5, 11}, ids) ids, err = SearchIssuesByKeyword([]int64{1}, "good") assert.NoError(t, err) @@ -89,7 +89,7 @@ func TestDBSearchIssues(t *testing.T) { ids, err = SearchIssuesByKeyword([]int64{1}, "for") assert.NoError(t, err) - assert.EqualValues(t, []int64{1, 2, 3, 5}, ids) + assert.EqualValues(t, []int64{1, 2, 3, 5, 11}, ids) ids, err = SearchIssuesByKeyword([]int64{1}, "good") assert.NoError(t, err) diff --git a/services/pull/update.go b/services/pull/update.go index 57388a9bcbaa..ff7f8403d47a 100644 --- a/services/pull/update.go +++ b/services/pull/update.go @@ -15,8 +15,8 @@ import ( ) // Update updates pull request with base branch. -func Update(pull *models.PullRequest, doer *models.User, message string) (err error) { - //use merge functions but switch repo's and branche's +func Update(pull *models.PullRequest, doer *models.User, message string) error { + //use merge functions but switch repo's and branch's pr := &models.PullRequest{ HeadRepoID: pull.BaseRepoID, BaseRepoID: pull.HeadRepoID, @@ -24,7 +24,7 @@ func Update(pull *models.PullRequest, doer *models.User, message string) (err er BaseBranch: pull.HeadBranch, } - if err = pr.LoadHeadRepo(); err != nil { + if err := pr.LoadHeadRepo(); err != nil { log.Error("LoadHeadRepo: %v", err) return fmt.Errorf("LoadHeadRepo: %v", err) } else if err = pr.LoadBaseRepo(); err != nil { @@ -43,11 +43,7 @@ func Update(pull *models.PullRequest, doer *models.User, message string) (err er go AddTestPullRequestTask(doer, pr.HeadRepo.ID, pr.HeadBranch, false, "", "") }() - if err := rawMerge(pr, doer, models.MergeStyleMerge, message); err != nil { - return err - } - - return nil + return rawMerge(pr, doer, models.MergeStyleMerge, message) } // IsUserAllowedToUpdate check if user is allowed to update PR with given permissions and branch protections From 069a393b786e0f67417aad731b6a5723b075f9d9 Mon Sep 17 00:00:00 2001 From: 6543 <6543@obermui.de> Date: Thu, 16 Jan 2020 20:48:02 +0100 Subject: [PATCH 20/35] WIP: add pull update test --- integrations/pull_update_test.go | 41 ++++++++++++++++++++++++++++++++ 1 file changed, 41 insertions(+) create mode 100644 integrations/pull_update_test.go diff --git a/integrations/pull_update_test.go b/integrations/pull_update_test.go new file mode 100644 index 000000000000..bb2b16916df4 --- /dev/null +++ b/integrations/pull_update_test.go @@ -0,0 +1,41 @@ +// Copyright 2020 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 integrations + +import ( + "fmt" + "net/url" + "testing" + + "code.gitea.io/gitea/models" + pull_service "code.gitea.io/gitea/services/pull" + + "github.com/stretchr/testify/assert" +) + +func TestPullUpdate(t *testing.T) { + onGiteaRun(t, func(t *testing.T, giteaURL *url.URL) { + + pr := models.AssertExistsAndLoadBean(t, &models.PullRequest{ID: 5}).(*models.PullRequest) + user := models.AssertExistsAndLoadBean(t, &models.User{ID: 1}).(*models.User) + + //Test GetDiverging + diffCount, err := pull_service.GetDiverging(pr) + assert.NoError(t, err) + assert.EqualValues(t, 1, diffCount.Behind) + assert.EqualValues(t, 1, diffCount.Ahead) + + message := fmt.Sprintf("Merge branch '%s' into %s", pr.BaseBranch, pr.HeadBranch) + err = pull_service.Update(pr,user, message) + assert.NoError(t, err) + + //Test GetDiverging after update + diffCount, err = pull_service.GetDiverging(pr) + assert.NoError(t, err) + assert.EqualValues(t, 0, diffCount.Behind) + assert.EqualValues(t, 2, diffCount.Ahead) + + }) +} From 720fbf16ee9416e33f4f5248f8f24766df94c219 Mon Sep 17 00:00:00 2001 From: 6543 <6543@obermui.de> Date: Thu, 16 Jan 2020 21:02:10 +0100 Subject: [PATCH 21/35] update revs --- integrations/gitea-repositories-meta/user2/repo1.git/info/refs | 2 ++ 1 file changed, 2 insertions(+) diff --git a/integrations/gitea-repositories-meta/user2/repo1.git/info/refs b/integrations/gitea-repositories-meta/user2/repo1.git/info/refs index ca1df85e2ebf..fa3009793de7 100644 --- a/integrations/gitea-repositories-meta/user2/repo1.git/info/refs +++ b/integrations/gitea-repositories-meta/user2/repo1.git/info/refs @@ -1 +1,3 @@ 65f1bf27bc3bf70f64657658635e66094edbcb4d refs/heads/master +985f0301dba5e7b34be866819cd15ad3d8f508ee refs/heads/branch2 +62fb502a7172d4453f0322a2cc85bddffa57f07a refs/heads/pr-to-update From 892ddd9bb63643fb2d31faa55fa3dd103cdd6216 Mon Sep 17 00:00:00 2001 From: 6543 <6543@obermui.de> Date: Thu, 16 Jan 2020 21:10:04 +0100 Subject: [PATCH 22/35] update locales --- options/locale/locale_en-US.ini | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/options/locale/locale_en-US.ini b/options/locale/locale_en-US.ini index 261a4996bfb3..555116944d93 100644 --- a/options/locale/locale_en-US.ini +++ b/options/locale/locale_en-US.ini @@ -1082,8 +1082,9 @@ pulls.open_unmerged_pull_exists = `You cannot perform a reopen operation because pulls.status_checking = Some checks are pending pulls.status_checks_success = All checks were successful pulls.status_checks_error = Some checks failed -pulls.update_branch = Update Branch -pulls.update_branch_success = Update Branch was successful +pulls.update_branch = Update branch +pulls.update_branch_success = Update branch was successful +pulls.update_not_allowed = You are not allowed to update branch milestones.new = New Milestone milestones.open_tab = %d Open From 7aa9e84763bcf0a068dafdb83216e8bbb4f4e446 Mon Sep 17 00:00:00 2001 From: 6543 <6543@obermui.de> Date: Thu, 16 Jan 2020 22:22:49 +0100 Subject: [PATCH 23/35] working TEST --- integrations/pull_update_test.go | 103 +++++++++++++++++++++++++++++-- 1 file changed, 99 insertions(+), 4 deletions(-) diff --git a/integrations/pull_update_test.go b/integrations/pull_update_test.go index bb2b16916df4..3ed8b0ef4271 100644 --- a/integrations/pull_update_test.go +++ b/integrations/pull_update_test.go @@ -8,18 +8,23 @@ import ( "fmt" "net/url" "testing" + "time" "code.gitea.io/gitea/models" + "code.gitea.io/gitea/modules/repofiles" + repo_module "code.gitea.io/gitea/modules/repository" pull_service "code.gitea.io/gitea/services/pull" + repo_service "code.gitea.io/gitea/services/repository" "github.com/stretchr/testify/assert" ) func TestPullUpdate(t *testing.T) { onGiteaRun(t, func(t *testing.T, giteaURL *url.URL) { - - pr := models.AssertExistsAndLoadBean(t, &models.PullRequest{ID: 5}).(*models.PullRequest) - user := models.AssertExistsAndLoadBean(t, &models.User{ID: 1}).(*models.User) + //Create PR to test + user := models.AssertExistsAndLoadBean(t, &models.User{ID: 2}).(*models.User) + org26 := models.AssertExistsAndLoadBean(t, &models.User{ID: 26}).(*models.User) + pr := createOutdatedPR(t, user, org26) //Test GetDiverging diffCount, err := pull_service.GetDiverging(pr) @@ -28,7 +33,7 @@ func TestPullUpdate(t *testing.T) { assert.EqualValues(t, 1, diffCount.Ahead) message := fmt.Sprintf("Merge branch '%s' into %s", pr.BaseBranch, pr.HeadBranch) - err = pull_service.Update(pr,user, message) + err = pull_service.Update(pr, user, message) assert.NoError(t, err) //Test GetDiverging after update @@ -39,3 +44,93 @@ func TestPullUpdate(t *testing.T) { }) } + +func createOutdatedPR(t *testing.T, actor, forkOrg *models.User) *models.PullRequest { + baseRepo, err := repo_service.CreateRepository(actor, actor, models.CreateRepoOptions{ + Name: "repo-pr-update", + Description: "repo-tmp-pr-update descritpion", + AutoInit: true, + Gitignores: "C,C++", + License: "MIT", + Readme: "Default", + IsPrivate: false, + }) + assert.NoError(t, err) + assert.NotEmpty(t, baseRepo) + + headRepo, err := repo_module.ForkRepository(actor, forkOrg, baseRepo, "repo-pr-update", "desc") + assert.NoError(t, err) + assert.NotEmpty(t, headRepo) + + //create a commit on base Repo + _, err = repofiles.CreateOrUpdateRepoFile(baseRepo, actor, &repofiles.UpdateRepoFileOptions{ + TreePath: "File_A", + Message: "Add File A", + Content: "File A", + IsNewFile: true, + OldBranch: "master", + NewBranch: "master", + Author: &repofiles.IdentityOptions{ + Name: actor.Name, + Email: actor.Email, + }, + Committer: &repofiles.IdentityOptions{ + Name: actor.Name, + Email: actor.Email, + }, + Dates: &repofiles.CommitDateOptions{ + Author: time.Now(), + Committer: time.Now(), + }, + }) + assert.NoError(t, err) + + //create a commit on head Repo + _, err = repofiles.CreateOrUpdateRepoFile(headRepo, actor, &repofiles.UpdateRepoFileOptions{ + TreePath: "File_B", + Message: "Add File on PR branch", + Content: "File B", + IsNewFile: true, + OldBranch: "master", + NewBranch: "newBranch", + Author: &repofiles.IdentityOptions{ + Name: actor.Name, + Email: actor.Email, + }, + Committer: &repofiles.IdentityOptions{ + Name: actor.Name, + Email: actor.Email, + }, + Dates: &repofiles.CommitDateOptions{ + Author: time.Now(), + Committer: time.Now(), + }, + }) + assert.NoError(t, err) + + //create Pull + pullIssue := &models.Issue{ + RepoID: baseRepo.ID, + Title: "Test Pull -to-update-", + PosterID: actor.ID, + Poster: actor, + IsPull: true, + } + pullRequest := &models.PullRequest{ + HeadRepoID: headRepo.ID, + BaseRepoID: baseRepo.ID, + HeadBranch: "newBranch", + BaseBranch: "master", + HeadRepo: headRepo, + BaseRepo: baseRepo, + Type: models.PullRequestGitea, + } + err = pull_service.NewPullRequest(baseRepo, pullIssue, nil, nil, pullRequest, nil) + assert.NoError(t, err) + + issue := models.AssertExistsAndLoadBean(t, &models.Issue{Title: "Test Pull -to-update-"}).(*models.Issue) + pr, err := models.GetPullRequestByIssueID(issue.ID) + assert.NoError(t, err) + + return pr +} From 36a34cd6ed228a1c385ceeb16a4d27216fac7d36 Mon Sep 17 00:00:00 2001 From: 6543 <6543@obermui.de> Date: Thu, 16 Jan 2020 23:41:56 +0100 Subject: [PATCH 24/35] update UI --- options/locale/locale_en-US.ini | 1 + routers/repo/pull.go | 12 ++++++++--- templates/repo/issue/view_content/pull.tmpl | 22 ++++++++++++++------- web_src/less/_repository.less | 3 +++ 4 files changed, 28 insertions(+), 10 deletions(-) diff --git a/options/locale/locale_en-US.ini b/options/locale/locale_en-US.ini index 555116944d93..0f6852c8e9b2 100644 --- a/options/locale/locale_en-US.ini +++ b/options/locale/locale_en-US.ini @@ -1085,6 +1085,7 @@ pulls.status_checks_error = Some checks failed pulls.update_branch = Update branch pulls.update_branch_success = Update branch was successful pulls.update_not_allowed = You are not allowed to update branch +pulls.outdated_with_base_branch = This branch is out-of-date with the base branch milestones.new = New Milestone milestones.open_tab = %d Open diff --git a/routers/repo/pull.go b/routers/repo/pull.go index a89ce79873d5..498ce11e4b4d 100644 --- a/routers/repo/pull.go +++ b/routers/repo/pull.go @@ -342,12 +342,18 @@ func PrepareViewPullInfo(ctx *context.Context, issue *models.Issue) *git.Compare setMergeTarget(ctx, pull) - divergence, divergenceError := pull_service.GetDiverging(pull) - if divergenceError != nil { - ctx.ServerError("GetDiverging", divergenceError) + divergence, err := pull_service.GetDiverging(pull) + if err != nil { + ctx.ServerError("GetDiverging", err) return nil } ctx.Data["Divergence"] = divergence + allowUpdate, err := pull_service.IsUserAllowedToUpdate(pull, ctx.User) + if err != nil { + ctx.ServerError("GetDiverging", err) + return nil + } + ctx.Data["UpdateAllowed"] = allowUpdate if err := pull.LoadProtectedBranch(); err != nil { ctx.ServerError("LoadProtectedBranch", err) diff --git a/templates/repo/issue/view_content/pull.tmpl b/templates/repo/issue/view_content/pull.tmpl index 445fe523995a..ea18caa3158c 100644 --- a/templates/repo/issue/view_content/pull.tmpl +++ b/templates/repo/issue/view_content/pull.tmpl @@ -270,13 +270,21 @@ {{if and .Divergence (gt .Divergence.Behind 0)}} -
-
- {{.CsrfTokenHtml}} - -
+
+
+
+     {{$.i18n.Tr "repo.pulls.outdated_with_base_branch"}} +
+ {{if .UpdateAllowed}} +
+
+ {{.CsrfTokenHtml}} + +
+
+ {{end}}
{{end}} {{else}} diff --git a/web_src/less/_repository.less b/web_src/less/_repository.less index ed87131e66bd..79e1ac8173b6 100644 --- a/web_src/less/_repository.less +++ b/web_src/less/_repository.less @@ -658,6 +658,9 @@ .update-button { float: right; } + .maxwidth { + width: 100%; + } } .review-item { From 18fadeff493113dde8bbfaca37b5245ef4826459 Mon Sep 17 00:00:00 2001 From: 6543 <6543@obermui.de> Date: Thu, 16 Jan 2020 23:43:59 +0100 Subject: [PATCH 25/35] misspell --- integrations/pull_update_test.go | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/integrations/pull_update_test.go b/integrations/pull_update_test.go index 3ed8b0ef4271..484390001c8b 100644 --- a/integrations/pull_update_test.go +++ b/integrations/pull_update_test.go @@ -48,7 +48,7 @@ func TestPullUpdate(t *testing.T) { func createOutdatedPR(t *testing.T, actor, forkOrg *models.User) *models.PullRequest { baseRepo, err := repo_service.CreateRepository(actor, actor, models.CreateRepoOptions{ Name: "repo-pr-update", - Description: "repo-tmp-pr-update descritpion", + Description: "repo-tmp-pr-update description", AutoInit: true, Gitignores: "C,C++", License: "MIT", From 97e51ec37245ee3e6edc26d228065c7d12a6b5a6 Mon Sep 17 00:00:00 2001 From: 6543 <6543@obermui.de> Date: Thu, 16 Jan 2020 23:50:23 +0100 Subject: [PATCH 26/35] change style --- templates/repo/issue/view_content/pull.tmpl | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/templates/repo/issue/view_content/pull.tmpl b/templates/repo/issue/view_content/pull.tmpl index ea18caa3158c..6709c2c5ea7e 100644 --- a/templates/repo/issue/view_content/pull.tmpl +++ b/templates/repo/issue/view_content/pull.tmpl @@ -272,15 +272,15 @@ {{if and .Divergence (gt .Divergence.Behind 0)}}
-
-     {{$.i18n.Tr "repo.pulls.outdated_with_base_branch"}} +
+    {{$.i18n.Tr "repo.pulls.outdated_with_base_branch"}}
{{if .UpdateAllowed}}
{{.CsrfTokenHtml}}
From 18eb4951cf261673858c88a2db058ae634cc9bed Mon Sep 17 00:00:00 2001 From: 6543 <6543@obermui.de> Date: Fri, 17 Jan 2020 00:00:30 +0100 Subject: [PATCH 27/35] add 1s delay so rev exist --- routers/repo/pull.go | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/routers/repo/pull.go b/routers/repo/pull.go index 498ce11e4b4d..c037ee7539ad 100644 --- a/routers/repo/pull.go +++ b/routers/repo/pull.go @@ -14,6 +14,7 @@ import ( "net/http" "path" "strings" + "time" "code.gitea.io/gitea/models" "code.gitea.io/gitea/modules/auth" @@ -661,6 +662,9 @@ func UpdatePullRequest(ctx *context.Context) { ctx.Flash.Error(err.Error()) ctx.Redirect(ctx.Repo.RepoLink + "/pulls/" + com.ToStr(issue.Index)) } + + time.Sleep(1 * time.Second) + ctx.Flash.Success(ctx.Tr("repo.pulls.update_branch_success")) ctx.Redirect(ctx.Repo.RepoLink + "/pulls/" + com.ToStr(issue.Index)) } From 2b589612bd50be1cdd307cb19483335ff61e3674 Mon Sep 17 00:00:00 2001 From: 6543 <6543@obermui.de> Date: Fri, 17 Jan 2020 00:03:41 +0100 Subject: [PATCH 28/35] move row up (before merge row) --- templates/repo/issue/view_content/pull.tmpl | 36 ++++++++++----------- 1 file changed, 18 insertions(+), 18 deletions(-) diff --git a/templates/repo/issue/view_content/pull.tmpl b/templates/repo/issue/view_content/pull.tmpl index 6709c2c5ea7e..08c5c6855d05 100644 --- a/templates/repo/issue/view_content/pull.tmpl +++ b/templates/repo/issue/view_content/pull.tmpl @@ -157,6 +157,24 @@ {{$.i18n.Tr (printf "repo.signing.wont_sign.%s" .WontSignReason) }}
{{end}} + {{if and .Divergence (gt .Divergence.Behind 0)}} +
+
+
+    {{$.i18n.Tr "repo.pulls.outdated_with_base_branch"}} +
+ {{if .UpdateAllowed}} +
+
+ {{.CsrfTokenHtml}} + +
+
+ {{end}} +
+ {{end}} {{if .AllowMerge}} {{$prUnit := .Repository.MustGetUnit $.UnitTypePullRequests}} {{$approvers := .Issue.PullRequest.GetApprovers}} @@ -269,24 +287,6 @@
- {{if and .Divergence (gt .Divergence.Behind 0)}} -
-
-
-    {{$.i18n.Tr "repo.pulls.outdated_with_base_branch"}} -
- {{if .UpdateAllowed}} -
-
- {{.CsrfTokenHtml}} - -
-
- {{end}} -
- {{end}} {{else}}
From 688a53a6ec37b7ea7c5ea67472b820a7ab2aa095 Mon Sep 17 00:00:00 2001 From: 6543 <6543@obermui.de> Date: Fri, 17 Jan 2020 00:10:04 +0100 Subject: [PATCH 29/35] fix lint nit --- services/pull/update.go | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/services/pull/update.go b/services/pull/update.go index ff7f8403d47a..6d0e207d5bfe 100644 --- a/services/pull/update.go +++ b/services/pull/update.go @@ -112,8 +112,7 @@ func GetDiverging(pr *models.PullRequest) (*git.DivergeObject, error) { return &git.DivergeObject{}, errorBehind } - diffCount := git.DivergeObject{ahead, behind} - return &diffCount, nil + return &git.DivergeObject{Ahead: ahead, Behind: behind}, nil } func checkDivergence(repoPath string, baseBranch string, targetBranch string) (int, error) { From 97a6f830cf5e8bf0bc543b008d6ef6a15cf78cb9 Mon Sep 17 00:00:00 2001 From: 6543 <6543@obermui.de> Date: Fri, 17 Jan 2020 00:11:39 +0100 Subject: [PATCH 30/35] UI remove divider --- templates/repo/issue/view_content/pull.tmpl | 1 - 1 file changed, 1 deletion(-) diff --git a/templates/repo/issue/view_content/pull.tmpl b/templates/repo/issue/view_content/pull.tmpl index 08c5c6855d05..00fa7d0286d3 100644 --- a/templates/repo/issue/view_content/pull.tmpl +++ b/templates/repo/issue/view_content/pull.tmpl @@ -158,7 +158,6 @@
{{end}} {{if and .Divergence (gt .Divergence.Behind 0)}} -
   {{$.i18n.Tr "repo.pulls.outdated_with_base_branch"}} From 6400bccdf313cbf4f5036b702756cab8a54fd8fc Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Lauris=20Buk=C5=A1is-Haberkorns?= Date: Fri, 17 Jan 2020 02:12:14 +0200 Subject: [PATCH 31/35] Update style --- templates/repo/issue/view_content/pull.tmpl | 11 +++++++---- web_src/less/_repository.less | 11 ++++++----- 2 files changed, 13 insertions(+), 9 deletions(-) diff --git a/templates/repo/issue/view_content/pull.tmpl b/templates/repo/issue/view_content/pull.tmpl index 00fa7d0286d3..d15237137d4f 100644 --- a/templates/repo/issue/view_content/pull.tmpl +++ b/templates/repo/issue/view_content/pull.tmpl @@ -158,12 +158,14 @@
{{end}} {{if and .Divergence (gt .Divergence.Behind 0)}} -
-
-    {{$.i18n.Tr "repo.pulls.outdated_with_base_branch"}} +
+
+
+ + {{$.i18n.Tr "repo.pulls.outdated_with_base_branch"}}
{{if .UpdateAllowed}} -
+
{{.CsrfTokenHtml}}
{{end}}
+
{{end}} {{if .AllowMerge}} {{$prUnit := .Repository.MustGetUnit $.UnitTypePullRequests}} diff --git a/web_src/less/_repository.less b/web_src/less/_repository.less index 79e1ac8173b6..a1b55e86aaf6 100644 --- a/web_src/less/_repository.less +++ b/web_src/less/_repository.less @@ -655,11 +655,12 @@ .icon-octicon { padding-left: 2px; } - .update-button { - float: right; - } - .maxwidth { - width: 100%; + .branch-update.grid { + margin-bottom: -1.5rem; + margin-top: -0.5rem; + .row { + padding-bottom: 0; + } } } From fa4779bc7e8da7bb61d75f5aed6558b3981a06b2 Mon Sep 17 00:00:00 2001 From: 6543 <6543@obermui.de> Date: Fri, 17 Jan 2020 01:44:35 +0100 Subject: [PATCH 32/35] nits --- options/locale/locale_en-US.ini | 2 +- routers/repo/pull.go | 2 -- 2 files changed, 1 insertion(+), 3 deletions(-) diff --git a/options/locale/locale_en-US.ini b/options/locale/locale_en-US.ini index 0f6852c8e9b2..9a4f0535e8c6 100644 --- a/options/locale/locale_en-US.ini +++ b/options/locale/locale_en-US.ini @@ -1083,7 +1083,7 @@ pulls.status_checking = Some checks are pending pulls.status_checks_success = All checks were successful pulls.status_checks_error = Some checks failed pulls.update_branch = Update branch -pulls.update_branch_success = Update branch was successful +pulls.update_branch_success = Branch update was successful pulls.update_not_allowed = You are not allowed to update branch pulls.outdated_with_base_branch = This branch is out-of-date with the base branch diff --git a/routers/repo/pull.go b/routers/repo/pull.go index c037ee7539ad..fc0012ffbe55 100644 --- a/routers/repo/pull.go +++ b/routers/repo/pull.go @@ -603,7 +603,6 @@ func ViewPullFiles(ctx *context.Context) { // UpdatePullRequest merge master into PR func UpdatePullRequest(ctx *context.Context) { - issue := checkPullInfo(ctx) if ctx.Written() { return @@ -612,7 +611,6 @@ func UpdatePullRequest(ctx *context.Context) { ctx.NotFound("MergePullRequest", nil) return } - if issue.PullRequest.HasMerged { ctx.NotFound("MergePullRequest", nil) return From fbbc7f43132ec086ad77b283633f3d6b1c0d3660 Mon Sep 17 00:00:00 2001 From: 6543 <6543@obermui.de> Date: Fri, 17 Jan 2020 01:47:19 +0100 Subject: [PATCH 33/35] do it right --- routers/routes/routes.go | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/routers/routes/routes.go b/routers/routes/routes.go index 057fd7328b74..7e81f55de60f 100644 --- a/routers/routes/routes.go +++ b/routers/routes/routes.go @@ -855,7 +855,7 @@ func RegisterRoutes(m *macaron.Macaron) { m.Get(".patch", repo.DownloadPullPatch) m.Get("/commits", context.RepoRef(), repo.ViewPullCommits) m.Post("/merge", context.RepoMustNotBeArchived(), reqRepoPullsWriter, bindIgnErr(auth.MergePullRequestForm{}), repo.MergePullRequest) - m.Post("/update", ignSignInAndCsrf, repo.UpdatePullRequest) + m.Post("/update", repo.UpdatePullRequest) m.Post("/cleanup", context.RepoMustNotBeArchived(), context.RepoRef(), repo.CleanUpPullRequest) m.Group("/files", func() { m.Get("", context.RepoRef(), repo.SetEditorconfigIfExists, repo.SetDiffViewStyle, repo.SetWhitespaceBehavior, repo.ViewPullFiles) From 717406e971de5e7bfe6d23519602d06bc337c41c Mon Sep 17 00:00:00 2001 From: 6543 <6543@obermui.de> Date: Fri, 17 Jan 2020 03:09:32 +0100 Subject: [PATCH 34/35] introduce IsSameRepo --- models/pull.go | 5 +++++ services/pull/update.go | 2 +- 2 files changed, 6 insertions(+), 1 deletion(-) diff --git a/models/pull.go b/models/pull.go index 1edd890035e3..fcfcd221c459 100644 --- a/models/pull.go +++ b/models/pull.go @@ -742,3 +742,8 @@ func (pr *PullRequest) IsHeadEqualWithBranch(branchName string) (bool, error) { } return baseCommit.HasPreviousCommit(headCommit.ID) } + +// IsSameRepo returns true if base repo and head repo is the same +func (pr *PullRequest) IsSameRepo() bool { + return pr.BaseRepoID == pr.HeadRepoID +} diff --git a/services/pull/update.go b/services/pull/update.go index 6d0e207d5bfe..e310957e29b2 100644 --- a/services/pull/update.go +++ b/services/pull/update.go @@ -84,7 +84,7 @@ func GetDiverging(pr *models.PullRequest) (*git.DivergeObject, error) { } defer headGitRepo.Close() - if pr.BaseRepoID == pr.HeadRepoID { + if pr.IsSameRepo() { diff, err := git.GetDivergingCommits(pr.HeadRepo.RepoPath(), pr.BaseBranch, pr.HeadBranch) return &diff, err } From f26c8b3d27f4b6ac5f2e7b0cdf7415aa65ce22f0 Mon Sep 17 00:00:00 2001 From: 6543 <6543@obermui.de> Date: Fri, 17 Jan 2020 03:10:37 +0100 Subject: [PATCH 35/35] remove useless check --- services/pull/update.go | 13 ++++--------- 1 file changed, 4 insertions(+), 9 deletions(-) diff --git a/services/pull/update.go b/services/pull/update.go index e310957e29b2..5f055827e1af 100644 --- a/services/pull/update.go +++ b/services/pull/update.go @@ -65,16 +65,11 @@ func IsUserAllowedToUpdate(pull *models.PullRequest, user *models.User) (bool, e // GetDiverging determines how many commits a PR is ahead or behind the PR base branch func GetDiverging(pr *models.PullRequest) (*git.DivergeObject, error) { log.Trace("PushToBaseRepo[%d]: pushing commits to base repo '%s'", pr.BaseRepoID, pr.GetGitRefName()) - - if pr.BaseRepo == nil { - if err := pr.LoadBaseRepo(); err != nil { - return nil, err - } + if err := pr.LoadBaseRepo(); err != nil { + return nil, err } - if pr.HeadRepo == nil { - if err := pr.LoadHeadRepo(); err != nil { - return nil, err - } + if err := pr.LoadHeadRepo(); err != nil { + return nil, err } headRepoPath := pr.HeadRepo.RepoPath()