mirror of
https://codeberg.org/forgejo/forgejo.git
synced 2026-05-13 06:20:24 +00:00
[v13.0/forgejo] feat: allow workflows to control cancellation of existing jobs (#9797)
Partial backport of #9434. Fixes a bug: it was intended that pushes to a branch and pushes to a pull request would cancel any previous running job from the same workflow, however this functionality only worked on a `on: push` workflow. This PR fixes it for an `on: pull_request` workflow. Adds a feature: `concurrency.cancel-in-progress` can be used to override the automatic cancellation behaviour and disable it. It can be disabled unconditionally in a workflow: ```yaml concurrency: cancel-in-progress: false ``` Or it can be disabled with some logic; for example, keeping the cancel behaviour on PRs but disabling it otherwise: ```yaml concurrency: cancel-in-progress: ${{ github.event_name == 'pull_request' }} ``` Only a small subset of automated tests were applicable for backport, so I supplemented with manual testing in these cases: | | Expected | Actual | | ------------------------------------------------------------------ | ------------- | ------------- | | Default behaviour: | | | | on: pull_request -- push to a PR when it's already running | Cancelled | Cancelled | | on: push -- push to a branch (eg. main) when it's already running | Cancelled | Cancelled | | on: workflow_dispatch -- run again when it is already running | Multiple Runs | Multiple Runs | | | | | | Set cancel-in-progress: true | | | | on: pull_request -- push to a PR when it's already running | Cancelled | Cancelled | | on: push -- push to a branch (eg. main) when it's already running | Cancelled | Cancelled | | on: workflow_dispatch -- run again when it is already running | Multiple Runs | Multiple Runs | | | | | | Set cancel-in-progress: false | | | | on: pull_request -- push to a PR when it's already running | Multiple Runs | Multiple Runs | | on: push -- push to a branch (eg. main) when it's already running | Multiple Runs | Multiple Runs | | on: workflow_dispatch -- run again when it is already running | Multiple Runs | Multiple Runs | | | | | | Set cancel-in-progress: ${{ github.event_name == 'pull_request' }} | | | | on: pull_request -- push to a PR when it's already running | Cancelled | Cancelled | | on: push -- push to a branch (eg. main) when it's already running | Multiple Runs | Multiple Runs | | on: workflow_dispatch -- run again when it is already running | Multiple Runs | Multiple Runs | ## Checklist The [contributor guide](https://forgejo.org/docs/next/contributor/) contains information that will be helpful to first time contributors. There also are a few [conditions for merging Pull Requests in Forgejo repositories](https://codeberg.org/forgejo/governance/src/branch/main/PullRequestsAgreement.md). You are also welcome to join the [Forgejo development chatroom](https://matrix.to/#/#forgejo-development:matrix.org). ### Tests - I added test coverage for Go changes... - [x] in their respective `*_test.go` for unit tests. - [ ] in the `tests/integration` directory if it involves interactions with a live Forgejo server. - I added test coverage for JavaScript changes... - [ ] in `web_src/js/*.test.js` if it can be unit tested. - [ ] in `tests/e2e/*.test.e2e.js` if it requires interactions with a live Forgejo server (see also the [developer guide for JavaScript testing](https://codeberg.org/forgejo/forgejo/src/branch/forgejo/tests/e2e/README.md#end-to-end-tests)). ### Documentation - [ ] I created a pull request [to the documentation](https://codeberg.org/forgejo/docs) to explain to Forgejo users how to use this change. - **TODO:** Will backport the relevant documentation. - [ ] I did not document these changes and I do not expect someone else to do it. ### Release notes - [ ] I do not want this change to show in the release notes. - [x] I want the title to show in the release notes with a link to this pull request. - [ ] I want the content of the `release-notes/<pull request number>.md` to be be used for the release notes instead of the title. <!--start release-notes-assistant--> ## Release notes <!--URL:https://codeberg.org/forgejo/forgejo--> - Features - [PR](https://codeberg.org/forgejo/forgejo/pulls/9797): <!--number 9797 --><!--line 0 --><!--description ZmVhdDogYWxsb3cgd29ya2Zsb3dzIHRvIGNvbnRyb2wgY2FuY2VsbGF0aW9uIG9mIGV4aXN0aW5nIGpvYnM=-->feat: allow workflows to control cancellation of existing jobs<!--description--> <!--end release-notes-assistant--> Reviewed-on: https://codeberg.org/forgejo/forgejo/pulls/9797 Reviewed-by: Earl Warren <earl-warren@noreply.codeberg.org> Reviewed-by: Michael Kriese <michael.kriese@gmx.de> Co-authored-by: Mathieu Fenniak <mathieu@fenniak.net> Co-committed-by: Mathieu Fenniak <mathieu@fenniak.net>
This commit is contained in:
parent
aaf7960a77
commit
5f757d9e83
9 changed files with 617 additions and 53 deletions
2
go.mod
2
go.mod
|
|
@ -10,7 +10,7 @@ require (
|
|||
code.forgejo.org/forgejo/go-rpmutils v1.0.0
|
||||
code.forgejo.org/forgejo/levelqueue v1.0.0
|
||||
code.forgejo.org/forgejo/reply v1.0.2
|
||||
code.forgejo.org/forgejo/runner/v11 v11.1.1
|
||||
code.forgejo.org/forgejo/runner/v11 v11.1.2
|
||||
code.forgejo.org/go-chi/binding v1.0.1
|
||||
code.forgejo.org/go-chi/cache v1.0.1
|
||||
code.forgejo.org/go-chi/captcha v1.0.2
|
||||
|
|
|
|||
4
go.sum
4
go.sum
|
|
@ -28,8 +28,8 @@ code.forgejo.org/forgejo/levelqueue v1.0.0 h1:9krYpU6BM+j/1Ntj6m+VCAIu0UNnne1/Uf
|
|||
code.forgejo.org/forgejo/levelqueue v1.0.0/go.mod h1:fmG6zhVuqim2rxSFOoasgXO8V2W/k9U31VVYqLIRLhQ=
|
||||
code.forgejo.org/forgejo/reply v1.0.2 h1:dMhQCHV6/O3L5CLWNTol+dNzDAuyCK88z4J/lCdgFuQ=
|
||||
code.forgejo.org/forgejo/reply v1.0.2/go.mod h1:RyZUfzQLc+fuLIGjTSQWDAJWPiL4WtKXB/FifT5fM7U=
|
||||
code.forgejo.org/forgejo/runner/v11 v11.1.1 h1:CoSfxBOLKLMJZq5VhKd5ZIUc3tCf04iyFx926s+zaMA=
|
||||
code.forgejo.org/forgejo/runner/v11 v11.1.1/go.mod h1:9f0D2EG7uabL+cv71SWHKrGgo2vmLpvko0QLmtn3RDE=
|
||||
code.forgejo.org/forgejo/runner/v11 v11.1.2 h1:jM5YsNmScH11VJEwmvsTUiqGjAqtiUzBhQ65BIo8ZOs=
|
||||
code.forgejo.org/forgejo/runner/v11 v11.1.2/go.mod h1:9f0D2EG7uabL+cv71SWHKrGgo2vmLpvko0QLmtn3RDE=
|
||||
code.forgejo.org/forgejo/ssh v0.0.0-20241211213324-5fc306ca0616 h1:kEZL84+02jY9RxXM4zHBWZ3Fml0B09cmP1LGkDsCfIA=
|
||||
code.forgejo.org/forgejo/ssh v0.0.0-20241211213324-5fc306ca0616/go.mod h1:zpHEXBstFnQYtGnB8k8kQLol82umzn/2/snG7alWVD8=
|
||||
code.forgejo.org/go-chi/binding v1.0.1 h1:coKNI+X1NzRN7X85LlrpvBRqk0TXpJ+ja28vusQWEuY=
|
||||
|
|
|
|||
|
|
@ -25,6 +25,18 @@ import (
|
|||
"xorm.io/builder"
|
||||
)
|
||||
|
||||
type ConcurrencyMode int
|
||||
|
||||
const (
|
||||
// Don't enforce concurrency control. Note that you won't find `UnlimitedConcurrency` implemented directly in the
|
||||
// code; setting it on an `ActionRun` prevents the other limiting behaviors.
|
||||
UnlimitedConcurrency ConcurrencyMode = iota
|
||||
// Queue behind other jobs with the same concurrency group -- to be supported in Forgejo v14
|
||||
QueueBehind
|
||||
// Cancel other jobs with the same concurrency group
|
||||
CancelInProgress
|
||||
)
|
||||
|
||||
// ActionRun represents a run of a workflow file
|
||||
type ActionRun struct {
|
||||
ID int64
|
||||
|
|
@ -57,6 +69,8 @@ type ActionRun struct {
|
|||
Updated timeutil.TimeStamp `xorm:"updated"`
|
||||
NotifyEmail bool
|
||||
|
||||
ConcurrencyType ConcurrencyMode `xorm:"-"` // Forgejo v13 note: this is a persisted field in v14+
|
||||
|
||||
PreExecutionError string `xorm:"LONGTEXT"` // used to report errors that blocked execution of a workflow
|
||||
}
|
||||
|
||||
|
|
|
|||
|
|
@ -14,11 +14,11 @@ import (
|
|||
"forgejo.org/modules/git"
|
||||
"forgejo.org/modules/json"
|
||||
"forgejo.org/modules/setting"
|
||||
|
||||
"code.forgejo.org/forgejo/runner/v11/act/model"
|
||||
)
|
||||
|
||||
// GenerateGiteaContext generate the gitea context without token and gitea_runtime_token
|
||||
// job can be nil when generating a context for parsing workflow-level expressions
|
||||
func GenerateGiteaContext(run *actions_model.ActionRun, job *actions_model.ActionRunJob) map[string]any {
|
||||
func generateGiteaContextForRun(run *actions_model.ActionRun) *model.GithubContext {
|
||||
event := map[string]any{}
|
||||
_ = json.Unmarshal([]byte(run.EventPayload), &event)
|
||||
|
||||
|
|
@ -41,45 +41,64 @@ func GenerateGiteaContext(run *actions_model.ActionRun, job *actions_model.Actio
|
|||
|
||||
refName := git.RefName(ref)
|
||||
|
||||
gitContext := map[string]any{
|
||||
gitContextObj := &model.GithubContext{
|
||||
// standard contexts, see https://docs.github.com/en/actions/learn-github-actions/contexts#github-context
|
||||
"action": "", // string, The name of the action currently running, or the id of a step. GitHub removes special characters, and uses the name __run when the current step runs a script without an id. If you use the same action more than once in the same job, the name will include a suffix with the sequence number with underscore before it. For example, the first script you run will have the name __run, and the second script will be named __run_2. Similarly, the second invocation of actions/checkout will be actionscheckout2.
|
||||
"action_path": "", // string, The path where an action is located. This property is only supported in composite actions. You can use this path to access files located in the same repository as the action.
|
||||
"action_ref": "", // string, For a step executing an action, this is the ref of the action being executed. For example, v2.
|
||||
"action_repository": "", // string, For a step executing an action, this is the owner and repository name of the action. For example, actions/checkout.
|
||||
"action_status": "", // string, For a composite action, the current result of the composite action.
|
||||
"actor": run.TriggerUser.Name, // string, The username of the user that triggered the initial workflow run. If the workflow run is a re-run, this value may differ from github.triggering_actor. Any workflow re-runs will use the privileges of github.actor, even if the actor initiating the re-run (github.triggering_actor) has different privileges.
|
||||
"api_url": setting.AppURL + "api/v1", // string, The URL of the GitHub REST API.
|
||||
"base_ref": baseRef, // string, The base_ref or target branch of the pull request in a workflow run. This property is only available when the event that triggers a workflow run is either pull_request or pull_request_target.
|
||||
"env": "", // string, Path on the runner to the file that sets environment variables from workflow commands. This file is unique to the current step and is a different file for each step in a job. For more information, see "Workflow commands for GitHub Actions."
|
||||
"event": event, // object, The full event webhook payload. You can access individual properties of the event using this context. This object is identical to the webhook payload of the event that triggered the workflow run, and is different for each event. The webhooks for each GitHub Actions event is linked in "Events that trigger workflows." For example, for a workflow run triggered by the push event, this object contains the contents of the push webhook payload.
|
||||
"event_name": run.TriggerEvent, // string, The name of the event that triggered the workflow run.
|
||||
"event_path": "", // string, The path to the file on the runner that contains the full event webhook payload.
|
||||
"graphql_url": "", // string, The URL of the GitHub GraphQL API.
|
||||
"head_ref": headRef, // string, The head_ref or source branch of the pull request in a workflow run. This property is only available when the event that triggers a workflow run is either pull_request or pull_request_target.
|
||||
"job": "", // string, The job_id of the current job.
|
||||
"ref": ref, // string, The fully-formed ref of the branch or tag that triggered the workflow run. For workflows triggered by push, this is the branch or tag ref that was pushed. For workflows triggered by pull_request, this is the pull request merge branch. For workflows triggered by release, this is the release tag created. For other triggers, this is the branch or tag ref that triggered the workflow run. This is only set if a branch or tag is available for the event type. The ref given is fully-formed, meaning that for branches the format is refs/heads/<branch_name>, for pull requests it is refs/pull/<pr_number>/merge, and for tags it is refs/tags/<tag_name>. For example, refs/heads/feature-branch-1.
|
||||
"ref_name": refName.ShortName(), // string, The short ref name of the branch or tag that triggered the workflow run. This value matches the branch or tag name shown on GitHub. For example, feature-branch-1.
|
||||
"ref_protected": false, // boolean, true if branch protections are configured for the ref that triggered the workflow run.
|
||||
"ref_type": refName.RefType(), // string, The type of ref that triggered the workflow run. Valid values are branch or tag.
|
||||
"path": "", // string, Path on the runner to the file that sets system PATH variables from workflow commands. This file is unique to the current step and is a different file for each step in a job. For more information, see "Workflow commands for GitHub Actions."
|
||||
"repository": run.Repo.OwnerName + "/" + run.Repo.Name, // string, The owner and repository name. For example, Codertocat/Hello-World.
|
||||
"repository_owner": run.Repo.OwnerName, // string, The repository owner's name. For example, Codertocat.
|
||||
"repositoryUrl": run.Repo.HTMLURL(), // string, The Git URL to the repository. For example, git://github.com/codertocat/hello-world.git.
|
||||
"retention_days": "", // string, The number of days that workflow run logs and artifacts are kept.
|
||||
"run_id": "", // string, A unique number for each workflow run within a repository. This number does not change if you re-run the workflow run.
|
||||
"run_number": fmt.Sprint(run.Index), // string, A unique number for each run of a particular workflow in a repository. This number begins at 1 for the workflow's first run, and increments with each new run. This number does not change if you re-run the workflow run.
|
||||
"run_attempt": "", // string, A unique number for each attempt of a particular workflow run in a repository. This number begins at 1 for the workflow run's first attempt, and increments with each re-run.
|
||||
"secret_source": "Actions", // string, The source of a secret used in a workflow. Possible values are None, Actions, Dependabot, or Codespaces.
|
||||
"server_url": setting.AppURL, // string, The URL of the GitHub server. For example: https://github.com.
|
||||
"sha": sha, // string, The commit SHA that triggered the workflow. The value of this commit SHA depends on the event that triggered the workflow. For more information, see "Events that trigger workflows." For example, ffac537e6cbbf934b08745a378932722df287a53.
|
||||
"triggering_actor": "", // string, The username of the user that initiated the workflow run. If the workflow run is a re-run, this value may differ from github.actor. Any workflow re-runs will use the privileges of github.actor, even if the actor initiating the re-run (github.triggering_actor) has different privileges.
|
||||
"workflow": run.WorkflowID, // string, The name of the workflow. If the workflow file doesn't specify a name, the value of this property is the full path of the workflow file in the repository.
|
||||
"workspace": "", // string, The default working directory on the runner for steps, and the default location of your repository when using the checkout action.
|
||||
|
||||
// additional contexts
|
||||
"gitea_default_actions_url": setting.Actions.DefaultActionsURL.URL(),
|
||||
APIURL: setting.AppURL + "api/v1", // string, The URL of the GitHub REST API.
|
||||
Action: "", // string, The name of the action currently running, or the id of a step. GitHub removes special characters, and uses the name __run when the current step runs a script without an id. If you use the same action more than once in the same job, the name will include a suffix with the sequence number with underscore before it. For example, the first script you run will have the name __run, and the second script will be named __run_2. Similarly, the second invocation of actions/checkout will be actionscheckout2.
|
||||
ActionPath: "", // string, The path where an action is located. This property is only supported in composite actions. You can use this path to access files located in the same repository as the action.
|
||||
ActionRef: "", // string, For a step executing an action, this is the ref of the action being executed. For example, v2.
|
||||
ActionRepository: "", // string, For a step executing an action, this is the owner and repository name of the action. For example, actions/checkout.
|
||||
BaseRef: baseRef, // string, The base_ref or target branch of the pull request in a workflow run. This property is only available when the event that triggers a workflow run is either pull_request or pull_request_target.
|
||||
Event: event, // object, The full event webhook payload. You can access individual properties of the event using this context. This object is identical to the webhook payload of the event that triggered the workflow run, and is different for each event. The webhooks for each GitHub Actions event is linked in "Events that trigger workflows." For example, for a workflow run triggered by the push event, this object contains the contents of the push webhook payload.
|
||||
EventName: run.TriggerEvent, // string, The name of the event that triggered the workflow run.
|
||||
EventPath: "", // string, The path to the file on the runner that contains the full event webhook payload.
|
||||
GraphQLURL: "", // string, The URL of the GitHub GraphQL API.
|
||||
HeadRef: headRef, // string, The head_ref or source branch of the pull request in a workflow run. This property is only available when the event that triggers a workflow run is either pull_request or pull_request_target.
|
||||
Job: "", // string, The job_id of the current job.
|
||||
Ref: ref, // string, The fully-formed ref of the branch or tag that triggered the workflow run. For workflows triggered by push, this is the branch or tag ref that was pushed. For workflows triggered by pull_request, this is the pull request merge branch. For workflows triggered by release, this is the release tag created. For other triggers, this is the branch or tag ref that triggered the workflow run. This is only set if a branch or tag is available for the event type. The ref given is fully-formed, meaning that for branches the format is refs/heads/<branch_name>, for pull requests it is refs/pull/<pr_number>/merge, and for tags it is refs/tags/<tag_name>. For example, refs/heads/feature-branch-1.
|
||||
RefName: refName.ShortName(), // string, The short ref name of the branch or tag that triggered the workflow run. This value matches the branch or tag name shown on GitHub. For example, feature-branch-1.
|
||||
RefType: refName.RefType(), // string, The type of ref that triggered the workflow run. Valid values are branch or tag.
|
||||
Repository: run.Repo.OwnerName + "/" + run.Repo.Name, // string, The owner and repository name. For example, Codertocat/Hello-World.
|
||||
RepositoryOwner: run.Repo.OwnerName, // string, The repository owner's name. For example, Codertocat.
|
||||
RetentionDays: "", // string, The number of days that workflow run logs and artifacts are kept.
|
||||
RunID: "", // string, A unique number for each workflow run within a repository. This number does not change if you re-run the workflow run.
|
||||
RunNumber: fmt.Sprint(run.Index), // string, A unique number for each run of a particular workflow in a repository. This number begins at 1 for the workflow's first run, and increments with each new run. This number does not change if you re-run the workflow run.
|
||||
RunAttempt: "", // string, A unique number for each attempt of a particular workflow run in a repository. This number begins at 1 for the workflow run's first attempt, and increments with each re-run.
|
||||
ServerURL: setting.AppURL, // string, The URL of the GitHub server. For example: https://github.com.
|
||||
Sha: sha, // string, The commit SHA that triggered the workflow. The value of this commit SHA depends on the event that triggered the workflow. For more information, see "Events that trigger workflows." For example, ffac537e6cbbf934b08745a378932722df287a53.
|
||||
Workflow: run.WorkflowID, // string, The name of the workflow. If the workflow file doesn't specify a name, the value of this property is the full path of the workflow file in the repository.
|
||||
Workspace: "", // string, The default working directory on the runner for steps, and the default location of your repository when using the checkout action.
|
||||
}
|
||||
if run.TriggerUser != nil {
|
||||
gitContextObj.Actor = run.TriggerUser.Name // string, The username of the user that triggered the initial workflow run. If the workflow run is a re-run, this value may differ from github.triggering_actor. Any workflow re-runs will use the privileges of github.actor, even if the actor initiating the re-run (github.triggering_actor) has different privileges.
|
||||
}
|
||||
|
||||
return gitContextObj
|
||||
}
|
||||
|
||||
// GenerateGiteaContext generate the gitea context without token and gitea_runtime_token
|
||||
// job can be nil when generating a context for parsing workflow-level expressions
|
||||
func GenerateGiteaContext(run *actions_model.ActionRun, job *actions_model.ActionRunJob) map[string]any {
|
||||
gitContextObj := generateGiteaContextForRun(run)
|
||||
|
||||
gitContext, _ := githubContextToMap(gitContextObj)
|
||||
|
||||
// standard contexts, see https://docs.github.com/en/actions/learn-github-actions/contexts#github-context
|
||||
gitContext["action_status"] = "" // string, For a composite action, the current result of the composite action.
|
||||
gitContext["actor"] = run.TriggerUser.Name // string, The username of the user that triggered the initial workflow run. If the workflow run is a re-run, this value may differ from github.triggering_actor. Any workflow re-runs will use the privileges of github.actor, even if the actor initiating the re-run (github.triggering_actor) has different privileges.
|
||||
gitContext["env"] = "" // string, Path on the runner to the file that sets environment variables from workflow commands. This file is unique to the current step and is a different file for each step in a job. For more information, see "Workflow commands for GitHub Actions."
|
||||
gitContext["path"] = "" // string, Path on the runner to the file that sets system PATH variables from workflow commands. This file is unique to the current step and is a different file for each step in a job. For more information, see "Workflow commands for GitHub Actions."
|
||||
gitContext["ref_protected"] = false // boolean, true if branch protections are configured for the ref that triggered the workflow run.
|
||||
gitContext["repository_owner"] = run.Repo.OwnerName // string, The repository owner's name. For example, Codertocat.
|
||||
gitContext["repository"] = run.Repo.OwnerName + "/" + run.Repo.Name // string, The owner and repository name. For example, Codertocat/Hello-World.
|
||||
gitContext["repositoryUrl"] = run.Repo.HTMLURL() // string, The Git URL to the repository. For example, git://github.com/codertocat/hello-world.git.
|
||||
gitContext["secret_source"] = "Actions" // string, The source of a secret used in a workflow. Possible values are None, Actions, Dependabot, or Codespaces.
|
||||
gitContext["server_url"] = setting.AppURL // string, The URL of the GitHub server. For example: https://github.com.
|
||||
gitContext["triggering_actor"] = "" // string, The username of the user that initiated the workflow run. If the workflow run is a re-run, this value may differ from github.actor. Any workflow re-runs will use the privileges of github.actor, even if the actor initiating the re-run (github.triggering_actor) has different privileges.
|
||||
gitContext["workflow"] = run.WorkflowID // string, The name of the workflow. If the workflow file doesn't specify a name, the value of this property is the full path of the workflow file in the repository.
|
||||
|
||||
// additional contexts
|
||||
gitContext["gitea_default_actions_url"] = setting.Actions.DefaultActionsURL.URL()
|
||||
|
||||
if job != nil {
|
||||
gitContext["job"] = job.JobID
|
||||
|
|
@ -90,6 +109,21 @@ func GenerateGiteaContext(run *actions_model.ActionRun, job *actions_model.Actio
|
|||
return gitContext
|
||||
}
|
||||
|
||||
func githubContextToMap(gitContext *model.GithubContext) (map[string]any, error) {
|
||||
jsonBytes, err := json.Marshal(gitContext)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("failed to marshal struct: %w", err)
|
||||
}
|
||||
|
||||
var result map[string]any
|
||||
err = json.Unmarshal(jsonBytes, &result)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("failed to unmarshal to map: %w", err)
|
||||
}
|
||||
|
||||
return result, nil
|
||||
}
|
||||
|
||||
type TaskNeed struct {
|
||||
Result actions_model.Status
|
||||
Outputs map[string]string
|
||||
|
|
|
|||
|
|
@ -7,7 +7,13 @@ import (
|
|||
"testing"
|
||||
|
||||
actions_model "forgejo.org/models/actions"
|
||||
"forgejo.org/models/repo"
|
||||
"forgejo.org/models/unittest"
|
||||
"forgejo.org/models/user"
|
||||
actions_module "forgejo.org/modules/actions"
|
||||
"forgejo.org/modules/json"
|
||||
"forgejo.org/modules/setting"
|
||||
webhook_module "forgejo.org/modules/webhook"
|
||||
|
||||
"github.com/stretchr/testify/assert"
|
||||
"github.com/stretchr/testify/require"
|
||||
|
|
@ -27,3 +33,321 @@ func TestFindTaskNeeds(t *testing.T) {
|
|||
assert.Equal(t, "abc", ret["job1"].Outputs["output_a"])
|
||||
assert.Equal(t, "bbb", ret["job1"].Outputs["output_b"])
|
||||
}
|
||||
|
||||
func TestGenerateGiteaContext(t *testing.T) {
|
||||
testUser := &user.User{
|
||||
ID: 1,
|
||||
Name: "testuser",
|
||||
}
|
||||
|
||||
testRepo := &repo.Repository{
|
||||
ID: 1,
|
||||
OwnerName: "testowner",
|
||||
Name: "testrepo",
|
||||
}
|
||||
|
||||
emptyField := func(t *testing.T, context map[string]any, field string) {
|
||||
v, ok := context[field]
|
||||
assert.True(t, ok, "expected field %q to be present", field)
|
||||
assert.Empty(t, v)
|
||||
}
|
||||
|
||||
t.Run("Basic workflow run without job", func(t *testing.T) {
|
||||
run := &actions_model.ActionRun{
|
||||
ID: 1,
|
||||
Index: 42,
|
||||
TriggerUser: testUser,
|
||||
Repo: testRepo,
|
||||
TriggerEvent: "push",
|
||||
Ref: "refs/heads/main",
|
||||
CommitSHA: "abc123def456",
|
||||
WorkflowID: "test-workflow",
|
||||
EventPayload: `{"repository": {"name": "testrepo"}}`,
|
||||
}
|
||||
|
||||
context := GenerateGiteaContext(run, nil)
|
||||
|
||||
assert.Equal(t, "testuser", context["actor"])
|
||||
assert.Equal(t, setting.AppURL+"api/v1", context["api_url"])
|
||||
assert.Equal(t, "push", context["event_name"])
|
||||
assert.Equal(t, "refs/heads/main", context["ref"])
|
||||
assert.Equal(t, "main", context["ref_name"])
|
||||
assert.Equal(t, "branch", context["ref_type"])
|
||||
assert.Equal(t, "testowner/testrepo", context["repository"])
|
||||
assert.Equal(t, "testowner", context["repository_owner"])
|
||||
assert.Equal(t, "abc123def456", context["sha"])
|
||||
assert.Equal(t, "42", context["run_number"])
|
||||
assert.Equal(t, "test-workflow", context["workflow"])
|
||||
assert.Equal(t, false, context["ref_protected"])
|
||||
assert.Equal(t, "Actions", context["secret_source"])
|
||||
assert.Equal(t, setting.AppURL, context["server_url"])
|
||||
|
||||
event, ok := context["event"].(map[string]any)
|
||||
require.True(t, ok)
|
||||
assert.Equal(t, "testrepo", event["repository"].(map[string]any)["name"])
|
||||
|
||||
emptyField(t, context, "action_path")
|
||||
emptyField(t, context, "action_ref")
|
||||
emptyField(t, context, "action_repository")
|
||||
emptyField(t, context, "action_status")
|
||||
emptyField(t, context, "action")
|
||||
emptyField(t, context, "base_ref")
|
||||
emptyField(t, context, "env")
|
||||
emptyField(t, context, "event_path")
|
||||
emptyField(t, context, "graphql_url")
|
||||
emptyField(t, context, "head_ref")
|
||||
emptyField(t, context, "job")
|
||||
emptyField(t, context, "path")
|
||||
emptyField(t, context, "retention_days")
|
||||
emptyField(t, context, "run_attempt")
|
||||
emptyField(t, context, "run_id")
|
||||
emptyField(t, context, "triggering_actor")
|
||||
emptyField(t, context, "workspace")
|
||||
})
|
||||
|
||||
t.Run("Workflow run with job", func(t *testing.T) {
|
||||
run := &actions_model.ActionRun{
|
||||
ID: 1,
|
||||
Index: 42,
|
||||
TriggerUser: testUser,
|
||||
Repo: testRepo,
|
||||
TriggerEvent: "push",
|
||||
Ref: "refs/heads/main",
|
||||
CommitSHA: "abc123def456",
|
||||
WorkflowID: "test-workflow",
|
||||
EventPayload: `{}`,
|
||||
}
|
||||
|
||||
job := &actions_model.ActionRunJob{
|
||||
ID: 100,
|
||||
RunID: 1,
|
||||
JobID: "test-job",
|
||||
Attempt: 1,
|
||||
}
|
||||
|
||||
context := GenerateGiteaContext(run, job)
|
||||
|
||||
assert.Equal(t, "test-job", context["job"])
|
||||
assert.Equal(t, "1", context["run_id"])
|
||||
assert.Equal(t, "1", context["run_attempt"])
|
||||
})
|
||||
|
||||
t.Run("Pull request event", func(t *testing.T) {
|
||||
pullRequestPayload := map[string]any{
|
||||
"pull_request": map[string]any{
|
||||
"base": map[string]any{
|
||||
"ref": "main",
|
||||
"label": "main",
|
||||
"sha": "base123sha",
|
||||
},
|
||||
"head": map[string]any{
|
||||
"ref": "feature-branch",
|
||||
"label": "feature-branch",
|
||||
"sha": "head456sha",
|
||||
},
|
||||
},
|
||||
}
|
||||
|
||||
payloadBytes, _ := json.Marshal(pullRequestPayload)
|
||||
|
||||
run := &actions_model.ActionRun{
|
||||
ID: 1,
|
||||
Index: 42,
|
||||
TriggerUser: testUser,
|
||||
Repo: testRepo,
|
||||
TriggerEvent: "pull_request",
|
||||
Ref: "refs/pull/1/merge",
|
||||
CommitSHA: "merge789sha",
|
||||
WorkflowID: "test-workflow",
|
||||
Event: webhook_module.HookEventPullRequest,
|
||||
EventPayload: string(payloadBytes),
|
||||
}
|
||||
|
||||
context := GenerateGiteaContext(run, nil)
|
||||
|
||||
assert.Equal(t, "main", context["base_ref"])
|
||||
assert.Equal(t, "feature-branch", context["head_ref"])
|
||||
assert.Equal(t, "refs/pull/1/merge", context["ref"])
|
||||
assert.Equal(t, "merge789sha", context["sha"])
|
||||
})
|
||||
|
||||
t.Run("Pull request target event", func(t *testing.T) {
|
||||
pullRequestPayload := map[string]any{
|
||||
"pull_request": map[string]any{
|
||||
"base": map[string]any{
|
||||
"ref": "main",
|
||||
"label": "main",
|
||||
"sha": "base123sha",
|
||||
},
|
||||
"head": map[string]any{
|
||||
"ref": "feature-branch",
|
||||
"label": "feature-branch",
|
||||
"sha": "head456sha",
|
||||
},
|
||||
},
|
||||
}
|
||||
|
||||
payloadBytes, _ := json.Marshal(pullRequestPayload)
|
||||
|
||||
run := &actions_model.ActionRun{
|
||||
ID: 1,
|
||||
Index: 42,
|
||||
TriggerUser: testUser,
|
||||
Repo: testRepo,
|
||||
TriggerEvent: actions_module.GithubEventPullRequestTarget,
|
||||
Ref: "refs/pull/1/merge",
|
||||
CommitSHA: "merge789sha",
|
||||
WorkflowID: "test-workflow",
|
||||
Event: webhook_module.HookEventPullRequest,
|
||||
EventPayload: string(payloadBytes),
|
||||
}
|
||||
|
||||
context := GenerateGiteaContext(run, nil)
|
||||
|
||||
assert.Equal(t, "main", context["base_ref"])
|
||||
assert.Equal(t, "feature-branch", context["head_ref"])
|
||||
// For pull_request_target, ref and sha should be from base
|
||||
assert.Equal(t, "refs/heads/main", context["ref"])
|
||||
assert.Equal(t, "base123sha", context["sha"])
|
||||
assert.Equal(t, "main", context["ref_name"])
|
||||
assert.Equal(t, "branch", context["ref_type"])
|
||||
})
|
||||
}
|
||||
|
||||
func TestGenerateGiteaContextForRun(t *testing.T) {
|
||||
testUser := &user.User{
|
||||
ID: 1,
|
||||
Name: "testuser",
|
||||
}
|
||||
|
||||
testRepo := &repo.Repository{
|
||||
ID: 1,
|
||||
OwnerName: "testowner",
|
||||
Name: "testrepo",
|
||||
}
|
||||
|
||||
t.Run("Basic workflow run", func(t *testing.T) {
|
||||
run := &actions_model.ActionRun{
|
||||
ID: 1,
|
||||
Index: 42,
|
||||
TriggerUser: testUser,
|
||||
Repo: testRepo,
|
||||
TriggerEvent: "push",
|
||||
Ref: "refs/heads/main",
|
||||
CommitSHA: "abc123def456",
|
||||
WorkflowID: "test-workflow",
|
||||
EventPayload: `{"repository": {"name": "testrepo"}}`,
|
||||
}
|
||||
|
||||
gitContextObj := generateGiteaContextForRun(run)
|
||||
|
||||
assert.Equal(t, "testuser", gitContextObj.Actor)
|
||||
assert.Equal(t, setting.AppURL+"api/v1", gitContextObj.APIURL)
|
||||
assert.Equal(t, "push", gitContextObj.EventName)
|
||||
assert.Equal(t, "refs/heads/main", gitContextObj.Ref)
|
||||
assert.Equal(t, "main", gitContextObj.RefName)
|
||||
assert.Equal(t, "branch", gitContextObj.RefType)
|
||||
assert.Equal(t, "testowner/testrepo", gitContextObj.Repository)
|
||||
assert.Equal(t, "testowner", gitContextObj.RepositoryOwner)
|
||||
assert.Equal(t, "abc123def456", gitContextObj.Sha)
|
||||
assert.Equal(t, "42", gitContextObj.RunNumber)
|
||||
assert.Equal(t, "test-workflow", gitContextObj.Workflow)
|
||||
|
||||
assert.Equal(t, "testrepo", gitContextObj.Event["repository"].(map[string]any)["name"])
|
||||
|
||||
assert.Empty(t, gitContextObj.ActionPath)
|
||||
assert.Empty(t, gitContextObj.ActionRef)
|
||||
assert.Empty(t, gitContextObj.ActionRepository)
|
||||
assert.Empty(t, gitContextObj.Action)
|
||||
assert.Empty(t, gitContextObj.BaseRef)
|
||||
assert.Empty(t, gitContextObj.EventPath)
|
||||
assert.Empty(t, gitContextObj.GraphQLURL)
|
||||
assert.Empty(t, gitContextObj.HeadRef)
|
||||
assert.Empty(t, gitContextObj.Job)
|
||||
assert.Empty(t, gitContextObj.RetentionDays)
|
||||
assert.Empty(t, gitContextObj.RunAttempt)
|
||||
assert.Empty(t, gitContextObj.RunID)
|
||||
assert.Empty(t, gitContextObj.Workspace)
|
||||
})
|
||||
|
||||
t.Run("Pull request event", func(t *testing.T) {
|
||||
pullRequestPayload := map[string]any{
|
||||
"pull_request": map[string]any{
|
||||
"base": map[string]any{
|
||||
"ref": "main",
|
||||
"label": "main",
|
||||
"sha": "base123sha",
|
||||
},
|
||||
"head": map[string]any{
|
||||
"ref": "feature-branch",
|
||||
"label": "feature-branch",
|
||||
"sha": "head456sha",
|
||||
},
|
||||
},
|
||||
}
|
||||
|
||||
payloadBytes, _ := json.Marshal(pullRequestPayload)
|
||||
|
||||
run := &actions_model.ActionRun{
|
||||
ID: 1,
|
||||
Index: 42,
|
||||
TriggerUser: testUser,
|
||||
Repo: testRepo,
|
||||
TriggerEvent: "pull_request",
|
||||
Ref: "refs/pull/1/merge",
|
||||
CommitSHA: "merge789sha",
|
||||
WorkflowID: "test-workflow",
|
||||
Event: webhook_module.HookEventPullRequest,
|
||||
EventPayload: string(payloadBytes),
|
||||
}
|
||||
|
||||
gitContextObj := generateGiteaContextForRun(run)
|
||||
|
||||
assert.Equal(t, "main", gitContextObj.BaseRef)
|
||||
assert.Equal(t, "feature-branch", gitContextObj.HeadRef)
|
||||
assert.Equal(t, "refs/pull/1/merge", gitContextObj.Ref)
|
||||
assert.Equal(t, "merge789sha", gitContextObj.Sha)
|
||||
})
|
||||
|
||||
t.Run("Pull request target event", func(t *testing.T) {
|
||||
pullRequestPayload := map[string]any{
|
||||
"pull_request": map[string]any{
|
||||
"base": map[string]any{
|
||||
"ref": "main",
|
||||
"label": "main",
|
||||
"sha": "base123sha",
|
||||
},
|
||||
"head": map[string]any{
|
||||
"ref": "feature-branch",
|
||||
"label": "feature-branch",
|
||||
"sha": "head456sha",
|
||||
},
|
||||
},
|
||||
}
|
||||
|
||||
payloadBytes, _ := json.Marshal(pullRequestPayload)
|
||||
|
||||
run := &actions_model.ActionRun{
|
||||
ID: 1,
|
||||
Index: 42,
|
||||
TriggerUser: testUser,
|
||||
Repo: testRepo,
|
||||
TriggerEvent: actions_module.GithubEventPullRequestTarget,
|
||||
Ref: "refs/pull/1/merge",
|
||||
CommitSHA: "merge789sha",
|
||||
WorkflowID: "test-workflow",
|
||||
Event: webhook_module.HookEventPullRequest,
|
||||
EventPayload: string(payloadBytes),
|
||||
}
|
||||
|
||||
gitContextObj := generateGiteaContextForRun(run)
|
||||
|
||||
assert.Equal(t, "main", gitContextObj.BaseRef)
|
||||
assert.Equal(t, "feature-branch", gitContextObj.HeadRef)
|
||||
// For pull_request_target, ref and sha should be from base
|
||||
assert.Equal(t, "refs/heads/main", gitContextObj.Ref)
|
||||
assert.Equal(t, "base123sha", gitContextObj.Sha)
|
||||
assert.Equal(t, "main", gitContextObj.RefName)
|
||||
assert.Equal(t, "branch", gitContextObj.RefType)
|
||||
})
|
||||
}
|
||||
|
|
|
|||
|
|
@ -352,14 +352,17 @@ func handleWorkflows(
|
|||
Status: actions_model.StatusWaiting,
|
||||
}
|
||||
|
||||
if workflow, err := model.ReadWorkflow(bytes.NewReader(dwf.Content), false); err == nil {
|
||||
notifications, err := workflow.Notifications()
|
||||
if err != nil {
|
||||
log.Error("Notifications: %w", err)
|
||||
}
|
||||
run.NotifyEmail = notifications
|
||||
workflow, err := model.ReadWorkflow(bytes.NewReader(dwf.Content), false)
|
||||
if err != nil {
|
||||
log.Error("unable to read workflow: %v", err)
|
||||
}
|
||||
|
||||
notifications, err := workflow.Notifications()
|
||||
if err != nil {
|
||||
log.Error("Notifications: %w", err)
|
||||
}
|
||||
run.NotifyEmail = notifications
|
||||
|
||||
need, err := ifNeedApproval(ctx, run, input.Repo, input.Doer)
|
||||
if err != nil {
|
||||
log.Error("check if need approval for repo %d with user %d: %v", input.Repo.ID, input.Doer.ID, err)
|
||||
|
|
@ -379,6 +382,11 @@ func handleWorkflows(
|
|||
continue
|
||||
}
|
||||
|
||||
err = ConfigureActionRunConcurrency(workflow, run, vars, map[string]any{})
|
||||
if err != nil {
|
||||
log.Error("ConfigureActionRunConcurrency: %v", err)
|
||||
}
|
||||
|
||||
var jobs []*jobparser.SingleWorkflow
|
||||
if dwf.EventDetectionError != nil { // don't even bother trying to parse jobs due to event detection error
|
||||
tr := translation.NewLocale(input.Doer.Language)
|
||||
|
|
@ -400,15 +408,13 @@ func handleWorkflows(
|
|||
}
|
||||
}
|
||||
|
||||
// cancel running jobs if the event is push or pull_request_sync
|
||||
if run.Event == webhook_module.HookEventPush ||
|
||||
run.Event == webhook_module.HookEventPullRequestSync {
|
||||
if run.ConcurrencyType == actions_model.CancelInProgress {
|
||||
if err := CancelPreviousJobs(
|
||||
ctx,
|
||||
run.RepoID,
|
||||
run.Ref,
|
||||
run.WorkflowID,
|
||||
run.Event,
|
||||
webhook_module.HookEventType(run.TriggerEvent),
|
||||
); err != nil {
|
||||
log.Error("CancelPreviousJobs: %v", err)
|
||||
}
|
||||
|
|
|
|||
|
|
@ -5,6 +5,7 @@ package actions
|
|||
|
||||
import (
|
||||
"errors"
|
||||
"slices"
|
||||
"testing"
|
||||
|
||||
actions_model "forgejo.org/models/actions"
|
||||
|
|
@ -230,3 +231,62 @@ func TestActionsPreExecutionEventDetectionError(t *testing.T) {
|
|||
assert.Equal(t, actions_model.StatusFailure, createdRun.Status)
|
||||
assert.Equal(t, "actions.workflow.event_detection_error%!(EXTRA *errors.errorString=nothing is not a valid event)", createdRun.PreExecutionError)
|
||||
}
|
||||
|
||||
func TestActionsNotifierConcurrencyGroup(t *testing.T) {
|
||||
require.NoError(t, unittest.PrepareTestDatabase())
|
||||
|
||||
repo := unittest.AssertExistsAndLoadBean(t, &repo_model.Repository{ID: 10})
|
||||
doer := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: 1})
|
||||
pr := unittest.AssertExistsAndLoadBean(t, &issues_model.PullRequest{ID: 3})
|
||||
|
||||
commit := &git.Commit{
|
||||
ID: git.MustIDFromString("0000000000000000000000000000000000000000"),
|
||||
CommitMessage: "test",
|
||||
}
|
||||
detectedWorkflows := []*actions_module.DetectedWorkflow{
|
||||
{
|
||||
EntryName: "test.yml",
|
||||
TriggerEvent: &jobparser.Event{
|
||||
Name: "pull_request",
|
||||
},
|
||||
Content: []byte("{ on: pull_request, jobs: { j1: {} }}"),
|
||||
},
|
||||
}
|
||||
input := ¬ifyInput{
|
||||
Repo: repo,
|
||||
Doer: doer,
|
||||
Event: webhook_module.HookEventPullRequestSync,
|
||||
PullRequest: pr,
|
||||
Payload: &api.PullRequestPayload{},
|
||||
}
|
||||
|
||||
err := handleWorkflows(db.DefaultContext, detectedWorkflows, commit, input, "refs/head/main")
|
||||
require.NoError(t, err)
|
||||
|
||||
runs, err := db.Find[actions_model.ActionRun](db.DefaultContext, actions_model.FindRunOptions{
|
||||
RepoID: repo.ID,
|
||||
})
|
||||
require.NoError(t, err)
|
||||
require.Len(t, runs, 1)
|
||||
firstRun := runs[0]
|
||||
|
||||
assert.Equal(t, actions_model.StatusWaiting, firstRun.Status)
|
||||
|
||||
// Also... check if CancelPreviousWithConcurrencyGroup is invoked from handleWorkflows by firing off a second
|
||||
// workflow and checking that the first one gets cancelled:
|
||||
|
||||
err = handleWorkflows(db.DefaultContext, detectedWorkflows, commit, input, "refs/head/main")
|
||||
require.NoError(t, err)
|
||||
|
||||
runs, err = db.Find[actions_model.ActionRun](db.DefaultContext, actions_model.FindRunOptions{
|
||||
RepoID: repo.ID,
|
||||
})
|
||||
require.NoError(t, err)
|
||||
require.Len(t, runs, 2)
|
||||
|
||||
firstRunIndex := slices.IndexFunc(runs, func(run *actions_model.ActionRun) bool { return run.ID == firstRun.ID })
|
||||
require.NotEqual(t, -1, firstRunIndex)
|
||||
firstRun = runs[firstRunIndex]
|
||||
|
||||
assert.Equal(t, actions_model.StatusCancelled, firstRun.Status)
|
||||
}
|
||||
|
|
|
|||
|
|
@ -180,3 +180,29 @@ func GetWorkflowFromCommit(gitRepo *git.Repository, ref, workflowID string) (*Wo
|
|||
GitEntry: workflowEntry,
|
||||
}, nil
|
||||
}
|
||||
|
||||
// Sets the ConcurrencyGroup & ConcurrencyType on the provided ActionRun based upon the Workflow's `concurrency` data,
|
||||
// or appropriate defaults if not present.
|
||||
func ConfigureActionRunConcurrency(workflow *act_model.Workflow, run *actions_model.ActionRun, vars map[string]string, inputs map[string]any) error {
|
||||
_, cancelInProgress, err := jobparser.EvaluateWorkflowConcurrency(
|
||||
workflow.RawConcurrency, generateGiteaContextForRun(run), vars, inputs)
|
||||
if err != nil {
|
||||
return fmt.Errorf("unable to evaluate workflow `concurrency` block: %w", err)
|
||||
}
|
||||
if cancelInProgress == nil {
|
||||
// Maintain compatible behavior from before concurrency groups were implemented -- if `cancel-in-progress`
|
||||
// isn't defined in the workflow, cancel on push & PR sync events.
|
||||
if run.Event == webhook.HookEventPush || run.Event == webhook.HookEventPullRequestSync {
|
||||
run.ConcurrencyType = actions_model.CancelInProgress
|
||||
} else {
|
||||
run.ConcurrencyType = actions_model.UnlimitedConcurrency
|
||||
}
|
||||
} else if *cancelInProgress {
|
||||
run.ConcurrencyType = actions_model.CancelInProgress
|
||||
} else {
|
||||
// A workflow has explicitly listed `cancel-in-progress: false`, and we don't support concurrency groups
|
||||
// (queue-behind style behaviour, to be added in Forgejo v14).
|
||||
run.ConcurrencyType = actions_model.UnlimitedConcurrency
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
|
|
|||
100
services/actions/workflows_test.go
Normal file
100
services/actions/workflows_test.go
Normal file
|
|
@ -0,0 +1,100 @@
|
|||
// Copyright 2025 The Forgejo Authors. All rights reserved.
|
||||
// SPDX-License-Identifier: GPL-3.0-or-later
|
||||
|
||||
package actions
|
||||
|
||||
import (
|
||||
"testing"
|
||||
|
||||
actions_model "forgejo.org/models/actions"
|
||||
"forgejo.org/models/repo"
|
||||
"forgejo.org/modules/webhook"
|
||||
|
||||
act_model "code.forgejo.org/forgejo/runner/v11/act/model"
|
||||
"github.com/stretchr/testify/assert"
|
||||
"github.com/stretchr/testify/require"
|
||||
)
|
||||
|
||||
func TestConfigureActionRunConcurrency(t *testing.T) {
|
||||
for _, tc := range []struct {
|
||||
name string
|
||||
concurrency *act_model.RawConcurrency
|
||||
vars map[string]string
|
||||
inputs map[string]any
|
||||
runEvent webhook.HookEventType
|
||||
expectedConcurrencyType actions_model.ConcurrencyMode
|
||||
}{
|
||||
// Before the introduction of concurrency groups, push & pull_request_sync would cancel runs on the same repo,
|
||||
// reference, workflow, and event -- these cases cover undefined concurrency group and backwards compatibility
|
||||
// checks.
|
||||
{
|
||||
name: "backwards compatibility push",
|
||||
runEvent: webhook.HookEventPush,
|
||||
expectedConcurrencyType: actions_model.CancelInProgress,
|
||||
},
|
||||
{
|
||||
name: "backwards compatibility pull_request_sync",
|
||||
runEvent: webhook.HookEventPullRequestSync,
|
||||
expectedConcurrencyType: actions_model.CancelInProgress,
|
||||
},
|
||||
{
|
||||
name: "backwards compatibility other event",
|
||||
runEvent: webhook.HookEventWorkflowDispatch,
|
||||
expectedConcurrencyType: actions_model.UnlimitedConcurrency,
|
||||
},
|
||||
|
||||
{
|
||||
name: "fully-specified cancel-in-progress",
|
||||
concurrency: &act_model.RawConcurrency{
|
||||
Group: "abc",
|
||||
CancelInProgress: "true",
|
||||
},
|
||||
runEvent: webhook.HookEventPullRequestSync,
|
||||
expectedConcurrencyType: actions_model.CancelInProgress,
|
||||
},
|
||||
{
|
||||
name: "no concurrency group, cancel-in-progress: false",
|
||||
concurrency: &act_model.RawConcurrency{
|
||||
CancelInProgress: "false",
|
||||
},
|
||||
runEvent: webhook.HookEventPullRequestSync,
|
||||
expectedConcurrencyType: actions_model.UnlimitedConcurrency,
|
||||
},
|
||||
|
||||
{
|
||||
name: "interpreted values",
|
||||
concurrency: &act_model.RawConcurrency{
|
||||
Group: "${{ github.workflow }}-${{ github.ref }}",
|
||||
CancelInProgress: "${{ !contains(github.ref, 'release/')}}",
|
||||
},
|
||||
runEvent: webhook.HookEventPullRequestSync,
|
||||
expectedConcurrencyType: actions_model.CancelInProgress,
|
||||
},
|
||||
{
|
||||
name: "interpreted values with inputs and vars",
|
||||
concurrency: &act_model.RawConcurrency{
|
||||
Group: "${{ inputs.abc }}-${{ vars.def }}",
|
||||
},
|
||||
inputs: map[string]any{"abc": "123"},
|
||||
vars: map[string]string{"def": "456"},
|
||||
runEvent: webhook.HookEventPullRequestSync,
|
||||
expectedConcurrencyType: actions_model.CancelInProgress,
|
||||
},
|
||||
} {
|
||||
t.Run(tc.name, func(t *testing.T) {
|
||||
workflow := &act_model.Workflow{RawConcurrency: tc.concurrency}
|
||||
run := &actions_model.ActionRun{
|
||||
Ref: "refs/head/main",
|
||||
WorkflowID: "testing.yml",
|
||||
Event: tc.runEvent,
|
||||
TriggerEvent: string(tc.runEvent),
|
||||
Repo: &repo.Repository{},
|
||||
}
|
||||
|
||||
err := ConfigureActionRunConcurrency(workflow, run, tc.vars, tc.inputs)
|
||||
require.NoError(t, err)
|
||||
|
||||
assert.Equal(t, tc.expectedConcurrencyType, run.ConcurrencyType)
|
||||
})
|
||||
}
|
||||
}
|
||||
Loading…
Add table
Add a link
Reference in a new issue