get_contents.go 1.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485
  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 GithubGetContentsHandler struct {
  15. handlers.PorterHandlerReadWriter
  16. authz.KubernetesAgentGetter
  17. }
  18. func NewGithubGetContentsHandler(
  19. config *config.Config,
  20. decoderValidator shared.RequestDecoderValidator,
  21. writer shared.ResultWriter,
  22. ) *GithubGetContentsHandler {
  23. return &GithubGetContentsHandler{
  24. PorterHandlerReadWriter: handlers.NewDefaultPorterHandler(config, decoderValidator, writer),
  25. }
  26. }
  27. func (c *GithubGetContentsHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
  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, _, err := client.Repositories.GetContents(
  49. context.Background(),
  50. owner,
  51. name,
  52. request.Dir,
  53. &repoContentOptions,
  54. )
  55. if err != nil {
  56. c.HandleAPIError(w, r, apierrors.NewErrInternal(err))
  57. return
  58. }
  59. res := make(types.GetContentsResponse, 0)
  60. for i := range directoryContents {
  61. res = append(res, types.GithubDirectoryItem{
  62. Path: *directoryContents[i].Path,
  63. Type: *directoryContents[i].Type,
  64. })
  65. }
  66. c.WriteResult(w, r, res)
  67. }