Skip to content
63 changes: 63 additions & 0 deletions modules/gitrepo/compare_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,9 +4,17 @@
package gitrepo

import (
"bytes"
"os"
"path/filepath"
"strings"
"testing"
"time"

"code.gitea.io/gitea/modules/git/gitcmd"

"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
)

type mockRepository struct {
Expand All @@ -17,6 +25,61 @@ func (r *mockRepository) RelativePath() string {
return r.path
}

func commitRootTree(t *testing.T, repoDir, fileName, content, message string) string {
t.Helper()

require.NoError(t, gitcmd.NewCommand("read-tree", "--empty").WithDir(repoDir).Run(t.Context()))

stdout, _, err := gitcmd.NewCommand("hash-object", "-w", "--stdin").
WithDir(repoDir).
WithStdinBytes([]byte(content)).
RunStdString(t.Context())
require.NoError(t, err)
blobSHA := strings.TrimSpace(stdout)

_, _, err = gitcmd.NewCommand("update-index", "--add", "--replace", "--cacheinfo").
AddDynamicArguments("100644", blobSHA, fileName).
WithDir(repoDir).
RunStdString(t.Context())
require.NoError(t, err)

stdout, _, err = gitcmd.NewCommand("write-tree").WithDir(repoDir).RunStdString(t.Context())
require.NoError(t, err)
treeSHA := strings.TrimSpace(stdout)

commitTimeStr := time.Now().Format(time.RFC3339)
env := append(os.Environ(),
"GIT_AUTHOR_NAME=Test",
"GIT_AUTHOR_EMAIL=test@example.com",
"GIT_AUTHOR_DATE="+commitTimeStr,
"GIT_COMMITTER_NAME=Test",
"GIT_COMMITTER_EMAIL=test@example.com",
"GIT_COMMITTER_DATE="+commitTimeStr,
)

messageBytes := bytes.NewBufferString(message + "\n")
stdout, _, err = gitcmd.NewCommand("commit-tree").AddDynamicArguments(treeSHA).
WithEnv(env).
WithDir(repoDir).
WithStdinBytes(messageBytes.Bytes()).
RunStdString(t.Context())
require.NoError(t, err)

return strings.TrimSpace(stdout)
}

func TestMergeBaseNoCommonHistory(t *testing.T) {
repoDir := filepath.Join(t.TempDir(), "repo.git")
require.NoError(t, gitcmd.NewCommand("init").AddDynamicArguments(repoDir).Run(t.Context()))

baseCommit := commitRootTree(t, repoDir, "base.txt", "base", "base")
headCommit := commitRootTree(t, repoDir, "head.txt", "head", "head")

mergeBase, err := MergeBase(t.Context(), &mockRepository{path: repoDir}, baseCommit, headCommit)
assert.Empty(t, mergeBase)
assert.True(t, IsErrNoMergeBase(err), "expected no merge base error, got %v", err)
}

func TestRepoGetDivergingCommits(t *testing.T) {
repo := &mockRepository{path: "repo1_bare"}
do, err := GetDivergingCommits(t.Context(), repo, "master", "branch2")
Expand Down
27 changes: 27 additions & 0 deletions modules/gitrepo/merge.go
Original file line number Diff line number Diff line change
Expand Up @@ -5,17 +5,44 @@ package gitrepo

import (
"context"
"errors"
"fmt"
"strings"

"code.gitea.io/gitea/modules/git/gitcmd"
)

type ErrNoMergeBase struct {
BaseCommitID string
HeadCommitID string
Err error
}

func IsErrNoMergeBase(err error) bool {
Comment thread
wxiaoguang marked this conversation as resolved.
Outdated
var noMergeBase ErrNoMergeBase
return errors.As(err, &noMergeBase)
}

func (err ErrNoMergeBase) Error() string {
return fmt.Sprintf("get merge-base of %s and %s failed: %v", err.BaseCommitID, err.HeadCommitID, err.Err)
}

func (err ErrNoMergeBase) Unwrap() error {
return err.Err
}

// MergeBase checks and returns merge base of two commits.
func MergeBase(ctx context.Context, repo Repository, baseCommitID, headCommitID string) (string, error) {
mergeBase, _, err := RunCmdString(ctx, repo, gitcmd.NewCommand("merge-base").
AddDashesAndList(baseCommitID, headCommitID))
if err != nil {
if gitcmd.IsErrorExitCode(err, 1) {
Comment thread
wxiaoguang marked this conversation as resolved.
Outdated
return "", ErrNoMergeBase{
BaseCommitID: baseCommitID,
HeadCommitID: headCommitID,
Err: err,
}
}
return "", fmt.Errorf("get merge-base of %s and %s failed: %w", baseCommitID, headCommitID, err)
}
return strings.TrimSpace(mergeBase), nil
Expand Down
1 change: 1 addition & 0 deletions options/locale/locale_en-US.json
Original file line number Diff line number Diff line change
Expand Up @@ -1784,6 +1784,7 @@
"repo.pulls.review_only_possible_for_full_diff": "Review is only possible when viewing the full diff",
"repo.pulls.filter_changes_by_commit": "Filter by commit",
"repo.pulls.nothing_to_compare": "These branches are equal. There is no need to create a pull request.",
"repo.pulls.no_common_history": "These branches do not share a common merge base. Select a different base or compare branch.",
"repo.pulls.nothing_to_compare_have_tag": "The selected branches/tags are equal.",
"repo.pulls.nothing_to_compare_and_allow_empty_pr": "These branches are equal. This PR will be empty.",
"repo.pulls.has_pull_request": "A pull request between these branches already exists: <a href=\"%[1]s\">%[2]s#%[3]d</a>",
Expand Down
12 changes: 12 additions & 0 deletions routers/web/repo/compare.go
Original file line number Diff line number Diff line change
Expand Up @@ -413,6 +413,12 @@ func ParseCompareInfo(ctx *context.Context) *git_service.CompareInfo {

compareInfo, err := git_service.GetCompareInfo(ctx, baseRepo, headRepo, headGitRepo, baseRef, headRef, compareReq.DirectComparison(), fileOnly)
if err != nil {
if gitrepo.IsErrNoMergeBase(err) {
ctx.Data["NoMergeBase"] = true
ctx.Data["BeforeCommitID"] = compareInfo.BaseCommitID
ctx.Data["AfterCommitID"] = compareInfo.HeadCommitID
return &compareInfo
}
Comment thread
wxiaoguang marked this conversation as resolved.
Outdated
ctx.ServerError("GetCompareInfo", err)
return nil
}
Expand Down Expand Up @@ -473,6 +479,12 @@ func PrepareCompareDiff(
ctx.Data["TitleQuery"] = newPrFormTitle
ctx.Data["BodyQuery"] = newPrFormBody

if ctx.Data["NoMergeBase"] == true {
Comment thread
wxiaoguang marked this conversation as resolved.
Outdated
ctx.Data["CommitCount"] = 0
ctx.Data["Commits"] = []*git_model.SignCommitWithStatuses{}
return true
}

if (headCommitID == ci.MergeBase && !ci.DirectComparison()) ||
headCommitID == ci.BaseCommitID {
ctx.Data["IsNothingToCompare"] = true
Expand Down
6 changes: 5 additions & 1 deletion templates/repo/diff/compare.tmpl
Original file line number Diff line number Diff line change
Expand Up @@ -168,7 +168,11 @@
</div>

{{$showDiffBox := and .CommitCount (not .IsNothingToCompare)}}
{{if and .IsSigned .PageIsComparePull}}
{{if .NoMergeBase}}
<div class="ui warning message">
{{ctx.Locale.Tr "repo.pulls.no_common_history"}}
</div>
{{else if and .IsSigned .PageIsComparePull}}
Comment thread
wxiaoguang marked this conversation as resolved.
Outdated
{{$allowCreatePR := and ($.CompareInfo.BaseRef.IsBranch) ($.CompareInfo.HeadRef.IsBranch) (not $.CompareInfo.DirectComparison) (or $.AllowEmptyPr (not .IsNothingToCompare))}}
{{if .IsNothingToCompare}}
<div class="ui segment">
Expand Down
76 changes: 76 additions & 0 deletions tests/integration/compare_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,19 +4,25 @@
package integration

import (
"bytes"
"fmt"
"net/http"
"net/url"
"os"
"strings"
"testing"
"time"

repo_model "code.gitea.io/gitea/models/repo"
"code.gitea.io/gitea/models/unittest"
user_model "code.gitea.io/gitea/models/user"
"code.gitea.io/gitea/modules/git/gitcmd"
"code.gitea.io/gitea/modules/test"
repo_service "code.gitea.io/gitea/services/repository"
"code.gitea.io/gitea/tests"

"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
)

func TestCompareTag(t *testing.T) {
Expand Down Expand Up @@ -124,6 +130,76 @@ func TestCompareBranches(t *testing.T) {
inspectCompare(t, htmlDoc, diffCount, diffChanges)
}

func createUnrelatedBranch(t *testing.T, repo *repo_model.Repository, user *user_model.User, branchName string) {
t.Helper()

repoPath := repo_model.RepoPath(user.Name, repo.Name)
require.NoError(t, gitcmd.NewCommand("read-tree", "--empty").WithDir(repoPath).Run(t.Context()))

stdout, _, err := gitcmd.NewCommand("hash-object", "-w", "--stdin").
WithDir(repoPath).
WithStdinBytes([]byte("Unrelated File")).
RunStdString(t.Context())
require.NoError(t, err)
blobSHA := strings.TrimSpace(stdout)

_, _, err = gitcmd.NewCommand("update-index", "--add", "--replace", "--cacheinfo").
AddDynamicArguments("100644", blobSHA, "unrelated.txt").
WithDir(repoPath).
RunStdString(t.Context())
require.NoError(t, err)

stdout, _, err = gitcmd.NewCommand("write-tree").WithDir(repoPath).RunStdString(t.Context())
require.NoError(t, err)
treeSHA := strings.TrimSpace(stdout)

commitTimeStr := time.Now().Format(time.RFC3339)
doerSig := user.NewGitSig()
env := append(os.Environ(),
"GIT_AUTHOR_NAME="+doerSig.Name,
"GIT_AUTHOR_EMAIL="+doerSig.Email,
"GIT_AUTHOR_DATE="+commitTimeStr,
"GIT_COMMITTER_NAME="+doerSig.Name,
"GIT_COMMITTER_EMAIL="+doerSig.Email,
"GIT_COMMITTER_DATE="+commitTimeStr,
)

messageBytes := bytes.NewBufferString("Unrelated\n")
stdout, _, err = gitcmd.NewCommand("commit-tree").AddDynamicArguments(treeSHA).
WithEnv(env).
WithDir(repoPath).
WithStdinBytes(messageBytes.Bytes()).
RunStdString(t.Context())
require.NoError(t, err)
commitSHA := strings.TrimSpace(stdout)

_, _, err = gitcmd.NewCommand("branch").AddDynamicArguments(branchName, commitSHA).
WithDir(repoPath).
RunStdString(t.Context())
require.NoError(t, err)
}

func TestCompareBranchesNoCommonMergeBase(t *testing.T) {
defer tests.PrepareTestEnv(t)()

user2 := unittest.AssertExistsAndLoadBean(t, &user_model.User{Name: "user2"})
repo1 := unittest.AssertExistsAndLoadBean(t, &repo_model.Repository{OwnerID: user2.ID, Name: "repo1"})
createUnrelatedBranch(t, repo1, user2, "unrelated-history")

session := loginUser(t, "user2")
req := NewRequest(t, "GET", "/user2/repo1/compare/master...unrelated-history")
resp := session.MakeRequest(t, req, http.StatusOK)
body := resp.Body.String()
htmlDoc := NewHTMLParser(t, resp.Body)

selection := htmlDoc.doc.Find(".ui.dropdown.select-branch")
assert.Lenf(t, selection.Nodes, 2, "The template has changed")
assert.Contains(t, body, "These branches do not share a common merge base")
assert.Equal(t, 1, htmlDoc.doc.Find(`a.item[href="/user2/repo1/compare/master...unrelated-history"]`).Length())
assert.Equal(t, 1, htmlDoc.doc.Find(`a.item[href="/user2/repo1/compare/master...master"]`).Length())
assert.Equal(t, 0, htmlDoc.doc.Find(".pullrequest-form").Length())
}

func TestCompareCodeExpand(t *testing.T) {
onGiteaRun(t, func(t *testing.T, u *url.URL) {
user1 := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: 1})
Expand Down