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