gitea源码

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960
  1. // Copyright 2024 The Gitea Authors. All rights reserved.
  2. // SPDX-License-Identifier: MIT
  3. package actions
  4. import (
  5. "errors"
  6. "net/http"
  7. "path/filepath"
  8. "strings"
  9. actions_model "code.gitea.io/gitea/models/actions"
  10. "code.gitea.io/gitea/modules/badge"
  11. "code.gitea.io/gitea/modules/git"
  12. "code.gitea.io/gitea/modules/util"
  13. "code.gitea.io/gitea/services/context"
  14. )
  15. func GetWorkflowBadge(ctx *context.Context) {
  16. workflowFile := ctx.PathParam("workflow_name")
  17. branch := ctx.FormString("branch", ctx.Repo.Repository.DefaultBranch)
  18. event := ctx.FormString("event")
  19. style := ctx.FormString("style")
  20. branchRef := git.RefNameFromBranch(branch)
  21. b, err := getWorkflowBadge(ctx, workflowFile, branchRef.String(), event)
  22. if err != nil {
  23. ctx.ServerError("GetWorkflowBadge", err)
  24. return
  25. }
  26. ctx.Data["Badge"] = b
  27. ctx.RespHeader().Set("Content-Type", "image/svg+xml")
  28. switch style {
  29. case badge.StyleFlatSquare:
  30. ctx.HTML(http.StatusOK, "shared/actions/runner_badge_flat-square")
  31. default: // defaults to badge.StyleFlat
  32. ctx.HTML(http.StatusOK, "shared/actions/runner_badge_flat")
  33. }
  34. }
  35. func getWorkflowBadge(ctx *context.Context, workflowFile, branchName, event string) (badge.Badge, error) {
  36. extension := filepath.Ext(workflowFile)
  37. workflowName := strings.TrimSuffix(workflowFile, extension)
  38. run, err := actions_model.GetWorkflowLatestRun(ctx, ctx.Repo.Repository.ID, workflowFile, branchName, event)
  39. if err != nil {
  40. if errors.Is(err, util.ErrNotExist) {
  41. return badge.GenerateBadge(workflowName, "no status", badge.DefaultColor), nil
  42. }
  43. return badge.Badge{}, err
  44. }
  45. color, ok := badge.GlobalVars().StatusColorMap[run.Status]
  46. if !ok {
  47. return badge.GenerateBadge(workflowName, "unknown status", badge.DefaultColor), nil
  48. }
  49. return badge.GenerateBadge(workflowName, run.Status.String(), color), nil
  50. }