git_repo_handler.go 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516
  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 := chi.URLParam(r, "branch")
  276. repoContentOptions := github.RepositoryContentGetOptions{}
  277. repoContentOptions.Ref = branch
  278. _, directoryContents, _, err := client.Repositories.GetContents(context.Background(), owner, name, queryParams["dir"][0], &repoContentOptions)
  279. if err != nil {
  280. app.handleErrorInternal(err, w)
  281. return
  282. }
  283. res := []DirectoryItem{}
  284. for i := range directoryContents {
  285. d := DirectoryItem{}
  286. d.Path = *directoryContents[i].Path
  287. d.Type = *directoryContents[i].Type
  288. res = append(res, d)
  289. }
  290. // Ret2: recursively traverse all dirs to create config bundle (case on type == dir)
  291. // https://api.github.com/repos/porter-dev/porter/contents?ref=frontend-graph
  292. json.NewEncoder(w).Encode(res)
  293. }
  294. type GetProcfileContentsResp map[string]string
  295. var procfileRegex = regexp.MustCompile("^([A-Za-z0-9_]+):\\s*(.+)$")
  296. // HandleGetProcfileContents retrieves the contents of a procfile in a github repo
  297. func (app *App) HandleGetProcfileContents(w http.ResponseWriter, r *http.Request) {
  298. client, err := app.githubAppClientFromRequest(r)
  299. if err != nil {
  300. app.handleErrorInternal(err, w)
  301. return
  302. }
  303. owner := chi.URLParam(r, "owner")
  304. name := chi.URLParam(r, "name")
  305. branch := chi.URLParam(r, "branch")
  306. queryParams, err := url.ParseQuery(r.URL.RawQuery)
  307. if err != nil {
  308. app.handleErrorFormDecoding(err, ErrReleaseDecode, w)
  309. return
  310. }
  311. resp, _, _, err := client.Repositories.GetContents(
  312. context.TODO(),
  313. owner,
  314. name,
  315. queryParams["path"][0],
  316. &github.RepositoryContentGetOptions{
  317. Ref: branch,
  318. },
  319. )
  320. if err != nil {
  321. http.NotFound(w, r)
  322. return
  323. }
  324. fileData, err := resp.GetContent()
  325. if err != nil {
  326. app.handleErrorInternal(err, w)
  327. return
  328. }
  329. parsedContents := make(GetProcfileContentsResp)
  330. // parse the procfile information
  331. for _, line := range strings.Split(fileData, "\n") {
  332. if matches := procfileRegex.FindStringSubmatch(line); matches != nil {
  333. parsedContents[matches[1]] = matches[2]
  334. }
  335. }
  336. json.NewEncoder(w).Encode(parsedContents)
  337. }
  338. type HandleGetRepoZIPDownloadURLResp struct {
  339. URLString string `json:"url"`
  340. LatestCommitSHA string `json:"latest_commit_sha"`
  341. }
  342. // HandleGetRepoZIPDownloadURL gets the URL for downloading a zip file from a Github
  343. // repository
  344. func (app *App) HandleGetRepoZIPDownloadURL(w http.ResponseWriter, r *http.Request) {
  345. client, err := app.githubAppClientFromRequest(r)
  346. if err != nil {
  347. app.handleErrorInternal(err, w)
  348. return
  349. }
  350. owner := chi.URLParam(r, "owner")
  351. name := chi.URLParam(r, "name")
  352. branch := chi.URLParam(r, "branch")
  353. branchResp, _, err := client.Repositories.GetBranch(
  354. context.TODO(),
  355. owner,
  356. name,
  357. branch,
  358. )
  359. if err != nil {
  360. app.handleErrorInternal(err, w)
  361. return
  362. }
  363. ghURL, _, err := client.Repositories.GetArchiveLink(
  364. context.TODO(),
  365. owner,
  366. name,
  367. github.Zipball,
  368. &github.RepositoryContentGetOptions{
  369. Ref: *branchResp.Commit.SHA,
  370. },
  371. )
  372. if err != nil {
  373. app.handleErrorInternal(err, w)
  374. return
  375. }
  376. apiResp := HandleGetRepoZIPDownloadURLResp{
  377. URLString: ghURL.String(),
  378. LatestCommitSHA: *branchResp.Commit.SHA,
  379. }
  380. json.NewEncoder(w).Encode(apiResp)
  381. }
  382. // githubAppClientFromRequest gets the github app installation id from the request and authenticates
  383. // using it and a private key file
  384. func (app *App) githubAppClientFromRequest(r *http.Request) (*github.Client, error) {
  385. installationID, err := strconv.ParseUint(chi.URLParam(r, "installation_id"), 0, 64)
  386. if err != nil || installationID == 0 {
  387. return nil, fmt.Errorf("could not read installation id")
  388. }
  389. itr, err := ghinstallation.NewKeyFromFile(
  390. http.DefaultTransport,
  391. app.GithubAppConf.AppID,
  392. int64(installationID),
  393. app.GithubAppConf.SecretPath)
  394. if err != nil {
  395. return nil, err
  396. }
  397. return github.NewClient(&http.Client{Transport: itr}), nil
  398. }