|
| 1 | +// Copyright 2024 The Gitea Authors. All rights reserved. |
| 2 | +// SPDX-License-Identifier: MIT |
| 3 | + |
| 4 | +package actions |
| 5 | + |
| 6 | +import ( |
| 7 | + "errors" |
| 8 | + "fmt" |
| 9 | + "net/http" |
| 10 | + "path/filepath" |
| 11 | + "strings" |
| 12 | + |
| 13 | + actions_model "code.gitea.io/gitea/models/actions" |
| 14 | + "code.gitea.io/gitea/modules/badge" |
| 15 | + "code.gitea.io/gitea/modules/util" |
| 16 | + "code.gitea.io/gitea/services/context" |
| 17 | +) |
| 18 | + |
| 19 | +func GetWorkflowBadge(ctx *context.Context) { |
| 20 | + workflowFile := ctx.Params("workflow_name") |
| 21 | + branch := ctx.Req.URL.Query().Get("branch") |
| 22 | + if branch == "" { |
| 23 | + branch = ctx.Repo.Repository.DefaultBranch |
| 24 | + } |
| 25 | + branchRef := fmt.Sprintf("refs/heads/%s", branch) |
| 26 | + event := ctx.Req.URL.Query().Get("event") |
| 27 | + |
| 28 | + badge, err := getWorkflowBadge(ctx, workflowFile, branchRef, event) |
| 29 | + if err != nil { |
| 30 | + ctx.ServerError("GetWorkflowBadge", err) |
| 31 | + return |
| 32 | + } |
| 33 | + |
| 34 | + ctx.Data["Badge"] = badge |
| 35 | + ctx.RespHeader().Set("Content-Type", "image/svg+xml") |
| 36 | + ctx.HTML(http.StatusOK, "shared/actions/runner_badge") |
| 37 | +} |
| 38 | + |
| 39 | +func getWorkflowBadge(ctx *context.Context, workflowFile, branchName, event string) (badge.Badge, error) { |
| 40 | + extension := filepath.Ext(workflowFile) |
| 41 | + workflowName := strings.TrimSuffix(workflowFile, extension) |
| 42 | + |
| 43 | + run, err := actions_model.GetWorkflowLatestRun(ctx, ctx.Repo.Repository.ID, workflowFile, branchName, event) |
| 44 | + if err != nil { |
| 45 | + if errors.Is(err, util.ErrNotExist) { |
| 46 | + return badge.GenerateBadge(workflowName, "no status", badge.DefaultColor), nil |
| 47 | + } |
| 48 | + return badge.Badge{}, err |
| 49 | + } |
| 50 | + |
| 51 | + color, ok := badge.StatusColorMap[run.Status] |
| 52 | + if !ok { |
| 53 | + return badge.GenerateBadge(workflowName, "unknown status", badge.DefaultColor), nil |
| 54 | + } |
| 55 | + return badge.GenerateBadge(workflowName, run.Status.String(), color), nil |
| 56 | +} |
0 commit comments