git_repo_handler.go 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519
  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. Sort: "updated",
  68. }
  69. allRepos, resp, err := client.Repositories.List(context.Background(), "", opt)
  70. if err != nil {
  71. app.handleErrorInternal(err, w)
  72. return
  73. }
  74. // make workers to get pages concurrently
  75. const WCOUNT = 5
  76. numPages := resp.LastPage + 1
  77. var workerErr error
  78. var mu sync.Mutex
  79. var wg sync.WaitGroup
  80. worker := func(cp int) {
  81. defer wg.Done()
  82. for cp < numPages {
  83. cur_opt := &github.RepositoryListOptions{
  84. ListOptions: github.ListOptions{
  85. Page: cp,
  86. PerPage: 100,
  87. },
  88. Sort: "updated",
  89. }
  90. repos, _, err := client.Repositories.List(context.Background(), "", cur_opt)
  91. if err != nil {
  92. mu.Lock()
  93. workerErr = err
  94. mu.Unlock()
  95. return
  96. }
  97. mu.Lock()
  98. allRepos = append(allRepos, repos...)
  99. mu.Unlock()
  100. cp += WCOUNT
  101. }
  102. }
  103. var numJobs int
  104. if numPages > WCOUNT {
  105. numJobs = WCOUNT
  106. } else {
  107. numJobs = numPages
  108. }
  109. wg.Add(numJobs)
  110. // page 1 is already loaded so we start with 2
  111. for i := 1; i <= numJobs; i++ {
  112. go worker(i + 1)
  113. }
  114. wg.Wait()
  115. if workerErr != nil {
  116. app.handleErrorInternal(workerErr, w)
  117. return
  118. }
  119. res := make([]Repo, 0)
  120. for _, repo := range allRepos {
  121. res = append(res, Repo{
  122. FullName: repo.GetFullName(),
  123. Kind: "github",
  124. })
  125. }
  126. json.NewEncoder(w).Encode(res)
  127. }
  128. // HandleDeleteProjectGitRepo handles the deletion of a Github Repo via the git repo ID
  129. func (app *App) HandleDeleteProjectGitRepo(w http.ResponseWriter, r *http.Request) {
  130. id, err := strconv.ParseUint(chi.URLParam(r, "git_repo_id"), 0, 64)
  131. if err != nil || id == 0 {
  132. app.handleErrorFormDecoding(err, ErrProjectDecode, w)
  133. return
  134. }
  135. repo, err := app.Repo.GitRepo.ReadGitRepo(uint(id))
  136. if err != nil {
  137. app.handleErrorRead(err, ErrProjectDataRead, w)
  138. return
  139. }
  140. err = app.Repo.GitRepo.DeleteGitRepo(repo)
  141. if err != nil {
  142. app.handleErrorRead(err, ErrProjectDataRead, w)
  143. return
  144. }
  145. w.WriteHeader(http.StatusOK)
  146. }
  147. // HandleGetBranches retrieves a list of branch names for a specified repo
  148. func (app *App) HandleGetBranches(w http.ResponseWriter, r *http.Request) {
  149. tok, err := app.githubTokenFromRequest(r)
  150. if err != nil {
  151. app.handleErrorInternal(err, w)
  152. return
  153. }
  154. owner := chi.URLParam(r, "owner")
  155. name := chi.URLParam(r, "name")
  156. client := github.NewClient(app.GithubProjectConf.Client(oauth2.NoContext, tok))
  157. // List all branches for a specified repo
  158. allBranches, resp, err := client.Repositories.ListBranches(context.Background(), owner, name, &github.ListOptions{
  159. PerPage: 100,
  160. })
  161. if err != nil {
  162. app.handleErrorInternal(err, w)
  163. return
  164. }
  165. // make workers to get branches concurrently
  166. const WCOUNT = 5
  167. numPages := resp.LastPage + 1
  168. var workerErr error
  169. var mu sync.Mutex
  170. var wg sync.WaitGroup
  171. worker := func(cp int) {
  172. defer wg.Done()
  173. for cp < numPages {
  174. opts := &github.ListOptions{
  175. Page: cp,
  176. PerPage: 100,
  177. }
  178. branches, _, err := client.Repositories.ListBranches(context.Background(), owner, name, opts)
  179. if err != nil {
  180. mu.Lock()
  181. workerErr = err
  182. mu.Unlock()
  183. return
  184. }
  185. mu.Lock()
  186. allBranches = append(allBranches, branches...)
  187. mu.Unlock()
  188. cp += WCOUNT
  189. }
  190. }
  191. var numJobs int
  192. if numPages > WCOUNT {
  193. numJobs = WCOUNT
  194. } else {
  195. numJobs = numPages
  196. }
  197. wg.Add(numJobs)
  198. // page 1 is already loaded so we start with 2
  199. for i := 1; i <= numJobs; i++ {
  200. go worker(i + 1)
  201. }
  202. wg.Wait()
  203. if workerErr != nil {
  204. app.handleErrorInternal(workerErr, w)
  205. return
  206. }
  207. res := make([]string, 0)
  208. for _, b := range allBranches {
  209. res = append(res, b.GetName())
  210. }
  211. json.NewEncoder(w).Encode(res)
  212. }
  213. // HandleDetectBuildpack attempts to figure which buildpack will be auto used based on directory contents
  214. func (app *App) HandleDetectBuildpack(w http.ResponseWriter, r *http.Request) {
  215. tok, err := app.githubTokenFromRequest(r)
  216. if err != nil {
  217. app.handleErrorInternal(err, w)
  218. return
  219. }
  220. queryParams, err := url.ParseQuery(r.URL.RawQuery)
  221. if err != nil {
  222. app.handleErrorFormDecoding(err, ErrReleaseDecode, w)
  223. return
  224. }
  225. client := github.NewClient(app.GithubProjectConf.Client(oauth2.NoContext, tok))
  226. owner := chi.URLParam(r, "owner")
  227. name := chi.URLParam(r, "name")
  228. branch := chi.URLParam(r, "branch")
  229. repoContentOptions := github.RepositoryContentGetOptions{}
  230. repoContentOptions.Ref = branch
  231. _, directoryContents, _, err := client.Repositories.GetContents(context.Background(), owner, name, queryParams["dir"][0], &repoContentOptions)
  232. if err != nil {
  233. app.handleErrorInternal(err, w)
  234. return
  235. }
  236. var BREQS = map[string]string{
  237. "requirements.txt": "Python",
  238. "Gemfile": "Ruby",
  239. "package.json": "Node.js",
  240. "pom.xml": "Java",
  241. "composer.json": "PHP",
  242. }
  243. res := AutoBuildpack{
  244. Valid: true,
  245. }
  246. matches := 0
  247. for i := range directoryContents {
  248. name := *directoryContents[i].Name
  249. bname, ok := BREQS[name]
  250. if ok {
  251. matches++
  252. res.Name = bname
  253. }
  254. }
  255. if matches != 1 {
  256. res.Valid = false
  257. res.Name = ""
  258. }
  259. json.NewEncoder(w).Encode(res)
  260. }
  261. // HandleGetBranchContents retrieves the contents of a specific branch and subdirectory
  262. func (app *App) HandleGetBranchContents(w http.ResponseWriter, r *http.Request) {
  263. tok, err := app.githubTokenFromRequest(r)
  264. if err != nil {
  265. app.handleErrorInternal(err, w)
  266. return
  267. }
  268. client := github.NewClient(app.GithubProjectConf.Client(oauth2.NoContext, tok))
  269. queryParams, err := url.ParseQuery(r.URL.RawQuery)
  270. if err != nil {
  271. app.handleErrorFormDecoding(err, ErrReleaseDecode, w)
  272. return
  273. }
  274. owner := chi.URLParam(r, "owner")
  275. name := chi.URLParam(r, "name")
  276. branch := chi.URLParam(r, "branch")
  277. repoContentOptions := github.RepositoryContentGetOptions{}
  278. repoContentOptions.Ref = branch
  279. _, directoryContents, _, err := client.Repositories.GetContents(context.Background(), owner, name, queryParams["dir"][0], &repoContentOptions)
  280. if err != nil {
  281. app.handleErrorInternal(err, w)
  282. return
  283. }
  284. res := []DirectoryItem{}
  285. for i := range directoryContents {
  286. d := DirectoryItem{}
  287. d.Path = *directoryContents[i].Path
  288. d.Type = *directoryContents[i].Type
  289. res = append(res, d)
  290. }
  291. // Ret2: recursively traverse all dirs to create config bundle (case on type == dir)
  292. // https://api.github.com/repos/porter-dev/porter/contents?ref=frontend-graph
  293. json.NewEncoder(w).Encode(res)
  294. }
  295. type GetProcfileContentsResp map[string]string
  296. var procfileRegex = regexp.MustCompile("^([A-Za-z0-9_]+):\\s*(.+)$")
  297. // HandleGetProcfileContents retrieves the contents of a procfile in a github repo
  298. func (app *App) HandleGetProcfileContents(w http.ResponseWriter, r *http.Request) {
  299. tok, err := app.githubTokenFromRequest(r)
  300. if err != nil {
  301. app.handleErrorInternal(err, w)
  302. return
  303. }
  304. client := github.NewClient(app.GithubProjectConf.Client(oauth2.NoContext, tok))
  305. owner := chi.URLParam(r, "owner")
  306. name := chi.URLParam(r, "name")
  307. branch := chi.URLParam(r, "branch")
  308. queryParams, err := url.ParseQuery(r.URL.RawQuery)
  309. if err != nil {
  310. app.handleErrorFormDecoding(err, ErrReleaseDecode, w)
  311. return
  312. }
  313. resp, _, _, err := client.Repositories.GetContents(
  314. context.TODO(),
  315. owner,
  316. name,
  317. queryParams["path"][0],
  318. &github.RepositoryContentGetOptions{
  319. Ref: branch,
  320. },
  321. )
  322. if err != nil {
  323. http.NotFound(w, r)
  324. return
  325. }
  326. fileData, err := resp.GetContent()
  327. if err != nil {
  328. app.handleErrorInternal(err, w)
  329. return
  330. }
  331. parsedContents := make(GetProcfileContentsResp)
  332. // parse the procfile information
  333. for _, line := range strings.Split(fileData, "\n") {
  334. if matches := procfileRegex.FindStringSubmatch(line); matches != nil {
  335. parsedContents[matches[1]] = matches[2]
  336. }
  337. }
  338. json.NewEncoder(w).Encode(parsedContents)
  339. }
  340. type HandleGetRepoZIPDownloadURLResp struct {
  341. URLString string `json:"url"`
  342. LatestCommitSHA string `json:"latest_commit_sha"`
  343. }
  344. // HandleGetRepoZIPDownloadURL gets the URL for downloading a zip file from a Github
  345. // repository
  346. func (app *App) HandleGetRepoZIPDownloadURL(w http.ResponseWriter, r *http.Request) {
  347. tok, err := app.githubTokenFromRequest(r)
  348. if err != nil {
  349. app.handleErrorInternal(err, w)
  350. return
  351. }
  352. client := github.NewClient(app.GithubProjectConf.Client(oauth2.NoContext, tok))
  353. owner := chi.URLParam(r, "owner")
  354. name := chi.URLParam(r, "name")
  355. branch := chi.URLParam(r, "branch")
  356. branchResp, _, err := client.Repositories.GetBranch(
  357. context.TODO(),
  358. owner,
  359. name,
  360. branch,
  361. )
  362. if err != nil {
  363. app.handleErrorInternal(err, w)
  364. return
  365. }
  366. ghURL, _, err := client.Repositories.GetArchiveLink(
  367. context.TODO(),
  368. owner,
  369. name,
  370. github.Zipball,
  371. &github.RepositoryContentGetOptions{
  372. Ref: *branchResp.Commit.SHA,
  373. },
  374. )
  375. if err != nil {
  376. app.handleErrorInternal(err, w)
  377. return
  378. }
  379. apiResp := HandleGetRepoZIPDownloadURLResp{
  380. URLString: ghURL.String(),
  381. LatestCommitSHA: *branchResp.Commit.SHA,
  382. }
  383. json.NewEncoder(w).Encode(apiResp)
  384. }
  385. // finds the github token given the git repo id and the project id
  386. func (app *App) githubTokenFromRequest(
  387. r *http.Request,
  388. ) (*oauth2.Token, error) {
  389. grID, err := strconv.ParseUint(chi.URLParam(r, "git_repo_id"), 0, 64)
  390. if err != nil || grID == 0 {
  391. return nil, fmt.Errorf("could not read git repo id")
  392. }
  393. // query for the git repo
  394. gr, err := app.Repo.GitRepo.ReadGitRepo(uint(grID))
  395. if err != nil {
  396. return nil, err
  397. }
  398. // get the oauth integration
  399. oauthInt, err := app.Repo.OAuthIntegration.ReadOAuthIntegration(gr.OAuthIntegrationID)
  400. if err != nil {
  401. return nil, err
  402. }
  403. return &oauth2.Token{
  404. AccessToken: string(oauthInt.AccessToken),
  405. RefreshToken: string(oauthInt.RefreshToken),
  406. TokenType: "Bearer",
  407. }, nil
  408. }