mirror of
https://github.com/go-gitea/gitea.git
synced 2026-12-04 15:54:57 +00:00
refactor(actions): restructure run admission, settings scopes and oversized files (#39724)
Structural cleanups in the Actions code, plus fixes that align run behaviour with GitHub Actions. - Load a reusable caller's ancestor chain once for both expansion checks and its dispatch inputs. - Extract the rerun job reset and pass-through rules so they can be unit tested. - Share the gate a job passes once its `if:` holds (max-parallel slot, invalid `runs-on`, concurrency group) between run insertion, rerun and approval. The job emitter keeps its own, which also defers to groups admitted in the same pass. - Resolve the scope of every actions settings page, secrets included, in one place. The variables and secrets pages dereferenced a nil context when the org header failed to render. - Move the API handler interface to the API router, and record runner bulk-action audit events after the commit. - Split the 1500 and 2200 line handler files and move the actions converters into their own file, without code changes. - Partial reruns load a reusable workflow at the previous attempt's commit, full reruns resolve its ref again. - Reject loops through the root workflow at validation. - Compare concurrency groups case-insensitively and keep runs awaiting approval out of them until approved. - Fail-fast ignores failures carried over from an earlier attempt, and reruns fail a job with an invalid `runs-on`. Assisted-by: Claude Code:claude-opus-5-5 --------- Co-authored-by: Zettat123 <zettat123@gmail.com> Co-authored-by: silverwind <me@silverwind.io>
This commit is contained in:
42 files changed
+3326
-3245
No files matched your search
@@ -386,12 +386,16 @@ func GetConcurrencyWaiters(ctx context.Context, repoID int64, concurrencyGroup s
|
||||
|
||||
func findConcurrencyGroupEntries(ctx context.Context, repoID int64, concurrencyGroup string, attemptCond, jobCond builder.Cond) ([]*ActionRunAttempt, []*ActionRunJob, error) {
|
||||
groupCond := builder.Eq{"repo_id": repoID, "concurrency_group": concurrencyGroup}
|
||||
notAwaitingApproval := func(table string) builder.Cond {
|
||||
return builder.NotExists(builder.Select("1").From("action_run").
|
||||
Where(builder.Expr("action_run.id = " + table + ".run_id").And(builder.Eq{"action_run.need_approval": true})))
|
||||
}
|
||||
attempts := make([]*ActionRunAttempt, 0)
|
||||
if err := db.GetEngine(ctx).Where(groupCond.And(attemptCond)).Find(&attempts); err != nil {
|
||||
if err := db.GetEngine(ctx).Where(groupCond.And(attemptCond, notAwaitingApproval("action_run_attempt"))).Find(&attempts); err != nil {
|
||||
return nil, nil, fmt.Errorf("find run attempts: %w", err)
|
||||
}
|
||||
jobs := make([]*ActionRunJob, 0)
|
||||
if err := db.GetEngine(ctx).Where(groupCond.And(jobCond)).Find(&jobs); err != nil {
|
||||
if err := db.GetEngine(ctx).Where(groupCond.And(jobCond, notAwaitingApproval("action_run_job"))).Find(&jobs); err != nil {
|
||||
return nil, nil, fmt.Errorf("find jobs: %w", err)
|
||||
}
|
||||
return attempts, jobs, nil
|
||||
|
||||
@@ -710,17 +710,30 @@ func CancelPreviousJobs(ctx context.Context, repoID int64, ref, workflowID strin
|
||||
return CancelJobs(ctx, jobs, false)
|
||||
}
|
||||
|
||||
// GetAncestorCallerIDs returns the IDs of the reusable workflow callers the job is nested in.
|
||||
func GetAncestorCallerIDs(ctx context.Context, job *ActionRunJob) (container.Set[int64], error) {
|
||||
ids := make(container.Set[int64])
|
||||
// GetAncestorCallers returns the reusable workflow callers the job is nested in, nearest first.
|
||||
func GetAncestorCallers(ctx context.Context, job *ActionRunJob) ([]*ActionRunJob, error) {
|
||||
var callers []*ActionRunJob
|
||||
for parentID := job.ParentJobID; parentID != 0; {
|
||||
parent, err := GetRunJobByRunAndID(ctx, job.RunID, parentID)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("load caller %d: %w", parentID, err)
|
||||
return nil, fmt.Errorf("GetAncestorCallers: load caller %d: %w", parentID, err)
|
||||
}
|
||||
ids.Add(parent.ID)
|
||||
callers = append(callers, parent)
|
||||
parentID = parent.ParentJobID
|
||||
}
|
||||
return callers, nil
|
||||
}
|
||||
|
||||
// GetAncestorCallerIDs returns the IDs of the reusable workflow callers the job is nested in.
|
||||
func GetAncestorCallerIDs(ctx context.Context, job *ActionRunJob) (container.Set[int64], error) {
|
||||
callers, err := GetAncestorCallers(ctx, job)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
ids := make(container.Set[int64], len(callers))
|
||||
for _, caller := range callers {
|
||||
ids.Add(caller.ID)
|
||||
}
|
||||
return ids, nil
|
||||
}
|
||||
|
||||
|
||||
@@ -96,7 +96,6 @@ import (
|
||||
"gitea.dev/routers/api/v1/token"
|
||||
"gitea.dev/routers/api/v1/user"
|
||||
"gitea.dev/routers/common"
|
||||
"gitea.dev/services/actions"
|
||||
"gitea.dev/services/audit"
|
||||
"gitea.dev/services/auth"
|
||||
"gitea.dev/services/context"
|
||||
@@ -982,7 +981,7 @@ func Routes() *web.Router {
|
||||
m *web.Router,
|
||||
reqReaderCheck func(ctx *context.APIContext),
|
||||
reqManagerCheck func(ctx *context.APIContext),
|
||||
act actions.API,
|
||||
act shared.ActionsAPI,
|
||||
) {
|
||||
m.Group("/actions", func() {
|
||||
m.Group("/secrets", func() {
|
||||
|
||||
@@ -13,7 +13,6 @@ import (
|
||||
"gitea.dev/modules/web"
|
||||
"gitea.dev/routers/api/v1/shared"
|
||||
"gitea.dev/routers/api/v1/utils"
|
||||
actions_service "gitea.dev/services/actions"
|
||||
"gitea.dev/services/audit"
|
||||
"gitea.dev/services/context"
|
||||
secret_service "gitea.dev/services/secrets"
|
||||
@@ -529,12 +528,12 @@ func (Action) ListWorkflowRuns(ctx *context.APIContext) {
|
||||
shared.ListRuns(ctx, ctx.Org.Organization.ID, 0, "")
|
||||
}
|
||||
|
||||
var _ actions_service.API = new(Action)
|
||||
var _ shared.ActionsAPI = new(Action)
|
||||
|
||||
// Action implements actions_service.API
|
||||
// Action implements shared.ActionsAPI
|
||||
type Action struct{}
|
||||
|
||||
// NewAction creates a new Action service
|
||||
func NewAction() actions_service.API {
|
||||
func NewAction() shared.ActionsAPI {
|
||||
return Action{}
|
||||
}
|
||||
+3
-1226
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,371 @@
|
||||
// Copyright 2026 The Gitea Authors. All rights reserved.
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
package repo
|
||||
|
||||
import (
|
||||
go_context "context"
|
||||
"crypto/hmac"
|
||||
"encoding/base64"
|
||||
"errors"
|
||||
"fmt"
|
||||
"net/http"
|
||||
"net/url"
|
||||
"strconv"
|
||||
"time"
|
||||
|
||||
actions_model "gitea.dev/models/actions"
|
||||
"gitea.dev/models/db"
|
||||
repo_model "gitea.dev/models/repo"
|
||||
"gitea.dev/modules/actions"
|
||||
"gitea.dev/modules/httplib"
|
||||
api "gitea.dev/modules/structs"
|
||||
"gitea.dev/modules/util"
|
||||
"gitea.dev/routers/api/v1/utils"
|
||||
actions_service "gitea.dev/services/actions"
|
||||
"gitea.dev/services/context"
|
||||
"gitea.dev/services/convert"
|
||||
)
|
||||
|
||||
// GetArtifactsOfRun Lists all artifacts for a repository.
|
||||
func GetArtifactsOfRun(ctx *context.APIContext) {
|
||||
// swagger:operation GET /repos/{owner}/{repo}/actions/runs/{run}/artifacts repository getArtifactsOfRun
|
||||
// ---
|
||||
// summary: Lists all artifacts for a repository run
|
||||
// produces:
|
||||
// - application/json
|
||||
// parameters:
|
||||
// - name: owner
|
||||
// in: path
|
||||
// description: owner of the repo
|
||||
// type: string
|
||||
// required: true
|
||||
// - name: repo
|
||||
// in: path
|
||||
// description: name of the repository
|
||||
// type: string
|
||||
// required: true
|
||||
// - name: run
|
||||
// in: path
|
||||
// description: runid of the workflow run
|
||||
// type: integer
|
||||
// required: true
|
||||
// - name: name
|
||||
// in: query
|
||||
// description: name of the artifact
|
||||
// type: string
|
||||
// required: false
|
||||
// responses:
|
||||
// "200":
|
||||
// "$ref": "#/responses/ArtifactsList"
|
||||
// default:
|
||||
// "$ref": "#/responses/error"
|
||||
|
||||
artifactName := ctx.Req.URL.Query().Get("name")
|
||||
repoID, runID := ctx.Repo.Repository.ID, ctx.PathParamInt64("run")
|
||||
|
||||
artifacts, total, err := db.FindAndCount[actions_model.ActionArtifact](ctx, actions_model.FindArtifactsOptions{
|
||||
RepoID: repoID,
|
||||
RunID: runID,
|
||||
ArtifactName: artifactName,
|
||||
FinalizedArtifactsV4: true,
|
||||
ListOptions: utils.GetListOptions(ctx),
|
||||
})
|
||||
if err != nil {
|
||||
ctx.APIErrorInternal(err)
|
||||
return
|
||||
}
|
||||
|
||||
res := new(api.ActionArtifactsResponse)
|
||||
res.TotalCount = total
|
||||
|
||||
res.Entries = make([]*api.ActionArtifact, len(artifacts))
|
||||
for i := range artifacts {
|
||||
res.Entries[i] = convert.ToActionArtifact(ctx.Repo.Repository, artifacts[i])
|
||||
}
|
||||
|
||||
ctx.JSON(http.StatusOK, &res)
|
||||
}
|
||||
|
||||
// GetArtifacts Lists all artifacts for a repository.
|
||||
func GetArtifacts(ctx *context.APIContext) {
|
||||
// swagger:operation GET /repos/{owner}/{repo}/actions/artifacts repository getArtifacts
|
||||
// ---
|
||||
// summary: Lists all artifacts for a repository
|
||||
// produces:
|
||||
// - application/json
|
||||
// parameters:
|
||||
// - name: owner
|
||||
// in: path
|
||||
// description: owner of the repo
|
||||
// type: string
|
||||
// required: true
|
||||
// - name: repo
|
||||
// in: path
|
||||
// description: name of the repository
|
||||
// type: string
|
||||
// required: true
|
||||
// - name: name
|
||||
// in: query
|
||||
// description: name of the artifact
|
||||
// type: string
|
||||
// required: false
|
||||
// responses:
|
||||
// "200":
|
||||
// "$ref": "#/responses/ArtifactsList"
|
||||
// default:
|
||||
// "$ref": "#/responses/error"
|
||||
|
||||
repoID := ctx.Repo.Repository.ID
|
||||
artifactName := ctx.Req.URL.Query().Get("name")
|
||||
|
||||
artifacts, total, err := db.FindAndCount[actions_model.ActionArtifact](ctx, actions_model.FindArtifactsOptions{
|
||||
RepoID: repoID,
|
||||
ArtifactName: artifactName,
|
||||
FinalizedArtifactsV4: true,
|
||||
ListOptions: utils.GetListOptions(ctx),
|
||||
})
|
||||
if err != nil {
|
||||
ctx.APIErrorInternal(err)
|
||||
return
|
||||
}
|
||||
|
||||
res := new(api.ActionArtifactsResponse)
|
||||
res.TotalCount = total
|
||||
|
||||
res.Entries = make([]*api.ActionArtifact, len(artifacts))
|
||||
for i := range artifacts {
|
||||
res.Entries[i] = convert.ToActionArtifact(ctx.Repo.Repository, artifacts[i])
|
||||
}
|
||||
|
||||
ctx.JSON(http.StatusOK, &res)
|
||||
}
|
||||
|
||||
// GetArtifact Gets a specific artifact for a workflow run.
|
||||
func GetArtifact(ctx *context.APIContext) {
|
||||
// swagger:operation GET /repos/{owner}/{repo}/actions/artifacts/{artifact_id} repository getArtifact
|
||||
// ---
|
||||
// summary: Gets a specific artifact for a workflow run
|
||||
// produces:
|
||||
// - application/json
|
||||
// parameters:
|
||||
// - name: owner
|
||||
// in: path
|
||||
// description: owner of the repo
|
||||
// type: string
|
||||
// required: true
|
||||
// - name: repo
|
||||
// in: path
|
||||
// description: name of the repository
|
||||
// type: string
|
||||
// required: true
|
||||
// - name: artifact_id
|
||||
// in: path
|
||||
// description: id of the artifact
|
||||
// type: string
|
||||
// required: true
|
||||
// responses:
|
||||
// "200":
|
||||
// "$ref": "#/responses/Artifact"
|
||||
// default:
|
||||
// "$ref": "#/responses/error"
|
||||
|
||||
art := getArtifactByPathParam(ctx, ctx.Repo.Repository)
|
||||
if ctx.Written() {
|
||||
return
|
||||
}
|
||||
|
||||
if actions_service.IsArtifactV4(art) {
|
||||
ctx.JSON(http.StatusOK, convert.ToActionArtifact(ctx.Repo.Repository, art))
|
||||
return
|
||||
}
|
||||
// v3 not supported due to not having one unique id
|
||||
ctx.APIError(http.StatusNotFound, "Artifact not found")
|
||||
}
|
||||
|
||||
// DeleteArtifact Deletes a specific artifact for a workflow run.
|
||||
func DeleteArtifact(ctx *context.APIContext) {
|
||||
// swagger:operation DELETE /repos/{owner}/{repo}/actions/artifacts/{artifact_id} repository deleteArtifact
|
||||
// ---
|
||||
// summary: Deletes a specific artifact for a workflow run
|
||||
// produces:
|
||||
// - application/json
|
||||
// parameters:
|
||||
// - name: owner
|
||||
// in: path
|
||||
// description: owner of the repo
|
||||
// type: string
|
||||
// required: true
|
||||
// - name: repo
|
||||
// in: path
|
||||
// description: name of the repository
|
||||
// type: string
|
||||
// required: true
|
||||
// - name: artifact_id
|
||||
// in: path
|
||||
// description: id of the artifact
|
||||
// type: string
|
||||
// required: true
|
||||
// responses:
|
||||
// "204":
|
||||
// description: "No Content"
|
||||
// default:
|
||||
// "$ref": "#/responses/error"
|
||||
|
||||
art := getArtifactByPathParam(ctx, ctx.Repo.Repository)
|
||||
if ctx.Written() {
|
||||
return
|
||||
}
|
||||
|
||||
if actions_service.IsArtifactV4(art) {
|
||||
if err := actions_model.SetArtifactNeedDeleteByID(ctx, art.ID); err != nil {
|
||||
ctx.APIErrorInternal(err)
|
||||
return
|
||||
}
|
||||
ctx.Status(http.StatusNoContent)
|
||||
return
|
||||
}
|
||||
// v3 not supported due to not having one unique id
|
||||
ctx.APIError(http.StatusNotFound, "Artifact not found")
|
||||
}
|
||||
|
||||
func buildSignature(endp string, expires, artifactID int64) []byte {
|
||||
return actions.BuildSignature("api", endp, strconv.FormatInt(expires, 10), strconv.FormatInt(artifactID, 10))
|
||||
}
|
||||
|
||||
func buildDownloadRawEndpoint(ownerName, repoName string, artifactID int64) string {
|
||||
return fmt.Sprintf("api/v1/repos/%s/%s/actions/artifacts/%d/zip/raw", url.PathEscape(ownerName), url.PathEscape(repoName), artifactID)
|
||||
}
|
||||
|
||||
func buildSigURL(ctx go_context.Context, endPoint string, artifactID int64) string {
|
||||
// endPoint is a path like "api/v1/repos/owner/repo/actions/artifacts/1/zip/raw"
|
||||
expires := time.Now().Add(60 * time.Minute).Unix()
|
||||
uploadURL := httplib.GuessCurrentAppURL(ctx) + endPoint + "?sig=" + base64.RawURLEncoding.EncodeToString(buildSignature(endPoint, expires, artifactID)) + "&expires=" + strconv.FormatInt(expires, 10)
|
||||
return uploadURL
|
||||
}
|
||||
|
||||
// DownloadArtifact Downloads a specific artifact for a workflow run redirects to blob url.
|
||||
func DownloadArtifact(ctx *context.APIContext) {
|
||||
// swagger:operation GET /repos/{owner}/{repo}/actions/artifacts/{artifact_id}/zip repository downloadArtifact
|
||||
// ---
|
||||
// summary: Downloads a specific artifact for a workflow run redirects to blob url
|
||||
// produces:
|
||||
// - application/json
|
||||
// parameters:
|
||||
// - name: owner
|
||||
// in: path
|
||||
// description: owner of the repo
|
||||
// type: string
|
||||
// required: true
|
||||
// - name: repo
|
||||
// in: path
|
||||
// description: name of the repository
|
||||
// type: string
|
||||
// required: true
|
||||
// - name: artifact_id
|
||||
// in: path
|
||||
// description: id of the artifact
|
||||
// type: string
|
||||
// required: true
|
||||
// responses:
|
||||
// "302":
|
||||
// description: redirect to the blob download
|
||||
// default:
|
||||
// "$ref": "#/responses/error"
|
||||
|
||||
art := getArtifactByPathParam(ctx, ctx.Repo.Repository)
|
||||
if ctx.Written() {
|
||||
return
|
||||
}
|
||||
|
||||
// if artifacts status is not uploaded-confirmed, treat it as not found
|
||||
if art.Status == actions_model.ArtifactStatusExpired {
|
||||
ctx.APIError(http.StatusNotFound, "Artifact has expired")
|
||||
return
|
||||
}
|
||||
|
||||
if actions_service.IsArtifactV4(art) {
|
||||
// @actions/toolkit asserts that downloaded artifacts of a different runid return 302
|
||||
// https://github.com/actions/toolkit/blob/44d43b5490b02998bd09b0c4ff369a4cc67876c2/packages/artifact/src/internal/download/download-artifact.ts#L203-L210
|
||||
if actions_service.DownloadArtifactV4ServeDirect(ctx.Base, art) {
|
||||
return
|
||||
}
|
||||
|
||||
// @actions/toolkit asserts a 302 for the artifact download, so we have to build a signed URL and redirect to it
|
||||
// TODO: a perma link to the code for reference
|
||||
redirectURL := buildSigURL(ctx, buildDownloadRawEndpoint(ctx.Repo.Repository.OwnerName, ctx.Repo.Repository.Name, art.ID), art.ID)
|
||||
ctx.Redirect(redirectURL, http.StatusFound)
|
||||
return
|
||||
}
|
||||
// v3 not supported due to not having one unique id
|
||||
ctx.APIError(http.StatusNotFound, "Artifact not found")
|
||||
}
|
||||
|
||||
// DownloadArtifactRaw Downloads a specific artifact for a workflow run directly.
|
||||
func DownloadArtifactRaw(ctx *context.APIContext) {
|
||||
// it doesn't use repoAssignment middleware, so it needs to prepare the repo and check permission (sig) by itself
|
||||
ownerName, repoName := ctx.PathParam("username"), ctx.PathParam("reponame")
|
||||
query := ctx.Req.URL.Query()
|
||||
sigBytes, _ := base64.RawURLEncoding.DecodeString(query.Get("sig"))
|
||||
expires, _ := strconv.ParseInt(query.Get("expires"), 10, 64)
|
||||
artifactID := ctx.PathParamInt64("artifact_id")
|
||||
|
||||
if !hmac.Equal(sigBytes, buildSignature(buildDownloadRawEndpoint(ownerName, repoName, artifactID), expires, artifactID)) {
|
||||
ctx.APIErrorNotFound()
|
||||
return
|
||||
}
|
||||
if time.Unix(expires, 0).Before(time.Now()) {
|
||||
ctx.APIError(http.StatusUnauthorized, "Error link expired")
|
||||
return
|
||||
}
|
||||
|
||||
repo, err := repo_model.GetRepositoryByOwnerAndName(ctx, ownerName, repoName)
|
||||
if err != nil {
|
||||
if errors.Is(err, util.ErrNotExist) {
|
||||
ctx.APIErrorNotFound()
|
||||
} else {
|
||||
ctx.APIErrorInternal(err)
|
||||
}
|
||||
return
|
||||
}
|
||||
art := getArtifactByPathParam(ctx, repo)
|
||||
if ctx.Written() {
|
||||
return
|
||||
}
|
||||
|
||||
// if artifacts status is not uploaded-confirmed, treat it as not found
|
||||
if art.Status == actions_model.ArtifactStatusExpired {
|
||||
ctx.APIError(http.StatusNotFound, "Artifact has expired")
|
||||
return
|
||||
}
|
||||
if actions_service.IsArtifactV4(art) {
|
||||
err := actions_service.DownloadArtifactV4(ctx.Base, art)
|
||||
if err != nil {
|
||||
ctx.APIErrorInternal(err)
|
||||
return
|
||||
}
|
||||
return
|
||||
}
|
||||
// v3 not supported due to not having one unique id
|
||||
ctx.APIError(http.StatusNotFound, "artifact not found")
|
||||
}
|
||||
|
||||
// Try to get the artifact by ID and check access
|
||||
func getArtifactByPathParam(ctx *context.APIContext, repo *repo_model.Repository) *actions_model.ActionArtifact {
|
||||
artifactID := ctx.PathParamInt64("artifact_id")
|
||||
|
||||
art, ok, err := db.GetByID[actions_model.ActionArtifact](ctx, artifactID)
|
||||
if err != nil {
|
||||
ctx.APIErrorInternal(err)
|
||||
return nil
|
||||
}
|
||||
// if artifacts status is not uploaded-confirmed, treat it as not found
|
||||
// only check RepoID here, because the repository owner may change over the time
|
||||
if !ok ||
|
||||
art.RepoID != repo.ID ||
|
||||
art.Status != actions_model.ArtifactStatusUploadConfirmed && art.Status != actions_model.ArtifactStatusExpired {
|
||||
ctx.APIError(http.StatusNotFound, "artifact not found")
|
||||
return nil
|
||||
}
|
||||
return art
|
||||
}
|
||||
@@ -5,11 +5,16 @@ package repo
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
"slices"
|
||||
|
||||
actions_model "gitea.dev/models/actions"
|
||||
"gitea.dev/models/db"
|
||||
"gitea.dev/modules/optional"
|
||||
"gitea.dev/routers/api/v1/shared"
|
||||
"gitea.dev/routers/common"
|
||||
actions_service "gitea.dev/services/actions"
|
||||
"gitea.dev/services/context"
|
||||
"gitea.dev/services/convert"
|
||||
)
|
||||
|
||||
func DownloadActionsRunJobLogs(ctx *context.APIContext) {
|
||||
@@ -232,3 +237,526 @@ func GetWorkflowRunLogs(ctx *context.APIContext) {
|
||||
ctx.APIErrorAuto(err)
|
||||
}
|
||||
}
|
||||
|
||||
func getCurrentRepoActionRunByID(ctx *context.APIContext) *actions_model.ActionRun {
|
||||
runID := ctx.PathParamInt64("run")
|
||||
run, err := actions_model.GetRunByRepoAndID(ctx, ctx.Repo.Repository.ID, runID)
|
||||
if err != nil {
|
||||
ctx.APIErrorAuto(err)
|
||||
return nil
|
||||
}
|
||||
run.Repo = ctx.Repo.Repository
|
||||
return run
|
||||
}
|
||||
|
||||
func getCurrentRepoActionRunJobsByID(ctx *context.APIContext) (*actions_model.ActionRun, actions_model.ActionJobList) {
|
||||
run := getCurrentRepoActionRunByID(ctx)
|
||||
if ctx.Written() {
|
||||
return nil, nil
|
||||
}
|
||||
|
||||
jobs, err := actions_model.GetLatestAttemptJobsByRun(ctx, run)
|
||||
if err != nil {
|
||||
ctx.APIErrorInternal(err)
|
||||
return nil, nil
|
||||
}
|
||||
jobs.SortMatrixGroupsByName()
|
||||
return run, jobs
|
||||
}
|
||||
|
||||
func getCurrentRepoActionRunAttemptByNumber(ctx *context.APIContext) (*actions_model.ActionRun, *actions_model.ActionRunAttempt) {
|
||||
run := getCurrentRepoActionRunByID(ctx)
|
||||
if ctx.Written() {
|
||||
return nil, nil
|
||||
}
|
||||
|
||||
attemptNum := ctx.PathParamInt64("attempt")
|
||||
attempt, err := actions_model.GetRunAttemptByRunIDAndAttemptNum(ctx, run.ID, attemptNum)
|
||||
if err != nil {
|
||||
ctx.APIErrorAuto(err)
|
||||
return nil, nil
|
||||
}
|
||||
return run, attempt
|
||||
}
|
||||
|
||||
func respondRepoActionWorkflowRun(ctx *context.APIContext, run *actions_model.ActionRun) {
|
||||
run.Repo = ctx.Repo.Repository
|
||||
convertedRun, err := convert.ToActionWorkflowRun(ctx, run, nil, false)
|
||||
if err != nil {
|
||||
ctx.APIErrorInternal(err)
|
||||
return
|
||||
}
|
||||
ctx.JSON(http.StatusOK, convertedRun)
|
||||
}
|
||||
|
||||
// GetWorkflowRun Gets a specific workflow run.
|
||||
func GetWorkflowRun(ctx *context.APIContext) {
|
||||
// swagger:operation GET /repos/{owner}/{repo}/actions/runs/{run} repository GetWorkflowRun
|
||||
// ---
|
||||
// summary: Gets a specific workflow run
|
||||
// produces:
|
||||
// - application/json
|
||||
// parameters:
|
||||
// - name: owner
|
||||
// in: path
|
||||
// description: owner of the repo
|
||||
// type: string
|
||||
// required: true
|
||||
// - name: repo
|
||||
// in: path
|
||||
// description: name of the repository
|
||||
// type: string
|
||||
// required: true
|
||||
// - name: run
|
||||
// in: path
|
||||
// description: id of the run
|
||||
// type: integer
|
||||
// required: true
|
||||
// responses:
|
||||
// "200":
|
||||
// "$ref": "#/responses/WorkflowRun"
|
||||
// default:
|
||||
// "$ref": "#/responses/error"
|
||||
|
||||
run := getCurrentRepoActionRunByID(ctx)
|
||||
if ctx.Written() {
|
||||
return
|
||||
}
|
||||
|
||||
respondRepoActionWorkflowRun(ctx, run)
|
||||
}
|
||||
|
||||
// GetWorkflowRunAttempt Gets a specific workflow run attempt.
|
||||
func GetWorkflowRunAttempt(ctx *context.APIContext) {
|
||||
// swagger:operation GET /repos/{owner}/{repo}/actions/runs/{run}/attempts/{attempt} repository getWorkflowRunAttempt
|
||||
// ---
|
||||
// summary: Gets a specific workflow run attempt
|
||||
// produces:
|
||||
// - application/json
|
||||
// parameters:
|
||||
// - name: owner
|
||||
// in: path
|
||||
// description: owner of the repo
|
||||
// type: string
|
||||
// required: true
|
||||
// - name: repo
|
||||
// in: path
|
||||
// description: name of the repository
|
||||
// type: string
|
||||
// required: true
|
||||
// - name: run
|
||||
// in: path
|
||||
// description: id of the run
|
||||
// type: integer
|
||||
// required: true
|
||||
// - name: attempt
|
||||
// in: path
|
||||
// description: logical attempt number of the run
|
||||
// type: integer
|
||||
// required: true
|
||||
// responses:
|
||||
// "200":
|
||||
// "$ref": "#/responses/WorkflowRun"
|
||||
// default:
|
||||
// "$ref": "#/responses/error"
|
||||
|
||||
run, attempt := getCurrentRepoActionRunAttemptByNumber(ctx)
|
||||
if ctx.Written() {
|
||||
return
|
||||
}
|
||||
|
||||
convertedRun, err := convert.ToActionWorkflowRun(ctx, run, attempt, false)
|
||||
if err != nil {
|
||||
ctx.APIErrorInternal(err)
|
||||
return
|
||||
}
|
||||
ctx.JSON(http.StatusOK, convertedRun)
|
||||
}
|
||||
|
||||
// RerunWorkflowRun Reruns an entire workflow run.
|
||||
func RerunWorkflowRun(ctx *context.APIContext) {
|
||||
// swagger:operation POST /repos/{owner}/{repo}/actions/runs/{run}/rerun repository rerunWorkflowRun
|
||||
// ---
|
||||
// summary: Reruns an entire workflow run
|
||||
// produces:
|
||||
// - application/json
|
||||
// parameters:
|
||||
// - name: owner
|
||||
// in: path
|
||||
// description: owner of the repo
|
||||
// type: string
|
||||
// required: true
|
||||
// - name: repo
|
||||
// in: path
|
||||
// description: name of the repository
|
||||
// type: string
|
||||
// required: true
|
||||
// - name: run
|
||||
// in: path
|
||||
// description: id of the run
|
||||
// type: integer
|
||||
// required: true
|
||||
// responses:
|
||||
// "201":
|
||||
// "$ref": "#/responses/WorkflowRun"
|
||||
// default:
|
||||
// "$ref": "#/responses/error"
|
||||
|
||||
run := getCurrentRepoActionRunByID(ctx)
|
||||
if ctx.Written() {
|
||||
return
|
||||
}
|
||||
|
||||
if _, err := actions_service.RerunWorkflowRunJobs(ctx, ctx.Repo.Repository, run, ctx.Doer, nil); err != nil { // nil reruns all jobs, which re-resolves reusable workflow refs
|
||||
ctx.APIErrorAuto(err)
|
||||
return
|
||||
}
|
||||
|
||||
convertedRun, err := convert.ToActionWorkflowRun(ctx, run, nil, false)
|
||||
if err != nil {
|
||||
ctx.APIErrorInternal(err)
|
||||
return
|
||||
}
|
||||
ctx.JSON(http.StatusCreated, convertedRun)
|
||||
}
|
||||
|
||||
// RerunFailedWorkflowRun Reruns all failed jobs in a workflow run.
|
||||
func RerunFailedWorkflowRun(ctx *context.APIContext) {
|
||||
// swagger:operation POST /repos/{owner}/{repo}/actions/runs/{run}/rerun-failed-jobs repository rerunFailedWorkflowRun
|
||||
// ---
|
||||
// summary: Reruns all failed jobs in a workflow run
|
||||
// parameters:
|
||||
// - name: owner
|
||||
// in: path
|
||||
// description: owner of the repo
|
||||
// type: string
|
||||
// required: true
|
||||
// - name: repo
|
||||
// in: path
|
||||
// description: name of the repository
|
||||
// type: string
|
||||
// required: true
|
||||
// - name: run
|
||||
// in: path
|
||||
// description: id of the run
|
||||
// type: integer
|
||||
// required: true
|
||||
// responses:
|
||||
// "201":
|
||||
// "$ref": "#/responses/empty"
|
||||
// default:
|
||||
// "$ref": "#/responses/error"
|
||||
|
||||
run, jobs := getCurrentRepoActionRunJobsByID(ctx)
|
||||
if ctx.Written() {
|
||||
return
|
||||
}
|
||||
|
||||
failedJobs := actions_service.GetFailedJobsForRerun(jobs)
|
||||
// Empty failedJobs means no failed jobs to re-run
|
||||
if len(failedJobs) == 0 {
|
||||
ctx.APIError(http.StatusBadRequest, "this workflow run has no failed jobs to re-run")
|
||||
return
|
||||
}
|
||||
|
||||
if _, err := actions_service.RerunWorkflowRunJobs(ctx, ctx.Repo.Repository, run, ctx.Doer, failedJobs); err != nil {
|
||||
ctx.APIErrorAuto(err)
|
||||
return
|
||||
}
|
||||
|
||||
ctx.Status(http.StatusCreated)
|
||||
}
|
||||
|
||||
// RerunWorkflowJob Reruns a specific workflow job in a run.
|
||||
func RerunWorkflowJob(ctx *context.APIContext) {
|
||||
// swagger:operation POST /repos/{owner}/{repo}/actions/runs/{run}/jobs/{job_id}/rerun repository rerunWorkflowJob
|
||||
// ---
|
||||
// summary: Reruns a specific workflow job in a run
|
||||
// produces:
|
||||
// - application/json
|
||||
// parameters:
|
||||
// - name: owner
|
||||
// in: path
|
||||
// description: owner of the repo
|
||||
// type: string
|
||||
// required: true
|
||||
// - name: repo
|
||||
// in: path
|
||||
// description: name of the repository
|
||||
// type: string
|
||||
// required: true
|
||||
// - name: run
|
||||
// in: path
|
||||
// description: id of the run
|
||||
// type: integer
|
||||
// required: true
|
||||
// - name: job_id
|
||||
// in: path
|
||||
// description: id of the job
|
||||
// type: integer
|
||||
// required: true
|
||||
// responses:
|
||||
// "201":
|
||||
// "$ref": "#/responses/WorkflowJob"
|
||||
// default:
|
||||
// "$ref": "#/responses/error"
|
||||
|
||||
run, jobs := getCurrentRepoActionRunJobsByID(ctx)
|
||||
if ctx.Written() {
|
||||
return
|
||||
}
|
||||
|
||||
jobID := ctx.PathParamInt64("job_id")
|
||||
jobIdx := slices.IndexFunc(jobs, func(job *actions_model.ActionRunJob) bool { return job.ID == jobID })
|
||||
if jobIdx == -1 {
|
||||
ctx.APIErrorNotFound("workflow job not found")
|
||||
return
|
||||
}
|
||||
|
||||
targetJob := jobs[jobIdx]
|
||||
newAttempt, err := actions_service.RerunWorkflowRunJobs(ctx, ctx.Repo.Repository, run, ctx.Doer, []*actions_model.ActionRunJob{targetJob})
|
||||
if err != nil {
|
||||
ctx.APIErrorAuto(err)
|
||||
return
|
||||
}
|
||||
|
||||
// Legacy jobs had AttemptJobID=0 before the rerun; createOriginalAttemptForLegacyRun inside
|
||||
// RerunWorkflowRunJobs has since backfilled it in the DB, so reload only in that case.
|
||||
if targetJob.AttemptJobID == 0 {
|
||||
targetJob, err = actions_model.GetRunJobByRepoAndID(ctx, run.RepoID, targetJob.ID)
|
||||
if err != nil {
|
||||
ctx.APIErrorInternal(err)
|
||||
return
|
||||
}
|
||||
}
|
||||
rerunJob, err := actions_model.GetRunJobByAttemptJobID(ctx, run.ID, newAttempt.ID, targetJob.AttemptJobID)
|
||||
if err != nil {
|
||||
ctx.APIErrorAuto(err)
|
||||
return
|
||||
}
|
||||
|
||||
convertedJob, err := convert.ToActionWorkflowJob(ctx, ctx.Repo.Repository, nil, rerunJob)
|
||||
if err != nil {
|
||||
ctx.APIErrorInternal(err)
|
||||
return
|
||||
}
|
||||
ctx.JSON(http.StatusCreated, convertedJob)
|
||||
}
|
||||
|
||||
// ListWorkflowRunJobs Lists all jobs for a workflow run.
|
||||
func ListWorkflowRunJobs(ctx *context.APIContext) {
|
||||
// swagger:operation GET /repos/{owner}/{repo}/actions/runs/{run}/jobs repository listWorkflowRunJobs
|
||||
// ---
|
||||
// summary: Lists all jobs for a workflow run
|
||||
// produces:
|
||||
// - application/json
|
||||
// parameters:
|
||||
// - name: owner
|
||||
// in: path
|
||||
// description: owner of the repo
|
||||
// type: string
|
||||
// required: true
|
||||
// - name: repo
|
||||
// in: path
|
||||
// description: name of the repository
|
||||
// type: string
|
||||
// required: true
|
||||
// - name: run
|
||||
// in: path
|
||||
// description: runid of the workflow run
|
||||
// type: integer
|
||||
// required: true
|
||||
// - name: status
|
||||
// in: query
|
||||
// description: workflow status (requested, pending, queued, in_progress, failure, success, skipped)
|
||||
// type: string
|
||||
// required: false
|
||||
// - name: page
|
||||
// in: query
|
||||
// description: page number of results to return (1-based)
|
||||
// type: integer
|
||||
// - name: limit
|
||||
// in: query
|
||||
// description: page size of results
|
||||
// type: integer
|
||||
// - name: sort
|
||||
// in: query
|
||||
// description: sort jobs by attribute. Supported values are "id". Default is "id"
|
||||
// type: string
|
||||
// - name: order
|
||||
// in: query
|
||||
// description: sort order, either "asc" (ascending) or "desc" (descending). Default is "asc"
|
||||
// type: string
|
||||
// responses:
|
||||
// "200":
|
||||
// "$ref": "#/responses/WorkflowJobsList"
|
||||
// default:
|
||||
// "$ref": "#/responses/error"
|
||||
|
||||
repoID, runID := ctx.Repo.Repository.ID, ctx.PathParamInt64("run")
|
||||
|
||||
// Avoid the list all jobs functionality for this api route to be used with a runID == 0.
|
||||
if runID <= 0 {
|
||||
ctx.APIError(http.StatusBadRequest, "runID must be a positive integer")
|
||||
return
|
||||
}
|
||||
|
||||
run, err := actions_model.GetRunByRepoAndID(ctx, repoID, runID)
|
||||
if err != nil {
|
||||
ctx.APIErrorAuto(err)
|
||||
return
|
||||
}
|
||||
// runID is used as an additional filter next to repoID to ensure that we only list jobs for the specified repoID and runID.
|
||||
// no additional checks for runID are needed here
|
||||
shared.ListJobs(ctx, 0, repoID, runID, optional.Some(run.LatestAttemptID))
|
||||
}
|
||||
|
||||
// ListWorkflowRunAttemptJobs Lists all jobs for a workflow run attempt.
|
||||
func ListWorkflowRunAttemptJobs(ctx *context.APIContext) {
|
||||
// swagger:operation GET /repos/{owner}/{repo}/actions/runs/{run}/attempts/{attempt}/jobs repository listWorkflowRunAttemptJobs
|
||||
// ---
|
||||
// summary: Lists all jobs for a workflow run attempt
|
||||
// produces:
|
||||
// - application/json
|
||||
// parameters:
|
||||
// - name: owner
|
||||
// in: path
|
||||
// description: owner of the repo
|
||||
// type: string
|
||||
// required: true
|
||||
// - name: repo
|
||||
// in: path
|
||||
// description: name of the repository
|
||||
// type: string
|
||||
// required: true
|
||||
// - name: run
|
||||
// in: path
|
||||
// description: id of the workflow run
|
||||
// type: integer
|
||||
// required: true
|
||||
// - name: attempt
|
||||
// in: path
|
||||
// description: logical attempt number of the run
|
||||
// type: integer
|
||||
// required: true
|
||||
// - name: status
|
||||
// in: query
|
||||
// description: workflow status (requested, pending, queued, in_progress, failure, success, skipped)
|
||||
// type: string
|
||||
// required: false
|
||||
// - name: page
|
||||
// in: query
|
||||
// description: page number of results to return (1-based)
|
||||
// type: integer
|
||||
// - name: limit
|
||||
// in: query
|
||||
// description: page size of results
|
||||
// type: integer
|
||||
// responses:
|
||||
// "200":
|
||||
// "$ref": "#/responses/WorkflowJobsList"
|
||||
// default:
|
||||
// "$ref": "#/responses/error"
|
||||
|
||||
run, attempt := getCurrentRepoActionRunAttemptByNumber(ctx)
|
||||
if ctx.Written() {
|
||||
return
|
||||
}
|
||||
|
||||
shared.ListJobs(ctx, 0, run.RepoID, run.ID, optional.Some(attempt.ID))
|
||||
}
|
||||
|
||||
// GetWorkflowJob Gets a specific workflow job for a workflow run.
|
||||
func GetWorkflowJob(ctx *context.APIContext) {
|
||||
// swagger:operation GET /repos/{owner}/{repo}/actions/jobs/{job_id} repository getWorkflowJob
|
||||
// ---
|
||||
// summary: Gets a specific workflow job for a workflow run
|
||||
// produces:
|
||||
// - application/json
|
||||
// parameters:
|
||||
// - name: owner
|
||||
// in: path
|
||||
// description: owner of the repo
|
||||
// type: string
|
||||
// required: true
|
||||
// - name: repo
|
||||
// in: path
|
||||
// description: name of the repository
|
||||
// type: string
|
||||
// required: true
|
||||
// - name: job_id
|
||||
// in: path
|
||||
// description: id of the job
|
||||
// type: string
|
||||
// required: true
|
||||
// responses:
|
||||
// "200":
|
||||
// "$ref": "#/responses/WorkflowJob"
|
||||
// default:
|
||||
// "$ref": "#/responses/error"
|
||||
|
||||
jobID := ctx.PathParamInt64("job_id")
|
||||
job, has, err := db.GetByID[actions_model.ActionRunJob](ctx, jobID)
|
||||
if err != nil {
|
||||
ctx.APIErrorInternal(err)
|
||||
return
|
||||
}
|
||||
|
||||
if !has || job.RepoID != ctx.Repo.Repository.ID {
|
||||
ctx.APIErrorNotFound()
|
||||
return
|
||||
}
|
||||
|
||||
convertedWorkflowJob, err := convert.ToActionWorkflowJob(ctx, ctx.Repo.Repository, nil, job)
|
||||
if err != nil {
|
||||
ctx.APIErrorInternal(err)
|
||||
return
|
||||
}
|
||||
ctx.JSON(http.StatusOK, convertedWorkflowJob)
|
||||
}
|
||||
|
||||
// DeleteActionRun Delete a workflow run
|
||||
func DeleteActionRun(ctx *context.APIContext) {
|
||||
// swagger:operation DELETE /repos/{owner}/{repo}/actions/runs/{run} repository deleteActionRun
|
||||
// ---
|
||||
// summary: Delete a workflow run
|
||||
// produces:
|
||||
// - application/json
|
||||
// parameters:
|
||||
// - name: owner
|
||||
// in: path
|
||||
// description: owner of the repo
|
||||
// type: string
|
||||
// required: true
|
||||
// - name: repo
|
||||
// in: path
|
||||
// description: name of the repository
|
||||
// type: string
|
||||
// required: true
|
||||
// - name: run
|
||||
// in: path
|
||||
// description: runid of the workflow run
|
||||
// type: integer
|
||||
// required: true
|
||||
// responses:
|
||||
// "204":
|
||||
// description: "No Content"
|
||||
// default:
|
||||
// "$ref": "#/responses/error"
|
||||
|
||||
run := getCurrentRepoActionRunByID(ctx)
|
||||
if ctx.Written() {
|
||||
return
|
||||
}
|
||||
|
||||
if !run.Status.IsDone() {
|
||||
ctx.APIError(http.StatusBadRequest, "this workflow run is not done")
|
||||
return
|
||||
}
|
||||
|
||||
if err := actions_service.DeleteRun(ctx, run); err != nil {
|
||||
ctx.APIErrorInternal(err)
|
||||
return
|
||||
}
|
||||
ctx.Status(http.StatusNoContent)
|
||||
}
|
||||
@@ -0,0 +1,363 @@
|
||||
// Copyright 2026 The Gitea Authors. All rights reserved.
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
package repo
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"fmt"
|
||||
"net/http"
|
||||
"strings"
|
||||
|
||||
"gitea.dev/actionslib/pkg/model"
|
||||
actions_model "gitea.dev/models/actions"
|
||||
"gitea.dev/models/db"
|
||||
"gitea.dev/modules/optional"
|
||||
api "gitea.dev/modules/structs"
|
||||
"gitea.dev/modules/util"
|
||||
"gitea.dev/modules/web"
|
||||
"gitea.dev/routers/api/v1/shared"
|
||||
actions_service "gitea.dev/services/actions"
|
||||
"gitea.dev/services/context"
|
||||
"gitea.dev/services/convert"
|
||||
)
|
||||
|
||||
func ActionsListRepositoryWorkflows(ctx *context.APIContext) {
|
||||
// swagger:operation GET /repos/{owner}/{repo}/actions/workflows repository ActionsListRepositoryWorkflows
|
||||
// ---
|
||||
// summary: List repository workflows
|
||||
// produces:
|
||||
// - application/json
|
||||
// parameters:
|
||||
// - name: owner
|
||||
// in: path
|
||||
// description: owner of the repo
|
||||
// type: string
|
||||
// required: true
|
||||
// - name: repo
|
||||
// in: path
|
||||
// description: name of the repo
|
||||
// type: string
|
||||
// required: true
|
||||
// responses:
|
||||
// "200":
|
||||
// "$ref": "#/responses/ActionWorkflowList"
|
||||
// default:
|
||||
// "$ref": "#/responses/error"
|
||||
|
||||
workflows, err := convert.ListActionWorkflows(ctx, ctx.Repo.GitRepo, ctx.Repo.Repository)
|
||||
if err != nil {
|
||||
ctx.APIErrorInternal(err)
|
||||
return
|
||||
}
|
||||
|
||||
ctx.JSON(http.StatusOK, &api.ActionWorkflowResponse{Workflows: workflows, TotalCount: int64(len(workflows))})
|
||||
}
|
||||
|
||||
func ActionsGetWorkflow(ctx *context.APIContext) {
|
||||
// swagger:operation GET /repos/{owner}/{repo}/actions/workflows/{workflow_id} repository ActionsGetWorkflow
|
||||
// ---
|
||||
// summary: Get a workflow
|
||||
// produces:
|
||||
// - application/json
|
||||
// parameters:
|
||||
// - name: owner
|
||||
// in: path
|
||||
// description: owner of the repo
|
||||
// type: string
|
||||
// required: true
|
||||
// - name: repo
|
||||
// in: path
|
||||
// description: name of the repo
|
||||
// type: string
|
||||
// required: true
|
||||
// - name: workflow_id
|
||||
// in: path
|
||||
// description: id of the workflow
|
||||
// type: string
|
||||
// required: true
|
||||
// responses:
|
||||
// "200":
|
||||
// "$ref": "#/responses/ActionWorkflow"
|
||||
// default:
|
||||
// "$ref": "#/responses/error"
|
||||
|
||||
workflowID := ctx.PathParam("workflow_id")
|
||||
workflow, err := convert.GetActionWorkflow(ctx, ctx.Repo.GitRepo, ctx.Repo.Repository, workflowID)
|
||||
if err != nil {
|
||||
ctx.APIErrorAuto(err)
|
||||
return
|
||||
}
|
||||
|
||||
ctx.JSON(http.StatusOK, workflow)
|
||||
}
|
||||
|
||||
func ActionsListWorkflowRuns(ctx *context.APIContext) {
|
||||
// swagger:operation GET /repos/{owner}/{repo}/actions/workflows/{workflow_id}/runs repository ActionsListWorkflowRuns
|
||||
// ---
|
||||
// summary: List runs for a workflow
|
||||
// produces:
|
||||
// - application/json
|
||||
// parameters:
|
||||
// - name: owner
|
||||
// in: path
|
||||
// description: owner of the repo
|
||||
// type: string
|
||||
// required: true
|
||||
// - name: repo
|
||||
// in: path
|
||||
// description: name of the repo
|
||||
// type: string
|
||||
// required: true
|
||||
// - name: workflow_id
|
||||
// in: path
|
||||
// description: id of the workflow, must be the workflow file name (e.g. `build.yml`)
|
||||
// type: string
|
||||
// required: true
|
||||
// - name: event
|
||||
// in: query
|
||||
// description: workflow event name
|
||||
// type: string
|
||||
// required: false
|
||||
// - name: branch
|
||||
// in: query
|
||||
// description: workflow branch
|
||||
// type: string
|
||||
// required: false
|
||||
// - name: status
|
||||
// in: query
|
||||
// description: workflow status (requested, pending, queued, in_progress, failure, success, skipped)
|
||||
// type: string
|
||||
// required: false
|
||||
// - name: actor
|
||||
// in: query
|
||||
// description: triggered by user
|
||||
// type: string
|
||||
// required: false
|
||||
// - name: head_sha
|
||||
// in: query
|
||||
// description: triggering sha of the workflow run
|
||||
// type: string
|
||||
// required: false
|
||||
// - name: exclude_pull_requests
|
||||
// in: query
|
||||
// description: if true, the `pull_requests` field on each returned run is emptied
|
||||
// type: boolean
|
||||
// required: false
|
||||
// - name: scoped_workflow_source_repo_id
|
||||
// description: For a scoped workflow, the ID of the source repository providing it; omit or 0 for a repo-level workflow.
|
||||
// in: query
|
||||
// type: integer
|
||||
// format: int64
|
||||
// - name: page
|
||||
// in: query
|
||||
// description: page number of results to return (1-based)
|
||||
// type: integer
|
||||
// - name: limit
|
||||
// in: query
|
||||
// description: page size of results
|
||||
// type: integer
|
||||
// responses:
|
||||
// "200":
|
||||
// "$ref": "#/responses/WorkflowRunsList"
|
||||
// default:
|
||||
// "$ref": "#/responses/error"
|
||||
|
||||
workflowID := ctx.PathParam("workflow_id")
|
||||
scopedWorkflowSourceRepoID := ctx.FormInt64("scoped_workflow_source_repo_id")
|
||||
// Existing runs prove the workflow is/was valid and cover historical workflows whose file was later removed.
|
||||
// Repo-level never-run workflows fall back to a git lookup; scoped workflows are selected by source repo ID and may return an empty run list.
|
||||
runExists, err := db.Exist[actions_model.ActionRun](ctx, actions_model.FindRunOptions{
|
||||
RepoID: ctx.Repo.Repository.ID,
|
||||
WorkflowID: workflowID,
|
||||
WorkflowRepoID: scopedWorkflowSourceRepoID,
|
||||
IsScopedRun: optional.Some(scopedWorkflowSourceRepoID > 0),
|
||||
}.ToConds())
|
||||
if err != nil {
|
||||
ctx.APIErrorInternal(err)
|
||||
return
|
||||
}
|
||||
if !runExists {
|
||||
if scopedWorkflowSourceRepoID == 0 {
|
||||
if _, err := convert.GetActionWorkflow(ctx, ctx.Repo.GitRepo, ctx.Repo.Repository, workflowID); err != nil {
|
||||
ctx.APIErrorAuto(err)
|
||||
return
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
shared.ListRuns(ctx, 0, ctx.Repo.Repository.ID, workflowID)
|
||||
}
|
||||
|
||||
func ActionsDisableWorkflow(ctx *context.APIContext) {
|
||||
// swagger:operation PUT /repos/{owner}/{repo}/actions/workflows/{workflow_id}/disable repository ActionsDisableWorkflow
|
||||
// ---
|
||||
// summary: Disable a workflow
|
||||
// produces:
|
||||
// - application/json
|
||||
// parameters:
|
||||
// - name: owner
|
||||
// in: path
|
||||
// description: owner of the repo
|
||||
// type: string
|
||||
// required: true
|
||||
// - name: repo
|
||||
// in: path
|
||||
// description: name of the repo
|
||||
// type: string
|
||||
// required: true
|
||||
// - name: workflow_id
|
||||
// in: path
|
||||
// description: id of the workflow
|
||||
// type: string
|
||||
// required: true
|
||||
// responses:
|
||||
// "204":
|
||||
// description: No Content
|
||||
// default:
|
||||
// "$ref": "#/responses/error"
|
||||
|
||||
workflowID := ctx.PathParam("workflow_id")
|
||||
err := actions_service.EnableOrDisableWorkflow(ctx, workflowID, false)
|
||||
if err != nil {
|
||||
ctx.APIErrorAuto(err)
|
||||
return
|
||||
}
|
||||
|
||||
ctx.Status(http.StatusNoContent)
|
||||
}
|
||||
|
||||
func ActionsDispatchWorkflow(ctx *context.APIContext) {
|
||||
// swagger:operation POST /repos/{owner}/{repo}/actions/workflows/{workflow_id}/dispatches repository ActionsDispatchWorkflow
|
||||
// ---
|
||||
// summary: Create a workflow dispatch event
|
||||
// produces:
|
||||
// - application/json
|
||||
// parameters:
|
||||
// - name: owner
|
||||
// in: path
|
||||
// description: owner of the repo
|
||||
// type: string
|
||||
// required: true
|
||||
// - name: repo
|
||||
// in: path
|
||||
// description: name of the repo
|
||||
// type: string
|
||||
// required: true
|
||||
// - name: workflow_id
|
||||
// in: path
|
||||
// description: id of the workflow
|
||||
// type: string
|
||||
// required: true
|
||||
// - name: body
|
||||
// in: body
|
||||
// schema:
|
||||
// "$ref": "#/definitions/CreateActionWorkflowDispatch"
|
||||
// - name: return_run_details
|
||||
// description: Whether the response should include the workflow run ID and URLs.
|
||||
// in: query
|
||||
// type: boolean
|
||||
// - name: scoped_workflow_source_repo_id
|
||||
// description: For a scoped workflow, the ID of the source repository providing it; omit or 0 for a repo-level workflow.
|
||||
// in: query
|
||||
// type: integer
|
||||
// format: int64
|
||||
// responses:
|
||||
// "200":
|
||||
// "$ref": "#/responses/RunDetails"
|
||||
// "204":
|
||||
// description: No Content, if return_run_details is missing or false
|
||||
// default:
|
||||
// "$ref": "#/responses/error"
|
||||
|
||||
workflowID := ctx.PathParam("workflow_id")
|
||||
opt := web.GetForm[*api.CreateActionWorkflowDispatch](ctx)
|
||||
if opt.Ref == "" {
|
||||
ctx.APIError(http.StatusUnprocessableEntity, "ref is required parameter")
|
||||
return
|
||||
}
|
||||
|
||||
// a non-zero scoped_workflow_source_repo_id dispatches a scoped workflow from that source repo; 0/absent is repo-level.
|
||||
scopedWorkflowSourceRepoID := ctx.FormInt64("scoped_workflow_source_repo_id")
|
||||
runID, err := actions_service.DispatchActionWorkflow(ctx, ctx.Doer, ctx.Repo.Repository, ctx.Repo.GitRepo, workflowID, opt.Ref, scopedWorkflowSourceRepoID, func(workflowDispatch *model.WorkflowDispatch, inputs map[string]any) error {
|
||||
if strings.Contains(ctx.Req.Header.Get("Content-Type"), "form-urlencoded") {
|
||||
// The chi framework's "Binding" doesn't support to bind the form map values into a map[string]string
|
||||
// So we have to manually read the `inputs[key]` from the form
|
||||
for name, config := range workflowDispatch.Inputs {
|
||||
value := ctx.FormString("inputs["+name+"]", config.Default)
|
||||
inputs[name] = value
|
||||
}
|
||||
} else {
|
||||
for name, config := range workflowDispatch.Inputs {
|
||||
value, ok := opt.Inputs[name]
|
||||
if ok {
|
||||
inputs[name] = value
|
||||
} else {
|
||||
inputs[name] = config.Default
|
||||
}
|
||||
}
|
||||
}
|
||||
return nil
|
||||
})
|
||||
if err != nil {
|
||||
if errors.Is(err, util.ErrNotExist) {
|
||||
ctx.APIError(http.StatusNotFound, err.Error())
|
||||
} else if errors.Is(err, util.ErrPermissionDenied) {
|
||||
ctx.APIError(http.StatusForbidden, err.Error())
|
||||
} else if errors.Is(err, util.ErrInvalidArgument) {
|
||||
ctx.APIError(http.StatusUnprocessableEntity, err.Error())
|
||||
} else {
|
||||
ctx.APIErrorInternal(err)
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
if !ctx.FormBool("return_run_details") {
|
||||
ctx.Status(http.StatusNoContent)
|
||||
return
|
||||
}
|
||||
|
||||
ctx.JSON(http.StatusOK, &api.RunDetails{
|
||||
WorkflowRunID: runID,
|
||||
HTMLURL: fmt.Sprintf("%s/actions/runs/%d", ctx.Repo.Repository.HTMLURL(ctx), runID),
|
||||
RunURL: fmt.Sprintf("%s/actions/runs/%d", ctx.Repo.Repository.APIURL(), runID),
|
||||
})
|
||||
}
|
||||
|
||||
func ActionsEnableWorkflow(ctx *context.APIContext) {
|
||||
// swagger:operation PUT /repos/{owner}/{repo}/actions/workflows/{workflow_id}/enable repository ActionsEnableWorkflow
|
||||
// ---
|
||||
// summary: Enable a workflow
|
||||
// produces:
|
||||
// - application/json
|
||||
// parameters:
|
||||
// - name: owner
|
||||
// in: path
|
||||
// description: owner of the repo
|
||||
// type: string
|
||||
// required: true
|
||||
// - name: repo
|
||||
// in: path
|
||||
// description: name of the repo
|
||||
// type: string
|
||||
// required: true
|
||||
// - name: workflow_id
|
||||
// in: path
|
||||
// description: id of the workflow
|
||||
// type: string
|
||||
// required: true
|
||||
// responses:
|
||||
// "204":
|
||||
// description: No Content
|
||||
// default:
|
||||
// "$ref": "#/responses/error"
|
||||
|
||||
workflowID := ctx.PathParam("workflow_id")
|
||||
err := actions_service.EnableOrDisableWorkflow(ctx, workflowID, true)
|
||||
if err != nil {
|
||||
ctx.APIErrorAuto(err)
|
||||
return
|
||||
}
|
||||
|
||||
ctx.Status(http.StatusNoContent)
|
||||
}
|
||||
@@ -1,12 +1,12 @@
|
||||
// Copyright 2024 The Gitea Authors. All rights reserved.
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
package actions
|
||||
package shared
|
||||
|
||||
import "gitea.dev/services/context"
|
||||
|
||||
// API for actions of a repository or organization
|
||||
type API interface {
|
||||
// ActionsAPI for actions of a repository or organization
|
||||
type ActionsAPI interface {
|
||||
// ListActionsSecrets list secrets
|
||||
ListActionsSecrets(*context.APIContext)
|
||||
// CreateOrUpdateSecret create or update a secret
|
||||
@@ -4,21 +4,15 @@
|
||||
package actions
|
||||
|
||||
import (
|
||||
"archive/zip"
|
||||
"cmp"
|
||||
"compress/gzip"
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"html/template"
|
||||
"io"
|
||||
"net/http"
|
||||
"net/url"
|
||||
"strconv"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"gitea.dev/actionslib/pkg/model"
|
||||
actions_model "gitea.dev/models/actions"
|
||||
"gitea.dev/models/db"
|
||||
git_model "gitea.dev/models/git"
|
||||
@@ -30,11 +24,9 @@ import (
|
||||
"gitea.dev/modules/base"
|
||||
"gitea.dev/modules/cache"
|
||||
"gitea.dev/modules/git"
|
||||
"gitea.dev/modules/httplib"
|
||||
"gitea.dev/modules/json"
|
||||
"gitea.dev/modules/log"
|
||||
"gitea.dev/modules/optional"
|
||||
"gitea.dev/modules/storage"
|
||||
api "gitea.dev/modules/structs"
|
||||
"gitea.dev/modules/templates"
|
||||
"gitea.dev/modules/translation"
|
||||
@@ -42,165 +34,9 @@ import (
|
||||
"gitea.dev/modules/web"
|
||||
"gitea.dev/modules/web/middleware"
|
||||
"gitea.dev/routers/common"
|
||||
actions_service "gitea.dev/services/actions"
|
||||
context_module "gitea.dev/services/context"
|
||||
)
|
||||
|
||||
func findCurrentJobByPathParam(ctx *context_module.Context, jobs []*actions_model.ActionRunJob) (job *actions_model.ActionRunJob, hasPathParam bool) {
|
||||
selectedJobID := ctx.PathParamInt64("job")
|
||||
if selectedJobID <= 0 {
|
||||
return nil, false
|
||||
}
|
||||
for _, job = range jobs {
|
||||
if job.ID == selectedJobID {
|
||||
return job, true
|
||||
}
|
||||
}
|
||||
return nil, true
|
||||
}
|
||||
|
||||
func getCurrentRunByPathParam(ctx *context_module.Context) (run *actions_model.ActionRun) {
|
||||
var err error
|
||||
// if run param is "latest", get the latest run id
|
||||
if ctx.PathParam("run") == "latest" {
|
||||
run, err = actions_model.GetLatestRun(ctx, ctx.Repo.Repository.ID)
|
||||
} else {
|
||||
run, err = actions_model.GetRunByRepoAndID(ctx, ctx.Repo.Repository.ID, ctx.PathParamInt64("run"))
|
||||
}
|
||||
if err != nil {
|
||||
ctx.ServerErrorAuto(err)
|
||||
}
|
||||
return run
|
||||
}
|
||||
|
||||
// resolveCurrentRunForView resolves GET Actions page URLs and supports both ID-based and legacy index-based forms.
|
||||
//
|
||||
// By default, run summary pages (/actions/runs/{run}) use a best-effort ID-first fallback,
|
||||
// and job pages (/actions/runs/{run}/jobs/{job}) try to confirm an ID-based URL first and prefer the ID-based interpretation when both are valid.
|
||||
//
|
||||
// `by_id=1` param explicitly forces the ID-based path, and `by_index=1` explicitly forces the legacy index-based path.
|
||||
// If both are present, `by_id` takes precedence.
|
||||
func resolveCurrentRunForView(ctx *context_module.Context) *actions_model.ActionRun {
|
||||
// `by_id` explicitly requests ID-based resolution, so the request skips the legacy index-based disambiguation logic and resolves the run by ID directly.
|
||||
// It takes precedence over `by_index` when both query parameters are present.
|
||||
if ctx.PathParam("run") == "latest" || ctx.FormBool("by_id") {
|
||||
return getCurrentRunByPathParam(ctx)
|
||||
}
|
||||
|
||||
runNum := ctx.PathParamInt64("run")
|
||||
if runNum <= 0 {
|
||||
ctx.NotFound()
|
||||
return nil
|
||||
}
|
||||
|
||||
byIndex := ctx.FormBool("by_index")
|
||||
|
||||
if ctx.PathParam("job") == "" {
|
||||
// The URL does not contain a {job} path parameter, so it cannot use the
|
||||
// job-specific rules to disambiguate ID-based URLs from legacy index-based URLs.
|
||||
// Because of that, this path is handled with a best-effort ID-first fallback by default.
|
||||
//
|
||||
// When the same repository contains:
|
||||
// - a run whose ID matches runNum, and
|
||||
// - a different run whose repo-scope index also matches runNum
|
||||
// this path prefers the ID match and may show a different run than the old legacy URL originally intended,
|
||||
// unless `by_index=1` explicitly forces the legacy index-based interpretation.
|
||||
|
||||
if !byIndex {
|
||||
runByID, err := actions_model.GetRunByRepoAndID(ctx, ctx.Repo.Repository.ID, runNum)
|
||||
if err == nil {
|
||||
return runByID
|
||||
}
|
||||
if !errors.Is(err, util.ErrNotExist) {
|
||||
ctx.ServerErrorAuto(err)
|
||||
return nil
|
||||
}
|
||||
}
|
||||
|
||||
runByIndex, err := actions_model.GetRunByRepoAndIndex(ctx, ctx.Repo.Repository.ID, runNum)
|
||||
if err == nil {
|
||||
ctx.Redirect(fmt.Sprintf("%s/actions/runs/%d", ctx.Repo.RepoLink, runByIndex.ID), http.StatusFound)
|
||||
return nil
|
||||
}
|
||||
if !errors.Is(err, util.ErrNotExist) {
|
||||
ctx.ServerErrorAuto(err)
|
||||
return nil
|
||||
}
|
||||
ctx.NotFound()
|
||||
return nil
|
||||
}
|
||||
|
||||
jobNum := ctx.PathParamInt64("job")
|
||||
if jobNum < 0 {
|
||||
ctx.NotFound()
|
||||
return nil
|
||||
}
|
||||
|
||||
// A job index should not be larger than MaxJobNumPerRun, so larger values can skip the legacy index-based path and be treated as job IDs directly.
|
||||
if !byIndex && jobNum >= actions_model.MaxJobNumPerRun {
|
||||
return getCurrentRunByPathParam(ctx)
|
||||
}
|
||||
|
||||
var runByID, runByIndex *actions_model.ActionRun
|
||||
var targetJobByIndex *actions_model.ActionRunJob
|
||||
|
||||
if !byIndex {
|
||||
// Probe the repo-scoped job ID first and only accept it when the job exists and belongs to the same runNum.
|
||||
job, err := actions_model.GetRunJobByRepoAndID(ctx, ctx.Repo.Repository.ID, jobNum)
|
||||
if err != nil && !errors.Is(err, util.ErrNotExist) {
|
||||
ctx.ServerErrorAuto(err)
|
||||
return nil
|
||||
}
|
||||
if job != nil {
|
||||
if err := job.LoadRun(ctx); err != nil {
|
||||
ctx.ServerErrorAuto(err)
|
||||
return nil
|
||||
}
|
||||
if job.Run.ID == runNum {
|
||||
runByID = job.Run
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Try to resolve the request as a legacy run-index/job-index URL.
|
||||
{
|
||||
run, err := actions_model.GetRunByRepoAndIndex(ctx, ctx.Repo.Repository.ID, runNum)
|
||||
if err != nil && !errors.Is(err, util.ErrNotExist) {
|
||||
ctx.ServerErrorAuto(err)
|
||||
return nil
|
||||
}
|
||||
if run != nil {
|
||||
jobs, err := actions_model.GetLatestAttemptJobsByRepoAndRunID(ctx, run.RepoID, run.ID)
|
||||
if err != nil {
|
||||
ctx.ServerErrorAuto(err)
|
||||
return nil
|
||||
}
|
||||
if jobNum < int64(len(jobs)) {
|
||||
runByIndex = run
|
||||
targetJobByIndex = jobs[jobNum]
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if runByID == nil && runByIndex == nil {
|
||||
ctx.NotFound()
|
||||
return nil
|
||||
}
|
||||
|
||||
if runByID != nil && runByIndex == nil {
|
||||
return runByID
|
||||
}
|
||||
|
||||
if runByID == nil && runByIndex != nil {
|
||||
ctx.Redirect(fmt.Sprintf("%s/actions/runs/%d/jobs/%d", ctx.Repo.RepoLink, runByIndex.ID, targetJobByIndex.ID), http.StatusFound)
|
||||
return nil
|
||||
}
|
||||
|
||||
// Reaching this point means both ID-based and legacy index-based interpretations are valid. Prefer the ID-based interpretation by default.
|
||||
// Use `by_index=1` query parameter to access the legacy index-based interpretation when necessary.
|
||||
return runByID
|
||||
}
|
||||
|
||||
func View(ctx *context_module.Context) {
|
||||
ctx.Data["PageIsActions"] = true
|
||||
run := resolveCurrentRunForView(ctx)
|
||||
@@ -916,117 +752,6 @@ func convertToViewModel(ctx context.Context, locale translation.Locale, cursors
|
||||
return viewJobs, logs, nil
|
||||
}
|
||||
|
||||
// checkRunRerunAllowed checks whether a rerun is permitted for the given run,
|
||||
// writing the appropriate JSON error to ctx and returning false when it is not.
|
||||
func checkRunRerunAllowed(ctx *context_module.Context, run *actions_model.ActionRun) bool {
|
||||
if !run.Status.IsDone() {
|
||||
ctx.JSONError(ctx.Locale.Tr("actions.runs.not_done"))
|
||||
return false
|
||||
}
|
||||
cfgUnit := ctx.Repo.Repository.MustGetUnit(ctx, unit.TypeActions)
|
||||
cfg := cfgUnit.ActionsConfig()
|
||||
disabled := cfg.IsWorkflowDisabled(run.WorkflowID)
|
||||
if run.IsScopedRun {
|
||||
optedOut, err := actions_model.IsScopedWorkflowOptedOut(ctx, cfg, ctx.Repo.Repository.OwnerID, run.WorkflowRepoID, run.WorkflowID)
|
||||
if err != nil {
|
||||
ctx.ServerErrorAuto(err)
|
||||
return false
|
||||
}
|
||||
disabled = optedOut
|
||||
}
|
||||
if disabled {
|
||||
ctx.JSONError(ctx.Locale.Tr("actions.workflow.disabled"))
|
||||
return false
|
||||
}
|
||||
return true
|
||||
}
|
||||
|
||||
func checkLatestAttempt(ctx *context_module.Context, run *actions_model.ActionRun, attempt *actions_model.ActionRunAttempt) bool {
|
||||
if attempt != nil && run.LatestAttemptID != attempt.ID {
|
||||
ctx.NotFound()
|
||||
return false
|
||||
}
|
||||
return true
|
||||
}
|
||||
|
||||
// Rerun will rerun jobs in the given run
|
||||
// If jobIDStr is a blank string, it means rerun all jobs
|
||||
func Rerun(ctx *context_module.Context) {
|
||||
run, attempt, jobs := getCurrentRunJobsByPathParam(ctx)
|
||||
if ctx.Written() {
|
||||
return
|
||||
}
|
||||
if !checkLatestAttempt(ctx, run, attempt) {
|
||||
return
|
||||
}
|
||||
if !checkRunRerunAllowed(ctx, run) {
|
||||
return
|
||||
}
|
||||
if len(jobs) == 0 {
|
||||
ctx.JSONError(ctx.Locale.Tr("actions.runs.no_job"))
|
||||
return
|
||||
}
|
||||
|
||||
currentJob, hasPathParam := findCurrentJobByPathParam(ctx, jobs)
|
||||
if hasPathParam && currentJob == nil {
|
||||
ctx.NotFound()
|
||||
return
|
||||
}
|
||||
|
||||
var jobsToRerun []*actions_model.ActionRunJob
|
||||
if currentJob != nil {
|
||||
jobsToRerun = []*actions_model.ActionRunJob{currentJob}
|
||||
}
|
||||
|
||||
if _, err := actions_service.RerunWorkflowRunJobs(ctx, ctx.Repo.Repository, run, ctx.Doer, jobsToRerun); err != nil {
|
||||
handleWorkflowRerunError(ctx, err)
|
||||
return
|
||||
}
|
||||
|
||||
ctx.JSONRedirect(run.Link())
|
||||
}
|
||||
|
||||
// RerunFailed reruns all failed jobs in the given run
|
||||
func RerunFailed(ctx *context_module.Context) {
|
||||
run, attempt, jobs := getCurrentRunJobsByPathParam(ctx)
|
||||
if ctx.Written() {
|
||||
return
|
||||
}
|
||||
if !checkLatestAttempt(ctx, run, attempt) {
|
||||
return
|
||||
}
|
||||
if !checkRunRerunAllowed(ctx, run) {
|
||||
return
|
||||
}
|
||||
|
||||
// An empty job list means "re-run the whole run" to RerunWorkflowRunJobs, which is right for the plain
|
||||
// rerun button but wrong here, so a direct POST on a fully successful run cannot re-run everything.
|
||||
failedJobs := actions_service.GetFailedJobsForRerun(jobs)
|
||||
if len(failedJobs) == 0 {
|
||||
ctx.JSONError(ctx.Locale.Tr("actions.runs.no_failed_jobs"))
|
||||
return
|
||||
}
|
||||
|
||||
if _, err := actions_service.RerunWorkflowRunJobs(ctx, ctx.Repo.Repository, run, ctx.Doer, failedJobs); err != nil {
|
||||
handleWorkflowRerunError(ctx, err)
|
||||
return
|
||||
}
|
||||
|
||||
ctx.JSONRedirect(run.Link())
|
||||
}
|
||||
|
||||
func handleWorkflowRerunError(ctx *context_module.Context, err error) {
|
||||
if errors.Is(err, util.ErrAlreadyExist) {
|
||||
ctx.JSON(http.StatusConflict, map[string]any{"message": err.Error()})
|
||||
return
|
||||
}
|
||||
if errors.Is(err, util.ErrInvalidArgument) {
|
||||
ctx.JSON(http.StatusBadRequest, map[string]any{"message": err.Error()})
|
||||
return
|
||||
}
|
||||
ctx.ServerErrorAuto(err)
|
||||
}
|
||||
|
||||
func Logs(ctx *context_module.Context) {
|
||||
run := getCurrentRunByPathParam(ctx)
|
||||
if ctx.Written() {
|
||||
@@ -1039,376 +764,6 @@ func Logs(ctx *context_module.Context) {
|
||||
}
|
||||
}
|
||||
|
||||
func Cancel(ctx *context_module.Context) {
|
||||
run, attempt, jobs := getCurrentRunJobsByPathParam(ctx)
|
||||
if ctx.Written() {
|
||||
return
|
||||
}
|
||||
if !checkLatestAttempt(ctx, run, attempt) {
|
||||
return
|
||||
}
|
||||
|
||||
if _, err := actions_service.CancelRun(ctx, run, jobs); err != nil {
|
||||
ctx.ServerErrorAuto(err)
|
||||
return
|
||||
}
|
||||
ctx.JSONOK()
|
||||
}
|
||||
|
||||
func Approve(ctx *context_module.Context) {
|
||||
run := getCurrentRunByPathParam(ctx)
|
||||
if ctx.Written() {
|
||||
return
|
||||
}
|
||||
if _, err := actions_service.ApproveRuns(ctx, ctx.Repo.Repository, ctx.Doer, []int64{run.ID}); err != nil {
|
||||
ctx.ServerErrorAuto(err)
|
||||
return
|
||||
}
|
||||
|
||||
ctx.JSONOK()
|
||||
}
|
||||
|
||||
func Delete(ctx *context_module.Context) {
|
||||
run := getCurrentRunByPathParam(ctx)
|
||||
if ctx.Written() {
|
||||
return
|
||||
}
|
||||
|
||||
if !run.Status.IsDone() {
|
||||
ctx.JSONError(ctx.Tr("actions.runs.not_done"))
|
||||
return
|
||||
}
|
||||
|
||||
if err := actions_service.DeleteRun(ctx, run); err != nil {
|
||||
ctx.ServerErrorAuto(err)
|
||||
return
|
||||
}
|
||||
|
||||
ctx.JSONOK()
|
||||
}
|
||||
|
||||
func getRunViewLink(run *actions_model.ActionRun, attempt *actions_model.ActionRunAttempt) string {
|
||||
if attempt == nil || run.LatestAttemptID == attempt.ID {
|
||||
return run.Link()
|
||||
}
|
||||
return fmt.Sprintf("%s/attempts/%d", run.Link(), attempt.Attempt)
|
||||
}
|
||||
|
||||
// getCurrentRunJobsByPathParam resolves the current run view context from path parameters, including the run, optional attempt, and jobs to render.
|
||||
// Any error will be written to the ctx, then the return values are all nil.
|
||||
func getCurrentRunJobsByPathParam(ctx *context_module.Context) (*actions_model.ActionRun, *actions_model.ActionRunAttempt, []*actions_model.ActionRunJob) {
|
||||
run := getCurrentRunByPathParam(ctx)
|
||||
if ctx.Written() {
|
||||
return nil, nil, nil
|
||||
}
|
||||
run.Repo = ctx.Repo.Repository
|
||||
|
||||
var err error
|
||||
var selectedJob *actions_model.ActionRunJob
|
||||
if ctx.PathParam("job") != "" {
|
||||
jobID := ctx.PathParamInt64("job")
|
||||
selectedJob, err = actions_model.GetRunJobByRunAndID(ctx, run.ID, jobID)
|
||||
if err != nil {
|
||||
ctx.ServerErrorAuto(err)
|
||||
return nil, nil, nil
|
||||
}
|
||||
}
|
||||
|
||||
// Resolve the attempt to display.
|
||||
// Priority: explicit path param (/attempts/:num) > job's attempt (when navigating to a specific job) > latest attempt.
|
||||
// attempt may be nil for legacy runs that pre-date ActionRunAttempt; callers must handle that case.
|
||||
attemptNum := ctx.PathParamInt64("attempt")
|
||||
var attempt *actions_model.ActionRunAttempt
|
||||
switch {
|
||||
case attemptNum > 0:
|
||||
// Explicit attempt number in the URL — user is viewing a historical attempt.
|
||||
attempt, err = actions_model.GetRunAttemptByRunIDAndAttemptNum(ctx, run.ID, attemptNum)
|
||||
if err != nil {
|
||||
ctx.ServerErrorAuto(err)
|
||||
return nil, nil, nil
|
||||
}
|
||||
case selectedJob != nil && selectedJob.RunAttemptID > 0:
|
||||
// No explicit attempt in the URL, but the requested job belongs to a known attempt — resolve via the job.
|
||||
attempt, err = actions_model.GetRunAttemptByRepoAndID(ctx, selectedJob.RepoID, selectedJob.RunAttemptID)
|
||||
if err != nil {
|
||||
ctx.ServerErrorAuto(err)
|
||||
return nil, nil, nil
|
||||
}
|
||||
default:
|
||||
// No attempt context at all — show the latest attempt (nil for legacy runs).
|
||||
attempt, _, err = run.GetLatestAttempt(ctx)
|
||||
if err != nil {
|
||||
ctx.ServerErrorAuto(err)
|
||||
return nil, nil, nil
|
||||
}
|
||||
}
|
||||
|
||||
// Resolve the jobs for the resolved attempt.
|
||||
// When attempt is nil (legacy run or legacy job), jobs are stored with run_attempt_id=0.
|
||||
var resolvedAttemptID int64
|
||||
if attempt != nil {
|
||||
resolvedAttemptID = attempt.ID
|
||||
}
|
||||
jobs, err := actions_model.GetRunJobsByRunAndAttemptID(ctx, run.ID, resolvedAttemptID)
|
||||
if err != nil {
|
||||
ctx.ServerErrorAuto(err)
|
||||
return nil, nil, nil
|
||||
}
|
||||
jobs.SortMatrixGroupsByName()
|
||||
|
||||
for _, job := range jobs {
|
||||
job.Run = run
|
||||
}
|
||||
return run, attempt, jobs
|
||||
}
|
||||
|
||||
// resolveArtifactAttemptIDFromQuery resolves the run_attempt_id used to scope artifact lookups.
|
||||
// If the `attempt` query parameter is present and valid, it returns the matching attempt's ID.
|
||||
// Otherwise it falls back to run.LatestAttemptID, which is 0 only for legacy runs created before ActionRunAttempt existed.
|
||||
func resolveArtifactAttemptIDFromQuery(ctx *context_module.Context, run *actions_model.ActionRun) (int64, error) {
|
||||
if ctx.FormString("attempt") == "" {
|
||||
return run.LatestAttemptID, nil
|
||||
}
|
||||
attemptNum := ctx.FormInt64("attempt")
|
||||
if attemptNum <= 0 {
|
||||
return 0, util.ErrNotExist
|
||||
}
|
||||
attempt, err := actions_model.GetRunAttemptByRunIDAndAttemptNum(ctx, run.ID, attemptNum)
|
||||
if err != nil {
|
||||
return 0, err
|
||||
}
|
||||
return attempt.ID, nil
|
||||
}
|
||||
|
||||
func ArtifactsDeleteView(ctx *context_module.Context) {
|
||||
run := getCurrentRunByPathParam(ctx)
|
||||
if ctx.Written() {
|
||||
return
|
||||
}
|
||||
resolvedAttemptID, err := resolveArtifactAttemptIDFromQuery(ctx, run)
|
||||
if err != nil {
|
||||
ctx.ServerErrorAuto(err)
|
||||
return
|
||||
}
|
||||
artifactName := ctx.PathParam("artifact_name")
|
||||
if err := actions_model.SetArtifactNeedDeleteByRunAttempt(ctx, run.ID, resolvedAttemptID, artifactName); err != nil {
|
||||
ctx.ServerErrorAuto(err)
|
||||
return
|
||||
}
|
||||
ctx.JSON(http.StatusOK, struct{}{})
|
||||
}
|
||||
|
||||
func ArtifactsDownloadView(ctx *context_module.Context) {
|
||||
run := getCurrentRunByPathParam(ctx)
|
||||
if ctx.Written() {
|
||||
return
|
||||
}
|
||||
resolvedAttemptID, err := resolveArtifactAttemptIDFromQuery(ctx, run)
|
||||
if err != nil {
|
||||
ctx.ServerErrorAuto(err)
|
||||
return
|
||||
}
|
||||
artifactName := ctx.PathParam("artifact_name")
|
||||
artifacts, err := actions_model.GetArtifactsByRunAttemptAndName(ctx, run.ID, resolvedAttemptID, artifactName)
|
||||
if err != nil {
|
||||
ctx.ServerErrorAuto(err)
|
||||
return
|
||||
}
|
||||
if len(artifacts) == 0 {
|
||||
ctx.HTTPError(http.StatusNotFound, "artifact not found")
|
||||
return
|
||||
}
|
||||
|
||||
// if artifacts status is not uploaded-confirmed, treat it as not found
|
||||
for _, art := range artifacts {
|
||||
if art.Status != actions_model.ArtifactStatusUploadConfirmed {
|
||||
ctx.HTTPError(http.StatusNotFound, "artifact not found")
|
||||
return
|
||||
}
|
||||
}
|
||||
|
||||
// A v4 Artifact may only contain a single file
|
||||
// Multiple files are uploaded as a single file archive
|
||||
// All other cases fall back to the legacy v1–v3 zip handling below
|
||||
if len(artifacts) == 1 && actions_service.IsArtifactV4(artifacts[0]) {
|
||||
err := actions_service.DownloadArtifactV4(ctx.Base, artifacts[0])
|
||||
if err != nil {
|
||||
ctx.ServerErrorAuto(err)
|
||||
return
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
// Artifacts using the v1-v3 backend are stored as multiple individual files per artifact on the backend
|
||||
// Those need to be zipped for download
|
||||
ctx.Resp.Header().Set("Content-Disposition", httplib.EncodeContentDispositionAttachment(artifactName+".zip"))
|
||||
zipWriter := zip.NewWriter(ctx.Resp)
|
||||
defer zipWriter.Close()
|
||||
|
||||
writeArtifactToZip := func(art *actions_model.ActionArtifact) error {
|
||||
f, err := storage.ActionsArtifacts.Open(art.StoragePath)
|
||||
if err != nil {
|
||||
return fmt.Errorf("ActionsArtifacts.Open: %w", err)
|
||||
}
|
||||
defer f.Close()
|
||||
|
||||
var r io.ReadCloser = f
|
||||
if art.ContentEncodingOrType == actions_model.ContentEncodingV3Gzip {
|
||||
r, err = gzip.NewReader(f)
|
||||
if err != nil {
|
||||
return fmt.Errorf("gzip.NewReader: %w", err)
|
||||
}
|
||||
}
|
||||
defer r.Close()
|
||||
|
||||
w, err := zipWriter.Create(art.ArtifactPath)
|
||||
if err != nil {
|
||||
return fmt.Errorf("zipWriter.Create: %w", err)
|
||||
}
|
||||
_, err = io.Copy(w, r)
|
||||
if err != nil {
|
||||
return fmt.Errorf("io.Copy: %w", err)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
for _, art := range artifacts {
|
||||
err := writeArtifactToZip(art)
|
||||
if err != nil {
|
||||
ctx.ServerErrorAuto(err)
|
||||
return
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func ApproveAllChecks(ctx *context_module.Context) {
|
||||
repo := ctx.Repo.Repository
|
||||
commitID := ctx.FormString("commit_id")
|
||||
|
||||
runs, err := actions_service.GetRunsFromCommitStatuses(ctx, repo.ID, commitID)
|
||||
if err != nil {
|
||||
ctx.ServerErrorAuto(err)
|
||||
return
|
||||
}
|
||||
|
||||
runIDs := make([]int64, 0, len(runs))
|
||||
for _, run := range runs {
|
||||
if run.IsAwaitingApproval() {
|
||||
runIDs = append(runIDs, run.ID)
|
||||
}
|
||||
}
|
||||
|
||||
if len(runIDs) == 0 {
|
||||
ctx.JSONOK()
|
||||
return
|
||||
}
|
||||
|
||||
if _, err := actions_service.ApproveRuns(ctx, repo, ctx.Doer, runIDs); err != nil {
|
||||
ctx.ServerErrorAuto(err)
|
||||
return
|
||||
}
|
||||
|
||||
ctx.Flash.Success(ctx.Tr("actions.approve_all_success"))
|
||||
ctx.JSONOK()
|
||||
}
|
||||
|
||||
func DisableWorkflowFile(ctx *context_module.Context) {
|
||||
disableOrEnableWorkflowFile(ctx, false)
|
||||
}
|
||||
|
||||
func EnableWorkflowFile(ctx *context_module.Context) {
|
||||
disableOrEnableWorkflowFile(ctx, true)
|
||||
}
|
||||
|
||||
func disableOrEnableWorkflowFile(ctx *context_module.Context, isEnable bool) {
|
||||
workflow := ctx.FormString("workflow")
|
||||
if len(workflow) == 0 {
|
||||
ctx.JSONError("workflow is required")
|
||||
return
|
||||
}
|
||||
|
||||
cfgUnit := ctx.Repo.Repository.MustGetUnit(ctx, unit.TypeActions)
|
||||
cfg := cfgUnit.ActionsConfig()
|
||||
|
||||
scopedRepoID := ctx.FormInt64("scoped_workflow_source_repo_id")
|
||||
if scopedRepoID > 0 {
|
||||
if !isEnable {
|
||||
// a required scoped workflow can never be opted out
|
||||
required, err := actions_model.IsScopedWorkflowRequired(ctx, ctx.Repo.Repository.OwnerID, scopedRepoID, workflow)
|
||||
if err != nil {
|
||||
ctx.ServerErrorAuto(err)
|
||||
return
|
||||
}
|
||||
if required {
|
||||
ctx.JSONError(ctx.Locale.Tr("actions.workflow.scoped_required_cannot_disable"))
|
||||
return
|
||||
}
|
||||
cfg.DisableScopedWorkflow(scopedRepoID, workflow)
|
||||
} else {
|
||||
cfg.EnableScopedWorkflow(scopedRepoID, workflow)
|
||||
}
|
||||
} else if isEnable {
|
||||
cfg.EnableWorkflow(workflow)
|
||||
} else {
|
||||
cfg.DisableWorkflow(workflow)
|
||||
}
|
||||
|
||||
if err := repo_model.UpdateRepoUnitConfig(ctx, cfgUnit); err != nil {
|
||||
ctx.ServerErrorAuto(err)
|
||||
return
|
||||
}
|
||||
actions_service.RecordWorkflowToggle(ctx, ctx.Repo.Repository, workflow, isEnable)
|
||||
|
||||
if isEnable {
|
||||
ctx.Flash.Success(ctx.Tr("actions.workflow.enable_success", workflow))
|
||||
} else {
|
||||
ctx.Flash.Success(ctx.Tr("actions.workflow.disable_success", workflow))
|
||||
}
|
||||
|
||||
redirectURL := actionsListRedirectURL(ctx.Repo.RepoLink, workflow, ctx.FormString("scoped_workflow_source_repo_id"),
|
||||
ctx.FormString("actor"), ctx.FormString("status"), ctx.FormString("branch"))
|
||||
ctx.JSONRedirect(redirectURL)
|
||||
}
|
||||
|
||||
func Run(ctx *context_module.Context) {
|
||||
redirectURL := actionsListRedirectURL(ctx.Repo.RepoLink, ctx.FormString("workflow"), ctx.FormString("scoped_workflow_source_repo_id"),
|
||||
ctx.FormString("actor"), ctx.FormString("status"), ctx.FormString("branch"))
|
||||
|
||||
workflowID := ctx.FormString("workflow")
|
||||
if len(workflowID) == 0 {
|
||||
ctx.ServerErrorAuto(errors.New("workflow"))
|
||||
return
|
||||
}
|
||||
|
||||
ref := ctx.FormString("ref")
|
||||
if len(ref) == 0 {
|
||||
ctx.ServerErrorAuto(errors.New("ref"))
|
||||
return
|
||||
}
|
||||
sourceRepoID := ctx.FormInt64("scoped_workflow_source_repo_id")
|
||||
_, err := actions_service.DispatchActionWorkflow(ctx, ctx.Doer, ctx.Repo.Repository, ctx.Repo.GitRepo, workflowID, ref, sourceRepoID, func(workflowDispatch *model.WorkflowDispatch, inputs map[string]any) error {
|
||||
for name, config := range workflowDispatch.Inputs {
|
||||
value := ctx.Req.PostFormValue(name)
|
||||
if config.Type == "boolean" {
|
||||
inputs[name] = strconv.FormatBool(ctx.FormBool(name))
|
||||
} else if value != "" {
|
||||
inputs[name] = value
|
||||
} else {
|
||||
inputs[name] = config.Default
|
||||
}
|
||||
}
|
||||
return nil
|
||||
})
|
||||
if err != nil {
|
||||
ctx.FlashErrorAuto(err)
|
||||
ctx.Redirect(redirectURL)
|
||||
return
|
||||
}
|
||||
|
||||
ctx.Flash.Success(ctx.Tr("actions.workflow.run_success", workflowID))
|
||||
ctx.Redirect(redirectURL)
|
||||
}
|
||||
|
||||
// viewScopedWorkflowFile redirects to the scoped workflow file in its SOURCE repo.
|
||||
func viewScopedWorkflowFile(ctx *context_module.Context, run *actions_model.ActionRun) {
|
||||
sourceRepo, err := repo_model.GetRepositoryByID(ctx, run.WorkflowRepoID)
|
||||
|
||||
@@ -482,3 +482,122 @@ func serveArtifactPreviewRaw(ctx *context_module.Base, artifactID int64, filePat
|
||||
ServeArtifactPreviewContent(ctx, filePath, reader, artifact.FileSize)
|
||||
return nil
|
||||
}
|
||||
|
||||
// resolveArtifactAttemptIDFromQuery resolves the run_attempt_id used to scope artifact lookups.
|
||||
// If the `attempt` query parameter is present and valid, it returns the matching attempt's ID.
|
||||
// Otherwise it falls back to run.LatestAttemptID, which is 0 only for legacy runs created before ActionRunAttempt existed.
|
||||
func resolveArtifactAttemptIDFromQuery(ctx *context_module.Context, run *actions_model.ActionRun) (int64, error) {
|
||||
if ctx.FormString("attempt") == "" {
|
||||
return run.LatestAttemptID, nil
|
||||
}
|
||||
attemptNum := ctx.FormInt64("attempt")
|
||||
if attemptNum <= 0 {
|
||||
return 0, util.ErrNotExist
|
||||
}
|
||||
attempt, err := actions_model.GetRunAttemptByRunIDAndAttemptNum(ctx, run.ID, attemptNum)
|
||||
if err != nil {
|
||||
return 0, err
|
||||
}
|
||||
return attempt.ID, nil
|
||||
}
|
||||
|
||||
func ArtifactsDeleteView(ctx *context_module.Context) {
|
||||
run := getCurrentRunByPathParam(ctx)
|
||||
if ctx.Written() {
|
||||
return
|
||||
}
|
||||
resolvedAttemptID, err := resolveArtifactAttemptIDFromQuery(ctx, run)
|
||||
if err != nil {
|
||||
ctx.ServerErrorAuto(err)
|
||||
return
|
||||
}
|
||||
artifactName := ctx.PathParam("artifact_name")
|
||||
if err := actions_model.SetArtifactNeedDeleteByRunAttempt(ctx, run.ID, resolvedAttemptID, artifactName); err != nil {
|
||||
ctx.ServerErrorAuto(err)
|
||||
return
|
||||
}
|
||||
ctx.JSON(http.StatusOK, struct{}{})
|
||||
}
|
||||
|
||||
func ArtifactsDownloadView(ctx *context_module.Context) {
|
||||
run := getCurrentRunByPathParam(ctx)
|
||||
if ctx.Written() {
|
||||
return
|
||||
}
|
||||
resolvedAttemptID, err := resolveArtifactAttemptIDFromQuery(ctx, run)
|
||||
if err != nil {
|
||||
ctx.ServerErrorAuto(err)
|
||||
return
|
||||
}
|
||||
artifactName := ctx.PathParam("artifact_name")
|
||||
artifacts, err := actions_model.GetArtifactsByRunAttemptAndName(ctx, run.ID, resolvedAttemptID, artifactName)
|
||||
if err != nil {
|
||||
ctx.ServerErrorAuto(err)
|
||||
return
|
||||
}
|
||||
if len(artifacts) == 0 {
|
||||
ctx.HTTPError(http.StatusNotFound, "artifact not found")
|
||||
return
|
||||
}
|
||||
|
||||
// if artifacts status is not uploaded-confirmed, treat it as not found
|
||||
for _, art := range artifacts {
|
||||
if art.Status != actions_model.ArtifactStatusUploadConfirmed {
|
||||
ctx.HTTPError(http.StatusNotFound, "artifact not found")
|
||||
return
|
||||
}
|
||||
}
|
||||
|
||||
// A v4 Artifact may only contain a single file
|
||||
// Multiple files are uploaded as a single file archive
|
||||
// All other cases fall back to the legacy v1–v3 zip handling below
|
||||
if len(artifacts) == 1 && actions_service.IsArtifactV4(artifacts[0]) {
|
||||
err := actions_service.DownloadArtifactV4(ctx.Base, artifacts[0])
|
||||
if err != nil {
|
||||
ctx.ServerErrorAuto(err)
|
||||
return
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
// Artifacts using the v1-v3 backend are stored as multiple individual files per artifact on the backend
|
||||
// Those need to be zipped for download
|
||||
ctx.Resp.Header().Set("Content-Disposition", httplib.EncodeContentDispositionAttachment(artifactName+".zip"))
|
||||
zipWriter := zip.NewWriter(ctx.Resp)
|
||||
defer zipWriter.Close()
|
||||
|
||||
writeArtifactToZip := func(art *actions_model.ActionArtifact) error {
|
||||
f, err := storage.ActionsArtifacts.Open(art.StoragePath)
|
||||
if err != nil {
|
||||
return fmt.Errorf("ActionsArtifacts.Open: %w", err)
|
||||
}
|
||||
defer f.Close()
|
||||
|
||||
var r io.ReadCloser = f
|
||||
if art.ContentEncodingOrType == actions_model.ContentEncodingV3Gzip {
|
||||
r, err = gzip.NewReader(f)
|
||||
if err != nil {
|
||||
return fmt.Errorf("gzip.NewReader: %w", err)
|
||||
}
|
||||
}
|
||||
defer r.Close()
|
||||
|
||||
w, err := zipWriter.Create(art.ArtifactPath)
|
||||
if err != nil {
|
||||
return fmt.Errorf("zipWriter.Create: %w", err)
|
||||
}
|
||||
_, err = io.Copy(w, r)
|
||||
if err != nil {
|
||||
return fmt.Errorf("io.Copy: %w", err)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
for _, art := range artifacts {
|
||||
err := writeArtifactToZip(art)
|
||||
if err != nil {
|
||||
ctx.ServerErrorAuto(err)
|
||||
return
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,205 @@
|
||||
// Copyright 2026 The Gitea Authors. All rights reserved.
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
package actions
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"net/http"
|
||||
|
||||
actions_model "gitea.dev/models/actions"
|
||||
"gitea.dev/models/unit"
|
||||
"gitea.dev/modules/util"
|
||||
actions_service "gitea.dev/services/actions"
|
||||
context_module "gitea.dev/services/context"
|
||||
)
|
||||
|
||||
// checkRunRerunAllowed checks whether a rerun is permitted for the given run,
|
||||
// writing the appropriate JSON error to ctx and returning false when it is not.
|
||||
func checkRunRerunAllowed(ctx *context_module.Context, run *actions_model.ActionRun) bool {
|
||||
if !run.Status.IsDone() {
|
||||
ctx.JSONError(ctx.Locale.Tr("actions.runs.not_done"))
|
||||
return false
|
||||
}
|
||||
cfgUnit := ctx.Repo.Repository.MustGetUnit(ctx, unit.TypeActions)
|
||||
cfg := cfgUnit.ActionsConfig()
|
||||
disabled := cfg.IsWorkflowDisabled(run.WorkflowID)
|
||||
if run.IsScopedRun {
|
||||
optedOut, err := actions_model.IsScopedWorkflowOptedOut(ctx, cfg, ctx.Repo.Repository.OwnerID, run.WorkflowRepoID, run.WorkflowID)
|
||||
if err != nil {
|
||||
ctx.ServerErrorAuto(err)
|
||||
return false
|
||||
}
|
||||
disabled = optedOut
|
||||
}
|
||||
if disabled {
|
||||
ctx.JSONError(ctx.Locale.Tr("actions.workflow.disabled"))
|
||||
return false
|
||||
}
|
||||
return true
|
||||
}
|
||||
|
||||
func checkLatestAttempt(ctx *context_module.Context, run *actions_model.ActionRun, attempt *actions_model.ActionRunAttempt) bool {
|
||||
if attempt != nil && run.LatestAttemptID != attempt.ID {
|
||||
ctx.NotFound()
|
||||
return false
|
||||
}
|
||||
return true
|
||||
}
|
||||
|
||||
// Rerun will rerun jobs in the given run
|
||||
// If jobIDStr is a blank string, it means rerun all jobs
|
||||
func Rerun(ctx *context_module.Context) {
|
||||
run, attempt, jobs := getCurrentRunJobsByPathParam(ctx)
|
||||
if ctx.Written() {
|
||||
return
|
||||
}
|
||||
if !checkLatestAttempt(ctx, run, attempt) {
|
||||
return
|
||||
}
|
||||
if !checkRunRerunAllowed(ctx, run) {
|
||||
return
|
||||
}
|
||||
if len(jobs) == 0 {
|
||||
ctx.JSONError(ctx.Locale.Tr("actions.runs.no_job"))
|
||||
return
|
||||
}
|
||||
|
||||
currentJob, hasPathParam := findCurrentJobByPathParam(ctx, jobs)
|
||||
if hasPathParam && currentJob == nil {
|
||||
ctx.NotFound()
|
||||
return
|
||||
}
|
||||
|
||||
var jobsToRerun []*actions_model.ActionRunJob
|
||||
if currentJob != nil {
|
||||
jobsToRerun = []*actions_model.ActionRunJob{currentJob}
|
||||
}
|
||||
|
||||
if _, err := actions_service.RerunWorkflowRunJobs(ctx, ctx.Repo.Repository, run, ctx.Doer, jobsToRerun); err != nil {
|
||||
handleWorkflowRerunError(ctx, err)
|
||||
return
|
||||
}
|
||||
|
||||
ctx.JSONRedirect(run.Link())
|
||||
}
|
||||
|
||||
// RerunFailed reruns all failed jobs in the given run
|
||||
func RerunFailed(ctx *context_module.Context) {
|
||||
run, attempt, jobs := getCurrentRunJobsByPathParam(ctx)
|
||||
if ctx.Written() {
|
||||
return
|
||||
}
|
||||
if !checkLatestAttempt(ctx, run, attempt) {
|
||||
return
|
||||
}
|
||||
if !checkRunRerunAllowed(ctx, run) {
|
||||
return
|
||||
}
|
||||
|
||||
// An empty job list means "re-run the whole run" to RerunWorkflowRunJobs, which is right for the plain
|
||||
// rerun button but wrong here, so a direct POST on a fully successful run cannot re-run everything.
|
||||
failedJobs := actions_service.GetFailedJobsForRerun(jobs)
|
||||
if len(failedJobs) == 0 {
|
||||
ctx.JSONError(ctx.Locale.Tr("actions.runs.no_failed_jobs"))
|
||||
return
|
||||
}
|
||||
|
||||
if _, err := actions_service.RerunWorkflowRunJobs(ctx, ctx.Repo.Repository, run, ctx.Doer, failedJobs); err != nil {
|
||||
handleWorkflowRerunError(ctx, err)
|
||||
return
|
||||
}
|
||||
|
||||
ctx.JSONRedirect(run.Link())
|
||||
}
|
||||
|
||||
func handleWorkflowRerunError(ctx *context_module.Context, err error) {
|
||||
if errors.Is(err, util.ErrAlreadyExist) {
|
||||
ctx.JSON(http.StatusConflict, map[string]any{"message": err.Error()})
|
||||
return
|
||||
}
|
||||
if errors.Is(err, util.ErrInvalidArgument) {
|
||||
ctx.JSON(http.StatusBadRequest, map[string]any{"message": err.Error()})
|
||||
return
|
||||
}
|
||||
ctx.ServerErrorAuto(err)
|
||||
}
|
||||
|
||||
func Cancel(ctx *context_module.Context) {
|
||||
run, attempt, jobs := getCurrentRunJobsByPathParam(ctx)
|
||||
if ctx.Written() {
|
||||
return
|
||||
}
|
||||
if !checkLatestAttempt(ctx, run, attempt) {
|
||||
return
|
||||
}
|
||||
|
||||
if _, err := actions_service.CancelRun(ctx, run, jobs); err != nil {
|
||||
ctx.ServerErrorAuto(err)
|
||||
return
|
||||
}
|
||||
ctx.JSONOK()
|
||||
}
|
||||
|
||||
func Approve(ctx *context_module.Context) {
|
||||
run := getCurrentRunByPathParam(ctx)
|
||||
if ctx.Written() {
|
||||
return
|
||||
}
|
||||
if _, err := actions_service.ApproveRuns(ctx, ctx.Repo.Repository, ctx.Doer, []int64{run.ID}); err != nil {
|
||||
ctx.ServerErrorAuto(err)
|
||||
return
|
||||
}
|
||||
|
||||
ctx.JSONOK()
|
||||
}
|
||||
|
||||
func Delete(ctx *context_module.Context) {
|
||||
run := getCurrentRunByPathParam(ctx)
|
||||
if ctx.Written() {
|
||||
return
|
||||
}
|
||||
|
||||
if !run.Status.IsDone() {
|
||||
ctx.JSONError(ctx.Tr("actions.runs.not_done"))
|
||||
return
|
||||
}
|
||||
|
||||
if err := actions_service.DeleteRun(ctx, run); err != nil {
|
||||
ctx.ServerErrorAuto(err)
|
||||
return
|
||||
}
|
||||
|
||||
ctx.JSONOK()
|
||||
}
|
||||
|
||||
func ApproveAllChecks(ctx *context_module.Context) {
|
||||
repo := ctx.Repo.Repository
|
||||
commitID := ctx.FormString("commit_id")
|
||||
|
||||
runs, err := actions_service.GetRunsFromCommitStatuses(ctx, repo.ID, commitID)
|
||||
if err != nil {
|
||||
ctx.ServerErrorAuto(err)
|
||||
return
|
||||
}
|
||||
|
||||
runIDs := make([]int64, 0, len(runs))
|
||||
for _, run := range runs {
|
||||
if run.IsAwaitingApproval() {
|
||||
runIDs = append(runIDs, run.ID)
|
||||
}
|
||||
}
|
||||
|
||||
if len(runIDs) == 0 {
|
||||
ctx.JSONOK()
|
||||
return
|
||||
}
|
||||
|
||||
if _, err := actions_service.ApproveRuns(ctx, repo, ctx.Doer, runIDs); err != nil {
|
||||
ctx.ServerErrorAuto(err)
|
||||
return
|
||||
}
|
||||
|
||||
ctx.Flash.Success(ctx.Tr("actions.approve_all_success"))
|
||||
ctx.JSONOK()
|
||||
}
|
||||
@@ -0,0 +1,244 @@
|
||||
// Copyright 2026 The Gitea Authors. All rights reserved.
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
package actions
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"fmt"
|
||||
"net/http"
|
||||
|
||||
actions_model "gitea.dev/models/actions"
|
||||
"gitea.dev/modules/util"
|
||||
context_module "gitea.dev/services/context"
|
||||
)
|
||||
|
||||
func findCurrentJobByPathParam(ctx *context_module.Context, jobs []*actions_model.ActionRunJob) (job *actions_model.ActionRunJob, hasPathParam bool) {
|
||||
selectedJobID := ctx.PathParamInt64("job")
|
||||
if selectedJobID <= 0 {
|
||||
return nil, false
|
||||
}
|
||||
for _, job = range jobs {
|
||||
if job.ID == selectedJobID {
|
||||
return job, true
|
||||
}
|
||||
}
|
||||
return nil, true
|
||||
}
|
||||
|
||||
func getCurrentRunByPathParam(ctx *context_module.Context) (run *actions_model.ActionRun) {
|
||||
var err error
|
||||
// if run param is "latest", get the latest run id
|
||||
if ctx.PathParam("run") == "latest" {
|
||||
run, err = actions_model.GetLatestRun(ctx, ctx.Repo.Repository.ID)
|
||||
} else {
|
||||
run, err = actions_model.GetRunByRepoAndID(ctx, ctx.Repo.Repository.ID, ctx.PathParamInt64("run"))
|
||||
}
|
||||
if err != nil {
|
||||
ctx.ServerErrorAuto(err)
|
||||
}
|
||||
return run
|
||||
}
|
||||
|
||||
// resolveCurrentRunForView resolves GET Actions page URLs and supports both ID-based and legacy index-based forms.
|
||||
//
|
||||
// By default, run summary pages (/actions/runs/{run}) use a best-effort ID-first fallback,
|
||||
// and job pages (/actions/runs/{run}/jobs/{job}) try to confirm an ID-based URL first and prefer the ID-based interpretation when both are valid.
|
||||
//
|
||||
// `by_id=1` param explicitly forces the ID-based path, and `by_index=1` explicitly forces the legacy index-based path.
|
||||
// If both are present, `by_id` takes precedence.
|
||||
func resolveCurrentRunForView(ctx *context_module.Context) *actions_model.ActionRun {
|
||||
// `by_id` explicitly requests ID-based resolution, so the request skips the legacy index-based disambiguation logic and resolves the run by ID directly.
|
||||
// It takes precedence over `by_index` when both query parameters are present.
|
||||
if ctx.PathParam("run") == "latest" || ctx.FormBool("by_id") {
|
||||
return getCurrentRunByPathParam(ctx)
|
||||
}
|
||||
|
||||
runNum := ctx.PathParamInt64("run")
|
||||
if runNum <= 0 {
|
||||
ctx.NotFound()
|
||||
return nil
|
||||
}
|
||||
|
||||
byIndex := ctx.FormBool("by_index")
|
||||
|
||||
if ctx.PathParam("job") == "" {
|
||||
// The URL does not contain a {job} path parameter, so it cannot use the
|
||||
// job-specific rules to disambiguate ID-based URLs from legacy index-based URLs.
|
||||
// Because of that, this path is handled with a best-effort ID-first fallback by default.
|
||||
//
|
||||
// When the same repository contains:
|
||||
// - a run whose ID matches runNum, and
|
||||
// - a different run whose repo-scope index also matches runNum
|
||||
// this path prefers the ID match and may show a different run than the old legacy URL originally intended,
|
||||
// unless `by_index=1` explicitly forces the legacy index-based interpretation.
|
||||
|
||||
if !byIndex {
|
||||
runByID, err := actions_model.GetRunByRepoAndID(ctx, ctx.Repo.Repository.ID, runNum)
|
||||
if err == nil {
|
||||
return runByID
|
||||
}
|
||||
if !errors.Is(err, util.ErrNotExist) {
|
||||
ctx.ServerErrorAuto(err)
|
||||
return nil
|
||||
}
|
||||
}
|
||||
|
||||
runByIndex, err := actions_model.GetRunByRepoAndIndex(ctx, ctx.Repo.Repository.ID, runNum)
|
||||
if err == nil {
|
||||
ctx.Redirect(fmt.Sprintf("%s/actions/runs/%d", ctx.Repo.RepoLink, runByIndex.ID), http.StatusFound)
|
||||
return nil
|
||||
}
|
||||
if !errors.Is(err, util.ErrNotExist) {
|
||||
ctx.ServerErrorAuto(err)
|
||||
return nil
|
||||
}
|
||||
ctx.NotFound()
|
||||
return nil
|
||||
}
|
||||
|
||||
jobNum := ctx.PathParamInt64("job")
|
||||
if jobNum < 0 {
|
||||
ctx.NotFound()
|
||||
return nil
|
||||
}
|
||||
|
||||
// A job index should not be larger than MaxJobNumPerRun, so larger values can skip the legacy index-based path and be treated as job IDs directly.
|
||||
if !byIndex && jobNum >= actions_model.MaxJobNumPerRun {
|
||||
return getCurrentRunByPathParam(ctx)
|
||||
}
|
||||
|
||||
var runByID, runByIndex *actions_model.ActionRun
|
||||
var targetJobByIndex *actions_model.ActionRunJob
|
||||
|
||||
if !byIndex {
|
||||
// Probe the repo-scoped job ID first and only accept it when the job exists and belongs to the same runNum.
|
||||
job, err := actions_model.GetRunJobByRepoAndID(ctx, ctx.Repo.Repository.ID, jobNum)
|
||||
if err != nil && !errors.Is(err, util.ErrNotExist) {
|
||||
ctx.ServerErrorAuto(err)
|
||||
return nil
|
||||
}
|
||||
if job != nil {
|
||||
if err := job.LoadRun(ctx); err != nil {
|
||||
ctx.ServerErrorAuto(err)
|
||||
return nil
|
||||
}
|
||||
if job.Run.ID == runNum {
|
||||
runByID = job.Run
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Try to resolve the request as a legacy run-index/job-index URL.
|
||||
{
|
||||
run, err := actions_model.GetRunByRepoAndIndex(ctx, ctx.Repo.Repository.ID, runNum)
|
||||
if err != nil && !errors.Is(err, util.ErrNotExist) {
|
||||
ctx.ServerErrorAuto(err)
|
||||
return nil
|
||||
}
|
||||
if run != nil {
|
||||
jobs, err := actions_model.GetLatestAttemptJobsByRepoAndRunID(ctx, run.RepoID, run.ID)
|
||||
if err != nil {
|
||||
ctx.ServerErrorAuto(err)
|
||||
return nil
|
||||
}
|
||||
if jobNum < int64(len(jobs)) {
|
||||
runByIndex = run
|
||||
targetJobByIndex = jobs[jobNum]
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if runByID == nil && runByIndex == nil {
|
||||
ctx.NotFound()
|
||||
return nil
|
||||
}
|
||||
|
||||
if runByID != nil && runByIndex == nil {
|
||||
return runByID
|
||||
}
|
||||
|
||||
if runByID == nil && runByIndex != nil {
|
||||
ctx.Redirect(fmt.Sprintf("%s/actions/runs/%d/jobs/%d", ctx.Repo.RepoLink, runByIndex.ID, targetJobByIndex.ID), http.StatusFound)
|
||||
return nil
|
||||
}
|
||||
|
||||
// Reaching this point means both ID-based and legacy index-based interpretations are valid. Prefer the ID-based interpretation by default.
|
||||
// Use `by_index=1` query parameter to access the legacy index-based interpretation when necessary.
|
||||
return runByID
|
||||
}
|
||||
|
||||
func getRunViewLink(run *actions_model.ActionRun, attempt *actions_model.ActionRunAttempt) string {
|
||||
if attempt == nil || run.LatestAttemptID == attempt.ID {
|
||||
return run.Link()
|
||||
}
|
||||
return fmt.Sprintf("%s/attempts/%d", run.Link(), attempt.Attempt)
|
||||
}
|
||||
|
||||
// getCurrentRunJobsByPathParam resolves the current run view context from path parameters, including the run, optional attempt, and jobs to render.
|
||||
// Any error will be written to the ctx, then the return values are all nil.
|
||||
func getCurrentRunJobsByPathParam(ctx *context_module.Context) (*actions_model.ActionRun, *actions_model.ActionRunAttempt, []*actions_model.ActionRunJob) {
|
||||
run := getCurrentRunByPathParam(ctx)
|
||||
if ctx.Written() {
|
||||
return nil, nil, nil
|
||||
}
|
||||
run.Repo = ctx.Repo.Repository
|
||||
|
||||
var err error
|
||||
var selectedJob *actions_model.ActionRunJob
|
||||
if ctx.PathParam("job") != "" {
|
||||
jobID := ctx.PathParamInt64("job")
|
||||
selectedJob, err = actions_model.GetRunJobByRunAndID(ctx, run.ID, jobID)
|
||||
if err != nil {
|
||||
ctx.ServerErrorAuto(err)
|
||||
return nil, nil, nil
|
||||
}
|
||||
}
|
||||
|
||||
// Resolve the attempt to display.
|
||||
// Priority: explicit path param (/attempts/:num) > job's attempt (when navigating to a specific job) > latest attempt.
|
||||
// attempt may be nil for legacy runs that pre-date ActionRunAttempt; callers must handle that case.
|
||||
attemptNum := ctx.PathParamInt64("attempt")
|
||||
var attempt *actions_model.ActionRunAttempt
|
||||
switch {
|
||||
case attemptNum > 0:
|
||||
// Explicit attempt number in the URL — user is viewing a historical attempt.
|
||||
attempt, err = actions_model.GetRunAttemptByRunIDAndAttemptNum(ctx, run.ID, attemptNum)
|
||||
if err != nil {
|
||||
ctx.ServerErrorAuto(err)
|
||||
return nil, nil, nil
|
||||
}
|
||||
case selectedJob != nil && selectedJob.RunAttemptID > 0:
|
||||
// No explicit attempt in the URL, but the requested job belongs to a known attempt — resolve via the job.
|
||||
attempt, err = actions_model.GetRunAttemptByRepoAndID(ctx, selectedJob.RepoID, selectedJob.RunAttemptID)
|
||||
if err != nil {
|
||||
ctx.ServerErrorAuto(err)
|
||||
return nil, nil, nil
|
||||
}
|
||||
default:
|
||||
// No attempt context at all — show the latest attempt (nil for legacy runs).
|
||||
attempt, _, err = run.GetLatestAttempt(ctx)
|
||||
if err != nil {
|
||||
ctx.ServerErrorAuto(err)
|
||||
return nil, nil, nil
|
||||
}
|
||||
}
|
||||
|
||||
// Resolve the jobs for the resolved attempt.
|
||||
// When attempt is nil (legacy run or legacy job), jobs are stored with run_attempt_id=0.
|
||||
var resolvedAttemptID int64
|
||||
if attempt != nil {
|
||||
resolvedAttemptID = attempt.ID
|
||||
}
|
||||
jobs, err := actions_model.GetRunJobsByRunAndAttemptID(ctx, run.ID, resolvedAttemptID)
|
||||
if err != nil {
|
||||
ctx.ServerErrorAuto(err)
|
||||
return nil, nil, nil
|
||||
}
|
||||
jobs.SortMatrixGroupsByName()
|
||||
|
||||
for _, job := range jobs {
|
||||
job.Run = run
|
||||
}
|
||||
return run, attempt, jobs
|
||||
}
|
||||
@@ -0,0 +1,113 @@
|
||||
// Copyright 2026 The Gitea Authors. All rights reserved.
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
package actions
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"strconv"
|
||||
|
||||
"gitea.dev/actionslib/pkg/model"
|
||||
actions_model "gitea.dev/models/actions"
|
||||
repo_model "gitea.dev/models/repo"
|
||||
"gitea.dev/models/unit"
|
||||
actions_service "gitea.dev/services/actions"
|
||||
context_module "gitea.dev/services/context"
|
||||
)
|
||||
|
||||
func DisableWorkflowFile(ctx *context_module.Context) {
|
||||
disableOrEnableWorkflowFile(ctx, false)
|
||||
}
|
||||
|
||||
func EnableWorkflowFile(ctx *context_module.Context) {
|
||||
disableOrEnableWorkflowFile(ctx, true)
|
||||
}
|
||||
|
||||
func disableOrEnableWorkflowFile(ctx *context_module.Context, isEnable bool) {
|
||||
workflow := ctx.FormString("workflow")
|
||||
if len(workflow) == 0 {
|
||||
ctx.JSONError("workflow is required")
|
||||
return
|
||||
}
|
||||
|
||||
cfgUnit := ctx.Repo.Repository.MustGetUnit(ctx, unit.TypeActions)
|
||||
cfg := cfgUnit.ActionsConfig()
|
||||
|
||||
scopedRepoID := ctx.FormInt64("scoped_workflow_source_repo_id")
|
||||
if scopedRepoID > 0 {
|
||||
if !isEnable {
|
||||
// a required scoped workflow can never be opted out
|
||||
required, err := actions_model.IsScopedWorkflowRequired(ctx, ctx.Repo.Repository.OwnerID, scopedRepoID, workflow)
|
||||
if err != nil {
|
||||
ctx.ServerErrorAuto(err)
|
||||
return
|
||||
}
|
||||
if required {
|
||||
ctx.JSONError(ctx.Locale.Tr("actions.workflow.scoped_required_cannot_disable"))
|
||||
return
|
||||
}
|
||||
cfg.DisableScopedWorkflow(scopedRepoID, workflow)
|
||||
} else {
|
||||
cfg.EnableScopedWorkflow(scopedRepoID, workflow)
|
||||
}
|
||||
} else if isEnable {
|
||||
cfg.EnableWorkflow(workflow)
|
||||
} else {
|
||||
cfg.DisableWorkflow(workflow)
|
||||
}
|
||||
|
||||
if err := repo_model.UpdateRepoUnitConfig(ctx, cfgUnit); err != nil {
|
||||
ctx.ServerErrorAuto(err)
|
||||
return
|
||||
}
|
||||
actions_service.RecordWorkflowToggle(ctx, ctx.Repo.Repository, workflow, isEnable)
|
||||
|
||||
if isEnable {
|
||||
ctx.Flash.Success(ctx.Tr("actions.workflow.enable_success", workflow))
|
||||
} else {
|
||||
ctx.Flash.Success(ctx.Tr("actions.workflow.disable_success", workflow))
|
||||
}
|
||||
|
||||
redirectURL := actionsListRedirectURL(ctx.Repo.RepoLink, workflow, ctx.FormString("scoped_workflow_source_repo_id"),
|
||||
ctx.FormString("actor"), ctx.FormString("status"), ctx.FormString("branch"))
|
||||
ctx.JSONRedirect(redirectURL)
|
||||
}
|
||||
|
||||
func Run(ctx *context_module.Context) {
|
||||
redirectURL := actionsListRedirectURL(ctx.Repo.RepoLink, ctx.FormString("workflow"), ctx.FormString("scoped_workflow_source_repo_id"),
|
||||
ctx.FormString("actor"), ctx.FormString("status"), ctx.FormString("branch"))
|
||||
|
||||
workflowID := ctx.FormString("workflow")
|
||||
if len(workflowID) == 0 {
|
||||
ctx.ServerErrorAuto(errors.New("workflow"))
|
||||
return
|
||||
}
|
||||
|
||||
ref := ctx.FormString("ref")
|
||||
if len(ref) == 0 {
|
||||
ctx.ServerErrorAuto(errors.New("ref"))
|
||||
return
|
||||
}
|
||||
sourceRepoID := ctx.FormInt64("scoped_workflow_source_repo_id")
|
||||
_, err := actions_service.DispatchActionWorkflow(ctx, ctx.Doer, ctx.Repo.Repository, ctx.Repo.GitRepo, workflowID, ref, sourceRepoID, func(workflowDispatch *model.WorkflowDispatch, inputs map[string]any) error {
|
||||
for name, config := range workflowDispatch.Inputs {
|
||||
value := ctx.Req.PostFormValue(name)
|
||||
if config.Type == "boolean" {
|
||||
inputs[name] = strconv.FormatBool(ctx.FormBool(name))
|
||||
} else if value != "" {
|
||||
inputs[name] = value
|
||||
} else {
|
||||
inputs[name] = config.Default
|
||||
}
|
||||
}
|
||||
return nil
|
||||
})
|
||||
if err != nil {
|
||||
ctx.FlashErrorAuto(err)
|
||||
ctx.Redirect(redirectURL)
|
||||
return
|
||||
}
|
||||
|
||||
ctx.Flash.Success(ctx.Tr("actions.workflow.run_success", workflowID))
|
||||
ctx.Redirect(redirectURL)
|
||||
}
|
||||
@@ -1,132 +0,0 @@
|
||||
// Copyright 2022 The Gitea Authors. All rights reserved.
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
package setting
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"net/http"
|
||||
|
||||
actions_model "gitea.dev/models/actions"
|
||||
repo_model "gitea.dev/models/repo"
|
||||
user_model "gitea.dev/models/user"
|
||||
"gitea.dev/modules/setting"
|
||||
"gitea.dev/modules/templates"
|
||||
shared "gitea.dev/routers/web/shared/secrets"
|
||||
shared_user "gitea.dev/routers/web/shared/user"
|
||||
"gitea.dev/services/context"
|
||||
)
|
||||
|
||||
const (
|
||||
// TODO: Separate secrets from runners when layout is ready
|
||||
tplRepoSecrets templates.TplName = "repo/settings/actions"
|
||||
tplOrgSecrets templates.TplName = "org/settings/actions"
|
||||
tplUserSecrets templates.TplName = "user/settings/actions"
|
||||
)
|
||||
|
||||
type secretsCtx struct {
|
||||
Owner *user_model.User
|
||||
Repo *repo_model.Repository
|
||||
BelongingScope actions_model.BelongingScope
|
||||
IsRepo bool
|
||||
IsOrg bool
|
||||
IsUser bool
|
||||
SecretsTemplate templates.TplName
|
||||
RedirectLink string
|
||||
}
|
||||
|
||||
func getSecretsCtx(ctx *context.Context) (*secretsCtx, error) {
|
||||
if ctx.Data["PageIsRepoSettings"] == true {
|
||||
return &secretsCtx{
|
||||
Repo: ctx.Repo.Repository,
|
||||
BelongingScope: actions_model.BelongingScopeRepo(ctx.Repo.Repository.ID),
|
||||
IsRepo: true,
|
||||
SecretsTemplate: tplRepoSecrets,
|
||||
RedirectLink: ctx.Repo.RepoLink + "/settings/actions/secrets",
|
||||
}, nil
|
||||
}
|
||||
|
||||
if ctx.Data["PageIsOrgSettings"] == true {
|
||||
if _, err := shared_user.RenderUserOrgHeader(ctx); err != nil {
|
||||
ctx.ServerErrorAuto(err)
|
||||
return nil, nil //nolint:nilnil // error is already handled by ctx.ServerError
|
||||
}
|
||||
return &secretsCtx{
|
||||
Owner: ctx.ContextUser,
|
||||
BelongingScope: actions_model.BelongingScopeOwner(ctx.ContextUser.ID),
|
||||
IsOrg: true,
|
||||
SecretsTemplate: tplOrgSecrets,
|
||||
RedirectLink: ctx.Org.OrgLink + "/settings/actions/secrets",
|
||||
}, nil
|
||||
}
|
||||
|
||||
if ctx.Data["PageIsUserSettings"] == true {
|
||||
return &secretsCtx{
|
||||
Owner: ctx.Doer,
|
||||
BelongingScope: actions_model.BelongingScopeOwner(ctx.Doer.ID),
|
||||
IsUser: true,
|
||||
SecretsTemplate: tplUserSecrets,
|
||||
RedirectLink: setting.AppSubURL + "/user/settings/actions/secrets",
|
||||
}, nil
|
||||
}
|
||||
|
||||
return nil, errors.New("unable to set Secrets context")
|
||||
}
|
||||
|
||||
func Secrets(ctx *context.Context) {
|
||||
ctx.Data["Title"] = ctx.Tr("secrets.secrets")
|
||||
ctx.Data["PageType"] = "secrets"
|
||||
ctx.Data["PageIsSharedSettingsSecrets"] = true
|
||||
|
||||
sCtx, err := getSecretsCtx(ctx)
|
||||
if err != nil {
|
||||
ctx.ServerErrorAuto(err)
|
||||
return
|
||||
}
|
||||
|
||||
if sCtx.IsRepo {
|
||||
ctx.Data["DisableSSH"] = setting.SSH.Disabled
|
||||
}
|
||||
|
||||
shared.SetSecretsContext(ctx, sCtx.BelongingScope)
|
||||
if ctx.Written() {
|
||||
return
|
||||
}
|
||||
ctx.HTML(http.StatusOK, sCtx.SecretsTemplate)
|
||||
}
|
||||
|
||||
func SecretsPost(ctx *context.Context) {
|
||||
sCtx, err := getSecretsCtx(ctx)
|
||||
if err != nil {
|
||||
ctx.ServerErrorAuto(err)
|
||||
return
|
||||
}
|
||||
|
||||
if ctx.HasError() {
|
||||
ctx.JSONError(ctx.GetErrMsg())
|
||||
return
|
||||
}
|
||||
|
||||
shared.PerformSecretsPost(
|
||||
ctx,
|
||||
sCtx.BelongingScope,
|
||||
sCtx.Owner,
|
||||
sCtx.Repo,
|
||||
sCtx.RedirectLink,
|
||||
)
|
||||
}
|
||||
|
||||
func SecretsDelete(ctx *context.Context) {
|
||||
sCtx, err := getSecretsCtx(ctx)
|
||||
if err != nil {
|
||||
ctx.ServerErrorAuto(err)
|
||||
return
|
||||
}
|
||||
shared.PerformSecretsDelete(
|
||||
ctx,
|
||||
sCtx.BelongingScope,
|
||||
sCtx.Owner,
|
||||
sCtx.Repo,
|
||||
sCtx.RedirectLink,
|
||||
)
|
||||
}
|
||||
@@ -53,13 +53,14 @@ func GeneralSettings(ctx *context.Context) {
|
||||
return
|
||||
}
|
||||
|
||||
if rCtx.IsOrg {
|
||||
switch rCtx.Kind {
|
||||
case settingsScopeOrg:
|
||||
ctx.Data["PageIsOrgSettings"] = true
|
||||
ctx.Data["PageIsOrgSettingsActionsGeneral"] = true
|
||||
} else if rCtx.IsUser {
|
||||
case settingsScopeUser:
|
||||
ctx.Data["PageIsUserSettings"] = true
|
||||
ctx.Data["PageIsUserSettingsActionsGeneral"] = true
|
||||
} else {
|
||||
default:
|
||||
ctx.NotFound()
|
||||
return
|
||||
}
|
||||
@@ -90,7 +91,7 @@ func GeneralSettings(ctx *context.Context) {
|
||||
ctx.Data["AllowedRepos"] = allowedRepos
|
||||
ctx.Data["OwnerID"] = rCtx.OwnerID
|
||||
|
||||
if rCtx.IsOrg {
|
||||
if rCtx.Kind == settingsScopeOrg {
|
||||
ctx.HTML(http.StatusOK, tplOrgSettingsActionsGeneral)
|
||||
} else {
|
||||
ctx.HTML(http.StatusOK, tplUserSettingsActionsGeneral)
|
||||
@@ -105,7 +106,7 @@ func UpdateGeneralSettings(ctx *context.Context) {
|
||||
return
|
||||
}
|
||||
|
||||
if !rCtx.IsOrg && !rCtx.IsUser {
|
||||
if rCtx.Kind != settingsScopeOrg && rCtx.Kind != settingsScopeUser {
|
||||
ctx.NotFound()
|
||||
return
|
||||
}
|
||||
|
||||
@@ -5,96 +5,37 @@ package actions
|
||||
|
||||
import (
|
||||
stdctx "context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"net/http"
|
||||
"net/url"
|
||||
|
||||
actions_model "gitea.dev/models/actions"
|
||||
"gitea.dev/models/db"
|
||||
"gitea.dev/modules/log"
|
||||
"gitea.dev/modules/setting"
|
||||
"gitea.dev/modules/templates"
|
||||
"gitea.dev/modules/web"
|
||||
shared_user "gitea.dev/routers/web/shared/user"
|
||||
"gitea.dev/services/audit"
|
||||
"gitea.dev/services/context"
|
||||
"gitea.dev/services/forms"
|
||||
)
|
||||
|
||||
const (
|
||||
// TODO: Separate secrets from runners when layout is ready
|
||||
tplRepoRunners templates.TplName = "repo/settings/actions"
|
||||
tplOrgRunners templates.TplName = "org/settings/actions"
|
||||
tplAdminRunners templates.TplName = "admin/actions"
|
||||
tplUserRunners templates.TplName = "user/settings/actions"
|
||||
tplRepoRunnerEdit templates.TplName = "repo/settings/runner_edit"
|
||||
tplOrgRunnerEdit templates.TplName = "org/settings/runners_edit"
|
||||
tplAdminRunnerEdit templates.TplName = "admin/runners/edit"
|
||||
tplUserRunnerEdit templates.TplName = "user/settings/runner_edit"
|
||||
)
|
||||
var runnerEditTemplates = map[settingsScopeKind]templates.TplName{
|
||||
settingsScopeRepo: "repo/settings/runner_edit",
|
||||
settingsScopeOrg: "org/settings/runners_edit",
|
||||
settingsScopeUser: "user/settings/runner_edit",
|
||||
settingsScopeAdmin: "admin/runners/edit",
|
||||
}
|
||||
|
||||
type runnersCtx struct {
|
||||
OwnerID int64
|
||||
RepoID int64
|
||||
IsRepo bool
|
||||
IsOrg bool
|
||||
IsAdmin bool
|
||||
IsUser bool
|
||||
RunnersTemplate templates.TplName
|
||||
RunnerEditTemplate templates.TplName
|
||||
RedirectLink string
|
||||
*settingsScope
|
||||
RedirectLink string
|
||||
}
|
||||
|
||||
func getRunnersCtx(ctx *context.Context) (*runnersCtx, error) {
|
||||
if ctx.Data["PageIsRepoSettings"] == true {
|
||||
return &runnersCtx{
|
||||
RepoID: ctx.Repo.Repository.ID,
|
||||
OwnerID: 0,
|
||||
IsRepo: true,
|
||||
RunnersTemplate: tplRepoRunners,
|
||||
RunnerEditTemplate: tplRepoRunnerEdit,
|
||||
RedirectLink: ctx.Repo.RepoLink + "/settings/actions/runners/",
|
||||
}, nil
|
||||
scope, err := getSettingsScope(ctx)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
if ctx.Data["PageIsOrgSettings"] == true {
|
||||
if _, err := shared_user.RenderUserOrgHeader(ctx); err != nil {
|
||||
return nil, fmt.Errorf("RenderUserOrgHeader: %w", err)
|
||||
}
|
||||
return &runnersCtx{
|
||||
RepoID: 0,
|
||||
OwnerID: ctx.Org.Organization.ID,
|
||||
IsOrg: true,
|
||||
RunnersTemplate: tplOrgRunners,
|
||||
RunnerEditTemplate: tplOrgRunnerEdit,
|
||||
RedirectLink: ctx.Org.OrgLink + "/settings/actions/runners/",
|
||||
}, nil
|
||||
}
|
||||
|
||||
if ctx.Data["PageIsAdmin"] == true {
|
||||
return &runnersCtx{
|
||||
RepoID: 0,
|
||||
OwnerID: 0,
|
||||
IsAdmin: true,
|
||||
RunnersTemplate: tplAdminRunners,
|
||||
RunnerEditTemplate: tplAdminRunnerEdit,
|
||||
RedirectLink: setting.AppSubURL + "/-/admin/actions/runners/",
|
||||
}, nil
|
||||
}
|
||||
|
||||
if ctx.Data["PageIsUserSettings"] == true {
|
||||
return &runnersCtx{
|
||||
OwnerID: ctx.Doer.ID,
|
||||
RepoID: 0,
|
||||
IsUser: true,
|
||||
RunnersTemplate: tplUserRunners,
|
||||
RunnerEditTemplate: tplUserRunnerEdit,
|
||||
RedirectLink: setting.AppSubURL + "/user/settings/actions/runners/",
|
||||
}, nil
|
||||
}
|
||||
|
||||
return nil, errors.New("unable to set Runners context")
|
||||
return &runnersCtx{settingsScope: scope, RedirectLink: scope.LinkPrefix + "/runners/"}, nil
|
||||
}
|
||||
|
||||
// Runners render settings/actions/runners page for repo level
|
||||
@@ -109,22 +50,16 @@ func Runners(ctx *context.Context) {
|
||||
return
|
||||
}
|
||||
|
||||
page := max(ctx.FormInt("page"), 1)
|
||||
|
||||
opts := actions_model.FindRunnerOptions{
|
||||
ListOptions: db.ListOptions{
|
||||
Page: page,
|
||||
Page: max(ctx.FormInt("page"), 1),
|
||||
PageSize: 100,
|
||||
},
|
||||
Sort: ctx.Req.URL.Query().Get("sort"),
|
||||
Filter: ctx.Req.URL.Query().Get("q"),
|
||||
}
|
||||
if rCtx.IsRepo {
|
||||
opts.RepoID = rCtx.RepoID
|
||||
opts.WithAvailable = true
|
||||
} else if rCtx.IsOrg || rCtx.IsUser {
|
||||
opts.OwnerID = rCtx.OwnerID
|
||||
opts.WithAvailable = true
|
||||
Sort: ctx.Req.URL.Query().Get("sort"),
|
||||
Filter: ctx.Req.URL.Query().Get("q"),
|
||||
OwnerID: rCtx.OwnerID,
|
||||
RepoID: rCtx.RepoID,
|
||||
WithAvailable: !rCtx.IsAdmin(),
|
||||
}
|
||||
|
||||
runners, count, err := db.FindAndCount[actions_model.ActionRunner](ctx, opts)
|
||||
@@ -152,13 +87,13 @@ func Runners(ctx *context.Context) {
|
||||
ctx.Data["RunnerOwnerID"] = opts.OwnerID
|
||||
ctx.Data["RunnerRepoID"] = opts.RepoID
|
||||
ctx.Data["SortType"] = opts.Sort
|
||||
ctx.Data["AllowBulkActions"] = rCtx.IsAdmin
|
||||
ctx.Data["AllowBulkActions"] = rCtx.IsAdmin()
|
||||
|
||||
pager := context.NewPagerBuilder(ctx).TotalCount(count).PerPageLimit(opts.PageSize).CurPage(opts.Page).Build()
|
||||
|
||||
ctx.Data["Page"] = pager
|
||||
|
||||
ctx.HTML(http.StatusOK, rCtx.RunnersTemplate)
|
||||
ctx.HTML(http.StatusOK, rCtx.Template)
|
||||
}
|
||||
|
||||
// RunnersEdit renders runner edit page for repository level
|
||||
@@ -217,7 +152,7 @@ func RunnersEdit(ctx *context.Context) {
|
||||
pager := context.NewPagerBuilder(ctx).TotalCount(count).PerPageLimit(opts.PageSize).CurPage(opts.Page).Build()
|
||||
ctx.Data["Page"] = pager
|
||||
|
||||
ctx.HTML(http.StatusOK, rCtx.RunnerEditTemplate)
|
||||
ctx.HTML(http.StatusOK, runnerEditTemplates[rCtx.Kind])
|
||||
}
|
||||
|
||||
func RunnersEditPost(ctx *context.Context) {
|
||||
@@ -293,19 +228,11 @@ func RunnerDeletePost(ctx *context.Context) {
|
||||
return
|
||||
}
|
||||
|
||||
if !runner.EditableInContext(rCtx.OwnerID, rCtx.RepoID) {
|
||||
ctx.NotFound()
|
||||
return
|
||||
}
|
||||
|
||||
successRedirectTo := rCtx.RedirectLink
|
||||
failedRedirectTo := rCtx.RedirectLink + url.PathEscape(ctx.PathParam("runnerid"))
|
||||
|
||||
if err := actions_model.DeleteRunner(ctx, runner.ID); err != nil {
|
||||
log.Warn("DeleteRunnerPost.UpdateRunner failed: %v, url: %s", err, ctx.Req.URL)
|
||||
ctx.Flash.Warning(ctx.Tr("actions.runners.delete_runner_failed"))
|
||||
|
||||
ctx.JSONRedirect(failedRedirectTo)
|
||||
ctx.JSONRedirect(rCtx.RedirectLink + url.PathEscape(ctx.PathParam("runnerid")))
|
||||
return
|
||||
}
|
||||
|
||||
@@ -314,7 +241,7 @@ func RunnerDeletePost(ctx *context.Context) {
|
||||
|
||||
ctx.Flash.Success(ctx.Tr("actions.runners.delete_runner_success"))
|
||||
|
||||
ctx.JSONRedirect(successRedirectTo)
|
||||
ctx.JSONRedirect(rCtx.RedirectLink)
|
||||
}
|
||||
|
||||
func RunnerUpdatePost(ctx *context.Context) {
|
||||
@@ -329,11 +256,6 @@ func RunnerUpdatePost(ctx *context.Context) {
|
||||
return
|
||||
}
|
||||
|
||||
if !runner.EditableInContext(rCtx.OwnerID, rCtx.RepoID) {
|
||||
ctx.NotFound()
|
||||
return
|
||||
}
|
||||
|
||||
isDisabled := ctx.FormOptionalBool("disabled")
|
||||
if !isDisabled.Has() {
|
||||
ctx.HTTPError(http.StatusBadRequest, "missing 'disabled' parameter")
|
||||
@@ -368,7 +290,7 @@ func RunnerBulkActionPost(ctx *context.Context) {
|
||||
return
|
||||
}
|
||||
|
||||
if !rCtx.IsAdmin {
|
||||
if !rCtx.IsAdmin() {
|
||||
ctx.HTTPError(http.StatusForbidden, "bulk actions are admin-only")
|
||||
return
|
||||
}
|
||||
@@ -401,62 +323,49 @@ func RunnerBulkActionPost(ctx *context.Context) {
|
||||
return
|
||||
}
|
||||
|
||||
err = db.WithTx(ctx, func(txCtx stdctx.Context) error {
|
||||
for _, r := range runners {
|
||||
switch action {
|
||||
case "delete":
|
||||
if err := actions_model.DeleteRunner(txCtx, r.ID); err != nil {
|
||||
return err
|
||||
}
|
||||
audit.RecordScopedByID(txCtx, r.OwnerID, r.RepoID, audit.RunnerRemove, "runner", r.Name)
|
||||
case "disable", "enable":
|
||||
disabled := action == "disable"
|
||||
if err := actions_model.SetRunnerDisabled(txCtx, r, disabled); err != nil {
|
||||
return err
|
||||
}
|
||||
audit.RecordScopedByID(txCtx, r.OwnerID, r.RepoID, audit.RunnerUpdate, "runner", r.Name, "disabled", disabled)
|
||||
deleting, disabled := action == "delete", action == "disable"
|
||||
if err := db.WithTx(ctx, func(txCtx stdctx.Context) error {
|
||||
for _, runner := range runners {
|
||||
var err error
|
||||
if deleting {
|
||||
err = actions_model.DeleteRunner(txCtx, runner.ID)
|
||||
} else {
|
||||
err = actions_model.SetRunnerDisabled(txCtx, runner, disabled)
|
||||
}
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
return nil
|
||||
})
|
||||
if err != nil {
|
||||
}); err != nil {
|
||||
log.Warn("RunnerBulkActionPost.%s failed: %v, url: %s", action, err, ctx.Req.URL)
|
||||
ctx.Flash.Error(ctx.Tr(failedKey))
|
||||
ctx.JSONRedirect(rCtx.RedirectLink)
|
||||
return
|
||||
}
|
||||
|
||||
for _, runner := range runners {
|
||||
if deleting {
|
||||
audit.RecordScopedByID(ctx, runner.OwnerID, runner.RepoID, audit.RunnerRemove, "runner", runner.Name)
|
||||
} else {
|
||||
audit.RecordScopedByID(ctx, runner.OwnerID, runner.RepoID, audit.RunnerUpdate, "runner", runner.Name, "disabled", disabled)
|
||||
}
|
||||
}
|
||||
|
||||
ctx.Flash.Success(ctx.Tr(successKey))
|
||||
ctx.JSONRedirect(rCtx.RedirectLink)
|
||||
}
|
||||
|
||||
func findActionsRunner(ctx *context.Context, rCtx *runnersCtx) *actions_model.ActionRunner {
|
||||
runnerID := ctx.PathParamInt64("runnerid")
|
||||
opts := &actions_model.FindRunnerOptions{
|
||||
IDs: []int64{runnerID},
|
||||
}
|
||||
switch {
|
||||
case rCtx.IsRepo:
|
||||
opts.RepoID = rCtx.RepoID
|
||||
if opts.RepoID == 0 {
|
||||
panic("repoID is 0")
|
||||
}
|
||||
case rCtx.IsOrg, rCtx.IsUser:
|
||||
opts.OwnerID = rCtx.OwnerID
|
||||
if opts.OwnerID == 0 {
|
||||
panic("ownerID is 0")
|
||||
}
|
||||
case rCtx.IsAdmin:
|
||||
// do nothing
|
||||
default:
|
||||
panic("invalid actions runner context")
|
||||
}
|
||||
|
||||
got, err := db.Find[actions_model.ActionRunner](ctx, opts)
|
||||
got, err := db.Find[actions_model.ActionRunner](ctx, &actions_model.FindRunnerOptions{
|
||||
IDs: []int64{ctx.PathParamInt64("runnerid")},
|
||||
OwnerID: rCtx.OwnerID,
|
||||
RepoID: rCtx.RepoID,
|
||||
})
|
||||
if err != nil {
|
||||
ctx.ServerErrorAuto(err)
|
||||
return nil
|
||||
} else if len(got) == 0 {
|
||||
} else if len(got) == 0 || !got[0].EditableInContext(rCtx.OwnerID, rCtx.RepoID) {
|
||||
ctx.NotFound()
|
||||
return nil
|
||||
}
|
||||
|
||||
@@ -0,0 +1,59 @@
|
||||
// Copyright 2026 The Gitea Authors. All rights reserved.
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
package actions
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"fmt"
|
||||
|
||||
actions_model "gitea.dev/models/actions"
|
||||
"gitea.dev/modules/setting"
|
||||
"gitea.dev/modules/templates"
|
||||
shared_user "gitea.dev/routers/web/shared/user"
|
||||
"gitea.dev/services/context"
|
||||
)
|
||||
|
||||
type settingsScopeKind int
|
||||
|
||||
const (
|
||||
settingsScopeRepo settingsScopeKind = iota + 1
|
||||
settingsScopeOrg
|
||||
settingsScopeUser
|
||||
settingsScopeAdmin
|
||||
)
|
||||
|
||||
type settingsScope struct {
|
||||
Kind settingsScopeKind
|
||||
OwnerID, RepoID int64
|
||||
BelongingScope actions_model.BelongingScope
|
||||
LinkPrefix string
|
||||
Template templates.TplName // TODO: Separate secrets from runners when layout is ready
|
||||
}
|
||||
|
||||
func (s *settingsScope) IsAdmin() bool { return s.Kind == settingsScopeAdmin }
|
||||
|
||||
func getSettingsScope(ctx *context.Context) (*settingsScope, error) {
|
||||
scope := &settingsScope{}
|
||||
switch {
|
||||
case ctx.Data["PageIsRepoSettings"] == true:
|
||||
scope.Kind, scope.BelongingScope = settingsScopeRepo, actions_model.BelongingScopeRepo(ctx.Repo.Repository.ID)
|
||||
scope.LinkPrefix, scope.Template = ctx.Repo.RepoLink+"/settings/actions", "repo/settings/actions"
|
||||
case ctx.Data["PageIsOrgSettings"] == true:
|
||||
if _, err := shared_user.RenderUserOrgHeader(ctx); err != nil {
|
||||
return nil, fmt.Errorf("getSettingsScope: %w", err)
|
||||
}
|
||||
scope.Kind, scope.BelongingScope = settingsScopeOrg, actions_model.BelongingScopeOwner(ctx.Org.Organization.ID)
|
||||
scope.LinkPrefix, scope.Template = ctx.Org.OrgLink+"/settings/actions", "org/settings/actions"
|
||||
case ctx.Data["PageIsUserSettings"] == true:
|
||||
scope.Kind, scope.BelongingScope = settingsScopeUser, actions_model.BelongingScopeOwner(ctx.Doer.ID)
|
||||
scope.LinkPrefix, scope.Template = setting.AppSubURL+"/user/settings/actions", "user/settings/actions"
|
||||
case ctx.Data["PageIsAdmin"] == true:
|
||||
scope.Kind, scope.BelongingScope = settingsScopeAdmin, actions_model.BelongingScopeGlobal()
|
||||
scope.LinkPrefix, scope.Template = setting.AppSubURL+"/-/admin/actions", "admin/actions"
|
||||
default:
|
||||
return nil, errors.New("getSettingsScope: not an actions settings page")
|
||||
}
|
||||
scope.OwnerID, scope.RepoID = scope.BelongingScope.GetOwnerRepoIDs()
|
||||
return scope, nil
|
||||
}
|
||||
@@ -16,67 +16,25 @@ import (
|
||||
"gitea.dev/modules/container"
|
||||
"gitea.dev/modules/log"
|
||||
"gitea.dev/modules/setting"
|
||||
"gitea.dev/modules/templates"
|
||||
"gitea.dev/modules/util"
|
||||
shared_user "gitea.dev/routers/web/shared/user"
|
||||
actions_service "gitea.dev/services/actions"
|
||||
"gitea.dev/services/context"
|
||||
)
|
||||
|
||||
const (
|
||||
tplOrgScopedWorkflows templates.TplName = "org/settings/actions"
|
||||
tplUserScopedWorkflows templates.TplName = "user/settings/actions"
|
||||
tplAdminScopedWorkflows templates.TplName = "admin/actions"
|
||||
)
|
||||
|
||||
type scopedWorkflowsCtx struct {
|
||||
OwnerID int64 // 0 = instance-level
|
||||
IsOrg bool
|
||||
IsUser bool
|
||||
IsGlobal bool
|
||||
Template templates.TplName
|
||||
*settingsScope
|
||||
RedirectLink string
|
||||
// SearchUID is the uid passed to the repo-search box. For org/user it scopes the search to that owner;
|
||||
// for admin (0) it searches all repos and therefore requires admin access on the route.
|
||||
SearchUID int64
|
||||
}
|
||||
|
||||
func getScopedWorkflowsCtx(ctx *context.Context) (*scopedWorkflowsCtx, error) {
|
||||
if ctx.Data["PageIsOrgSettings"] == true {
|
||||
if _, err := shared_user.RenderUserOrgHeader(ctx); err != nil {
|
||||
ctx.ServerErrorAuto(err)
|
||||
return nil, nil //nolint:nilnil // error is already handled by ctx.ServerError
|
||||
}
|
||||
return &scopedWorkflowsCtx{
|
||||
OwnerID: ctx.Org.Organization.ID,
|
||||
IsOrg: true,
|
||||
Template: tplOrgScopedWorkflows,
|
||||
RedirectLink: ctx.Org.OrgLink + "/settings/actions/scoped-workflows",
|
||||
SearchUID: ctx.Org.Organization.ID,
|
||||
}, nil
|
||||
scope, err := getSettingsScope(ctx)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
if ctx.Data["PageIsUserSettings"] == true {
|
||||
return &scopedWorkflowsCtx{
|
||||
OwnerID: ctx.Doer.ID,
|
||||
IsUser: true,
|
||||
Template: tplUserScopedWorkflows,
|
||||
RedirectLink: setting.AppSubURL + "/user/settings/actions/scoped-workflows",
|
||||
SearchUID: ctx.Doer.ID,
|
||||
}, nil
|
||||
if scope.Kind == settingsScopeRepo {
|
||||
return nil, errors.New("getScopedWorkflowsCtx: scoped workflows are not managed per repository")
|
||||
}
|
||||
|
||||
if ctx.Data["PageIsAdmin"] == true {
|
||||
return &scopedWorkflowsCtx{
|
||||
OwnerID: 0,
|
||||
IsGlobal: true,
|
||||
Template: tplAdminScopedWorkflows,
|
||||
RedirectLink: setting.AppSubURL + "/-/admin/actions/scoped-workflows",
|
||||
SearchUID: 0,
|
||||
}, nil
|
||||
}
|
||||
|
||||
return nil, errors.New("unable to set scoped workflows context")
|
||||
return &scopedWorkflowsCtx{settingsScope: scope, RedirectLink: scope.LinkPrefix + "/scoped-workflows"}, nil
|
||||
}
|
||||
|
||||
// scopedWorkflowInfo is one scoped workflow shown on the settings page, merged with its stored merge-gate config.
|
||||
@@ -105,14 +63,11 @@ func ScopedWorkflows(ctx *context.Context) {
|
||||
ctx.ServerErrorAuto(err)
|
||||
return
|
||||
}
|
||||
if ctx.Written() {
|
||||
return
|
||||
}
|
||||
|
||||
switch {
|
||||
case swCtx.IsOrg:
|
||||
switch swCtx.Kind {
|
||||
case settingsScopeOrg:
|
||||
ctx.Data["ScopedWorkflowsDesc"] = ctx.Tr("actions.scoped_workflows.desc_org")
|
||||
case swCtx.IsUser:
|
||||
case settingsScopeUser:
|
||||
ctx.Data["ScopedWorkflowsDesc"] = ctx.Tr("actions.scoped_workflows.desc_user")
|
||||
default: // instance-level
|
||||
ctx.Data["ScopedWorkflowsDesc"] = ctx.Tr("actions.scoped_workflows.desc_global")
|
||||
@@ -138,11 +93,11 @@ func ScopedWorkflows(ctx *context.Context) {
|
||||
}
|
||||
|
||||
ctx.Data["ScopedWorkflowSources"] = views
|
||||
ctx.Data["RepoSearchUID"] = swCtx.SearchUID
|
||||
ctx.Data["RepoSearchUID"] = swCtx.OwnerID
|
||||
// owner/user scopes the repo search to the owner (exclusive);
|
||||
// instance-level (admin) searches all repos and so must submit owner/name to disambiguate the selection across owners.
|
||||
ctx.Data["ScopedWorkflowsSearchExclusive"] = !swCtx.IsGlobal
|
||||
ctx.Data["ScopedWorkflowsSearchFullName"] = swCtx.IsGlobal
|
||||
ctx.Data["ScopedWorkflowsSearchExclusive"] = !swCtx.IsAdmin()
|
||||
ctx.Data["ScopedWorkflowsSearchFullName"] = swCtx.IsAdmin()
|
||||
ctx.Data["RedirectLink"] = swCtx.RedirectLink
|
||||
ctx.Data["ScopedWorkflowDirs"] = strings.Join(setting.Actions.ScopedWorkflowDirs, ", ")
|
||||
ctx.HTML(http.StatusOK, swCtx.Template)
|
||||
@@ -236,13 +191,10 @@ func ScopedWorkflowAdd(ctx *context.Context) {
|
||||
ctx.ServerErrorAuto(err)
|
||||
return
|
||||
}
|
||||
if ctx.Written() {
|
||||
return
|
||||
}
|
||||
|
||||
repoName := ctx.FormString("repo_name")
|
||||
var repo *repo_model.Repository
|
||||
if swCtx.IsGlobal {
|
||||
if swCtx.IsAdmin() {
|
||||
// instance-level: the source may be any repo on the instance, identified by owner/name
|
||||
ownerName, name, ok := strings.Cut(repoName, "/")
|
||||
if !ok {
|
||||
@@ -273,9 +225,6 @@ func ScopedWorkflowSetRequired(ctx *context.Context) {
|
||||
ctx.ServerErrorAuto(err)
|
||||
return
|
||||
}
|
||||
if ctx.Written() {
|
||||
return
|
||||
}
|
||||
|
||||
repoID := ctx.FormInt64("repo_id")
|
||||
|
||||
@@ -342,9 +291,6 @@ func ScopedWorkflowRemove(ctx *context.Context) {
|
||||
ctx.ServerErrorAuto(err)
|
||||
return
|
||||
}
|
||||
if ctx.Written() {
|
||||
return
|
||||
}
|
||||
|
||||
repoID := ctx.FormInt64("repo_id")
|
||||
if err := actions_model.RemoveScopedWorkflowSource(ctx, swCtx.OwnerID, repoID); err != nil {
|
||||
|
||||
@@ -0,0 +1,79 @@
|
||||
// Copyright 2026 The Gitea Authors. All rights reserved.
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
package actions
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"net/http"
|
||||
|
||||
repo_model "gitea.dev/models/repo"
|
||||
user_model "gitea.dev/models/user"
|
||||
shared_secrets "gitea.dev/routers/web/shared/secrets"
|
||||
"gitea.dev/services/context"
|
||||
)
|
||||
|
||||
func getSecretsScope(ctx *context.Context) (*settingsScope, error) {
|
||||
scope, err := getSettingsScope(ctx)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if scope.IsAdmin() {
|
||||
return nil, errors.New("getSecretsScope: secrets are not managed at instance level")
|
||||
}
|
||||
return scope, nil
|
||||
}
|
||||
|
||||
func secretAuditTarget(ctx *context.Context, scope *settingsScope) (*user_model.User, *repo_model.Repository) {
|
||||
switch scope.Kind {
|
||||
case settingsScopeRepo:
|
||||
return nil, ctx.Repo.Repository
|
||||
case settingsScopeOrg:
|
||||
return ctx.ContextUser, nil
|
||||
default:
|
||||
return ctx.Doer, nil
|
||||
}
|
||||
}
|
||||
|
||||
func Secrets(ctx *context.Context) {
|
||||
ctx.Data["Title"] = ctx.Tr("secrets.secrets")
|
||||
ctx.Data["PageType"] = "secrets"
|
||||
ctx.Data["PageIsSharedSettingsSecrets"] = true
|
||||
|
||||
scope, err := getSecretsScope(ctx)
|
||||
if err != nil {
|
||||
ctx.ServerErrorAuto(err)
|
||||
return
|
||||
}
|
||||
|
||||
shared_secrets.SetSecretsContext(ctx, scope.BelongingScope)
|
||||
if !ctx.Written() {
|
||||
ctx.HTML(http.StatusOK, scope.Template)
|
||||
}
|
||||
}
|
||||
|
||||
func SecretsPost(ctx *context.Context) {
|
||||
scope, err := getSecretsScope(ctx)
|
||||
if err != nil {
|
||||
ctx.ServerErrorAuto(err)
|
||||
return
|
||||
}
|
||||
|
||||
if ctx.HasError() {
|
||||
ctx.JSONError(ctx.GetErrMsg())
|
||||
return
|
||||
}
|
||||
|
||||
owner, repo := secretAuditTarget(ctx, scope)
|
||||
shared_secrets.PerformSecretsPost(ctx, scope.BelongingScope, owner, repo, scope.LinkPrefix+"/secrets")
|
||||
}
|
||||
|
||||
func SecretsDelete(ctx *context.Context) {
|
||||
scope, err := getSecretsScope(ctx)
|
||||
if err != nil {
|
||||
ctx.ServerErrorAuto(err)
|
||||
return
|
||||
}
|
||||
owner, repo := secretAuditTarget(ctx, scope)
|
||||
shared_secrets.PerformSecretsDelete(ctx, scope.BelongingScope, owner, repo, scope.LinkPrefix+"/secrets")
|
||||
}
|
||||
@@ -4,96 +4,28 @@
|
||||
package actions
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"net/http"
|
||||
|
||||
actions_model "gitea.dev/models/actions"
|
||||
"gitea.dev/models/db"
|
||||
"gitea.dev/modules/log"
|
||||
"gitea.dev/modules/setting"
|
||||
"gitea.dev/modules/templates"
|
||||
"gitea.dev/modules/web"
|
||||
shared_user "gitea.dev/routers/web/shared/user"
|
||||
actions_service "gitea.dev/services/actions"
|
||||
"gitea.dev/services/context"
|
||||
"gitea.dev/services/forms"
|
||||
)
|
||||
|
||||
const (
|
||||
tplRepoVariables templates.TplName = "repo/settings/actions"
|
||||
tplOrgVariables templates.TplName = "org/settings/actions"
|
||||
tplUserVariables templates.TplName = "user/settings/actions"
|
||||
tplAdminVariables templates.TplName = "admin/actions"
|
||||
)
|
||||
|
||||
type variablesCtx struct {
|
||||
BelongingScope actions_model.BelongingScope
|
||||
IsRepo bool
|
||||
IsOrg bool
|
||||
IsUser bool
|
||||
IsGlobal bool
|
||||
VariablesTemplate templates.TplName
|
||||
RedirectLink string
|
||||
}
|
||||
|
||||
func getVariablesCtx(ctx *context.Context) (*variablesCtx, error) {
|
||||
if ctx.Data["PageIsRepoSettings"] == true {
|
||||
return &variablesCtx{
|
||||
BelongingScope: actions_model.BelongingScopeRepo(ctx.Repo.Repository.ID),
|
||||
IsRepo: true,
|
||||
VariablesTemplate: tplRepoVariables,
|
||||
RedirectLink: ctx.Repo.RepoLink + "/settings/actions/variables",
|
||||
}, nil
|
||||
}
|
||||
|
||||
if ctx.Data["PageIsOrgSettings"] == true {
|
||||
if _, err := shared_user.RenderUserOrgHeader(ctx); err != nil {
|
||||
ctx.ServerErrorAuto(err)
|
||||
return nil, nil //nolint:nilnil // error is already handled by ctx.ServerError
|
||||
}
|
||||
return &variablesCtx{
|
||||
BelongingScope: actions_model.BelongingScopeOwner(ctx.Org.Organization.ID),
|
||||
IsOrg: true,
|
||||
VariablesTemplate: tplOrgVariables,
|
||||
RedirectLink: ctx.Org.OrgLink + "/settings/actions/variables",
|
||||
}, nil
|
||||
}
|
||||
|
||||
if ctx.Data["PageIsUserSettings"] == true {
|
||||
return &variablesCtx{
|
||||
BelongingScope: actions_model.BelongingScopeOwner(ctx.Doer.ID),
|
||||
IsUser: true,
|
||||
VariablesTemplate: tplUserVariables,
|
||||
RedirectLink: setting.AppSubURL + "/user/settings/actions/variables",
|
||||
}, nil
|
||||
}
|
||||
|
||||
if ctx.Data["PageIsAdmin"] == true {
|
||||
return &variablesCtx{
|
||||
BelongingScope: actions_model.BelongingScopeGlobal(),
|
||||
IsGlobal: true,
|
||||
VariablesTemplate: tplAdminVariables,
|
||||
RedirectLink: setting.AppSubURL + "/-/admin/actions/variables",
|
||||
}, nil
|
||||
}
|
||||
|
||||
return nil, errors.New("unable to set Variables context")
|
||||
}
|
||||
|
||||
func Variables(ctx *context.Context) {
|
||||
ctx.Data["Title"] = ctx.Tr("actions.variables")
|
||||
ctx.Data["PageType"] = "variables"
|
||||
ctx.Data["PageIsSharedSettingsVariables"] = true
|
||||
|
||||
vCtx, err := getVariablesCtx(ctx)
|
||||
scope, err := getSettingsScope(ctx)
|
||||
if err != nil {
|
||||
ctx.ServerErrorAuto(err)
|
||||
return
|
||||
}
|
||||
|
||||
variables, err := db.Find[actions_model.ActionVariable](ctx, actions_model.FindVariablesOpts{
|
||||
BelongingScope: vCtx.BelongingScope,
|
||||
})
|
||||
variables, err := actions_model.FindVariables(ctx, actions_model.FindVariablesOpts{BelongingScope: scope.BelongingScope})
|
||||
if err != nil {
|
||||
ctx.ServerErrorAuto(err)
|
||||
return
|
||||
@@ -101,48 +33,46 @@ func Variables(ctx *context.Context) {
|
||||
ctx.Data["Variables"] = variables
|
||||
ctx.Data["DataMaxLength"] = actions_model.VariableDataMaxLength
|
||||
ctx.Data["DescriptionMaxLength"] = actions_model.VariableDescriptionMaxLength
|
||||
ctx.HTML(http.StatusOK, vCtx.VariablesTemplate)
|
||||
ctx.HTML(http.StatusOK, scope.Template)
|
||||
}
|
||||
|
||||
func VariableCreate(ctx *context.Context) {
|
||||
vCtx, err := getVariablesCtx(ctx)
|
||||
scope, err := getSettingsScope(ctx)
|
||||
if err != nil {
|
||||
ctx.ServerErrorAuto(err)
|
||||
return
|
||||
}
|
||||
|
||||
if ctx.HasError() { // form binding validation error
|
||||
if ctx.HasError() {
|
||||
ctx.JSONError(ctx.GetErrMsg())
|
||||
return
|
||||
}
|
||||
|
||||
form := web.GetForm[*forms.EditVariableForm](ctx)
|
||||
|
||||
v, err := actions_service.CreateVariable(ctx, vCtx.BelongingScope, form.Name, form.Data, form.Description)
|
||||
variable, err := actions_service.CreateVariable(ctx, scope.BelongingScope, form.Name, form.Data, form.Description)
|
||||
if err != nil {
|
||||
ctx.JSONErrorAuto(err)
|
||||
return
|
||||
}
|
||||
|
||||
ctx.Flash.Success(ctx.Tr("actions.variables.creation.success", v.Name))
|
||||
ctx.JSONRedirect(vCtx.RedirectLink)
|
||||
ctx.Flash.Success(ctx.Tr("actions.variables.creation.success", variable.Name))
|
||||
ctx.JSONRedirect(scope.LinkPrefix + "/variables")
|
||||
}
|
||||
|
||||
func VariableUpdate(ctx *context.Context) {
|
||||
vCtx, err := getVariablesCtx(ctx)
|
||||
scope, err := getSettingsScope(ctx)
|
||||
if err != nil {
|
||||
ctx.ServerErrorAuto(err)
|
||||
return
|
||||
}
|
||||
|
||||
if ctx.HasError() { // form binding validation error
|
||||
if ctx.HasError() {
|
||||
ctx.JSONError(ctx.GetErrMsg())
|
||||
return
|
||||
}
|
||||
|
||||
id := ctx.PathParamInt64("variable_id")
|
||||
|
||||
variable := findActionsVariable(ctx, id, vCtx)
|
||||
variable := findActionsVariable(ctx, ctx.PathParamInt64("variable_id"), scope.BelongingScope)
|
||||
if ctx.Written() {
|
||||
return
|
||||
}
|
||||
@@ -157,27 +87,26 @@ func VariableUpdate(ctx *context.Context) {
|
||||
return
|
||||
}
|
||||
ctx.Flash.Success(ctx.Tr("actions.variables.update.success"))
|
||||
ctx.JSONRedirect(vCtx.RedirectLink)
|
||||
ctx.JSONRedirect(scope.LinkPrefix + "/variables")
|
||||
}
|
||||
|
||||
func findActionsVariable(ctx *context.Context, id int64, vCtx *variablesCtx) *actions_model.ActionVariable {
|
||||
opts := actions_model.FindVariablesOpts{
|
||||
func findActionsVariable(ctx *context.Context, id int64, scope actions_model.BelongingScope) *actions_model.ActionVariable {
|
||||
variables, err := actions_model.FindVariables(ctx, actions_model.FindVariablesOpts{
|
||||
IDs: []int64{id},
|
||||
BelongingScope: vCtx.BelongingScope,
|
||||
}
|
||||
got, err := actions_model.FindVariables(ctx, opts)
|
||||
BelongingScope: scope,
|
||||
})
|
||||
if err != nil {
|
||||
ctx.ServerErrorAuto(err)
|
||||
return nil
|
||||
} else if len(got) == 0 {
|
||||
} else if len(variables) == 0 {
|
||||
ctx.NotFound()
|
||||
return nil
|
||||
}
|
||||
return got[0]
|
||||
return variables[0]
|
||||
}
|
||||
|
||||
func VariableDelete(ctx *context.Context) {
|
||||
vCtx, err := getVariablesCtx(ctx)
|
||||
scope, err := getSettingsScope(ctx)
|
||||
if err != nil {
|
||||
ctx.ServerErrorAuto(err)
|
||||
return
|
||||
@@ -185,7 +114,7 @@ func VariableDelete(ctx *context.Context) {
|
||||
|
||||
id := ctx.PathParamInt64("variable_id")
|
||||
|
||||
variable := findActionsVariable(ctx, id, vCtx)
|
||||
variable := findActionsVariable(ctx, id, scope.BelongingScope)
|
||||
if ctx.Written() {
|
||||
return
|
||||
}
|
||||
@@ -196,5 +125,5 @@ func VariableDelete(ctx *context.Context) {
|
||||
return
|
||||
}
|
||||
ctx.Flash.Success(ctx.Tr("actions.variables.deletion.success"))
|
||||
ctx.JSONRedirect(vCtx.RedirectLink)
|
||||
ctx.JSONRedirect(scope.LinkPrefix + "/variables")
|
||||
}
|
||||
+14
-25
@@ -486,9 +486,9 @@ func registerWebRoutes(m *web.Router, webAuth *AuthMiddleware) {
|
||||
|
||||
addSettingsSecretsRoutes := func() {
|
||||
m.Group("/secrets", func() {
|
||||
m.Get("", repo_setting.Secrets)
|
||||
m.Post("", web.Bind[*forms.AddSecretForm](), repo_setting.SecretsPost)
|
||||
m.Post("/delete", repo_setting.SecretsDelete)
|
||||
m.Get("", shared_actions.Secrets)
|
||||
m.Post("", web.Bind[*forms.AddSecretForm](), shared_actions.SecretsPost)
|
||||
m.Post("/delete", shared_actions.SecretsDelete)
|
||||
})
|
||||
}
|
||||
|
||||
@@ -512,6 +512,15 @@ func registerWebRoutes(m *web.Router, webAuth *AuthMiddleware) {
|
||||
})
|
||||
}
|
||||
|
||||
addOwnerActionsRoutes := func() {
|
||||
m.Get("", misc.LocationRedirect("./actions/general"))
|
||||
m.Combo("/general").Get(shared_actions.GeneralSettings).Post(shared_actions.UpdateGeneralSettings)
|
||||
addSettingsRunnersRoutes()
|
||||
addSettingsSecretsRoutes()
|
||||
addSettingsVariablesRoutes()
|
||||
addSettingsScopedWorkflowsRoutes()
|
||||
}
|
||||
|
||||
// FIXME: not all routes need go through same middleware.
|
||||
// Especially some AJAX requests, we can reduce middleware number to improve performance.
|
||||
|
||||
@@ -688,17 +697,7 @@ func registerWebRoutes(m *web.Router, webAuth *AuthMiddleware) {
|
||||
m.Post("/chef/regenerate_keypair", user_setting.RegenerateChefKeyPair)
|
||||
}, packagesEnabled)
|
||||
|
||||
m.Group("/actions", func() {
|
||||
m.Get("", misc.LocationRedirect("./actions/general"))
|
||||
m.Group("/general", func() {
|
||||
m.Get("", shared_actions.GeneralSettings)
|
||||
m.Post("", shared_actions.UpdateGeneralSettings)
|
||||
})
|
||||
addSettingsRunnersRoutes()
|
||||
addSettingsSecretsRoutes()
|
||||
addSettingsVariablesRoutes()
|
||||
addSettingsScopedWorkflowsRoutes()
|
||||
}, actions.MustEnableActions)
|
||||
m.Group("/actions", addOwnerActionsRoutes, actions.MustEnableActions)
|
||||
|
||||
m.Get("/organization", user_setting.Organization)
|
||||
m.Get("/repos", user_setting.Repos)
|
||||
@@ -1025,17 +1024,7 @@ func registerWebRoutes(m *web.Router, webAuth *AuthMiddleware) {
|
||||
m.Post("/initialize", web.Bind[*forms.InitializeLabelsForm](), org.InitializeLabels)
|
||||
})
|
||||
|
||||
m.Group("/actions", func() {
|
||||
m.Get("", misc.LocationRedirect("./actions/general"))
|
||||
m.Group("/general", func() {
|
||||
m.Get("", shared_actions.GeneralSettings)
|
||||
m.Post("", shared_actions.UpdateGeneralSettings)
|
||||
})
|
||||
addSettingsRunnersRoutes()
|
||||
addSettingsSecretsRoutes()
|
||||
addSettingsVariablesRoutes()
|
||||
addSettingsScopedWorkflowsRoutes()
|
||||
}, actions.MustEnableActions)
|
||||
m.Group("/actions", addOwnerActionsRoutes, actions.MustEnableActions)
|
||||
|
||||
m.Get("/audit_logs", org_setting.ViewAuditLogs)
|
||||
|
||||
|
||||
@@ -15,7 +15,6 @@ import (
|
||||
user_model "gitea.dev/models/user"
|
||||
"gitea.dev/modules/container"
|
||||
"gitea.dev/modules/log"
|
||||
"gitea.dev/modules/timeutil"
|
||||
"gitea.dev/modules/util"
|
||||
|
||||
"xorm.io/builder"
|
||||
@@ -96,12 +95,11 @@ func ApproveRuns(ctx context.Context, repo *repo_model.Repository, doer *user_mo
|
||||
}
|
||||
continue
|
||||
}
|
||||
// A slot-starved job cannot start, skip the following checks.
|
||||
if !slots.available(job) {
|
||||
continue
|
||||
jobsToCancel, runsOnErr, err := admitJob(ctx, job, slots, func() error { return invalidRunsOn(job) }, nil)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if invalid := invalidRunsOn(job); invalid != nil {
|
||||
job.Status, job.Stopped = actions_model.StatusFailure, timeutil.TimeStampNow()
|
||||
if runsOnErr != nil {
|
||||
n, err := actions_model.UpdateRunJob(ctx, job, nil, "status", "stopped")
|
||||
if err != nil {
|
||||
return err
|
||||
@@ -109,18 +107,12 @@ func ApproveRuns(ctx context.Context, repo *repo_model.Repository, doer *user_mo
|
||||
if n > 0 {
|
||||
updatedJobs = append(updatedJobs, job)
|
||||
}
|
||||
if err := upsertJobErrorSummary(ctx, job, "runs-on", invalid); err != nil {
|
||||
if err := upsertJobErrorSummary(ctx, job, "runs-on", runsOnErr); err != nil {
|
||||
return err
|
||||
}
|
||||
continue
|
||||
}
|
||||
var jobsToCancel []*actions_model.ActionRunJob
|
||||
job.Status, jobsToCancel, err = PrepareToStartJobWithConcurrency(ctx, job)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
cancelledConcurrencyJobs = append(cancelledConcurrencyJobs, jobsToCancel...)
|
||||
applyMaxParallel(job, slots)
|
||||
if job.Status != actions_model.StatusWaiting {
|
||||
continue
|
||||
}
|
||||
|
||||
@@ -49,9 +49,30 @@ func TestApproveRuns(t *testing.T) {
|
||||
return job
|
||||
}
|
||||
|
||||
t.Run("approve unblocks a job with no dependencies", func(t *testing.T) {
|
||||
run := insertRun(1001, actions_model.StatusBlocked, true, 0)
|
||||
job := insertJob(run, actions_model.StatusBlocked)
|
||||
t.Run("approve unblocks a job with no dependencies that a newer job in its group did not replace", func(t *testing.T) {
|
||||
content := []byte("on: [pull_request, push]\njobs:\n job1:\n runs-on: ubuntu-latest\n concurrency: ci-${{ github.base_ref || github.ref_name }}\n steps:\n - run: echo hi\n")
|
||||
const pushCommit, pullCommit = "65f1bf27bc3bf70f64657658635e66094edbcb4d", "985f0301dba5e7b34be866819cd15ad3d8f508ee"
|
||||
push := actions_model.ActionRun{
|
||||
RepoID: repo.ID, OwnerID: repo.OwnerID, WorkflowID: "test.yaml", TriggerUserID: doer.ID,
|
||||
Ref: "refs/heads/master", CommitSHA: pushCommit, WorkflowRepoID: repo.ID, WorkflowCommitSHA: pushCommit,
|
||||
Event: "push", TriggerEvent: "push", EventPayload: `{"head_commit":{"id":"` + pushCommit + `"}}`,
|
||||
}
|
||||
run := push
|
||||
run.Ref, run.CommitSHA, run.WorkflowCommitSHA, run.TriggerUserID = "refs/pull/1/head", pullCommit, pullCommit, 4
|
||||
run.Event, run.TriggerEvent, run.IsForkPullRequest, run.NeedApproval = "pull_request", "pull_request", true, true
|
||||
run.EventPayload = `{"pull_request":{"base":{"ref":"master"},"head":{"ref":"branch2","sha":"` + pullCommit + `"}}}`
|
||||
require.NoError(t, PrepareRunAndInsert(t.Context(), content, &run, nil))
|
||||
require.NoError(t, PrepareRunAndInsert(t.Context(), content, &push, nil))
|
||||
job := unittest.AssertExistsAndLoadBean(t, &actions_model.ActionRunJob{RunID: run.ID})
|
||||
pushJob := unittest.AssertExistsAndLoadBean(t, &actions_model.ActionRunJob{RunID: push.ID})
|
||||
require.Equal(t, "ci-master", pushJob.ConcurrencyGroup)
|
||||
require.Equal(t, pushJob.ConcurrencyGroup, job.ConcurrencyGroup)
|
||||
require.Equal(t, actions_model.StatusWaiting, pushJob.Status)
|
||||
require.Equal(t, actions_model.StatusBlocked, job.Status)
|
||||
|
||||
pushJob.Status = actions_model.StatusCancelled
|
||||
_, err := actions_model.UpdateRunJob(t.Context(), pushJob, nil, "status")
|
||||
require.NoError(t, err)
|
||||
|
||||
approved, err := ApproveRuns(t.Context(), repo, doer, []int64{run.ID})
|
||||
require.NoError(t, err)
|
||||
|
||||
@@ -6,6 +6,7 @@ package actions
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"strings"
|
||||
"unicode/utf8"
|
||||
|
||||
act_model "gitea.dev/actionslib/pkg/model"
|
||||
@@ -43,7 +44,7 @@ func EvaluateRunConcurrencyFillModel(ctx context.Context, run *actions_model.Act
|
||||
if err != nil {
|
||||
return fmt.Errorf("evaluate concurrency: %w", err)
|
||||
}
|
||||
attempt.ConcurrencyGroup = boundedConcurrencyGroup(attempt.ConcurrencyGroup)
|
||||
attempt.ConcurrencyGroup = normalizeConcurrencyGroup(attempt.ConcurrencyGroup)
|
||||
return nil
|
||||
}
|
||||
|
||||
@@ -86,12 +87,13 @@ func EvaluateJobConcurrencyFillModel(ctx context.Context, run *actions_model.Act
|
||||
if err != nil {
|
||||
return util.NewInvalidArgumentErrorf("%v", err)
|
||||
}
|
||||
actionRunJob.ConcurrencyGroup = boundedConcurrencyGroup(actionRunJob.ConcurrencyGroup)
|
||||
actionRunJob.ConcurrencyGroup = normalizeConcurrencyGroup(actionRunJob.ConcurrencyGroup)
|
||||
actionRunJob.IsConcurrencyEvaluated = true
|
||||
return nil
|
||||
}
|
||||
|
||||
func boundedConcurrencyGroup(group string) string {
|
||||
func normalizeConcurrencyGroup(group string) string {
|
||||
group = strings.ToLower(group)
|
||||
if utf8.RuneCountInString(group) > 255 {
|
||||
return base.EncodeSha256(group)
|
||||
}
|
||||
|
||||
@@ -282,7 +282,7 @@ func computeReusableCallerOutputs(ctx context.Context, caller *actions_model.Act
|
||||
return nil, err
|
||||
}
|
||||
|
||||
inputs, err := calledWorkflowInputs(ctx, caller.Run, caller, workflowCallInputs)
|
||||
inputs, err := calledWorkflowInputs(ctx, caller.Run, caller, nil, workflowCallInputs)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
@@ -52,7 +52,7 @@ func TestEvaluateRunConcurrency_RunIDFallback(t *testing.T) {
|
||||
assert.Contains(t, attemptB.ConcurrencyGroup, "792")
|
||||
assert.NotEqual(t, attemptA.ConcurrencyGroup, attemptB.ConcurrencyGroup)
|
||||
|
||||
t.Run("preserves 255 runes and bounds longer groups", func(t *testing.T) {
|
||||
t.Run("preserves 255 runes and normalizes case before bounding longer groups", func(t *testing.T) {
|
||||
evaluateGroup := func(group string) string {
|
||||
require.NoError(t, EvaluateRunConcurrencyFillModel(ctx, runA, attemptA, &act_model.RawConcurrency{Group: group}, nil, nil))
|
||||
return attemptA.ConcurrencyGroup
|
||||
@@ -61,7 +61,7 @@ func TestEvaluateRunConcurrency_RunIDFallback(t *testing.T) {
|
||||
assert.Equal(t, group, evaluateGroup(group))
|
||||
boundedGroup := evaluateGroup(group + "a")
|
||||
assert.LessOrEqual(t, utf8.RuneCountInString(boundedGroup), 255)
|
||||
assert.Equal(t, boundedGroup, evaluateGroup(group+"a"))
|
||||
assert.Equal(t, boundedGroup, evaluateGroup(group+"A"))
|
||||
assert.NotEqual(t, boundedGroup, evaluateGroup(group+"b"))
|
||||
})
|
||||
}
|
||||
|
||||
+49
-10
@@ -14,6 +14,7 @@ import (
|
||||
"gitea.dev/modules/actions/jobparser"
|
||||
"gitea.dev/modules/json"
|
||||
api "gitea.dev/modules/structs"
|
||||
"gitea.dev/modules/timeutil"
|
||||
"gitea.dev/modules/util"
|
||||
webhook_module "gitea.dev/modules/webhook"
|
||||
)
|
||||
@@ -56,19 +57,29 @@ func dispatchInputsForRunJobs(run *actions_model.ActionRun, jobs []*actions_mode
|
||||
// - For top-level jobs, it falls back to the run's dispatch inputs (empty for non-dispatch events)
|
||||
// - For reusable workflow children (and nested callers), this is calledWorkflowInputs of the direct parent caller
|
||||
func getInputsForJob(ctx context.Context, run *actions_model.ActionRun, job *actions_model.ActionRunJob) (map[string]any, error) {
|
||||
return getInputsForJobWithAncestors(ctx, run, job, nil)
|
||||
}
|
||||
|
||||
func getInputsForJobWithAncestors(ctx context.Context, run *actions_model.ActionRun, job *actions_model.ActionRunJob, ancestors []*actions_model.ActionRunJob) (map[string]any, error) {
|
||||
if job.ParentJobID == 0 {
|
||||
return dispatchInputsForJob(run, job)
|
||||
}
|
||||
|
||||
caller, err := actions_model.GetRunJobByRunAndID(ctx, run.ID, job.ParentJobID)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("load caller job %d: %w", job.ParentJobID, err)
|
||||
var caller *actions_model.ActionRunJob
|
||||
if len(ancestors) > 0 {
|
||||
caller, ancestors = ancestors[0], ancestors[1:]
|
||||
} else {
|
||||
var err error
|
||||
caller, err = actions_model.GetRunJobByRunAndID(ctx, run.ID, job.ParentJobID)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("getInputsForJobWithAncestors: load caller job %d: %w", job.ParentJobID, err)
|
||||
}
|
||||
}
|
||||
workflowCallInputs, err := decodeWorkflowCallInputs(caller)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return calledWorkflowInputs(ctx, run, caller, workflowCallInputs)
|
||||
return calledWorkflowInputs(ctx, run, caller, ancestors, workflowCallInputs)
|
||||
}
|
||||
|
||||
func decodeWorkflowCallInputs(caller *actions_model.ActionRunJob) (map[string]any, error) {
|
||||
@@ -82,14 +93,17 @@ func decodeWorkflowCallInputs(caller *actions_model.ActionRunJob) (map[string]an
|
||||
}
|
||||
|
||||
// calledWorkflowInputs overlays the run's dispatch inputs with `workflowCallInputs`, as GitHub does.
|
||||
func calledWorkflowInputs(ctx context.Context, run *actions_model.ActionRun, caller *actions_model.ActionRunJob, workflowCallInputs map[string]any) (map[string]any, error) {
|
||||
top := caller
|
||||
for run.Event == webhook_module.HookEventWorkflowDispatch && top.ParentJobID != 0 {
|
||||
parent, err := actions_model.GetRunJobByRunAndID(ctx, run.ID, top.ParentJobID)
|
||||
func calledWorkflowInputs(ctx context.Context, run *actions_model.ActionRun, caller *actions_model.ActionRunJob, ancestors []*actions_model.ActionRunJob, workflowCallInputs map[string]any) (map[string]any, error) {
|
||||
if run.Event == webhook_module.HookEventWorkflowDispatch && len(ancestors) == 0 {
|
||||
var err error
|
||||
ancestors, err = actions_model.GetAncestorCallers(ctx, caller)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("load caller job %d: %w", top.ParentJobID, err)
|
||||
return nil, err
|
||||
}
|
||||
top = parent
|
||||
}
|
||||
top := caller
|
||||
if len(ancestors) > 0 {
|
||||
top = ancestors[len(ancestors)-1]
|
||||
}
|
||||
inputs, err := dispatchInputsForJob(run, top)
|
||||
if err != nil {
|
||||
@@ -178,6 +192,31 @@ func invalidRunsOn(job *actions_model.ActionRunJob) error {
|
||||
return nil
|
||||
}
|
||||
|
||||
// admitJob gates a job whose `if:` passed, a slot-starved job stays blocked without checking runs-on or cancelling its group peers.
|
||||
func admitJob(ctx context.Context, job *actions_model.ActionRunJob, slots maxParallelSlots, checkRunsOn, evaluateConcurrency func() error) (cancelled []*actions_model.ActionRunJob, runsOnErr, err error) {
|
||||
if !slots.available(job) {
|
||||
applyMaxParallel(job, slots)
|
||||
return nil, nil, nil
|
||||
}
|
||||
if checkRunsOn != nil {
|
||||
if runsOnErr = checkRunsOn(); runsOnErr != nil {
|
||||
job.Status, job.Stopped = actions_model.StatusFailure, timeutil.TimeStampNow()
|
||||
return nil, runsOnErr, nil
|
||||
}
|
||||
}
|
||||
if evaluateConcurrency != nil && job.RawConcurrency != "" {
|
||||
if err := evaluateConcurrency(); err != nil {
|
||||
return nil, nil, fmt.Errorf("evaluate job concurrency: %w", err)
|
||||
}
|
||||
}
|
||||
job.Status, cancelled, err = PrepareToStartJobWithConcurrency(ctx, job)
|
||||
if err != nil {
|
||||
return nil, nil, fmt.Errorf("prepare to start job with concurrency: %w", err)
|
||||
}
|
||||
applyMaxParallel(job, slots)
|
||||
return cancelled, nil, nil
|
||||
}
|
||||
|
||||
func findJobNeedsAndFillJobResults(ctx context.Context, job *actions_model.ActionRunJob) (map[string]*jobparser.JobResult, error) {
|
||||
taskNeeds, jobsByID, err := FindTaskNeeds(ctx, job)
|
||||
if err != nil {
|
||||
|
||||
@@ -4,6 +4,7 @@
|
||||
package actions
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"testing"
|
||||
|
||||
actions_model "gitea.dev/models/actions"
|
||||
@@ -14,6 +15,59 @@ import (
|
||||
"github.com/stretchr/testify/require"
|
||||
)
|
||||
|
||||
func TestAdmitJob(t *testing.T) {
|
||||
checked, evaluated := 0, 0
|
||||
badRunsOn, badConcurrency := errors.New("bad runs-on"), errors.New("bad concurrency")
|
||||
checkRunsOn := func() error { checked++; return badRunsOn }
|
||||
evaluate := func(job *actions_model.ActionRunJob) func() error {
|
||||
return func() error { evaluated++; job.IsConcurrencyEvaluated = true; return nil }
|
||||
}
|
||||
newJob := func() *actions_model.ActionRunJob {
|
||||
return &actions_model.ActionRunJob{JobID: "build", Status: actions_model.StatusWaiting, MaxParallel: 1, RawConcurrency: "group: g"}
|
||||
}
|
||||
|
||||
t.Run("a full slot blocks the next job before runs-on and concurrency checks", func(t *testing.T) {
|
||||
slots := maxParallelSlots{}
|
||||
first := newJob()
|
||||
cancelled, runsOnErr, err := admitJob(t.Context(), first, slots, nil, evaluate(first))
|
||||
require.NoError(t, err)
|
||||
require.NoError(t, runsOnErr)
|
||||
assert.Empty(t, cancelled)
|
||||
assert.Equal(t, actions_model.StatusWaiting, first.Status)
|
||||
|
||||
starved := newJob()
|
||||
_, runsOnErr, err = admitJob(t.Context(), starved, slots, checkRunsOn, evaluate(starved))
|
||||
require.NoError(t, err)
|
||||
require.NoError(t, runsOnErr)
|
||||
assert.Equal(t, actions_model.StatusBlocked, starved.Status)
|
||||
assert.Equal(t, 0, checked)
|
||||
assert.Equal(t, 1, evaluated)
|
||||
})
|
||||
|
||||
t.Run("an invalid runs-on fails the job before concurrency", func(t *testing.T) {
|
||||
failed := newJob()
|
||||
_, runsOnErr, err := admitJob(t.Context(), failed, maxParallelSlots{}, checkRunsOn, evaluate(failed))
|
||||
require.NoError(t, err)
|
||||
assert.ErrorIs(t, runsOnErr, badRunsOn)
|
||||
assert.Equal(t, actions_model.StatusFailure, failed.Status)
|
||||
assert.NotZero(t, failed.Stopped)
|
||||
assert.False(t, failed.IsConcurrencyEvaluated)
|
||||
})
|
||||
|
||||
t.Run("a job without concurrency skips evaluation", func(t *testing.T) {
|
||||
plain := newJob()
|
||||
plain.RawConcurrency = ""
|
||||
_, _, err := admitJob(t.Context(), plain, maxParallelSlots{}, nil, evaluate(plain))
|
||||
require.NoError(t, err)
|
||||
assert.False(t, plain.IsConcurrencyEvaluated)
|
||||
})
|
||||
|
||||
t.Run("a concurrency evaluation error is returned", func(t *testing.T) {
|
||||
_, _, err := admitJob(t.Context(), newJob(), maxParallelSlots{}, nil, func() error { return badConcurrency })
|
||||
assert.ErrorIs(t, err, badConcurrency)
|
||||
})
|
||||
}
|
||||
|
||||
func TestDispatchInputsForRunJobs(t *testing.T) {
|
||||
// a child carries the callee's `on: workflow_call`, so only a top-level job answers for the run
|
||||
run := &actions_model.ActionRun{Event: "workflow_dispatch", EventPayload: `{"inputs":{"deploy":"true"}}`}
|
||||
@@ -44,16 +98,17 @@ func TestReusableChildInputs(t *testing.T) {
|
||||
caller := insertJob("caller", 0,
|
||||
"on: {workflow_dispatch: {inputs: {flag: {type: boolean}, Shared: {type: string}}}}\njobs:\n caller:\n uses: ./.gitea/workflows/mid.yml\n",
|
||||
`{"inputs":{"shared":"from-call","mid_only":"mid"}}`)
|
||||
mid := insertJob("mid", caller.ID, "", `{"inputs":{"env":"leaf"}}`)
|
||||
mid := insertJob("mid", caller.ID, "", `{"inputs":{"shared":"from-mid","env":"leaf"}}`)
|
||||
leaf := insertJob("leaf", mid.ID, "", "")
|
||||
|
||||
dispatchRun := &actions_model.ActionRun{ID: runID, Event: "workflow_dispatch", EventPayload: `{"inputs":{"flag":"true","Shared":"from-dispatch"}}`}
|
||||
pushRun := &actions_model.ActionRun{ID: runID, Event: "push", EventPayload: `{}`}
|
||||
dispatchInputs := map[string]any{"flag": true, "shared": "from-mid", "env": "leaf"}
|
||||
|
||||
t.Run("dispatch inputs overlaid case-insensitively with the caller's with", func(t *testing.T) {
|
||||
inputs, err := getInputsForJob(ctx, dispatchRun, mid)
|
||||
t.Run("preloaded ancestors supply top-level dispatch inputs and overlay direct caller inputs case-insensitively", func(t *testing.T) {
|
||||
inputs, err := getInputsForJobWithAncestors(ctx, dispatchRun, leaf, []*actions_model.ActionRunJob{mid, caller})
|
||||
require.NoError(t, err)
|
||||
assert.Equal(t, map[string]any{"flag": true, "shared": "from-call", "mid_only": "mid"}, inputs)
|
||||
assert.Equal(t, dispatchInputs, inputs)
|
||||
})
|
||||
|
||||
t.Run("task context of a nested child keeps the older runners' form and carries the original event", func(t *testing.T) {
|
||||
@@ -63,13 +118,12 @@ func TestReusableChildInputs(t *testing.T) {
|
||||
"event": map[string]any{"inputs": map[string]any{"flag": "true", "Shared": "from-dispatch"}},
|
||||
}
|
||||
require.NoError(t, setCalledWorkflowContext(ctx, leaf, gitCtx))
|
||||
inputs := map[string]any{"flag": true, "Shared": "from-dispatch", "env": "leaf"}
|
||||
assert.Equal(t, "workflow_call", gitCtx["event_name"])
|
||||
assert.Equal(t, map[string]any{"inputs": inputs}, gitCtx["event"])
|
||||
assert.Equal(t, map[string]any{"inputs": dispatchInputs}, gitCtx["event"])
|
||||
assert.Equal(t, map[string]any{
|
||||
"original_event_name": "workflow_dispatch",
|
||||
"original_event_inputs": map[string]any{"flag": "true", "Shared": "from-dispatch"},
|
||||
"inputs": inputs,
|
||||
"inputs": dispatchInputs,
|
||||
}, gitCtx["gitea_workflow_call"])
|
||||
})
|
||||
|
||||
|
||||
@@ -195,16 +195,6 @@ func checkRunConcurrency(ctx context.Context, run *actions_model.ActionRun) (*jo
|
||||
if concurrentRunID == 0 {
|
||||
return nil
|
||||
}
|
||||
|
||||
concurrentRun, err := actions_model.GetRunByRepoAndID(ctx, run.RepoID, concurrentRunID)
|
||||
if err != nil {
|
||||
return fmt.Errorf("get concurrent run %d: %w", concurrentRunID, err)
|
||||
}
|
||||
// A run awaiting approval is not advanced by concurrency; ApproveRuns emits it once approved.
|
||||
if concurrentRun.NeedApproval {
|
||||
return nil
|
||||
}
|
||||
|
||||
result.RunIDsToReEmit = append(result.RunIDsToReEmit, concurrentRunID)
|
||||
return nil
|
||||
}
|
||||
@@ -399,7 +389,7 @@ func reloadCallersFinishedByChildren(ctx context.Context, runID int64, jobMap ma
|
||||
func cancelFailedMatrixSiblings(ctx context.Context, jobs actions_model.ActionJobList) ([]*actions_model.ActionRunJob, error) {
|
||||
var toCancel []*actions_model.ActionRunJob
|
||||
for _, failed := range jobs {
|
||||
if failed.Status != actions_model.StatusFailure || failed.ContinueOnError {
|
||||
if failed.Status != actions_model.StatusFailure || failed.ContinueOnError || failed.SourceTaskID != 0 { // fail-fast only reacts to failures of this attempt
|
||||
continue
|
||||
}
|
||||
siblings := slices.DeleteFunc(slices.Clone(jobs), func(sibling *actions_model.ActionRunJob) bool {
|
||||
@@ -529,7 +519,12 @@ func (r *jobStatusResolver) resolveCheckNeeds(id int64) (allDone, allSucceed boo
|
||||
|
||||
func updateBlockedJobStatus(ctx context.Context, job *actions_model.ActionRunJob, status actions_model.Status) error {
|
||||
job.Status = status
|
||||
if n, err := actions_model.UpdateRunJob(ctx, job, builder.Eq{"status": actions_model.StatusBlocked}, "status"); err != nil {
|
||||
columns := []string{"status"}
|
||||
if status.IsFailure() {
|
||||
job.Stopped = timeutil.TimeStampNow()
|
||||
columns = append(columns, "stopped")
|
||||
}
|
||||
if n, err := actions_model.UpdateRunJob(ctx, job, builder.Eq{"status": actions_model.StatusBlocked}, columns...); err != nil {
|
||||
return err
|
||||
} else if n != 1 {
|
||||
return fmt.Errorf("no affected for updating blocked job %v", job.ID)
|
||||
|
||||
@@ -341,6 +341,11 @@ jobs:
|
||||
got, err := r.Resolve(ctx)
|
||||
require.NoError(t, err)
|
||||
assert.Equal(t, want, got)
|
||||
for id, status := range want {
|
||||
if status.IsFailure() {
|
||||
assert.NotZero(t, unittest.AssertExistsAndLoadBean(t, &actions_model.ActionRunJob{ID: id}).Stopped)
|
||||
}
|
||||
}
|
||||
if tt.note != "" {
|
||||
summaries, err := actions_model.ListActionRunJobSummaries(ctx, 1, runID, attemptID, 0)
|
||||
require.NoError(t, err)
|
||||
@@ -357,11 +362,13 @@ func Test_cancelFailedMatrixSiblings(t *testing.T) {
|
||||
name string
|
||||
failFast bool
|
||||
continueOnError bool
|
||||
sourceTaskID int64
|
||||
wantCancelled bool
|
||||
}{
|
||||
{name: "fail fast cancels a queued combination", failFast: true, wantCancelled: true},
|
||||
{name: "disabled fail fast keeps a queued combination", failFast: false},
|
||||
{name: "continued failure keeps a queued combination", failFast: true, continueOnError: true},
|
||||
{name: "failure carried over by a rerun keeps a queued combination", failFast: true, sourceTaskID: 7},
|
||||
} {
|
||||
t.Run(test.name, func(t *testing.T) {
|
||||
ctx := t.Context()
|
||||
@@ -372,7 +379,7 @@ func Test_cancelFailedMatrixSiblings(t *testing.T) {
|
||||
_, err := db.Exec(ctx, "UPDATE `action_run` SET latest_attempt_id = ? WHERE id = ?", attempt.ID, run.ID)
|
||||
require.NoError(t, err)
|
||||
jobs := actions_model.ActionJobList{
|
||||
{RunID: run.ID, RunAttemptID: attempt.ID, RepoID: 1, OwnerID: 1, JobID: "matrix", Status: actions_model.StatusFailure, ContinueOnError: test.continueOnError, WorkflowPayload: fmt.Appendf(nil, "jobs: {matrix: {strategy: {fail-fast: %t}}}", test.failFast)},
|
||||
{RunID: run.ID, RunAttemptID: attempt.ID, RepoID: 1, OwnerID: 1, JobID: "matrix", Status: actions_model.StatusFailure, ContinueOnError: test.continueOnError, SourceTaskID: test.sourceTaskID, WorkflowPayload: fmt.Appendf(nil, "jobs: {matrix: {strategy: {fail-fast: %t}}}", test.failFast)},
|
||||
{RunID: run.ID, RunAttemptID: attempt.ID, RepoID: 1, OwnerID: 1, JobID: "matrix", Status: actions_model.StatusWaiting},
|
||||
}
|
||||
for _, job := range jobs {
|
||||
|
||||
@@ -191,11 +191,11 @@ jobs:
|
||||
steps:
|
||||
- run: echo hi
|
||||
`)}
|
||||
require.EqualError(t, insertCallerChildren(ctx, run, attempt, caller, "read", called, nil, nil),
|
||||
require.EqualError(t, insertCallerChildren(ctx, run, attempt, caller, "read", called, nil, nil, nil),
|
||||
"cache-mode: The nested job 'build' is requesting 'write-only', but is only allowed 'read'")
|
||||
require.EqualError(t, insertCallerChildren(ctx, run, attempt, caller, "write-only", called, nil, nil),
|
||||
require.EqualError(t, insertCallerChildren(ctx, run, attempt, caller, "write-only", called, nil, nil, nil),
|
||||
"cache-mode: The workflow is requesting 'read', but is only allowed 'write-only'")
|
||||
require.NoError(t, insertCallerChildren(ctx, run, attempt, caller, "", called, nil, nil))
|
||||
require.NoError(t, insertCallerChildren(ctx, run, attempt, caller, "", called, nil, nil, nil))
|
||||
|
||||
children := 0
|
||||
for _, job := range runJobs(t, run.ID, attempt.ID) {
|
||||
|
||||
+47
-35
@@ -124,6 +124,7 @@ type rerunPlan struct {
|
||||
templateAttempt *actions_model.ActionRunAttempt
|
||||
templateJobs actions_model.ActionJobList
|
||||
triggerUser *user_model.User
|
||||
rerunAll bool
|
||||
|
||||
// rerunAttemptJobIDs holds the AttemptJobIDs of jobs that will actually be re-run in the new attempt.
|
||||
// If a job here is a reusable caller, the whole subtree under it will be re-run.
|
||||
@@ -174,6 +175,7 @@ func buildRerunPlan(ctx context.Context, run *actions_model.ActionRun, triggerUs
|
||||
templateAttempt: templateAttempt,
|
||||
templateJobs: templateJobs,
|
||||
triggerUser: triggerUser,
|
||||
rerunAll: len(jobsToRerun) == 0,
|
||||
}
|
||||
|
||||
if err := plan.expandRerunJobIDs(jobsToRerun); err != nil {
|
||||
@@ -185,6 +187,34 @@ func buildRerunPlan(ctx context.Context, run *actions_model.ActionRun, triggerUs
|
||||
return plan, nil
|
||||
}
|
||||
|
||||
// The emitter decides `if:` once all needs have results, and is the only place expanding a deferred matrix.
|
||||
func resetJobForRerun(job *actions_model.ActionRunJob, shouldBlock bool) {
|
||||
job.Status = util.Iif(shouldBlock, actions_model.StatusBlocked, actions_model.StatusWaiting)
|
||||
if job.Status.IsWaiting() && len(job.Needs) > 0 {
|
||||
job.Status = actions_model.StatusPending
|
||||
}
|
||||
job.TaskID = 0
|
||||
job.SourceTaskID = 0
|
||||
job.Started = 0
|
||||
job.Stopped = 0
|
||||
job.ConcurrencyGroup = ""
|
||||
job.ConcurrencyCancel = false
|
||||
job.IsConcurrencyEvaluated = false
|
||||
|
||||
if job.IsReusableCaller {
|
||||
job.IsExpanded = false
|
||||
job.CallPayload = ""
|
||||
}
|
||||
}
|
||||
|
||||
// An ancestor caller of a rerun job runs again through its children, so its timing is cleared.
|
||||
func markJobPassThrough(job, templateJob *actions_model.ActionRunJob, isAncestor bool) {
|
||||
job.TaskID = 0
|
||||
job.SourceTaskID = templateJob.EffectiveTaskID()
|
||||
job.Started = util.Iif(isAncestor, 0, templateJob.Started)
|
||||
job.Stopped = util.Iif(isAncestor, 0, templateJob.Stopped)
|
||||
}
|
||||
|
||||
// execRerunPlan executes the rerun plan built by buildRerunPlan.
|
||||
// It loads run variables, constructs the new ActionRunAttempt and evaluates run-level concurrency (all outside the transaction to keep the tx short).
|
||||
// Inside a single database transaction it then inserts the new attempt, clones all template jobs, evaluates job-level concurrency for rerun jobs,
|
||||
@@ -283,60 +313,42 @@ func execRerunPlan(ctx context.Context, plan *rerunPlan) (*actions_model.ActionR
|
||||
newJob.ParentJobID = newParentID
|
||||
}
|
||||
|
||||
var invalidIf error
|
||||
var invalidErr error
|
||||
invalidKey := "if"
|
||||
if plan.rerunAttemptJobIDs.Contains(templateJob.AttemptJobID) {
|
||||
// the emitter decides `if:` once all needs have results, and is the only place expanding a deferred matrix
|
||||
newJob.Status = util.Iif(shouldBlock, actions_model.StatusBlocked, actions_model.StatusWaiting)
|
||||
if newJob.Status.IsWaiting() && len(newJob.Needs) > 0 {
|
||||
newJob.Status = actions_model.StatusPending
|
||||
}
|
||||
newJob.TaskID = 0
|
||||
newJob.SourceTaskID = 0
|
||||
newJob.Started = 0
|
||||
newJob.Stopped = 0
|
||||
newJob.ConcurrencyGroup = ""
|
||||
newJob.ConcurrencyCancel = false
|
||||
newJob.IsConcurrencyEvaluated = false
|
||||
|
||||
if templateJob.IsReusableCaller {
|
||||
newJob.IsExpanded = false
|
||||
newJob.CallPayload = ""
|
||||
resetJobForRerun(newJob, shouldBlock)
|
||||
if plan.rerunAll {
|
||||
newJob.ReusableWorkflowRef = ""
|
||||
}
|
||||
|
||||
invalidIf, err = decideJobIf(ctx, plan.run, newAttempt, newJob, vars)
|
||||
invalidErr, err = decideJobIf(ctx, plan.run, newAttempt, newJob, vars)
|
||||
if err != nil {
|
||||
return fmt.Errorf("evaluate job if: %w", err)
|
||||
}
|
||||
|
||||
// A slot-starved job must not cancel its group peers.
|
||||
if newJob.RawConcurrency != "" && newJob.Status == actions_model.StatusWaiting && slots.available(newJob) {
|
||||
if err := EvaluateJobConcurrencyFillModel(ctx, plan.run, newAttempt, newJob, vars, nil); err != nil {
|
||||
return fmt.Errorf("evaluate job concurrency: %w", err)
|
||||
}
|
||||
newJob.Status, jobsToCancel, err = PrepareToStartJobWithConcurrency(ctx, newJob)
|
||||
if newJob.Status == actions_model.StatusWaiting {
|
||||
jobsToCancel, runsOnErr, err := admitJob(ctx, newJob, slots, func() error { return invalidRunsOn(newJob) }, func() error {
|
||||
return EvaluateJobConcurrencyFillModel(ctx, plan.run, newAttempt, newJob, vars, nil)
|
||||
})
|
||||
if err != nil {
|
||||
return fmt.Errorf("prepare to start job with concurrency: %w", err)
|
||||
return err
|
||||
}
|
||||
if runsOnErr != nil {
|
||||
invalidKey, invalidErr = "runs-on", runsOnErr
|
||||
}
|
||||
cancelledConcurrencyJobs = append(cancelledConcurrencyJobs, jobsToCancel...)
|
||||
}
|
||||
|
||||
applyMaxParallel(newJob, slots)
|
||||
newJobsToRerun = append(newJobsToRerun, newJob)
|
||||
} else {
|
||||
newJob.TaskID = 0
|
||||
newJob.SourceTaskID = templateJob.EffectiveTaskID()
|
||||
|
||||
isAncestor := plan.ancestorAttemptJobIDs.Contains(templateJob.AttemptJobID)
|
||||
newJob.Started = util.Iif(isAncestor, 0, templateJob.Started)
|
||||
newJob.Stopped = util.Iif(isAncestor, 0, templateJob.Stopped)
|
||||
markJobPassThrough(newJob, templateJob, plan.ancestorAttemptJobIDs.Contains(templateJob.AttemptJobID))
|
||||
}
|
||||
|
||||
if err := db.Insert(ctx, newJob); err != nil {
|
||||
return err
|
||||
}
|
||||
templateIDToNewID[templateJob.ID] = newJob.ID
|
||||
if invalidIf != nil {
|
||||
if err := upsertJobErrorSummary(ctx, newJob, "if", invalidIf); err != nil {
|
||||
if invalidErr != nil {
|
||||
if err := upsertJobErrorSummary(ctx, newJob, invalidKey, invalidErr); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
|
||||
@@ -106,6 +106,42 @@ func TestCloneRunJobForAttempt(t *testing.T) {
|
||||
})
|
||||
}
|
||||
|
||||
func TestResetJobForRerun(t *testing.T) {
|
||||
newRanJob := func() *actions_model.ActionRunJob {
|
||||
return &actions_model.ActionRunJob{
|
||||
Status: actions_model.StatusSuccess, TaskID: 5, SourceTaskID: 4, Started: 10, Stopped: 20,
|
||||
ConcurrencyGroup: "g", ConcurrencyCancel: true, IsConcurrencyEvaluated: true,
|
||||
IsReusableCaller: true, IsExpanded: true, CallPayload: "{}",
|
||||
}
|
||||
}
|
||||
|
||||
job := newRanJob()
|
||||
resetJobForRerun(job, false)
|
||||
assert.Equal(t, &actions_model.ActionRunJob{Status: actions_model.StatusWaiting, IsReusableCaller: true}, job)
|
||||
|
||||
job = newRanJob()
|
||||
job.Needs = []string{"build"}
|
||||
resetJobForRerun(job, false)
|
||||
assert.Equal(t, actions_model.StatusPending, job.Status)
|
||||
|
||||
job = newRanJob()
|
||||
job.Needs = []string{"build"}
|
||||
resetJobForRerun(job, true)
|
||||
assert.Equal(t, actions_model.StatusBlocked, job.Status)
|
||||
}
|
||||
|
||||
func TestMarkJobPassThrough(t *testing.T) {
|
||||
template := &actions_model.ActionRunJob{TaskID: 7, Started: 10, Stopped: 20}
|
||||
|
||||
job := &actions_model.ActionRunJob{TaskID: 7}
|
||||
markJobPassThrough(job, template, false)
|
||||
assert.Equal(t, &actions_model.ActionRunJob{SourceTaskID: 7, Started: 10, Stopped: 20}, job)
|
||||
|
||||
job = &actions_model.ActionRunJob{TaskID: 7}
|
||||
markJobPassThrough(job, template, true)
|
||||
assert.Equal(t, &actions_model.ActionRunJob{SourceTaskID: 7}, job)
|
||||
}
|
||||
|
||||
func TestRerunValidation(t *testing.T) {
|
||||
runningRun := &actions_model.ActionRun{Status: actions_model.StatusRunning}
|
||||
|
||||
@@ -457,7 +493,7 @@ func TestCollectMatrixCollapse(t *testing.T) {
|
||||
})
|
||||
}
|
||||
|
||||
func TestRerunDecidesJobIf(t *testing.T) {
|
||||
func TestRerunDecidesJobIfAndValidatesRunsOn(t *testing.T) {
|
||||
require.NoError(t, unittest.PrepareTestDatabase())
|
||||
defer test.MockVariableValue(&EmitJobsIfReadyByRun, func(int64) error { return nil })()
|
||||
ctx := t.Context()
|
||||
@@ -474,19 +510,23 @@ jobs:
|
||||
- run: echo
|
||||
deploy:
|
||||
if: vars.DEPLOY == 'yes'
|
||||
runs-on: ubuntu-latest
|
||||
runs-on: ${{ vars.RUNNER }}
|
||||
concurrency:
|
||||
group: deploy
|
||||
cancel-in-progress: true
|
||||
steps:
|
||||
- run: echo
|
||||
`, false)
|
||||
jobs := map[string]*actions_model.ActionRunJob{}
|
||||
for _, job := range runJobs(t, run.ID, run.LatestAttemptID) {
|
||||
require.Equal(t, actions_model.StatusWaiting, job.Status)
|
||||
job.Status = actions_model.StatusSuccess
|
||||
_, err = actions_model.UpdateRunJob(ctx, job, nil, "status")
|
||||
require.NoError(t, err)
|
||||
jobs[job.JobID] = job
|
||||
}
|
||||
require.Equal(t, actions_model.StatusFailure, jobs["deploy"].Status)
|
||||
jobs["build"].Status = actions_model.StatusSuccess
|
||||
_, err = actions_model.UpdateRunJob(ctx, jobs["build"], nil, "status")
|
||||
require.NoError(t, err)
|
||||
run = unittest.AssertExistsAndLoadBean(t, &actions_model.ActionRun{ID: run.ID})
|
||||
holder := insertConcurrencyHolder(t, 9705, "deploy")
|
||||
|
||||
variable.Data = "no"
|
||||
_, err = actions_model.UpdateVariableCols(ctx, variable, "data")
|
||||
@@ -503,5 +543,19 @@ jobs:
|
||||
attempt = unittest.AssertExistsAndLoadBean(t, &actions_model.ActionRunAttempt{ID: attempt.ID})
|
||||
assert.Equal(t, actions_model.StatusSuccess, attempt.Status)
|
||||
assert.NotZero(t, attempt.Stopped)
|
||||
assert.Equal(t, actions_model.StatusSuccess, unittest.AssertExistsAndLoadBean(t, &actions_model.ActionRun{ID: run.ID}).Status)
|
||||
run = unittest.AssertExistsAndLoadBean(t, &actions_model.ActionRun{ID: run.ID})
|
||||
assert.Equal(t, actions_model.StatusSuccess, run.Status)
|
||||
|
||||
variable.Data = "yes"
|
||||
_, err = actions_model.UpdateVariableCols(ctx, variable, "data")
|
||||
require.NoError(t, err)
|
||||
attempt, err = RerunWorkflowRunJobs(ctx, repo, run, &user_model.User{ID: 1}, []*actions_model.ActionRunJob{rerunJobs["deploy"]})
|
||||
require.NoError(t, err)
|
||||
deploy := unittest.AssertExistsAndLoadBean(t, &actions_model.ActionRunJob{RunAttemptID: attempt.ID, JobID: "deploy"})
|
||||
assert.Equal(t, actions_model.StatusFailure, deploy.Status)
|
||||
assert.NotZero(t, deploy.Stopped)
|
||||
assert.Equal(t, actions_model.StatusRunning, unittest.AssertExistsAndLoadBean(t, &actions_model.ActionRunJob{ID: holder.ID}).Status)
|
||||
summary, err := actions_model.GetActionRunJobSummary(ctx, repo.ID, run.ID, attempt.ID, deploy.ID, 0)
|
||||
require.NoError(t, err)
|
||||
assert.Contains(t, summary.Content, "Error when evaluating `runs-on` for job `deploy`.")
|
||||
}
|
||||
@@ -4,6 +4,7 @@
|
||||
package actions
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"cmp"
|
||||
"context"
|
||||
"errors"
|
||||
@@ -35,8 +36,7 @@ import (
|
||||
"xorm.io/builder"
|
||||
)
|
||||
|
||||
// MaxReusableCallLevels counts ancestors of the deepest caller, leaving room for the caller and its callee.
|
||||
const MaxReusableCallLevels = model.MaxWorkflowCallDepth - 2
|
||||
const maxReusableCallerAncestors = model.MaxWorkflowCallDepth - 2 // Reserve one level for the caller and one for its callee.
|
||||
|
||||
// checkRunJobLimit rejects adding jobs that would push the attempt over actions_model.MaxJobNumPerRun.
|
||||
// checkCallerChain bounds nesting *depth*, but a reusable graph also fans out in *breadth*: without a
|
||||
@@ -104,7 +104,7 @@ func loadReusableWorkflowSource(ctx context.Context, run *actions_model.ActionRu
|
||||
}
|
||||
|
||||
// validateCalledWorkflows validates all workflows content calls, recursively.
|
||||
func validateCalledWorkflows(ctx context.Context, run *actions_model.ActionRun, content []byte) error {
|
||||
func validateCalledWorkflows(ctx context.Context, run *actions_model.ActionRun, rootContent []byte) error {
|
||||
validated := make(container.Set[string])
|
||||
var validate func([]byte, *actions_model.ActionRunJob, int, string) error
|
||||
validate = func(content []byte, source *actions_model.ActionRunJob, level int, callerCacheMode string) error {
|
||||
@@ -124,7 +124,7 @@ func validateCalledWorkflows(ctx context.Context, run *actions_model.ActionRun,
|
||||
if uses == "" {
|
||||
continue
|
||||
}
|
||||
if level > MaxReusableCallLevels {
|
||||
if level > maxReusableCallerAncestors {
|
||||
return errCallLevelExceeded(uses)
|
||||
}
|
||||
if !validated.Add(fmt.Sprintf("%d@%s:%s:%s", source.WorkflowSourceRepoID, source.WorkflowSourceCommitSHA, uses, jobCacheMode)) {
|
||||
@@ -138,6 +138,10 @@ func validateCalledWorkflows(ctx context.Context, run *actions_model.ActionRun,
|
||||
if err != nil {
|
||||
return fmt.Errorf("job %s: %w", id, err)
|
||||
}
|
||||
// the root has no caller row for the runtime check, and a same-commit file with its content repeats its calls
|
||||
if called.repoID == run.WorkflowRepoID && called.commitSHA == run.WorkflowCommitSHA && bytes.Equal(called.content, rootContent) {
|
||||
return fmt.Errorf("job %s: reusable workflow call cycle detected: %q", id, uses)
|
||||
}
|
||||
if _, err = jobparser.ValidateWorkflowStatic(called.content); err == nil {
|
||||
err = validate(called.content, &actions_model.ActionRunJob{WorkflowSourceRepoID: called.repoID, WorkflowSourceCommitSHA: called.commitSHA}, level+1, jobCacheMode)
|
||||
}
|
||||
@@ -147,7 +151,7 @@ func validateCalledWorkflows(ctx context.Context, run *actions_model.ActionRun,
|
||||
}
|
||||
return nil
|
||||
}
|
||||
return validate(content, &actions_model.ActionRunJob{WorkflowSourceRepoID: run.WorkflowRepoID, WorkflowSourceCommitSHA: run.WorkflowCommitSHA}, 0, "")
|
||||
return validate(rootContent, &actions_model.ActionRunJob{WorkflowSourceRepoID: run.WorkflowRepoID, WorkflowSourceCommitSHA: run.WorkflowCommitSHA}, 0, "")
|
||||
}
|
||||
|
||||
// checkSelfRepoStepExpressions rejects `$/` steps with expressions that runnerWorkflowPayload can't pin to the workflow's source.
|
||||
@@ -167,7 +171,7 @@ func checkSelfRepoStepExpressions(run *actions_model.ActionRun, source *actions_
|
||||
}
|
||||
|
||||
func errCallLevelExceeded(uses string) error {
|
||||
return fmt.Errorf("reusable workflow call exceeds the maximum nesting level of %d at %q", MaxReusableCallLevels, uses)
|
||||
return fmt.Errorf("reusable workflow call at %q exceeds the maximum of %d workflow levels, including the top-level caller", uses, model.MaxWorkflowCallDepth)
|
||||
}
|
||||
|
||||
// resolveSameRepoWorkflowSourceCommit returns the commit to read a same-repo reusable workflow from.
|
||||
@@ -218,41 +222,23 @@ func qualifyRef(ctx context.Context, repo *repo_model.Repository, gitRepo *git.R
|
||||
return sha
|
||||
}
|
||||
|
||||
// checkCallerChain walks `caller`'s ancestor chain (via ParentJobID) and:
|
||||
// - rejects cycles (caller.CallUses appearing in any ancestor's CallUses)
|
||||
// - enforces MaxReusableCallLevels on the number of ancestors above `caller`
|
||||
func checkCallerChain(ctx context.Context, caller *actions_model.ActionRunJob) error {
|
||||
if caller.ParentJobID == 0 {
|
||||
return nil // top-level caller: depth 0, no ancestors to walk
|
||||
}
|
||||
|
||||
// checkCallerChain walks the nearest ancestors first, so a cycle within the depth limit is reported before the depth error.
|
||||
func checkCallerChain(caller *actions_model.ActionRunJob, ancestors []*actions_model.ActionRunJob) error {
|
||||
visited := container.SetOf(canonicalCallUses(caller))
|
||||
|
||||
depth := 0
|
||||
current := caller
|
||||
for current.ParentJobID != 0 {
|
||||
next, err := actions_model.GetRunJobByRunAndID(ctx, current.RunID, current.ParentJobID)
|
||||
if err != nil {
|
||||
return fmt.Errorf("walk caller chain: %w", err)
|
||||
}
|
||||
current = next
|
||||
depth++
|
||||
if depth > MaxReusableCallLevels {
|
||||
for i, ancestor := range ancestors {
|
||||
if i == maxReusableCallerAncestors {
|
||||
return errCallLevelExceeded(caller.CallUses)
|
||||
}
|
||||
if current.IsReusableCaller && current.CallUses != "" && !visited.Add(canonicalCallUses(current)) {
|
||||
return fmt.Errorf("reusable workflow call cycle detected: %q", current.CallUses)
|
||||
if ancestor.IsReusableCaller && ancestor.CallUses != "" && !visited.Add(canonicalCallUses(ancestor)) {
|
||||
return fmt.Errorf("reusable workflow call cycle detected: %q", ancestor.CallUses)
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func checkResolvedCallerCycle(ctx context.Context, caller *actions_model.ActionRunJob, sourceRepoID int64, sourceCommitSHA, path string) error {
|
||||
for current := caller; current.ParentJobID != 0; {
|
||||
parent, err := actions_model.GetRunJobByRunAndID(ctx, current.RunID, current.ParentJobID)
|
||||
if err != nil {
|
||||
return fmt.Errorf("walk caller chain: %w", err)
|
||||
}
|
||||
func checkResolvedCallerCycle(ctx context.Context, caller *actions_model.ActionRunJob, ancestors []*actions_model.ActionRunJob, sourceRepoID int64, sourceCommitSHA, path string) error {
|
||||
current := caller
|
||||
for _, parent := range ancestors {
|
||||
ref, err := ResolveUses(ctx, parent.CallUses)
|
||||
if err != nil {
|
||||
return fmt.Errorf("resolve ancestor uses %q: %w", parent.CallUses, err)
|
||||
@@ -292,7 +278,11 @@ func expandReusableWorkflowCaller(ctx context.Context, run *actions_model.Action
|
||||
}
|
||||
|
||||
// 1. Cycle + depth check via the ParentJobID chain.
|
||||
if err := checkCallerChain(ctx, caller); err != nil {
|
||||
ancestors, err := actions_model.GetAncestorCallers(ctx, caller)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if err := checkCallerChain(caller, ancestors); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
@@ -307,11 +297,21 @@ func expandReusableWorkflowCaller(ctx context.Context, run *actions_model.Action
|
||||
if err != nil {
|
||||
return fmt.Errorf("resolve uses %q: %w", parsedJob.Uses, err)
|
||||
}
|
||||
priorChildren, err := actions_model.GetPriorAttemptChildrenByParent(ctx, run.ID, attempt.ID, caller.AttemptJobID)
|
||||
if err != nil {
|
||||
return fmt.Errorf("expandReusableWorkflowCaller: look up prior children of caller %d: %w", caller.ID, err)
|
||||
}
|
||||
var priorRef string
|
||||
if !ref.IsLocal() && caller.ReusableWorkflowRef != "" {
|
||||
if commitSHA := priorCalleeCommit(priorChildren); commitSHA != "" {
|
||||
ref.Ref, priorRef = commitSHA, caller.ReusableWorkflowRef
|
||||
}
|
||||
}
|
||||
source, err := loadReusableWorkflowSource(ctx, run, caller, ref)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if err := checkResolvedCallerCycle(ctx, caller, source.repoID, source.commitSHA, ref.Path); err != nil {
|
||||
if err := checkResolvedCallerCycle(ctx, caller, ancestors, source.repoID, source.commitSHA, ref.Path); err != nil {
|
||||
return err
|
||||
}
|
||||
if _, err := jobparser.ValidateWorkflowStatic(source.content); err != nil {
|
||||
@@ -356,7 +356,6 @@ func expandReusableWorkflowCaller(ctx context.Context, run *actions_model.Action
|
||||
caller.CallSecrets = string(mapBytes)
|
||||
}
|
||||
caller.ReusableWorkflowContent = source.content
|
||||
caller.ReusableWorkflowRef = source.ref
|
||||
|
||||
// 6. Evaluate caller's `with:`, then match against the callee schema.
|
||||
workflowCallInputs := map[string]any{}
|
||||
@@ -365,7 +364,7 @@ func expandReusableWorkflowCaller(ctx context.Context, run *actions_model.Action
|
||||
if err != nil {
|
||||
return fmt.Errorf("find caller needs: %w", err)
|
||||
}
|
||||
parentInputs, err := getInputsForJob(ctx, run, caller)
|
||||
parentInputs, err := getInputsForJobWithAncestors(ctx, run, caller, ancestors)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
@@ -375,7 +374,7 @@ func expandReusableWorkflowCaller(ctx context.Context, run *actions_model.Action
|
||||
return fmt.Errorf("caller %q inputs: %w", caller.JobID, err)
|
||||
}
|
||||
}
|
||||
jobInputs, err := calledWorkflowInputs(ctx, run, caller, workflowCallInputs)
|
||||
jobInputs, err := calledWorkflowInputs(ctx, run, caller, ancestors, workflowCallInputs)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
@@ -410,13 +409,14 @@ func expandReusableWorkflowCaller(ctx context.Context, run *actions_model.Action
|
||||
}
|
||||
|
||||
// 9. We own the expansion: insert the direct children.
|
||||
if err := insertCallerChildren(ctx, run, attempt, caller, cmp.Or(parsedJob.CacheMode, callerWorkflow.CacheMode), source, vars, jobInputs); err != nil {
|
||||
if err := insertCallerChildren(ctx, run, attempt, caller, cmp.Or(parsedJob.CacheMode, callerWorkflow.CacheMode), source, vars, jobInputs, priorChildren); err != nil {
|
||||
// On failure, undo the partial expansion so an error return always leaves the caller unexpanded and childless.
|
||||
return errors.Join(err, undoExpansion(ctx, caller))
|
||||
}
|
||||
|
||||
// 10. Persist the remaining caller metadata (the row is already ours via the claim above).
|
||||
caller.CallPayload = string(callPayload)
|
||||
caller.ReusableWorkflowRef = cmp.Or(priorRef, source.ref) // set after inserting children, they inherit a pin only from an already pinned caller
|
||||
if _, err := actions_model.UpdateRunJob(ctx, caller, nil, "call_secrets", "reusable_workflow_content", "reusable_workflow_ref", "call_payload"); err != nil {
|
||||
return errors.Join(fmt.Errorf("persist caller %d expansion metadata: %w", caller.ID, err), undoExpansion(ctx, caller))
|
||||
}
|
||||
@@ -424,7 +424,7 @@ func expandReusableWorkflowCaller(ctx context.Context, run *actions_model.Action
|
||||
}
|
||||
|
||||
// insertCallerChildren parses the called workflow with the caller's resolved inputs and inserts each parsed job.
|
||||
func insertCallerChildren(ctx context.Context, run *actions_model.ActionRun, attempt *actions_model.ActionRunAttempt, caller *actions_model.ActionRunJob, callerCacheMode string, source *reusableWorkflowSource, vars map[string]string, inputs map[string]any) error {
|
||||
func insertCallerChildren(ctx context.Context, run *actions_model.ActionRun, attempt *actions_model.ActionRunAttempt, caller *actions_model.ActionRunJob, callerCacheMode string, source *reusableWorkflowSource, vars map[string]string, inputs map[string]any, priorChildren map[string]map[string]*actions_model.ActionRunJob) error {
|
||||
callerPermissions := caller.TokenPermissions
|
||||
if callerPermissions == nil {
|
||||
actionsUnit, err := run.Repo.GetUnit(ctx, unit.TypeActions)
|
||||
@@ -459,11 +459,6 @@ func insertCallerChildren(ctx context.Context, run *actions_model.ActionRun, att
|
||||
return err
|
||||
}
|
||||
|
||||
priorChildren, err := actions_model.GetPriorAttemptChildrenByParent(ctx, run.ID, attempt.ID, caller.AttemptJobID)
|
||||
if err != nil {
|
||||
return fmt.Errorf("lookup prior-attempt children of caller %d: %w", caller.ID, err)
|
||||
}
|
||||
|
||||
for _, sw := range childWorkflows {
|
||||
jobID, parsedChild := sw.Job()
|
||||
if parsedChild == nil {
|
||||
@@ -486,8 +481,9 @@ func insertCallerChildren(ctx context.Context, run *actions_model.ActionRun, att
|
||||
|
||||
// AttemptJobID: prefer a prior-attempt match and fall back to a fresh allocator value for newly-appearing logical jobs.
|
||||
var attemptJobID int64
|
||||
if priorID, ok := priorAttemptJobID(priorChildren[jobID], parsedChild.Name, isMatrixDeferred); ok {
|
||||
attemptJobID = priorID
|
||||
prior := matchPriorChild(priorChildren[jobID], parsedChild.Name, isMatrixDeferred)
|
||||
if prior != nil {
|
||||
attemptJobID = prior.AttemptJobID
|
||||
} else {
|
||||
attemptJobID, err = actions_model.GetNextAttemptJobID(ctx, run.ID)
|
||||
if err != nil {
|
||||
@@ -528,6 +524,9 @@ func insertCallerChildren(ctx context.Context, run *actions_model.ActionRun, att
|
||||
if parsedChild.Uses != "" {
|
||||
child.IsReusableCaller = true
|
||||
child.CallUses = parsedChild.Uses
|
||||
if caller.ReusableWorkflowRef != "" && prior != nil {
|
||||
child.ReusableWorkflowRef = prior.ReusableWorkflowRef
|
||||
}
|
||||
}
|
||||
if parsedChild.RawConcurrency != nil {
|
||||
rawConcurrency, err := yaml.Marshal(parsedChild.RawConcurrency)
|
||||
@@ -594,20 +593,24 @@ func undoExpansion(ctx context.Context, caller *actions_model.ActionRunJob) erro
|
||||
return nil
|
||||
}
|
||||
|
||||
// priorAttemptJobID returns the AttemptJobID a re-inserted child should reuse,
|
||||
// given the prior attempt's rows of the same JobID indexed by Name.
|
||||
func priorAttemptJobID(priorSameJobID map[string]*actions_model.ActionRunJob, name string, isMatrixDeferred bool) (int64, bool) {
|
||||
// priorCalleeCommit returns the callee commit of the previous expansion, all its direct children share it.
|
||||
func priorCalleeCommit(priorChildren map[string]map[string]*actions_model.ActionRunJob) string {
|
||||
for _, jobs := range priorChildren {
|
||||
for _, child := range jobs {
|
||||
return child.WorkflowSourceCommitSHA
|
||||
}
|
||||
}
|
||||
return ""
|
||||
}
|
||||
|
||||
func matchPriorChild(priorSameJobID map[string]*actions_model.ActionRunJob, name string, isMatrixDeferred bool) *actions_model.ActionRunJob {
|
||||
if isMatrixDeferred {
|
||||
for _, prior := range priorSameJobID {
|
||||
if len(prior.DeferredMatrixPayload) > 0 {
|
||||
return prior.AttemptJobID, true
|
||||
return prior
|
||||
}
|
||||
}
|
||||
return 0, false
|
||||
return nil
|
||||
}
|
||||
prior, ok := priorSameJobID[name]
|
||||
if !ok {
|
||||
return 0, false
|
||||
}
|
||||
return prior.AttemptJobID, true
|
||||
return priorSameJobID[name]
|
||||
}
|
||||
@@ -22,82 +22,51 @@ import (
|
||||
"github.com/stretchr/testify/require"
|
||||
)
|
||||
|
||||
func TestCheckCallerChain_Cycle(t *testing.T) {
|
||||
func TestCheckCallerChain(t *testing.T) {
|
||||
levels := func(count int) []*actions_model.ActionRunJob {
|
||||
ancestors := make([]*actions_model.ActionRunJob, count)
|
||||
for i := range ancestors {
|
||||
ancestors[i] = &actions_model.ActionRunJob{IsReusableCaller: true, CallUses: fmt.Sprintf("./.gitea/workflows/level%d.yml", i+1)}
|
||||
}
|
||||
return ancestors
|
||||
}
|
||||
const called = "./.gitea/workflows/called.yml"
|
||||
cycleWithinLimit := levels(9)
|
||||
cycleWithinLimit[7].CallUses = called
|
||||
libCall := &actions_model.ActionRunJob{IsReusableCaller: true, CallUses: "owner/lib/.gitea/workflows/b.yml@v1"}
|
||||
|
||||
for _, testCase := range []struct {
|
||||
name string
|
||||
uses []string
|
||||
sourceRepoID int64
|
||||
error string
|
||||
name string
|
||||
caller *actions_model.ActionRunJob
|
||||
ancestors []*actions_model.ActionRunJob
|
||||
err string
|
||||
}{
|
||||
// A -> A: leaf's CallUses matches its direct parent's.
|
||||
{"DirectCycle", []string{"./.gitea/workflows/a.yml", "./.gitea/workflows/a.yml"}, 0, "cycle detected"},
|
||||
// A -> B -> A: leaf's CallUses matches its grandparent's.
|
||||
{"IndirectCycle", []string{"./.gitea/workflows/a.yml", "./.gitea/workflows/b.yml", "./.gitea/workflows/a.yml"}, 0, "cycle detected"},
|
||||
// A -> A written with both same-repo prefixes: they name the same file.
|
||||
{"MixedPrefixCycle", []string{"./.gitea/workflows/a.yml", "$/.gitea/workflows/a.yml"}, 0, "cycle detected"},
|
||||
// Sanity: linear chain with distinct CallUses must not trip cycle detection.
|
||||
{"NoCycle", []string{"./.gitea/workflows/a.yml", "./.gitea/workflows/b.yml", "./.gitea/workflows/c.yml"}, 0, ""},
|
||||
{"SameLocalPathInOtherRepo", []string{"./.gitea/workflows/a.yml", "owner/lib/.gitea/workflows/lib.yml@v1", "./.gitea/workflows/a.yml"}, 2, ""},
|
||||
{"LocalAliasInOtherSourceRepo", &actions_model.ActionRunJob{CallUses: "$/.gitea/workflows/a.yml", WorkflowSourceRepoID: 1}, []*actions_model.ActionRunJob{libCall, {IsReusableCaller: true, CallUses: "./.gitea/workflows/a.yml", WorkflowSourceRepoID: 2}}, ""},
|
||||
{"LocalAliasInSameSourceRepo", &actions_model.ActionRunJob{CallUses: "$/.gitea/workflows/a.yml", WorkflowSourceRepoID: 1}, []*actions_model.ActionRunJob{libCall, {IsReusableCaller: true, CallUses: "./.gitea/workflows/a.yml", WorkflowSourceRepoID: 1}}, "cycle detected"},
|
||||
{"SelfAlias", &actions_model.ActionRunJob{CallUses: "self:" + libCall.CallUses}, []*actions_model.ActionRunJob{libCall}, "cycle detected"},
|
||||
{"TenWorkflowLevels", &actions_model.ActionRunJob{CallUses: called}, levels(8), ""},
|
||||
{"ElevenWorkflowLevels", &actions_model.ActionRunJob{CallUses: called}, levels(9), `reusable workflow call at "./.gitea/workflows/called.yml" exceeds the maximum of 10 workflow levels, including the top-level caller`},
|
||||
{"CycleWithinLimitBeforeDepth", &actions_model.ActionRunJob{CallUses: called}, cycleWithinLimit, "cycle detected"},
|
||||
} {
|
||||
t.Run(testCase.name, func(t *testing.T) {
|
||||
require.NoError(t, unittest.PrepareTestDatabase())
|
||||
chain := buildCallerChain(t, testCase.uses...)
|
||||
leaf := chain[len(chain)-1]
|
||||
leaf.WorkflowSourceRepoID = testCase.sourceRepoID
|
||||
err := checkCallerChain(t.Context(), leaf)
|
||||
if testCase.error == "" {
|
||||
err := checkCallerChain(testCase.caller, testCase.ancestors)
|
||||
if testCase.err == "" {
|
||||
require.NoError(t, err)
|
||||
} else {
|
||||
assert.ErrorContains(t, err, testCase.error)
|
||||
}
|
||||
if testCase.name == "MixedPrefixCycle" {
|
||||
assert.Equal(t, canonicalCallUses(&actions_model.ActionRunJob{CallUses: "owner/repo/.gitea/workflows/a.yml@v1"}), canonicalCallUses(&actions_model.ActionRunJob{CallUses: "self:owner/repo/.gitea/workflows/a.yml@v1"}))
|
||||
assert.ErrorContains(t, err, testCase.err)
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
t.Run("ResolvedIdentityCycle", func(t *testing.T) {
|
||||
require.NoError(t, unittest.PrepareTestDatabase())
|
||||
chain := buildCallerChain(t,
|
||||
"./.gitea/workflows/a.yml",
|
||||
"owner/repo/.gitea/workflows/b.yml@v1",
|
||||
"owner/repo/.gitea/workflows/a.yml@v1",
|
||||
)
|
||||
chain[1].WorkflowSourceRepoID = 4
|
||||
chain[1].WorkflowSourceCommitSHA = "first-commit"
|
||||
_, err := actions_model.UpdateRunJob(t.Context(), chain[1], nil, "workflow_source_repo_id", "workflow_source_commit_sha")
|
||||
require.NoError(t, err)
|
||||
chain[2].WorkflowSourceRepoID = 5
|
||||
chain[2].WorkflowSourceCommitSHA = "second-commit"
|
||||
|
||||
require.NoError(t, checkCallerChain(t.Context(), chain[2]))
|
||||
require.ErrorContains(t, checkResolvedCallerCycle(t.Context(), chain[2], 4, "first-commit", ".gitea/workflows/a.yml"), "cycle detected")
|
||||
require.NoError(t, checkResolvedCallerCycle(t.Context(), chain[2], 4, "other-commit", ".gitea/workflows/a.yml"))
|
||||
})
|
||||
}
|
||||
|
||||
func TestCheckCallerChain_DepthLimit(t *testing.T) {
|
||||
// top + MaxReusableCallLevels nested callers is the longest accepted; one more exceeds the limit.
|
||||
makeDistinctUses := func(n int) []string {
|
||||
out := make([]string, n)
|
||||
for i := range out {
|
||||
out[i] = fmt.Sprintf("./.gitea/workflows/level%d.yml", i)
|
||||
}
|
||||
return out
|
||||
func TestCheckResolvedCallerCycle(t *testing.T) {
|
||||
caller := &actions_model.ActionRunJob{CallUses: "owner/repo/.gitea/workflows/a.yml@v1", WorkflowSourceRepoID: 5, WorkflowSourceCommitSHA: "second-commit"}
|
||||
ancestors := []*actions_model.ActionRunJob{
|
||||
{IsReusableCaller: true, CallUses: "owner/repo/.gitea/workflows/b.yml@v1", WorkflowSourceRepoID: 4, WorkflowSourceCommitSHA: "first-commit"},
|
||||
{IsReusableCaller: true, CallUses: "./.gitea/workflows/a.yml"},
|
||||
}
|
||||
|
||||
t.Run("ExactlyAtLimit", func(t *testing.T) {
|
||||
require.NoError(t, unittest.PrepareTestDatabase())
|
||||
chain := buildCallerChain(t, makeDistinctUses(MaxReusableCallLevels+1)...)
|
||||
require.NoError(t, checkCallerChain(t.Context(), chain[len(chain)-1]))
|
||||
})
|
||||
|
||||
t.Run("OneOverLimit", func(t *testing.T) {
|
||||
require.NoError(t, unittest.PrepareTestDatabase())
|
||||
chain := buildCallerChain(t, makeDistinctUses(MaxReusableCallLevels+2)...)
|
||||
err := checkCallerChain(t.Context(), chain[len(chain)-1])
|
||||
assert.ErrorContains(t, err, "exceeds the maximum nesting level")
|
||||
})
|
||||
assert.ErrorContains(t, checkResolvedCallerCycle(t.Context(), caller, ancestors, 4, "first-commit", ".gitea/workflows/a.yml"), "cycle detected")
|
||||
assert.NoError(t, checkResolvedCallerCycle(t.Context(), caller, ancestors, 4, "other-commit", ".gitea/workflows/a.yml"))
|
||||
}
|
||||
|
||||
// buildCallerChain inserts a linear chain of reusable caller jobs in a single run+attempt.
|
||||
|
||||
+25
-25
@@ -13,7 +13,6 @@ import (
|
||||
"gitea.dev/models/db"
|
||||
"gitea.dev/modules/actions/jobparser"
|
||||
"gitea.dev/modules/log"
|
||||
"gitea.dev/modules/timeutil"
|
||||
"gitea.dev/modules/util"
|
||||
|
||||
"go.yaml.in/yaml/v4"
|
||||
@@ -256,39 +255,40 @@ func insertRunJob(ctx context.Context, run *actions_model.ActionRun, runAttempt
|
||||
return nil, nil, false, fmt.Errorf("evaluate job if: %w", err)
|
||||
}
|
||||
invalidKey := "if"
|
||||
if runsOnProblem != "" && runJob.Status.IsWaiting() && slots.available(runJob) {
|
||||
invalidKey, invalidErr = "runs-on", errors.New(runsOnProblem)
|
||||
runJob.Status, runJob.Stopped = actions_model.StatusFailure, timeutil.TimeStampNow()
|
||||
}
|
||||
|
||||
var cancelledConcurrencyJobs []*actions_model.ActionRunJob
|
||||
// check job concurrency
|
||||
if job.RawConcurrency != nil {
|
||||
rawConcurrency, err := yaml.Marshal(job.RawConcurrency)
|
||||
if err != nil {
|
||||
return nil, nil, false, fmt.Errorf("marshal raw concurrency: %w", err)
|
||||
}
|
||||
runJob.RawConcurrency = string(rawConcurrency)
|
||||
|
||||
// a job enters its group at its gate, ApproveRuns gates an approval-blocked one with this evaluation
|
||||
if runJob.Status == actions_model.StatusWaiting && slots.available(runJob) || len(needs) == 0 && run.NeedApproval {
|
||||
if err := EvaluateJobConcurrencyFillModel(ctx, run, runAttempt, runJob, vars, inputs); err != nil {
|
||||
return nil, nil, false, fmt.Errorf("evaluate job concurrency: %w", err)
|
||||
}
|
||||
}
|
||||
|
||||
// A slot-starved job skips the check: it will not start, so it must not cancel its group peers.
|
||||
if runJob.Status == actions_model.StatusWaiting && slots.available(runJob) {
|
||||
var jobsToCancel []*actions_model.ActionRunJob
|
||||
runJob.Status, jobsToCancel, err = PrepareToStartJobWithConcurrency(ctx, runJob)
|
||||
if err != nil {
|
||||
return nil, nil, false, fmt.Errorf("prepare to start job with concurrency: %w", err)
|
||||
}
|
||||
cancelledConcurrencyJobs = append(cancelledConcurrencyJobs, jobsToCancel...)
|
||||
}
|
||||
}
|
||||
evaluateConcurrency := func() error {
|
||||
return EvaluateJobConcurrencyFillModel(ctx, run, runAttempt, runJob, vars, inputs)
|
||||
}
|
||||
|
||||
applyMaxParallel(runJob, slots)
|
||||
var cancelledConcurrencyJobs []*actions_model.ActionRunJob
|
||||
if runJob.Status == actions_model.StatusWaiting {
|
||||
checkRunsOn := func() error {
|
||||
if runsOnProblem != "" {
|
||||
return errors.New(runsOnProblem)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
jobsToCancel, runsOnErr, err := admitJob(ctx, runJob, slots, checkRunsOn, evaluateConcurrency)
|
||||
if err != nil {
|
||||
return nil, nil, false, err
|
||||
}
|
||||
if runsOnErr != nil {
|
||||
invalidKey, invalidErr = "runs-on", runsOnErr
|
||||
}
|
||||
cancelledConcurrencyJobs = jobsToCancel
|
||||
} else if runJob.RawConcurrency != "" && len(needs) == 0 && run.NeedApproval {
|
||||
// a job enters its group at its gate, ApproveRuns gates an approval-blocked one with this evaluation
|
||||
if err := evaluateConcurrency(); err != nil {
|
||||
return nil, nil, false, fmt.Errorf("evaluate job concurrency: %w", err)
|
||||
}
|
||||
}
|
||||
|
||||
if err := db.Insert(ctx, runJob); err != nil {
|
||||
return nil, nil, false, err
|
||||
|
||||
@@ -0,0 +1,588 @@
|
||||
// Copyright 2026 The Gitea Authors. All rights reserved.
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
package convert
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"maps"
|
||||
"net/url"
|
||||
"path"
|
||||
"slices"
|
||||
|
||||
runnerv1 "gitea.dev/actionslib/runner/v1"
|
||||
actions_model "gitea.dev/models/actions"
|
||||
"gitea.dev/models/db"
|
||||
issues_model "gitea.dev/models/issues"
|
||||
"gitea.dev/models/perm"
|
||||
access_model "gitea.dev/models/perm/access"
|
||||
repo_model "gitea.dev/models/repo"
|
||||
"gitea.dev/models/unit"
|
||||
"gitea.dev/modules/actions"
|
||||
"gitea.dev/modules/actions/jobparser"
|
||||
"gitea.dev/modules/container"
|
||||
"gitea.dev/modules/git"
|
||||
"gitea.dev/modules/httplib"
|
||||
"gitea.dev/modules/log"
|
||||
"gitea.dev/modules/setting"
|
||||
api "gitea.dev/modules/structs"
|
||||
"gitea.dev/modules/util"
|
||||
webhook_module "gitea.dev/modules/webhook"
|
||||
)
|
||||
|
||||
// ToActionTask convert an actions_model.ActionTask to an api.ActionTask
|
||||
func ToActionTask(ctx context.Context, t *actions_model.ActionTask) (*api.ActionTask, error) {
|
||||
// don't need Steps here, only need to load job and its run
|
||||
if err := t.LoadJob(ctx); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if err := t.Job.LoadRun(ctx); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if err := t.Job.Run.LoadRepo(ctx); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return &api.ActionTask{
|
||||
ID: t.ID,
|
||||
Name: t.Job.Name,
|
||||
HeadBranch: t.Job.Run.PrettyRef(),
|
||||
HeadSHA: t.Job.CommitSHA,
|
||||
RunNumber: t.Job.Run.Index,
|
||||
Event: t.Job.Run.TriggerEvent,
|
||||
DisplayTitle: t.Job.Run.Title,
|
||||
Status: t.Status.String(),
|
||||
WorkflowID: t.Job.Run.WorkflowID,
|
||||
URL: httplib.MakeAbsoluteURL(ctx, t.Job.Run.Link()),
|
||||
CreatedAt: t.Created.AsLocalTime(),
|
||||
UpdatedAt: t.Updated.AsLocalTime(),
|
||||
RunStartedAt: t.Started.AsLocalTime(),
|
||||
}, nil
|
||||
}
|
||||
|
||||
func ToActionWorkflowRun(ctx context.Context, run *actions_model.ActionRun, attempt *actions_model.ActionRunAttempt, excludePullRequests bool) (_ *api.ActionWorkflowRun, err error) {
|
||||
if err := run.LoadAttributes(ctx); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
if attempt == nil {
|
||||
attempt, _, err = run.GetLatestAttempt(ctx)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
}
|
||||
|
||||
runAttempt := int64(0)
|
||||
status, conclusion := ToRunActionsStatus(run, run.Status)
|
||||
startedAt := run.Started.AsLocalTime()
|
||||
completedAt := run.Stopped.AsLocalTime()
|
||||
actor := run.TriggerUser // The username of the user that triggered the initial workflow run.
|
||||
triggerUser := run.TriggerUser // The username of the user that initiated the workflow run. If the workflow run is a re-run, this value may differ from actor.
|
||||
|
||||
// previousAttemptURL is the value of ActionWorkflowRun.PreviousAttemptURL, which is declared as *string without `omitempty` on purpose:
|
||||
// a nil value must still appear in the JSON body as `"previous_attempt_url": null`, matching GitHub's Actions API.
|
||||
var previousAttemptURL *string
|
||||
|
||||
if attempt != nil {
|
||||
attempt.Run = run
|
||||
if err := attempt.LoadAttributes(ctx); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
runAttempt = attempt.Attempt
|
||||
status, conclusion = ToRunActionsStatus(run, attempt.Status)
|
||||
startedAt = attempt.Started.AsLocalTime()
|
||||
completedAt = attempt.Stopped.AsLocalTime()
|
||||
triggerUser = attempt.TriggerUser
|
||||
if attempt.Attempt > 1 {
|
||||
url := fmt.Sprintf("%s/attempts/%d", run.APIURL(ctx), attempt.Attempt-1)
|
||||
previousAttemptURL = &url
|
||||
}
|
||||
}
|
||||
pullRequests := []*api.PullRequestMinimal{}
|
||||
if !excludePullRequests {
|
||||
pullRequests, err = loadPullRequestsForRun(ctx, run)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
}
|
||||
|
||||
runURL := run.APIURL(ctx)
|
||||
return &api.ActionWorkflowRun{
|
||||
ID: run.ID,
|
||||
URL: runURL,
|
||||
PreviousAttemptURL: previousAttemptURL,
|
||||
HTMLURL: run.HTMLURL(ctx),
|
||||
JobsURL: runURL + "/jobs",
|
||||
LogsURL: runURL + "/logs",
|
||||
ArtifactsURL: runURL + "/artifacts",
|
||||
CancelURL: runURL + "/cancel",
|
||||
RerunURL: runURL + "/rerun",
|
||||
RunNumber: run.Index,
|
||||
RunAttempt: runAttempt,
|
||||
CreatedAt: run.Created.AsLocalTime(),
|
||||
UpdatedAt: run.Updated.AsLocalTime(),
|
||||
StartedAt: startedAt,
|
||||
CompletedAt: completedAt,
|
||||
Event: run.TriggerEvent,
|
||||
DisplayTitle: run.Title,
|
||||
HeadBranch: git.RefName(run.Ref).BranchName(),
|
||||
HeadSha: run.CommitSHA,
|
||||
Status: status,
|
||||
Conclusion: conclusion,
|
||||
Path: fmt.Sprintf("%s@%s", run.WorkflowID, run.Ref),
|
||||
Repository: ToRepo(ctx, run.Repo, access_model.Permission{AccessMode: perm.AccessModeNone}),
|
||||
TriggerActor: ToUser(ctx, triggerUser, nil),
|
||||
Actor: ToUser(ctx, actor, nil),
|
||||
PullRequests: pullRequests,
|
||||
}, nil
|
||||
}
|
||||
|
||||
// loadPullRequestsForRun returns the pull requests associated with a run, matching
|
||||
// GitHub's `pull_requests` field on workflow run responses:
|
||||
// - For pull_request / pull_request_review events, the PR whose ref triggered the run.
|
||||
// - For push events, open PRs whose head branch matches the pushed ref in the same repo.
|
||||
// - For other events, no PRs.
|
||||
func loadPullRequestsForRun(ctx context.Context, run *actions_model.ActionRun) ([]*api.PullRequestMinimal, error) {
|
||||
result := []*api.PullRequestMinimal{}
|
||||
refName := git.RefName(run.Ref)
|
||||
var prs issues_model.PullRequestList
|
||||
switch {
|
||||
case run.Event.IsPullRequest() || run.Event.IsPullRequestReview():
|
||||
index, ok := refName.PullIndex()
|
||||
if !ok {
|
||||
return result, nil
|
||||
}
|
||||
pr, err := issues_model.GetPullRequestByIndex(ctx, run.RepoID, index)
|
||||
if err != nil {
|
||||
if issues_model.IsErrPullRequestNotExist(err) {
|
||||
return result, nil
|
||||
}
|
||||
return nil, err
|
||||
}
|
||||
prs = issues_model.PullRequestList{pr}
|
||||
case run.Event == webhook_module.HookEventPush:
|
||||
branch := refName.BranchName()
|
||||
if branch == "" {
|
||||
return result, nil
|
||||
}
|
||||
var err error
|
||||
prs, err = issues_model.GetUnmergedPullRequestsByHeadInfo(ctx, run.RepoID, branch)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
default:
|
||||
return result, nil
|
||||
}
|
||||
for _, pr := range prs {
|
||||
minimal, err := toPullRequestMinimal(ctx, run.Repo, pr, run.CommitSHA)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
result = append(result, minimal)
|
||||
}
|
||||
return result, nil
|
||||
}
|
||||
|
||||
func toPullRequestMinimal(ctx context.Context, repo *repo_model.Repository, pr *issues_model.PullRequest, headSHA string) (*api.PullRequestMinimal, error) {
|
||||
if err := pr.LoadBaseRepo(ctx); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if err := pr.LoadHeadRepo(ctx); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
headRepo := pr.HeadRepo
|
||||
if headRepo == nil {
|
||||
headRepo = pr.BaseRepo
|
||||
}
|
||||
return &api.PullRequestMinimal{
|
||||
ID: pr.ID,
|
||||
Number: pr.Index,
|
||||
URL: fmt.Sprintf("%s/pulls/%d", repo.APIURL(ctx), pr.Index),
|
||||
Head: api.PullRequestMinimalHead{
|
||||
Ref: pr.HeadBranch,
|
||||
SHA: headSHA,
|
||||
Repo: api.PullRequestMinimalHeadRepo{
|
||||
ID: headRepo.ID,
|
||||
URL: headRepo.APIURL(ctx),
|
||||
Name: headRepo.Name,
|
||||
},
|
||||
},
|
||||
Base: api.PullRequestMinimalHead{
|
||||
Ref: pr.BaseBranch,
|
||||
SHA: pr.MergeBase,
|
||||
Repo: api.PullRequestMinimalHeadRepo{
|
||||
ID: pr.BaseRepo.ID,
|
||||
URL: pr.BaseRepo.APIURL(ctx),
|
||||
Name: pr.BaseRepo.Name,
|
||||
},
|
||||
},
|
||||
}, nil
|
||||
}
|
||||
|
||||
func ToWorkflowRunAction(status actions_model.Status) (action string) {
|
||||
switch status {
|
||||
case actions_model.StatusWaiting, actions_model.StatusBlocked:
|
||||
action = "requested"
|
||||
case actions_model.StatusRunning, actions_model.StatusCancelling:
|
||||
action = "in_progress"
|
||||
default:
|
||||
if status.IsDone() {
|
||||
action = "completed"
|
||||
} else {
|
||||
setting.PanicInDevOrTesting("unknown action status: %v", status)
|
||||
}
|
||||
}
|
||||
return action
|
||||
}
|
||||
|
||||
func ToRunActionsStatus(run *actions_model.ActionRun, status actions_model.Status) (action, conclusion string) {
|
||||
if status.IsBlocked() && run.NeedApproval {
|
||||
return "waiting", ""
|
||||
}
|
||||
return ToActionsStatus(status)
|
||||
}
|
||||
|
||||
func ToActionsStatus(status actions_model.Status) (action, conclusion string) {
|
||||
switch status {
|
||||
case actions_model.StatusWaiting:
|
||||
action = "queued"
|
||||
case actions_model.StatusBlocked:
|
||||
action = "pending"
|
||||
case actions_model.StatusPending:
|
||||
action = "requested"
|
||||
case actions_model.StatusRunning, actions_model.StatusCancelling:
|
||||
action = "in_progress"
|
||||
default:
|
||||
action = "completed"
|
||||
switch status {
|
||||
case actions_model.StatusSuccess:
|
||||
conclusion = "success"
|
||||
case actions_model.StatusCancelled:
|
||||
conclusion = "cancelled"
|
||||
case actions_model.StatusFailure:
|
||||
conclusion = "failure"
|
||||
case actions_model.StatusSkipped:
|
||||
conclusion = "skipped"
|
||||
default:
|
||||
setting.PanicInDevOrTesting("unknown action status: %v", status)
|
||||
}
|
||||
}
|
||||
return action, conclusion
|
||||
}
|
||||
|
||||
// ToActionWorkflowJob convert a actions_model.ActionRunJob to an api.ActionWorkflowJob
|
||||
// task is optional and can be nil
|
||||
func ToActionWorkflowJob(ctx context.Context, repo *repo_model.Repository, task *actions_model.ActionTask, job *actions_model.ActionRunJob) (*api.ActionWorkflowJob, error) {
|
||||
err := job.LoadAttributes(ctx)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
if effectiveTaskID := job.EffectiveTaskID(); effectiveTaskID != 0 {
|
||||
if task == nil {
|
||||
task, _, err = db.GetByID[actions_model.ActionTask](ctx, effectiveTaskID)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
}
|
||||
|
||||
if task != nil {
|
||||
if err := (actions_model.TaskList{task}).LoadSteps(ctx); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
}
|
||||
}
|
||||
return toActionWorkflowJob(ctx, repo, task, job), nil
|
||||
}
|
||||
|
||||
// ToActionWorkflowJobs requires job.Run.Repo to be loaded
|
||||
func ToActionWorkflowJobs(ctx context.Context, jobs []*actions_model.ActionRunJob) ([]*api.ActionWorkflowJob, error) {
|
||||
tasks, err := actions_model.GetTasksMapByIDs(ctx, container.FilterSlice(jobs, func(job *actions_model.ActionRunJob) (int64, bool) {
|
||||
taskID := job.EffectiveTaskID()
|
||||
return taskID, taskID != 0
|
||||
}))
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
taskList := actions_model.TaskList(slices.Collect(maps.Values(tasks)))
|
||||
if err := taskList.LoadSteps(ctx); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
result := make([]*api.ActionWorkflowJob, len(jobs))
|
||||
for i, job := range jobs {
|
||||
result[i] = toActionWorkflowJob(ctx, job.Run.Repo, tasks[job.EffectiveTaskID()], job)
|
||||
}
|
||||
return result, nil
|
||||
}
|
||||
|
||||
func toActionWorkflowJob(ctx context.Context, repo *repo_model.Repository, task *actions_model.ActionTask, job *actions_model.ActionRunJob) *api.ActionWorkflowJob {
|
||||
status, conclusion := ToRunActionsStatus(job.Run, job.Status)
|
||||
var runnerID int64
|
||||
var runnerName string
|
||||
var steps []*api.ActionWorkflowStep
|
||||
|
||||
if task != nil && job.EffectiveTaskID() != 0 {
|
||||
runnerID = task.RunnerID
|
||||
runnerName = task.RunnerName
|
||||
for i, step := range task.Steps {
|
||||
stepStatus, stepConclusion := ToActionsStatus(step.Status)
|
||||
steps = append(steps, &api.ActionWorkflowStep{
|
||||
Name: step.Name,
|
||||
Number: int64(i),
|
||||
Status: stepStatus,
|
||||
Conclusion: stepConclusion,
|
||||
StartedAt: step.Started.AsTime().UTC(),
|
||||
CompletedAt: step.Stopped.AsTime().UTC(),
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
return &api.ActionWorkflowJob{
|
||||
ID: job.ID,
|
||||
// missing api endpoint for this location
|
||||
URL: fmt.Sprintf("%s/actions/jobs/%d", repo.APIURL(ctx), job.ID),
|
||||
HTMLURL: fmt.Sprintf("%s/jobs/%d", job.Run.HTMLURL(ctx), job.ID),
|
||||
RunID: job.RunID,
|
||||
// Missing api endpoint for this location, artifacts are available under a nested url
|
||||
RunURL: fmt.Sprintf("%s/actions/runs/%d", repo.APIURL(ctx), job.RunID),
|
||||
Name: job.Name,
|
||||
Labels: job.RunsOn,
|
||||
RunAttempt: job.Attempt,
|
||||
HeadSha: job.Run.CommitSHA,
|
||||
HeadBranch: git.RefName(job.Run.Ref).BranchName(),
|
||||
Status: status,
|
||||
Conclusion: conclusion,
|
||||
RunnerID: runnerID,
|
||||
RunnerName: runnerName,
|
||||
Steps: util.SliceNilAsEmpty(steps),
|
||||
CreatedAt: job.Created.AsTime().UTC(),
|
||||
StartedAt: job.Started.AsTime().UTC(),
|
||||
CompletedAt: job.Stopped.AsTime().UTC(),
|
||||
}
|
||||
}
|
||||
|
||||
func getActionWorkflowEntry(ctx context.Context, repo *repo_model.Repository, gitRepo *git.Repository, commit *git.Commit, refName git.RefName, folder string, entry *git.TreeEntry) *api.ActionWorkflow {
|
||||
cfgUnit := repo.MustGetUnit(ctx, unit.TypeActions)
|
||||
cfg := cfgUnit.ActionsConfig()
|
||||
|
||||
workflowURL := fmt.Sprintf("%s/actions/workflows/%s", repo.APIURL(), util.PathEscapeSegments(entry.Name()))
|
||||
workflowRepoURL := fmt.Sprintf("%s/src/commit/%s/%s/%s", repo.HTMLURL(ctx), commit.ID.String(), util.PathEscapeSegments(folder), util.PathEscapeSegments(entry.Name()))
|
||||
if refWebLinkPath := refName.RefWebLinkPath(); refWebLinkPath != "" {
|
||||
workflowRepoURL = fmt.Sprintf("%s/src/%s/%s/%s", repo.HTMLURL(ctx), refWebLinkPath, util.PathEscapeSegments(folder), util.PathEscapeSegments(entry.Name()))
|
||||
}
|
||||
badgeURL := fmt.Sprintf("%s/actions/workflows/%s/badge.svg?branch=%s", repo.HTMLURL(ctx), util.PathEscapeSegments(entry.Name()), url.QueryEscape(repo.DefaultBranch))
|
||||
|
||||
// See https://docs.github.com/en/rest/actions/workflows?apiVersion=2022-11-28#get-a-workflow
|
||||
// State types:
|
||||
// - active
|
||||
// - deleted
|
||||
// - disabled_fork
|
||||
// - disabled_inactivity
|
||||
// - disabled_manually
|
||||
state := "active"
|
||||
if cfg.IsWorkflowDisabled(entry.Name()) {
|
||||
state = "disabled_manually"
|
||||
}
|
||||
|
||||
// The CreatedAt and UpdatedAt fields currently reflect the timestamp of the latest commit, which can later be refined
|
||||
// by retrieving the first and last commits for the file history. The first commit would indicate the creation date,
|
||||
// while the last commit would represent the modification date. The DeletedAt could be determined by identifying
|
||||
// the last commit where the file existed. However, this implementation has not been done here yet, as it would likely
|
||||
// cause a significant performance degradation.
|
||||
createdAt := commit.Author.When
|
||||
updatedAt := commit.Author.When
|
||||
|
||||
content, err := actions.GetContentFromEntry(ctx, gitRepo, entry)
|
||||
name := entry.Name()
|
||||
if err == nil {
|
||||
workflow, err := jobparser.ReadWorkflow(content)
|
||||
if err == nil {
|
||||
// Only use the name when specified in the workflow file
|
||||
if workflow.Name != "" {
|
||||
name = workflow.Name
|
||||
}
|
||||
} else {
|
||||
log.Error("getActionWorkflowEntry: Failed to parse workflow: %v", err)
|
||||
}
|
||||
} else {
|
||||
log.Error("getActionWorkflowEntry: Failed to get content from entry: %v", err)
|
||||
}
|
||||
|
||||
return &api.ActionWorkflow{
|
||||
ID: entry.Name(),
|
||||
Name: name,
|
||||
Path: path.Join(folder, entry.Name()),
|
||||
State: state,
|
||||
CreatedAt: createdAt,
|
||||
UpdatedAt: updatedAt,
|
||||
URL: workflowURL,
|
||||
HTMLURL: workflowRepoURL,
|
||||
BadgeURL: badgeURL,
|
||||
}
|
||||
}
|
||||
|
||||
func ListActionWorkflows(ctx context.Context, gitrepo *git.Repository, repo *repo_model.Repository) ([]*api.ActionWorkflow, error) {
|
||||
defaultBranchCommit, err := gitrepo.GetBranchCommit(ctx, repo.DefaultBranch)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
folder, entries, err := actions.ListWorkflows(ctx, gitrepo, defaultBranchCommit)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
workflows := make([]*api.ActionWorkflow, len(entries))
|
||||
for i, entry := range entries {
|
||||
workflows[i] = getActionWorkflowEntry(ctx, repo, gitrepo, defaultBranchCommit, git.RefNameFromBranch(repo.DefaultBranch), folder, entry)
|
||||
}
|
||||
|
||||
return workflows, nil
|
||||
}
|
||||
|
||||
func GetActionWorkflow(ctx context.Context, gitRepo *git.Repository, repo *repo_model.Repository, workflowID string) (*api.ActionWorkflow, error) {
|
||||
defaultBranchCommit, err := gitRepo.GetBranchCommit(ctx, repo.DefaultBranch)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
return getActionWorkflowFromCommit(ctx, repo, gitRepo, defaultBranchCommit, git.RefNameFromBranch(repo.DefaultBranch), workflowID)
|
||||
}
|
||||
|
||||
func GetActionWorkflowByRef(ctx context.Context, gitrepo *git.Repository, repo *repo_model.Repository, workflowID string, ref git.RefName) (*api.ActionWorkflow, error) {
|
||||
if ref == "" {
|
||||
return nil, util.NewNotExistErrorf("workflow %q not found", workflowID)
|
||||
}
|
||||
|
||||
refCommitID, err := gitrepo.GetRefCommitID(ctx, ref.String())
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
refCommit, err := gitrepo.GetCommit(ctx, refCommitID)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
return getActionWorkflowFromCommit(ctx, repo, gitrepo, refCommit, ref, workflowID)
|
||||
}
|
||||
|
||||
func getActionWorkflowFromCommit(ctx context.Context, repo *repo_model.Repository, gitRepo *git.Repository, commit *git.Commit, refName git.RefName, workflowID string) (*api.ActionWorkflow, error) {
|
||||
folder, entries, err := actions.ListWorkflows(ctx, gitRepo, commit)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
for _, entry := range entries {
|
||||
if entry.Name() == workflowID {
|
||||
return getActionWorkflowEntry(ctx, repo, gitRepo, commit, refName, folder, entry), nil
|
||||
}
|
||||
}
|
||||
|
||||
return nil, util.NewNotExistErrorf("workflow %q not found", workflowID)
|
||||
}
|
||||
|
||||
// GetScopedActionWorkflow resolves a scoped workflow definition (under SCOPED_WORKFLOW_DIRS) from the source repo at commitSHA.
|
||||
func GetScopedActionWorkflow(ctx context.Context, sourceGitRepo *git.Repository, sourceRepo *repo_model.Repository, workflowID, commitSHA string) (*api.ActionWorkflow, error) {
|
||||
commit, err := sourceGitRepo.GetCommit(ctx, commitSHA)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
folder, entries, err := actions.ListScopedWorkflows(ctx, sourceGitRepo, commit)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
for _, entry := range entries {
|
||||
if entry.Name() == workflowID {
|
||||
// An empty ref pins HTMLURL to commit (the run's WorkflowCommitSHA) rather than the moving default branch.
|
||||
wf := getActionWorkflowEntry(ctx, sourceRepo, sourceGitRepo, commit, "", folder, entry)
|
||||
// TODO: a scoped workflow has no repo-level representation on the source: the workflow API scans WORKFLOW_DIRS (not SCOPED_WORKFLOW_DIRS),
|
||||
// and the badge only reflects the source's repo-level runs, so neither link resolves a scoped workflow.
|
||||
// Blank them for now and populate once a scoped-aware workflow/badge endpoint exists.
|
||||
wf.URL = ""
|
||||
wf.BadgeURL = ""
|
||||
return wf, nil
|
||||
}
|
||||
}
|
||||
|
||||
return nil, util.NewNotExistErrorf("scoped workflow %q not found", workflowID)
|
||||
}
|
||||
|
||||
// ResolveActionWorkflowForRun returns the api.ActionWorkflow describing a run's workflow definition.
|
||||
// For a scoped run the definition lives in the source repo (run.WorkflowRepoID @ run.WorkflowCommitSHA) under SCOPED_WORKFLOW_DIRS,
|
||||
// not in the consuming repo, so it is resolved against the source repo.
|
||||
func ResolveActionWorkflowForRun(ctx context.Context, repo *repo_model.Repository, run *actions_model.ActionRun) (*api.ActionWorkflow, error) {
|
||||
if run.IsScopedRun {
|
||||
sourceRepo, err := repo_model.GetRepositoryByID(ctx, run.WorkflowRepoID)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
sourceGitRepo, err := git.OpenRepository(ctx, sourceRepo)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
defer sourceGitRepo.Close()
|
||||
return GetScopedActionWorkflow(ctx, sourceGitRepo, sourceRepo, run.WorkflowID, run.WorkflowCommitSHA)
|
||||
}
|
||||
|
||||
gitRepo, err := git.OpenRepository(ctx, repo)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
defer gitRepo.Close()
|
||||
|
||||
convertedWorkflow, err := GetActionWorkflowByRef(ctx, gitRepo, repo, run.WorkflowID, git.RefName(run.Ref))
|
||||
if err != nil && errors.Is(err, util.ErrNotExist) {
|
||||
convertedWorkflow, err = GetActionWorkflow(ctx, gitRepo, repo, run.WorkflowID)
|
||||
}
|
||||
return convertedWorkflow, err
|
||||
}
|
||||
|
||||
// ToActionArtifact convert a actions_model.ActionArtifact to an api.ActionArtifact
|
||||
func ToActionArtifact(repo *repo_model.Repository, art *actions_model.ActionArtifact) *api.ActionArtifact {
|
||||
url := fmt.Sprintf("%s/actions/artifacts/%d", repo.APIURL(), art.ID)
|
||||
|
||||
return &api.ActionArtifact{
|
||||
ID: art.ID,
|
||||
Name: art.ArtifactName,
|
||||
SizeInBytes: art.FileSize,
|
||||
Expired: art.Status == actions_model.ArtifactStatusExpired,
|
||||
URL: url,
|
||||
ArchiveDownloadURL: url + "/zip",
|
||||
CreatedAt: art.CreatedUnix.AsLocalTime(),
|
||||
UpdatedAt: art.UpdatedUnix.AsLocalTime(),
|
||||
ExpiresAt: art.ExpiredUnix.AsLocalTime(),
|
||||
WorkflowRun: &api.ActionWorkflowRun{
|
||||
ID: art.RunID,
|
||||
RepositoryID: art.RepoID,
|
||||
HeadSha: art.CommitSHA,
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
func ToActionRunner(runner *actions_model.ActionRunner) *api.ActionRunner {
|
||||
status := runner.Status()
|
||||
apiStatus := "offline"
|
||||
if runner.IsOnline() {
|
||||
apiStatus = "online"
|
||||
}
|
||||
labels := make([]*api.ActionRunnerLabel, len(runner.AgentLabels))
|
||||
for i, label := range runner.AgentLabels {
|
||||
labels[i] = &api.ActionRunnerLabel{
|
||||
ID: int64(i),
|
||||
Name: label,
|
||||
Type: "custom",
|
||||
}
|
||||
}
|
||||
return &api.ActionRunner{
|
||||
ID: runner.ID,
|
||||
Name: runner.Name,
|
||||
Status: apiStatus,
|
||||
Busy: status == runnerv1.RunnerStatus_RUNNER_STATUS_ACTIVE,
|
||||
Disabled: runner.IsDisabled,
|
||||
Ephemeral: runner.Ephemeral,
|
||||
Labels: labels,
|
||||
}
|
||||
}
|
||||
@@ -6,20 +6,15 @@ package convert
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"maps"
|
||||
"net/url"
|
||||
"path"
|
||||
"slices"
|
||||
"strconv"
|
||||
"time"
|
||||
|
||||
runnerv1 "gitea.dev/actionslib/runner/v1"
|
||||
actions_model "gitea.dev/models/actions"
|
||||
asymkey_model "gitea.dev/models/asymkey"
|
||||
"gitea.dev/models/auth"
|
||||
"gitea.dev/models/db"
|
||||
deploykey_model "gitea.dev/models/deploykey"
|
||||
git_model "gitea.dev/models/git"
|
||||
issues_model "gitea.dev/models/issues"
|
||||
@@ -29,16 +24,12 @@ import (
|
||||
repo_model "gitea.dev/models/repo"
|
||||
"gitea.dev/models/unit"
|
||||
user_model "gitea.dev/models/user"
|
||||
"gitea.dev/modules/actions"
|
||||
"gitea.dev/modules/actions/jobparser"
|
||||
"gitea.dev/modules/container"
|
||||
"gitea.dev/modules/git"
|
||||
"gitea.dev/modules/httplib"
|
||||
"gitea.dev/modules/log"
|
||||
"gitea.dev/modules/setting"
|
||||
api "gitea.dev/modules/structs"
|
||||
"gitea.dev/modules/util"
|
||||
webhook_module "gitea.dev/modules/webhook"
|
||||
asymkey_service "gitea.dev/services/asymkey"
|
||||
"gitea.dev/services/gitdiff"
|
||||
)
|
||||
@@ -255,561 +246,6 @@ func ToTag(repo *repo_model.Repository, t *git.Tag) *api.Tag {
|
||||
}
|
||||
}
|
||||
|
||||
// ToActionTask convert an actions_model.ActionTask to an api.ActionTask
|
||||
func ToActionTask(ctx context.Context, t *actions_model.ActionTask) (*api.ActionTask, error) {
|
||||
// don't need Steps here, only need to load job and its run
|
||||
if err := t.LoadJob(ctx); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if err := t.Job.LoadRun(ctx); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if err := t.Job.Run.LoadRepo(ctx); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return &api.ActionTask{
|
||||
ID: t.ID,
|
||||
Name: t.Job.Name,
|
||||
HeadBranch: t.Job.Run.PrettyRef(),
|
||||
HeadSHA: t.Job.CommitSHA,
|
||||
RunNumber: t.Job.Run.Index,
|
||||
Event: t.Job.Run.TriggerEvent,
|
||||
DisplayTitle: t.Job.Run.Title,
|
||||
Status: t.Status.String(),
|
||||
WorkflowID: t.Job.Run.WorkflowID,
|
||||
URL: httplib.MakeAbsoluteURL(ctx, t.Job.Run.Link()),
|
||||
CreatedAt: t.Created.AsLocalTime(),
|
||||
UpdatedAt: t.Updated.AsLocalTime(),
|
||||
RunStartedAt: t.Started.AsLocalTime(),
|
||||
}, nil
|
||||
}
|
||||
|
||||
func ToActionWorkflowRun(ctx context.Context, run *actions_model.ActionRun, attempt *actions_model.ActionRunAttempt, excludePullRequests bool) (_ *api.ActionWorkflowRun, err error) {
|
||||
if err := run.LoadAttributes(ctx); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
if attempt == nil {
|
||||
attempt, _, err = run.GetLatestAttempt(ctx)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
}
|
||||
|
||||
runAttempt := int64(0)
|
||||
status, conclusion := ToRunActionsStatus(run, run.Status)
|
||||
startedAt := run.Started.AsLocalTime()
|
||||
completedAt := run.Stopped.AsLocalTime()
|
||||
actor := run.TriggerUser // The username of the user that triggered the initial workflow run.
|
||||
triggerUser := run.TriggerUser // The username of the user that initiated the workflow run. If the workflow run is a re-run, this value may differ from actor.
|
||||
|
||||
// previousAttemptURL is the value of ActionWorkflowRun.PreviousAttemptURL, which is declared as *string without `omitempty` on purpose:
|
||||
// a nil value must still appear in the JSON body as `"previous_attempt_url": null`, matching GitHub's Actions API.
|
||||
var previousAttemptURL *string
|
||||
|
||||
if attempt != nil {
|
||||
attempt.Run = run
|
||||
if err := attempt.LoadAttributes(ctx); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
runAttempt = attempt.Attempt
|
||||
status, conclusion = ToRunActionsStatus(run, attempt.Status)
|
||||
startedAt = attempt.Started.AsLocalTime()
|
||||
completedAt = attempt.Stopped.AsLocalTime()
|
||||
triggerUser = attempt.TriggerUser
|
||||
if attempt.Attempt > 1 {
|
||||
url := fmt.Sprintf("%s/attempts/%d", run.APIURL(ctx), attempt.Attempt-1)
|
||||
previousAttemptURL = &url
|
||||
}
|
||||
}
|
||||
pullRequests := []*api.PullRequestMinimal{}
|
||||
if !excludePullRequests {
|
||||
pullRequests, err = loadPullRequestsForRun(ctx, run)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
}
|
||||
|
||||
runURL := run.APIURL(ctx)
|
||||
return &api.ActionWorkflowRun{
|
||||
ID: run.ID,
|
||||
URL: runURL,
|
||||
PreviousAttemptURL: previousAttemptURL,
|
||||
HTMLURL: run.HTMLURL(ctx),
|
||||
JobsURL: runURL + "/jobs",
|
||||
LogsURL: runURL + "/logs",
|
||||
ArtifactsURL: runURL + "/artifacts",
|
||||
CancelURL: runURL + "/cancel",
|
||||
RerunURL: runURL + "/rerun",
|
||||
RunNumber: run.Index,
|
||||
RunAttempt: runAttempt,
|
||||
CreatedAt: run.Created.AsLocalTime(),
|
||||
UpdatedAt: run.Updated.AsLocalTime(),
|
||||
StartedAt: startedAt,
|
||||
CompletedAt: completedAt,
|
||||
Event: run.TriggerEvent,
|
||||
DisplayTitle: run.Title,
|
||||
HeadBranch: git.RefName(run.Ref).BranchName(),
|
||||
HeadSha: run.CommitSHA,
|
||||
Status: status,
|
||||
Conclusion: conclusion,
|
||||
Path: fmt.Sprintf("%s@%s", run.WorkflowID, run.Ref),
|
||||
Repository: ToRepo(ctx, run.Repo, access_model.Permission{AccessMode: perm.AccessModeNone}),
|
||||
TriggerActor: ToUser(ctx, triggerUser, nil),
|
||||
Actor: ToUser(ctx, actor, nil),
|
||||
PullRequests: pullRequests,
|
||||
}, nil
|
||||
}
|
||||
|
||||
// loadPullRequestsForRun returns the pull requests associated with a run, matching
|
||||
// GitHub's `pull_requests` field on workflow run responses:
|
||||
// - For pull_request / pull_request_review events, the PR whose ref triggered the run.
|
||||
// - For push events, open PRs whose head branch matches the pushed ref in the same repo.
|
||||
// - For other events, no PRs.
|
||||
func loadPullRequestsForRun(ctx context.Context, run *actions_model.ActionRun) ([]*api.PullRequestMinimal, error) {
|
||||
result := []*api.PullRequestMinimal{}
|
||||
refName := git.RefName(run.Ref)
|
||||
var prs issues_model.PullRequestList
|
||||
switch {
|
||||
case run.Event.IsPullRequest() || run.Event.IsPullRequestReview():
|
||||
index, ok := refName.PullIndex()
|
||||
if !ok {
|
||||
return result, nil
|
||||
}
|
||||
pr, err := issues_model.GetPullRequestByIndex(ctx, run.RepoID, index)
|
||||
if err != nil {
|
||||
if issues_model.IsErrPullRequestNotExist(err) {
|
||||
return result, nil
|
||||
}
|
||||
return nil, err
|
||||
}
|
||||
prs = issues_model.PullRequestList{pr}
|
||||
case run.Event == webhook_module.HookEventPush:
|
||||
branch := refName.BranchName()
|
||||
if branch == "" {
|
||||
return result, nil
|
||||
}
|
||||
var err error
|
||||
prs, err = issues_model.GetUnmergedPullRequestsByHeadInfo(ctx, run.RepoID, branch)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
default:
|
||||
return result, nil
|
||||
}
|
||||
for _, pr := range prs {
|
||||
minimal, err := toPullRequestMinimal(ctx, run.Repo, pr, run.CommitSHA)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
result = append(result, minimal)
|
||||
}
|
||||
return result, nil
|
||||
}
|
||||
|
||||
func toPullRequestMinimal(ctx context.Context, repo *repo_model.Repository, pr *issues_model.PullRequest, headSHA string) (*api.PullRequestMinimal, error) {
|
||||
if err := pr.LoadBaseRepo(ctx); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if err := pr.LoadHeadRepo(ctx); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
headRepo := pr.HeadRepo
|
||||
if headRepo == nil {
|
||||
headRepo = pr.BaseRepo
|
||||
}
|
||||
return &api.PullRequestMinimal{
|
||||
ID: pr.ID,
|
||||
Number: pr.Index,
|
||||
URL: fmt.Sprintf("%s/pulls/%d", repo.APIURL(ctx), pr.Index),
|
||||
Head: api.PullRequestMinimalHead{
|
||||
Ref: pr.HeadBranch,
|
||||
SHA: headSHA,
|
||||
Repo: api.PullRequestMinimalHeadRepo{
|
||||
ID: headRepo.ID,
|
||||
URL: headRepo.APIURL(ctx),
|
||||
Name: headRepo.Name,
|
||||
},
|
||||
},
|
||||
Base: api.PullRequestMinimalHead{
|
||||
Ref: pr.BaseBranch,
|
||||
SHA: pr.MergeBase,
|
||||
Repo: api.PullRequestMinimalHeadRepo{
|
||||
ID: pr.BaseRepo.ID,
|
||||
URL: pr.BaseRepo.APIURL(ctx),
|
||||
Name: pr.BaseRepo.Name,
|
||||
},
|
||||
},
|
||||
}, nil
|
||||
}
|
||||
|
||||
func ToWorkflowRunAction(status actions_model.Status) (action string) {
|
||||
switch status {
|
||||
case actions_model.StatusWaiting, actions_model.StatusBlocked:
|
||||
action = "requested"
|
||||
case actions_model.StatusRunning, actions_model.StatusCancelling:
|
||||
action = "in_progress"
|
||||
default:
|
||||
if status.IsDone() {
|
||||
action = "completed"
|
||||
} else {
|
||||
setting.PanicInDevOrTesting("unknown action status: %v", status)
|
||||
}
|
||||
}
|
||||
return action
|
||||
}
|
||||
|
||||
func ToRunActionsStatus(run *actions_model.ActionRun, status actions_model.Status) (action, conclusion string) {
|
||||
if status.IsBlocked() && run.NeedApproval {
|
||||
return "waiting", ""
|
||||
}
|
||||
return ToActionsStatus(status)
|
||||
}
|
||||
|
||||
func ToActionsStatus(status actions_model.Status) (action, conclusion string) {
|
||||
switch status {
|
||||
case actions_model.StatusWaiting:
|
||||
action = "queued"
|
||||
case actions_model.StatusBlocked:
|
||||
action = "pending"
|
||||
case actions_model.StatusPending:
|
||||
action = "requested"
|
||||
case actions_model.StatusRunning, actions_model.StatusCancelling:
|
||||
action = "in_progress"
|
||||
default:
|
||||
action = "completed"
|
||||
switch status {
|
||||
case actions_model.StatusSuccess:
|
||||
conclusion = "success"
|
||||
case actions_model.StatusCancelled:
|
||||
conclusion = "cancelled"
|
||||
case actions_model.StatusFailure:
|
||||
conclusion = "failure"
|
||||
case actions_model.StatusSkipped:
|
||||
conclusion = "skipped"
|
||||
default:
|
||||
setting.PanicInDevOrTesting("unknown action status: %v", status)
|
||||
}
|
||||
}
|
||||
return action, conclusion
|
||||
}
|
||||
|
||||
// ToActionWorkflowJob convert a actions_model.ActionRunJob to an api.ActionWorkflowJob
|
||||
// task is optional and can be nil
|
||||
func ToActionWorkflowJob(ctx context.Context, repo *repo_model.Repository, task *actions_model.ActionTask, job *actions_model.ActionRunJob) (*api.ActionWorkflowJob, error) {
|
||||
err := job.LoadAttributes(ctx)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
if effectiveTaskID := job.EffectiveTaskID(); effectiveTaskID != 0 {
|
||||
if task == nil {
|
||||
task, _, err = db.GetByID[actions_model.ActionTask](ctx, effectiveTaskID)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
}
|
||||
|
||||
if task != nil {
|
||||
if err := (actions_model.TaskList{task}).LoadSteps(ctx); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
}
|
||||
}
|
||||
return toActionWorkflowJob(ctx, repo, task, job), nil
|
||||
}
|
||||
|
||||
// ToActionWorkflowJobs requires job.Run.Repo to be loaded
|
||||
func ToActionWorkflowJobs(ctx context.Context, jobs []*actions_model.ActionRunJob) ([]*api.ActionWorkflowJob, error) {
|
||||
tasks, err := actions_model.GetTasksMapByIDs(ctx, container.FilterSlice(jobs, func(job *actions_model.ActionRunJob) (int64, bool) {
|
||||
taskID := job.EffectiveTaskID()
|
||||
return taskID, taskID != 0
|
||||
}))
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
taskList := actions_model.TaskList(slices.Collect(maps.Values(tasks)))
|
||||
if err := taskList.LoadSteps(ctx); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
result := make([]*api.ActionWorkflowJob, len(jobs))
|
||||
for i, job := range jobs {
|
||||
result[i] = toActionWorkflowJob(ctx, job.Run.Repo, tasks[job.EffectiveTaskID()], job)
|
||||
}
|
||||
return result, nil
|
||||
}
|
||||
|
||||
func toActionWorkflowJob(ctx context.Context, repo *repo_model.Repository, task *actions_model.ActionTask, job *actions_model.ActionRunJob) *api.ActionWorkflowJob {
|
||||
status, conclusion := ToRunActionsStatus(job.Run, job.Status)
|
||||
var runnerID int64
|
||||
var runnerName string
|
||||
var steps []*api.ActionWorkflowStep
|
||||
|
||||
if task != nil && job.EffectiveTaskID() != 0 {
|
||||
runnerID = task.RunnerID
|
||||
runnerName = task.RunnerName
|
||||
for i, step := range task.Steps {
|
||||
stepStatus, stepConclusion := ToActionsStatus(step.Status)
|
||||
steps = append(steps, &api.ActionWorkflowStep{
|
||||
Name: step.Name,
|
||||
Number: int64(i),
|
||||
Status: stepStatus,
|
||||
Conclusion: stepConclusion,
|
||||
StartedAt: step.Started.AsTime().UTC(),
|
||||
CompletedAt: step.Stopped.AsTime().UTC(),
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
return &api.ActionWorkflowJob{
|
||||
ID: job.ID,
|
||||
// missing api endpoint for this location
|
||||
URL: fmt.Sprintf("%s/actions/jobs/%d", repo.APIURL(ctx), job.ID),
|
||||
HTMLURL: fmt.Sprintf("%s/jobs/%d", job.Run.HTMLURL(ctx), job.ID),
|
||||
RunID: job.RunID,
|
||||
// Missing api endpoint for this location, artifacts are available under a nested url
|
||||
RunURL: fmt.Sprintf("%s/actions/runs/%d", repo.APIURL(ctx), job.RunID),
|
||||
Name: job.Name,
|
||||
Labels: job.RunsOn,
|
||||
RunAttempt: job.Attempt,
|
||||
HeadSha: job.Run.CommitSHA,
|
||||
HeadBranch: git.RefName(job.Run.Ref).BranchName(),
|
||||
Status: status,
|
||||
Conclusion: conclusion,
|
||||
RunnerID: runnerID,
|
||||
RunnerName: runnerName,
|
||||
Steps: util.SliceNilAsEmpty(steps),
|
||||
CreatedAt: job.Created.AsTime().UTC(),
|
||||
StartedAt: job.Started.AsTime().UTC(),
|
||||
CompletedAt: job.Stopped.AsTime().UTC(),
|
||||
}
|
||||
}
|
||||
|
||||
func getActionWorkflowEntry(ctx context.Context, repo *repo_model.Repository, gitRepo *git.Repository, commit *git.Commit, refName git.RefName, folder string, entry *git.TreeEntry) *api.ActionWorkflow {
|
||||
cfgUnit := repo.MustGetUnit(ctx, unit.TypeActions)
|
||||
cfg := cfgUnit.ActionsConfig()
|
||||
|
||||
workflowURL := fmt.Sprintf("%s/actions/workflows/%s", repo.APIURL(), util.PathEscapeSegments(entry.Name()))
|
||||
workflowRepoURL := fmt.Sprintf("%s/src/commit/%s/%s/%s", repo.HTMLURL(ctx), commit.ID.String(), util.PathEscapeSegments(folder), util.PathEscapeSegments(entry.Name()))
|
||||
if refWebLinkPath := refName.RefWebLinkPath(); refWebLinkPath != "" {
|
||||
workflowRepoURL = fmt.Sprintf("%s/src/%s/%s/%s", repo.HTMLURL(ctx), refWebLinkPath, util.PathEscapeSegments(folder), util.PathEscapeSegments(entry.Name()))
|
||||
}
|
||||
badgeURL := fmt.Sprintf("%s/actions/workflows/%s/badge.svg?branch=%s", repo.HTMLURL(ctx), util.PathEscapeSegments(entry.Name()), url.QueryEscape(repo.DefaultBranch))
|
||||
|
||||
// See https://docs.github.com/en/rest/actions/workflows?apiVersion=2022-11-28#get-a-workflow
|
||||
// State types:
|
||||
// - active
|
||||
// - deleted
|
||||
// - disabled_fork
|
||||
// - disabled_inactivity
|
||||
// - disabled_manually
|
||||
state := "active"
|
||||
if cfg.IsWorkflowDisabled(entry.Name()) {
|
||||
state = "disabled_manually"
|
||||
}
|
||||
|
||||
// The CreatedAt and UpdatedAt fields currently reflect the timestamp of the latest commit, which can later be refined
|
||||
// by retrieving the first and last commits for the file history. The first commit would indicate the creation date,
|
||||
// while the last commit would represent the modification date. The DeletedAt could be determined by identifying
|
||||
// the last commit where the file existed. However, this implementation has not been done here yet, as it would likely
|
||||
// cause a significant performance degradation.
|
||||
createdAt := commit.Author.When
|
||||
updatedAt := commit.Author.When
|
||||
|
||||
content, err := actions.GetContentFromEntry(ctx, gitRepo, entry)
|
||||
name := entry.Name()
|
||||
if err == nil {
|
||||
workflow, err := jobparser.ReadWorkflow(content)
|
||||
if err == nil {
|
||||
// Only use the name when specified in the workflow file
|
||||
if workflow.Name != "" {
|
||||
name = workflow.Name
|
||||
}
|
||||
} else {
|
||||
log.Error("getActionWorkflowEntry: Failed to parse workflow: %v", err)
|
||||
}
|
||||
} else {
|
||||
log.Error("getActionWorkflowEntry: Failed to get content from entry: %v", err)
|
||||
}
|
||||
|
||||
return &api.ActionWorkflow{
|
||||
ID: entry.Name(),
|
||||
Name: name,
|
||||
Path: path.Join(folder, entry.Name()),
|
||||
State: state,
|
||||
CreatedAt: createdAt,
|
||||
UpdatedAt: updatedAt,
|
||||
URL: workflowURL,
|
||||
HTMLURL: workflowRepoURL,
|
||||
BadgeURL: badgeURL,
|
||||
}
|
||||
}
|
||||
|
||||
func ListActionWorkflows(ctx context.Context, gitrepo *git.Repository, repo *repo_model.Repository) ([]*api.ActionWorkflow, error) {
|
||||
defaultBranchCommit, err := gitrepo.GetBranchCommit(ctx, repo.DefaultBranch)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
folder, entries, err := actions.ListWorkflows(ctx, gitrepo, defaultBranchCommit)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
workflows := make([]*api.ActionWorkflow, len(entries))
|
||||
for i, entry := range entries {
|
||||
workflows[i] = getActionWorkflowEntry(ctx, repo, gitrepo, defaultBranchCommit, git.RefNameFromBranch(repo.DefaultBranch), folder, entry)
|
||||
}
|
||||
|
||||
return workflows, nil
|
||||
}
|
||||
|
||||
func GetActionWorkflow(ctx context.Context, gitRepo *git.Repository, repo *repo_model.Repository, workflowID string) (*api.ActionWorkflow, error) {
|
||||
defaultBranchCommit, err := gitRepo.GetBranchCommit(ctx, repo.DefaultBranch)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
return getActionWorkflowFromCommit(ctx, repo, gitRepo, defaultBranchCommit, git.RefNameFromBranch(repo.DefaultBranch), workflowID)
|
||||
}
|
||||
|
||||
func GetActionWorkflowByRef(ctx context.Context, gitrepo *git.Repository, repo *repo_model.Repository, workflowID string, ref git.RefName) (*api.ActionWorkflow, error) {
|
||||
if ref == "" {
|
||||
return nil, util.NewNotExistErrorf("workflow %q not found", workflowID)
|
||||
}
|
||||
|
||||
refCommitID, err := gitrepo.GetRefCommitID(ctx, ref.String())
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
refCommit, err := gitrepo.GetCommit(ctx, refCommitID)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
return getActionWorkflowFromCommit(ctx, repo, gitrepo, refCommit, ref, workflowID)
|
||||
}
|
||||
|
||||
func getActionWorkflowFromCommit(ctx context.Context, repo *repo_model.Repository, gitRepo *git.Repository, commit *git.Commit, refName git.RefName, workflowID string) (*api.ActionWorkflow, error) {
|
||||
folder, entries, err := actions.ListWorkflows(ctx, gitRepo, commit)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
for _, entry := range entries {
|
||||
if entry.Name() == workflowID {
|
||||
return getActionWorkflowEntry(ctx, repo, gitRepo, commit, refName, folder, entry), nil
|
||||
}
|
||||
}
|
||||
|
||||
return nil, util.NewNotExistErrorf("workflow %q not found", workflowID)
|
||||
}
|
||||
|
||||
// GetScopedActionWorkflow resolves a scoped workflow definition (under SCOPED_WORKFLOW_DIRS) from the source repo at commitSHA.
|
||||
func GetScopedActionWorkflow(ctx context.Context, sourceGitRepo *git.Repository, sourceRepo *repo_model.Repository, workflowID, commitSHA string) (*api.ActionWorkflow, error) {
|
||||
commit, err := sourceGitRepo.GetCommit(ctx, commitSHA)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
folder, entries, err := actions.ListScopedWorkflows(ctx, sourceGitRepo, commit)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
for _, entry := range entries {
|
||||
if entry.Name() == workflowID {
|
||||
// An empty ref pins HTMLURL to commit (the run's WorkflowCommitSHA) rather than the moving default branch.
|
||||
wf := getActionWorkflowEntry(ctx, sourceRepo, sourceGitRepo, commit, "", folder, entry)
|
||||
// TODO: a scoped workflow has no repo-level representation on the source: the workflow API scans WORKFLOW_DIRS (not SCOPED_WORKFLOW_DIRS),
|
||||
// and the badge only reflects the source's repo-level runs, so neither link resolves a scoped workflow.
|
||||
// Blank them for now and populate once a scoped-aware workflow/badge endpoint exists.
|
||||
wf.URL = ""
|
||||
wf.BadgeURL = ""
|
||||
return wf, nil
|
||||
}
|
||||
}
|
||||
|
||||
return nil, util.NewNotExistErrorf("scoped workflow %q not found", workflowID)
|
||||
}
|
||||
|
||||
// ResolveActionWorkflowForRun returns the api.ActionWorkflow describing a run's workflow definition.
|
||||
// For a scoped run the definition lives in the source repo (run.WorkflowRepoID @ run.WorkflowCommitSHA) under SCOPED_WORKFLOW_DIRS,
|
||||
// not in the consuming repo, so it is resolved against the source repo.
|
||||
func ResolveActionWorkflowForRun(ctx context.Context, repo *repo_model.Repository, run *actions_model.ActionRun) (*api.ActionWorkflow, error) {
|
||||
if run.IsScopedRun {
|
||||
sourceRepo, err := repo_model.GetRepositoryByID(ctx, run.WorkflowRepoID)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
sourceGitRepo, err := git.OpenRepository(ctx, sourceRepo)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
defer sourceGitRepo.Close()
|
||||
return GetScopedActionWorkflow(ctx, sourceGitRepo, sourceRepo, run.WorkflowID, run.WorkflowCommitSHA)
|
||||
}
|
||||
|
||||
gitRepo, err := git.OpenRepository(ctx, repo)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
defer gitRepo.Close()
|
||||
|
||||
convertedWorkflow, err := GetActionWorkflowByRef(ctx, gitRepo, repo, run.WorkflowID, git.RefName(run.Ref))
|
||||
if err != nil && errors.Is(err, util.ErrNotExist) {
|
||||
convertedWorkflow, err = GetActionWorkflow(ctx, gitRepo, repo, run.WorkflowID)
|
||||
}
|
||||
return convertedWorkflow, err
|
||||
}
|
||||
|
||||
// ToActionArtifact convert a actions_model.ActionArtifact to an api.ActionArtifact
|
||||
func ToActionArtifact(repo *repo_model.Repository, art *actions_model.ActionArtifact) *api.ActionArtifact {
|
||||
url := fmt.Sprintf("%s/actions/artifacts/%d", repo.APIURL(), art.ID)
|
||||
|
||||
return &api.ActionArtifact{
|
||||
ID: art.ID,
|
||||
Name: art.ArtifactName,
|
||||
SizeInBytes: art.FileSize,
|
||||
Expired: art.Status == actions_model.ArtifactStatusExpired,
|
||||
URL: url,
|
||||
ArchiveDownloadURL: url + "/zip",
|
||||
CreatedAt: art.CreatedUnix.AsLocalTime(),
|
||||
UpdatedAt: art.UpdatedUnix.AsLocalTime(),
|
||||
ExpiresAt: art.ExpiredUnix.AsLocalTime(),
|
||||
WorkflowRun: &api.ActionWorkflowRun{
|
||||
ID: art.RunID,
|
||||
RepositoryID: art.RepoID,
|
||||
HeadSha: art.CommitSHA,
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
func ToActionRunner(runner *actions_model.ActionRunner) *api.ActionRunner {
|
||||
status := runner.Status()
|
||||
apiStatus := "offline"
|
||||
if runner.IsOnline() {
|
||||
apiStatus = "online"
|
||||
}
|
||||
labels := make([]*api.ActionRunnerLabel, len(runner.AgentLabels))
|
||||
for i, label := range runner.AgentLabels {
|
||||
labels[i] = &api.ActionRunnerLabel{
|
||||
ID: int64(i),
|
||||
Name: label,
|
||||
Type: "custom",
|
||||
}
|
||||
}
|
||||
return &api.ActionRunner{
|
||||
ID: runner.ID,
|
||||
Name: runner.Name,
|
||||
Status: apiStatus,
|
||||
Busy: status == runnerv1.RunnerStatus_RUNNER_STATUS_ACTIVE,
|
||||
Disabled: runner.IsDisabled,
|
||||
Ephemeral: runner.Ephemeral,
|
||||
Labels: labels,
|
||||
}
|
||||
}
|
||||
|
||||
// ToVerification convert a git.Commit.Signature to an api.PayloadCommitVerification
|
||||
func ToVerification(ctx context.Context, c *git.Commit) *api.PayloadCommitVerification {
|
||||
verif := asymkey_service.ParseCommitWithSignature(ctx, c)
|
||||
|
||||
@@ -333,7 +333,7 @@ jobs:
|
||||
version: ${{ steps.version_step.outputs.app_version }}
|
||||
steps:
|
||||
- id: version_step
|
||||
run: echo "app_version=v1.23.0" >> "$GITHUB_OUTPUT"
|
||||
run: echo "app_version=V1.23.0" >> "$GITHUB_OUTPUT"
|
||||
wf2-job2:
|
||||
runs-on: runner1
|
||||
needs: [wf2-job1]
|
||||
@@ -373,7 +373,7 @@ jobs:
|
||||
runner2.execTask(t, wf2Job1Task, &mockTaskOutcome{
|
||||
result: runnerv1.Result_RESULT_SUCCESS,
|
||||
outputs: map[string]string{
|
||||
"version": "v1.23.0",
|
||||
"version": "V1.23.0",
|
||||
},
|
||||
})
|
||||
// cannot fetch wf2-job2 because wf1-job1 is running
|
||||
@@ -1185,7 +1185,7 @@ on:
|
||||
paths:
|
||||
- '.gitea/workflows/workflow-2.yml'
|
||||
concurrency:
|
||||
group: test-group
|
||||
group: Test-Group
|
||||
jobs:
|
||||
wf2-job1:
|
||||
runs-on: ubuntu-latest
|
||||
|
||||
@@ -605,10 +605,13 @@ jobs:
|
||||
unittest.AssertNotExistsBean(t, &actions_model.ActionRunJob{RunID: run.ID, JobID: "util_consumer_job"})
|
||||
})
|
||||
|
||||
t.Run("Missing, invalid or cache-mode exceeding callee fails the run as an invalid workflow file", func(t *testing.T) {
|
||||
t.Run("Invalid and cyclic reusable calls fail workflow validation", func(t *testing.T) {
|
||||
apiRepo := createActionsTestRepo(t, user2Token, "invalid-callees", false)
|
||||
repo := unittest.AssertExistsAndLoadBean(t, &repo_model.Repository{ID: apiRepo.ID})
|
||||
const caller = "on: push\njobs:\n plain_job: {runs-on: ubuntu-latest, steps: [{run: echo}]}\n call:\n needs: plain_job\n uses: ./.gitea/workflows/"
|
||||
const callerJobs = "\njobs:\n plain_job: {runs-on: ubuntu-latest, steps: [{run: echo}]}\n call:\n"
|
||||
const localCall = " uses: ./.gitea/workflows/"
|
||||
const caller = "on: push" + callerJobs + " needs: plain_job\n" + localCall
|
||||
cycleTarget := repo.FullName() + "/.gitea/workflows/nested/cycle.yaml@" + repo.DefaultBranch
|
||||
testCreateFileInBranch(t, user2, repo, createFileInBranchOptions{}, map[string]string{
|
||||
".gitea/workflows/missing.yaml": caller + "absent.yml\n",
|
||||
".gitea/workflows/invalid.yaml": caller + "no-runs-on.yml\n",
|
||||
@@ -617,12 +620,23 @@ jobs:
|
||||
".gitea/workflows/leaf.yml": "on: workflow_call\ncache-mode: read\njobs: {build: {runs-on: ubuntu-latest, cache-mode: write-only, steps: [{run: echo}]}}\n",
|
||||
".gitea/workflows/relay.yml": "on: workflow_call\njobs: {forward: {uses: ./.gitea/workflows/leaf.yml}}\n",
|
||||
".gitea/workflows/job-cap.yaml": "on: push\ncache-mode: read\njobs:\n allow: {uses: ./.gitea/workflows/relay.yml, cache-mode: write}\n inherit: {uses: ./.gitea/workflows/relay.yml}\n",
|
||||
".gitea/workflows/direct-cycle.yaml": "on: [workflow_dispatch, workflow_call]\njobs:\n call:\n" + localCall + "direct-cycle.yaml\n",
|
||||
".gitea/workflows/nested/cycle.yaml": "on: [push, workflow_call]" + callerJobs + localCall + "cycle-relay.yml\n",
|
||||
".gitea/workflows/cycle-relay.yml": "on: workflow_call\njobs: {forward: {uses: " + cycleTarget + "}}\n",
|
||||
})
|
||||
|
||||
req := NewRequestWithJSON(t, "POST", "/api/v1/repos/"+repo.FullName()+"/actions/workflows/direct-cycle.yaml/dispatches",
|
||||
&api.CreateActionWorkflowDispatch{Ref: repo.DefaultBranch}).AddTokenAuth(user2Token)
|
||||
resp := MakeRequest(t, req, http.StatusUnprocessableEntity)
|
||||
assert.Contains(t, DecodeJSON(t, resp, &api.APIError{}).Message, `cycle detected: "./.gitea/workflows/direct-cycle.yaml"`)
|
||||
unittest.AssertNotExistsBean(t, &actions_model.ActionRun{RepoID: repo.ID, WorkflowID: "direct-cycle.yaml"})
|
||||
|
||||
for workflowID, want := range map[string]string{
|
||||
"missing.yaml": "job call: read user2/invalid-callees@",
|
||||
"invalid.yaml": "job call: Error from called workflow ./.gitea/workflows/no-runs-on.yml: job inner: Required property is missing: runs-on",
|
||||
"workflow-cap.yaml": "job call: Error from called workflow ./.gitea/workflows/leaf.yml: cache-mode: The workflow is requesting 'read', but is only allowed 'write-only'",
|
||||
"job-cap.yaml": "job inherit: Error from called workflow ./.gitea/workflows/relay.yml: job forward: Error from called workflow ./.gitea/workflows/leaf.yml: cache-mode: The nested job 'build' is requesting 'write-only', but is only allowed 'read'",
|
||||
"nested/cycle.yaml": fmt.Sprintf("cycle detected: %q", cycleTarget),
|
||||
} {
|
||||
assertInvalidWorkflowRun(t, repo.ID, workflowID, want)
|
||||
}
|
||||
@@ -822,110 +836,84 @@ jobs:
|
||||
assert.Equal(t, "release", taskContext["base_ref"].GetStringValue())
|
||||
})
|
||||
|
||||
t.Run("Caller alternates expanding across attempts", func(t *testing.T) {
|
||||
t.Run("Partial reruns reuse callee commits across skipped attempts and full reruns resolve the moved branch", func(t *testing.T) {
|
||||
apiRepo := createActionsTestRepo(t, user2Token, "caller-walkback-test", false)
|
||||
repo := unittest.AssertExistsAndLoadBean(t, &repo_model.Repository{ID: apiRepo.ID})
|
||||
|
||||
runner := newMockRunner()
|
||||
runner.registerAsRepoRunner(t, repo.OwnerName, repo.Name, "mock-walkback-runner", []string{"ubuntu-latest"}, false)
|
||||
|
||||
// Scenario:
|
||||
// attempt 1: gate succeeds -> caller expands -> inner runs (records inner.AttemptJobID = N)
|
||||
// attempt 2: rerun gate, mock Failure -> caller is Skipped without expanding (no children inserted)
|
||||
// attempt 3: rerun gate, mock Success -> caller expands again -> inner.AttemptJobID must equal N
|
||||
|
||||
createRepoWorkflowFile(t, user2, user2Token, repo, ".gitea/workflows/lib.yaml",
|
||||
`name: Lib
|
||||
on:
|
||||
workflow_call:
|
||||
|
||||
testCreateFileInBranch(t, user2, repo, createFileInBranchOptions{}, map[string]string{
|
||||
".gitea/workflows/inner.yaml": "on: workflow_call\njobs: {inner: {runs-on: ubuntu-latest, steps: [{run: echo inner}]}}\n",
|
||||
".gitea/workflows/lib.yaml": fmt.Sprintf(`on: workflow_call
|
||||
jobs:
|
||||
inner:
|
||||
generate:
|
||||
runs-on: ubuntu-latest
|
||||
outputs:
|
||||
matrix: ${{ steps.output.outputs.matrix }}
|
||||
steps:
|
||||
- run: echo inner
|
||||
`)
|
||||
createRepoWorkflowFile(t, user2, user2Token, repo, ".gitea/workflows/main.yaml",
|
||||
`name: Main
|
||||
on:
|
||||
- id: output
|
||||
run: echo 'matrix=["a"]' >> "$GITHUB_OUTPUT"
|
||||
nested:
|
||||
needs: [generate]
|
||||
strategy:
|
||||
matrix:
|
||||
value: ${{ fromJson(needs.generate.outputs.matrix) }}
|
||||
uses: %s/.gitea/workflows/inner.yaml@%s
|
||||
`, repo.FullName(), repo.DefaultBranch),
|
||||
".gitea/workflows/main.yaml": fmt.Sprintf(`on:
|
||||
push:
|
||||
paths:
|
||||
- '.gitea/workflows/main.yaml'
|
||||
paths: ['.gitea/workflows/main.yaml']
|
||||
jobs:
|
||||
gate:
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- run: echo gate
|
||||
|
||||
gate: {runs-on: ubuntu-latest, steps: [{run: echo gate}]}
|
||||
caller:
|
||||
needs: [gate]
|
||||
uses: ./.gitea/workflows/lib.yaml
|
||||
`)
|
||||
uses: %s/.gitea/workflows/lib.yaml@%s
|
||||
`, repo.FullName(), repo.DefaultBranch),
|
||||
})
|
||||
|
||||
run := unittest.AssertExistsAndLoadBean(t, &actions_model.ActionRun{RepoID: repo.ID})
|
||||
runID := run.ID
|
||||
|
||||
latestAttempt := func() *actions_model.ActionRunAttempt {
|
||||
r := unittest.AssertExistsAndLoadBean(t, &actions_model.ActionRun{ID: runID})
|
||||
return unittest.AssertExistsAndLoadBean(t, &actions_model.ActionRunAttempt{ID: r.LatestAttemptID})
|
||||
}
|
||||
jobInLatest := func(jobID string) *actions_model.ActionRunJob {
|
||||
a := latestAttempt()
|
||||
return unittest.AssertExistsAndLoadBean(t, &actions_model.ActionRunJob{RunID: runID, RunAttemptID: a.ID, JobID: jobID})
|
||||
latest := unittest.AssertExistsAndLoadBean(t, &actions_model.ActionRun{ID: run.ID})
|
||||
return unittest.AssertExistsAndLoadBean(t, &actions_model.ActionRunJob{RunID: run.ID, RunAttemptID: latest.LatestAttemptID, JobID: jobID})
|
||||
}
|
||||
completeTask := func(jobID string, result runnerv1.Result, outputs map[string]string) {
|
||||
t.Helper()
|
||||
task := runner.fetchTask(t)
|
||||
require.Equal(t, jobID, task.GetContext().GetFields()["job"].GetStringValue())
|
||||
runner.execTask(t, task, &mockTaskOutcome{result: result, outputs: outputs})
|
||||
}
|
||||
completeAttempt := func() {
|
||||
completeTask("gate", runnerv1.Result_RESULT_SUCCESS, nil)
|
||||
completeTask("generate", runnerv1.Result_RESULT_SUCCESS, map[string]string{"matrix": `["a"]`})
|
||||
completeTask("inner", runnerv1.Result_RESULT_SUCCESS, nil)
|
||||
}
|
||||
assertCalleeCommits := func(commitSHA string) {
|
||||
t.Helper()
|
||||
assert.Equal(t, commitSHA, jobInLatest("nested").WorkflowSourceCommitSHA)
|
||||
assert.Equal(t, commitSHA, jobInLatest("inner").WorkflowSourceCommitSHA)
|
||||
}
|
||||
|
||||
// attempt 1: gate Success -> caller expands -> inner runs
|
||||
gate1Task := runner.fetchTask(t)
|
||||
_, gate1, _ := getTaskAndJobAndRunByTaskID(t, gate1Task.Id)
|
||||
assert.Equal(t, "gate", gate1.JobID)
|
||||
runner.execTask(t, gate1Task, &mockTaskOutcome{result: runnerv1.Result_RESULT_SUCCESS})
|
||||
completeAttempt()
|
||||
innerAttemptJobID := jobInLatest("inner").AttemptJobID
|
||||
movedCommit := testCreateFileInBranch(t, user2, repo, createFileInBranchOptions{}, map[string]string{"advance-branch.txt": "new commit"}).Commit.SHA
|
||||
require.NotEqual(t, run.WorkflowCommitSHA, movedCommit)
|
||||
|
||||
inner1Task := runner.fetchTask(t)
|
||||
_, inner1, _ := getTaskAndJobAndRunByTaskID(t, inner1Task.Id)
|
||||
assert.Equal(t, "inner", inner1.JobID)
|
||||
innerAttemptJobID := inner1.AttemptJobID
|
||||
callerAttempt1 := jobInLatest("caller")
|
||||
assert.True(t, callerAttempt1.IsExpanded)
|
||||
assert.Equal(t, callerAttempt1.ID, inner1.ParentJobID)
|
||||
runner.execTask(t, inner1Task, &mockTaskOutcome{result: runnerv1.Result_RESULT_SUCCESS})
|
||||
|
||||
run = unittest.AssertExistsAndLoadBean(t, &actions_model.ActionRun{ID: runID})
|
||||
assert.Equal(t, actions_model.StatusSuccess, run.Status)
|
||||
|
||||
// attempt 2: rerun gate, mock Failure -> caller stays unexpanded (Skipped)
|
||||
gateLatest := jobInLatest("gate")
|
||||
req := NewRequest(t, "POST", fmt.Sprintf("/%s/%s/actions/runs/%d/jobs/%d/rerun", repo.OwnerName, repo.Name, runID, gateLatest.ID))
|
||||
req := NewRequest(t, "POST", fmt.Sprintf("/%s/actions/runs/%d/jobs/%d/rerun", repo.FullName(), run.ID, jobInLatest("gate").ID))
|
||||
user2Session.MakeRequest(t, req, http.StatusOK)
|
||||
completeTask("gate", runnerv1.Result_RESULT_FAILURE, nil)
|
||||
assert.Equal(t, actions_model.StatusSkipped, jobInLatest("caller").Status)
|
||||
|
||||
gate2Task := runner.fetchTask(t)
|
||||
_, gate2, _ := getTaskAndJobAndRunByTaskID(t, gate2Task.Id)
|
||||
assert.Equal(t, "gate", gate2.JobID)
|
||||
runner.execTask(t, gate2Task, &mockTaskOutcome{result: runnerv1.Result_RESULT_FAILURE})
|
||||
apiRunPath := fmt.Sprintf("/api/v1/repos/%s/actions/runs/%d", repo.FullName(), run.ID)
|
||||
MakeRequest(t, NewRequest(t, "POST", apiRunPath+"/rerun-failed-jobs").AddTokenAuth(user2Token), http.StatusCreated)
|
||||
completeAttempt()
|
||||
assertCalleeCommits(run.WorkflowCommitSHA)
|
||||
assert.Equal(t, innerAttemptJobID, jobInLatest("inner").AttemptJobID)
|
||||
assert.Equal(t, "refs/heads/"+repo.DefaultBranch, jobInLatest("caller").ReusableWorkflowRef)
|
||||
assert.Equal(t, "refs/heads/"+repo.DefaultBranch, jobInLatest("nested").ReusableWorkflowRef)
|
||||
|
||||
runner.fetchNoTask(t) // no inner because caller did not expand
|
||||
attempt2 := latestAttempt()
|
||||
assert.Equal(t, actions_model.StatusFailure, attempt2.Status)
|
||||
callerAttempt2 := jobInLatest("caller")
|
||||
assert.Equal(t, actions_model.StatusSkipped, callerAttempt2.Status)
|
||||
assert.False(t, callerAttempt2.IsExpanded)
|
||||
assert.Equal(t, 0, unittest.GetCount(t, &actions_model.ActionRunJob{RunID: runID, RunAttemptID: attempt2.ID, JobID: "inner"}))
|
||||
|
||||
// attempt 3: rerun gate, mock Success -> caller expands and inner reuses attempt 1's AttemptJobID
|
||||
gateLatest = jobInLatest("gate")
|
||||
req = NewRequest(t, "POST", fmt.Sprintf("/%s/%s/actions/runs/%d/jobs/%d/rerun", repo.OwnerName, repo.Name, runID, gateLatest.ID))
|
||||
user2Session.MakeRequest(t, req, http.StatusOK)
|
||||
|
||||
gate3Task := runner.fetchTask(t)
|
||||
runner.execTask(t, gate3Task, &mockTaskOutcome{result: runnerv1.Result_RESULT_SUCCESS})
|
||||
|
||||
inner3Task := runner.fetchTask(t)
|
||||
_, inner3, _ := getTaskAndJobAndRunByTaskID(t, inner3Task.Id)
|
||||
assert.Equal(t, "inner", inner3.JobID)
|
||||
assert.Equal(t, innerAttemptJobID, inner3.AttemptJobID)
|
||||
runner.execTask(t, inner3Task, &mockTaskOutcome{result: runnerv1.Result_RESULT_SUCCESS})
|
||||
|
||||
run = unittest.AssertExistsAndLoadBean(t, &actions_model.ActionRun{ID: runID})
|
||||
assert.Equal(t, actions_model.StatusSuccess, run.Status)
|
||||
MakeRequest(t, NewRequest(t, "POST", apiRunPath+"/rerun").AddTokenAuth(user2Token), http.StatusCreated)
|
||||
completeAttempt()
|
||||
assertCalleeCommits(movedCommit)
|
||||
})
|
||||
|
||||
t.Run("No-needs callers: if evaluated inline, called job concurrency serializes them", func(t *testing.T) {
|
||||
|
||||
@@ -0,0 +1,51 @@
|
||||
// Copyright 2026 The Gitea Authors. All rights reserved.
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
package integration
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"net/http"
|
||||
"testing"
|
||||
|
||||
secret_model "gitea.dev/models/secret"
|
||||
"gitea.dev/models/unittest"
|
||||
"gitea.dev/modules/test"
|
||||
"gitea.dev/tests"
|
||||
|
||||
"github.com/stretchr/testify/assert"
|
||||
)
|
||||
|
||||
func TestActionsSecretsSettings(t *testing.T) {
|
||||
defer tests.PrepareTestEnv(t)()
|
||||
session := loginUser(t, "user2")
|
||||
const secretName = "SCOPED_SECRET"
|
||||
|
||||
for _, scope := range []struct {
|
||||
name, link string
|
||||
ownerID, repoID int64
|
||||
}{
|
||||
{"User", "/user/settings/actions/secrets", 2, 0},
|
||||
{"Org", "/org/org3/settings/actions/secrets", 3, 0},
|
||||
{"Repo", "/user2/repo1/settings/actions/secrets", 0, 1},
|
||||
} {
|
||||
t.Run(scope.name, func(t *testing.T) {
|
||||
req := NewRequestWithValues(t, "POST", scope.link, map[string]string{"name": secretName, "data": "data"})
|
||||
resp := session.MakeRequest(t, req, http.StatusOK)
|
||||
assert.Equal(t, scope.link, test.RedirectURL(resp))
|
||||
secret := unittest.AssertExistsAndLoadBean(t, &secret_model.Secret{Name: secretName})
|
||||
assert.Equal(t, scope.ownerID, secret.OwnerID)
|
||||
assert.Equal(t, scope.repoID, secret.RepoID)
|
||||
|
||||
deleteURL := fmt.Sprintf("%s/delete?id=%d", scope.link, secret.ID)
|
||||
deleteButton := `button[data-url="` + deleteURL + `"]`
|
||||
resp = session.MakeRequest(t, NewRequest(t, "GET", scope.link), http.StatusOK)
|
||||
AssertHTMLElement(t, NewHTMLParser(t, resp.Body), deleteButton, 1)
|
||||
|
||||
session.MakeRequest(t, NewRequest(t, "POST", deleteURL), http.StatusOK)
|
||||
unittest.AssertNotExistsBean(t, &secret_model.Secret{ID: secret.ID})
|
||||
resp = session.MakeRequest(t, NewRequest(t, "GET", scope.link), http.StatusOK)
|
||||
AssertHTMLElement(t, NewHTMLParser(t, resp.Body), deleteButton, 0)
|
||||
})
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user