···20202121 // Test pull names
2222 assert.Equal(t, "1", RefName("refs/pull/1/head").PullName())
2323+ assert.True(t, RefName("refs/pull/1/head").IsPull())
2424+ assert.True(t, RefName("refs/pull/1/merge").IsPull())
2325 assert.Equal(t, "my/pull", RefName("refs/pull/my/pull/head").PullName())
24262527 // Test for branch names
+11-133
routers/api/actions/runner/utils.go
···88 "fmt"
991010 actions_model "code.gitea.io/gitea/models/actions"
1111- "code.gitea.io/gitea/models/db"
1211 secret_model "code.gitea.io/gitea/models/secret"
1313- actions_module "code.gitea.io/gitea/modules/actions"
1414- "code.gitea.io/gitea/modules/container"
1515- "code.gitea.io/gitea/modules/git"
1616- "code.gitea.io/gitea/modules/json"
1712 "code.gitea.io/gitea/modules/log"
1818- "code.gitea.io/gitea/modules/setting"
1913 "code.gitea.io/gitea/services/actions"
20142115 runnerv1 "code.gitea.io/actions-proto-go/runner/v1"
···6559}
66606761func generateTaskContext(t *actions_model.ActionTask) *structpb.Struct {
6868- event := map[string]any{}
6969- _ = json.Unmarshal([]byte(t.Job.Run.EventPayload), &event)
7070-7171- // TriggerEvent is added in https://github.com/go-gitea/gitea/pull/25229
7272- // This fallback is for the old ActionRun that doesn't have the TriggerEvent field
7373- // and should be removed in 1.22
7474- eventName := t.Job.Run.TriggerEvent
7575- if eventName == "" {
7676- eventName = t.Job.Run.Event.Event()
7777- }
7878-7979- baseRef := ""
8080- headRef := ""
8181- ref := t.Job.Run.Ref
8282- sha := t.Job.Run.CommitSHA
8383- if pullPayload, err := t.Job.Run.GetPullRequestEventPayload(); err == nil && pullPayload.PullRequest != nil && pullPayload.PullRequest.Base != nil && pullPayload.PullRequest.Head != nil {
8484- baseRef = pullPayload.PullRequest.Base.Ref
8585- headRef = pullPayload.PullRequest.Head.Ref
8686-8787- // if the TriggerEvent is pull_request_target, ref and sha need to be set according to the base of pull request
8888- // In GitHub's documentation, ref should be the branch or tag that triggered workflow. But when the TriggerEvent is pull_request_target,
8989- // the ref will be the base branch.
9090- if t.Job.Run.TriggerEvent == actions_module.GithubEventPullRequestTarget {
9191- ref = git.BranchPrefix + pullPayload.PullRequest.Base.Name
9292- sha = pullPayload.PullRequest.Base.Sha
9393- }
9494- }
9595-9696- refName := git.RefName(ref)
9797-9862 giteaRuntimeToken, err := actions.CreateAuthorizationToken(t.ID, t.Job.RunID, t.JobID)
9963 if err != nil {
10064 log.Error("actions.CreateAuthorizationToken failed: %v", err)
10165 }
10266103103- taskContext, err := structpb.NewStruct(map[string]any{
104104- // standard contexts, see https://docs.github.com/en/actions/learn-github-actions/contexts#github-context
105105- "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.
106106- "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.
107107- "action_ref": "", // string, For a step executing an action, this is the ref of the action being executed. For example, v2.
108108- "action_repository": "", // string, For a step executing an action, this is the owner and repository name of the action. For example, actions/checkout.
109109- "action_status": "", // string, For a composite action, the current result of the composite action.
110110- "actor": t.Job.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.
111111- "api_url": setting.AppURL + "api/v1", // string, The URL of the GitHub REST API.
112112- "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.
113113- "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."
114114- "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.
115115- "event_name": eventName, // string, The name of the event that triggered the workflow run.
116116- "event_path": "", // string, The path to the file on the runner that contains the full event webhook payload.
117117- "graphql_url": "", // string, The URL of the GitHub GraphQL API.
118118- "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.
119119- "job": fmt.Sprint(t.JobID), // string, The job_id of the current job.
120120- "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.
121121- "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.
122122- "ref_protected": false, // boolean, true if branch protections are configured for the ref that triggered the workflow run.
123123- "ref_type": refName.RefType(), // string, The type of ref that triggered the workflow run. Valid values are branch or tag.
124124- "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."
125125- "repository": t.Job.Run.Repo.OwnerName + "/" + t.Job.Run.Repo.Name, // string, The owner and repository name. For example, Codertocat/Hello-World.
126126- "repository_owner": t.Job.Run.Repo.OwnerName, // string, The repository owner's name. For example, Codertocat.
127127- "repositoryUrl": t.Job.Run.Repo.HTMLURL(), // string, The Git URL to the repository. For example, git://github.com/codertocat/hello-world.git.
128128- "retention_days": "", // string, The number of days that workflow run logs and artifacts are kept.
129129- "run_id": fmt.Sprint(t.Job.RunID), // string, A unique number for each workflow run within a repository. This number does not change if you re-run the workflow run.
130130- "run_number": fmt.Sprint(t.Job.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.
131131- "run_attempt": fmt.Sprint(t.Job.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.
132132- "secret_source": "Actions", // string, The source of a secret used in a workflow. Possible values are None, Actions, Dependabot, or Codespaces.
133133- "server_url": setting.AppURL, // string, The URL of the GitHub server. For example: https://github.com.
134134- "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.
135135- "token": t.Token, // string, A token to authenticate on behalf of the GitHub App installed on your repository. This is functionally equivalent to the GITHUB_TOKEN secret. For more information, see "Automatic token authentication."
136136- "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.
137137- "workflow": t.Job.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.
138138- "workspace": "", // string, The default working directory on the runner for steps, and the default location of your repository when using the checkout action.
6767+ gitCtx := actions.GenerateGiteaContext(t.Job.Run, t.Job)
6868+ gitCtx["token"] = t.Token
6969+ gitCtx["gitea_runtime_token"] = giteaRuntimeToken
13970140140- // additional contexts
141141- "gitea_default_actions_url": setting.Actions.DefaultActionsURL.URL(),
142142- "gitea_runtime_token": giteaRuntimeToken,
143143- })
7171+ taskContext, err := structpb.NewStruct(gitCtx)
14472 if err != nil {
14573 log.Error("structpb.NewStruct failed: %v", err)
14674 }
···1507815179func findTaskNeeds(ctx context.Context, task *actions_model.ActionTask) (map[string]*runnerv1.TaskNeed, error) {
15280 if err := task.LoadAttributes(ctx); err != nil {
153153- return nil, fmt.Errorf("LoadAttributes: %w", err)
8181+ return nil, fmt.Errorf("task LoadAttributes: %w", err)
15482 }
155155- if len(task.Job.Needs) == 0 {
156156- return nil, nil
157157- }
158158- needs := container.SetOf(task.Job.Needs...)
159159-160160- jobs, err := db.Find[actions_model.ActionRunJob](ctx, actions_model.FindRunJobOptions{RunID: task.Job.RunID})
8383+ taskNeeds, err := actions.FindTaskNeeds(ctx, task.Job)
16184 if err != nil {
162162- return nil, fmt.Errorf("FindRunJobs: %w", err)
8585+ return nil, err
16386 }
164164-165165- jobIDJobs := make(map[string][]*actions_model.ActionRunJob)
166166- for _, job := range jobs {
167167- jobIDJobs[job.JobID] = append(jobIDJobs[job.JobID], job)
168168- }
169169-170170- ret := make(map[string]*runnerv1.TaskNeed, len(needs))
171171- for jobID, jobsWithSameID := range jobIDJobs {
172172- if !needs.Contains(jobID) {
173173- continue
174174- }
175175- var jobOutputs map[string]string
176176- for _, job := range jobsWithSameID {
177177- if job.TaskID == 0 || !job.Status.IsDone() {
178178- // it shouldn't happen, or the job has been rerun
179179- continue
180180- }
181181- got, err := actions_model.FindTaskOutputByTaskID(ctx, job.TaskID)
182182- if err != nil {
183183- return nil, fmt.Errorf("FindTaskOutputByTaskID: %w", err)
184184- }
185185- outputs := make(map[string]string, len(got))
186186- for _, v := range got {
187187- outputs[v.OutputKey] = v.OutputValue
188188- }
189189- if len(jobOutputs) == 0 {
190190- jobOutputs = outputs
191191- } else {
192192- jobOutputs = mergeTwoOutputs(outputs, jobOutputs)
193193- }
194194- }
8787+ ret := make(map[string]*runnerv1.TaskNeed, len(taskNeeds))
8888+ for jobID, taskNeed := range taskNeeds {
19589 ret[jobID] = &runnerv1.TaskNeed{
196196- Outputs: jobOutputs,
197197- Result: runnerv1.Result(actions_model.AggregateJobStatus(jobsWithSameID)),
9090+ Outputs: taskNeed.Outputs,
9191+ Result: runnerv1.Result(taskNeed.Result),
19892 }
19993 }
200200-20194 return ret, nil
20295}
203203-204204-// mergeTwoOutputs merges two outputs from two different ActionRunJobs
205205-// Values with the same output name may be overridden. The user should ensure the output names are unique.
206206-// See https://docs.github.com/en/actions/writing-workflows/workflow-syntax-for-github-actions#using-job-outputs-in-a-matrix-job
207207-func mergeTwoOutputs(o1, o2 map[string]string) map[string]string {
208208- ret := make(map[string]string, len(o1))
209209- for k1, v1 := range o1 {
210210- if len(v1) > 0 {
211211- ret[k1] = v1
212212- } else {
213213- ret[k1] = o2[k1]
214214- }
215215- }
216216- return ret
217217-}
···11+// Copyright 2025 The Gitea Authors. All rights reserved.
22+// SPDX-License-Identifier: MIT
33+44+package actions
55+66+import (
77+ "context"
88+ "fmt"
99+1010+ actions_model "code.gitea.io/gitea/models/actions"
1111+ "code.gitea.io/gitea/models/db"
1212+ actions_module "code.gitea.io/gitea/modules/actions"
1313+ "code.gitea.io/gitea/modules/container"
1414+ "code.gitea.io/gitea/modules/git"
1515+ "code.gitea.io/gitea/modules/json"
1616+ "code.gitea.io/gitea/modules/setting"
1717+)
1818+1919+// GenerateGiteaContext generate the gitea context without token and gitea_runtime_token
2020+// job can be nil when generating a context for parsing workflow-level expressions
2121+func GenerateGiteaContext(run *actions_model.ActionRun, job *actions_model.ActionRunJob) map[string]any {
2222+ event := map[string]any{}
2323+ _ = json.Unmarshal([]byte(run.EventPayload), &event)
2424+2525+ baseRef := ""
2626+ headRef := ""
2727+ ref := run.Ref
2828+ sha := run.CommitSHA
2929+ if pullPayload, err := run.GetPullRequestEventPayload(); err == nil && pullPayload.PullRequest != nil && pullPayload.PullRequest.Base != nil && pullPayload.PullRequest.Head != nil {
3030+ baseRef = pullPayload.PullRequest.Base.Ref
3131+ headRef = pullPayload.PullRequest.Head.Ref
3232+3333+ // if the TriggerEvent is pull_request_target, ref and sha need to be set according to the base of pull request
3434+ // In GitHub's documentation, ref should be the branch or tag that triggered workflow. But when the TriggerEvent is pull_request_target,
3535+ // the ref will be the base branch.
3636+ if run.TriggerEvent == actions_module.GithubEventPullRequestTarget {
3737+ ref = git.BranchPrefix + pullPayload.PullRequest.Base.Name
3838+ sha = pullPayload.PullRequest.Base.Sha
3939+ }
4040+ }
4141+4242+ refName := git.RefName(ref)
4343+4444+ gitContext := map[string]any{
4545+ // standard contexts, see https://docs.github.com/en/actions/learn-github-actions/contexts#github-context
4646+ "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.
4747+ "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.
4848+ "action_ref": "", // string, For a step executing an action, this is the ref of the action being executed. For example, v2.
4949+ "action_repository": "", // string, For a step executing an action, this is the owner and repository name of the action. For example, actions/checkout.
5050+ "action_status": "", // string, For a composite action, the current result of the composite action.
5151+ "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.
5252+ "api_url": setting.AppURL + "api/v1", // string, The URL of the GitHub REST API.
5353+ "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.
5454+ "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."
5555+ "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.
5656+ "event_name": run.TriggerEvent, // string, The name of the event that triggered the workflow run.
5757+ "event_path": "", // string, The path to the file on the runner that contains the full event webhook payload.
5858+ "graphql_url": "", // string, The URL of the GitHub GraphQL API.
5959+ "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.
6060+ "job": "", // string, The job_id of the current job.
6161+ "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.
6262+ "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.
6363+ "ref_protected": false, // boolean, true if branch protections are configured for the ref that triggered the workflow run.
6464+ "ref_type": refName.RefType(), // string, The type of ref that triggered the workflow run. Valid values are branch or tag.
6565+ "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."
6666+ "repository": run.Repo.OwnerName + "/" + run.Repo.Name, // string, The owner and repository name. For example, Codertocat/Hello-World.
6767+ "repository_owner": run.Repo.OwnerName, // string, The repository owner's name. For example, Codertocat.
6868+ "repositoryUrl": run.Repo.HTMLURL(), // string, The Git URL to the repository. For example, git://github.com/codertocat/hello-world.git.
6969+ "retention_days": "", // string, The number of days that workflow run logs and artifacts are kept.
7070+ "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.
7171+ "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.
7272+ "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.
7373+ "secret_source": "Actions", // string, The source of a secret used in a workflow. Possible values are None, Actions, Dependabot, or Codespaces.
7474+ "server_url": setting.AppURL, // string, The URL of the GitHub server. For example: https://github.com.
7575+ "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.
7676+ "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.
7777+ "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.
7878+ "workspace": "", // string, The default working directory on the runner for steps, and the default location of your repository when using the checkout action.
7979+8080+ // additional contexts
8181+ "gitea_default_actions_url": setting.Actions.DefaultActionsURL.URL(),
8282+ }
8383+8484+ if job != nil {
8585+ gitContext["job"] = job.JobID
8686+ gitContext["run_id"] = fmt.Sprint(job.RunID)
8787+ gitContext["run_attempt"] = fmt.Sprint(job.Attempt)
8888+ }
8989+9090+ return gitContext
9191+}
9292+9393+type TaskNeed struct {
9494+ Result actions_model.Status
9595+ Outputs map[string]string
9696+}
9797+9898+// FindTaskNeeds finds the `needs` for the task by the task's job
9999+func FindTaskNeeds(ctx context.Context, job *actions_model.ActionRunJob) (map[string]*TaskNeed, error) {
100100+ if len(job.Needs) == 0 {
101101+ return nil, nil
102102+ }
103103+ needs := container.SetOf(job.Needs...)
104104+105105+ jobs, err := db.Find[actions_model.ActionRunJob](ctx, actions_model.FindRunJobOptions{RunID: job.RunID})
106106+ if err != nil {
107107+ return nil, fmt.Errorf("FindRunJobs: %w", err)
108108+ }
109109+110110+ jobIDJobs := make(map[string][]*actions_model.ActionRunJob)
111111+ for _, job := range jobs {
112112+ jobIDJobs[job.JobID] = append(jobIDJobs[job.JobID], job)
113113+ }
114114+115115+ ret := make(map[string]*TaskNeed, len(needs))
116116+ for jobID, jobsWithSameID := range jobIDJobs {
117117+ if !needs.Contains(jobID) {
118118+ continue
119119+ }
120120+ var jobOutputs map[string]string
121121+ for _, job := range jobsWithSameID {
122122+ if job.TaskID == 0 || !job.Status.IsDone() {
123123+ // it shouldn't happen, or the job has been rerun
124124+ continue
125125+ }
126126+ got, err := actions_model.FindTaskOutputByTaskID(ctx, job.TaskID)
127127+ if err != nil {
128128+ return nil, fmt.Errorf("FindTaskOutputByTaskID: %w", err)
129129+ }
130130+ outputs := make(map[string]string, len(got))
131131+ for _, v := range got {
132132+ outputs[v.OutputKey] = v.OutputValue
133133+ }
134134+ if len(jobOutputs) == 0 {
135135+ jobOutputs = outputs
136136+ } else {
137137+ jobOutputs = mergeTwoOutputs(outputs, jobOutputs)
138138+ }
139139+ }
140140+ ret[jobID] = &TaskNeed{
141141+ Outputs: jobOutputs,
142142+ Result: actions_model.AggregateJobStatus(jobsWithSameID),
143143+ }
144144+ }
145145+ return ret, nil
146146+}
147147+148148+// mergeTwoOutputs merges two outputs from two different ActionRunJobs
149149+// Values with the same output name may be overridden. The user should ensure the output names are unique.
150150+// See https://docs.github.com/en/actions/writing-workflows/workflow-syntax-for-github-actions#using-job-outputs-in-a-matrix-job
151151+func mergeTwoOutputs(o1, o2 map[string]string) map[string]string {
152152+ ret := make(map[string]string, len(o1))
153153+ for k1, v1 := range o1 {
154154+ if len(v1) > 0 {
155155+ ret[k1] = v1
156156+ } else {
157157+ ret[k1] = o2[k1]
158158+ }
159159+ }
160160+ return ret
161161+}