mirror of
https://github.com/go-gitea/gitea.git
synced 2026-11-26 10:47:04 -06:00
Adds a merge queue for protected branches, modeled on GitHub's. Merging
into a branch that requires it queues the pull request, tests it with
the ones ahead of it in `merge_group` runs and fast-forwards the base
once the required checks pass. Failing or conflicting pull requests are
removed.
Rules configure merge method, group sizes, grouping and timeouts. Each
queue has a page at `/{owner}/{repo}/queue/{branch}`. The API can queue,
jump, look up and remove a pull request and list or clear a queue, and
webhooks and Actions get the `merge_group` event and
`enqueued`/`dequeued` actions. The merge box's command line hint now
sits beside the merge buttons like on GitHub, also outside of merge
queues.
One notable difference from GitHub is that Gitea allows merge queue to
be enabled in any repo, as opposed to GitHub which only allows it in
organization repos.
| View | Screenshot |
| --- | --- |
| Merge box, ready | <img width="440" alt="Merge box, ready"
src="https://github.com/user-attachments/assets/7d2ac984-90c4-4744-8ac8-5daf37cd96e9"
/> |
| Merge box, queued | <img width="440" alt="Merge box, queued"
src="https://github.com/user-attachments/assets/33b85cab-dfd6-405f-8ffd-283cd920e59f"
/> |
| Pull request header, queued | <img width="600" alt="Pull request
header, queued"
src="https://github.com/user-attachments/assets/d61c635b-8552-4b47-a900-e493912e8c16"
/> |
| Timeline, removal after failed checks | <img width="440"
alt="Timeline, removal after failed checks"
src="https://github.com/user-attachments/assets/bee95e79-4c76-4592-ad35-82109d9da4ed"
/> |
| Queue page | <img width="600" alt="Queue page"
src="https://github.com/user-attachments/assets/847a595a-1e13-4099-aa37-7f44018dc188"
/> |
| Pull request list, queued | <img width="600" alt="Pull request list,
queued"
src="https://github.com/user-attachments/assets/a382a143-a67f-4298-aa11-594e281d54db"
/> |
| Merge queue settings | <img width="600" alt="Merge queue settings"
src="https://github.com/user-attachments/assets/cdaf4aa5-350e-4570-a095-c91c41d03cde"
/> |
Fixes: https://github.com/go-gitea/gitea/issues/36392
Docs: https://gitea.com/gitea/docs/pulls/655
Assisted-by: Claude Code:claude-opus-5-5
---------
Co-authored-by: silverwind <me@silverwind.io>
Co-authored-by: TheFox0x7 <thefox0x7@gmail.com>
928 lines
28 KiB
Go
928 lines
28 KiB
Go
// Copyright 2022 The Gitea Authors. All rights reserved.
|
|
// SPDX-License-Identifier: MIT
|
|
|
|
package actions
|
|
|
|
import (
|
|
"bytes"
|
|
"context"
|
|
"fmt"
|
|
"path"
|
|
"slices"
|
|
"strings"
|
|
|
|
"gitea.dev/actionslib/pkg/model"
|
|
"gitea.dev/modules/actions/jobparser"
|
|
"gitea.dev/modules/actions/workflowpattern"
|
|
"gitea.dev/modules/git"
|
|
"gitea.dev/modules/glob"
|
|
"gitea.dev/modules/log"
|
|
"gitea.dev/modules/optional"
|
|
"gitea.dev/modules/setting"
|
|
api "gitea.dev/modules/structs"
|
|
"gitea.dev/modules/util"
|
|
webhook_module "gitea.dev/modules/webhook"
|
|
|
|
"go.yaml.in/yaml/v4"
|
|
)
|
|
|
|
type DetectedWorkflow struct {
|
|
EntryName string
|
|
TriggerEvent *jobparser.Event
|
|
Content []byte
|
|
// SourceCommitSHA is the commit Content was read from, and must always be filled in together with Content.
|
|
SourceCommitSHA string
|
|
}
|
|
|
|
type detectResult int
|
|
|
|
const (
|
|
detectMatched detectResult = iota // event matched; run normally
|
|
detectNotApplicable // event/type doesn't apply; create nothing
|
|
detectFilteredOut // matched but excluded by a branch/paths filter; posts a skipped commit status when the context is a required check
|
|
)
|
|
|
|
func init() {
|
|
model.OnDecodeNodeError = func(node yaml.Node, out any, err error) {
|
|
// Log the error instead of panic or fatal.
|
|
// It will be a big job to refactor act/pkg/model to return decode error,
|
|
// so we just log the error and return empty value, and improve it later.
|
|
log.Error("Failed to decode node %v into %T: %v", node, out, err)
|
|
}
|
|
}
|
|
|
|
func IsWorkflow(path string) bool {
|
|
return isWorkflowInDirs(path, setting.Actions.WorkflowDirs)
|
|
}
|
|
|
|
// IsWorkflowOrScopedWorkflow reports whether path is a workflow file under WORKFLOW_DIRS or SCOPED_WORKFLOW_DIRS.
|
|
func IsWorkflowOrScopedWorkflow(path string) bool {
|
|
return isWorkflowInDirs(path, setting.Actions.WorkflowDirs) || isWorkflowInDirs(path, setting.Actions.ScopedWorkflowDirs)
|
|
}
|
|
|
|
func isWorkflowInDirs(path string, dirs []string) bool {
|
|
if (!strings.HasSuffix(path, ".yaml")) && (!strings.HasSuffix(path, ".yml")) {
|
|
return false
|
|
}
|
|
|
|
for _, workflowDir := range dirs {
|
|
if strings.HasPrefix(path, workflowDir+"/") {
|
|
return true
|
|
}
|
|
}
|
|
return false
|
|
}
|
|
|
|
func ListWorkflows(ctx context.Context, gitRepo *git.Repository, commit *git.Commit) (string, git.Entries, error) {
|
|
return listWorkflowsInDirs(ctx, gitRepo, commit, setting.Actions.WorkflowDirs)
|
|
}
|
|
|
|
func listWorkflowsInDirs(ctx context.Context, gitRepo *git.Repository, commit *git.Commit, dirs []string) (string, git.Entries, error) {
|
|
var tree *git.Tree
|
|
var err error
|
|
var workflowDir string
|
|
for _, workflowDir = range dirs {
|
|
tree, err = commit.SubTree(ctx, gitRepo, workflowDir)
|
|
if err == nil {
|
|
break
|
|
}
|
|
if !git.IsErrNotExist(err) {
|
|
return "", nil, err
|
|
}
|
|
}
|
|
if tree == nil {
|
|
return "", nil, nil
|
|
}
|
|
|
|
entries, err := tree.ListEntriesRecursiveFast(ctx, gitRepo)
|
|
if err != nil {
|
|
return "", nil, err
|
|
}
|
|
|
|
ret := make(git.Entries, 0, len(entries))
|
|
for _, entry := range entries {
|
|
if strings.HasSuffix(entry.Name(), ".yml") || strings.HasSuffix(entry.Name(), ".yaml") {
|
|
ret = append(ret, entry)
|
|
}
|
|
}
|
|
return workflowDir, ret, nil
|
|
}
|
|
|
|
func GetContentFromEntry(ctx context.Context, gitRepo *git.Repository, entry *git.TreeEntry) ([]byte, error) {
|
|
f, err := entry.Blob(gitRepo).DataAsync(ctx)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
content, err := util.ReadWithLimit(f, 1024*1024)
|
|
_ = f.Close()
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
return content, nil
|
|
}
|
|
|
|
func GetEventsFromContent(content []byte) ([]*jobparser.Event, error) {
|
|
events, _, err := readWorkflowEvents(content)
|
|
return events, err
|
|
}
|
|
|
|
// readWorkflowEvents also reports whether its error needs no run-time values to find, as a parse error of a workflow without expressions does.
|
|
func readWorkflowEvents(content []byte) (events []*jobparser.Event, static bool, err error) {
|
|
if events, err = jobparser.ValidateWorkflowStatic(content); err != nil {
|
|
return nil, true, err
|
|
}
|
|
if err = ValidateWorkflowContent(content); err != nil {
|
|
return nil, !bytes.Contains(content, []byte("${{")), err
|
|
}
|
|
return events, false, nil
|
|
}
|
|
|
|
// ValidateWorkflowContent catches structural errors (e.g. blank lines in run: | blocks)
|
|
// that model.ReadWorkflow alone does not detect.
|
|
func ValidateWorkflowContent(content []byte) error {
|
|
_, err := jobparser.Parse(content)
|
|
return err
|
|
}
|
|
|
|
// WorkflowDisplayName returns a workflow's display name: its `name:` if non-blank, otherwise the base file name.
|
|
// This is the value used as the workflow segment of its commit-status context.
|
|
func WorkflowDisplayName(file string, content []byte) string {
|
|
displayName := path.Base(file)
|
|
if wfs, err := jobparser.Parse(content); err == nil && len(wfs) > 0 {
|
|
if name := strings.TrimSpace(wfs[0].Name); name != "" {
|
|
displayName = name
|
|
}
|
|
}
|
|
return displayName
|
|
}
|
|
|
|
// WorkflowStatusContextName builds a workflow job's commit-status context name: "<display> / <job> (<event>)".
|
|
func WorkflowStatusContextName(displayName, jobName, event string) string {
|
|
return strings.TrimSpace(fmt.Sprintf("%s / %s (%s)", displayName, jobName, event))
|
|
}
|
|
|
|
// ScopedWorkflowStatusContextName prefixes a scoped run's status-check context with its source repo, set off by a colon: "<prefix>: <display> / <job> (<event>)".
|
|
func ScopedWorkflowStatusContextName(prefix, displayName, jobName, event string) string {
|
|
return strings.TrimSpace(fmt.Sprintf("%s: %s", prefix, WorkflowStatusContextName(displayName, jobName, event)))
|
|
}
|
|
|
|
// IsPullRequestCheckEvent reports whether a run triggered by the given workflow `on:` event posts a commit status that pull requests count,
|
|
// so its context can serve as a required status check.
|
|
// TODO: this allowlist duplicates the truth in services/actions.getCommitStatusEventNameAndCommitID, which decides the actual event string and whether a status is posted,
|
|
// and in services/pull.GetLatestPullCommitStatuses, which decides whether pull requests count it.
|
|
// They are kept in sync by hand and can drift, unify them into a single source so adding a status-producing event in one place automatically updates the others.
|
|
func IsPullRequestCheckEvent(event string) bool {
|
|
switch event {
|
|
case "push", "pull_request", "pull_request_target", "pull_request_review", "pull_request_review_comment", "release":
|
|
return true
|
|
}
|
|
return false
|
|
}
|
|
|
|
func DetectWorkflows(
|
|
ctx context.Context,
|
|
gitRepo *git.Repository,
|
|
commit *git.Commit,
|
|
triggedEvent webhook_module.HookEventType,
|
|
payload api.Payloader,
|
|
detectSchedule bool,
|
|
) (workflows, schedules, filtered []*DetectedWorkflow, invalid map[string]error, err error) {
|
|
_, entries, err := ListWorkflows(ctx, gitRepo, commit)
|
|
if err != nil {
|
|
return nil, nil, nil, nil, err
|
|
}
|
|
|
|
invalid = map[string]error{}
|
|
for _, entry := range entries {
|
|
content, err := GetContentFromEntry(ctx, gitRepo, entry)
|
|
if err != nil {
|
|
return nil, nil, nil, nil, err
|
|
}
|
|
|
|
// one workflow may have multiple events
|
|
events, static, err := readWorkflowEvents(content)
|
|
if err != nil {
|
|
log.Warn("ignore invalid workflow %q: %v", entry.Name(), err)
|
|
if static {
|
|
invalid[entry.Name()] = err
|
|
}
|
|
continue
|
|
}
|
|
for _, evt := range events {
|
|
log.Trace("detect workflow %q for event %#v matching %q", entry.Name(), evt, triggedEvent)
|
|
if evt.IsSchedule() {
|
|
if detectSchedule {
|
|
dwf := &DetectedWorkflow{
|
|
EntryName: entry.Name(),
|
|
TriggerEvent: evt,
|
|
Content: content,
|
|
SourceCommitSHA: commit.ID.String(),
|
|
}
|
|
schedules = append(schedules, dwf)
|
|
}
|
|
} else {
|
|
dwf := &DetectedWorkflow{
|
|
EntryName: entry.Name(),
|
|
TriggerEvent: evt,
|
|
Content: content,
|
|
SourceCommitSHA: commit.ID.String(),
|
|
}
|
|
switch detectWorkflowMatch(ctx, gitRepo, commit, triggedEvent, payload, evt) {
|
|
case detectMatched:
|
|
workflows = append(workflows, dwf)
|
|
case detectFilteredOut:
|
|
filtered = append(filtered, dwf)
|
|
case detectNotApplicable:
|
|
}
|
|
}
|
|
}
|
|
}
|
|
|
|
return workflows, schedules, filtered, invalid, nil
|
|
}
|
|
|
|
func DetectScheduledWorkflows(ctx context.Context, gitRepo *git.Repository, commit *git.Commit) ([]*DetectedWorkflow, error) {
|
|
_, entries, err := ListWorkflows(ctx, gitRepo, commit)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
|
|
wfs := make([]*DetectedWorkflow, 0, len(entries))
|
|
for _, entry := range entries {
|
|
content, err := GetContentFromEntry(ctx, gitRepo, entry)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
|
|
// one workflow may have multiple events
|
|
events, err := GetEventsFromContent(content)
|
|
if err != nil {
|
|
log.Warn("ignore invalid workflow %q: %v", entry.Name(), err)
|
|
continue
|
|
}
|
|
for _, evt := range events {
|
|
if evt.IsSchedule() {
|
|
log.Trace("detect scheduled workflow: %q", entry.Name())
|
|
dwf := &DetectedWorkflow{
|
|
EntryName: entry.Name(),
|
|
TriggerEvent: evt,
|
|
Content: content,
|
|
SourceCommitSHA: commit.ID.String(),
|
|
}
|
|
wfs = append(wfs, dwf)
|
|
}
|
|
}
|
|
}
|
|
|
|
return wfs, nil
|
|
}
|
|
|
|
// payloadAs returns the payload as the type the event is expected to carry
|
|
func payloadAs[T api.Payloader](payload api.Payloader, inputEvent webhook_module.HookEventType) T {
|
|
typedPayload, ok := payload.(T)
|
|
if !ok {
|
|
// the event type determines the payload type, so a mismatch can only be a programming error
|
|
panic(fmt.Errorf("event %q was triggered with payload type %T instead of %T", inputEvent, payload, typedPayload))
|
|
}
|
|
return typedPayload
|
|
}
|
|
|
|
func detectWorkflowMatch(ctx context.Context, gitRepo *git.Repository, commit *git.Commit, inputEvent webhook_module.HookEventType, payload api.Payloader, evt *jobparser.Event) detectResult {
|
|
if !canGithubEventMatch(evt.Name, inputEvent) {
|
|
return detectNotApplicable
|
|
}
|
|
|
|
switch inputEvent {
|
|
case // events with no activity types
|
|
webhook_module.HookEventCreate,
|
|
webhook_module.HookEventDelete,
|
|
webhook_module.HookEventFork,
|
|
webhook_module.HookEventWiki,
|
|
webhook_module.HookEventSchedule:
|
|
if len(evt.Acts()) != 0 {
|
|
log.Warn("Ignore unsupported %s event arguments %v", inputEvent, evt.Acts())
|
|
}
|
|
// no special filter parameters for these events, just return true if name matched
|
|
return detectMatched
|
|
|
|
case // push
|
|
webhook_module.HookEventPush:
|
|
pushPayload := payloadAs[*api.PushPayload](payload, inputEvent)
|
|
return matchPushEvent(ctx, gitRepo, commit, pushPayload, evt)
|
|
|
|
case // issues
|
|
webhook_module.HookEventIssues,
|
|
webhook_module.HookEventIssueAssign,
|
|
webhook_module.HookEventIssueLabel,
|
|
webhook_module.HookEventIssueMilestone:
|
|
issuePayload := payloadAs[*api.IssuePayload](payload, inputEvent)
|
|
if matchIssuesEvent(issuePayload, evt) {
|
|
return detectMatched
|
|
}
|
|
return detectNotApplicable
|
|
|
|
case // issue_comment
|
|
webhook_module.HookEventIssueComment,
|
|
// `pull_request_comment` is same as `issue_comment`
|
|
// See https://docs.github.com/en/actions/using-workflows/events-that-trigger-workflows#pull_request_comment-use-issue_comment
|
|
webhook_module.HookEventPullRequestComment:
|
|
issueCommentPayload := payloadAs[*api.IssueCommentPayload](payload, inputEvent)
|
|
if matchIssueCommentEvent(issueCommentPayload, evt) {
|
|
return detectMatched
|
|
}
|
|
return detectNotApplicable
|
|
|
|
case // pull_request
|
|
webhook_module.HookEventPullRequest,
|
|
webhook_module.HookEventPullRequestSync,
|
|
webhook_module.HookEventPullRequestAssign,
|
|
webhook_module.HookEventPullRequestLabel,
|
|
webhook_module.HookEventPullRequestReviewRequest,
|
|
webhook_module.HookEventPullRequestMilestone:
|
|
pullRequestPayload := payloadAs[*api.PullRequestPayload](payload, inputEvent)
|
|
return matchPullRequestEvent(ctx, gitRepo, commit, pullRequestPayload, evt)
|
|
|
|
case // pull_request_review
|
|
webhook_module.HookEventPullRequestReviewApproved,
|
|
webhook_module.HookEventPullRequestReviewRejected:
|
|
reviewPayload := payloadAs[*api.PullRequestPayload](payload, inputEvent)
|
|
if matchPullRequestReviewEvent(reviewPayload, evt) {
|
|
return detectMatched
|
|
}
|
|
return detectNotApplicable
|
|
|
|
case // pull_request_review_comment
|
|
webhook_module.HookEventPullRequestReviewComment:
|
|
reviewCommentPayload := payloadAs[*api.PullRequestPayload](payload, inputEvent)
|
|
if matchPullRequestReviewCommentEvent(reviewCommentPayload, evt) {
|
|
return detectMatched
|
|
}
|
|
return detectNotApplicable
|
|
|
|
case // release
|
|
webhook_module.HookEventRelease:
|
|
releasePayload := payloadAs[*api.ReleasePayload](payload, inputEvent)
|
|
if matchReleaseEvent(releasePayload, evt) {
|
|
return detectMatched
|
|
}
|
|
return detectNotApplicable
|
|
|
|
case // registry_package
|
|
webhook_module.HookEventPackage:
|
|
packagePayload := payloadAs[*api.PackagePayload](payload, inputEvent)
|
|
if matchPackageEvent(packagePayload, evt) {
|
|
return detectMatched
|
|
}
|
|
return detectNotApplicable
|
|
|
|
case // workflow_run
|
|
webhook_module.HookEventWorkflowRun:
|
|
workflowRunPayload := payloadAs[*api.WorkflowRunPayload](payload, inputEvent)
|
|
if matchWorkflowRunEvent(workflowRunPayload, evt) {
|
|
return detectMatched
|
|
}
|
|
return detectNotApplicable
|
|
|
|
case webhook_module.HookEventMergeGroup:
|
|
return matchMergeGroupEvent(payloadAs[*api.MergeGroupPayload](payload, inputEvent), evt)
|
|
|
|
default:
|
|
log.Warn("unsupported event %q", inputEvent)
|
|
return detectNotApplicable
|
|
}
|
|
}
|
|
|
|
func matchMergeGroupEvent(payload *api.MergeGroupPayload, evt *jobparser.Event) detectResult {
|
|
acts := evt.Acts()
|
|
types := optional.FromMapLookup(acts, "types").ValueOrDefault([]string{string(api.HookMergeGroupChecksRequested)})
|
|
if !slices.ContainsFunc(types, func(val string) bool { return matchActivityType(val, string(payload.Action)) }) {
|
|
return detectNotApplicable
|
|
}
|
|
|
|
branches := []string{git.RefName(payload.MergeGroup.BaseRef).ShortName()}
|
|
for cond, values := range acts {
|
|
switch cond {
|
|
case "types":
|
|
case "branches", "branches-ignore":
|
|
skip := util.Iif(cond == "branches", workflowpattern.Skip, workflowpattern.Filter)
|
|
if patterns, err := workflowpattern.CompilePatterns(values...); err != nil || skip(patterns, branches) {
|
|
return detectFilteredOut
|
|
}
|
|
default:
|
|
log.Warn("merge group event unsupported condition %q", cond)
|
|
}
|
|
}
|
|
return detectMatched
|
|
}
|
|
|
|
func matchPushEvent(ctx context.Context, gitRepo *git.Repository, commit *git.Commit, pushPayload *api.PushPayload, evt *jobparser.Event) detectResult {
|
|
// with no special filter parameters
|
|
if len(evt.Acts()) == 0 {
|
|
return detectMatched
|
|
}
|
|
|
|
matchTimes := 0
|
|
hasBranchFilter := false
|
|
hasTagFilter := false
|
|
refName := git.RefName(pushPayload.Ref)
|
|
// all acts conditions should be satisfied
|
|
for cond, vals := range evt.Acts() {
|
|
switch cond {
|
|
case "branches":
|
|
hasBranchFilter = true
|
|
if !refName.IsBranch() {
|
|
break
|
|
}
|
|
patterns, err := workflowpattern.CompilePatterns(vals...)
|
|
if err != nil {
|
|
break
|
|
}
|
|
if !workflowpattern.Skip(patterns, []string{refName.BranchName()}) {
|
|
matchTimes++
|
|
}
|
|
case "branches-ignore":
|
|
hasBranchFilter = true
|
|
if !refName.IsBranch() {
|
|
break
|
|
}
|
|
patterns, err := workflowpattern.CompilePatterns(vals...)
|
|
if err != nil {
|
|
break
|
|
}
|
|
if !workflowpattern.Filter(patterns, []string{refName.BranchName()}) {
|
|
matchTimes++
|
|
}
|
|
case "tags":
|
|
hasTagFilter = true
|
|
if !refName.IsTag() {
|
|
break
|
|
}
|
|
patterns, err := workflowpattern.CompilePatterns(vals...)
|
|
if err != nil {
|
|
break
|
|
}
|
|
if !workflowpattern.Skip(patterns, []string{refName.TagName()}) {
|
|
matchTimes++
|
|
}
|
|
case "tags-ignore":
|
|
hasTagFilter = true
|
|
if !refName.IsTag() {
|
|
break
|
|
}
|
|
patterns, err := workflowpattern.CompilePatterns(vals...)
|
|
if err != nil {
|
|
break
|
|
}
|
|
if !workflowpattern.Filter(patterns, []string{refName.TagName()}) {
|
|
matchTimes++
|
|
}
|
|
case "paths":
|
|
if refName.IsTag() {
|
|
matchTimes++
|
|
break
|
|
}
|
|
filesChanged, err := commit.GetFilesChangedSinceCommit(ctx, gitRepo, pushPayload.Before)
|
|
if err != nil {
|
|
log.Error("GetFilesChangedSinceCommit [commit_sha1: %s]: %v", commit.ID.String(), err)
|
|
return detectNotApplicable
|
|
}
|
|
patterns, err := workflowpattern.CompilePatterns(vals...)
|
|
if err != nil {
|
|
break
|
|
}
|
|
if !workflowpattern.Skip(patterns, filesChanged) {
|
|
matchTimes++
|
|
}
|
|
case "paths-ignore":
|
|
if refName.IsTag() {
|
|
matchTimes++
|
|
break
|
|
}
|
|
filesChanged, err := commit.GetFilesChangedSinceCommit(ctx, gitRepo, pushPayload.Before)
|
|
if err != nil {
|
|
log.Error("GetFilesChangedSinceCommit [commit_sha1: %s]: %v", commit.ID.String(), err)
|
|
return detectNotApplicable
|
|
}
|
|
patterns, err := workflowpattern.CompilePatterns(vals...)
|
|
if err != nil {
|
|
break
|
|
}
|
|
if !workflowpattern.Filter(patterns, filesChanged) {
|
|
matchTimes++
|
|
}
|
|
default:
|
|
log.Warn("push event unsupported condition %q", cond)
|
|
}
|
|
}
|
|
// if both branch and tag filter are defined in the workflow only one needs to match
|
|
if hasBranchFilter && hasTagFilter {
|
|
matchTimes++
|
|
}
|
|
if matchTimes == len(evt.Acts()) {
|
|
return detectMatched
|
|
}
|
|
return detectFilteredOut
|
|
}
|
|
|
|
func matchIssuesEvent(issuePayload *api.IssuePayload, evt *jobparser.Event) bool {
|
|
// with no special filter parameters
|
|
if len(evt.Acts()) == 0 {
|
|
return true
|
|
}
|
|
|
|
matchTimes := 0
|
|
// all acts conditions should be satisfied
|
|
for cond, vals := range evt.Acts() {
|
|
switch cond {
|
|
case "types":
|
|
// See https://docs.github.com/en/actions/using-workflows/events-that-trigger-workflows#issues
|
|
// Actions with the same name:
|
|
// opened, edited, closed, reopened, assigned, unassigned, milestoned, demilestoned
|
|
// Actions need to be converted: see toActivityTypes
|
|
// Unsupported activity types:
|
|
// deleted, transferred, pinned, unpinned, locked, unlocked
|
|
|
|
actions := toActivityTypes(issuePayload.Action, issuePayload.Changes)
|
|
for _, val := range vals {
|
|
if matchActivityType(val, actions...) {
|
|
matchTimes++
|
|
break
|
|
}
|
|
}
|
|
default:
|
|
log.Warn("issue event unsupported condition %q", cond)
|
|
}
|
|
}
|
|
return matchTimes == len(evt.Acts())
|
|
}
|
|
|
|
func matchPullRequestEvent(ctx context.Context, gitRepo *git.Repository, commit *git.Commit, prPayload *api.PullRequestPayload, evt *jobparser.Event) detectResult {
|
|
acts := evt.Acts()
|
|
activityTypeMatched := false
|
|
matchTimes := 0
|
|
|
|
if vals, ok := acts["types"]; !ok {
|
|
// defaultly, only pull request `opened`, `reopened` and `synchronized` will trigger workflow
|
|
// See https://docs.github.com/en/actions/using-workflows/events-that-trigger-workflows#pull_request
|
|
activityTypeMatched = prPayload.Action == api.HookIssueSynchronized || prPayload.Action == api.HookIssueOpened || prPayload.Action == api.HookIssueReOpened
|
|
} else {
|
|
// See https://docs.github.com/en/actions/using-workflows/events-that-trigger-workflows#pull_request
|
|
// Actions with the same name:
|
|
// opened, edited, closed, reopened, assigned, unassigned, review_requested, review_request_removed, milestoned, demilestoned
|
|
// Actions need to be converted: see toActivityTypes
|
|
// Unsupported activity types:
|
|
// converted_to_draft, ready_for_review, locked, unlocked, auto_merge_enabled, auto_merge_disabled
|
|
|
|
actions := toActivityTypes(prPayload.Action, prPayload.Changes)
|
|
log.Trace("matching pull_request %v with %v", actions, vals)
|
|
for _, val := range vals {
|
|
if matchActivityType(val, actions...) {
|
|
activityTypeMatched = true
|
|
matchTimes++
|
|
break
|
|
}
|
|
}
|
|
}
|
|
|
|
var (
|
|
headCommit = commit
|
|
err error
|
|
)
|
|
if (len(acts["paths"]) > 0 || len(acts["paths-ignore"]) > 0) && commit.ID.String() != prPayload.PullRequest.Head.Sha {
|
|
headCommit, err = gitRepo.GetCommit(ctx, prPayload.PullRequest.Head.Sha)
|
|
if err != nil {
|
|
log.Error("GetCommit [ref: %s]: %v", prPayload.PullRequest.Head.Sha, err)
|
|
return detectNotApplicable
|
|
}
|
|
}
|
|
|
|
// all acts conditions should be satisfied
|
|
for cond, vals := range acts {
|
|
switch cond {
|
|
case "types":
|
|
// types have been checked
|
|
continue
|
|
case "branches":
|
|
refName := git.RefName(prPayload.PullRequest.Base.Ref)
|
|
patterns, err := workflowpattern.CompilePatterns(vals...)
|
|
if err != nil {
|
|
break
|
|
}
|
|
if !workflowpattern.Skip(patterns, []string{refName.ShortName()}) {
|
|
matchTimes++
|
|
}
|
|
case "branches-ignore":
|
|
refName := git.RefName(prPayload.PullRequest.Base.Ref)
|
|
patterns, err := workflowpattern.CompilePatterns(vals...)
|
|
if err != nil {
|
|
break
|
|
}
|
|
if !workflowpattern.Filter(patterns, []string{refName.ShortName()}) {
|
|
matchTimes++
|
|
}
|
|
case "paths":
|
|
filesChanged, err := headCommit.GetFilesChangedSinceCommit(ctx, gitRepo, prPayload.PullRequest.MergeBase)
|
|
if err != nil {
|
|
log.Error("GetFilesChangedSinceCommit [commit_sha1: %s]: %v", headCommit.ID.String(), err)
|
|
return detectNotApplicable
|
|
}
|
|
patterns, err := workflowpattern.CompilePatterns(vals...)
|
|
if err != nil {
|
|
break
|
|
}
|
|
if !workflowpattern.Skip(patterns, filesChanged) {
|
|
matchTimes++
|
|
}
|
|
case "paths-ignore":
|
|
filesChanged, err := headCommit.GetFilesChangedSinceCommit(ctx, gitRepo, prPayload.PullRequest.MergeBase)
|
|
if err != nil {
|
|
log.Error("GetFilesChangedSinceCommit [commit_sha1: %s]: %v", headCommit.ID.String(), err)
|
|
return detectNotApplicable
|
|
}
|
|
patterns, err := workflowpattern.CompilePatterns(vals...)
|
|
if err != nil {
|
|
break
|
|
}
|
|
if !workflowpattern.Filter(patterns, filesChanged) {
|
|
matchTimes++
|
|
}
|
|
default:
|
|
log.Warn("pull request event unsupported condition %q", cond)
|
|
}
|
|
}
|
|
if !activityTypeMatched {
|
|
return detectNotApplicable
|
|
}
|
|
if matchTimes != len(evt.Acts()) {
|
|
return detectFilteredOut
|
|
}
|
|
return detectMatched
|
|
}
|
|
|
|
func matchIssueCommentEvent(issueCommentPayload *api.IssueCommentPayload, evt *jobparser.Event) bool {
|
|
// with no special filter parameters
|
|
if len(evt.Acts()) == 0 {
|
|
return true
|
|
}
|
|
|
|
matchTimes := 0
|
|
// all acts conditions should be satisfied
|
|
for cond, vals := range evt.Acts() {
|
|
switch cond {
|
|
case "types":
|
|
// See https://docs.github.com/en/actions/using-workflows/events-that-trigger-workflows#issue_comment
|
|
// Actions with the same name:
|
|
// created, edited, deleted
|
|
// Actions need to be converted:
|
|
// NONE
|
|
// Unsupported activity types:
|
|
// NONE
|
|
|
|
for _, val := range vals {
|
|
if matchActivityType(val, string(issueCommentPayload.Action)) {
|
|
matchTimes++
|
|
break
|
|
}
|
|
}
|
|
default:
|
|
log.Warn("issue comment event unsupported condition %q", cond)
|
|
}
|
|
}
|
|
return matchTimes == len(evt.Acts())
|
|
}
|
|
|
|
func matchPullRequestReviewEvent(prPayload *api.PullRequestPayload, evt *jobparser.Event) bool {
|
|
// with no special filter parameters
|
|
if len(evt.Acts()) == 0 {
|
|
return true
|
|
}
|
|
|
|
matchTimes := 0
|
|
// all acts conditions should be satisfied
|
|
for cond, vals := range evt.Acts() {
|
|
switch cond {
|
|
case "types":
|
|
// See https://docs.github.com/en/actions/using-workflows/events-that-trigger-workflows#pull_request_review
|
|
// Activity types with the same name:
|
|
// NONE
|
|
// Activity types need to be converted:
|
|
// reviewed -> submitted
|
|
// reviewed -> edited
|
|
// Unsupported activity types:
|
|
// dismissed
|
|
|
|
actions := make([]string, 0)
|
|
if prPayload.Action == api.HookIssueReviewed {
|
|
// the `reviewed` HookIssueAction can match the two activity types: `submitted` and `edited`
|
|
// See https://docs.github.com/en/actions/using-workflows/events-that-trigger-workflows#pull_request_review
|
|
actions = append(actions, "submitted", "edited")
|
|
}
|
|
|
|
for _, val := range vals {
|
|
if matchActivityType(val, actions...) {
|
|
matchTimes++
|
|
break
|
|
}
|
|
}
|
|
default:
|
|
log.Warn("pull request review event unsupported condition %q", cond)
|
|
}
|
|
}
|
|
return matchTimes == len(evt.Acts())
|
|
}
|
|
|
|
func matchPullRequestReviewCommentEvent(prPayload *api.PullRequestPayload, evt *jobparser.Event) bool {
|
|
// with no special filter parameters
|
|
if len(evt.Acts()) == 0 {
|
|
return true
|
|
}
|
|
|
|
matchTimes := 0
|
|
// all acts conditions should be satisfied
|
|
for cond, vals := range evt.Acts() {
|
|
switch cond {
|
|
case "types":
|
|
// See https://docs.github.com/en/actions/using-workflows/events-that-trigger-workflows#pull_request_review_comment
|
|
// Activity types with the same name:
|
|
// NONE
|
|
// Activity types need to be converted:
|
|
// reviewed -> created
|
|
// reviewed -> edited
|
|
// Unsupported activity types:
|
|
// deleted
|
|
|
|
actions := make([]string, 0)
|
|
if prPayload.Action == api.HookIssueReviewed {
|
|
// the `reviewed` HookIssueAction can match the two activity types: `created` and `edited`
|
|
// See https://docs.github.com/en/actions/using-workflows/events-that-trigger-workflows#pull_request_review_comment
|
|
actions = append(actions, "created", "edited")
|
|
}
|
|
|
|
for _, val := range vals {
|
|
if matchActivityType(val, actions...) {
|
|
matchTimes++
|
|
break
|
|
}
|
|
}
|
|
default:
|
|
log.Warn("pull request review comment event unsupported condition %q", cond)
|
|
}
|
|
}
|
|
return matchTimes == len(evt.Acts())
|
|
}
|
|
|
|
func matchReleaseEvent(payload *api.ReleasePayload, evt *jobparser.Event) bool {
|
|
// with no special filter parameters
|
|
if len(evt.Acts()) == 0 {
|
|
return true
|
|
}
|
|
|
|
matchTimes := 0
|
|
// all acts conditions should be satisfied
|
|
for cond, vals := range evt.Acts() {
|
|
switch cond {
|
|
case "types":
|
|
// See https://docs.github.com/en/actions/using-workflows/events-that-trigger-workflows#release
|
|
// Activity types with the same name:
|
|
// published
|
|
// Activity types need to be converted:
|
|
// updated -> edited
|
|
// Unsupported activity types:
|
|
// unpublished, created, deleted, prereleased, released
|
|
|
|
action := payload.Action
|
|
switch action {
|
|
case api.HookReleaseUpdated:
|
|
action = "edited"
|
|
}
|
|
for _, val := range vals {
|
|
if matchActivityType(val, string(action)) {
|
|
matchTimes++
|
|
break
|
|
}
|
|
}
|
|
default:
|
|
log.Warn("release event unsupported condition %q", cond)
|
|
}
|
|
}
|
|
return matchTimes == len(evt.Acts())
|
|
}
|
|
|
|
func matchPackageEvent(payload *api.PackagePayload, evt *jobparser.Event) bool {
|
|
// with no special filter parameters
|
|
if len(evt.Acts()) == 0 {
|
|
return true
|
|
}
|
|
|
|
matchTimes := 0
|
|
// all acts conditions should be satisfied
|
|
for cond, vals := range evt.Acts() {
|
|
switch cond {
|
|
case "types":
|
|
// See https://docs.github.com/en/actions/using-workflows/events-that-trigger-workflows#registry_package
|
|
// Activity types with the same name:
|
|
// NONE
|
|
// Activity types need to be converted:
|
|
// created -> published
|
|
// Unsupported activity types:
|
|
// updated
|
|
|
|
action := payload.Action
|
|
switch action {
|
|
case api.HookPackageCreated:
|
|
action = "published"
|
|
}
|
|
for _, val := range vals {
|
|
if matchActivityType(val, string(action)) {
|
|
matchTimes++
|
|
break
|
|
}
|
|
}
|
|
default:
|
|
log.Warn("package event unsupported condition %q", cond)
|
|
}
|
|
}
|
|
return matchTimes == len(evt.Acts())
|
|
}
|
|
|
|
func matchWorkflowRunEvent(payload *api.WorkflowRunPayload, evt *jobparser.Event) bool {
|
|
// with no special filter parameters
|
|
if len(evt.Acts()) == 0 {
|
|
return true
|
|
}
|
|
|
|
matchTimes := 0
|
|
// all acts conditions should be satisfied
|
|
for cond, vals := range evt.Acts() {
|
|
switch cond {
|
|
case "types":
|
|
action := payload.Action
|
|
for _, val := range vals {
|
|
if matchActivityType(val, action) {
|
|
matchTimes++
|
|
break
|
|
}
|
|
}
|
|
case "workflows":
|
|
workflow := payload.Workflow
|
|
patterns, err := workflowpattern.CompilePatterns(vals...)
|
|
if err != nil {
|
|
break
|
|
}
|
|
if !workflowpattern.Skip(patterns, []string{workflow.Name}) {
|
|
matchTimes++
|
|
}
|
|
case "branches":
|
|
patterns, err := workflowpattern.CompilePatterns(vals...)
|
|
if err != nil {
|
|
break
|
|
}
|
|
if !workflowpattern.Skip(patterns, []string{payload.WorkflowRun.HeadBranch}) {
|
|
matchTimes++
|
|
}
|
|
case "branches-ignore":
|
|
patterns, err := workflowpattern.CompilePatterns(vals...)
|
|
if err != nil {
|
|
break
|
|
}
|
|
if !workflowpattern.Filter(patterns, []string{payload.WorkflowRun.HeadBranch}) {
|
|
matchTimes++
|
|
}
|
|
default:
|
|
log.Warn("workflow run event unsupported condition %q", cond)
|
|
}
|
|
}
|
|
return matchTimes == len(evt.Acts())
|
|
}
|
|
|
|
// toActivityTypes returns several types because one label update can both add and remove labels
|
|
func toActivityTypes(action api.HookIssueAction, changes *api.ChangesPayload) []string {
|
|
switch action {
|
|
case api.HookIssueSynchronized:
|
|
return []string{"synchronize"}
|
|
case api.HookIssueLabelUpdated:
|
|
var types []string
|
|
if len(changes.AddedLabels) > 0 {
|
|
types = append(types, "labeled")
|
|
}
|
|
if len(changes.RemovedLabels) > 0 {
|
|
types = append(types, "unlabeled")
|
|
}
|
|
return types
|
|
case api.HookIssueLabelCleared:
|
|
return []string{"unlabeled"}
|
|
default:
|
|
return []string{string(action)}
|
|
}
|
|
}
|
|
|
|
// matchActivityType treats an invalid user-provided pattern as no match instead of panicking
|
|
func matchActivityType(pattern string, actions ...string) bool {
|
|
g, err := glob.Compile(pattern, '/')
|
|
if err != nil {
|
|
log.Debug("invalid activity type pattern %q: %v", pattern, err)
|
|
return false
|
|
}
|
|
return slices.ContainsFunc(actions, g.Match)
|
|
}
|