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