git_repo_handler.go 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531
  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. "sync"
  12. "github.com/porter-dev/porter/internal/models"
  13. "golang.org/x/oauth2"
  14. "github.com/bradleyfalzon/ghinstallation"
  15. "github.com/go-chi/chi"
  16. "github.com/google/go-github/github"
  17. )
  18. // HandleListProjectGitRepos returns a list of git repos for a project
  19. func (app *App) HandleListProjectGitRepos(w http.ResponseWriter, r *http.Request) {
  20. tok, err := app.getGithubAppOauthTokenFromRequest(r)
  21. if err != nil {
  22. app.Logger.Warn().Err(err).
  23. Str("info", "github app oauth token error").
  24. Msg("")
  25. json.NewEncoder(w).Encode(make([]*models.GitRepoExternal, 0))
  26. return
  27. }
  28. client := github.NewClient(app.GithubProjectConf.Client(oauth2.NoContext, tok))
  29. accountIds := make([]int64, 0)
  30. AuthUser, _, err := client.Users.Get(context.Background(), "")
  31. if err != nil {
  32. app.handleErrorInternal(err, w)
  33. return
  34. }
  35. accountIds = append(accountIds, *AuthUser.ID)
  36. opts := &github.ListOptions{
  37. PerPage: 100,
  38. Page: 1,
  39. }
  40. for {
  41. orgs, pages, err := client.Organizations.List(context.Background(), "", opts)
  42. if err != nil {
  43. res := HandleListGithubAppAccessResp{
  44. HasAccess: false,
  45. }
  46. json.NewEncoder(w).Encode(res)
  47. return
  48. }
  49. for _, org := range orgs {
  50. accountIds = append(accountIds, *org.ID)
  51. }
  52. if pages.NextPage == 0 {
  53. break
  54. }
  55. }
  56. installationData, err := app.Repo.GithubAppInstallation.ReadGithubAppInstallationByAccountIDs(accountIds)
  57. if err != nil {
  58. app.handleErrorInternal(err, w)
  59. return
  60. }
  61. installationIds := make([]int64, 0)
  62. for _, v := range installationData {
  63. installationIds = append(installationIds, v.InstallationID)
  64. }
  65. json.NewEncoder(w).Encode(installationIds)
  66. }
  67. // Repo represents a GitHub or Gitab repository
  68. type Repo struct {
  69. FullName string
  70. Kind string
  71. }
  72. // DirectoryItem represents a file or subfolder in a repository
  73. type DirectoryItem struct {
  74. Path string
  75. Type string
  76. }
  77. // AutoBuildpack represents an automatically detected buildpack
  78. type AutoBuildpack struct {
  79. Valid bool `json:"valid"`
  80. Name string `json:"name"`
  81. }
  82. // HandleListRepos retrieves a list of repo names
  83. func (app *App) HandleListRepos(w http.ResponseWriter, r *http.Request) {
  84. client, err := app.githubAppClientFromRequest(r)
  85. if err != nil {
  86. app.handleErrorInternal(err, w)
  87. return
  88. }
  89. // figure out number of repositories
  90. opt := &github.ListOptions{
  91. PerPage: 100,
  92. }
  93. allRepos, resp, err := client.Apps.ListRepos(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.ListOptions{
  108. Page: cp,
  109. PerPage: 100,
  110. }
  111. repos, _, err := client.Apps.ListRepos(context.Background(), cur_opt)
  112. if err != nil {
  113. mu.Lock()
  114. workerErr = err
  115. mu.Unlock()
  116. return
  117. }
  118. mu.Lock()
  119. allRepos = append(allRepos, repos...)
  120. mu.Unlock()
  121. cp += WCOUNT
  122. }
  123. }
  124. var numJobs int
  125. if numPages > WCOUNT {
  126. numJobs = WCOUNT
  127. } else {
  128. numJobs = numPages
  129. }
  130. wg.Add(numJobs)
  131. // page 1 is already loaded so we start with 2
  132. for i := 1; i <= numJobs; i++ {
  133. go worker(i + 1)
  134. }
  135. wg.Wait()
  136. if workerErr != nil {
  137. app.handleErrorInternal(workerErr, w)
  138. return
  139. }
  140. res := make([]Repo, 0)
  141. for _, repo := range allRepos {
  142. res = append(res, Repo{
  143. FullName: repo.GetFullName(),
  144. Kind: "github",
  145. })
  146. }
  147. json.NewEncoder(w).Encode(res)
  148. }
  149. // HandleGetBranches retrieves a list of branch names for a specified repo
  150. func (app *App) HandleGetBranches(w http.ResponseWriter, r *http.Request) {
  151. client, err := app.githubAppClientFromRequest(r)
  152. if err != nil {
  153. app.handleErrorInternal(err, w)
  154. return
  155. }
  156. owner := chi.URLParam(r, "owner")
  157. name := chi.URLParam(r, "name")
  158. // List all branches for a specified repo
  159. allBranches, resp, err := client.Repositories.ListBranches(context.Background(), owner, name, &github.ListOptions{
  160. PerPage: 100,
  161. })
  162. if err != nil {
  163. app.handleErrorInternal(err, w)
  164. return
  165. }
  166. // make workers to get branches concurrently
  167. const WCOUNT = 5
  168. numPages := resp.LastPage + 1
  169. var workerErr error
  170. var mu sync.Mutex
  171. var wg sync.WaitGroup
  172. worker := func(cp int) {
  173. defer wg.Done()
  174. for cp < numPages {
  175. opts := &github.ListOptions{
  176. Page: cp,
  177. PerPage: 100,
  178. }
  179. branches, _, err := client.Repositories.ListBranches(context.Background(), owner, name, opts)
  180. if err != nil {
  181. mu.Lock()
  182. workerErr = err
  183. mu.Unlock()
  184. return
  185. }
  186. mu.Lock()
  187. allBranches = append(allBranches, branches...)
  188. mu.Unlock()
  189. cp += WCOUNT
  190. }
  191. }
  192. var numJobs int
  193. if numPages > WCOUNT {
  194. numJobs = WCOUNT
  195. } else {
  196. numJobs = numPages
  197. }
  198. wg.Add(numJobs)
  199. // page 1 is already loaded so we start with 2
  200. for i := 1; i <= numJobs; i++ {
  201. go worker(i + 1)
  202. }
  203. wg.Wait()
  204. if workerErr != nil {
  205. app.handleErrorInternal(workerErr, w)
  206. return
  207. }
  208. res := make([]string, 0)
  209. for _, b := range allBranches {
  210. res = append(res, b.GetName())
  211. }
  212. json.NewEncoder(w).Encode(res)
  213. }
  214. // HandleDetectBuildpack attempts to figure which buildpack will be auto used based on directory contents
  215. func (app *App) HandleDetectBuildpack(w http.ResponseWriter, r *http.Request) {
  216. client, err := app.githubAppClientFromRequest(r)
  217. if err != nil {
  218. app.handleErrorInternal(err, w)
  219. return
  220. }
  221. queryParams, err := url.ParseQuery(r.URL.RawQuery)
  222. if err != nil {
  223. app.handleErrorFormDecoding(err, ErrReleaseDecode, w)
  224. return
  225. }
  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. client, err := app.githubAppClientFromRequest(r)
  264. if err != nil {
  265. app.handleErrorInternal(err, w)
  266. return
  267. }
  268. queryParams, err := url.ParseQuery(r.URL.RawQuery)
  269. if err != nil {
  270. app.handleErrorFormDecoding(err, ErrReleaseDecode, w)
  271. return
  272. }
  273. owner := chi.URLParam(r, "owner")
  274. name := chi.URLParam(r, "name")
  275. branch, err := url.QueryUnescape(chi.URLParam(r, "branch"))
  276. if err != nil {
  277. app.handleErrorInternal(err, w)
  278. return
  279. }
  280. repoContentOptions := github.RepositoryContentGetOptions{}
  281. repoContentOptions.Ref = branch
  282. _, directoryContents, _, err := client.Repositories.GetContents(context.Background(), owner, name, queryParams["dir"][0], &repoContentOptions)
  283. if err != nil {
  284. app.handleErrorInternal(err, w)
  285. return
  286. }
  287. res := []DirectoryItem{}
  288. for i := range directoryContents {
  289. d := DirectoryItem{}
  290. d.Path = *directoryContents[i].Path
  291. d.Type = *directoryContents[i].Type
  292. res = append(res, d)
  293. }
  294. // Ret2: recursively traverse all dirs to create config bundle (case on type == dir)
  295. // https://api.github.com/repos/porter-dev/porter/contents?ref=frontend-graph
  296. json.NewEncoder(w).Encode(res)
  297. }
  298. type GetProcfileContentsResp map[string]string
  299. var procfileRegex = regexp.MustCompile("^([A-Za-z0-9_]+):\\s*(.+)$")
  300. // HandleGetProcfileContents retrieves the contents of a procfile in a github repo
  301. func (app *App) HandleGetProcfileContents(w http.ResponseWriter, r *http.Request) {
  302. client, err := app.githubAppClientFromRequest(r)
  303. if err != nil {
  304. app.handleErrorInternal(err, w)
  305. return
  306. }
  307. owner := chi.URLParam(r, "owner")
  308. name := chi.URLParam(r, "name")
  309. branch, err := url.QueryUnescape(chi.URLParam(r, "branch"))
  310. if err != nil {
  311. app.handleErrorInternal(err, w)
  312. return
  313. }
  314. queryParams, err := url.ParseQuery(r.URL.RawQuery)
  315. if err != nil {
  316. app.handleErrorFormDecoding(err, ErrReleaseDecode, w)
  317. return
  318. }
  319. resp, _, _, err := client.Repositories.GetContents(
  320. context.TODO(),
  321. owner,
  322. name,
  323. queryParams["path"][0],
  324. &github.RepositoryContentGetOptions{
  325. Ref: branch,
  326. },
  327. )
  328. if err != nil {
  329. http.NotFound(w, r)
  330. return
  331. }
  332. fileData, err := resp.GetContent()
  333. if err != nil {
  334. app.handleErrorInternal(err, w)
  335. return
  336. }
  337. parsedContents := make(GetProcfileContentsResp)
  338. // parse the procfile information
  339. for _, line := range strings.Split(fileData, "\n") {
  340. if matches := procfileRegex.FindStringSubmatch(line); matches != nil {
  341. parsedContents[matches[1]] = matches[2]
  342. }
  343. }
  344. json.NewEncoder(w).Encode(parsedContents)
  345. }
  346. type HandleGetRepoZIPDownloadURLResp struct {
  347. URLString string `json:"url"`
  348. LatestCommitSHA string `json:"latest_commit_sha"`
  349. }
  350. // HandleGetRepoZIPDownloadURL gets the URL for downloading a zip file from a Github
  351. // repository
  352. func (app *App) HandleGetRepoZIPDownloadURL(w http.ResponseWriter, r *http.Request) {
  353. client, err := app.githubAppClientFromRequest(r)
  354. if err != nil {
  355. app.handleErrorInternal(err, w)
  356. return
  357. }
  358. owner := chi.URLParam(r, "owner")
  359. name := chi.URLParam(r, "name")
  360. branch, err := url.QueryUnescape(chi.URLParam(r, "branch"))
  361. if err != nil {
  362. app.handleErrorInternal(err, w)
  363. return
  364. }
  365. branchResp, _, err := client.Repositories.GetBranch(
  366. context.TODO(),
  367. owner,
  368. name,
  369. branch,
  370. )
  371. if err != nil {
  372. app.handleErrorInternal(err, w)
  373. return
  374. }
  375. ghURL, _, err := client.Repositories.GetArchiveLink(
  376. context.TODO(),
  377. owner,
  378. name,
  379. github.Zipball,
  380. &github.RepositoryContentGetOptions{
  381. Ref: *branchResp.Commit.SHA,
  382. },
  383. )
  384. if err != nil {
  385. app.handleErrorInternal(err, w)
  386. return
  387. }
  388. apiResp := HandleGetRepoZIPDownloadURLResp{
  389. URLString: ghURL.String(),
  390. LatestCommitSHA: *branchResp.Commit.SHA,
  391. }
  392. json.NewEncoder(w).Encode(apiResp)
  393. }
  394. // githubAppClientFromRequest gets the github app installation id from the request and authenticates
  395. // using it and a private key file
  396. func (app *App) githubAppClientFromRequest(r *http.Request) (*github.Client, error) {
  397. installationID, err := strconv.ParseUint(chi.URLParam(r, "installation_id"), 0, 64)
  398. if err != nil || installationID == 0 {
  399. return nil, fmt.Errorf("could not read installation id")
  400. }
  401. itr, err := ghinstallation.NewKeyFromFile(
  402. http.DefaultTransport,
  403. app.GithubAppConf.AppID,
  404. int64(installationID),
  405. app.GithubAppConf.SecretPath)
  406. if err != nil {
  407. return nil, err
  408. }
  409. return github.NewClient(&http.Client{Transport: itr}), nil
  410. }