You can not select more than 25 topics Topics must start with a chinese character,a letter or number, can include dashes ('-') and can be up to 35 characters long.

push.go 13 kB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411
  1. // Copyright 2020 The Gitea Authors. All rights reserved.
  2. // Use of this source code is governed by a MIT-style
  3. // license that can be found in the LICENSE file.
  4. package repository
  5. import (
  6. "container/list"
  7. "encoding/json"
  8. "fmt"
  9. "strings"
  10. "time"
  11. "code.gitea.io/gitea/models"
  12. "code.gitea.io/gitea/modules/cache"
  13. "code.gitea.io/gitea/modules/git"
  14. "code.gitea.io/gitea/modules/graceful"
  15. "code.gitea.io/gitea/modules/log"
  16. "code.gitea.io/gitea/modules/notification"
  17. "code.gitea.io/gitea/modules/queue"
  18. "code.gitea.io/gitea/modules/repofiles"
  19. repo_module "code.gitea.io/gitea/modules/repository"
  20. "code.gitea.io/gitea/modules/setting"
  21. pull_service "code.gitea.io/gitea/services/pull"
  22. )
  23. // PushUpdateOptions defines the push update options
  24. type PushUpdateOptions struct {
  25. PusherID int64
  26. PusherName string
  27. RepoUserName string
  28. RepoName string
  29. RefFullName string // branch, tag or other name to push
  30. OldCommitID string
  31. NewCommitID string
  32. }
  33. // IsNewRef return true if it's a first-time push to a branch, tag or etc.
  34. func (opts PushUpdateOptions) IsNewRef() bool {
  35. return opts.OldCommitID == git.EmptySHA
  36. }
  37. // IsDelRef return true if it's a deletion to a branch or tag
  38. func (opts PushUpdateOptions) IsDelRef() bool {
  39. return opts.NewCommitID == git.EmptySHA
  40. }
  41. // IsUpdateRef return true if it's an update operation
  42. func (opts PushUpdateOptions) IsUpdateRef() bool {
  43. return !opts.IsNewRef() && !opts.IsDelRef()
  44. }
  45. // IsTag return true if it's an operation to a tag
  46. func (opts PushUpdateOptions) IsTag() bool {
  47. return strings.HasPrefix(opts.RefFullName, git.TagPrefix)
  48. }
  49. // IsNewTag return true if it's a creation to a tag
  50. func (opts PushUpdateOptions) IsNewTag() bool {
  51. return opts.IsTag() && opts.IsNewRef()
  52. }
  53. // IsDelTag return true if it's a deletion to a tag
  54. func (opts PushUpdateOptions) IsDelTag() bool {
  55. return opts.IsTag() && opts.IsDelRef()
  56. }
  57. // IsBranch return true if it's a push to branch
  58. func (opts PushUpdateOptions) IsBranch() bool {
  59. return strings.HasPrefix(opts.RefFullName, git.BranchPrefix)
  60. }
  61. // IsNewBranch return true if it's the first-time push to a branch
  62. func (opts PushUpdateOptions) IsNewBranch() bool {
  63. return opts.IsBranch() && opts.IsNewRef()
  64. }
  65. // IsUpdateBranch return true if it's not the first push to a branch
  66. func (opts PushUpdateOptions) IsUpdateBranch() bool {
  67. return opts.IsBranch() && opts.IsUpdateRef()
  68. }
  69. // IsDelBranch return true if it's a deletion to a branch
  70. func (opts PushUpdateOptions) IsDelBranch() bool {
  71. return opts.IsBranch() && opts.IsDelRef()
  72. }
  73. // TagName returns simple tag name if it's an operation to a tag
  74. func (opts PushUpdateOptions) TagName() string {
  75. return opts.RefFullName[len(git.TagPrefix):]
  76. }
  77. // BranchName returns simple branch name if it's an operation to branch
  78. func (opts PushUpdateOptions) BranchName() string {
  79. return opts.RefFullName[len(git.BranchPrefix):]
  80. }
  81. // RefName returns simple name for ref
  82. func (opts PushUpdateOptions) RefName() string {
  83. if strings.HasPrefix(opts.RefFullName, git.TagPrefix) {
  84. return opts.RefFullName[len(git.TagPrefix):]
  85. } else if strings.HasPrefix(opts.RefFullName, git.BranchPrefix) {
  86. return opts.RefFullName[len(git.BranchPrefix):]
  87. }
  88. return ""
  89. }
  90. // RepoFullName returns repo full name
  91. func (opts PushUpdateOptions) RepoFullName() string {
  92. return opts.RepoUserName + "/" + opts.RepoName
  93. }
  94. // isForcePush detect if a push is a force push
  95. func isForcePush(repoPath string, opts *PushUpdateOptions) (bool, error) {
  96. if !opts.IsUpdateBranch() {
  97. return false, nil
  98. }
  99. output, err := git.NewCommand("rev-list", "--max-count=1", opts.OldCommitID, "^"+opts.NewCommitID).RunInDir(repoPath)
  100. if err != nil {
  101. return false, err
  102. } else if len(output) > 0 {
  103. return true, nil
  104. }
  105. return false, nil
  106. }
  107. // pushQueue represents a queue to handle update pull request tests
  108. var pushQueue queue.Queue
  109. // handle passed PR IDs and test the PRs
  110. func handle(data ...queue.Data) {
  111. for _, datum := range data {
  112. opts := datum.([]*PushUpdateOptions)
  113. if err := pushUpdates(opts); err != nil {
  114. log.Error("pushUpdate failed: %v", err)
  115. }
  116. }
  117. }
  118. func initPushQueue() error {
  119. pushQueue = queue.CreateQueue("push_update", handle, []*PushUpdateOptions{}).(queue.Queue)
  120. if pushQueue == nil {
  121. return fmt.Errorf("Unable to create push_update Queue")
  122. }
  123. go graceful.GetManager().RunWithShutdownFns(pushQueue.Run)
  124. return nil
  125. }
  126. // PushUpdate is an alias of PushUpdates for single push update options
  127. func PushUpdate(opts *PushUpdateOptions) error {
  128. return PushUpdates([]*PushUpdateOptions{opts})
  129. }
  130. // PushUpdates adds a push update to push queue
  131. func PushUpdates(opts []*PushUpdateOptions) error {
  132. if len(opts) == 0 {
  133. return nil
  134. }
  135. for _, opt := range opts {
  136. if opt.IsNewRef() && opt.IsDelRef() {
  137. return fmt.Errorf("Old and new revisions are both %s", git.EmptySHA)
  138. }
  139. }
  140. return pushQueue.Push(opts)
  141. }
  142. // pushUpdates generates push action history feeds for push updating multiple refs
  143. func pushUpdates(optsList []*PushUpdateOptions) error {
  144. if len(optsList) == 0 {
  145. return nil
  146. }
  147. repo, err := models.GetRepositoryByOwnerAndName(optsList[0].RepoUserName, optsList[0].RepoName)
  148. if err != nil {
  149. return fmt.Errorf("GetRepositoryByOwnerAndName failed: %v", err)
  150. }
  151. repoPath := repo.RepoPath()
  152. gitRepo, err := git.OpenRepository(repoPath)
  153. if err != nil {
  154. return fmt.Errorf("OpenRepository: %v", err)
  155. }
  156. defer gitRepo.Close()
  157. if err = repo.UpdateSize(models.DefaultDBContext()); err != nil {
  158. log.Error("Failed to update size for repository: %v", err)
  159. }
  160. addTags := make([]string, 0, len(optsList))
  161. delTags := make([]string, 0, len(optsList))
  162. actions := make([]*commitRepoActionOptions, 0, len(optsList))
  163. var pusher *models.User
  164. for _, opts := range optsList {
  165. if opts.IsNewRef() && opts.IsDelRef() {
  166. return fmt.Errorf("Old and new revisions are both %s", git.EmptySHA)
  167. }
  168. var commits = &repo_module.PushCommits{}
  169. if opts.IsTag() { // If is tag reference {
  170. tagName := opts.TagName()
  171. if opts.IsDelRef() {
  172. delTags = append(delTags, tagName)
  173. } else { // is new tag
  174. addTags = append(addTags, tagName)
  175. }
  176. } else if opts.IsBranch() { // If is branch reference
  177. if pusher == nil || pusher.ID != opts.PusherID {
  178. var err error
  179. if pusher, err = models.GetUserByID(opts.PusherID); err != nil {
  180. return err
  181. }
  182. }
  183. branch := opts.BranchName()
  184. if !opts.IsDelRef() {
  185. log.Trace("TriggerTask '%s/%s' by %s", repo.Name, branch, pusher.Name)
  186. go pull_service.AddTestPullRequestTask(pusher, repo.ID, branch, true, opts.OldCommitID, opts.NewCommitID)
  187. newCommit, err := gitRepo.GetCommit(opts.NewCommitID)
  188. if err != nil {
  189. return fmt.Errorf("gitRepo.GetCommit: %v", err)
  190. }
  191. // Push new branch.
  192. var l *list.List
  193. if opts.IsNewRef() {
  194. l, err = newCommit.CommitsBeforeLimit(10)
  195. if err != nil {
  196. return fmt.Errorf("newCommit.CommitsBeforeLimit: %v", err)
  197. }
  198. } else {
  199. l, err = newCommit.CommitsBeforeUntil(opts.OldCommitID)
  200. if err != nil {
  201. return fmt.Errorf("newCommit.CommitsBeforeUntil: %v", err)
  202. }
  203. isForce, err := isForcePush(repo.RepoPath(), opts)
  204. if err != nil {
  205. log.Error("isForcePush %s/%s failed: %v", repo.ID, branch, err)
  206. }
  207. if isForce {
  208. log.Trace("Push %s is a force push", opts.NewCommitID)
  209. cache.Remove(repo.GetCommitsCountCacheKey(opts.RefName(), true))
  210. } else {
  211. // TODO: increment update the commit count cache but not remove
  212. cache.Remove(repo.GetCommitsCountCacheKey(opts.RefName(), true))
  213. }
  214. }
  215. commits = repo_module.ListToPushCommits(l)
  216. if err = models.RemoveDeletedBranch(repo.ID, branch); err != nil {
  217. log.Error("models.RemoveDeletedBranch %s/%s failed: %v", repo.ID, branch, err)
  218. }
  219. // Cache for big repository
  220. if err := repo_module.CacheRef(repo, gitRepo, opts.RefFullName); err != nil {
  221. log.Error("repo_module.CacheRef %s/%s failed: %v", repo.ID, branch, err)
  222. }
  223. } else if err = pull_service.CloseBranchPulls(pusher, repo.ID, branch); err != nil {
  224. // close all related pulls
  225. log.Error("close related pull request failed: %v", err)
  226. }
  227. // Even if user delete a branch on a repository which he didn't watch, he will be watch that.
  228. if err = models.WatchIfAuto(opts.PusherID, repo.ID, true); err != nil {
  229. log.Warn("Fail to perform auto watch on user %v for repo %v: %v", opts.PusherID, repo.ID, err)
  230. }
  231. }
  232. actions = append(actions, &commitRepoActionOptions{
  233. PushUpdateOptions: *opts,
  234. Pusher: pusher,
  235. RepoOwnerID: repo.OwnerID,
  236. Commits: commits,
  237. })
  238. }
  239. if err := repo_module.PushUpdateAddDeleteTags(repo, gitRepo, addTags, delTags); err != nil {
  240. return fmt.Errorf("PushUpdateAddDeleteTags: %v", err)
  241. }
  242. if err := commitRepoAction(repo, gitRepo, actions...); err != nil {
  243. return fmt.Errorf("commitRepoAction: %v", err)
  244. }
  245. return nil
  246. }
  247. // commitRepoActionOptions represent options of a new commit action.
  248. type commitRepoActionOptions struct {
  249. PushUpdateOptions
  250. Pusher *models.User
  251. RepoOwnerID int64
  252. Commits *repo_module.PushCommits
  253. }
  254. // commitRepoAction adds new commit action to the repository, and prepare
  255. // corresponding webhooks.
  256. func commitRepoAction(repo *models.Repository, gitRepo *git.Repository, optsList ...*commitRepoActionOptions) error {
  257. actions := make([]*models.Action, len(optsList))
  258. for i, opts := range optsList {
  259. if opts.Pusher == nil || opts.Pusher.Name != opts.PusherName {
  260. var err error
  261. opts.Pusher, err = models.GetUserByName(opts.PusherName)
  262. if err != nil {
  263. return fmt.Errorf("GetUserByName [%s]: %v", opts.PusherName, err)
  264. }
  265. }
  266. refName := git.RefEndName(opts.RefFullName)
  267. // Change default branch and empty status only if pushed ref is non-empty branch.
  268. if repo.IsEmpty && opts.IsBranch() && !opts.IsDelRef() {
  269. repo.DefaultBranch = refName
  270. repo.IsEmpty = false
  271. if refName != "master" {
  272. if err := gitRepo.SetDefaultBranch(repo.DefaultBranch); err != nil {
  273. if !git.IsErrUnsupportedVersion(err) {
  274. return err
  275. }
  276. }
  277. }
  278. // Update the is empty and default_branch columns
  279. if err := models.UpdateRepositoryCols(repo, "default_branch", "is_empty"); err != nil {
  280. return fmt.Errorf("UpdateRepositoryCols: %v", err)
  281. }
  282. }
  283. opType := models.ActionCommitRepo
  284. // Check it's tag push or branch.
  285. if opts.IsTag() {
  286. opType = models.ActionPushTag
  287. if opts.IsDelRef() {
  288. opType = models.ActionDeleteTag
  289. }
  290. opts.Commits = &repo_module.PushCommits{}
  291. } else if opts.IsDelRef() {
  292. opType = models.ActionDeleteBranch
  293. opts.Commits = &repo_module.PushCommits{}
  294. } else {
  295. // if not the first commit, set the compare URL.
  296. if !opts.IsNewRef() {
  297. opts.Commits.CompareURL = repo.ComposeCompareURL(opts.OldCommitID, opts.NewCommitID)
  298. }
  299. if err := repofiles.UpdateIssuesCommit(opts.Pusher, repo, opts.Commits.Commits, refName); err != nil {
  300. log.Error("updateIssuesCommit: %v", err)
  301. }
  302. }
  303. if len(opts.Commits.Commits) > setting.UI.FeedMaxCommitNum {
  304. opts.Commits.Commits = opts.Commits.Commits[:setting.UI.FeedMaxCommitNum]
  305. }
  306. data, err := json.Marshal(opts.Commits)
  307. if err != nil {
  308. return fmt.Errorf("Marshal: %v", err)
  309. }
  310. actions[i] = &models.Action{
  311. ActUserID: opts.Pusher.ID,
  312. ActUser: opts.Pusher,
  313. OpType: opType,
  314. Content: string(data),
  315. RepoID: repo.ID,
  316. Repo: repo,
  317. RefName: refName,
  318. IsPrivate: repo.IsPrivate,
  319. }
  320. var isHookEventPush = true
  321. switch opType {
  322. case models.ActionCommitRepo: // Push
  323. if opts.IsNewBranch() {
  324. notification.NotifyCreateRef(opts.Pusher, repo, "branch", opts.RefFullName)
  325. }
  326. case models.ActionDeleteBranch: // Delete Branch
  327. notification.NotifyDeleteRef(opts.Pusher, repo, "branch", opts.RefFullName)
  328. case models.ActionPushTag: // Create
  329. notification.NotifyCreateRef(opts.Pusher, repo, "tag", opts.RefFullName)
  330. case models.ActionDeleteTag: // Delete Tag
  331. notification.NotifyDeleteRef(opts.Pusher, repo, "tag", opts.RefFullName)
  332. default:
  333. isHookEventPush = false
  334. }
  335. if isHookEventPush {
  336. notification.NotifyPushCommits(opts.Pusher, repo, opts.RefFullName, opts.OldCommitID, opts.NewCommitID, opts.Commits)
  337. }
  338. }
  339. // Change repository last updated time.
  340. if err := models.UpdateRepositoryUpdatedTime(repo.ID, time.Now()); err != nil {
  341. return fmt.Errorf("UpdateRepositoryUpdatedTime: %v", err)
  342. }
  343. if err := models.NotifyWatchers(actions...); err != nil {
  344. return fmt.Errorf("NotifyWatchers: %v", err)
  345. }
  346. return nil
  347. }