git_utils.go 2.2 KB

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