Skip to content

Commit 7bf2972

Browse files
lunnywxiaoguang
andauthored
Move GetDiverging functions to gitrepo (#35524)
Extracted from #35469 --------- Co-authored-by: wxiaoguang <[email protected]>
1 parent 8ad2a53 commit 7bf2972

File tree

16 files changed

+219
-175
lines changed

16 files changed

+219
-175
lines changed

models/issues/pull.go

Lines changed: 2 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -417,10 +417,6 @@ func (pr *PullRequest) GetGitHeadRefName() string {
417417
return fmt.Sprintf("%s%d/head", git.PullPrefix, pr.Index)
418418
}
419419

420-
func (pr *PullRequest) GetGitHeadBranchRefName() string {
421-
return fmt.Sprintf("%s%s", git.BranchPrefix, pr.HeadBranch)
422-
}
423-
424420
// GetReviewCommentsCount returns the number of review comments made on the diff of a PR review (not including comments on commits or issues in a PR)
425421
func (pr *PullRequest) GetReviewCommentsCount(ctx context.Context) int {
426422
opts := FindCommentsOptions{
@@ -646,9 +642,8 @@ func (pr *PullRequest) UpdateCols(ctx context.Context, cols ...string) error {
646642
}
647643

648644
// UpdateColsIfNotMerged updates specific fields of a pull request if it has not been merged
649-
func (pr *PullRequest) UpdateColsIfNotMerged(ctx context.Context, cols ...string) error {
650-
_, err := db.GetEngine(ctx).Where("id = ? AND has_merged = ?", pr.ID, false).Cols(cols...).Update(pr)
651-
return err
645+
func (pr *PullRequest) UpdateColsIfNotMerged(ctx context.Context, cols ...string) (int64, error) {
646+
return db.GetEngine(ctx).Where("id = ? AND has_merged = ?", pr.ID, false).Cols(cols...).Update(pr)
652647
}
653648

654649
// IsWorkInProgress determine if the Pull Request is a Work In Progress by its title

models/migrations/v1_12/v136.go

Lines changed: 4 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -6,11 +6,10 @@ package v1_12
66
import (
77
"fmt"
88
"math"
9-
"path/filepath"
10-
"strings"
119
"time"
1210

13-
"code.gitea.io/gitea/modules/git"
11+
repo_model "code.gitea.io/gitea/models/repo"
12+
"code.gitea.io/gitea/modules/gitrepo"
1413
"code.gitea.io/gitea/modules/graceful"
1514
"code.gitea.io/gitea/modules/log"
1615
"code.gitea.io/gitea/modules/setting"
@@ -85,12 +84,9 @@ func AddCommitDivergenceToPulls(x *xorm.Engine) error {
8584
log.Error("Missing base repo with id %d for PR ID %d", pr.BaseRepoID, pr.ID)
8685
continue
8786
}
88-
userPath := filepath.Join(setting.RepoRootPath, strings.ToLower(baseRepo.OwnerName))
89-
repoPath := filepath.Join(userPath, strings.ToLower(baseRepo.Name)+".git")
90-
87+
repoStore := repo_model.StorageRepo(repo_model.RelativePath(baseRepo.OwnerName, baseRepo.Name))
9188
gitRefName := fmt.Sprintf("refs/pull/%d/head", pr.Index)
92-
93-
divergence, err := git.GetDivergingCommits(graceful.GetManager().HammerContext(), repoPath, pr.BaseBranch, gitRefName)
89+
divergence, err := gitrepo.GetDivergingCommits(graceful.GetManager().HammerContext(), repoStore, pr.BaseBranch, gitRefName)
9490
if err != nil {
9591
log.Warn("Could not recalculate Divergence for pull: %d", pr.ID)
9692
pr.CommitsAhead = 0

modules/git/repo.go

Lines changed: 0 additions & 30 deletions
Original file line numberDiff line numberDiff line change
@@ -243,36 +243,6 @@ func GetLatestCommitTime(ctx context.Context, repoPath string) (time.Time, error
243243
return time.Parse("Mon Jan _2 15:04:05 2006 -0700", commitTime)
244244
}
245245

246-
// DivergeObject represents commit count diverging commits
247-
type DivergeObject struct {
248-
Ahead int
249-
Behind int
250-
}
251-
252-
// GetDivergingCommits returns the number of commits a targetBranch is ahead or behind a baseBranch
253-
func GetDivergingCommits(ctx context.Context, repoPath, baseBranch, targetBranch string) (do DivergeObject, err error) {
254-
cmd := gitcmd.NewCommand("rev-list", "--count", "--left-right").
255-
AddDynamicArguments(baseBranch + "..." + targetBranch).AddArguments("--")
256-
stdout, _, err := cmd.RunStdString(ctx, &gitcmd.RunOpts{Dir: repoPath})
257-
if err != nil {
258-
return do, err
259-
}
260-
left, right, found := strings.Cut(strings.Trim(stdout, "\n"), "\t")
261-
if !found {
262-
return do, fmt.Errorf("git rev-list output is missing a tab: %q", stdout)
263-
}
264-
265-
do.Behind, err = strconv.Atoi(left)
266-
if err != nil {
267-
return do, err
268-
}
269-
do.Ahead, err = strconv.Atoi(right)
270-
if err != nil {
271-
return do, err
272-
}
273-
return do, nil
274-
}
275-
276246
// CreateBundle create bundle content to the target path
277247
func (repo *Repository) CreateBundle(ctx context.Context, commit string, out io.Writer) error {
278248
tmp, cleanup, err := setting.AppDataTempDir("git-repo-content").MkdirTempRandom("gitea-bundle")

modules/git/repo_test.go

Lines changed: 0 additions & 24 deletions
Original file line numberDiff line numberDiff line change
@@ -29,27 +29,3 @@ func TestRepoIsEmpty(t *testing.T) {
2929
assert.NoError(t, err)
3030
assert.True(t, isEmpty)
3131
}
32-
33-
func TestRepoGetDivergingCommits(t *testing.T) {
34-
bareRepo1Path := filepath.Join(testReposDir, "repo1_bare")
35-
do, err := GetDivergingCommits(t.Context(), bareRepo1Path, "master", "branch2")
36-
assert.NoError(t, err)
37-
assert.Equal(t, DivergeObject{
38-
Ahead: 1,
39-
Behind: 5,
40-
}, do)
41-
42-
do, err = GetDivergingCommits(t.Context(), bareRepo1Path, "master", "master")
43-
assert.NoError(t, err)
44-
assert.Equal(t, DivergeObject{
45-
Ahead: 0,
46-
Behind: 0,
47-
}, do)
48-
49-
do, err = GetDivergingCommits(t.Context(), bareRepo1Path, "master", "test")
50-
assert.NoError(t, err)
51-
assert.Equal(t, DivergeObject{
52-
Ahead: 0,
53-
Behind: 2,
54-
}, do)
55-
}

modules/gitrepo/compare.go

Lines changed: 44 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,44 @@
1+
// Copyright 2025 The Gitea Authors. All rights reserved.
2+
// SPDX-License-Identifier: MIT
3+
4+
package gitrepo
5+
6+
import (
7+
"context"
8+
"fmt"
9+
"strconv"
10+
"strings"
11+
12+
"code.gitea.io/gitea/modules/git/gitcmd"
13+
)
14+
15+
// DivergeObject represents commit count diverging commits
16+
type DivergeObject struct {
17+
Ahead int
18+
Behind int
19+
}
20+
21+
// GetDivergingCommits returns the number of commits a targetBranch is ahead or behind a baseBranch
22+
func GetDivergingCommits(ctx context.Context, repo Repository, baseBranch, targetBranch string) (*DivergeObject, error) {
23+
cmd := gitcmd.NewCommand("rev-list", "--count", "--left-right").
24+
AddDynamicArguments(baseBranch + "..." + targetBranch).AddArguments("--")
25+
stdout, _, err1 := cmd.RunStdString(ctx, &gitcmd.RunOpts{Dir: repoPath(repo)})
26+
if err1 != nil {
27+
return nil, err1
28+
}
29+
30+
left, right, found := strings.Cut(strings.Trim(stdout, "\n"), "\t")
31+
if !found {
32+
return nil, fmt.Errorf("git rev-list output is missing a tab: %q", stdout)
33+
}
34+
35+
behind, err := strconv.Atoi(left)
36+
if err != nil {
37+
return nil, err
38+
}
39+
ahead, err := strconv.Atoi(right)
40+
if err != nil {
41+
return nil, err
42+
}
43+
return &DivergeObject{Ahead: ahead, Behind: behind}, nil
44+
}

modules/gitrepo/compare_test.go

Lines changed: 42 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,42 @@
1+
// Copyright 2024 The Gitea Authors. All rights reserved.
2+
// SPDX-License-Identifier: MIT
3+
4+
package gitrepo
5+
6+
import (
7+
"testing"
8+
9+
"github.com/stretchr/testify/assert"
10+
)
11+
12+
type mockRepository struct {
13+
path string
14+
}
15+
16+
func (r *mockRepository) RelativePath() string {
17+
return r.path
18+
}
19+
20+
func TestRepoGetDivergingCommits(t *testing.T) {
21+
repo := &mockRepository{path: "repo1_bare"}
22+
do, err := GetDivergingCommits(t.Context(), repo, "master", "branch2")
23+
assert.NoError(t, err)
24+
assert.Equal(t, &DivergeObject{
25+
Ahead: 1,
26+
Behind: 5,
27+
}, do)
28+
29+
do, err = GetDivergingCommits(t.Context(), repo, "master", "master")
30+
assert.NoError(t, err)
31+
assert.Equal(t, &DivergeObject{
32+
Ahead: 0,
33+
Behind: 0,
34+
}, do)
35+
36+
do, err = GetDivergingCommits(t.Context(), repo, "master", "test")
37+
assert.NoError(t, err)
38+
assert.Equal(t, &DivergeObject{
39+
Ahead: 0,
40+
Behind: 2,
41+
}, do)
42+
}

modules/gitrepo/gitrepo.go

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -20,9 +20,9 @@ type Repository interface {
2020
RelativePath() string // We don't assume how the directory structure of the repository is, so we only need the relative path
2121
}
2222

23-
// RelativePath should be an unix style path like username/reponame.git
24-
// This method should change it according to the current OS.
25-
func repoPath(repo Repository) string {
23+
// repoPath resolves the Repository.RelativePath (which is a unix-style path like "username/reponame.git")
24+
// to a local filesystem path according to setting.RepoRootPath
25+
var repoPath = func(repo Repository) string {
2626
return filepath.Join(setting.RepoRootPath, filepath.FromSlash(repo.RelativePath()))
2727
}
2828

modules/gitrepo/main_test.go

Lines changed: 32 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,32 @@
1+
// Copyright 2025 The Gitea Authors. All rights reserved.
2+
// SPDX-License-Identifier: MIT
3+
4+
package gitrepo
5+
6+
import (
7+
"os"
8+
"path/filepath"
9+
"testing"
10+
11+
"code.gitea.io/gitea/modules/log"
12+
"code.gitea.io/gitea/modules/setting"
13+
"code.gitea.io/gitea/modules/tempdir"
14+
"code.gitea.io/gitea/modules/test"
15+
)
16+
17+
func TestMain(m *testing.M) {
18+
gitHomePath, cleanup, err := tempdir.OsTempDir("gitea-test").MkdirTempRandom("git-home")
19+
if err != nil {
20+
log.Fatal("Unable to create temp dir: %v", err)
21+
}
22+
defer cleanup()
23+
24+
// resolve repository path relative to the test directory
25+
testRootDir := test.SetupGiteaRoot()
26+
repoPath = func(repo Repository) string {
27+
return filepath.Join(testRootDir, "/modules/git/tests/repos", repo.RelativePath())
28+
}
29+
30+
setting.Git.HomePath = gitHomePath
31+
os.Exit(m.Run())
32+
}

routers/web/repo/issue_comment.go

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -126,8 +126,8 @@ func NewComment(ctx *context.Context) {
126126
ctx.JSONError("The origin branch is delete, cannot reopen.")
127127
return
128128
}
129-
headBranchRef := pull.GetGitHeadBranchRefName()
130-
headBranchCommitID, err := git.GetFullCommitID(ctx, pull.HeadRepo.RepoPath(), headBranchRef)
129+
headBranchRef := git.RefNameFromBranch(pull.HeadBranch)
130+
headBranchCommitID, err := git.GetFullCommitID(ctx, pull.HeadRepo.RepoPath(), headBranchRef.String())
131131
if err != nil {
132132
ctx.ServerError("Get head commit Id of head branch fail", err)
133133
return

services/pull/check.go

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -50,7 +50,7 @@ var (
5050

5151
func markPullRequestStatusAsChecking(ctx context.Context, pr *issues_model.PullRequest) bool {
5252
pr.Status = issues_model.PullRequestStatusChecking
53-
err := pr.UpdateColsIfNotMerged(ctx, "status")
53+
_, err := pr.UpdateColsIfNotMerged(ctx, "status")
5454
if err != nil {
5555
log.Error("UpdateColsIfNotMerged failed, pr: %-v, err: %v", pr, err)
5656
return false
@@ -256,7 +256,7 @@ func markPullRequestAsMergeable(ctx context.Context, pr *issues_model.PullReques
256256
return
257257
}
258258

259-
if err := pr.UpdateColsIfNotMerged(ctx, "merge_base", "status", "conflicted_files", "changed_protected_files"); err != nil {
259+
if _, err := pr.UpdateColsIfNotMerged(ctx, "merge_base", "status", "conflicted_files", "changed_protected_files"); err != nil {
260260
log.Error("Update[%-v]: %v", pr, err)
261261
}
262262

0 commit comments

Comments
 (0)