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.

action.go 21 kB

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