2
0

git_utils.go 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687
  1. package commonutils
  2. import (
  3. "context"
  4. "errors"
  5. "net/http"
  6. "net/url"
  7. "time"
  8. "github.com/google/go-github/v41/github"
  9. "github.com/porter-dev/porter/api/server/handlers"
  10. "github.com/porter-dev/porter/api/server/shared/apierrors"
  11. "github.com/porter-dev/porter/api/server/shared/requestutils"
  12. "github.com/porter-dev/porter/api/types"
  13. )
  14. var (
  15. ErrNoWorkflowRuns = errors.New("no previous workflow runs found")
  16. ErrWorkflowNotFound = errors.New("no workflow found, file missing")
  17. )
  18. func GetLatestWorkflowRun(client *github.Client, owner, repo, filename, branch string) (*github.WorkflowRun, error) {
  19. ctx, cancel := context.WithTimeout(context.Background(), time.Second*5)
  20. defer cancel()
  21. workflowRuns, ghResponse, err := client.Actions.ListWorkflowRunsByFileName(
  22. ctx, owner, repo, filename, &github.ListWorkflowRunsOptions{
  23. Branch: branch,
  24. ListOptions: github.ListOptions{
  25. Page: 1,
  26. PerPage: 1,
  27. },
  28. },
  29. )
  30. if ghResponse != nil && ghResponse.StatusCode == http.StatusNotFound {
  31. return nil, ErrWorkflowNotFound
  32. }
  33. if err != nil {
  34. return nil, err
  35. }
  36. if workflowRuns == nil || workflowRuns.GetTotalCount() == 0 || len(workflowRuns.WorkflowRuns) == 0 {
  37. return nil, ErrNoWorkflowRuns
  38. }
  39. return workflowRuns.WorkflowRuns[0], nil
  40. }
  41. // GetOwnerAndNameParams gets the owner and name ref for the git repo
  42. func GetOwnerAndNameParams(c handlers.PorterHandler, w http.ResponseWriter, r *http.Request) (string, string, bool) {
  43. owner, reqErr := requestutils.GetURLParamString(r, types.URLParamGitRepoOwner)
  44. if reqErr != nil {
  45. c.HandleAPIError(w, r, reqErr)
  46. return "", "", false
  47. }
  48. name, reqErr := requestutils.GetURLParamString(r, types.URLParamGitRepoName)
  49. if reqErr != nil {
  50. c.HandleAPIError(w, r, reqErr)
  51. return "", "", false
  52. }
  53. return owner, name, true
  54. }
  55. // GetBranchParam gets the unencoded branch for the git repo
  56. func GetBranchParam(c handlers.PorterHandler, w http.ResponseWriter, r *http.Request) (string, bool) {
  57. branch, reqErr := requestutils.GetURLParamString(r, types.URLParamGitBranch)
  58. if reqErr != nil {
  59. c.HandleAPIError(w, r, reqErr)
  60. return "", false
  61. }
  62. branch, err := url.QueryUnescape(branch)
  63. if reqErr != nil {
  64. c.HandleAPIError(w, r, apierrors.NewErrInternal(err))
  65. return "", false
  66. }
  67. return branch, true
  68. }