get_tarball_url.go 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384
  1. package gitinstallation
  2. import (
  3. "context"
  4. "net/http"
  5. "github.com/google/go-github/v41/github"
  6. "github.com/porter-dev/porter/api/server/authz"
  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/commonutils"
  11. "github.com/porter-dev/porter/api/server/shared/config"
  12. "github.com/porter-dev/porter/api/types"
  13. )
  14. type GithubGetTarballURLHandler struct {
  15. handlers.PorterHandlerReadWriter
  16. authz.KubernetesAgentGetter
  17. }
  18. func NewGithubGetTarballURLHandler(
  19. config *config.Config,
  20. decoderValidator shared.RequestDecoderValidator,
  21. writer shared.ResultWriter,
  22. ) *GithubGetTarballURLHandler {
  23. return &GithubGetTarballURLHandler{
  24. PorterHandlerReadWriter: handlers.NewDefaultPorterHandler(config, decoderValidator, writer),
  25. }
  26. }
  27. func (c *GithubGetTarballURLHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
  28. owner, name, ok := commonutils.GetOwnerAndNameParams(c, w, r)
  29. if !ok {
  30. return
  31. }
  32. branch, ok := commonutils.GetBranchParam(c, w, r)
  33. if !ok {
  34. return
  35. }
  36. client, err := GetGithubAppClientFromRequest(c.Config(), r)
  37. if err != nil {
  38. c.HandleAPIError(w, r, apierrors.NewErrInternal(err))
  39. return
  40. }
  41. branchResp, _, err := client.Repositories.GetBranch(
  42. context.TODO(),
  43. owner,
  44. name,
  45. branch,
  46. false,
  47. )
  48. if err != nil {
  49. c.HandleAPIError(w, r, apierrors.NewErrInternal(err))
  50. return
  51. }
  52. ghURL, _, err := client.Repositories.GetArchiveLink(
  53. context.TODO(),
  54. owner,
  55. name,
  56. github.Zipball,
  57. &github.RepositoryContentGetOptions{
  58. Ref: *branchResp.Commit.SHA,
  59. },
  60. false,
  61. )
  62. if err != nil {
  63. c.HandleAPIError(w, r, apierrors.NewErrInternal(err))
  64. return
  65. }
  66. apiResp := &types.GetTarballURLResponse{
  67. URLString: ghURL.String(),
  68. LatestCommitSHA: *branchResp.Commit.SHA,
  69. }
  70. c.WriteResult(w, r, apiResp)
  71. }