aboutsummaryrefslogtreecommitdiffstats
path: root/services/pull/check.go
blob: bffca394a8b80e5530b3c2c3dee5d1ca1ce3f1e7 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
// Copyright 2019 The Gitea Authors.
// All rights reserved.
// SPDX-License-Identifier: MIT

package pull

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

	"code.gitea.io/gitea/models/db"
	git_model "code.gitea.io/gitea/models/git"
	issues_model "code.gitea.io/gitea/models/issues"
	access_model "code.gitea.io/gitea/models/perm/access"
	repo_model "code.gitea.io/gitea/models/repo"
	"code.gitea.io/gitea/models/unit"
	user_model "code.gitea.io/gitea/models/user"
	"code.gitea.io/gitea/modules/git"
	"code.gitea.io/gitea/modules/gitrepo"
	"code.gitea.io/gitea/modules/globallock"
	"code.gitea.io/gitea/modules/graceful"
	"code.gitea.io/gitea/modules/log"
	"code.gitea.io/gitea/modules/process"
	"code.gitea.io/gitea/modules/queue"
	"code.gitea.io/gitea/modules/timeutil"
	asymkey_service "code.gitea.io/gitea/services/asymkey"
	notify_service "code.gitea.io/gitea/services/notify"
)

// prPatchCheckerQueue represents a queue to handle update pull request tests
var prPatchCheckerQueue *queue.WorkerPoolQueue[string]

var (
	ErrIsClosed              = errors.New("pull is closed")
	ErrUserNotAllowedToMerge = ErrDisallowedToMerge{}
	ErrHasMerged             = errors.New("has already been merged")
	ErrIsWorkInProgress      = errors.New("work in progress PRs cannot be merged")
	ErrIsChecking            = errors.New("cannot merge while conflict checking is in progress")
	ErrNotMergeableState     = errors.New("not in mergeable state")
	ErrDependenciesLeft      = errors.New("is blocked by an open dependency")
)

// AddToTaskQueue adds itself to pull request test task queue.
func AddToTaskQueue(ctx context.Context, pr *issues_model.PullRequest) {
	pr.Status = issues_model.PullRequestStatusChecking
	err := pr.UpdateColsIfNotMerged(ctx, "status")
	if err != nil {
		log.Error("AddToTaskQueue(%-v).UpdateCols.(add to queue): %v", pr, err)
		return
	}
	log.Trace("Adding %-v to the test pull requests queue", pr)
	err = prPatchCheckerQueue.Push(strconv.FormatInt(pr.ID, 10))
	if err != nil && err != queue.ErrAlreadyInQueue {
		log.Error("Error adding %-v to the test pull requests queue: %v", pr, err)
	}
}

type MergeCheckType int

const (
	MergeCheckTypeGeneral  MergeCheckType = iota // general merge checks for "merge", "rebase", "squash", etc
	MergeCheckTypeManually                       // Manually Merged button (mark a PR as merged manually)
	MergeCheckTypeAuto                           // Auto Merge (Scheduled Merge) After Checks Succeed
)

// CheckPullMergeable check if the pull mergeable based on all conditions (branch protection, merge options, ...)
func CheckPullMergeable(stdCtx context.Context, doer *user_model.User, perm *access_model.Permission, pr *issues_model.PullRequest, mergeCheckType MergeCheckType, adminForceMerge bool) error {
	return db.WithTx(stdCtx, func(ctx context.Context) error {
		if pr.HasMerged {
			return ErrHasMerged
		}

		if err := pr.LoadIssue(ctx); err != nil {
			log.Error("Unable to load issue[%d] for %-v: %v", pr.IssueID, pr, err)
			return err
		} else if pr.Issue.IsClosed {
			return ErrIsClosed
		}

		if allowedMerge, err := IsUserAllowedToMerge(ctx, pr, *perm, doer); err != nil {
			log.Error("Error whilst checking if %-v is allowed to merge %-v: %v", doer, pr, err)
			return err
		} else if !allowedMerge {
			return ErrUserNotAllowedToMerge
		}

		if mergeCheckType == MergeCheckTypeManually {
			// if doer is doing "manually merge" (mark as merged manually), do not check anything
			return nil
		}

		if pr.IsWorkInProgress(ctx) {
			return ErrIsWorkInProgress
		}

		if !pr.CanAutoMerge() && !pr.IsEmpty() {
			return ErrNotMergeableState
		}

		if pr.IsChecking() {
			return ErrIsChecking
		}

		if err := CheckPullBranchProtections(ctx, pr, false); err != nil {
			if !IsErrDisallowedToMerge(err) {
				log.Error("Error whilst checking pull branch protection for %-v: %v", pr, err)
				return err
			}

			// Now the branch protection check failed, check whether the failure could be skipped (skip by setting err = nil)

			// * when doing Auto Merge (Scheduled Merge After Checks Succeed), skip the branch protection check
			if mergeCheckType == MergeCheckTypeAuto {
				err = nil
			}

			// * if admin tries to "Force Merge", they could sometimes skip the branch protection check
			if adminForceMerge {
				isRepoAdmin, errForceMerge := access_model.IsUserRepoAdmin(ctx, pr.BaseRepo, doer)
				if errForceMerge != nil {
					return fmt.Errorf("IsUserRepoAdmin failed, repo: %v, doer: %v, err: %w", pr.BaseRepoID, doer.ID, errForceMerge)
				}

				protectedBranchRule, errForceMerge := git_model.GetFirstMatchProtectedBranchRule(ctx, pr.BaseRepoID, pr.BaseBranch)
				if errForceMerge != nil {
					return fmt.Errorf("GetFirstMatchProtectedBranchRule failed, repo: %v, base branch: %v, err: %w", pr.BaseRepoID, pr.BaseBranch, errForceMerge)
				}

				// if doer is admin and the "Force Merge" is not blocked, then clear the branch protection check error
				blockAdminForceMerge := protectedBranchRule != nil && protectedBranchRule.BlockAdminMergeOverride
				if isRepoAdmin && !blockAdminForceMerge {
					err = nil
				}
			}

			// If there is still a branch protection check error, return it
			if err != nil {
				return err
			}
		}

		if _, err := isSignedIfRequired(ctx, pr, doer); err != nil {
			return err
		}

		if noDeps, err := issues_model.IssueNoDependenciesLeft(ctx, pr.Issue); err != nil {
			return err
		} else if !noDeps {
			return ErrDependenciesLeft
		}

		return nil
	})
}

// isSignedIfRequired check if merge will be signed if required
func isSignedIfRequired(ctx context.Context, pr *issues_model.PullRequest, doer *user_model.User) (bool, error) {
	pb, err := git_model.GetFirstMatchProtectedBranchRule(ctx, pr.BaseRepoID, pr.BaseBranch)
	if err != nil {
		return false, err
	}

	if pb == nil || !pb.RequireSignedCommits {
		return true, nil
	}

	sign, _, _, err := asymkey_service.SignMerge(ctx, pr, doer, pr.BaseRepo.RepoPath(), pr.BaseBranch, pr.GetGitRefName())

	return sign, err
}

// checkAndUpdateStatus checks if pull request is possible to leaving checking status,
// and set to be either conflict or mergeable.
func checkAndUpdateStatus(ctx context.Context, pr *issues_model.PullRequest) {
	// If status has not been changed to conflict by testPatch then we are mergeable
	if pr.Status == issues_model.PullRequestStatusChecking {
		pr.Status = issues_model.PullRequestStatusMergeable
	}

	// Make sure there is no waiting test to process before leaving the checking status.
	has, err := prPatchCheckerQueue.Has(strconv.FormatInt(pr.ID, 10))
	if err != nil {
		log.Error("Unable to check if the queue is waiting to reprocess %-v. Error: %v", pr, err)
	}

	if has {
		log.Trace("Not updating status for %-v as it is due to be rechecked", pr)
		return
	}

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

// getMergeCommit checks if a pull request has been merged
// Returns the git.Commit of the pull request if merged
func getMergeCommit(ctx context.Context, pr *issues_model.PullRequest) (*git.Commit, error) {
	if err := pr.LoadBaseRepo(ctx); err != nil {
		return nil, fmt.Errorf("unable to load base repo for %s: %w", pr, err)
	}

	prHeadRef := pr.GetGitRefName()

	// Check if the pull request is merged into BaseBranch
	if _, _, err := git.NewCommand(ctx, "merge-base", "--is-ancestor").
		AddDynamicArguments(prHeadRef, pr.BaseBranch).
		RunStdString(&git.RunOpts{Dir: pr.BaseRepo.RepoPath()}); err != nil {
		if strings.Contains(err.Error(), "exit status 1") {
			// prHeadRef is not an ancestor of the base branch
			return nil, nil
		}
		// Errors are signaled by a non-zero status that is not 1
		return nil, fmt.Errorf("%-v git merge-base --is-ancestor: %w", pr, err)
	}

	// If merge-base successfully exits then prHeadRef is an ancestor of pr.BaseBranch

	// Find the head commit id
	prHeadCommitID, err := git.GetFullCommitID(ctx, pr.BaseRepo.RepoPath(), prHeadRef)
	if err != nil {
		return nil, fmt.Errorf("GetFullCommitID(%s) in %s: %w", prHeadRef, pr.BaseRepo.FullName(), err)
	}

	gitRepo, err := gitrepo.OpenRepository(ctx, pr.BaseRepo)
	if err != nil {
		return nil, fmt.Errorf("%-v OpenRepository: %w", pr.BaseRepo, err)
	}
	defer gitRepo.Close()

	objectFormat := git.ObjectFormatFromName(pr.BaseRepo.ObjectFormatName)

	// Get the commit from BaseBranch where the pull request got merged
	mergeCommit, _, err := git.NewCommand(ctx, "rev-list", "--ancestry-path", "--merges", "--reverse").
		AddDynamicArguments(prHeadCommitID + ".." + pr.BaseBranch).
		RunStdString(&git.RunOpts{Dir: pr.BaseRepo.RepoPath()})
	if err != nil {
		return nil, fmt.Errorf("git rev-list --ancestry-path --merges --reverse: %w", err)
	} else if len(mergeCommit) < objectFormat.FullLength() {
		// PR was maybe fast-forwarded, so just use last commit of PR
		mergeCommit = prHeadCommitID
	}
	mergeCommit = strings.TrimSpace(mergeCommit)

	commit, err := gitRepo.GetCommit(mergeCommit)
	if err != nil {
		return nil, fmt.Errorf("GetMergeCommit[%s]: %w", mergeCommit, err)
	}

	return commit, nil
}

// manuallyMerged checks if a pull request got manually merged
// When a pull request got manually merged mark the pull request as merged
func manuallyMerged(ctx context.Context, pr *issues_model.PullRequest) bool {
	if err := pr.LoadBaseRepo(ctx); err != nil {
		log.Error("%-v LoadBaseRepo: %v", pr, err)
		return false
	}

	if unit, err := pr.BaseRepo.GetUnit(ctx, unit.TypePullRequests); err == nil {
		config := unit.PullRequestsConfig()
		if !config.AutodetectManualMerge {
			return false
		}
	} else {
		log.Error("%-v BaseRepo.GetUnit(unit.TypePullRequests): %v", pr, err)
		return false
	}

	commit, err := getMergeCommit(ctx, pr)
	if err != nil {
		log.Error("%-v getMergeCommit: %v", pr, err)
		return false
	}

	if commit == nil {
		// no merge commit found
		return false
	}

	pr.MergedCommitID = commit.ID.String()
	pr.MergedUnix = timeutil.TimeStamp(commit.Author.When.Unix())
	pr.Status = issues_model.PullRequestStatusManuallyMerged
	merger, _ := user_model.GetUserByEmail(ctx, commit.Author.Email)

	// When the commit author is unknown set the BaseRepo owner as merger
	if merger == nil {
		if pr.BaseRepo.Owner == nil {
			if err = pr.BaseRepo.LoadOwner(ctx); err != nil {
				log.Error("%-v BaseRepo.LoadOwner: %v", pr, err)
				return false
			}
		}
		merger = pr.BaseRepo.Owner
	}
	pr.Merger = merger
	pr.MergerID = merger.ID

	if merged, err := pr.SetMerged(ctx); err != nil {
		log.Error("%-v setMerged : %v", pr, err)
		return false
	} else if !merged {
		return false
	}

	notify_service.MergePullRequest(ctx, merger, pr)

	log.Info("manuallyMerged[%-v]: Marked as manually merged into %s/%s by commit id: %s", pr, pr.BaseRepo.Name, pr.BaseBranch, commit.ID.String())
	return true
}

// InitializePullRequests checks and tests untested patches of pull requests.
func InitializePullRequests(ctx context.Context) {
	prs, err := issues_model.GetPullRequestIDsByCheckStatus(ctx, issues_model.PullRequestStatusChecking)
	if err != nil {
		log.Error("Find Checking PRs: %v", err)
		return
	}
	for _, prID := range prs {
		select {
		case <-ctx.Done():
			return
		default:
			log.Trace("Adding PR[%d] to the pull requests patch checking queue", prID)
			if err := prPatchCheckerQueue.Push(strconv.FormatInt(prID, 10)); err != nil {
				log.Error("Error adding PR[%d] to the pull requests patch checking queue %v", prID, err)
			}
		}
	}
}

// handle passed PR IDs and test the PRs
func handler(items ...string) []string {
	for _, s := range items {
		id, _ := strconv.ParseInt(s, 10, 64)
		testPR(id)
	}
	return nil
}

func testPR(id int64) {
	ctx := graceful.GetManager().HammerContext()
	releaser, err := globallock.Lock(ctx, getPullWorkingLockKey(id))
	if err != nil {
		log.Error("lock.Lock(): %v", err)
		return
	}
	defer releaser()

	ctx, _, finished := process.GetManager().AddContext(ctx, fmt.Sprintf("Test PR[%d] from patch checking queue", id))
	defer finished()

	pr, err := issues_model.GetPullRequestByID(ctx, id)
	if err != nil {
		log.Error("Unable to GetPullRequestByID[%d] for testPR: %v", id, err)
		return
	}

	log.Trace("Testing %-v", pr)
	defer func() {
		log.Trace("Done testing %-v (status: %s)", pr, pr.Status)
	}()

	if pr.HasMerged {
		log.Trace("%-v is already merged (status: %s, merge commit: %s)", pr, pr.Status, pr.MergedCommitID)
		return
	}

	if manuallyMerged(ctx, pr) {
		log.Trace("%-v is manually merged (status: %s, merge commit: %s)", pr, pr.Status, pr.MergedCommitID)
		return
	}

	if err := TestPatch(pr); err != nil {
		log.Error("testPatch[%-v]: %v", pr, err)
		pr.Status = issues_model.PullRequestStatusError
		if err := pr.UpdateCols(ctx, "status"); err != nil {
			log.Error("update pr [%-v] status to PullRequestStatusError failed: %v", pr, err)
		}
		return
	}
	checkAndUpdateStatus(ctx, pr)
}

// CheckPRsForBaseBranch check all pulls with baseBrannch
func CheckPRsForBaseBranch(ctx context.Context, baseRepo *repo_model.Repository, baseBranchName string) error {
	prs, err := issues_model.GetUnmergedPullRequestsByBaseInfo(ctx, baseRepo.ID, baseBranchName)
	if err != nil {
		return err
	}

	for _, pr := range prs {
		AddToTaskQueue(ctx, pr)
	}

	return nil
}

// Init runs the task queue to test all the checking status pull requests
func Init() error {
	prPatchCheckerQueue = queue.CreateUniqueQueue(graceful.GetManager().ShutdownContext(), "pr_patch_checker", handler)

	if prPatchCheckerQueue == nil {
		return fmt.Errorf("unable to create pr_patch_checker queue")
	}

	go graceful.GetManager().RunWithCancel(prPatchCheckerQueue)
	go graceful.GetManager().RunWithShutdownContext(InitializePullRequests)
	return nil
}