git_repo_handler.go 7.4 KB

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