From 957aed48f16ee9b40a3bfa59e156661d63baf431 Mon Sep 17 00:00:00 2001 From: changchaishi Date: Wed, 8 Jan 2025 06:01:33 +0000 Subject: [PATCH 01/10] fix sync fork --- routers/web/repo/view_home.go | 2 +- services/repository/merge_upstream.go | 32 ++++++++++++++++++++++----- 2 files changed, 28 insertions(+), 6 deletions(-) diff --git a/routers/web/repo/view_home.go b/routers/web/repo/view_home.go index 8c9f54656b0c0..9041e0d2010e7 100644 --- a/routers/web/repo/view_home.go +++ b/routers/web/repo/view_home.go @@ -181,7 +181,7 @@ func prepareUpstreamDivergingInfo(ctx *context.Context) { if !ctx.Repo.Repository.IsFork || !ctx.Repo.IsViewBranch || ctx.Repo.TreePath != "" { return } - upstreamDivergingInfo, err := repo_service.GetUpstreamDivergingInfo(ctx, ctx.Repo.Repository, ctx.Repo.BranchName) + upstreamDivergingInfo, err := repo_service.GetUpstreamDivergingInfo(ctx, ctx.Repo.GitRepo, ctx.Repo.Repository, ctx.Repo.BranchName) if err != nil { if !errors.Is(err, util.ErrNotExist) && !errors.Is(err, util.ErrInvalidArgument) { log.Error("GetUpstreamDivergingInfo: %v", err) diff --git a/services/repository/merge_upstream.go b/services/repository/merge_upstream.go index 85ca8f7e31a7d..cd25101046f0b 100644 --- a/services/repository/merge_upstream.go +++ b/services/repository/merge_upstream.go @@ -6,12 +6,15 @@ package repository import ( "context" "fmt" + "strconv" + "time" git_model "code.gitea.io/gitea/models/git" issue_model "code.gitea.io/gitea/models/issues" repo_model "code.gitea.io/gitea/models/repo" user_model "code.gitea.io/gitea/models/user" "code.gitea.io/gitea/modules/git" + "code.gitea.io/gitea/modules/log" repo_module "code.gitea.io/gitea/modules/repository" "code.gitea.io/gitea/modules/util" "code.gitea.io/gitea/services/pull" @@ -74,7 +77,7 @@ func MergeUpstream(ctx context.Context, doer *user_model.User, repo *repo_model. return "merge", nil } -func GetUpstreamDivergingInfo(ctx context.Context, repo *repo_model.Repository, branch string) (*UpstreamDivergingInfo, error) { +func GetUpstreamDivergingInfo(ctx context.Context, gitRepo *git.Repository, repo *repo_model.Repository, branch string) (*UpstreamDivergingInfo, error) { if !repo.IsFork { return nil, util.NewInvalidArgumentErrorf("repo is not a fork") } @@ -102,10 +105,29 @@ func GetUpstreamDivergingInfo(ctx context.Context, repo *repo_model.Repository, return info, nil } - // TODO: if the fork repo has new commits, this call will fail: - // exit status 128 - fatal: Invalid symmetric difference expression aaaaaaaaaaaa...bbbbbbbbbbbb - // so at the moment, we are not able to handle this case, should be improved in the future - diff, err := git.GetDivergingCommits(ctx, repo.BaseRepo.RepoPath(), baseBranch.CommitID, forkBranch.CommitID) + // Add a temporary remote + tmpRemote := strconv.FormatInt(time.Now().UnixNano(), 10) + if err = gitRepo.AddRemote(tmpRemote, repo.BaseRepo.RepoPath(), false); err != nil { + log.Error("GetUpstreamDivergingInfo: AddRemote: %v", err) + } + defer func() { + if err := gitRepo.RemoveRemote(tmpRemote); err != nil { + log.Error("GetUpstreamDivergingInfo: RemoveRemote: %v", err) + } + }() + + var remoteBranch string + _, remoteBranch, err = gitRepo.GetMergeBase(tmpRemote, baseBranch.CommitID, forkBranch.CommitID) + if err != nil { + log.Error("GetMergeBase: %v", err) + } + + baseBranch.CommitID, err = git.GetFullCommitID(gitRepo.Ctx, gitRepo.Path, remoteBranch) + if err != nil { + baseBranch.CommitID = remoteBranch + } + + diff, err := git.GetDivergingCommits(gitRepo.Ctx, gitRepo.Path, baseBranch.CommitID, forkBranch.CommitID) if err != nil { info.BaseIsNewer = baseBranch.UpdatedUnix > forkBranch.UpdatedUnix return info, nil From 04c2a5e03a4bd415030d620e160b7400ff552a13 Mon Sep 17 00:00:00 2001 From: changchaishi Date: Thu, 9 Jan 2025 09:10:30 +0000 Subject: [PATCH 02/10] avoid using tmp remote for comparison to fork branch --- services/repository/merge_upstream.go | 45 ++++++++++++--------------- 1 file changed, 20 insertions(+), 25 deletions(-) diff --git a/services/repository/merge_upstream.go b/services/repository/merge_upstream.go index cd25101046f0b..d78cc3e2b8d47 100644 --- a/services/repository/merge_upstream.go +++ b/services/repository/merge_upstream.go @@ -6,15 +6,12 @@ package repository import ( "context" "fmt" - "strconv" - "time" git_model "code.gitea.io/gitea/models/git" issue_model "code.gitea.io/gitea/models/issues" repo_model "code.gitea.io/gitea/models/repo" user_model "code.gitea.io/gitea/models/user" "code.gitea.io/gitea/modules/git" - "code.gitea.io/gitea/modules/log" repo_module "code.gitea.io/gitea/modules/repository" "code.gitea.io/gitea/modules/util" "code.gitea.io/gitea/services/pull" @@ -105,31 +102,29 @@ func GetUpstreamDivergingInfo(ctx context.Context, gitRepo *git.Repository, repo return info, nil } - // Add a temporary remote - tmpRemote := strconv.FormatInt(time.Now().UnixNano(), 10) - if err = gitRepo.AddRemote(tmpRemote, repo.BaseRepo.RepoPath(), false); err != nil { - log.Error("GetUpstreamDivergingInfo: AddRemote: %v", err) - } - defer func() { - if err := gitRepo.RemoveRemote(tmpRemote); err != nil { - log.Error("GetUpstreamDivergingInfo: RemoveRemote: %v", err) - } - }() - - var remoteBranch string - _, remoteBranch, err = gitRepo.GetMergeBase(tmpRemote, baseBranch.CommitID, forkBranch.CommitID) - if err != nil { - log.Error("GetMergeBase: %v", err) - } - - baseBranch.CommitID, err = git.GetFullCommitID(gitRepo.Ctx, gitRepo.Path, remoteBranch) - if err != nil { - baseBranch.CommitID = remoteBranch - } - diff, err := git.GetDivergingCommits(gitRepo.Ctx, gitRepo.Path, baseBranch.CommitID, forkBranch.CommitID) if err != nil { info.BaseIsNewer = baseBranch.UpdatedUnix > forkBranch.UpdatedUnix + if !info.BaseIsNewer { + var ( + baseCommitID git.ObjectID + headCommit *git.Commit + ) + + gitRepo.GetCommit(forkBranch.CommitID) + + if baseCommitID, err = gitRepo.ConvertToGitID(baseBranch.CommitID); err != nil { + return info, nil + } + + if headCommit, err = gitRepo.GetCommit(forkBranch.CommitID); err != nil { + return info, nil + } + + if isAncester, _ := headCommit.HasPreviousCommit(baseCommitID); !isAncester { + info.BaseIsNewer = true + } + } return info, nil } info.CommitsBehind, info.CommitsAhead = diff.Behind, diff.Ahead From 1ec4df87c967450dcf5fd6ab482041b4baa08b39 Mon Sep 17 00:00:00 2001 From: changchaishi Date: Thu, 9 Jan 2025 10:12:14 +0000 Subject: [PATCH 03/10] add repo sync fork integration test --- services/repository/merge_upstream.go | 2 - tests/integration/repo_sync_fork_test.go | 71 ++++++++++++++++++++++++ 2 files changed, 71 insertions(+), 2 deletions(-) create mode 100644 tests/integration/repo_sync_fork_test.go diff --git a/services/repository/merge_upstream.go b/services/repository/merge_upstream.go index d78cc3e2b8d47..2c381f0f62416 100644 --- a/services/repository/merge_upstream.go +++ b/services/repository/merge_upstream.go @@ -111,8 +111,6 @@ func GetUpstreamDivergingInfo(ctx context.Context, gitRepo *git.Repository, repo headCommit *git.Commit ) - gitRepo.GetCommit(forkBranch.CommitID) - if baseCommitID, err = gitRepo.ConvertToGitID(baseBranch.CommitID); err != nil { return info, nil } diff --git a/tests/integration/repo_sync_fork_test.go b/tests/integration/repo_sync_fork_test.go new file mode 100644 index 0000000000000..e76003e0120e7 --- /dev/null +++ b/tests/integration/repo_sync_fork_test.go @@ -0,0 +1,71 @@ +// Copyright 2025 The Gitea Authors. All rights reserved. +// SPDX-License-Identifier: MIT + +package integration + +import ( + "fmt" + "net/http" + "net/url" + "strings" + "testing" + "time" + + auth_model "code.gitea.io/gitea/models/auth" + repo_model "code.gitea.io/gitea/models/repo" + "code.gitea.io/gitea/models/unittest" + user_model "code.gitea.io/gitea/models/user" + api "code.gitea.io/gitea/modules/structs" + "code.gitea.io/gitea/modules/util" + + "github.com/stretchr/testify/require" +) + +func TestRepoSyncFork(t *testing.T) { + onGiteaRun(t, func(*testing.T, *url.URL) { + forkUser := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: 4}) + + baseRepo := unittest.AssertExistsAndLoadBean(t, &repo_model.Repository{ID: 1}) + baseUser := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: baseRepo.OwnerID}) + repoString := baseUser.Name + "/" + baseRepo.Name + + session := loginUser(t, forkUser.Name) + token := getTokenForLoggedInUser(t, session, auth_model.AccessTokenScopeWriteRepository) + + checkSyncForkMessage := func(hasMessage bool, message string) { + require.Eventually(t, func() bool { + resp := session.MakeRequest(t, NewRequestf(t, "GET", "/%s/test-repo-fork", forkUser.Name), http.StatusOK) + htmlDoc := NewHTMLParser(t, resp.Body) + respMsg, _ := htmlDoc.Find(".ui.message").Html() + return strings.Contains(respMsg, message) != hasMessage + }, 5*time.Second, 100*time.Millisecond) + } + + // create a fork + req := NewRequestWithJSON(t, "POST", fmt.Sprintf("/api/v1/repos/%s/forks", repoString), &api.CreateForkOption{ + Name: util.ToPointer("test-repo-fork"), + }).AddTokenAuth(token) + MakeRequest(t, req, http.StatusAccepted) + forkRepo := unittest.AssertExistsAndLoadBean(t, &repo_model.Repository{OwnerID: forkUser.ID, Name: "test-repo-fork"}) + + // Case 0: Update fork, should have no sync fork message + require.NoError(t, createOrReplaceFileInBranch(baseUser, baseRepo, "file0.txt", "master", "dummy")) + // the repo shows a prompt to "sync fork" and with precise commit count + checkSyncForkMessage(false, fmt.Sprintf(`%v:master`, repoString, repoString)) + + // Case 2: Base is ahead of fork + require.NoError(t, createOrReplaceFileInBranch(baseUser, baseRepo, "file1.txt", "master", "dummy")) + // the repo shows a prompt to "sync fork" and with precise commit count + checkSyncForkMessage(true, fmt.Sprintf(`This branch is 1 commit behind %v:master`, repoString, repoString)) + + // Case 3: Base has some commits that fork does not have, but fork updated + require.NoError(t, createOrReplaceFileInBranch(forkUser, forkRepo, "file2.txt", "master", "dummy")) + // the repo shows a prompt to "sync fork" and with just "new changes" text + checkSyncForkMessage(true, fmt.Sprintf(`The base branch %v:master has new changes`, repoString, repoString)) + + // Case 4: Base updates again + require.NoError(t, createOrReplaceFileInBranch(forkUser, forkRepo, "file3.txt", "master", "dummy")) + // the repo shows a prompt to "sync fork" and with just "new changes" text + checkSyncForkMessage(true, fmt.Sprintf(`The base branch %v:master has new changes`, repoString, repoString)) + }) +} From cc008dd80d2a992a125a42b82ced3a2b745fa247 Mon Sep 17 00:00:00 2001 From: wxiaoguang Date: Fri, 10 Jan 2025 10:50:55 +0800 Subject: [PATCH 04/10] merge --- modules/structs/repo_branch.go | 8 ++ routers/api/v1/api.go | 1 + routers/api/v1/repo/branch.go | 45 +++++++++ routers/api/v1/swagger/repo.go | 12 +++ templates/swagger/v1_json.tmpl | 78 +++++++++++++++ tests/integration/repo_merge_upstream_test.go | 97 +++++++++++++++++++ tests/integration/repo_sync_fork_test.go | 71 -------------- 7 files changed, 241 insertions(+), 71 deletions(-) create mode 100644 tests/integration/repo_merge_upstream_test.go delete mode 100644 tests/integration/repo_sync_fork_test.go diff --git a/modules/structs/repo_branch.go b/modules/structs/repo_branch.go index a9aa1d330a184..55c98d60b9124 100644 --- a/modules/structs/repo_branch.go +++ b/modules/structs/repo_branch.go @@ -133,3 +133,11 @@ type EditBranchProtectionOption struct { type UpdateBranchProtectionPriories struct { IDs []int64 `json:"ids"` } + +type MergeUpstreamRequest struct { + Branch string `json:"branch"` +} + +type MergeUpstreamResponse struct { + MergeStyle string `json:"merge_type"` +} diff --git a/routers/api/v1/api.go b/routers/api/v1/api.go index 2f943d306cc5c..b1a42a85e6a82 100644 --- a/routers/api/v1/api.go +++ b/routers/api/v1/api.go @@ -1190,6 +1190,7 @@ func Routes() *web.Router { m.Get("/archive/*", reqRepoReader(unit.TypeCode), repo.GetArchive) m.Combo("/forks").Get(repo.ListForks). Post(reqToken(), reqRepoReader(unit.TypeCode), bind(api.CreateForkOption{}), repo.CreateFork) + m.Post("/merge-upstream", reqToken(), mustNotBeArchived, reqRepoWriter(unit.TypeCode), bind(api.MergeUpstreamRequest{}), repo.MergeUpstream) m.Group("/branches", func() { m.Get("", repo.ListBranches) m.Get("/*", repo.GetBranch) diff --git a/routers/api/v1/repo/branch.go b/routers/api/v1/repo/branch.go index 2fcdd0205875a..87d17dba875fc 100644 --- a/routers/api/v1/repo/branch.go +++ b/routers/api/v1/repo/branch.go @@ -18,6 +18,7 @@ import ( "code.gitea.io/gitea/modules/optional" repo_module "code.gitea.io/gitea/modules/repository" api "code.gitea.io/gitea/modules/structs" + "code.gitea.io/gitea/modules/util" "code.gitea.io/gitea/modules/web" "code.gitea.io/gitea/routers/api/v1/utils" "code.gitea.io/gitea/services/context" @@ -1186,3 +1187,47 @@ func UpdateBranchProtectionPriories(ctx *context.APIContext) { ctx.Status(http.StatusNoContent) } + +func MergeUpstream(ctx *context.APIContext) { + // swagger:operation POST /repos/{owner}/{repo}/merge-upstream repository repoMergeUpstream + // --- + // summary: Merge a branch from upstream + // produces: + // - application/json + // parameters: + // - name: owner + // in: path + // description: owner of the repo + // type: string + // required: true + // - name: repo + // in: path + // description: name of the repo + // type: string + // required: true + // - name: body + // in: body + // schema: + // "$ref": "#/definitions/MergeUpstreamRequest" + // responses: + // "200": + // "$ref": "#/responses/MergeUpstreamResponse" + // "400": + // "$ref": "#/responses/error" + // "404": + // "$ref": "#/responses/notFound" + form := web.GetForm(ctx).(*api.MergeUpstreamRequest) + mergeStyle, err := repo_service.MergeUpstream(ctx, ctx.Doer, ctx.Repo.Repository, form.Branch) + if err != nil { + if errors.Is(err, util.ErrInvalidArgument) { + ctx.Error(http.StatusBadRequest, "MergeUpstream", err) + return + } else if errors.Is(err, util.ErrNotExist) { + ctx.Error(http.StatusNotFound, "MergeUpstream", err) + return + } + ctx.Error(http.StatusInternalServerError, "MergeUpstream", err) + return + } + ctx.JSON(http.StatusOK, &api.MergeUpstreamResponse{MergeStyle: mergeStyle}) +} diff --git a/routers/api/v1/swagger/repo.go b/routers/api/v1/swagger/repo.go index b9d2a0217cd4f..f754c80a5b3d5 100644 --- a/routers/api/v1/swagger/repo.go +++ b/routers/api/v1/swagger/repo.go @@ -448,3 +448,15 @@ type swaggerCompare struct { // in:body Body api.Compare `json:"body"` } + +// swagger:response MergeUpstreamRequest +type swaggerMergeUpstreamRequest struct { + // in:body + Body api.MergeUpstreamRequest `json:"body"` +} + +// swagger:response MergeUpstreamResponse +type swaggerMergeUpstreamResponse struct { + // in:body + Body api.MergeUpstreamResponse `json:"body"` +} diff --git a/templates/swagger/v1_json.tmpl b/templates/swagger/v1_json.tmpl index 82a301da2fe99..fb37d45ce8de2 100644 --- a/templates/swagger/v1_json.tmpl +++ b/templates/swagger/v1_json.tmpl @@ -10867,6 +10867,52 @@ } } }, + "/repos/{owner}/{repo}/merge-upstream": { + "post": { + "produces": [ + "application/json" + ], + "tags": [ + "repository" + ], + "summary": "Merge a branch from upstream", + "operationId": "repoMergeUpstream", + "parameters": [ + { + "type": "string", + "description": "owner of the repo", + "name": "owner", + "in": "path", + "required": true + }, + { + "type": "string", + "description": "name of the repo", + "name": "repo", + "in": "path", + "required": true + }, + { + "name": "body", + "in": "body", + "schema": { + "$ref": "#/definitions/MergeUpstreamRequest" + } + } + ], + "responses": { + "200": { + "$ref": "#/responses/MergeUpstreamResponse" + }, + "400": { + "$ref": "#/responses/error" + }, + "404": { + "$ref": "#/responses/notFound" + } + } + } + }, "/repos/{owner}/{repo}/milestones": { "get": { "produces": [ @@ -22827,6 +22873,26 @@ "x-go-name": "MergePullRequestForm", "x-go-package": "code.gitea.io/gitea/services/forms" }, + "MergeUpstreamRequest": { + "type": "object", + "properties": { + "branch": { + "type": "string", + "x-go-name": "Branch" + } + }, + "x-go-package": "code.gitea.io/gitea/modules/structs" + }, + "MergeUpstreamResponse": { + "type": "object", + "properties": { + "merge_type": { + "type": "string", + "x-go-name": "MergeStyle" + } + }, + "x-go-package": "code.gitea.io/gitea/modules/structs" + }, "MigrateRepoOptions": { "description": "MigrateRepoOptions options for migrating repository's\nthis is used to interact with api v1", "type": "object", @@ -26008,6 +26074,18 @@ "type": "string" } }, + "MergeUpstreamRequest": { + "description": "", + "schema": { + "$ref": "#/definitions/MergeUpstreamRequest" + } + }, + "MergeUpstreamResponse": { + "description": "", + "schema": { + "$ref": "#/definitions/MergeUpstreamResponse" + } + }, "Milestone": { "description": "Milestone", "schema": { diff --git a/tests/integration/repo_merge_upstream_test.go b/tests/integration/repo_merge_upstream_test.go new file mode 100644 index 0000000000000..a6de31e432aa6 --- /dev/null +++ b/tests/integration/repo_merge_upstream_test.go @@ -0,0 +1,97 @@ +// Copyright 2025 The Gitea Authors. All rights reserved. +// SPDX-License-Identifier: MIT + +package integration + +import ( + "fmt" + "net/http" + "net/url" + "strings" + "testing" + "time" + + auth_model "code.gitea.io/gitea/models/auth" + repo_model "code.gitea.io/gitea/models/repo" + "code.gitea.io/gitea/models/unittest" + user_model "code.gitea.io/gitea/models/user" + api "code.gitea.io/gitea/modules/structs" + "code.gitea.io/gitea/modules/util" + + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" +) + +func TestRepoMergeUpstream(t *testing.T) { + onGiteaRun(t, func(*testing.T, *url.URL) { + forkUser := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: 4}) + + baseRepo := unittest.AssertExistsAndLoadBean(t, &repo_model.Repository{ID: 1}) + baseUser := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: baseRepo.OwnerID}) + + checkFileContent := func(exp string) { + req := NewRequest(t, "GET", fmt.Sprintf("/%s/test-repo-fork/raw/branch/master/new-file.txt", forkUser.Name)) + resp := MakeRequest(t, req, http.StatusOK) + require.Equal(t, exp, resp.Body.String()) + } + + session := loginUser(t, forkUser.Name) + token := getTokenForLoggedInUser(t, session, auth_model.AccessTokenScopeWriteRepository) + + // create a fork + req := NewRequestWithJSON(t, "POST", fmt.Sprintf("/api/v1/repos/%s/%s/forks", baseUser.Name, baseRepo.Name), &api.CreateForkOption{ + Name: util.ToPointer("test-repo-fork"), + }).AddTokenAuth(token) + MakeRequest(t, req, http.StatusAccepted) + forkRepo := unittest.AssertExistsAndLoadBean(t, &repo_model.Repository{OwnerID: forkUser.ID, Name: "test-repo-fork"}) + + t.Run("HeadBeforeBase", func(t *testing.T) { + // add a file in base repo + require.NoError(t, createOrReplaceFileInBranch(baseUser, baseRepo, "new-file.txt", "master", "test-content-1")) + + // the repo shows a prompt to "sync fork" + var mergeUpstreamLink string + require.Eventually(t, func() bool { + resp := session.MakeRequest(t, NewRequestf(t, "GET", "/%s/test-repo-fork", forkUser.Name), http.StatusOK) + htmlDoc := NewHTMLParser(t, resp.Body) + respMsg, _ := htmlDoc.Find(".ui.message").Html() + if !strings.Contains(respMsg, `This branch is 1 commit behind user2/repo1:master`) { + return false + } + mergeUpstreamLink = htmlDoc.Find("button[data-url*='merge-upstream']").AttrOr("data-url", "") + require.NotEmpty(t, mergeUpstreamLink) + return true + }, 5*time.Second, 100*time.Millisecond) + + // click the "sync fork" button + req = NewRequestWithValues(t, "POST", mergeUpstreamLink, map[string]string{"_csrf": GetUserCSRFToken(t, session)}) + session.MakeRequest(t, req, http.StatusOK) + checkFileContent("test-content-1") + }) + + t.Run("BaseChangeAfterHeadChange", func(t *testing.T) { + // update the files: base first, head later, and check the prompt + require.NoError(t, createOrReplaceFileInBranch(baseUser, baseRepo, "new-file.txt", "master", "test-content-2")) + require.NoError(t, createOrReplaceFileInBranch(forkUser, forkRepo, "new-file-other.txt", "master", "test-content-other")) + + // the repo shows a prompt to "sync fork" + require.Eventually(t, func() bool { + resp := session.MakeRequest(t, NewRequestf(t, "GET", "/%s/test-repo-fork", forkUser.Name), http.StatusOK) + htmlDoc := NewHTMLParser(t, resp.Body) + respMsg, _ := htmlDoc.Find(".ui.message:not(.positive)").Html() + return strings.Contains(respMsg, `The base branch user2/repo1:master has new changes`) + }, 5*time.Second, 100*time.Millisecond) + + // and do the merge-upstream by API + req = NewRequestWithJSON(t, "POST", fmt.Sprintf("/api/v1/repos/%s/test-repo-fork/merge-upstream", forkUser.Name), &api.MergeUpstreamRequest{ + Branch: "master", + }).AddTokenAuth(token) + resp := MakeRequest(t, req, http.StatusOK) + checkFileContent("test-content-2") + + var mergeResp api.MergeUpstreamResponse + DecodeJSON(t, resp, &mergeResp) + assert.Equal(t, "merge", mergeResp.MergeStyle) + }) + }) +} diff --git a/tests/integration/repo_sync_fork_test.go b/tests/integration/repo_sync_fork_test.go deleted file mode 100644 index e76003e0120e7..0000000000000 --- a/tests/integration/repo_sync_fork_test.go +++ /dev/null @@ -1,71 +0,0 @@ -// Copyright 2025 The Gitea Authors. All rights reserved. -// SPDX-License-Identifier: MIT - -package integration - -import ( - "fmt" - "net/http" - "net/url" - "strings" - "testing" - "time" - - auth_model "code.gitea.io/gitea/models/auth" - repo_model "code.gitea.io/gitea/models/repo" - "code.gitea.io/gitea/models/unittest" - user_model "code.gitea.io/gitea/models/user" - api "code.gitea.io/gitea/modules/structs" - "code.gitea.io/gitea/modules/util" - - "github.com/stretchr/testify/require" -) - -func TestRepoSyncFork(t *testing.T) { - onGiteaRun(t, func(*testing.T, *url.URL) { - forkUser := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: 4}) - - baseRepo := unittest.AssertExistsAndLoadBean(t, &repo_model.Repository{ID: 1}) - baseUser := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: baseRepo.OwnerID}) - repoString := baseUser.Name + "/" + baseRepo.Name - - session := loginUser(t, forkUser.Name) - token := getTokenForLoggedInUser(t, session, auth_model.AccessTokenScopeWriteRepository) - - checkSyncForkMessage := func(hasMessage bool, message string) { - require.Eventually(t, func() bool { - resp := session.MakeRequest(t, NewRequestf(t, "GET", "/%s/test-repo-fork", forkUser.Name), http.StatusOK) - htmlDoc := NewHTMLParser(t, resp.Body) - respMsg, _ := htmlDoc.Find(".ui.message").Html() - return strings.Contains(respMsg, message) != hasMessage - }, 5*time.Second, 100*time.Millisecond) - } - - // create a fork - req := NewRequestWithJSON(t, "POST", fmt.Sprintf("/api/v1/repos/%s/forks", repoString), &api.CreateForkOption{ - Name: util.ToPointer("test-repo-fork"), - }).AddTokenAuth(token) - MakeRequest(t, req, http.StatusAccepted) - forkRepo := unittest.AssertExistsAndLoadBean(t, &repo_model.Repository{OwnerID: forkUser.ID, Name: "test-repo-fork"}) - - // Case 0: Update fork, should have no sync fork message - require.NoError(t, createOrReplaceFileInBranch(baseUser, baseRepo, "file0.txt", "master", "dummy")) - // the repo shows a prompt to "sync fork" and with precise commit count - checkSyncForkMessage(false, fmt.Sprintf(`%v:master`, repoString, repoString)) - - // Case 2: Base is ahead of fork - require.NoError(t, createOrReplaceFileInBranch(baseUser, baseRepo, "file1.txt", "master", "dummy")) - // the repo shows a prompt to "sync fork" and with precise commit count - checkSyncForkMessage(true, fmt.Sprintf(`This branch is 1 commit behind %v:master`, repoString, repoString)) - - // Case 3: Base has some commits that fork does not have, but fork updated - require.NoError(t, createOrReplaceFileInBranch(forkUser, forkRepo, "file2.txt", "master", "dummy")) - // the repo shows a prompt to "sync fork" and with just "new changes" text - checkSyncForkMessage(true, fmt.Sprintf(`The base branch %v:master has new changes`, repoString, repoString)) - - // Case 4: Base updates again - require.NoError(t, createOrReplaceFileInBranch(forkUser, forkRepo, "file3.txt", "master", "dummy")) - // the repo shows a prompt to "sync fork" and with just "new changes" text - checkSyncForkMessage(true, fmt.Sprintf(`The base branch %v:master has new changes`, repoString, repoString)) - }) -} From 69fb07bbc75dd248a42028c0581adc1a385dcd95 Mon Sep 17 00:00:00 2001 From: wxiaoguang Date: Fri, 10 Jan 2025 11:28:34 +0800 Subject: [PATCH 05/10] use base repo's default branch to sync --- services/repository/merge_upstream.go | 42 ++++++++++--------- tests/integration/repo_merge_upstream_test.go | 31 ++++++++++---- 2 files changed, 45 insertions(+), 28 deletions(-) diff --git a/services/repository/merge_upstream.go b/services/repository/merge_upstream.go index 2c381f0f62416..3053f1c49083d 100644 --- a/services/repository/merge_upstream.go +++ b/services/repository/merge_upstream.go @@ -23,6 +23,7 @@ type UpstreamDivergingInfo struct { CommitsAhead int } +// MergeUpstream merges the base repository's default branch into the fork repository's current branch. func MergeUpstream(ctx context.Context, doer *user_model.User, repo *repo_model.Repository, branch string) (mergeStyle string, err error) { if err = repo.MustNotBeArchived(); err != nil { return "", err @@ -32,7 +33,7 @@ func MergeUpstream(ctx context.Context, doer *user_model.User, repo *repo_model. } err = git.Push(ctx, repo.BaseRepo.RepoPath(), git.PushOptions{ Remote: repo.RepoPath(), - Branch: fmt.Sprintf("%s:%s", branch, branch), + Branch: fmt.Sprintf("%s:%s", repo.BaseRepo.DefaultBranch, branch), Env: repo_module.PushingEnvironment(doer, repo), }) if err == nil { @@ -64,7 +65,7 @@ func MergeUpstream(ctx context.Context, doer *user_model.User, repo *repo_model. BaseRepoID: repo.BaseRepo.ID, BaseRepo: repo.BaseRepo, HeadBranch: branch, // maybe HeadCommitID is not needed - BaseBranch: branch, + BaseBranch: repo.BaseRepo.DefaultBranch, } fakeIssue.PullRequest = fakePR err = pull.Update(ctx, fakePR, doer, "merge upstream", false) @@ -74,6 +75,7 @@ func MergeUpstream(ctx context.Context, doer *user_model.User, repo *repo_model. return "merge", nil } +// GetUpstreamDivergingInfo returns the information about the divergence between the fork repository's branch and the base repository's default branch. func GetUpstreamDivergingInfo(ctx context.Context, gitRepo *git.Repository, repo *repo_model.Repository, branch string) (*UpstreamDivergingInfo, error) { if !repo.IsFork { return nil, util.NewInvalidArgumentErrorf("repo is not a fork") @@ -92,7 +94,7 @@ func GetUpstreamDivergingInfo(ctx context.Context, gitRepo *git.Repository, repo return nil, err } - baseBranch, err := git_model.GetBranch(ctx, repo.BaseRepo.ID, branch) + baseBranch, err := git_model.GetBranch(ctx, repo.BaseRepo.ID, repo.BaseRepo.DefaultBranch) if err != nil { return nil, err } @@ -102,26 +104,26 @@ func GetUpstreamDivergingInfo(ctx context.Context, gitRepo *git.Repository, repo return info, nil } + // if the fork repo has new commits, this call will fail because they are not in the base repo + // exit status 128 - fatal: Invalid symmetric difference expression aaaaaaaaaaaa...bbbbbbbbbbbb + // so at the moment, we first check the update time, then check whether the head branch has base's head diff, err := git.GetDivergingCommits(gitRepo.Ctx, gitRepo.Path, baseBranch.CommitID, forkBranch.CommitID) if err != nil { info.BaseIsNewer = baseBranch.UpdatedUnix > forkBranch.UpdatedUnix - if !info.BaseIsNewer { - var ( - baseCommitID git.ObjectID - headCommit *git.Commit - ) - - if baseCommitID, err = gitRepo.ConvertToGitID(baseBranch.CommitID); err != nil { - return info, nil - } - - if headCommit, err = gitRepo.GetCommit(forkBranch.CommitID); err != nil { - return info, nil - } - - if isAncester, _ := headCommit.HasPreviousCommit(baseCommitID); !isAncester { - info.BaseIsNewer = true - } + if info.BaseIsNewer { + return info, nil + } + baseCommitID, err := gitRepo.ConvertToGitID(baseBranch.CommitID) + if err != nil { + return nil, err + } + headCommit, err := gitRepo.GetCommit(forkBranch.CommitID) + if err != nil { + return nil, err + } + info.BaseIsNewer, err = headCommit.HasPreviousCommit(baseCommitID) + if err != nil { + return nil, err } return info, nil } diff --git a/tests/integration/repo_merge_upstream_test.go b/tests/integration/repo_merge_upstream_test.go index a6de31e432aa6..2c2f9653720c2 100644 --- a/tests/integration/repo_merge_upstream_test.go +++ b/tests/integration/repo_merge_upstream_test.go @@ -12,6 +12,8 @@ import ( "time" auth_model "code.gitea.io/gitea/models/auth" + "code.gitea.io/gitea/models/db" + git_model "code.gitea.io/gitea/models/git" repo_model "code.gitea.io/gitea/models/repo" "code.gitea.io/gitea/models/unittest" user_model "code.gitea.io/gitea/models/user" @@ -29,8 +31,8 @@ func TestRepoMergeUpstream(t *testing.T) { baseRepo := unittest.AssertExistsAndLoadBean(t, &repo_model.Repository{ID: 1}) baseUser := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: baseRepo.OwnerID}) - checkFileContent := func(exp string) { - req := NewRequest(t, "GET", fmt.Sprintf("/%s/test-repo-fork/raw/branch/master/new-file.txt", forkUser.Name)) + checkFileContent := func(branch, exp string) { + req := NewRequest(t, "GET", fmt.Sprintf("/%s/test-repo-fork/raw/branch/%s/new-file.txt", branch, forkUser.Name)) resp := MakeRequest(t, req, http.StatusOK) require.Equal(t, exp, resp.Body.String()) } @@ -45,6 +47,13 @@ func TestRepoMergeUpstream(t *testing.T) { MakeRequest(t, req, http.StatusAccepted) forkRepo := unittest.AssertExistsAndLoadBean(t, &repo_model.Repository{OwnerID: forkUser.ID, Name: "test-repo-fork"}) + // create fork-branch + req = NewRequestWithValues(t, "POST", fmt.Sprintf("/%s/test-repo-fork/branches/_new/branch/master", forkUser.Name), map[string]string{ + "_csrf": GetUserCSRFToken(t, session), + "new_branch_name": "fork-branch", + }) + session.MakeRequest(t, req, http.StatusSeeOther) + t.Run("HeadBeforeBase", func(t *testing.T) { // add a file in base repo require.NoError(t, createOrReplaceFileInBranch(baseUser, baseRepo, "new-file.txt", "master", "test-content-1")) @@ -52,7 +61,7 @@ func TestRepoMergeUpstream(t *testing.T) { // the repo shows a prompt to "sync fork" var mergeUpstreamLink string require.Eventually(t, func() bool { - resp := session.MakeRequest(t, NewRequestf(t, "GET", "/%s/test-repo-fork", forkUser.Name), http.StatusOK) + resp := session.MakeRequest(t, NewRequestf(t, "GET", "/%s/test-repo-fork/src/branch/fork-branch", forkUser.Name), http.StatusOK) htmlDoc := NewHTMLParser(t, resp.Body) respMsg, _ := htmlDoc.Find(".ui.message").Html() if !strings.Contains(respMsg, `This branch is 1 commit behind user2/repo1:master`) { @@ -66,17 +75,23 @@ func TestRepoMergeUpstream(t *testing.T) { // click the "sync fork" button req = NewRequestWithValues(t, "POST", mergeUpstreamLink, map[string]string{"_csrf": GetUserCSRFToken(t, session)}) session.MakeRequest(t, req, http.StatusOK) - checkFileContent("test-content-1") + checkFileContent("fork-branch", "test-content-1") }) t.Run("BaseChangeAfterHeadChange", func(t *testing.T) { // update the files: base first, head later, and check the prompt require.NoError(t, createOrReplaceFileInBranch(baseUser, baseRepo, "new-file.txt", "master", "test-content-2")) - require.NoError(t, createOrReplaceFileInBranch(forkUser, forkRepo, "new-file-other.txt", "master", "test-content-other")) + require.NoError(t, createOrReplaceFileInBranch(forkUser, forkRepo, "new-file-other.txt", "fork-branch", "test-content-other")) + + // make sure the base branch's update time is before the fork, to make it test the complete logic + baseBranch := unittest.AssertExistsAndLoadBean(t, &git_model.Branch{RepoID: baseRepo.ID, Name: "master"}) + forkBranch := unittest.AssertExistsAndLoadBean(t, &git_model.Branch{RepoID: forkRepo.ID, Name: "fork-branch"}) + _, err := db.GetEngine(db.DefaultContext).ID(forkBranch.ID).Update(&git_model.Branch{UpdatedUnix: baseBranch.UpdatedUnix + 1}) + require.NoError(t, err) // the repo shows a prompt to "sync fork" require.Eventually(t, func() bool { - resp := session.MakeRequest(t, NewRequestf(t, "GET", "/%s/test-repo-fork", forkUser.Name), http.StatusOK) + resp := session.MakeRequest(t, NewRequestf(t, "GET", "/%s/test-repo-fork/src/branch/fork-branch", forkUser.Name), http.StatusOK) htmlDoc := NewHTMLParser(t, resp.Body) respMsg, _ := htmlDoc.Find(".ui.message:not(.positive)").Html() return strings.Contains(respMsg, `The base branch user2/repo1:master has new changes`) @@ -84,10 +99,10 @@ func TestRepoMergeUpstream(t *testing.T) { // and do the merge-upstream by API req = NewRequestWithJSON(t, "POST", fmt.Sprintf("/api/v1/repos/%s/test-repo-fork/merge-upstream", forkUser.Name), &api.MergeUpstreamRequest{ - Branch: "master", + Branch: "fork-branch", }).AddTokenAuth(token) resp := MakeRequest(t, req, http.StatusOK) - checkFileContent("test-content-2") + checkFileContent("fork-branch", "test-content-2") var mergeResp api.MergeUpstreamResponse DecodeJSON(t, resp, &mergeResp) From 93d9efdb45cd59654dd4d5efa4b4a8dc9ab19b94 Mon Sep 17 00:00:00 2001 From: wxiaoguang Date: Fri, 10 Jan 2025 11:45:12 +0800 Subject: [PATCH 06/10] fix git repo open --- routers/web/repo/view_home.go | 2 +- services/repository/merge_upstream.go | 24 ++++++++++++++++-------- 2 files changed, 17 insertions(+), 9 deletions(-) diff --git a/routers/web/repo/view_home.go b/routers/web/repo/view_home.go index 9041e0d2010e7..8c9f54656b0c0 100644 --- a/routers/web/repo/view_home.go +++ b/routers/web/repo/view_home.go @@ -181,7 +181,7 @@ func prepareUpstreamDivergingInfo(ctx *context.Context) { if !ctx.Repo.Repository.IsFork || !ctx.Repo.IsViewBranch || ctx.Repo.TreePath != "" { return } - upstreamDivergingInfo, err := repo_service.GetUpstreamDivergingInfo(ctx, ctx.Repo.GitRepo, ctx.Repo.Repository, ctx.Repo.BranchName) + upstreamDivergingInfo, err := repo_service.GetUpstreamDivergingInfo(ctx, ctx.Repo.Repository, ctx.Repo.BranchName) if err != nil { if !errors.Is(err, util.ErrNotExist) && !errors.Is(err, util.ErrInvalidArgument) { log.Error("GetUpstreamDivergingInfo: %v", err) diff --git a/services/repository/merge_upstream.go b/services/repository/merge_upstream.go index 3053f1c49083d..c061a9f435b56 100644 --- a/services/repository/merge_upstream.go +++ b/services/repository/merge_upstream.go @@ -12,7 +12,9 @@ import ( repo_model "code.gitea.io/gitea/models/repo" user_model "code.gitea.io/gitea/models/user" "code.gitea.io/gitea/modules/git" + "code.gitea.io/gitea/modules/gitrepo" repo_module "code.gitea.io/gitea/modules/repository" + "code.gitea.io/gitea/modules/reqctx" "code.gitea.io/gitea/modules/util" "code.gitea.io/gitea/services/pull" ) @@ -76,7 +78,7 @@ func MergeUpstream(ctx context.Context, doer *user_model.User, repo *repo_model. } // GetUpstreamDivergingInfo returns the information about the divergence between the fork repository's branch and the base repository's default branch. -func GetUpstreamDivergingInfo(ctx context.Context, gitRepo *git.Repository, repo *repo_model.Repository, branch string) (*UpstreamDivergingInfo, error) { +func GetUpstreamDivergingInfo(ctx reqctx.RequestContext, repo *repo_model.Repository, branch string) (*UpstreamDivergingInfo, error) { if !repo.IsFork { return nil, util.NewInvalidArgumentErrorf("repo is not a fork") } @@ -107,24 +109,30 @@ func GetUpstreamDivergingInfo(ctx context.Context, gitRepo *git.Repository, repo // if the fork repo has new commits, this call will fail because they are not in the base repo // exit status 128 - fatal: Invalid symmetric difference expression aaaaaaaaaaaa...bbbbbbbbbbbb // so at the moment, we first check the update time, then check whether the head branch has base's head - diff, err := git.GetDivergingCommits(gitRepo.Ctx, gitRepo.Path, baseBranch.CommitID, forkBranch.CommitID) + diff, err := git.GetDivergingCommits(ctx, repo.BaseRepo.RepoPath(), baseBranch.CommitID, forkBranch.CommitID) if err != nil { - info.BaseIsNewer = baseBranch.UpdatedUnix > forkBranch.UpdatedUnix - if info.BaseIsNewer { - return info, nil + baseGitRepo, err := gitrepo.RepositoryFromRequestContextOrOpen(ctx, repo.BaseRepo) + if err != nil { + return nil, err } - baseCommitID, err := gitRepo.ConvertToGitID(baseBranch.CommitID) + headGitRepo, err := gitrepo.RepositoryFromRequestContextOrOpen(ctx, repo) if err != nil { return nil, err } - headCommit, err := gitRepo.GetCommit(forkBranch.CommitID) + + info.BaseIsNewer = baseBranch.UpdatedUnix > forkBranch.UpdatedUnix + if info.BaseIsNewer { + return info, nil + } + baseCommitID, err := baseGitRepo.ConvertToGitID(baseBranch.CommitID) if err != nil { return nil, err } - info.BaseIsNewer, err = headCommit.HasPreviousCommit(baseCommitID) + headCommit, err := headGitRepo.GetCommit(forkBranch.CommitID) if err != nil { return nil, err } + info.BaseIsNewer, _ = headCommit.HasPreviousCommit(baseCommitID) return info, nil } info.CommitsBehind, info.CommitsAhead = diff.Behind, diff.Ahead From d87dfbf33451e239fd0a6c5117633eea57c61c0d Mon Sep 17 00:00:00 2001 From: wxiaoguang Date: Fri, 10 Jan 2025 12:05:25 +0800 Subject: [PATCH 07/10] fix tests --- services/repository/merge_upstream.go | 14 +++++++------ .../repo/code/upstream_diverging_info.tmpl | 6 +++--- tests/integration/repo_merge_upstream_test.go | 21 +++++++++++++++---- 3 files changed, 28 insertions(+), 13 deletions(-) diff --git a/services/repository/merge_upstream.go b/services/repository/merge_upstream.go index c061a9f435b56..1a0549f83a193 100644 --- a/services/repository/merge_upstream.go +++ b/services/repository/merge_upstream.go @@ -20,9 +20,9 @@ import ( ) type UpstreamDivergingInfo struct { - BaseIsNewer bool - CommitsBehind int - CommitsAhead int + BaseHasNewCommits bool + CommitsBehind int + CommitsAhead int } // MergeUpstream merges the base repository's default branch into the fork repository's current branch. @@ -120,8 +120,8 @@ func GetUpstreamDivergingInfo(ctx reqctx.RequestContext, repo *repo_model.Reposi return nil, err } - info.BaseIsNewer = baseBranch.UpdatedUnix > forkBranch.UpdatedUnix - if info.BaseIsNewer { + info.BaseHasNewCommits = baseBranch.UpdatedUnix > forkBranch.UpdatedUnix + if info.BaseHasNewCommits { return info, nil } baseCommitID, err := baseGitRepo.ConvertToGitID(baseBranch.CommitID) @@ -132,9 +132,11 @@ func GetUpstreamDivergingInfo(ctx reqctx.RequestContext, repo *repo_model.Reposi if err != nil { return nil, err } - info.BaseIsNewer, _ = headCommit.HasPreviousCommit(baseCommitID) + hasPreviousCommit, _ := headCommit.HasPreviousCommit(baseCommitID) + info.BaseHasNewCommits = !hasPreviousCommit return info, nil } + info.CommitsBehind, info.CommitsAhead = diff.Behind, diff.Ahead return info, nil } diff --git a/templates/repo/code/upstream_diverging_info.tmpl b/templates/repo/code/upstream_diverging_info.tmpl index 51402598f95cb..bdcd99a7f7e22 100644 --- a/templates/repo/code/upstream_diverging_info.tmpl +++ b/templates/repo/code/upstream_diverging_info.tmpl @@ -1,8 +1,8 @@ -{{if and .UpstreamDivergingInfo (or .UpstreamDivergingInfo.BaseIsNewer .UpstreamDivergingInfo.CommitsBehind)}} +{{if and .UpstreamDivergingInfo (or .UpstreamDivergingInfo.BaseHasNewCommits .UpstreamDivergingInfo.CommitsBehind)}}
- {{$upstreamLink := printf "%s/src/branch/%s" .Repository.BaseRepo.Link (.BranchName|PathEscapeSegments)}} - {{$upstreamHtml := HTMLFormat `%s:%s` $upstreamLink .Repository.BaseRepo.FullName .BranchName}} + {{$upstreamLink := printf "%s/src/branch/%s" .Repository.BaseRepo.Link (.Repository.BaseRepo.DefaultBranch|PathEscapeSegments)}} + {{$upstreamHtml := HTMLFormat `%s:%s` $upstreamLink .Repository.BaseRepo.FullName .Repository.BaseRepo.DefaultBranch}} {{if .UpstreamDivergingInfo.CommitsBehind}} {{ctx.Locale.TrN .UpstreamDivergingInfo.CommitsBehind "repo.pulls.upstream_diverging_prompt_behind_1" "repo.pulls.upstream_diverging_prompt_behind_n" .UpstreamDivergingInfo.CommitsBehind $upstreamHtml}} {{else}} diff --git a/tests/integration/repo_merge_upstream_test.go b/tests/integration/repo_merge_upstream_test.go index 2c2f9653720c2..95c90c58f7d79 100644 --- a/tests/integration/repo_merge_upstream_test.go +++ b/tests/integration/repo_merge_upstream_test.go @@ -32,7 +32,7 @@ func TestRepoMergeUpstream(t *testing.T) { baseUser := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: baseRepo.OwnerID}) checkFileContent := func(branch, exp string) { - req := NewRequest(t, "GET", fmt.Sprintf("/%s/test-repo-fork/raw/branch/%s/new-file.txt", branch, forkUser.Name)) + req := NewRequest(t, "GET", fmt.Sprintf("/%s/test-repo-fork/raw/branch/%s/new-file.txt", forkUser.Name, branch)) resp := MakeRequest(t, req, http.StatusOK) require.Equal(t, exp, resp.Body.String()) } @@ -54,6 +54,10 @@ func TestRepoMergeUpstream(t *testing.T) { }) session.MakeRequest(t, req, http.StatusSeeOther) + queryMergeUpstreamButtonLink := func(htmlDoc *HTMLDoc) string { + return htmlDoc.Find(`button[data-url*="merge-upstream"]`).AttrOr("data-url", "") + } + t.Run("HeadBeforeBase", func(t *testing.T) { // add a file in base repo require.NoError(t, createOrReplaceFileInBranch(baseUser, baseRepo, "new-file.txt", "master", "test-content-1")) @@ -63,12 +67,14 @@ func TestRepoMergeUpstream(t *testing.T) { require.Eventually(t, func() bool { resp := session.MakeRequest(t, NewRequestf(t, "GET", "/%s/test-repo-fork/src/branch/fork-branch", forkUser.Name), http.StatusOK) htmlDoc := NewHTMLParser(t, resp.Body) - respMsg, _ := htmlDoc.Find(".ui.message").Html() + mergeUpstreamLink = queryMergeUpstreamButtonLink(htmlDoc) + if mergeUpstreamLink == "" { + return false + } + respMsg, _ := htmlDoc.Find(".ui.message:not(.positive)").Html() if !strings.Contains(respMsg, `This branch is 1 commit behind user2/repo1:master`) { return false } - mergeUpstreamLink = htmlDoc.Find("button[data-url*='merge-upstream']").AttrOr("data-url", "") - require.NotEmpty(t, mergeUpstreamLink) return true }, 5*time.Second, 100*time.Millisecond) @@ -107,6 +113,13 @@ func TestRepoMergeUpstream(t *testing.T) { var mergeResp api.MergeUpstreamResponse DecodeJSON(t, resp, &mergeResp) assert.Equal(t, "merge", mergeResp.MergeStyle) + + // after merge, there should be no "sync fork" button anymore + require.Eventually(t, func() bool { + resp := session.MakeRequest(t, NewRequestf(t, "GET", "/%s/test-repo-fork/src/branch/fork-branch", forkUser.Name), http.StatusOK) + htmlDoc := NewHTMLParser(t, resp.Body) + return queryMergeUpstreamButtonLink(htmlDoc) == "" + }, 5*time.Second, 100*time.Millisecond) }) }) } From 1ca671b478c6f240fd7def42dd45289db3dc9d8d Mon Sep 17 00:00:00 2001 From: wxiaoguang Date: Fri, 10 Jan 2025 12:12:03 +0800 Subject: [PATCH 08/10] fine tune --- services/repository/merge_upstream.go | 10 ++++++---- 1 file changed, 6 insertions(+), 4 deletions(-) diff --git a/services/repository/merge_upstream.go b/services/repository/merge_upstream.go index 1a0549f83a193..60d3c9a784896 100644 --- a/services/repository/merge_upstream.go +++ b/services/repository/merge_upstream.go @@ -111,6 +111,12 @@ func GetUpstreamDivergingInfo(ctx reqctx.RequestContext, repo *repo_model.Reposi // so at the moment, we first check the update time, then check whether the head branch has base's head diff, err := git.GetDivergingCommits(ctx, repo.BaseRepo.RepoPath(), baseBranch.CommitID, forkBranch.CommitID) if err != nil { + info.BaseHasNewCommits = baseBranch.UpdatedUnix > forkBranch.UpdatedUnix + if info.BaseHasNewCommits { + return info, nil + } + + // if the base's update time is before the fork, check whether the base's head is in the fork baseGitRepo, err := gitrepo.RepositoryFromRequestContextOrOpen(ctx, repo.BaseRepo) if err != nil { return nil, err @@ -120,10 +126,6 @@ func GetUpstreamDivergingInfo(ctx reqctx.RequestContext, repo *repo_model.Reposi return nil, err } - info.BaseHasNewCommits = baseBranch.UpdatedUnix > forkBranch.UpdatedUnix - if info.BaseHasNewCommits { - return info, nil - } baseCommitID, err := baseGitRepo.ConvertToGitID(baseBranch.CommitID) if err != nil { return nil, err From 491bc53bcf007c14cfc76a41fcb728db46c94801 Mon Sep 17 00:00:00 2001 From: wxiaoguang Date: Fri, 10 Jan 2025 12:13:00 +0800 Subject: [PATCH 09/10] fix comment --- services/repository/merge_upstream.go | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/services/repository/merge_upstream.go b/services/repository/merge_upstream.go index 60d3c9a784896..ef161889c09d5 100644 --- a/services/repository/merge_upstream.go +++ b/services/repository/merge_upstream.go @@ -108,7 +108,7 @@ func GetUpstreamDivergingInfo(ctx reqctx.RequestContext, repo *repo_model.Reposi // if the fork repo has new commits, this call will fail because they are not in the base repo // exit status 128 - fatal: Invalid symmetric difference expression aaaaaaaaaaaa...bbbbbbbbbbbb - // so at the moment, we first check the update time, then check whether the head branch has base's head + // so at the moment, we first check the update time, then check whether the fork branch has base's head diff, err := git.GetDivergingCommits(ctx, repo.BaseRepo.RepoPath(), baseBranch.CommitID, forkBranch.CommitID) if err != nil { info.BaseHasNewCommits = baseBranch.UpdatedUnix > forkBranch.UpdatedUnix From dd352517d5ca08845a2f5de787f0fb06ca12f6ef Mon Sep 17 00:00:00 2001 From: wxiaoguang Date: Fri, 10 Jan 2025 12:23:13 +0800 Subject: [PATCH 10/10] fix lint --- tests/integration/repo_merge_upstream_test.go | 5 +---- 1 file changed, 1 insertion(+), 4 deletions(-) diff --git a/tests/integration/repo_merge_upstream_test.go b/tests/integration/repo_merge_upstream_test.go index 95c90c58f7d79..e3e423c51d5d2 100644 --- a/tests/integration/repo_merge_upstream_test.go +++ b/tests/integration/repo_merge_upstream_test.go @@ -72,10 +72,7 @@ func TestRepoMergeUpstream(t *testing.T) { return false } respMsg, _ := htmlDoc.Find(".ui.message:not(.positive)").Html() - if !strings.Contains(respMsg, `This branch is 1 commit behind user2/repo1:master`) { - return false - } - return true + return strings.Contains(respMsg, `This branch is 1 commit behind user2/repo1:master`) }, 5*time.Second, 100*time.Millisecond) // click the "sync fork" button