diff --git a/routers/web/repo/pull.go b/routers/web/repo/pull.go index 87efc3091b7..23ad59dae84 100644 --- a/routers/web/repo/pull.go +++ b/routers/web/repo/pull.go @@ -1308,7 +1308,7 @@ func PullsNewRedirect(ctx *context.Context) { return } redirectRepo = repo.BaseRepo - branch = fmt.Sprintf("%s:%s", repo.OwnerName, branch) + branch = context.CompareHeadRef(repo, branch) } ctx.Redirect(fmt.Sprintf("%s/compare/%s...%s?expand=1", redirectRepo.Link(), util.PathEscapeSegments(redirectRepo.DefaultBranch), util.PathEscapeSegments(branch))) } diff --git a/services/context/repo.go b/services/context/repo.go index 1c945dea5d2..f79ab39cc74 100644 --- a/services/context/repo.go +++ b/services/context/repo.go @@ -64,11 +64,15 @@ func (prc *PullRequestContext) CanCreateNewPull() bool { return can } +// CompareHeadRef formats the head side of a compare link, "owner/repo:branch" is only needed when a fork can share its base repo's owner +func CompareHeadRef(headRepo *repo_model.Repository, headBranch string) string { + return util.Iif(setting.Repository.AllowForkIntoSameOwner, headRepo.FullName(), headRepo.OwnerName) + ":" + headBranch +} + func (prc *PullRequestContext) MakeDefaultCompareLink(headBranch string) string { return prc.baseRepo.Link() + "/compare/" + util.PathEscapeSegments(prc.DefaultTargetBranch()) + "..." + - util.Iif(prc.SameRepo(), "", util.PathEscapeSegments(prc.headRepo.OwnerName)+":") + - util.PathEscapeSegments(headBranch) + util.PathEscapeSegments(util.Iif(prc.SameRepo(), headBranch, CompareHeadRef(prc.headRepo, headBranch))) } func (prc *PullRequestContext) DefaultTargetBranch() string { diff --git a/services/context/repo_test.go b/services/context/repo_test.go new file mode 100644 index 00000000000..868ce7783d3 --- /dev/null +++ b/services/context/repo_test.go @@ -0,0 +1,25 @@ +// Copyright 2026 The Gitea Authors. All rights reserved. +// SPDX-License-Identifier: MIT + +package context + +import ( + "testing" + + repo_model "gitea.dev/models/repo" + "gitea.dev/modules/setting" + "gitea.dev/modules/test" + + "github.com/stretchr/testify/assert" +) + +func TestCompareHeadRef(t *testing.T) { + defer test.MockVariableValue(&setting.Repository.AllowForkIntoSameOwner)() + headRepo := &repo_model.Repository{OwnerName: "user", Name: "fork"} + + setting.Repository.AllowForkIntoSameOwner = false + assert.Equal(t, "user:my-branch", CompareHeadRef(headRepo, "my-branch")) + + setting.Repository.AllowForkIntoSameOwner = true + assert.Equal(t, "user/fork:my-branch", CompareHeadRef(headRepo, "my-branch")) +}