get_contents.go 2.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586
  1. package gitinstallation
  2. import (
  3. "context"
  4. "net/http"
  5. "github.com/google/go-github/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/server/shared/requestutils"
  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 := GetOwnerAndNameParams(c, w, r)
  34. if !ok {
  35. return
  36. }
  37. branch, reqErr := requestutils.GetURLParamString(r, types.URLParamGitBranch)
  38. if reqErr != nil {
  39. c.HandleAPIError(w, r, reqErr)
  40. return
  41. }
  42. client, err := GetGithubAppClientFromRequest(c.Config(), r)
  43. if err != nil {
  44. c.HandleAPIError(w, r, apierrors.NewErrInternal(err))
  45. return
  46. }
  47. repoContentOptions := github.RepositoryContentGetOptions{}
  48. repoContentOptions.Ref = branch
  49. _, directoryContents, _, err := client.Repositories.GetContents(
  50. context.Background(),
  51. owner,
  52. name,
  53. request.Dir,
  54. &repoContentOptions,
  55. )
  56. if err != nil {
  57. c.HandleAPIError(w, r, apierrors.NewErrInternal(err))
  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. }