git_repo_handler.go 9.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406
  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. // AutoBuildpack represents an automatically detected buildpack
  50. type AutoBuildpack struct {
  51. Valid bool `json:"valid"`
  52. Name string `json:"name"`
  53. }
  54. // HandleListRepos retrieves a list of repo names
  55. func (app *App) HandleListRepos(w http.ResponseWriter, r *http.Request) {
  56. tok, err := app.githubTokenFromRequest(r)
  57. if err != nil {
  58. app.handleErrorInternal(err, w)
  59. return
  60. }
  61. client := github.NewClient(app.GithubProjectConf.Client(oauth2.NoContext, tok))
  62. // figure out number of repositories
  63. opt := &github.RepositoryListOptions{
  64. ListOptions: github.ListOptions{
  65. PerPage: 100,
  66. },
  67. }
  68. allRepos, resp, err := client.Repositories.List(context.Background(), "", opt)
  69. if err != nil {
  70. app.handleErrorInternal(err, w)
  71. return
  72. }
  73. // make workers to get pages concurrently
  74. const WCOUNT = 5
  75. numPages := resp.LastPage + 1
  76. var workerErr error
  77. var mu sync.Mutex
  78. var wg sync.WaitGroup
  79. worker := func(cp int) {
  80. defer wg.Done()
  81. for cp < numPages {
  82. cur_opt := &github.RepositoryListOptions{
  83. ListOptions: github.ListOptions{
  84. Page: cp,
  85. PerPage: 100,
  86. },
  87. }
  88. repos, _, err := client.Repositories.List(context.Background(), "", cur_opt)
  89. if err != nil {
  90. mu.Lock()
  91. workerErr = err
  92. mu.Unlock()
  93. return
  94. }
  95. mu.Lock()
  96. allRepos = append(allRepos, repos...)
  97. mu.Unlock()
  98. cp += WCOUNT
  99. }
  100. }
  101. var numJobs int
  102. if numPages > WCOUNT {
  103. numJobs = WCOUNT
  104. } else {
  105. numJobs = numPages
  106. }
  107. wg.Add(numJobs)
  108. // page 1 is already loaded so we start with 2
  109. for i := 1; i <= numJobs; i++ {
  110. go worker(i + 1)
  111. }
  112. wg.Wait()
  113. if workerErr != nil {
  114. app.handleErrorInternal(workerErr, w)
  115. return
  116. }
  117. res := make([]Repo, 0)
  118. for _, repo := range allRepos {
  119. res = append(res, Repo{
  120. FullName: repo.GetFullName(),
  121. Kind: "github",
  122. })
  123. }
  124. json.NewEncoder(w).Encode(res)
  125. }
  126. // HandleDeleteProjectGitRepo handles the deletion of a Github Repo via the git repo ID
  127. func (app *App) HandleDeleteProjectGitRepo(w http.ResponseWriter, r *http.Request) {
  128. id, err := strconv.ParseUint(chi.URLParam(r, "git_repo_id"), 0, 64)
  129. if err != nil || id == 0 {
  130. app.handleErrorFormDecoding(err, ErrProjectDecode, w)
  131. return
  132. }
  133. repo, err := app.Repo.GitRepo.ReadGitRepo(uint(id))
  134. if err != nil {
  135. app.handleErrorRead(err, ErrProjectDataRead, w)
  136. return
  137. }
  138. err = app.Repo.GitRepo.DeleteGitRepo(repo)
  139. if err != nil {
  140. app.handleErrorRead(err, ErrProjectDataRead, w)
  141. return
  142. }
  143. w.WriteHeader(http.StatusOK)
  144. }
  145. // HandleGetBranches retrieves a list of branch names for a specified repo
  146. func (app *App) HandleGetBranches(w http.ResponseWriter, r *http.Request) {
  147. tok, err := app.githubTokenFromRequest(r)
  148. if err != nil {
  149. app.handleErrorInternal(err, w)
  150. return
  151. }
  152. owner := chi.URLParam(r, "owner")
  153. name := chi.URLParam(r, "name")
  154. client := github.NewClient(app.GithubProjectConf.Client(oauth2.NoContext, tok))
  155. // List all branches for a specified repo
  156. branches, _, err := client.Repositories.ListBranches(context.Background(), owner, name, &github.ListOptions{
  157. PerPage: 100,
  158. })
  159. if err != nil {
  160. return
  161. }
  162. res := []string{}
  163. for _, b := range branches {
  164. res = append(res, b.GetName())
  165. }
  166. json.NewEncoder(w).Encode(res)
  167. }
  168. // HandleDetectBuildpack attempts to figure which buildpack will be auto used based on directory contents
  169. func (app *App) HandleDetectBuildpack(w http.ResponseWriter, r *http.Request) {
  170. tok, err := app.githubTokenFromRequest(r)
  171. if err != nil {
  172. app.handleErrorInternal(err, w)
  173. return
  174. }
  175. queryParams, err := url.ParseQuery(r.URL.RawQuery)
  176. if err != nil {
  177. app.handleErrorFormDecoding(err, ErrReleaseDecode, w)
  178. return
  179. }
  180. client := github.NewClient(app.GithubProjectConf.Client(oauth2.NoContext, tok))
  181. owner := chi.URLParam(r, "owner")
  182. name := chi.URLParam(r, "name")
  183. branch := chi.URLParam(r, "branch")
  184. repoContentOptions := github.RepositoryContentGetOptions{}
  185. repoContentOptions.Ref = branch
  186. _, directoryContents, _, err := client.Repositories.GetContents(context.Background(), owner, name, queryParams["dir"][0], &repoContentOptions)
  187. if err != nil {
  188. app.handleErrorInternal(err, w)
  189. return
  190. }
  191. var BREQS = map[string]string{
  192. "requirements.txt": "Python",
  193. "Gemfile": "Ruby",
  194. "package.json": "Node.js",
  195. "pom.xml": "Java",
  196. "composer.json": "PHP",
  197. }
  198. res := AutoBuildpack{
  199. Valid: true,
  200. }
  201. matches := 0
  202. for i := range directoryContents {
  203. name := *directoryContents[i].Path
  204. bname, ok := BREQS[name]
  205. if ok {
  206. matches++
  207. res.Name = bname
  208. }
  209. }
  210. if matches != 1 {
  211. res.Valid = false
  212. res.Name = ""
  213. }
  214. json.NewEncoder(w).Encode(res)
  215. }
  216. // HandleGetBranchContents retrieves the contents of a specific branch and subdirectory
  217. func (app *App) HandleGetBranchContents(w http.ResponseWriter, r *http.Request) {
  218. tok, err := app.githubTokenFromRequest(r)
  219. if err != nil {
  220. app.handleErrorInternal(err, w)
  221. return
  222. }
  223. client := github.NewClient(app.GithubProjectConf.Client(oauth2.NoContext, tok))
  224. queryParams, err := url.ParseQuery(r.URL.RawQuery)
  225. if err != nil {
  226. app.handleErrorFormDecoding(err, ErrReleaseDecode, w)
  227. return
  228. }
  229. owner := chi.URLParam(r, "owner")
  230. name := chi.URLParam(r, "name")
  231. branch := chi.URLParam(r, "branch")
  232. repoContentOptions := github.RepositoryContentGetOptions{}
  233. repoContentOptions.Ref = branch
  234. _, directoryContents, _, err := client.Repositories.GetContents(context.Background(), owner, name, queryParams["dir"][0], &repoContentOptions)
  235. if err != nil {
  236. app.handleErrorInternal(err, w)
  237. return
  238. }
  239. res := []DirectoryItem{}
  240. for i := range directoryContents {
  241. d := DirectoryItem{}
  242. d.Path = *directoryContents[i].Path
  243. d.Type = *directoryContents[i].Type
  244. res = append(res, d)
  245. }
  246. // Ret2: recursively traverse all dirs to create config bundle (case on type == dir)
  247. // https://api.github.com/repos/porter-dev/porter/contents?ref=frontend-graph
  248. json.NewEncoder(w).Encode(res)
  249. }
  250. type GetProcfileContentsResp map[string]string
  251. var procfileRegex = regexp.MustCompile("^([A-Za-z0-9_]+):\\s*(.+)$")
  252. // HandleGetProcfileContents retrieves the contents of a procfile in a github repo
  253. func (app *App) HandleGetProcfileContents(w http.ResponseWriter, r *http.Request) {
  254. tok, err := app.githubTokenFromRequest(r)
  255. if err != nil {
  256. app.handleErrorInternal(err, w)
  257. return
  258. }
  259. client := github.NewClient(app.GithubProjectConf.Client(oauth2.NoContext, tok))
  260. owner := chi.URLParam(r, "owner")
  261. name := chi.URLParam(r, "name")
  262. branch := chi.URLParam(r, "branch")
  263. queryParams, err := url.ParseQuery(r.URL.RawQuery)
  264. if err != nil {
  265. app.handleErrorFormDecoding(err, ErrReleaseDecode, w)
  266. return
  267. }
  268. resp, _, _, err := client.Repositories.GetContents(
  269. context.TODO(),
  270. owner,
  271. name,
  272. queryParams["path"][0],
  273. &github.RepositoryContentGetOptions{
  274. Ref: branch,
  275. },
  276. )
  277. if err != nil {
  278. app.handleErrorInternal(err, w)
  279. return
  280. }
  281. fileData, err := resp.GetContent()
  282. if err != nil {
  283. app.handleErrorInternal(err, w)
  284. return
  285. }
  286. parsedContents := make(GetProcfileContentsResp)
  287. // parse the procfile information
  288. for _, line := range strings.Split(fileData, "\n") {
  289. if matches := procfileRegex.FindStringSubmatch(line); matches != nil {
  290. parsedContents[matches[1]] = matches[2]
  291. }
  292. }
  293. json.NewEncoder(w).Encode(parsedContents)
  294. }
  295. // finds the github token given the git repo id and the project id
  296. func (app *App) githubTokenFromRequest(
  297. r *http.Request,
  298. ) (*oauth2.Token, error) {
  299. grID, err := strconv.ParseUint(chi.URLParam(r, "git_repo_id"), 0, 64)
  300. if err != nil || grID == 0 {
  301. return nil, fmt.Errorf("could not read git repo id")
  302. }
  303. // query for the git repo
  304. gr, err := app.Repo.GitRepo.ReadGitRepo(uint(grID))
  305. if err != nil {
  306. return nil, err
  307. }
  308. // get the oauth integration
  309. oauthInt, err := app.Repo.OAuthIntegration.ReadOAuthIntegration(gr.OAuthIntegrationID)
  310. if err != nil {
  311. return nil, err
  312. }
  313. return &oauth2.Token{
  314. AccessToken: string(oauthInt.AccessToken),
  315. RefreshToken: string(oauthInt.RefreshToken),
  316. TokenType: "Bearer",
  317. }, nil
  318. }