git_repo_handler.go 11 KB

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