選択できるのは25トピックまでです。 トピックは、先頭が英数字で、英数字とダッシュ('-')を使用した35文字以内のものにしてください。

action.go 21KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779
  1. // Copyright 2014 The Gogs 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 models
  5. import (
  6. "encoding/json"
  7. "fmt"
  8. "path"
  9. "regexp"
  10. "strconv"
  11. "strings"
  12. "time"
  13. "unicode"
  14. "code.gitea.io/git"
  15. "code.gitea.io/gitea/modules/base"
  16. "code.gitea.io/gitea/modules/log"
  17. "code.gitea.io/gitea/modules/setting"
  18. "code.gitea.io/gitea/modules/util"
  19. api "code.gitea.io/sdk/gitea"
  20. "github.com/Unknwon/com"
  21. "github.com/go-xorm/builder"
  22. )
  23. // ActionType represents the type of an action.
  24. type ActionType int
  25. // Possible action types.
  26. const (
  27. ActionCreateRepo ActionType = iota + 1 // 1
  28. ActionRenameRepo // 2
  29. ActionStarRepo // 3
  30. ActionWatchRepo // 4
  31. ActionCommitRepo // 5
  32. ActionCreateIssue // 6
  33. ActionCreatePullRequest // 7
  34. ActionTransferRepo // 8
  35. ActionPushTag // 9
  36. ActionCommentIssue // 10
  37. ActionMergePullRequest // 11
  38. ActionCloseIssue // 12
  39. ActionReopenIssue // 13
  40. ActionClosePullRequest // 14
  41. ActionReopenPullRequest // 15
  42. ActionDeleteTag // 16
  43. ActionDeleteBranch // 17
  44. )
  45. var (
  46. // Same as Github. See
  47. // https://help.github.com/articles/closing-issues-via-commit-messages
  48. issueCloseKeywords = []string{"close", "closes", "closed", "fix", "fixes", "fixed", "resolve", "resolves", "resolved"}
  49. issueReopenKeywords = []string{"reopen", "reopens", "reopened"}
  50. issueCloseKeywordsPat, issueReopenKeywordsPat *regexp.Regexp
  51. issueReferenceKeywordsPat *regexp.Regexp
  52. )
  53. const issueRefRegexpStr = `(?:\S+/\S=)?#\d+`
  54. func assembleKeywordsPattern(words []string) string {
  55. return fmt.Sprintf(`(?i)(?:%s) %s`, strings.Join(words, "|"), issueRefRegexpStr)
  56. }
  57. func init() {
  58. issueCloseKeywordsPat = regexp.MustCompile(assembleKeywordsPattern(issueCloseKeywords))
  59. issueReopenKeywordsPat = regexp.MustCompile(assembleKeywordsPattern(issueReopenKeywords))
  60. issueReferenceKeywordsPat = regexp.MustCompile(issueRefRegexpStr)
  61. }
  62. // Action represents user operation type and other information to
  63. // repository. It implemented interface base.Actioner so that can be
  64. // used in template render.
  65. type Action struct {
  66. ID int64 `xorm:"pk autoincr"`
  67. UserID int64 `xorm:"INDEX"` // Receiver user id.
  68. OpType ActionType
  69. ActUserID int64 `xorm:"INDEX"` // Action user id.
  70. ActUser *User `xorm:"-"`
  71. RepoID int64 `xorm:"INDEX"`
  72. Repo *Repository `xorm:"-"`
  73. CommentID int64 `xorm:"INDEX"`
  74. Comment *Comment `xorm:"-"`
  75. IsDeleted bool `xorm:"INDEX NOT NULL DEFAULT false"`
  76. RefName string
  77. IsPrivate bool `xorm:"INDEX NOT NULL DEFAULT false"`
  78. Content string `xorm:"TEXT"`
  79. CreatedUnix util.TimeStamp `xorm:"INDEX created"`
  80. }
  81. // GetOpType gets the ActionType of this action.
  82. func (a *Action) GetOpType() ActionType {
  83. return a.OpType
  84. }
  85. func (a *Action) loadActUser() {
  86. if a.ActUser != nil {
  87. return
  88. }
  89. var err error
  90. a.ActUser, err = GetUserByID(a.ActUserID)
  91. if err == nil {
  92. return
  93. } else if IsErrUserNotExist(err) {
  94. a.ActUser = NewGhostUser()
  95. } else {
  96. log.Error(4, "GetUserByID(%d): %v", a.ActUserID, err)
  97. }
  98. }
  99. func (a *Action) loadRepo() {
  100. if a.Repo != nil {
  101. return
  102. }
  103. var err error
  104. a.Repo, err = GetRepositoryByID(a.RepoID)
  105. if err != nil {
  106. log.Error(4, "GetRepositoryByID(%d): %v", a.RepoID, err)
  107. }
  108. }
  109. // GetActUserName gets the action's user name.
  110. func (a *Action) GetActUserName() string {
  111. a.loadActUser()
  112. return a.ActUser.Name
  113. }
  114. // ShortActUserName gets the action's user name trimmed to max 20
  115. // chars.
  116. func (a *Action) ShortActUserName() string {
  117. return base.EllipsisString(a.GetActUserName(), 20)
  118. }
  119. // GetActAvatar the action's user's avatar link
  120. func (a *Action) GetActAvatar() string {
  121. a.loadActUser()
  122. return a.ActUser.RelAvatarLink()
  123. }
  124. // GetRepoUserName returns the name of the action repository owner.
  125. func (a *Action) GetRepoUserName() string {
  126. a.loadRepo()
  127. return a.Repo.MustOwner().Name
  128. }
  129. // ShortRepoUserName returns the name of the action repository owner
  130. // trimmed to max 20 chars.
  131. func (a *Action) ShortRepoUserName() string {
  132. return base.EllipsisString(a.GetRepoUserName(), 20)
  133. }
  134. // GetRepoName returns the name of the action repository.
  135. func (a *Action) GetRepoName() string {
  136. a.loadRepo()
  137. return a.Repo.Name
  138. }
  139. // ShortRepoName returns the name of the action repository
  140. // trimmed to max 33 chars.
  141. func (a *Action) ShortRepoName() string {
  142. return base.EllipsisString(a.GetRepoName(), 33)
  143. }
  144. // GetRepoPath returns the virtual path to the action repository.
  145. func (a *Action) GetRepoPath() string {
  146. return path.Join(a.GetRepoUserName(), a.GetRepoName())
  147. }
  148. // ShortRepoPath returns the virtual path to the action repository
  149. // trimmed to max 20 + 1 + 33 chars.
  150. func (a *Action) ShortRepoPath() string {
  151. return path.Join(a.ShortRepoUserName(), a.ShortRepoName())
  152. }
  153. // GetRepoLink returns relative link to action repository.
  154. func (a *Action) GetRepoLink() string {
  155. if len(setting.AppSubURL) > 0 {
  156. return path.Join(setting.AppSubURL, a.GetRepoPath())
  157. }
  158. return "/" + a.GetRepoPath()
  159. }
  160. // GetCommentLink returns link to action comment.
  161. func (a *Action) GetCommentLink() string {
  162. if a == nil {
  163. return "#"
  164. }
  165. if a.Comment == nil && a.CommentID != 0 {
  166. a.Comment, _ = GetCommentByID(a.CommentID)
  167. }
  168. if a.Comment != nil {
  169. return a.Comment.HTMLURL()
  170. }
  171. if len(a.GetIssueInfos()) == 0 {
  172. return "#"
  173. }
  174. //Return link to issue
  175. issueIDString := a.GetIssueInfos()[0]
  176. issueID, err := strconv.ParseInt(issueIDString, 10, 64)
  177. if err != nil {
  178. return "#"
  179. }
  180. issue, err := GetIssueByID(issueID)
  181. if err != nil {
  182. return "#"
  183. }
  184. return issue.HTMLURL()
  185. }
  186. // GetBranch returns the action's repository branch.
  187. func (a *Action) GetBranch() string {
  188. return a.RefName
  189. }
  190. // GetContent returns the action's content.
  191. func (a *Action) GetContent() string {
  192. return a.Content
  193. }
  194. // GetCreate returns the action creation time.
  195. func (a *Action) GetCreate() time.Time {
  196. return a.CreatedUnix.AsTime()
  197. }
  198. // GetIssueInfos returns a list of issues associated with
  199. // the action.
  200. func (a *Action) GetIssueInfos() []string {
  201. return strings.SplitN(a.Content, "|", 2)
  202. }
  203. // GetIssueTitle returns the title of first issue associated
  204. // with the action.
  205. func (a *Action) GetIssueTitle() string {
  206. index := com.StrTo(a.GetIssueInfos()[0]).MustInt64()
  207. issue, err := GetIssueByIndex(a.RepoID, index)
  208. if err != nil {
  209. log.Error(4, "GetIssueByIndex: %v", err)
  210. return "500 when get issue"
  211. }
  212. return issue.Title
  213. }
  214. // GetIssueContent returns the content of first issue associated with
  215. // this action.
  216. func (a *Action) GetIssueContent() string {
  217. index := com.StrTo(a.GetIssueInfos()[0]).MustInt64()
  218. issue, err := GetIssueByIndex(a.RepoID, index)
  219. if err != nil {
  220. log.Error(4, "GetIssueByIndex: %v", err)
  221. return "500 when get issue"
  222. }
  223. return issue.Content
  224. }
  225. func newRepoAction(e Engine, u *User, repo *Repository) (err error) {
  226. if err = notifyWatchers(e, &Action{
  227. ActUserID: u.ID,
  228. ActUser: u,
  229. OpType: ActionCreateRepo,
  230. RepoID: repo.ID,
  231. Repo: repo,
  232. IsPrivate: repo.IsPrivate,
  233. }); err != nil {
  234. return fmt.Errorf("notify watchers '%d/%d': %v", u.ID, repo.ID, err)
  235. }
  236. log.Trace("action.newRepoAction: %s/%s", u.Name, repo.Name)
  237. return err
  238. }
  239. // NewRepoAction adds new action for creating repository.
  240. func NewRepoAction(u *User, repo *Repository) (err error) {
  241. return newRepoAction(x, u, repo)
  242. }
  243. func renameRepoAction(e Engine, actUser *User, oldRepoName string, repo *Repository) (err error) {
  244. if err = notifyWatchers(e, &Action{
  245. ActUserID: actUser.ID,
  246. ActUser: actUser,
  247. OpType: ActionRenameRepo,
  248. RepoID: repo.ID,
  249. Repo: repo,
  250. IsPrivate: repo.IsPrivate,
  251. Content: oldRepoName,
  252. }); err != nil {
  253. return fmt.Errorf("notify watchers: %v", err)
  254. }
  255. log.Trace("action.renameRepoAction: %s/%s", actUser.Name, repo.Name)
  256. return nil
  257. }
  258. // RenameRepoAction adds new action for renaming a repository.
  259. func RenameRepoAction(actUser *User, oldRepoName string, repo *Repository) error {
  260. return renameRepoAction(x, actUser, oldRepoName, repo)
  261. }
  262. func issueIndexTrimRight(c rune) bool {
  263. return !unicode.IsDigit(c)
  264. }
  265. // PushCommit represents a commit in a push operation.
  266. type PushCommit struct {
  267. Sha1 string
  268. Message string
  269. AuthorEmail string
  270. AuthorName string
  271. CommitterEmail string
  272. CommitterName string
  273. Timestamp time.Time
  274. }
  275. // PushCommits represents list of commits in a push operation.
  276. type PushCommits struct {
  277. Len int
  278. Commits []*PushCommit
  279. CompareURL string
  280. avatars map[string]string
  281. }
  282. // NewPushCommits creates a new PushCommits object.
  283. func NewPushCommits() *PushCommits {
  284. return &PushCommits{
  285. avatars: make(map[string]string),
  286. }
  287. }
  288. // ToAPIPayloadCommits converts a PushCommits object to
  289. // api.PayloadCommit format.
  290. func (pc *PushCommits) ToAPIPayloadCommits(repoLink string) []*api.PayloadCommit {
  291. commits := make([]*api.PayloadCommit, len(pc.Commits))
  292. for i, commit := range pc.Commits {
  293. authorUsername := ""
  294. author, err := GetUserByEmail(commit.AuthorEmail)
  295. if err == nil {
  296. authorUsername = author.Name
  297. }
  298. committerUsername := ""
  299. committer, err := GetUserByEmail(commit.CommitterEmail)
  300. if err == nil {
  301. // TODO: check errors other than email not found.
  302. committerUsername = committer.Name
  303. }
  304. commits[i] = &api.PayloadCommit{
  305. ID: commit.Sha1,
  306. Message: commit.Message,
  307. URL: fmt.Sprintf("%s/commit/%s", repoLink, commit.Sha1),
  308. Author: &api.PayloadUser{
  309. Name: commit.AuthorName,
  310. Email: commit.AuthorEmail,
  311. UserName: authorUsername,
  312. },
  313. Committer: &api.PayloadUser{
  314. Name: commit.CommitterName,
  315. Email: commit.CommitterEmail,
  316. UserName: committerUsername,
  317. },
  318. Timestamp: commit.Timestamp,
  319. }
  320. }
  321. return commits
  322. }
  323. // AvatarLink tries to match user in database with e-mail
  324. // in order to show custom avatar, and falls back to general avatar link.
  325. func (pc *PushCommits) AvatarLink(email string) string {
  326. _, ok := pc.avatars[email]
  327. if !ok {
  328. u, err := GetUserByEmail(email)
  329. if err != nil {
  330. pc.avatars[email] = base.AvatarLink(email)
  331. if !IsErrUserNotExist(err) {
  332. log.Error(4, "GetUserByEmail: %v", err)
  333. }
  334. } else {
  335. pc.avatars[email] = u.RelAvatarLink()
  336. }
  337. }
  338. return pc.avatars[email]
  339. }
  340. // getIssueFromRef returns the issue referenced by a ref. Returns a nil *Issue
  341. // if the provided ref is misformatted or references a non-existent issue.
  342. func getIssueFromRef(repo *Repository, ref string) (*Issue, error) {
  343. ref = ref[strings.IndexByte(ref, ' ')+1:]
  344. ref = strings.TrimRightFunc(ref, issueIndexTrimRight)
  345. var refRepo *Repository
  346. poundIndex := strings.IndexByte(ref, '#')
  347. if poundIndex < 0 {
  348. return nil, nil
  349. } else if poundIndex == 0 {
  350. refRepo = repo
  351. } else {
  352. slashIndex := strings.IndexByte(ref, '/')
  353. if slashIndex < 0 || slashIndex >= poundIndex {
  354. return nil, nil
  355. }
  356. ownerName := ref[:slashIndex]
  357. repoName := ref[slashIndex+1 : poundIndex]
  358. var err error
  359. refRepo, err = GetRepositoryByOwnerAndName(ownerName, repoName)
  360. if err != nil {
  361. if IsErrRepoNotExist(err) {
  362. return nil, nil
  363. }
  364. return nil, err
  365. }
  366. }
  367. issueIndex, err := strconv.ParseInt(ref[poundIndex+1:], 10, 64)
  368. if err != nil {
  369. return nil, nil
  370. }
  371. issue, err := GetIssueByIndex(refRepo.ID, int64(issueIndex))
  372. if err != nil {
  373. if IsErrIssueNotExist(err) {
  374. return nil, nil
  375. }
  376. return nil, err
  377. }
  378. return issue, nil
  379. }
  380. // UpdateIssuesCommit checks if issues are manipulated by commit message.
  381. func UpdateIssuesCommit(doer *User, repo *Repository, commits []*PushCommit) error {
  382. // Commits are appended in the reverse order.
  383. for i := len(commits) - 1; i >= 0; i-- {
  384. c := commits[i]
  385. refMarked := make(map[int64]bool)
  386. for _, ref := range issueReferenceKeywordsPat.FindAllString(c.Message, -1) {
  387. issue, err := getIssueFromRef(repo, ref)
  388. if err != nil {
  389. return err
  390. }
  391. if issue == nil || refMarked[issue.ID] {
  392. continue
  393. }
  394. refMarked[issue.ID] = true
  395. message := fmt.Sprintf(`<a href="%s/commit/%s">%s</a>`, repo.Link(), c.Sha1, c.Message)
  396. if err = CreateRefComment(doer, repo, issue, message, c.Sha1); err != nil {
  397. return err
  398. }
  399. }
  400. refMarked = make(map[int64]bool)
  401. // FIXME: can merge this one and next one to a common function.
  402. for _, ref := range issueCloseKeywordsPat.FindAllString(c.Message, -1) {
  403. issue, err := getIssueFromRef(repo, ref)
  404. if err != nil {
  405. return err
  406. }
  407. if issue == nil || refMarked[issue.ID] {
  408. continue
  409. }
  410. refMarked[issue.ID] = true
  411. if issue.RepoID != repo.ID || issue.IsClosed {
  412. continue
  413. }
  414. if err = issue.ChangeStatus(doer, repo, true); err != nil {
  415. return err
  416. }
  417. }
  418. // It is conflict to have close and reopen at same time, so refsMarked doesn't need to reinit here.
  419. for _, ref := range issueReopenKeywordsPat.FindAllString(c.Message, -1) {
  420. issue, err := getIssueFromRef(repo, ref)
  421. if err != nil {
  422. return err
  423. }
  424. if issue == nil || refMarked[issue.ID] {
  425. continue
  426. }
  427. refMarked[issue.ID] = true
  428. if issue.RepoID != repo.ID || !issue.IsClosed {
  429. continue
  430. }
  431. if err = issue.ChangeStatus(doer, repo, false); err != nil {
  432. return err
  433. }
  434. }
  435. }
  436. return nil
  437. }
  438. // CommitRepoActionOptions represent options of a new commit action.
  439. type CommitRepoActionOptions struct {
  440. PusherName string
  441. RepoOwnerID int64
  442. RepoName string
  443. RefFullName string
  444. OldCommitID string
  445. NewCommitID string
  446. Commits *PushCommits
  447. }
  448. // CommitRepoAction adds new commit action to the repository, and prepare
  449. // corresponding webhooks.
  450. func CommitRepoAction(opts CommitRepoActionOptions) error {
  451. pusher, err := GetUserByName(opts.PusherName)
  452. if err != nil {
  453. return fmt.Errorf("GetUserByName [%s]: %v", opts.PusherName, err)
  454. }
  455. repo, err := GetRepositoryByName(opts.RepoOwnerID, opts.RepoName)
  456. if err != nil {
  457. return fmt.Errorf("GetRepositoryByName [owner_id: %d, name: %s]: %v", opts.RepoOwnerID, opts.RepoName, err)
  458. }
  459. refName := git.RefEndName(opts.RefFullName)
  460. if repo.IsBare && refName != repo.DefaultBranch {
  461. repo.DefaultBranch = refName
  462. }
  463. // Change repository bare status and update last updated time.
  464. repo.IsBare = repo.IsBare && opts.Commits.Len <= 0
  465. if err = UpdateRepository(repo, false); err != nil {
  466. return fmt.Errorf("UpdateRepository: %v", err)
  467. }
  468. isNewBranch := false
  469. opType := ActionCommitRepo
  470. // Check it's tag push or branch.
  471. if strings.HasPrefix(opts.RefFullName, git.TagPrefix) {
  472. opType = ActionPushTag
  473. if opts.NewCommitID == git.EmptySHA {
  474. opType = ActionDeleteTag
  475. }
  476. opts.Commits = &PushCommits{}
  477. } else if opts.NewCommitID == git.EmptySHA {
  478. opType = ActionDeleteBranch
  479. opts.Commits = &PushCommits{}
  480. } else {
  481. // if not the first commit, set the compare URL.
  482. if opts.OldCommitID == git.EmptySHA {
  483. isNewBranch = true
  484. } else {
  485. opts.Commits.CompareURL = repo.ComposeCompareURL(opts.OldCommitID, opts.NewCommitID)
  486. }
  487. if err = UpdateIssuesCommit(pusher, repo, opts.Commits.Commits); err != nil {
  488. log.Error(4, "updateIssuesCommit: %v", err)
  489. }
  490. }
  491. if len(opts.Commits.Commits) > setting.UI.FeedMaxCommitNum {
  492. opts.Commits.Commits = opts.Commits.Commits[:setting.UI.FeedMaxCommitNum]
  493. }
  494. data, err := json.Marshal(opts.Commits)
  495. if err != nil {
  496. return fmt.Errorf("Marshal: %v", err)
  497. }
  498. if err = NotifyWatchers(&Action{
  499. ActUserID: pusher.ID,
  500. ActUser: pusher,
  501. OpType: opType,
  502. Content: string(data),
  503. RepoID: repo.ID,
  504. Repo: repo,
  505. RefName: refName,
  506. IsPrivate: repo.IsPrivate,
  507. }); err != nil {
  508. return fmt.Errorf("NotifyWatchers: %v", err)
  509. }
  510. defer func() {
  511. go HookQueue.Add(repo.ID)
  512. }()
  513. apiPusher := pusher.APIFormat()
  514. apiRepo := repo.APIFormat(AccessModeNone)
  515. var shaSum string
  516. var isHookEventPush = false
  517. switch opType {
  518. case ActionCommitRepo: // Push
  519. isHookEventPush = true
  520. if isNewBranch {
  521. gitRepo, err := git.OpenRepository(repo.RepoPath())
  522. if err != nil {
  523. log.Error(4, "OpenRepository[%s]: %v", repo.RepoPath(), err)
  524. }
  525. shaSum, err = gitRepo.GetBranchCommitID(refName)
  526. if err != nil {
  527. log.Error(4, "GetBranchCommitID[%s]: %v", opts.RefFullName, err)
  528. }
  529. if err = PrepareWebhooks(repo, HookEventCreate, &api.CreatePayload{
  530. Ref: refName,
  531. Sha: shaSum,
  532. RefType: "branch",
  533. Repo: apiRepo,
  534. Sender: apiPusher,
  535. }); err != nil {
  536. return fmt.Errorf("PrepareWebhooks: %v", err)
  537. }
  538. }
  539. case ActionDeleteBranch: // Delete Branch
  540. isHookEventPush = true
  541. if err = PrepareWebhooks(repo, HookEventDelete, &api.DeletePayload{
  542. Ref: refName,
  543. RefType: "branch",
  544. PusherType: api.PusherTypeUser,
  545. Repo: apiRepo,
  546. Sender: apiPusher,
  547. }); err != nil {
  548. return fmt.Errorf("PrepareWebhooks.(delete branch): %v", err)
  549. }
  550. case ActionPushTag: // Create
  551. isHookEventPush = true
  552. gitRepo, err := git.OpenRepository(repo.RepoPath())
  553. if err != nil {
  554. log.Error(4, "OpenRepository[%s]: %v", repo.RepoPath(), err)
  555. }
  556. shaSum, err = gitRepo.GetTagCommitID(refName)
  557. if err != nil {
  558. log.Error(4, "GetTagCommitID[%s]: %v", opts.RefFullName, err)
  559. }
  560. if err = PrepareWebhooks(repo, HookEventCreate, &api.CreatePayload{
  561. Ref: refName,
  562. Sha: shaSum,
  563. RefType: "tag",
  564. Repo: apiRepo,
  565. Sender: apiPusher,
  566. }); err != nil {
  567. return fmt.Errorf("PrepareWebhooks: %v", err)
  568. }
  569. case ActionDeleteTag: // Delete Tag
  570. isHookEventPush = true
  571. if err = PrepareWebhooks(repo, HookEventDelete, &api.DeletePayload{
  572. Ref: refName,
  573. RefType: "tag",
  574. PusherType: api.PusherTypeUser,
  575. Repo: apiRepo,
  576. Sender: apiPusher,
  577. }); err != nil {
  578. return fmt.Errorf("PrepareWebhooks.(delete tag): %v", err)
  579. }
  580. }
  581. if isHookEventPush {
  582. if err = PrepareWebhooks(repo, HookEventPush, &api.PushPayload{
  583. Ref: opts.RefFullName,
  584. Before: opts.OldCommitID,
  585. After: opts.NewCommitID,
  586. CompareURL: setting.AppURL + opts.Commits.CompareURL,
  587. Commits: opts.Commits.ToAPIPayloadCommits(repo.HTMLURL()),
  588. Repo: apiRepo,
  589. Pusher: apiPusher,
  590. Sender: apiPusher,
  591. }); err != nil {
  592. return fmt.Errorf("PrepareWebhooks: %v", err)
  593. }
  594. }
  595. return nil
  596. }
  597. func transferRepoAction(e Engine, doer, oldOwner *User, repo *Repository) (err error) {
  598. if err = notifyWatchers(e, &Action{
  599. ActUserID: doer.ID,
  600. ActUser: doer,
  601. OpType: ActionTransferRepo,
  602. RepoID: repo.ID,
  603. Repo: repo,
  604. IsPrivate: repo.IsPrivate,
  605. Content: path.Join(oldOwner.Name, repo.Name),
  606. }); err != nil {
  607. return fmt.Errorf("notifyWatchers: %v", err)
  608. }
  609. // Remove watch for organization.
  610. if oldOwner.IsOrganization() {
  611. if err = watchRepo(e, oldOwner.ID, repo.ID, false); err != nil {
  612. return fmt.Errorf("watchRepo [false]: %v", err)
  613. }
  614. }
  615. return nil
  616. }
  617. // TransferRepoAction adds new action for transferring repository,
  618. // the Owner field of repository is assumed to be new owner.
  619. func TransferRepoAction(doer, oldOwner *User, repo *Repository) error {
  620. return transferRepoAction(x, doer, oldOwner, repo)
  621. }
  622. func mergePullRequestAction(e Engine, doer *User, repo *Repository, issue *Issue) error {
  623. return notifyWatchers(e, &Action{
  624. ActUserID: doer.ID,
  625. ActUser: doer,
  626. OpType: ActionMergePullRequest,
  627. Content: fmt.Sprintf("%d|%s", issue.Index, issue.Title),
  628. RepoID: repo.ID,
  629. Repo: repo,
  630. IsPrivate: repo.IsPrivate,
  631. })
  632. }
  633. // MergePullRequestAction adds new action for merging pull request.
  634. func MergePullRequestAction(actUser *User, repo *Repository, pull *Issue) error {
  635. return mergePullRequestAction(x, actUser, repo, pull)
  636. }
  637. // GetFeedsOptions options for retrieving feeds
  638. type GetFeedsOptions struct {
  639. RequestedUser *User
  640. RequestingUserID int64
  641. IncludePrivate bool // include private actions
  642. OnlyPerformedBy bool // only actions performed by requested user
  643. IncludeDeleted bool // include deleted actions
  644. }
  645. // GetFeeds returns actions according to the provided options
  646. func GetFeeds(opts GetFeedsOptions) ([]*Action, error) {
  647. cond := builder.NewCond()
  648. var repoIDs []int64
  649. if opts.RequestedUser.IsOrganization() {
  650. env, err := opts.RequestedUser.AccessibleReposEnv(opts.RequestingUserID)
  651. if err != nil {
  652. return nil, fmt.Errorf("AccessibleReposEnv: %v", err)
  653. }
  654. if repoIDs, err = env.RepoIDs(1, opts.RequestedUser.NumRepos); err != nil {
  655. return nil, fmt.Errorf("GetUserRepositories: %v", err)
  656. }
  657. cond = cond.And(builder.In("repo_id", repoIDs))
  658. }
  659. cond = cond.And(builder.Eq{"user_id": opts.RequestedUser.ID})
  660. if opts.OnlyPerformedBy {
  661. cond = cond.And(builder.Eq{"act_user_id": opts.RequestedUser.ID})
  662. }
  663. if !opts.IncludePrivate {
  664. cond = cond.And(builder.Eq{"is_private": false})
  665. }
  666. if !opts.IncludeDeleted {
  667. cond = cond.And(builder.Eq{"is_deleted": false})
  668. }
  669. actions := make([]*Action, 0, 20)
  670. if err := x.Limit(20).Desc("id").Where(cond).Find(&actions); err != nil {
  671. return nil, fmt.Errorf("Find: %v", err)
  672. }
  673. if err := ActionList(actions).LoadAttributes(); err != nil {
  674. return nil, fmt.Errorf("LoadAttributes: %v", err)
  675. }
  676. return actions, nil
  677. }