mirror of
https://github.com/go-gitea/gitea.git
synced 2026-08-04 07:17:35 +00:00
f46c9a9769
## Summary This PR adds **scoped workflows** to Gitea Actions. Workflows defined centrally in a "source" repository that automatically run on every repository in scope: an organization's repositories, or (for instance admins) every repository on the instance. Each scoped run executes in the consuming repository's own context (its runners, secrets, and branch) while its content is read from the source repository, so an org or instance can mandate shared CI across many repositories without copying workflow files into each one. An owner or instance admin registers source repositories on a settings page and can mark individual workflows as **required**. A required scoped workflow cannot be opted out by a consuming repository and gates its pull-request merges; an optional one can be disabled per repository. Scoped workflows live under a dedicated `SCOPED_WORKFLOW_DIRS` (default `.gitea/scoped_workflows`), kept separate from regular `WORKFLOW_DIRS`. ## Main changes ### Configuration New `SCOPED_WORKFLOW_DIRS` setting, validated to not overlap with `WORKFLOW_DIRS`. Default: `.gitea/scoped_workflows` ### Data model & migration - New `action_scoped_workflow_source` table mapping a registering owner (`owner_id`, where `0` = instance-level) to a source repository, with a per-workflow `WorkflowConfigs` map. - `ActionRun` gains `WorkflowRepoID` / `WorkflowCommitSHA` (the pinned content source) and an `IsScopedRun` flag. ### Detection & run creation On consumer events, scoped workflows from the effective sources (the owner's own sources plus instance-level ones) are matched and turned into runs that execute in the consumer's context, with content pinned to the source repo's default-branch commit. `on: workflow_run` and `on: schedule` are currently not supported. ### Opt-out A consuming repository can disable an optional scoped workflow (tracked separately from regular `DisabledWorkflows`); required scoped workflows can never be disabled, opted out, or bypassed. ### Commit status A scoped run's status context format is `"<source repo full name>: <workflow display name> / <job> (<event>)"` (for example: `my-org/scoped-workflows: db-tests / test-sqlite (pull_request)`), keeping it distinct from a same-named repo-level workflow and from other sources. ### Required status checks Admins mark workflows required and supply status-check patterns. `EffectiveRequiredContexts` appends those patterns to the branch protection's required contexts and they are matched must-present-and-pass. If the status checks from scoped workflows fail, the PR cannot be merged. NOTE: scoped workflows' required status checks patterns can protect any target branch that has a protection rule, even though the rule's "Status Check" is disabled. A target branch with no protection rule cannot be protected. <details> <summary>Screenshots</summary> <img width="1400" alt="image" src="https://github.com/user-attachments/assets/a5d1db33-15ec-487e-93be-2bc04b4e6643" /> </details> ### Reusable workflows (`uses:`) A scoped workflow's local `uses: ./...` resolves against the source repository. `uses:` directory validation honors the instance-configurable `WORKFLOW_DIRS` and `SCOPED_WORKFLOW_DIRS` (previously hardcoded to `.gitea`/`.github/workflows`). ### Manual dispatch `workflow_dispatch` is supported for scoped workflows (web and API), resolving inputs/content from the source repo. ### Performance A process-local LRU cache keyed by source repo ID for the per-source workflow parse, so instance-level and owner-level sources don't open the source repo and parse workflow files on every event. ### UI Org / user / admin pages to register and remove sources, search repositories, and mark workflows required with their status-check patterns. The repository Actions sidebar groups scoped workflows by source with owner/instance labels and required/disabled badges. <details> <summary>Screenshots</summary> Scoped workflows setting page: <img width="1600" alt="image" src="https://github.com/user-attachments/assets/9d19f667-97a5-4935-92b2-e53f105e3642" /> Consumer repo's Actions runs list: <img width="1600" alt="image" src="https://github.com/user-attachments/assets/a77241f9-0aa9-41aa-ba73-12a9a688cb64" /> - `Owner`: this is a owner-level scoped workflows source repo - `Global`: this is a global scoped workflows source repo - `Required`: this scoped workflow is required, repo admin cannot disable it </details> --- Docs: https://gitea.com/gitea/docs/pulls/447 --------- Co-authored-by: bircni <bircni@icloud.com>
199 lines
6.5 KiB
Go
199 lines
6.5 KiB
Go
// Copyright 2022 The Gitea Authors. All rights reserved.
|
|
// SPDX-License-Identifier: MIT
|
|
|
|
package actions
|
|
|
|
import (
|
|
"context"
|
|
|
|
"gitea.dev/models/db"
|
|
repo_model "gitea.dev/models/repo"
|
|
user_model "gitea.dev/models/user"
|
|
"gitea.dev/modules/container"
|
|
"gitea.dev/modules/optional"
|
|
"gitea.dev/modules/translation"
|
|
webhook_module "gitea.dev/modules/webhook"
|
|
|
|
"xorm.io/builder"
|
|
)
|
|
|
|
type RunList []*ActionRun
|
|
|
|
func (runs RunList) LoadTriggerUser(ctx context.Context) error {
|
|
userIDs := container.FilterSlice(runs, func(run *ActionRun) (int64, bool) {
|
|
return run.TriggerUserID, run.TriggerUser == nil
|
|
})
|
|
users := make(map[int64]*user_model.User, len(userIDs))
|
|
if err := db.GetEngine(ctx).In("id", userIDs).Find(&users); err != nil {
|
|
return err
|
|
}
|
|
for _, run := range runs {
|
|
if run.TriggerUser != nil {
|
|
continue
|
|
}
|
|
run.TriggerUser = users[run.TriggerUserID]
|
|
if run.TriggerUserID < 0 {
|
|
run.TriggerUserID, run.TriggerUser, _ = user_model.GetPossibleUserByID(ctx, run.TriggerUserID)
|
|
} else if run.TriggerUser == nil {
|
|
run.TriggerUserID, run.TriggerUser, _ = user_model.GetPossibleUserByID(ctx, user_model.GhostUserID)
|
|
}
|
|
}
|
|
return nil
|
|
}
|
|
|
|
func (runs RunList) LoadRepos(ctx context.Context) error {
|
|
repoIDs := container.FilterSlice(runs, func(run *ActionRun) (int64, bool) {
|
|
return run.RepoID, run.Repo == nil
|
|
})
|
|
repos, err := repo_model.GetRepositoriesMapByIDs(ctx, repoIDs)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
for _, run := range runs {
|
|
if run.Repo == nil {
|
|
run.Repo = repos[run.RepoID]
|
|
}
|
|
}
|
|
return nil
|
|
}
|
|
|
|
type FindRunOptions struct {
|
|
db.ListOptions
|
|
RepoID int64
|
|
OwnerID int64
|
|
WorkflowID string
|
|
WorkflowRepoID int64 // source-aware filter: the repo a run's workflow content came from (0 = any)
|
|
IsScopedRun optional.Option[bool] // is the run from a scoped workflow
|
|
Ref string // the commit/tag/… that caused this workflow
|
|
TriggerUserID int64
|
|
TriggerEvent webhook_module.HookEventType
|
|
Status []Status
|
|
ConcurrencyGroup string
|
|
CommitSHA string
|
|
}
|
|
|
|
func (opts FindRunOptions) ToConds() builder.Cond {
|
|
cond := builder.NewCond()
|
|
if opts.RepoID > 0 {
|
|
cond = cond.And(builder.Eq{"`action_run`.repo_id": opts.RepoID})
|
|
}
|
|
if opts.WorkflowID != "" {
|
|
cond = cond.And(builder.Eq{"`action_run`.workflow_id": opts.WorkflowID})
|
|
}
|
|
if opts.WorkflowRepoID > 0 {
|
|
cond = cond.And(builder.Eq{"`action_run`.workflow_repo_id": opts.WorkflowRepoID})
|
|
}
|
|
if opts.IsScopedRun.Has() {
|
|
cond = cond.And(builder.Eq{"`action_run`.is_scoped_run": opts.IsScopedRun.Value()})
|
|
}
|
|
if opts.TriggerUserID > 0 {
|
|
cond = cond.And(builder.Eq{"`action_run`.trigger_user_id": opts.TriggerUserID})
|
|
}
|
|
if len(opts.Status) > 0 {
|
|
cond = cond.And(builder.In("`action_run`.status", opts.Status))
|
|
}
|
|
if opts.Ref != "" {
|
|
cond = cond.And(builder.Eq{"`action_run`.ref": opts.Ref})
|
|
}
|
|
if opts.TriggerEvent != "" {
|
|
cond = cond.And(builder.Eq{"`action_run`.trigger_event": opts.TriggerEvent})
|
|
}
|
|
if opts.CommitSHA != "" {
|
|
cond = cond.And(builder.Eq{"`action_run`.commit_sha": opts.CommitSHA})
|
|
}
|
|
return cond
|
|
}
|
|
|
|
func (opts FindRunOptions) ToJoins() []db.JoinFunc {
|
|
if opts.OwnerID > 0 {
|
|
return []db.JoinFunc{func(sess db.Engine) error {
|
|
sess.Join("INNER", "repository", "repository.id = repo_id AND repository.owner_id = ?", opts.OwnerID)
|
|
return nil
|
|
}}
|
|
}
|
|
return nil
|
|
}
|
|
|
|
func (opts FindRunOptions) ToOrders() string {
|
|
// When scoped to a repo, sort by `index`: it reuses the unique
|
|
// `repo_index` (repo_id, index) index, so the query seeks repo_id and
|
|
// walks index descending instead of filesorting all matching rows.
|
|
// Within a repo `index` is co-monotonic with `id`, so the order is the same.
|
|
if opts.RepoID > 0 {
|
|
return "`action_run`.`index` DESC"
|
|
}
|
|
// `index` is scoped per repo, so it is meaningless across repos. With no
|
|
// RepoID, sort by the global, PK-indexed `id` for a deterministic order.
|
|
return "`action_run`.`id` DESC"
|
|
}
|
|
|
|
type StatusInfo struct {
|
|
Status int
|
|
StatusName string
|
|
DisplayedStatus string
|
|
}
|
|
|
|
// GetStatusInfoList returns a slice of StatusInfo
|
|
func GetStatusInfoList(ctx context.Context, lang translation.Locale) []StatusInfo {
|
|
// same as those in aggregateJobStatus
|
|
allStatus := []Status{StatusSuccess, StatusFailure, StatusWaiting, StatusRunning, StatusCancelling}
|
|
statusInfoList := make([]StatusInfo, 0, len(allStatus))
|
|
for _, s := range allStatus {
|
|
statusInfoList = append(statusInfoList, StatusInfo{
|
|
Status: int(s),
|
|
StatusName: s.String(),
|
|
DisplayedStatus: s.LocaleString(lang),
|
|
})
|
|
}
|
|
return statusInfoList
|
|
}
|
|
|
|
// GetRunBranches returns branch names for the run-list "Branch" filter.
|
|
// Sourced from the `branch` table (indexed by repo_id) rather than DISTINCT-ing
|
|
// `action_run.ref`, which is wildcard-matched and slow on large repos; as a side
|
|
// effect the list reflects existing branches, not only ones that produced a run.
|
|
func GetRunBranches(ctx context.Context, repoID int64) ([]string, error) {
|
|
branches := make([]string, 0, 10)
|
|
return branches, db.GetEngine(ctx).Table("branch").
|
|
Where("repo_id = ?", repoID).
|
|
And("is_deleted = ?", false).
|
|
Cols("name").
|
|
OrderBy("name ASC").
|
|
Find(&branches)
|
|
}
|
|
|
|
// GetRunWorkflowIDs returns all distinct WorkflowIDs that have at least
|
|
// one ActionRun in the given repo.
|
|
func GetRunWorkflowIDs(ctx context.Context, repoID int64) ([]string, error) {
|
|
return getRunWorkflowIDs(ctx, repoID, builder.NewCond())
|
|
}
|
|
|
|
// GetRepoRunWorkflowIDs returns all distinct WorkflowIDs that have at least
|
|
// one repo-level ActionRun in the given repo.
|
|
func GetRepoRunWorkflowIDs(ctx context.Context, repoID int64) ([]string, error) {
|
|
return getRunWorkflowIDs(ctx, repoID, builder.Eq{"is_scoped_run": false})
|
|
}
|
|
|
|
func getRunWorkflowIDs(ctx context.Context, repoID int64, extraCond builder.Cond) ([]string, error) {
|
|
ids := make([]string, 0, 10)
|
|
cond := builder.Eq{"repo_id": repoID}
|
|
return ids, db.GetEngine(ctx).Table("action_run").
|
|
Where(cond.And(extraCond)).
|
|
Distinct("workflow_id").
|
|
Cols("workflow_id").
|
|
Asc("workflow_id").
|
|
Find(&ids)
|
|
}
|
|
|
|
// GetActors returns a slice of Actors
|
|
func GetActors(ctx context.Context, repoID int64) ([]*user_model.User, error) {
|
|
actors := make([]*user_model.User, 0, 10)
|
|
|
|
return actors, db.GetEngine(ctx).Where(builder.In("id", builder.Select("`action_run`.trigger_user_id").From("`action_run`").
|
|
GroupBy("`action_run`.trigger_user_id").
|
|
Where(builder.Eq{"`action_run`.repo_id": repoID}))).
|
|
Cols("id", "name", "full_name", "avatar", "avatar_email", "use_custom_avatar").
|
|
OrderBy(user_model.GetOrderByName()).
|
|
Find(&actors)
|
|
}
|