enable_pull_request.go 1.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273
  1. package environment
  2. import (
  3. "fmt"
  4. "net/http"
  5. "strconv"
  6. "github.com/google/go-github/v41/github"
  7. "github.com/porter-dev/porter/api/server/handlers"
  8. "github.com/porter-dev/porter/api/server/shared"
  9. "github.com/porter-dev/porter/api/server/shared/apierrors"
  10. "github.com/porter-dev/porter/api/server/shared/config"
  11. "github.com/porter-dev/porter/api/types"
  12. )
  13. type EnablePullRequestHandler struct {
  14. handlers.PorterHandlerReadWriter
  15. }
  16. func NewEnablePullRequestHandler(
  17. config *config.Config,
  18. decoderValidator shared.RequestDecoderValidator,
  19. writer shared.ResultWriter,
  20. ) *EnablePullRequestHandler {
  21. return &EnablePullRequestHandler{
  22. PorterHandlerReadWriter: handlers.NewDefaultPorterHandler(config, decoderValidator, writer),
  23. }
  24. }
  25. func (c *EnablePullRequestHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
  26. request := &types.PullRequest{}
  27. if ok := c.DecodeAndValidate(w, r, request); !ok {
  28. return
  29. }
  30. env, err := c.Repo().Environment().ReadEnvironmentByOwnerRepoName(request.RepoOwner, request.RepoName)
  31. if err != nil {
  32. c.HandleAPIError(w, r, apierrors.NewErrInternal(err))
  33. return
  34. }
  35. client, err := getGithubClientFromEnvironment(c.Config(), env)
  36. if err != nil {
  37. c.HandleAPIError(w, r, apierrors.NewErrInternal(err))
  38. return
  39. }
  40. ghResp, err := client.Actions.CreateWorkflowDispatchEventByFileName(
  41. r.Context(), env.GitRepoOwner, env.GitRepoName, fmt.Sprintf("porter_%s_env.yml", env.Name),
  42. github.CreateWorkflowDispatchEventRequest{
  43. Ref: request.BranchFrom,
  44. Inputs: map[string]interface{}{
  45. "pr_number": strconv.FormatUint(uint64(request.Number), 10),
  46. "pr_title": request.Title,
  47. "pr_branch_from": request.BranchFrom,
  48. "pr_branch_into": request.BranchInto,
  49. },
  50. },
  51. )
  52. if ghResp.StatusCode == 404 {
  53. c.HandleAPIError(w, r, apierrors.NewErrPassThroughToClient(fmt.Errorf("workflow file not found"), 404))
  54. return
  55. }
  56. if err != nil {
  57. c.HandleAPIError(w, r, apierrors.NewErrInternal(err))
  58. return
  59. }
  60. }