gitea源码

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357
  1. // Copyright 2021 The Gitea Authors. All rights reserved.
  2. // SPDX-License-Identifier: MIT
  3. package private
  4. import (
  5. "context"
  6. "fmt"
  7. "net/http"
  8. git_model "code.gitea.io/gitea/models/git"
  9. issues_model "code.gitea.io/gitea/models/issues"
  10. access_model "code.gitea.io/gitea/models/perm/access"
  11. repo_model "code.gitea.io/gitea/models/repo"
  12. user_model "code.gitea.io/gitea/models/user"
  13. "code.gitea.io/gitea/modules/cache"
  14. "code.gitea.io/gitea/modules/cachegroup"
  15. "code.gitea.io/gitea/modules/git"
  16. "code.gitea.io/gitea/modules/gitrepo"
  17. "code.gitea.io/gitea/modules/log"
  18. "code.gitea.io/gitea/modules/private"
  19. repo_module "code.gitea.io/gitea/modules/repository"
  20. "code.gitea.io/gitea/modules/setting"
  21. "code.gitea.io/gitea/modules/timeutil"
  22. "code.gitea.io/gitea/modules/util"
  23. "code.gitea.io/gitea/modules/web"
  24. gitea_context "code.gitea.io/gitea/services/context"
  25. pull_service "code.gitea.io/gitea/services/pull"
  26. repo_service "code.gitea.io/gitea/services/repository"
  27. )
  28. // HookPostReceive updates services and users
  29. func HookPostReceive(ctx *gitea_context.PrivateContext) {
  30. opts := web.GetForm(ctx).(*private.HookOptions)
  31. // We don't rely on RepoAssignment here because:
  32. // a) we don't need the git repo in this function
  33. // OUT OF DATE: we do need the git repo to sync the branch to the db now.
  34. // b) our update function will likely change the repository in the db so we will need to refresh it
  35. // c) we don't always need the repo
  36. ownerName := ctx.PathParam("owner")
  37. repoName := ctx.PathParam("repo")
  38. // defer getting the repository at this point - as we should only retrieve it if we're going to call update
  39. var (
  40. repo *repo_model.Repository
  41. gitRepo *git.Repository
  42. )
  43. defer gitRepo.Close() // it's safe to call Close on a nil pointer
  44. updates := make([]*repo_module.PushUpdateOptions, 0, len(opts.OldCommitIDs))
  45. wasEmpty := false
  46. for i := range opts.OldCommitIDs {
  47. refFullName := opts.RefFullNames[i]
  48. // Only trigger activity updates for changes to branches or
  49. // tags. Updates to other refs (eg, refs/notes, refs/changes,
  50. // or other less-standard refs spaces are ignored since there
  51. // may be a very large number of them).
  52. if refFullName.IsBranch() || refFullName.IsTag() {
  53. if repo == nil {
  54. repo = loadRepository(ctx, ownerName, repoName)
  55. if ctx.Written() {
  56. // Error handled in loadRepository
  57. return
  58. }
  59. wasEmpty = repo.IsEmpty
  60. }
  61. option := &repo_module.PushUpdateOptions{
  62. RefFullName: refFullName,
  63. OldCommitID: opts.OldCommitIDs[i],
  64. NewCommitID: opts.NewCommitIDs[i],
  65. PusherID: opts.UserID,
  66. PusherName: opts.UserName,
  67. RepoUserName: ownerName,
  68. RepoName: repoName,
  69. }
  70. updates = append(updates, option)
  71. if repo.IsEmpty && (refFullName.BranchName() == "master" || refFullName.BranchName() == "main") {
  72. // put the master/main branch first
  73. // FIXME: It doesn't always work, since the master/main branch may not be the first batch of updates.
  74. // If the user pushes many branches at once, the Git hook will call the internal API in batches, rather than all at once.
  75. // See https://github.com/go-gitea/gitea/blob/cb52b17f92e2d2293f7c003649743464492bca48/cmd/hook.go#L27
  76. // If the user executes `git push origin --all` and pushes more than 30 branches, the master/main may not be the default branch.
  77. copy(updates[1:], updates)
  78. updates[0] = option
  79. }
  80. }
  81. }
  82. if repo != nil && len(updates) > 0 {
  83. branchesToSync := make([]*repo_module.PushUpdateOptions, 0, len(updates))
  84. for _, update := range updates {
  85. if !update.RefFullName.IsBranch() {
  86. continue
  87. }
  88. if repo == nil {
  89. repo = loadRepository(ctx, ownerName, repoName)
  90. if ctx.Written() {
  91. return
  92. }
  93. wasEmpty = repo.IsEmpty
  94. }
  95. if update.IsDelRef() {
  96. if err := git_model.AddDeletedBranch(ctx, repo.ID, update.RefFullName.BranchName(), update.PusherID); err != nil {
  97. log.Error("Failed to add deleted branch: %s/%s Error: %v", ownerName, repoName, err)
  98. ctx.JSON(http.StatusInternalServerError, private.HookPostReceiveResult{
  99. Err: fmt.Sprintf("Failed to add deleted branch: %s/%s Error: %v", ownerName, repoName, err),
  100. })
  101. return
  102. }
  103. } else {
  104. branchesToSync = append(branchesToSync, update)
  105. // TODO: should we return the error and return the error when pushing? Currently it will log the error and not prevent the pushing
  106. pull_service.UpdatePullsRefs(ctx, repo, update)
  107. }
  108. }
  109. if len(branchesToSync) > 0 {
  110. var err error
  111. gitRepo, err = gitrepo.OpenRepository(ctx, repo)
  112. if err != nil {
  113. log.Error("Failed to open repository: %s/%s Error: %v", ownerName, repoName, err)
  114. ctx.JSON(http.StatusInternalServerError, private.HookPostReceiveResult{
  115. Err: fmt.Sprintf("Failed to open repository: %s/%s Error: %v", ownerName, repoName, err),
  116. })
  117. return
  118. }
  119. var (
  120. branchNames = make([]string, 0, len(branchesToSync))
  121. commitIDs = make([]string, 0, len(branchesToSync))
  122. )
  123. for _, update := range branchesToSync {
  124. branchNames = append(branchNames, update.RefFullName.BranchName())
  125. commitIDs = append(commitIDs, update.NewCommitID)
  126. }
  127. if err := repo_service.SyncBranchesToDB(ctx, repo.ID, opts.UserID, branchNames, commitIDs, gitRepo.GetCommit); err != nil {
  128. ctx.JSON(http.StatusInternalServerError, private.HookPostReceiveResult{
  129. Err: fmt.Sprintf("Failed to sync branch to DB in repository: %s/%s Error: %v", ownerName, repoName, err),
  130. })
  131. return
  132. }
  133. }
  134. if err := repo_service.PushUpdates(updates); err != nil {
  135. log.Error("Failed to Update: %s/%s Total Updates: %d", ownerName, repoName, len(updates))
  136. for i, update := range updates {
  137. log.Error("Failed to Update: %s/%s Update: %d/%d: Branch: %s", ownerName, repoName, i, len(updates), update.RefFullName.BranchName())
  138. }
  139. log.Error("Failed to Update: %s/%s Error: %v", ownerName, repoName, err)
  140. ctx.JSON(http.StatusInternalServerError, private.HookPostReceiveResult{
  141. Err: fmt.Sprintf("Failed to Update: %s/%s Error: %v", ownerName, repoName, err),
  142. })
  143. return
  144. }
  145. }
  146. // handle pull request merging, a pull request action should push at least 1 commit
  147. if opts.PushTrigger == repo_module.PushTriggerPRMergeToBase {
  148. handlePullRequestMerging(ctx, opts, ownerName, repoName, updates)
  149. if ctx.Written() {
  150. return
  151. }
  152. }
  153. isPrivate := opts.GitPushOptions.Bool(private.GitPushOptionRepoPrivate)
  154. isTemplate := opts.GitPushOptions.Bool(private.GitPushOptionRepoTemplate)
  155. // Handle Push Options
  156. if isPrivate.Has() || isTemplate.Has() {
  157. // load the repository
  158. if repo == nil {
  159. repo = loadRepository(ctx, ownerName, repoName)
  160. if ctx.Written() {
  161. // Error handled in loadRepository
  162. return
  163. }
  164. wasEmpty = repo.IsEmpty
  165. }
  166. pusher, err := loadContextCacheUser(ctx, opts.UserID)
  167. if err != nil {
  168. log.Error("Failed to Update: %s/%s Error: %v", ownerName, repoName, err)
  169. ctx.JSON(http.StatusInternalServerError, private.HookPostReceiveResult{
  170. Err: fmt.Sprintf("Failed to Update: %s/%s Error: %v", ownerName, repoName, err),
  171. })
  172. return
  173. }
  174. perm, err := access_model.GetUserRepoPermission(ctx, repo, pusher)
  175. if err != nil {
  176. log.Error("Failed to Update: %s/%s Error: %v", ownerName, repoName, err)
  177. ctx.JSON(http.StatusInternalServerError, private.HookPostReceiveResult{
  178. Err: fmt.Sprintf("Failed to Update: %s/%s Error: %v", ownerName, repoName, err),
  179. })
  180. return
  181. }
  182. if !perm.IsOwner() && !perm.IsAdmin() {
  183. ctx.JSON(http.StatusNotFound, private.HookPostReceiveResult{
  184. Err: "Permissions denied",
  185. })
  186. return
  187. }
  188. // FIXME: these options are not quite right, for example: changing visibility should do more works than just setting the is_private flag
  189. // These options should only be used for "push-to-create"
  190. if isPrivate.Has() && repo.IsPrivate != isPrivate.Value() {
  191. // TODO: it needs to do more work
  192. repo.IsPrivate = isPrivate.Value()
  193. if err = repo_model.UpdateRepositoryColsNoAutoTime(ctx, repo, "is_private"); err != nil {
  194. ctx.JSON(http.StatusInternalServerError, private.HookPostReceiveResult{Err: "Failed to change visibility"})
  195. }
  196. }
  197. if isTemplate.Has() && repo.IsTemplate != isTemplate.Value() {
  198. repo.IsTemplate = isTemplate.Value()
  199. if err = repo_model.UpdateRepositoryColsNoAutoTime(ctx, repo, "is_template"); err != nil {
  200. ctx.JSON(http.StatusInternalServerError, private.HookPostReceiveResult{Err: "Failed to change template status"})
  201. }
  202. }
  203. }
  204. results := make([]private.HookPostReceiveBranchResult, 0, len(opts.OldCommitIDs))
  205. // We have to reload the repo in case its state is changed above
  206. repo = nil
  207. var baseRepo *repo_model.Repository
  208. // Now handle the pull request notification trailers
  209. for i := range opts.OldCommitIDs {
  210. refFullName := opts.RefFullNames[i]
  211. newCommitID := opts.NewCommitIDs[i]
  212. // If we've pushed a branch (and not deleted it)
  213. if !git.IsEmptyCommitID(newCommitID) && refFullName.IsBranch() {
  214. // First ensure we have the repository loaded, we're allowed pulls requests and we can get the base repo
  215. if repo == nil {
  216. repo = loadRepository(ctx, ownerName, repoName)
  217. if ctx.Written() {
  218. return
  219. }
  220. baseRepo = repo
  221. if repo.IsFork {
  222. if err := repo.GetBaseRepo(ctx); err != nil {
  223. log.Error("Failed to get Base Repository of Forked repository: %-v Error: %v", repo, err)
  224. ctx.JSON(http.StatusInternalServerError, private.HookPostReceiveResult{
  225. Err: fmt.Sprintf("Failed to get Base Repository of Forked repository: %-v Error: %v", repo, err),
  226. RepoWasEmpty: wasEmpty,
  227. })
  228. return
  229. }
  230. if repo.BaseRepo.AllowsPulls(ctx) {
  231. baseRepo = repo.BaseRepo
  232. }
  233. }
  234. if !baseRepo.AllowsPulls(ctx) {
  235. // We can stop there's no need to go any further
  236. ctx.JSON(http.StatusOK, private.HookPostReceiveResult{
  237. RepoWasEmpty: wasEmpty,
  238. })
  239. return
  240. }
  241. }
  242. branch := refFullName.BranchName()
  243. if branch == baseRepo.DefaultBranch {
  244. if err := repo_service.AddRepoToLicenseUpdaterQueue(&repo_service.LicenseUpdaterOptions{
  245. RepoID: repo.ID,
  246. }); err != nil {
  247. ctx.JSON(http.StatusInternalServerError, private.Response{Err: err.Error()})
  248. return
  249. }
  250. // If our branch is the default branch of an unforked repo - there's no PR to create or refer to
  251. if !repo.IsFork {
  252. results = append(results, private.HookPostReceiveBranchResult{})
  253. continue
  254. }
  255. }
  256. pr, err := issues_model.GetUnmergedPullRequest(ctx, repo.ID, baseRepo.ID, branch, baseRepo.DefaultBranch, issues_model.PullRequestFlowGithub)
  257. if err != nil && !issues_model.IsErrPullRequestNotExist(err) {
  258. log.Error("Failed to get active PR in: %-v Branch: %s to: %-v Branch: %s Error: %v", repo, branch, baseRepo, baseRepo.DefaultBranch, err)
  259. ctx.JSON(http.StatusInternalServerError, private.HookPostReceiveResult{
  260. Err: fmt.Sprintf(
  261. "Failed to get active PR in: %-v Branch: %s to: %-v Branch: %s Error: %v", repo, branch, baseRepo, baseRepo.DefaultBranch, err),
  262. RepoWasEmpty: wasEmpty,
  263. })
  264. return
  265. }
  266. if pr == nil {
  267. results = append(results, private.HookPostReceiveBranchResult{
  268. Message: setting.Git.PullRequestPushMessage && baseRepo.AllowsPulls(ctx),
  269. Create: true,
  270. Branch: branch,
  271. URL: fmt.Sprintf("%s/pulls/new/%s", repo.HTMLURL(), util.PathEscapeSegments(branch)),
  272. })
  273. } else {
  274. results = append(results, private.HookPostReceiveBranchResult{
  275. Message: setting.Git.PullRequestPushMessage && baseRepo.AllowsPulls(ctx),
  276. Create: false,
  277. Branch: branch,
  278. URL: fmt.Sprintf("%s/pulls/%d", baseRepo.HTMLURL(), pr.Index),
  279. })
  280. }
  281. }
  282. }
  283. ctx.JSON(http.StatusOK, private.HookPostReceiveResult{
  284. Results: results,
  285. RepoWasEmpty: wasEmpty,
  286. })
  287. }
  288. func loadContextCacheUser(ctx context.Context, id int64) (*user_model.User, error) {
  289. return cache.GetWithContextCache(ctx, cachegroup.User, id, user_model.GetUserByID)
  290. }
  291. // handlePullRequestMerging handle pull request merging, a pull request action should push at least 1 commit
  292. func handlePullRequestMerging(ctx *gitea_context.PrivateContext, opts *private.HookOptions, ownerName, repoName string, updates []*repo_module.PushUpdateOptions) {
  293. if len(updates) == 0 {
  294. ctx.JSON(http.StatusInternalServerError, private.HookPostReceiveResult{
  295. Err: fmt.Sprintf("Pushing a merged PR (pr:%d) no commits pushed ", opts.PullRequestID),
  296. })
  297. return
  298. }
  299. pr, err := issues_model.GetPullRequestByID(ctx, opts.PullRequestID)
  300. if err != nil {
  301. log.Error("GetPullRequestByID[%d]: %v", opts.PullRequestID, err)
  302. ctx.JSON(http.StatusInternalServerError, private.HookPostReceiveResult{Err: "GetPullRequestByID failed"})
  303. return
  304. }
  305. pusher, err := loadContextCacheUser(ctx, opts.UserID)
  306. if err != nil {
  307. log.Error("Failed to Update: %s/%s Error: %v", ownerName, repoName, err)
  308. ctx.JSON(http.StatusInternalServerError, private.HookPostReceiveResult{Err: "Load pusher user failed"})
  309. return
  310. }
  311. // FIXME: Maybe we need a `PullRequestStatusMerged` status for PRs that are merged, currently we use the previous status
  312. // here to keep it as before, that maybe PullRequestStatusMergeable
  313. if _, err := pull_service.SetMerged(ctx, pr, updates[len(updates)-1].NewCommitID, timeutil.TimeStampNow(), pusher, pr.Status); err != nil {
  314. log.Error("Failed to update PR to merged: %v", err)
  315. ctx.JSON(http.StatusInternalServerError, private.HookPostReceiveResult{Err: "Failed to update PR to merged"})
  316. }
  317. }