mirror of
https://github.com/go-gitea/gitea.git
synced 2026-10-26 06:16:56 +09:00
This PR introduces project workflows, allowing users to configure event-based automations directly from the UI. Users can define filters and actions for each workflow event, and duplicate existing events when needed. ### Concepts Every workflow is composed of `event`, `filters`, and `actions`. - **Event** - An Event defines when a workflow should be triggered. It represents specific activities such as an issue being added to the project, a pull request being merged, or a project column being changed. - **Filter** - A Filter refines when an event should take effect. It allows users to specify conditions like issue type, labels, or project columns to ensure actions only run in targeted scenarios. - **Action** - An Action defines what happens when the event and filters match. It performs operations such as adding labels, moving issues between columns, or changing the issue or pull request state. ### Available Events Currently, the following eight events are supported: - On issues/pull requests closed - On issues/pull requests reopened - On issues/pull requests was added to the project, including when created in it - On issues/pull requests was removed from the project - On issues/pull requests' column was changed - On code changes requested - On code review approved - On pull request merged Each event type supports its own set of filters and actions. ### Available Filters There are four types of filters that can be configured for an event: - **Apply to** - Specify the target type: `issues only`, `pull requests only`, or `issues and pull requests`. - **Labels** - Trigger the event only if the issue or pull request contains one or more specified labels. - **Move from column** - Filter events based on the original project column. - **Move to column** - Filter events based on the destination project column. ### Available Actions There are four types of actions that can be executed when an event is triggered: - **Add labels** - Automatically add one or more labels to the issue or pull request. - **Remove labels** - Remove one or more specified labels. - **Move to column** - Move the issue or pull request to a designated project column. - **Issue state** - Close or reopen the issue. Pull requests can only be closed. ### Enable/Disable an event workflow Each event workflow can be individually enabled or disabled. When disabled, the workflow will be ignored even if the event occurs. This feature is useful when you want to temporarily stop certain automated actions without deleting the workflow configuration. Workflows of closed projects don't run either. ### Clone an event workflow When you need multiple workflows for the same event, you can clone an existing event to create a new one with different filters and actions. This allows you to customize how the same event behaves under different conditions, making workflows more flexible and powerful. ### Permissions Permissions are checked when workflows are managed, not when they run: - Viewing a project's workflows needs read access to the project - Managing them needs write access to the project plus write access to both issues and pull requests of a repository project's repository, being an owner of an organization project's organization or a site administrator, or being the user of a user project. Tokens limited to public repositories can't manage owner-level projects' workflows - A workflow runs when its event happens to an item of an open project that can hold the item's repository, unless that repository is archived, no matter who caused the event, and applies its actions without further permission checks. Pull requests are never reopened - Changes show as made by "Project workflow" on behalf of the user who triggered the event and don't trigger other workflows - Only users who can read an item can put it on a board or move its card The management rule is also documented on `CanManageWorkflows` in `services/projects/workflow.go`. Fixes: #14359 Fixes: #26704 Fixes: #27990 Replaces: #28745 Documentation PR: https://gitea.com/gitea/docs/pulls/308 Co-authored-by: bircni <bircni@icloud.com> Co-authored-by: silverwind <me@silverwind.io> Co-authored-by: Giteabot <teabot@gitea.io>
489 lines
14 KiB
Go
489 lines
14 KiB
Go
// Copyright 2020 The Gitea Authors. All rights reserved.
|
|
// SPDX-License-Identifier: MIT
|
|
|
|
package project
|
|
|
|
import (
|
|
"context"
|
|
"fmt"
|
|
"html/template"
|
|
|
|
"gitea.dev/models/db"
|
|
repo_model "gitea.dev/models/repo"
|
|
user_model "gitea.dev/models/user"
|
|
"gitea.dev/modules/log"
|
|
"gitea.dev/modules/optional"
|
|
"gitea.dev/modules/setting"
|
|
"gitea.dev/modules/timeutil"
|
|
"gitea.dev/modules/util"
|
|
|
|
"xorm.io/builder"
|
|
)
|
|
|
|
type (
|
|
// CardConfig is used to identify the type of column card that is being used
|
|
CardConfig struct {
|
|
CardType CardType
|
|
Translation string
|
|
}
|
|
|
|
// Type is used to identify the type of project in question and ownership
|
|
Type uint8
|
|
)
|
|
|
|
const (
|
|
// TypeIndividual is a type of project column that is owned by an individual
|
|
TypeIndividual Type = iota + 1
|
|
|
|
// TypeRepository is a project that is tied to a repository
|
|
TypeRepository
|
|
|
|
// TypeOrganization is a project that is tied to an organisation
|
|
TypeOrganization
|
|
)
|
|
|
|
// ErrProjectNotExist represents a "ProjectNotExist" kind of error.
|
|
type ErrProjectNotExist struct {
|
|
ID int64
|
|
RepoID int64
|
|
}
|
|
|
|
// IsErrProjectNotExist checks if an error is a ErrProjectNotExist
|
|
func IsErrProjectNotExist(err error) bool {
|
|
_, ok := err.(ErrProjectNotExist)
|
|
return ok
|
|
}
|
|
|
|
func (err ErrProjectNotExist) Error() string {
|
|
return fmt.Sprintf("projects does not exist [id: %d]", err.ID)
|
|
}
|
|
|
|
func (err ErrProjectNotExist) Unwrap() error {
|
|
return util.ErrNotExist
|
|
}
|
|
|
|
// ErrProjectColumnNotExist represents a "ErrProjectColumnNotExist" kind of error.
|
|
type ErrProjectColumnNotExist struct {
|
|
ColumnID int64
|
|
}
|
|
|
|
// IsErrProjectColumnNotExist checks if an error is a ErrProjectColumnNotExist
|
|
func IsErrProjectColumnNotExist(err error) bool {
|
|
_, ok := err.(ErrProjectColumnNotExist)
|
|
return ok
|
|
}
|
|
|
|
func (err ErrProjectColumnNotExist) Error() string {
|
|
return fmt.Sprintf("project column does not exist [id: %d]", err.ColumnID)
|
|
}
|
|
|
|
func (err ErrProjectColumnNotExist) Unwrap() error {
|
|
return util.ErrNotExist
|
|
}
|
|
|
|
// Project represents a project
|
|
type Project struct {
|
|
ID int64 `xorm:"pk autoincr"`
|
|
Title string `xorm:"INDEX NOT NULL"`
|
|
Description string `xorm:"TEXT"`
|
|
OwnerID int64 `xorm:"INDEX"`
|
|
Owner *user_model.User `xorm:"-"`
|
|
RepoID int64 `xorm:"INDEX"`
|
|
Repo *repo_model.Repository `xorm:"-"`
|
|
CreatorID int64 `xorm:"NOT NULL"`
|
|
IsClosed bool `xorm:"INDEX"`
|
|
TemplateType TemplateType `xorm:"'board_type'"` // TODO: rename the column to template_type
|
|
CardType CardType
|
|
Type Type
|
|
|
|
RenderedContent template.HTML `xorm:"-"`
|
|
NumOpenIssues int64 `xorm:"-"`
|
|
NumClosedIssues int64 `xorm:"-"`
|
|
NumIssues int64 `xorm:"-"`
|
|
|
|
CreatedUnix timeutil.TimeStamp `xorm:"INDEX created"`
|
|
UpdatedUnix timeutil.TimeStamp `xorm:"INDEX updated"`
|
|
ClosedDateUnix timeutil.TimeStamp
|
|
}
|
|
|
|
// Ghost Project is a project which has been deleted
|
|
const GhostProjectID = -1
|
|
|
|
func (p *Project) IsGhost() bool {
|
|
return p.ID == GhostProjectID
|
|
}
|
|
|
|
func (p *Project) LoadOwner(ctx context.Context) (err error) {
|
|
if p.Owner != nil {
|
|
return nil
|
|
}
|
|
p.Owner, err = user_model.GetUserByID(ctx, p.OwnerID)
|
|
return err
|
|
}
|
|
|
|
func (p *Project) LoadRepo(ctx context.Context) (err error) {
|
|
if p.RepoID == 0 || p.Repo != nil {
|
|
return nil
|
|
}
|
|
p.Repo, err = repo_model.GetRepositoryByID(ctx, p.RepoID)
|
|
return err
|
|
}
|
|
|
|
func ProjectLinkForOrg(org *user_model.User, projectID int64) string { //nolint:revive // export stutter
|
|
return fmt.Sprintf("%s/-/projects/%d", org.HomeLink(), projectID)
|
|
}
|
|
|
|
func ProjectLinkForRepo(repo *repo_model.Repository, projectID int64) string { //nolint:revive // export stutter
|
|
return fmt.Sprintf("%s/projects/%d", repo.Link(), projectID)
|
|
}
|
|
|
|
// Link returns the project's relative URL.
|
|
func (p *Project) Link(ctx context.Context) string {
|
|
if p.OwnerID > 0 {
|
|
err := p.LoadOwner(ctx)
|
|
if err != nil {
|
|
log.Error("LoadOwner: %v", err)
|
|
return ""
|
|
}
|
|
return ProjectLinkForOrg(p.Owner, p.ID)
|
|
}
|
|
if p.RepoID > 0 {
|
|
err := p.LoadRepo(ctx)
|
|
if err != nil {
|
|
log.Error("LoadRepo: %v", err)
|
|
return ""
|
|
}
|
|
return ProjectLinkForRepo(p.Repo, p.ID)
|
|
}
|
|
return ""
|
|
}
|
|
|
|
func (p *Project) IconName() string {
|
|
if p.IsRepositoryProject() {
|
|
return "octicon-project"
|
|
}
|
|
return "octicon-project-symlink"
|
|
}
|
|
|
|
func (p *Project) IsOrganizationProject() bool {
|
|
return p.Type == TypeOrganization
|
|
}
|
|
|
|
func (p *Project) IsRepositoryProject() bool {
|
|
return p.Type == TypeRepository
|
|
}
|
|
|
|
func (p *Project) CanBeAccessedByOwnerRepo(ownerID int64, repo *repo_model.Repository) bool {
|
|
if p.Type == TypeRepository {
|
|
return repo != nil && p.RepoID == repo.ID // if a project belongs to a repository, then its OwnerID is 0 and can be ignored
|
|
}
|
|
return p.OwnerID == ownerID && p.RepoID == 0
|
|
}
|
|
|
|
func init() {
|
|
db.RegisterModel(new(Project))
|
|
}
|
|
|
|
// GetCardConfig retrieves the types of configurations project column cards could have
|
|
func GetCardConfig() []CardConfig {
|
|
return []CardConfig{
|
|
{CardTypeTextOnly, "repo.projects.card_type.text_only"},
|
|
{CardTypeImagesAndText, "repo.projects.card_type.images_and_text"},
|
|
}
|
|
}
|
|
|
|
// IsTypeValid checks if a project type is valid
|
|
func IsTypeValid(p Type) bool {
|
|
switch p {
|
|
case TypeIndividual, TypeRepository, TypeOrganization:
|
|
return true
|
|
default:
|
|
return false
|
|
}
|
|
}
|
|
|
|
// SearchOptions are options for GetProjects
|
|
type SearchOptions struct {
|
|
db.ListOptions
|
|
OwnerID int64
|
|
RepoID int64
|
|
IsClosed optional.Option[bool]
|
|
OrderBy db.SearchOrderBy
|
|
Type Type
|
|
Title string
|
|
}
|
|
|
|
func (opts SearchOptions) ToConds() builder.Cond {
|
|
cond := builder.NewCond()
|
|
if opts.RepoID > 0 {
|
|
cond = cond.And(builder.Eq{"repo_id": opts.RepoID})
|
|
}
|
|
if opts.IsClosed.Has() {
|
|
cond = cond.And(builder.Eq{"is_closed": opts.IsClosed.Value()})
|
|
}
|
|
|
|
if opts.Type > 0 {
|
|
cond = cond.And(builder.Eq{"type": opts.Type})
|
|
}
|
|
if opts.OwnerID > 0 {
|
|
cond = cond.And(builder.Eq{"owner_id": opts.OwnerID})
|
|
}
|
|
|
|
if len(opts.Title) != 0 {
|
|
cond = cond.And(db.BuildCaseInsensitiveLike("title", opts.Title))
|
|
}
|
|
return cond
|
|
}
|
|
|
|
func (opts SearchOptions) ToOrders() string {
|
|
return util.IfZero(opts.OrderBy.String(), "id")
|
|
}
|
|
|
|
func GetSearchOrderByBySortType(sortType string) db.SearchOrderBy {
|
|
switch sortType {
|
|
case "oldest":
|
|
return db.SearchOrderByOldest
|
|
case "recentupdate":
|
|
return db.SearchOrderByRecentUpdated
|
|
case "leastupdate":
|
|
return db.SearchOrderByLeastUpdated
|
|
case "alphabetically":
|
|
return "title ASC"
|
|
case "reversealphabetically":
|
|
return "title DESC"
|
|
default:
|
|
return db.SearchOrderByNewest
|
|
}
|
|
}
|
|
|
|
// NewProject creates a new Project
|
|
// The title will be cut off at 255 characters if it's longer than 255 characters.
|
|
func NewProject(ctx context.Context, p *Project) error {
|
|
if !IsTemplateTypeValid(p.TemplateType) {
|
|
p.TemplateType = TemplateTypeNone
|
|
}
|
|
|
|
if !IsCardTypeValid(p.CardType) {
|
|
p.CardType = CardTypeTextOnly
|
|
}
|
|
|
|
if !IsTypeValid(p.Type) {
|
|
return util.NewInvalidArgumentErrorf("project type is not valid")
|
|
}
|
|
|
|
p.Title = util.EllipsisDisplayString(p.Title, 255)
|
|
|
|
return db.WithTx(ctx, func(ctx context.Context) error {
|
|
if err := db.Insert(ctx, p); err != nil {
|
|
return err
|
|
}
|
|
|
|
if p.RepoID > 0 {
|
|
if _, err := db.Exec(ctx, "UPDATE `repository` SET num_projects = num_projects + 1 WHERE id = ?", p.RepoID); err != nil {
|
|
return err
|
|
}
|
|
}
|
|
|
|
return createDefaultColumnsForProject(ctx, p)
|
|
})
|
|
}
|
|
|
|
// GetProjectByID returns the projects in a repository
|
|
func GetProjectByID(ctx context.Context, id int64) (*Project, error) {
|
|
p := new(Project)
|
|
|
|
has, err := db.GetEngine(ctx).ID(id).Get(p)
|
|
if err != nil {
|
|
return nil, err
|
|
} else if !has {
|
|
return nil, ErrProjectNotExist{ID: id}
|
|
}
|
|
|
|
return p, nil
|
|
}
|
|
|
|
// GetProjectsMapByIDs returns projects by a list of IDs.
|
|
func GetProjectsMapByIDs(ctx context.Context, ids []int64) (map[int64]*Project, error) {
|
|
projects := make(map[int64]*Project, len(ids))
|
|
if len(ids) == 0 {
|
|
return projects, nil
|
|
}
|
|
return projects, db.GetEngine(ctx).In("id", ids).Find(&projects)
|
|
}
|
|
|
|
func GetProjectByIDAndOwner(ctx context.Context, id, ownerID int64) (*Project, error) {
|
|
p := new(Project)
|
|
has, err := db.GetEngine(ctx).ID(id).And("owner_id = ?", ownerID).Get(p)
|
|
if err != nil {
|
|
return nil, err
|
|
} else if !has {
|
|
return nil, ErrProjectNotExist{ID: id}
|
|
}
|
|
|
|
return p, nil
|
|
}
|
|
|
|
// GetProjectForRepoByID returns the projects in a repository
|
|
func GetProjectForRepoByID(ctx context.Context, repoID, id int64) (*Project, error) {
|
|
p := new(Project)
|
|
has, err := db.GetEngine(ctx).Where("id=? AND repo_id=?", id, repoID).Get(p)
|
|
if err != nil {
|
|
return nil, err
|
|
} else if !has {
|
|
return nil, ErrProjectNotExist{ID: id}
|
|
}
|
|
return p, nil
|
|
}
|
|
|
|
// GetAllProjectsIDsByOwnerID returns the all projects ids it owns
|
|
func GetAllProjectsIDsByOwnerIDAndType(ctx context.Context, ownerID int64, projectType Type) ([]int64, error) {
|
|
projects := make([]int64, 0)
|
|
return projects, db.GetEngine(ctx).Table(&Project{}).Where("owner_id=? AND type=?", ownerID, projectType).Cols("id").Find(&projects)
|
|
}
|
|
|
|
// UpdateProject updates project properties
|
|
func UpdateProject(ctx context.Context, p *Project) error {
|
|
if !IsCardTypeValid(p.CardType) {
|
|
p.CardType = CardTypeTextOnly
|
|
}
|
|
|
|
p.Title = util.EllipsisDisplayString(p.Title, 255)
|
|
_, err := db.GetEngine(ctx).ID(p.ID).Cols(
|
|
"title",
|
|
"description",
|
|
"card_type",
|
|
).Update(p)
|
|
return err
|
|
}
|
|
|
|
func updateRepositoryProjectCount(ctx context.Context, repoID int64) error {
|
|
if _, err := db.GetEngine(ctx).Exec(builder.Update(
|
|
builder.Eq{
|
|
"`num_projects`": builder.Select("count(*)").From("`project`").
|
|
Where(builder.Eq{"`project`.`repo_id`": repoID}.
|
|
And(builder.Eq{"`project`.`type`": TypeRepository})),
|
|
}).From("`repository`").Where(builder.Eq{"id": repoID})); err != nil {
|
|
return err
|
|
}
|
|
|
|
if _, err := db.GetEngine(ctx).Exec(builder.Update(
|
|
builder.Eq{
|
|
"`num_closed_projects`": builder.Select("count(*)").From("`project`").
|
|
Where(builder.Eq{"`project`.`repo_id`": repoID}.
|
|
And(builder.Eq{"`project`.`type`": TypeRepository}).
|
|
And(builder.Eq{"`project`.`is_closed`": true})),
|
|
}).From("`repository`").Where(builder.Eq{"id": repoID})); err != nil {
|
|
return err
|
|
}
|
|
return nil
|
|
}
|
|
|
|
// ChangeProjectStatusByRepoIDAndID toggles a project between opened and closed
|
|
func ChangeProjectStatusByRepoIDAndID(ctx context.Context, repoID, projectID int64, isClosed bool) error {
|
|
return db.WithTx(ctx, func(ctx context.Context) error {
|
|
p := new(Project)
|
|
|
|
has, err := db.GetEngine(ctx).ID(projectID).Where("repo_id = ?", repoID).Get(p)
|
|
if err != nil {
|
|
return err
|
|
} else if !has {
|
|
return ErrProjectNotExist{ID: projectID, RepoID: repoID}
|
|
}
|
|
|
|
return changeProjectStatus(ctx, p, isClosed)
|
|
})
|
|
}
|
|
|
|
// ChangeProjectStatus toggle a project between opened and closed
|
|
func ChangeProjectStatus(ctx context.Context, p *Project, isClosed bool) error {
|
|
return db.WithTx(ctx, func(ctx context.Context) error {
|
|
return changeProjectStatus(ctx, p, isClosed)
|
|
})
|
|
}
|
|
|
|
func changeProjectStatus(ctx context.Context, p *Project, isClosed bool) error {
|
|
p.IsClosed = isClosed
|
|
p.ClosedDateUnix = timeutil.TimeStampNow()
|
|
count, err := db.GetEngine(ctx).ID(p.ID).Where("repo_id = ? AND is_closed = ?", p.RepoID, !isClosed).Cols("is_closed", "closed_date_unix").Update(p)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
if count < 1 {
|
|
return nil
|
|
}
|
|
|
|
return updateRepositoryProjectCount(ctx, p.RepoID)
|
|
}
|
|
|
|
// DeleteProjectByID deletes a project from a repository. if it's not in a database
|
|
// transaction, it will start a new database transaction
|
|
func DeleteProjectByID(ctx context.Context, id int64) error {
|
|
return db.WithTx(ctx, func(ctx context.Context) error {
|
|
p, err := GetProjectByID(ctx, id)
|
|
if err != nil {
|
|
if IsErrProjectNotExist(err) {
|
|
return nil
|
|
}
|
|
return err
|
|
}
|
|
|
|
if err := deleteProjectIssuesByProjectID(ctx, id); err != nil {
|
|
return err
|
|
}
|
|
|
|
if err := deleteColumnByProjectID(ctx, id); err != nil {
|
|
return err
|
|
}
|
|
|
|
if _, err := db.Delete[Workflow](ctx, FindWorkflowsOptions{ProjectIDs: []int64{id}}); err != nil {
|
|
return err
|
|
}
|
|
|
|
if _, err = db.GetEngine(ctx).ID(p.ID).Delete(new(Project)); err != nil {
|
|
return err
|
|
}
|
|
|
|
return updateRepositoryProjectCount(ctx, p.RepoID)
|
|
})
|
|
}
|
|
|
|
func DeleteProjectByRepoID(ctx context.Context, repoID int64) error {
|
|
if _, err := db.GetEngine(ctx).In("project_id", builder.Select("id").From("project").Where(builder.Eq{"repo_id": repoID})).Delete(new(Workflow)); err != nil {
|
|
return err
|
|
}
|
|
switch {
|
|
case setting.Database.Type.IsSQLite3():
|
|
if _, err := db.GetEngine(ctx).Exec("DELETE FROM project_issue WHERE project_issue.id IN (SELECT project_issue.id FROM project_issue INNER JOIN project WHERE project.id = project_issue.project_id AND project.repo_id = ?)", repoID); err != nil {
|
|
return err
|
|
}
|
|
if _, err := db.GetEngine(ctx).Exec("DELETE FROM project_board WHERE project_board.id IN (SELECT project_board.id FROM project_board INNER JOIN project WHERE project.id = project_board.project_id AND project.repo_id = ?)", repoID); err != nil {
|
|
return err
|
|
}
|
|
if _, err := db.GetEngine(ctx).Table("project").Where("repo_id = ? ", repoID).Delete(&Project{}); err != nil {
|
|
return err
|
|
}
|
|
case setting.Database.Type.IsPostgreSQL():
|
|
if _, err := db.GetEngine(ctx).Exec("DELETE FROM project_issue USING project WHERE project.id = project_issue.project_id AND project.repo_id = ? ", repoID); err != nil {
|
|
return err
|
|
}
|
|
if _, err := db.GetEngine(ctx).Exec("DELETE FROM project_board USING project WHERE project.id = project_board.project_id AND project.repo_id = ? ", repoID); err != nil {
|
|
return err
|
|
}
|
|
if _, err := db.GetEngine(ctx).Table("project").Where("repo_id = ? ", repoID).Delete(&Project{}); err != nil {
|
|
return err
|
|
}
|
|
default:
|
|
if _, err := db.GetEngine(ctx).Exec("DELETE project_issue FROM project_issue INNER JOIN project ON project.id = project_issue.project_id WHERE project.repo_id = ? ", repoID); err != nil {
|
|
return err
|
|
}
|
|
if _, err := db.GetEngine(ctx).Exec("DELETE project_board FROM project_board INNER JOIN project ON project.id = project_board.project_id WHERE project.repo_id = ? ", repoID); err != nil {
|
|
return err
|
|
}
|
|
if _, err := db.GetEngine(ctx).Table("project").Where("repo_id = ? ", repoID).Delete(&Project{}); err != nil {
|
|
return err
|
|
}
|
|
}
|
|
|
|
return updateRepositoryProjectCount(ctx, repoID)
|
|
}
|