git_repo_handler.go 12 KB

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