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