git_repo_handler.go 8.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353
  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. "golang.org/x/oauth2"
  12. "github.com/go-chi/chi"
  13. "github.com/google/go-github/github"
  14. "github.com/porter-dev/porter/internal/models"
  15. )
  16. // HandleListProjectGitRepos returns a list of git repos for a project
  17. func (app *App) HandleListProjectGitRepos(w http.ResponseWriter, r *http.Request) {
  18. projID, err := strconv.ParseUint(chi.URLParam(r, "project_id"), 0, 64)
  19. if err != nil || projID == 0 {
  20. app.handleErrorFormDecoding(err, ErrProjectDecode, w)
  21. return
  22. }
  23. grs, err := app.Repo.GitRepo().ListGitReposByProjectID(uint(projID))
  24. if err != nil {
  25. app.handleErrorRead(err, ErrProjectDataRead, w)
  26. return
  27. }
  28. extGRs := make([]*models.GitRepoExternal, 0)
  29. for _, gr := range grs {
  30. extGRs = append(extGRs, gr.Externalize())
  31. }
  32. w.WriteHeader(http.StatusOK)
  33. if err := json.NewEncoder(w).Encode(extGRs); err != nil {
  34. app.handleErrorFormDecoding(err, ErrProjectDecode, w)
  35. return
  36. }
  37. }
  38. // Repo represents a GitHub or Gitab repository
  39. type Repo struct {
  40. FullName string
  41. Kind string
  42. }
  43. // DirectoryItem represents a file or subfolder in a repository
  44. type DirectoryItem struct {
  45. Path string
  46. Type string
  47. }
  48. // HandleListRepos retrieves a list of repo names
  49. func (app *App) HandleListRepos(w http.ResponseWriter, r *http.Request) {
  50. tok, err := app.githubTokenFromRequest(r)
  51. if err != nil {
  52. app.handleErrorInternal(err, w)
  53. return
  54. }
  55. res := make([]Repo, 0)
  56. client := github.NewClient(app.GithubProjectConf.Client(oauth2.NoContext, tok))
  57. allRepos := make([]*github.Repository, 0)
  58. opt := &github.RepositoryListOptions{
  59. ListOptions: github.ListOptions{
  60. PerPage: 100,
  61. },
  62. Sort: "updated",
  63. }
  64. for {
  65. repos, resp, err := client.Repositories.List(context.Background(), "", opt)
  66. if err != nil {
  67. app.handleErrorInternal(err, w)
  68. return
  69. }
  70. allRepos = append(allRepos, repos...)
  71. if resp.NextPage == 0 {
  72. break
  73. }
  74. opt.Page = resp.NextPage
  75. }
  76. for _, repo := range allRepos {
  77. res = append(res, Repo{
  78. FullName: repo.GetFullName(),
  79. Kind: "github",
  80. })
  81. }
  82. json.NewEncoder(w).Encode(res)
  83. }
  84. // HandleDeleteProjectGitRepo handles the deletion of a Github Repo via the git repo ID
  85. func (app *App) HandleDeleteProjectGitRepo(w http.ResponseWriter, r *http.Request) {
  86. id, err := strconv.ParseUint(chi.URLParam(r, "git_repo_id"), 0, 64)
  87. if err != nil || id == 0 {
  88. app.handleErrorFormDecoding(err, ErrProjectDecode, w)
  89. return
  90. }
  91. repo, err := app.Repo.GitRepo().ReadGitRepo(uint(id))
  92. if err != nil {
  93. app.handleErrorRead(err, ErrProjectDataRead, w)
  94. return
  95. }
  96. err = app.Repo.GitRepo().DeleteGitRepo(repo)
  97. if err != nil {
  98. app.handleErrorRead(err, ErrProjectDataRead, w)
  99. return
  100. }
  101. w.WriteHeader(http.StatusOK)
  102. }
  103. // HandleGetBranches retrieves a list of branch names for a specified repo
  104. func (app *App) HandleGetBranches(w http.ResponseWriter, r *http.Request) {
  105. tok, err := app.githubTokenFromRequest(r)
  106. if err != nil {
  107. app.handleErrorInternal(err, w)
  108. return
  109. }
  110. owner := chi.URLParam(r, "owner")
  111. name := chi.URLParam(r, "name")
  112. client := github.NewClient(app.GithubProjectConf.Client(oauth2.NoContext, tok))
  113. // List all branches for a specified repo
  114. branches, _, err := client.Repositories.ListBranches(context.Background(), owner, name, &github.ListOptions{
  115. PerPage: 100,
  116. })
  117. if err != nil {
  118. return
  119. }
  120. res := []string{}
  121. for _, b := range branches {
  122. res = append(res, b.GetName())
  123. }
  124. json.NewEncoder(w).Encode(res)
  125. }
  126. // HandleGetBranchContents retrieves the contents of a specific branch and subdirectory
  127. func (app *App) HandleGetBranchContents(w http.ResponseWriter, r *http.Request) {
  128. tok, err := app.githubTokenFromRequest(r)
  129. if err != nil {
  130. app.handleErrorInternal(err, w)
  131. return
  132. }
  133. client := github.NewClient(app.GithubProjectConf.Client(oauth2.NoContext, tok))
  134. queryParams, err := url.ParseQuery(r.URL.RawQuery)
  135. if err != nil {
  136. app.handleErrorFormDecoding(err, ErrReleaseDecode, w)
  137. return
  138. }
  139. owner := chi.URLParam(r, "owner")
  140. name := chi.URLParam(r, "name")
  141. branch := chi.URLParam(r, "branch")
  142. repoContentOptions := github.RepositoryContentGetOptions{}
  143. repoContentOptions.Ref = branch
  144. _, directoryContents, _, err := client.Repositories.GetContents(context.Background(), owner, name, queryParams["dir"][0], &repoContentOptions)
  145. if err != nil {
  146. app.handleErrorInternal(err, w)
  147. return
  148. }
  149. res := []DirectoryItem{}
  150. for i := range directoryContents {
  151. d := DirectoryItem{}
  152. d.Path = *directoryContents[i].Path
  153. d.Type = *directoryContents[i].Type
  154. res = append(res, d)
  155. }
  156. // Ret2: recursively traverse all dirs to create config bundle (case on type == dir)
  157. // https://api.github.com/repos/porter-dev/porter/contents?ref=frontend-graph
  158. json.NewEncoder(w).Encode(res)
  159. }
  160. type GetProcfileContentsResp map[string]string
  161. var procfileRegex = regexp.MustCompile("^([A-Za-z0-9_]+):\\s*(.+)$")
  162. // HandleGetProcfileContents retrieves the contents of a procfile in a github repo
  163. func (app *App) HandleGetProcfileContents(w http.ResponseWriter, r *http.Request) {
  164. tok, err := app.githubTokenFromRequest(r)
  165. if err != nil {
  166. app.handleErrorInternal(err, w)
  167. return
  168. }
  169. client := github.NewClient(app.GithubProjectConf.Client(oauth2.NoContext, tok))
  170. owner := chi.URLParam(r, "owner")
  171. name := chi.URLParam(r, "name")
  172. branch := chi.URLParam(r, "branch")
  173. queryParams, err := url.ParseQuery(r.URL.RawQuery)
  174. if err != nil {
  175. app.handleErrorFormDecoding(err, ErrReleaseDecode, w)
  176. return
  177. }
  178. resp, _, _, err := client.Repositories.GetContents(
  179. context.TODO(),
  180. owner,
  181. name,
  182. queryParams["path"][0],
  183. &github.RepositoryContentGetOptions{
  184. Ref: branch,
  185. },
  186. )
  187. if err != nil {
  188. app.handleErrorInternal(err, w)
  189. return
  190. }
  191. fileData, err := resp.GetContent()
  192. if err != nil {
  193. app.handleErrorInternal(err, w)
  194. return
  195. }
  196. parsedContents := make(GetProcfileContentsResp)
  197. // parse the procfile information
  198. for _, line := range strings.Split(fileData, "\n") {
  199. if matches := procfileRegex.FindStringSubmatch(line); matches != nil {
  200. parsedContents[matches[1]] = matches[2]
  201. }
  202. }
  203. json.NewEncoder(w).Encode(parsedContents)
  204. }
  205. type HandleGetRepoZIPDownloadURLResp struct {
  206. URLString string `json:"url"`
  207. LatestCommitSHA string `json:"latest_commit_sha"`
  208. }
  209. // HandleGetRepoZIPDownloadURL gets the URL for downloading a zip file from a Github
  210. // repository
  211. func (app *App) HandleGetRepoZIPDownloadURL(w http.ResponseWriter, r *http.Request) {
  212. tok, err := app.githubTokenFromRequest(r)
  213. if err != nil {
  214. app.handleErrorInternal(err, w)
  215. return
  216. }
  217. client := github.NewClient(app.GithubProjectConf.Client(oauth2.NoContext, tok))
  218. owner := chi.URLParam(r, "owner")
  219. name := chi.URLParam(r, "name")
  220. branch := chi.URLParam(r, "branch")
  221. branchResp, _, err := client.Repositories.GetBranch(
  222. context.TODO(),
  223. owner,
  224. name,
  225. branch,
  226. )
  227. if err != nil {
  228. app.handleErrorInternal(err, w)
  229. return
  230. }
  231. ghURL, _, err := client.Repositories.GetArchiveLink(
  232. context.TODO(),
  233. owner,
  234. name,
  235. github.Zipball,
  236. &github.RepositoryContentGetOptions{
  237. Ref: *branchResp.Commit.SHA,
  238. },
  239. )
  240. if err != nil {
  241. app.handleErrorInternal(err, w)
  242. return
  243. }
  244. apiResp := HandleGetRepoZIPDownloadURLResp{
  245. URLString: ghURL.String(),
  246. LatestCommitSHA: *branchResp.Commit.SHA,
  247. }
  248. json.NewEncoder(w).Encode(apiResp)
  249. }
  250. // finds the github token given the git repo id and the project id
  251. func (app *App) githubTokenFromRequest(
  252. r *http.Request,
  253. ) (*oauth2.Token, error) {
  254. grID, err := strconv.ParseUint(chi.URLParam(r, "git_repo_id"), 0, 64)
  255. if err != nil || grID == 0 {
  256. return nil, fmt.Errorf("could not read git repo id")
  257. }
  258. // query for the git repo
  259. gr, err := app.Repo.GitRepo().ReadGitRepo(uint(grID))
  260. if err != nil {
  261. return nil, err
  262. }
  263. // get the oauth integration
  264. oauthInt, err := app.Repo.OAuthIntegration().ReadOAuthIntegration(gr.OAuthIntegrationID)
  265. if err != nil {
  266. return nil, err
  267. }
  268. return &oauth2.Token{
  269. AccessToken: string(oauthInt.AccessToken),
  270. RefreshToken: string(oauthInt.RefreshToken),
  271. TokenType: "Bearer",
  272. }, nil
  273. }