get_contents.go 1.8 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/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. request := &types.GetContentsRequest{}
  28. ok := c.DecodeAndValidate(w, r, request)
  29. if !ok {
  30. return
  31. }
  32. owner, name, ok := GetOwnerAndNameParams(c, w, r)
  33. if !ok {
  34. return
  35. }
  36. branch, ok := GetBranch(c, w, r)
  37. if !ok {
  38. return
  39. }
  40. client, err := GetGithubAppClientFromRequest(c.Config(), r)
  41. if err != nil {
  42. c.HandleAPIError(w, r, apierrors.NewErrInternal(err))
  43. return
  44. }
  45. repoContentOptions := github.RepositoryContentGetOptions{}
  46. repoContentOptions.Ref = branch
  47. _, directoryContents, _, err := client.Repositories.GetContents(
  48. context.Background(),
  49. owner,
  50. name,
  51. request.Dir,
  52. &repoContentOptions,
  53. )
  54. if err != nil {
  55. c.HandleAPIError(w, r, apierrors.NewErrInternal(err))
  56. return
  57. }
  58. res := make(types.GetContentsResponse, 0)
  59. for i := range directoryContents {
  60. res = append(res, types.GithubDirectoryItem{
  61. Path: *directoryContents[i].Path,
  62. Type: *directoryContents[i].Type,
  63. })
  64. }
  65. c.WriteResult(w, r, res)
  66. }