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