git_repo_handler.go 7.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310
  1. package api
  2. import (
  3. "context"
  4. "encoding/json"
  5. "fmt"
  6. "net/http"
  7. "net/url"
  8. "regexp"
  9. "strconv"
  10. "strings"
  11. "golang.org/x/oauth2"
  12. "github.com/go-chi/chi"
  13. "github.com/google/go-github/github"
  14. "github.com/porter-dev/porter/internal/models"
  15. )
  16. // HandleListProjectGitRepos returns a list of git repos for a project
  17. func (app *App) HandleListProjectGitRepos(w http.ResponseWriter, r *http.Request) {
  18. projID, err := strconv.ParseUint(chi.URLParam(r, "project_id"), 0, 64)
  19. if err != nil || projID == 0 {
  20. app.handleErrorFormDecoding(err, ErrProjectDecode, w)
  21. return
  22. }
  23. grs, err := app.Repo.GitRepo.ListGitReposByProjectID(uint(projID))
  24. if err != nil {
  25. app.handleErrorRead(err, ErrProjectDataRead, w)
  26. return
  27. }
  28. extGRs := make([]*models.GitRepoExternal, 0)
  29. for _, gr := range grs {
  30. extGRs = append(extGRs, gr.Externalize())
  31. }
  32. w.WriteHeader(http.StatusOK)
  33. if err := json.NewEncoder(w).Encode(extGRs); err != nil {
  34. app.handleErrorFormDecoding(err, ErrProjectDecode, w)
  35. return
  36. }
  37. }
  38. // Repo represents a GitHub or Gitab repository
  39. type Repo struct {
  40. FullName string
  41. Kind string
  42. }
  43. // DirectoryItem represents a file or subfolder in a repository
  44. type DirectoryItem struct {
  45. Path string
  46. Type string
  47. }
  48. // HandleSearchRepos searches user repos
  49. func (app *App) HandleSearchRepos(w http.ResponseWriter, r *http.Request) {
  50. tok, err := app.githubTokenFromRequest(r)
  51. if err != nil {
  52. app.handleErrorInternal(err, w)
  53. return
  54. }
  55. json.NewEncoder(w).Encode(tok)
  56. }
  57. // HandleListRepos retrieves a list of repo names
  58. func (app *App) HandleListRepos(w http.ResponseWriter, r *http.Request) {
  59. tok, err := app.githubTokenFromRequest(r)
  60. if err != nil {
  61. app.handleErrorInternal(err, w)
  62. return
  63. }
  64. res := make([]Repo, 0)
  65. client := github.NewClient(app.GithubProjectConf.Client(oauth2.NoContext, tok))
  66. allRepos := make([]*github.Repository, 0)
  67. opt := &github.RepositoryListOptions{
  68. ListOptions: github.ListOptions{
  69. PerPage: 100,
  70. },
  71. Sort: "updated",
  72. }
  73. for {
  74. repos, resp, err := client.Repositories.List(context.Background(), "", opt)
  75. if err != nil {
  76. app.handleErrorInternal(err, w)
  77. return
  78. }
  79. allRepos = append(allRepos, repos...)
  80. if resp.NextPage == 0 {
  81. break
  82. }
  83. opt.Page = resp.NextPage
  84. }
  85. for _, repo := range allRepos {
  86. res = append(res, Repo{
  87. FullName: repo.GetFullName(),
  88. Kind: "github",
  89. })
  90. }
  91. json.NewEncoder(w).Encode(res)
  92. }
  93. // HandleDeleteProjectGitRepo handles the deletion of a Github Repo via the git repo ID
  94. func (app *App) HandleDeleteProjectGitRepo(w http.ResponseWriter, r *http.Request) {
  95. id, err := strconv.ParseUint(chi.URLParam(r, "git_repo_id"), 0, 64)
  96. if err != nil || id == 0 {
  97. app.handleErrorFormDecoding(err, ErrProjectDecode, w)
  98. return
  99. }
  100. repo, err := app.Repo.GitRepo.ReadGitRepo(uint(id))
  101. if err != nil {
  102. app.handleErrorRead(err, ErrProjectDataRead, w)
  103. return
  104. }
  105. err = app.Repo.GitRepo.DeleteGitRepo(repo)
  106. if err != nil {
  107. app.handleErrorRead(err, ErrProjectDataRead, w)
  108. return
  109. }
  110. w.WriteHeader(http.StatusOK)
  111. }
  112. // HandleGetBranches retrieves a list of branch names for a specified repo
  113. func (app *App) HandleGetBranches(w http.ResponseWriter, r *http.Request) {
  114. tok, err := app.githubTokenFromRequest(r)
  115. if err != nil {
  116. app.handleErrorInternal(err, w)
  117. return
  118. }
  119. owner := chi.URLParam(r, "owner")
  120. name := chi.URLParam(r, "name")
  121. client := github.NewClient(app.GithubProjectConf.Client(oauth2.NoContext, tok))
  122. // List all branches for a specified repo
  123. branches, _, err := client.Repositories.ListBranches(context.Background(), owner, name, &github.ListOptions{
  124. PerPage: 100,
  125. })
  126. if err != nil {
  127. return
  128. }
  129. res := []string{}
  130. for _, b := range branches {
  131. res = append(res, b.GetName())
  132. }
  133. json.NewEncoder(w).Encode(res)
  134. }
  135. // HandleGetBranchContents retrieves the contents of a specific branch and subdirectory
  136. func (app *App) HandleGetBranchContents(w http.ResponseWriter, r *http.Request) {
  137. tok, err := app.githubTokenFromRequest(r)
  138. if err != nil {
  139. app.handleErrorInternal(err, w)
  140. return
  141. }
  142. client := github.NewClient(app.GithubProjectConf.Client(oauth2.NoContext, tok))
  143. queryParams, err := url.ParseQuery(r.URL.RawQuery)
  144. if err != nil {
  145. app.handleErrorFormDecoding(err, ErrReleaseDecode, w)
  146. return
  147. }
  148. owner := chi.URLParam(r, "owner")
  149. name := chi.URLParam(r, "name")
  150. branch := chi.URLParam(r, "branch")
  151. repoContentOptions := github.RepositoryContentGetOptions{}
  152. repoContentOptions.Ref = branch
  153. _, directoryContents, _, err := client.Repositories.GetContents(context.Background(), owner, name, queryParams["dir"][0], &repoContentOptions)
  154. if err != nil {
  155. app.handleErrorInternal(err, w)
  156. return
  157. }
  158. res := []DirectoryItem{}
  159. for i := range directoryContents {
  160. d := DirectoryItem{}
  161. d.Path = *directoryContents[i].Path
  162. d.Type = *directoryContents[i].Type
  163. res = append(res, d)
  164. }
  165. // Ret2: recursively traverse all dirs to create config bundle (case on type == dir)
  166. // https://api.github.com/repos/porter-dev/porter/contents?ref=frontend-graph
  167. json.NewEncoder(w).Encode(res)
  168. }
  169. type GetProcfileContentsResp map[string]string
  170. var procfileRegex = regexp.MustCompile("^([A-Za-z0-9_]+):\\s*(.+)$")
  171. // HandleGetProcfileContents retrieves the contents of a procfile in a github repo
  172. func (app *App) HandleGetProcfileContents(w http.ResponseWriter, r *http.Request) {
  173. tok, err := app.githubTokenFromRequest(r)
  174. if err != nil {
  175. app.handleErrorInternal(err, w)
  176. return
  177. }
  178. client := github.NewClient(app.GithubProjectConf.Client(oauth2.NoContext, tok))
  179. owner := chi.URLParam(r, "owner")
  180. name := chi.URLParam(r, "name")
  181. branch := chi.URLParam(r, "branch")
  182. queryParams, err := url.ParseQuery(r.URL.RawQuery)
  183. if err != nil {
  184. app.handleErrorFormDecoding(err, ErrReleaseDecode, w)
  185. return
  186. }
  187. resp, _, _, err := client.Repositories.GetContents(
  188. context.TODO(),
  189. owner,
  190. name,
  191. queryParams["path"][0],
  192. &github.RepositoryContentGetOptions{
  193. Ref: branch,
  194. },
  195. )
  196. if err != nil {
  197. app.handleErrorInternal(err, w)
  198. return
  199. }
  200. fileData, err := resp.GetContent()
  201. if err != nil {
  202. app.handleErrorInternal(err, w)
  203. return
  204. }
  205. parsedContents := make(GetProcfileContentsResp)
  206. // parse the procfile information
  207. for _, line := range strings.Split(fileData, "\n") {
  208. if matches := procfileRegex.FindStringSubmatch(line); matches != nil {
  209. parsedContents[matches[1]] = matches[2]
  210. }
  211. }
  212. json.NewEncoder(w).Encode(parsedContents)
  213. }
  214. // finds the github token given the git repo id and the project id
  215. func (app *App) githubTokenFromRequest(
  216. r *http.Request,
  217. ) (*oauth2.Token, error) {
  218. grID, err := strconv.ParseUint(chi.URLParam(r, "git_repo_id"), 0, 64)
  219. if err != nil || grID == 0 {
  220. return nil, fmt.Errorf("could not read git repo id")
  221. }
  222. // query for the git repo
  223. gr, err := app.Repo.GitRepo.ReadGitRepo(uint(grID))
  224. if err != nil {
  225. return nil, err
  226. }
  227. // get the oauth integration
  228. oauthInt, err := app.Repo.OAuthIntegration.ReadOAuthIntegration(gr.OAuthIntegrationID)
  229. if err != nil {
  230. return nil, err
  231. }
  232. return &oauth2.Token{
  233. AccessToken: string(oauthInt.AccessToken),
  234. RefreshToken: string(oauthInt.RefreshToken),
  235. TokenType: "Bearer",
  236. }, nil
  237. }