get_contents.go 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384
  1. package gitinstallation
  2. import (
  3. "net/http"
  4. "github.com/google/go-github/v41/github"
  5. "github.com/porter-dev/porter/api/server/authz"
  6. "github.com/porter-dev/porter/api/server/handlers"
  7. "github.com/porter-dev/porter/api/server/shared"
  8. "github.com/porter-dev/porter/api/server/shared/apierrors"
  9. "github.com/porter-dev/porter/api/server/shared/commonutils"
  10. "github.com/porter-dev/porter/api/server/shared/config"
  11. "github.com/porter-dev/porter/api/types"
  12. )
  13. type GithubGetContentsHandler struct {
  14. handlers.PorterHandlerReadWriter
  15. authz.KubernetesAgentGetter
  16. }
  17. func NewGithubGetContentsHandler(
  18. config *config.Config,
  19. decoderValidator shared.RequestDecoderValidator,
  20. writer shared.ResultWriter,
  21. ) *GithubGetContentsHandler {
  22. return &GithubGetContentsHandler{
  23. PorterHandlerReadWriter: handlers.NewDefaultPorterHandler(config, decoderValidator, writer),
  24. }
  25. }
  26. func (c *GithubGetContentsHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
  27. ctx := r.Context()
  28. request := &types.GetContentsRequest{}
  29. ok := c.DecodeAndValidate(w, r, request)
  30. if !ok {
  31. return
  32. }
  33. owner, name, ok := commonutils.GetOwnerAndNameParams(c, w, r)
  34. if !ok {
  35. return
  36. }
  37. branch, ok := commonutils.GetBranchParam(c, w, r)
  38. if !ok {
  39. return
  40. }
  41. client, err := GetGithubAppClientFromRequest(c.Config(), r)
  42. if err != nil {
  43. c.HandleAPIError(w, r, apierrors.NewErrInternal(err))
  44. return
  45. }
  46. repoContentOptions := github.RepositoryContentGetOptions{}
  47. repoContentOptions.Ref = branch
  48. _, directoryContents, resp, err := client.Repositories.GetContents(
  49. ctx,
  50. owner,
  51. name,
  52. request.Dir,
  53. &repoContentOptions,
  54. )
  55. if err != nil {
  56. c.HandleAPIError(w, r, apierrors.NewErrPassThroughToClient(
  57. err, resp.StatusCode))
  58. return
  59. }
  60. res := make(types.GetContentsResponse, 0)
  61. for i := range directoryContents {
  62. res = append(res, types.GithubDirectoryItem{
  63. Path: *directoryContents[i].Path,
  64. Type: *directoryContents[i].Type,
  65. })
  66. }
  67. c.WriteResult(w, r, res)
  68. }