Ви не можете вибрати більше 25 тем Теми мають розпочинатися з літери або цифри, можуть містити дефіси (-) і не повинні перевищувати 35 символів.

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