Skip to content

Commit 53a6f62

Browse files
committed
Move some pull request functions from models to services
1 parent d672206 commit 53a6f62

File tree

9 files changed

+278
-212
lines changed

9 files changed

+278
-212
lines changed

models/pull.go

Lines changed: 5 additions & 126 deletions
Original file line numberDiff line numberDiff line change
@@ -8,7 +8,6 @@ package models
88
import (
99
"bufio"
1010
"fmt"
11-
"io/ioutil"
1211
"os"
1312
"path"
1413
"path/filepath"
@@ -20,14 +19,11 @@ import (
2019
"code.gitea.io/gitea/modules/log"
2120
"code.gitea.io/gitea/modules/setting"
2221
api "code.gitea.io/gitea/modules/structs"
23-
"code.gitea.io/gitea/modules/sync"
2422
"code.gitea.io/gitea/modules/timeutil"
2523

2624
"github.com/unknwon/com"
2725
)
2826

29-
var pullRequestQueue = sync.NewUniqueQueue(setting.Repository.PullRequestQueueLength)
30-
3127
// PullRequestType defines pull request type
3228
type PullRequestType int
3329

@@ -485,102 +481,6 @@ func (pr *PullRequest) SetMerged() (err error) {
485481
return nil
486482
}
487483

488-
// manuallyMerged checks if a pull request got manually merged
489-
// When a pull request got manually merged mark the pull request as merged
490-
func (pr *PullRequest) manuallyMerged() bool {
491-
commit, err := pr.getMergeCommit()
492-
if err != nil {
493-
log.Error("PullRequest[%d].getMergeCommit: %v", pr.ID, err)
494-
return false
495-
}
496-
if commit != nil {
497-
pr.MergedCommitID = commit.ID.String()
498-
pr.MergedUnix = timeutil.TimeStamp(commit.Author.When.Unix())
499-
pr.Status = PullRequestStatusManuallyMerged
500-
merger, _ := GetUserByEmail(commit.Author.Email)
501-
502-
// When the commit author is unknown set the BaseRepo owner as merger
503-
if merger == nil {
504-
if pr.BaseRepo.Owner == nil {
505-
if err = pr.BaseRepo.getOwner(x); err != nil {
506-
log.Error("BaseRepo.getOwner[%d]: %v", pr.ID, err)
507-
return false
508-
}
509-
}
510-
merger = pr.BaseRepo.Owner
511-
}
512-
pr.Merger = merger
513-
pr.MergerID = merger.ID
514-
515-
if err = pr.SetMerged(); err != nil {
516-
log.Error("PullRequest[%d].setMerged : %v", pr.ID, err)
517-
return false
518-
}
519-
log.Info("manuallyMerged[%d]: Marked as manually merged into %s/%s by commit id: %s", pr.ID, pr.BaseRepo.Name, pr.BaseBranch, commit.ID.String())
520-
return true
521-
}
522-
return false
523-
}
524-
525-
// getMergeCommit checks if a pull request got merged
526-
// Returns the git.Commit of the pull request if merged
527-
func (pr *PullRequest) getMergeCommit() (*git.Commit, error) {
528-
if pr.BaseRepo == nil {
529-
var err error
530-
pr.BaseRepo, err = GetRepositoryByID(pr.BaseRepoID)
531-
if err != nil {
532-
return nil, fmt.Errorf("GetRepositoryByID: %v", err)
533-
}
534-
}
535-
536-
indexTmpPath := filepath.Join(os.TempDir(), "gitea-"+pr.BaseRepo.Name+"-"+strconv.Itoa(time.Now().Nanosecond()))
537-
defer os.Remove(indexTmpPath)
538-
539-
headFile := pr.GetGitRefName()
540-
541-
// Check if a pull request is merged into BaseBranch
542-
_, err := git.NewCommand("merge-base", "--is-ancestor", headFile, pr.BaseBranch).RunInDirWithEnv(pr.BaseRepo.RepoPath(), []string{"GIT_INDEX_FILE=" + indexTmpPath, "GIT_DIR=" + pr.BaseRepo.RepoPath()})
543-
if err != nil {
544-
// Errors are signaled by a non-zero status that is not 1
545-
if strings.Contains(err.Error(), "exit status 1") {
546-
return nil, nil
547-
}
548-
return nil, fmt.Errorf("git merge-base --is-ancestor: %v", err)
549-
}
550-
551-
commitIDBytes, err := ioutil.ReadFile(pr.BaseRepo.RepoPath() + "/" + headFile)
552-
if err != nil {
553-
return nil, fmt.Errorf("ReadFile(%s): %v", headFile, err)
554-
}
555-
commitID := string(commitIDBytes)
556-
if len(commitID) < 40 {
557-
return nil, fmt.Errorf(`ReadFile(%s): invalid commit-ID "%s"`, headFile, commitID)
558-
}
559-
cmd := commitID[:40] + ".." + pr.BaseBranch
560-
561-
// Get the commit from BaseBranch where the pull request got merged
562-
mergeCommit, err := git.NewCommand("rev-list", "--ancestry-path", "--merges", "--reverse", cmd).RunInDirWithEnv("", []string{"GIT_INDEX_FILE=" + indexTmpPath, "GIT_DIR=" + pr.BaseRepo.RepoPath()})
563-
if err != nil {
564-
return nil, fmt.Errorf("git rev-list --ancestry-path --merges --reverse: %v", err)
565-
} else if len(mergeCommit) < 40 {
566-
// PR was fast-forwarded, so just use last commit of PR
567-
mergeCommit = commitID[:40]
568-
}
569-
570-
gitRepo, err := git.OpenRepository(pr.BaseRepo.RepoPath())
571-
if err != nil {
572-
return nil, fmt.Errorf("OpenRepository: %v", err)
573-
}
574-
defer gitRepo.Close()
575-
576-
commit, err := gitRepo.GetCommit(mergeCommit[:40])
577-
if err != nil {
578-
return nil, fmt.Errorf("GetCommit: %v", err)
579-
}
580-
581-
return commit, nil
582-
}
583-
584484
// patchConflicts is a list of conflict description from Git.
585485
var patchConflicts = []string{
586486
"patch does not apply",
@@ -589,6 +489,11 @@ var patchConflicts = []string{
589489
"error:",
590490
}
591491

492+
// TestPatch checks if patch can be merged to base repository without conflict.
493+
func (pr *PullRequest) TestPatch() error {
494+
return pr.testPatch(x)
495+
}
496+
592497
// testPatch checks if patch can be merged to base repository without conflict.
593498
func (pr *PullRequest) testPatch(e Engine) (err error) {
594499
if pr.BaseRepo == nil {
@@ -949,32 +854,6 @@ func (pr *PullRequest) PushToBaseRepo() (err error) {
949854
return nil
950855
}
951856

952-
// AddToTaskQueue adds itself to pull request test task queue.
953-
func (pr *PullRequest) AddToTaskQueue() {
954-
go pullRequestQueue.AddFunc(pr.ID, func() {
955-
pr.Status = PullRequestStatusChecking
956-
if err := pr.UpdateCols("status"); err != nil {
957-
log.Error("AddToTaskQueue.UpdateCols[%d].(add to queue): %v", pr.ID, err)
958-
}
959-
})
960-
}
961-
962-
// checkAndUpdateStatus checks if pull request is possible to leaving checking status,
963-
// and set to be either conflict or mergeable.
964-
func (pr *PullRequest) checkAndUpdateStatus() {
965-
// Status is not changed to conflict means mergeable.
966-
if pr.Status == PullRequestStatusChecking {
967-
pr.Status = PullRequestStatusMergeable
968-
}
969-
970-
// Make sure there is no waiting test to process before leaving the checking status.
971-
if !pullRequestQueue.Exist(pr.ID) {
972-
if err := pr.UpdateCols("status, conflicted_files"); err != nil {
973-
log.Error("Update[%d]: %v", pr.ID, err)
974-
}
975-
}
976-
}
977-
978857
// IsWorkInProgress determine if the Pull Request is a Work In Progress by its title
979858
func (pr *PullRequest) IsWorkInProgress() bool {
980859
if err := pr.LoadIssue(); err != nil {

models/pull_list.go

Lines changed: 9 additions & 62 deletions
Original file line numberDiff line numberDiff line change
@@ -10,7 +10,7 @@ import (
1010
"code.gitea.io/gitea/modules/base"
1111
"code.gitea.io/gitea/modules/git"
1212
"code.gitea.io/gitea/modules/log"
13-
"github.com/unknwon/com"
13+
1414
"xorm.io/xorm"
1515
)
1616

@@ -68,6 +68,14 @@ func GetUnmergedPullRequestsByBaseInfo(repoID int64, branch string) ([]*PullRequ
6868
Find(&prs)
6969
}
7070

71+
// GetPullRequestsByCheckStatus returns all pull requests according the special checking status.
72+
func GetPullRequestsByCheckStatus(status PullRequestStatus) ([]*PullRequest, error) {
73+
prs := make([]*PullRequest, 0, 10)
74+
return prs, x.
75+
Where("status=?", status).
76+
Find(&prs)
77+
}
78+
7179
// PullRequests returns all pull requests for a base Repo by the given conditions
7280
func PullRequests(baseRepoID int64, opts *PullRequestsOptions) ([]*PullRequest, int64, error) {
7381
if opts.Page <= 0 {
@@ -161,64 +169,3 @@ func (prs PullRequestList) invalidateCodeComments(e Engine, doer *User, repo *gi
161169
func (prs PullRequestList) InvalidateCodeComments(doer *User, repo *git.Repository, branch string) error {
162170
return prs.invalidateCodeComments(x, doer, repo, branch)
163171
}
164-
165-
// TestPullRequests checks and tests untested patches of pull requests.
166-
// TODO: test more pull requests at same time.
167-
func TestPullRequests() {
168-
prs := make([]*PullRequest, 0, 10)
169-
170-
err := x.Where("status = ?", PullRequestStatusChecking).Find(&prs)
171-
if err != nil {
172-
log.Error("Find Checking PRs: %v", err)
173-
return
174-
}
175-
176-
var checkedPRs = make(map[int64]struct{})
177-
178-
// Update pull request status.
179-
for _, pr := range prs {
180-
checkedPRs[pr.ID] = struct{}{}
181-
if err := pr.GetBaseRepo(); err != nil {
182-
log.Error("GetBaseRepo: %v", err)
183-
continue
184-
}
185-
if pr.manuallyMerged() {
186-
continue
187-
}
188-
if err := pr.testPatch(x); err != nil {
189-
log.Error("testPatch: %v", err)
190-
continue
191-
}
192-
193-
pr.checkAndUpdateStatus()
194-
}
195-
196-
// Start listening on new test requests.
197-
for prID := range pullRequestQueue.Queue() {
198-
log.Trace("TestPullRequests[%v]: processing test task", prID)
199-
pullRequestQueue.Remove(prID)
200-
201-
id := com.StrTo(prID).MustInt64()
202-
if _, ok := checkedPRs[id]; ok {
203-
continue
204-
}
205-
206-
pr, err := GetPullRequestByID(id)
207-
if err != nil {
208-
log.Error("GetPullRequestByID[%s]: %v", prID, err)
209-
continue
210-
} else if pr.manuallyMerged() {
211-
continue
212-
} else if err = pr.testPatch(x); err != nil {
213-
log.Error("testPatch[%d]: %v", pr.ID, err)
214-
continue
215-
}
216-
217-
pr.checkAndUpdateStatus()
218-
}
219-
}
220-
221-
// InitTestPullRequests runs the task to test all the checking status pull requests
222-
func InitTestPullRequests() {
223-
go TestPullRequests()
224-
}

models/pull_test.go

Lines changed: 0 additions & 20 deletions
Original file line numberDiff line numberDiff line change
@@ -5,9 +5,7 @@
55
package models
66

77
import (
8-
"strconv"
98
"testing"
10-
"time"
119

1210
"github.com/stretchr/testify/assert"
1311
)
@@ -196,24 +194,6 @@ func TestPullRequest_UpdateCols(t *testing.T) {
196194

197195
// TODO TestPullRequest_PushToBaseRepo
198196

199-
func TestPullRequest_AddToTaskQueue(t *testing.T) {
200-
assert.NoError(t, PrepareTestDatabase())
201-
202-
pr := AssertExistsAndLoadBean(t, &PullRequest{ID: 1}).(*PullRequest)
203-
pr.AddToTaskQueue()
204-
205-
select {
206-
case id := <-pullRequestQueue.Queue():
207-
assert.EqualValues(t, strconv.FormatInt(pr.ID, 10), id)
208-
case <-time.After(time.Second):
209-
assert.Fail(t, "Timeout: nothing was added to pullRequestQueue")
210-
}
211-
212-
assert.True(t, pullRequestQueue.Exist(pr.ID))
213-
pr = AssertExistsAndLoadBean(t, &PullRequest{ID: 1}).(*PullRequest)
214-
assert.Equal(t, PullRequestStatusChecking, pr.Status)
215-
}
216-
217197
func TestPullRequestList_LoadAttributes(t *testing.T) {
218198
assert.NoError(t, PrepareTestDatabase())
219199

routers/init.go

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -26,6 +26,7 @@ import (
2626
"code.gitea.io/gitea/modules/webhook"
2727
"code.gitea.io/gitea/services/mailer"
2828
mirror_service "code.gitea.io/gitea/services/mirror"
29+
pull_service "code.gitea.io/gitea/services/pull"
2930

3031
"gitea.com/macaron/macaron"
3132
)
@@ -104,7 +105,7 @@ func GlobalInit() {
104105
models.InitRepoIndexer()
105106
mirror_service.InitSyncMirrors()
106107
webhook.InitDeliverHooks()
107-
models.InitTestPullRequests()
108+
pull_service.Init()
108109
if err := task.Init(); err != nil {
109110
log.Fatal("Failed to initialize task scheduler: %v", err)
110111
}

routers/repo/issue.go

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -28,6 +28,7 @@ import (
2828
"code.gitea.io/gitea/modules/util"
2929
comment_service "code.gitea.io/gitea/services/comments"
3030
issue_service "code.gitea.io/gitea/services/issue"
31+
pull_service "code.gitea.io/gitea/services/pull"
3132

3233
"github.com/unknwon/com"
3334
)
@@ -1272,7 +1273,7 @@ func NewComment(ctx *context.Context, form auth.CreateCommentForm) {
12721273
return
12731274
}
12741275

1275-
issue.PullRequest.AddToTaskQueue()
1276+
pull_service.AddToTaskQueue(issue.PullRequest)
12761277
}
12771278
}
12781279

0 commit comments

Comments
 (0)