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