You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

action.go 27KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010
  1. // Copyright 2014 The Gogs Authors. All rights reserved.
  2. // Copyright 2019 The Gitea Authors. All rights reserved.
  3. // Use of this source code is governed by a MIT-style
  4. // license that can be found in the LICENSE file.
  5. package models
  6. import (
  7. "encoding/json"
  8. "fmt"
  9. "html"
  10. "path"
  11. "regexp"
  12. "strconv"
  13. "strings"
  14. "time"
  15. "unicode"
  16. "code.gitea.io/gitea/modules/base"
  17. "code.gitea.io/gitea/modules/git"
  18. "code.gitea.io/gitea/modules/log"
  19. "code.gitea.io/gitea/modules/setting"
  20. api "code.gitea.io/gitea/modules/structs"
  21. "code.gitea.io/gitea/modules/util"
  22. "github.com/Unknwon/com"
  23. "xorm.io/builder"
  24. )
  25. // ActionType represents the type of an action.
  26. type ActionType int
  27. // Possible action types.
  28. const (
  29. ActionCreateRepo ActionType = iota + 1 // 1
  30. ActionRenameRepo // 2
  31. ActionStarRepo // 3
  32. ActionWatchRepo // 4
  33. ActionCommitRepo // 5
  34. ActionCreateIssue // 6
  35. ActionCreatePullRequest // 7
  36. ActionTransferRepo // 8
  37. ActionPushTag // 9
  38. ActionCommentIssue // 10
  39. ActionMergePullRequest // 11
  40. ActionCloseIssue // 12
  41. ActionReopenIssue // 13
  42. ActionClosePullRequest // 14
  43. ActionReopenPullRequest // 15
  44. ActionDeleteTag // 16
  45. ActionDeleteBranch // 17
  46. ActionMirrorSyncPush // 18
  47. ActionMirrorSyncCreate // 19
  48. ActionMirrorSyncDelete // 20
  49. )
  50. var (
  51. // Same as GitHub. See
  52. // https://help.github.com/articles/closing-issues-via-commit-messages
  53. issueCloseKeywords = []string{"close", "closes", "closed", "fix", "fixes", "fixed", "resolve", "resolves", "resolved"}
  54. issueReopenKeywords = []string{"reopen", "reopens", "reopened"}
  55. issueCloseKeywordsPat, issueReopenKeywordsPat *regexp.Regexp
  56. issueReferenceKeywordsPat *regexp.Regexp
  57. )
  58. const issueRefRegexpStr = `(?:([0-9a-zA-Z-_\.]+)/([0-9a-zA-Z-_\.]+))?(#[0-9]+)+`
  59. const issueRefRegexpStrNoKeyword = `(?:\s|^|\(|\[)(?:([0-9a-zA-Z-_\.]+)/([0-9a-zA-Z-_\.]+))?(#[0-9]+)(?:\s|$|\)|\]|:|\.(\s|$))`
  60. func assembleKeywordsPattern(words []string) string {
  61. return fmt.Sprintf(`(?i)(?:%s)(?::?) %s`, strings.Join(words, "|"), issueRefRegexpStr)
  62. }
  63. func init() {
  64. issueCloseKeywordsPat = regexp.MustCompile(assembleKeywordsPattern(issueCloseKeywords))
  65. issueReopenKeywordsPat = regexp.MustCompile(assembleKeywordsPattern(issueReopenKeywords))
  66. issueReferenceKeywordsPat = regexp.MustCompile(issueRefRegexpStrNoKeyword)
  67. }
  68. // Action represents user operation type and other information to
  69. // repository. It implemented interface base.Actioner so that can be
  70. // used in template render.
  71. type Action struct {
  72. ID int64 `xorm:"pk autoincr"`
  73. UserID int64 `xorm:"INDEX"` // Receiver user id.
  74. OpType ActionType
  75. ActUserID int64 `xorm:"INDEX"` // Action user id.
  76. ActUser *User `xorm:"-"`
  77. RepoID int64 `xorm:"INDEX"`
  78. Repo *Repository `xorm:"-"`
  79. CommentID int64 `xorm:"INDEX"`
  80. Comment *Comment `xorm:"-"`
  81. IsDeleted bool `xorm:"INDEX NOT NULL DEFAULT false"`
  82. RefName string
  83. IsPrivate bool `xorm:"INDEX NOT NULL DEFAULT false"`
  84. Content string `xorm:"TEXT"`
  85. CreatedUnix util.TimeStamp `xorm:"INDEX created"`
  86. }
  87. // GetOpType gets the ActionType of this action.
  88. func (a *Action) GetOpType() ActionType {
  89. return 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("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("GetRepositoryByID(%d): %v", a.RepoID, err)
  113. }
  114. }
  115. // GetActFullName gets the action's user full name.
  116. func (a *Action) GetActFullName() string {
  117. a.loadActUser()
  118. return a.ActUser.FullName
  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. // GetDisplayName gets the action's display name based on DEFAULT_SHOW_FULL_NAME
  131. func (a *Action) GetDisplayName() string {
  132. if setting.UI.DefaultShowFullName {
  133. return a.GetActFullName()
  134. }
  135. return a.ShortActUserName()
  136. }
  137. // GetDisplayNameTitle gets the action's display name used for the title (tooltip) based on DEFAULT_SHOW_FULL_NAME
  138. func (a *Action) GetDisplayNameTitle() string {
  139. if setting.UI.DefaultShowFullName {
  140. return a.ShortActUserName()
  141. }
  142. return a.GetActFullName()
  143. }
  144. // GetActAvatar the action's user's avatar link
  145. func (a *Action) GetActAvatar() string {
  146. a.loadActUser()
  147. return a.ActUser.RelAvatarLink()
  148. }
  149. // GetRepoUserName returns the name of the action repository owner.
  150. func (a *Action) GetRepoUserName() string {
  151. a.loadRepo()
  152. return a.Repo.MustOwner().Name
  153. }
  154. // ShortRepoUserName returns the name of the action repository owner
  155. // trimmed to max 20 chars.
  156. func (a *Action) ShortRepoUserName() string {
  157. return base.EllipsisString(a.GetRepoUserName(), 20)
  158. }
  159. // GetRepoName returns the name of the action repository.
  160. func (a *Action) GetRepoName() string {
  161. a.loadRepo()
  162. return a.Repo.Name
  163. }
  164. // ShortRepoName returns the name of the action repository
  165. // trimmed to max 33 chars.
  166. func (a *Action) ShortRepoName() string {
  167. return base.EllipsisString(a.GetRepoName(), 33)
  168. }
  169. // GetRepoPath returns the virtual path to the action repository.
  170. func (a *Action) GetRepoPath() string {
  171. return path.Join(a.GetRepoUserName(), a.GetRepoName())
  172. }
  173. // ShortRepoPath returns the virtual path to the action repository
  174. // trimmed to max 20 + 1 + 33 chars.
  175. func (a *Action) ShortRepoPath() string {
  176. return path.Join(a.ShortRepoUserName(), a.ShortRepoName())
  177. }
  178. // GetRepoLink returns relative link to action repository.
  179. func (a *Action) GetRepoLink() string {
  180. if len(setting.AppSubURL) > 0 {
  181. return path.Join(setting.AppSubURL, a.GetRepoPath())
  182. }
  183. return "/" + a.GetRepoPath()
  184. }
  185. // GetRepositoryFromMatch returns a *Repository from a username and repo strings
  186. func GetRepositoryFromMatch(ownerName string, repoName string) (*Repository, error) {
  187. var err error
  188. refRepo, err := GetRepositoryByOwnerAndName(ownerName, repoName)
  189. if err != nil {
  190. if IsErrRepoNotExist(err) {
  191. log.Warn("Repository referenced in commit but does not exist: %v", err)
  192. return nil, err
  193. }
  194. log.Error("GetRepositoryByOwnerAndName: %v", err)
  195. return nil, err
  196. }
  197. return refRepo, nil
  198. }
  199. // GetCommentLink returns link to action comment.
  200. func (a *Action) GetCommentLink() string {
  201. return a.getCommentLink(x)
  202. }
  203. func (a *Action) getCommentLink(e Engine) string {
  204. if a == nil {
  205. return "#"
  206. }
  207. if a.Comment == nil && a.CommentID != 0 {
  208. a.Comment, _ = GetCommentByID(a.CommentID)
  209. }
  210. if a.Comment != nil {
  211. return a.Comment.HTMLURL()
  212. }
  213. if len(a.GetIssueInfos()) == 0 {
  214. return "#"
  215. }
  216. //Return link to issue
  217. issueIDString := a.GetIssueInfos()[0]
  218. issueID, err := strconv.ParseInt(issueIDString, 10, 64)
  219. if err != nil {
  220. return "#"
  221. }
  222. issue, err := getIssueByID(e, issueID)
  223. if err != nil {
  224. return "#"
  225. }
  226. if err = issue.loadRepo(e); err != nil {
  227. return "#"
  228. }
  229. return issue.HTMLURL()
  230. }
  231. // GetBranch returns the action's repository branch.
  232. func (a *Action) GetBranch() string {
  233. return a.RefName
  234. }
  235. // GetContent returns the action's content.
  236. func (a *Action) GetContent() string {
  237. return a.Content
  238. }
  239. // GetCreate returns the action creation time.
  240. func (a *Action) GetCreate() time.Time {
  241. return a.CreatedUnix.AsTime()
  242. }
  243. // GetIssueInfos returns a list of issues associated with
  244. // the action.
  245. func (a *Action) GetIssueInfos() []string {
  246. return strings.SplitN(a.Content, "|", 2)
  247. }
  248. // GetIssueTitle returns the title of first issue associated
  249. // with the action.
  250. func (a *Action) GetIssueTitle() string {
  251. index := com.StrTo(a.GetIssueInfos()[0]).MustInt64()
  252. issue, err := GetIssueByIndex(a.RepoID, index)
  253. if err != nil {
  254. log.Error("GetIssueByIndex: %v", err)
  255. return "500 when get issue"
  256. }
  257. return issue.Title
  258. }
  259. // GetIssueContent returns the content of first issue associated with
  260. // this action.
  261. func (a *Action) GetIssueContent() string {
  262. index := com.StrTo(a.GetIssueInfos()[0]).MustInt64()
  263. issue, err := GetIssueByIndex(a.RepoID, index)
  264. if err != nil {
  265. log.Error("GetIssueByIndex: %v", err)
  266. return "500 when get issue"
  267. }
  268. return issue.Content
  269. }
  270. func newRepoAction(e Engine, u *User, repo *Repository) (err error) {
  271. if err = notifyWatchers(e, &Action{
  272. ActUserID: u.ID,
  273. ActUser: u,
  274. OpType: ActionCreateRepo,
  275. RepoID: repo.ID,
  276. Repo: repo,
  277. IsPrivate: repo.IsPrivate,
  278. }); err != nil {
  279. return fmt.Errorf("notify watchers '%d/%d': %v", u.ID, repo.ID, err)
  280. }
  281. log.Trace("action.newRepoAction: %s/%s", u.Name, repo.Name)
  282. return err
  283. }
  284. // NewRepoAction adds new action for creating repository.
  285. func NewRepoAction(u *User, repo *Repository) (err error) {
  286. return newRepoAction(x, u, repo)
  287. }
  288. func renameRepoAction(e Engine, actUser *User, oldRepoName string, repo *Repository) (err error) {
  289. if err = notifyWatchers(e, &Action{
  290. ActUserID: actUser.ID,
  291. ActUser: actUser,
  292. OpType: ActionRenameRepo,
  293. RepoID: repo.ID,
  294. Repo: repo,
  295. IsPrivate: repo.IsPrivate,
  296. Content: oldRepoName,
  297. }); err != nil {
  298. return fmt.Errorf("notify watchers: %v", err)
  299. }
  300. log.Trace("action.renameRepoAction: %s/%s", actUser.Name, repo.Name)
  301. return nil
  302. }
  303. // RenameRepoAction adds new action for renaming a repository.
  304. func RenameRepoAction(actUser *User, oldRepoName string, repo *Repository) error {
  305. return renameRepoAction(x, actUser, oldRepoName, repo)
  306. }
  307. func issueIndexTrimRight(c rune) bool {
  308. return !unicode.IsDigit(c)
  309. }
  310. // PushCommit represents a commit in a push operation.
  311. type PushCommit struct {
  312. Sha1 string
  313. Message string
  314. AuthorEmail string
  315. AuthorName string
  316. CommitterEmail string
  317. CommitterName string
  318. Timestamp time.Time
  319. }
  320. // PushCommits represents list of commits in a push operation.
  321. type PushCommits struct {
  322. Len int
  323. Commits []*PushCommit
  324. CompareURL string
  325. avatars map[string]string
  326. emailUsers map[string]*User
  327. }
  328. // NewPushCommits creates a new PushCommits object.
  329. func NewPushCommits() *PushCommits {
  330. return &PushCommits{
  331. avatars: make(map[string]string),
  332. emailUsers: make(map[string]*User),
  333. }
  334. }
  335. // ToAPIPayloadCommits converts a PushCommits object to
  336. // api.PayloadCommit format.
  337. func (pc *PushCommits) ToAPIPayloadCommits(repoLink string) []*api.PayloadCommit {
  338. commits := make([]*api.PayloadCommit, len(pc.Commits))
  339. if pc.emailUsers == nil {
  340. pc.emailUsers = make(map[string]*User)
  341. }
  342. var err error
  343. for i, commit := range pc.Commits {
  344. authorUsername := ""
  345. author, ok := pc.emailUsers[commit.AuthorEmail]
  346. if !ok {
  347. author, err = GetUserByEmail(commit.AuthorEmail)
  348. if err == nil {
  349. authorUsername = author.Name
  350. pc.emailUsers[commit.AuthorEmail] = author
  351. }
  352. } else {
  353. authorUsername = author.Name
  354. }
  355. committerUsername := ""
  356. committer, ok := pc.emailUsers[commit.CommitterEmail]
  357. if !ok {
  358. committer, err = GetUserByEmail(commit.CommitterEmail)
  359. if err == nil {
  360. // TODO: check errors other than email not found.
  361. committerUsername = committer.Name
  362. pc.emailUsers[commit.CommitterEmail] = committer
  363. }
  364. } else {
  365. committerUsername = committer.Name
  366. }
  367. commits[i] = &api.PayloadCommit{
  368. ID: commit.Sha1,
  369. Message: commit.Message,
  370. URL: fmt.Sprintf("%s/commit/%s", repoLink, commit.Sha1),
  371. Author: &api.PayloadUser{
  372. Name: commit.AuthorName,
  373. Email: commit.AuthorEmail,
  374. UserName: authorUsername,
  375. },
  376. Committer: &api.PayloadUser{
  377. Name: commit.CommitterName,
  378. Email: commit.CommitterEmail,
  379. UserName: committerUsername,
  380. },
  381. Timestamp: commit.Timestamp,
  382. }
  383. }
  384. return commits
  385. }
  386. // AvatarLink tries to match user in database with e-mail
  387. // in order to show custom avatar, and falls back to general avatar link.
  388. func (pc *PushCommits) AvatarLink(email string) string {
  389. avatar, ok := pc.avatars[email]
  390. if ok {
  391. return avatar
  392. }
  393. u, ok := pc.emailUsers[email]
  394. if !ok {
  395. var err error
  396. u, err = GetUserByEmail(email)
  397. if err != nil {
  398. pc.avatars[email] = base.AvatarLink(email)
  399. if !IsErrUserNotExist(err) {
  400. log.Error("GetUserByEmail: %v", err)
  401. return ""
  402. }
  403. } else {
  404. pc.emailUsers[email] = u
  405. }
  406. }
  407. if u != nil {
  408. pc.avatars[email] = u.RelAvatarLink()
  409. }
  410. return pc.avatars[email]
  411. }
  412. // getIssueFromRef returns the issue referenced by a ref. Returns a nil *Issue
  413. // if the provided ref is misformatted or references a non-existent issue.
  414. func getIssueFromRef(repo *Repository, ref string) (*Issue, error) {
  415. ref = ref[strings.IndexByte(ref, ' ')+1:]
  416. ref = strings.TrimRightFunc(ref, issueIndexTrimRight)
  417. var refRepo *Repository
  418. poundIndex := strings.IndexByte(ref, '#')
  419. if poundIndex < 0 {
  420. return nil, nil
  421. } else if poundIndex == 0 {
  422. refRepo = repo
  423. } else {
  424. slashIndex := strings.IndexByte(ref, '/')
  425. if slashIndex < 0 || slashIndex >= poundIndex {
  426. return nil, nil
  427. }
  428. ownerName := ref[:slashIndex]
  429. repoName := ref[slashIndex+1 : poundIndex]
  430. var err error
  431. refRepo, err = GetRepositoryByOwnerAndName(ownerName, repoName)
  432. if err != nil {
  433. if IsErrRepoNotExist(err) {
  434. return nil, nil
  435. }
  436. return nil, err
  437. }
  438. }
  439. issueIndex, err := strconv.ParseInt(ref[poundIndex+1:], 10, 64)
  440. if err != nil {
  441. return nil, nil
  442. }
  443. issue, err := GetIssueByIndex(refRepo.ID, int64(issueIndex))
  444. if err != nil {
  445. if IsErrIssueNotExist(err) {
  446. return nil, nil
  447. }
  448. return nil, err
  449. }
  450. return issue, nil
  451. }
  452. func changeIssueStatus(repo *Repository, doer *User, ref string, refMarked map[int64]bool, status bool) error {
  453. issue, err := getIssueFromRef(repo, ref)
  454. if err != nil {
  455. return err
  456. }
  457. if issue == nil || refMarked[issue.ID] {
  458. return nil
  459. }
  460. refMarked[issue.ID] = true
  461. if issue.RepoID != repo.ID || issue.IsClosed == status {
  462. return nil
  463. }
  464. stopTimerIfAvailable := func(doer *User, issue *Issue) error {
  465. if StopwatchExists(doer.ID, issue.ID) {
  466. if err := CreateOrStopIssueStopwatch(doer, issue); err != nil {
  467. return err
  468. }
  469. }
  470. return nil
  471. }
  472. issue.Repo = repo
  473. if err = issue.ChangeStatus(doer, status); err != nil {
  474. // Don't return an error when dependencies are open as this would let the push fail
  475. if IsErrDependenciesLeft(err) {
  476. return stopTimerIfAvailable(doer, issue)
  477. }
  478. return err
  479. }
  480. return stopTimerIfAvailable(doer, issue)
  481. }
  482. // UpdateIssuesCommit checks if issues are manipulated by commit message.
  483. func UpdateIssuesCommit(doer *User, repo *Repository, commits []*PushCommit, branchName string) error {
  484. // Commits are appended in the reverse order.
  485. for i := len(commits) - 1; i >= 0; i-- {
  486. c := commits[i]
  487. refMarked := make(map[int64]bool)
  488. var refRepo *Repository
  489. var err error
  490. for _, m := range issueReferenceKeywordsPat.FindAllStringSubmatch(c.Message, -1) {
  491. if len(m[3]) == 0 {
  492. continue
  493. }
  494. ref := m[3]
  495. // issue is from another repo
  496. if len(m[1]) > 0 && len(m[2]) > 0 {
  497. refRepo, err = GetRepositoryFromMatch(string(m[1]), string(m[2]))
  498. if err != nil {
  499. continue
  500. }
  501. } else {
  502. refRepo = repo
  503. }
  504. issue, err := getIssueFromRef(refRepo, ref)
  505. if err != nil {
  506. return err
  507. }
  508. if issue == nil || refMarked[issue.ID] {
  509. continue
  510. }
  511. refMarked[issue.ID] = true
  512. message := fmt.Sprintf(`<a href="%s/commit/%s">%s</a>`, repo.Link(), c.Sha1, html.EscapeString(c.Message))
  513. if err = CreateRefComment(doer, refRepo, issue, message, c.Sha1); err != nil {
  514. return err
  515. }
  516. }
  517. // Change issue status only if the commit has been pushed to the default branch.
  518. // and if the repo is configured to allow only that
  519. if repo.DefaultBranch != branchName && !repo.CloseIssuesViaCommitInAnyBranch {
  520. continue
  521. }
  522. refMarked = make(map[int64]bool)
  523. for _, m := range issueCloseKeywordsPat.FindAllStringSubmatch(c.Message, -1) {
  524. if len(m[3]) == 0 {
  525. continue
  526. }
  527. ref := m[3]
  528. // issue is from another repo
  529. if len(m[1]) > 0 && len(m[2]) > 0 {
  530. refRepo, err = GetRepositoryFromMatch(string(m[1]), string(m[2]))
  531. if err != nil {
  532. continue
  533. }
  534. } else {
  535. refRepo = repo
  536. }
  537. perm, err := GetUserRepoPermission(refRepo, doer)
  538. if err != nil {
  539. return err
  540. }
  541. // only close issues in another repo if user has push access
  542. if perm.CanWrite(UnitTypeCode) {
  543. if err := changeIssueStatus(refRepo, doer, ref, refMarked, true); err != nil {
  544. return err
  545. }
  546. }
  547. }
  548. // It is conflict to have close and reopen at same time, so refsMarked doesn't need to reinit here.
  549. for _, m := range issueReopenKeywordsPat.FindAllStringSubmatch(c.Message, -1) {
  550. if len(m[3]) == 0 {
  551. continue
  552. }
  553. ref := m[3]
  554. // issue is from another repo
  555. if len(m[1]) > 0 && len(m[2]) > 0 {
  556. refRepo, err = GetRepositoryFromMatch(string(m[1]), string(m[2]))
  557. if err != nil {
  558. continue
  559. }
  560. } else {
  561. refRepo = repo
  562. }
  563. perm, err := GetUserRepoPermission(refRepo, doer)
  564. if err != nil {
  565. return err
  566. }
  567. // only reopen issues in another repo if user has push access
  568. if perm.CanWrite(UnitTypeCode) {
  569. if err := changeIssueStatus(refRepo, doer, ref, refMarked, false); err != nil {
  570. return err
  571. }
  572. }
  573. }
  574. }
  575. return nil
  576. }
  577. // CommitRepoActionOptions represent options of a new commit action.
  578. type CommitRepoActionOptions struct {
  579. PusherName string
  580. RepoOwnerID int64
  581. RepoName string
  582. RefFullName string
  583. OldCommitID string
  584. NewCommitID string
  585. Commits *PushCommits
  586. }
  587. // CommitRepoAction adds new commit action to the repository, and prepare
  588. // corresponding webhooks.
  589. func CommitRepoAction(opts CommitRepoActionOptions) error {
  590. pusher, err := GetUserByName(opts.PusherName)
  591. if err != nil {
  592. return fmt.Errorf("GetUserByName [%s]: %v", opts.PusherName, err)
  593. }
  594. repo, err := GetRepositoryByName(opts.RepoOwnerID, opts.RepoName)
  595. if err != nil {
  596. return fmt.Errorf("GetRepositoryByName [owner_id: %d, name: %s]: %v", opts.RepoOwnerID, opts.RepoName, err)
  597. }
  598. refName := git.RefEndName(opts.RefFullName)
  599. // Change default branch and empty status only if pushed ref is non-empty branch.
  600. if repo.IsEmpty && opts.NewCommitID != git.EmptySHA && strings.HasPrefix(opts.RefFullName, git.BranchPrefix) {
  601. repo.DefaultBranch = refName
  602. repo.IsEmpty = false
  603. }
  604. // Change repository empty status and update last updated time.
  605. if err = UpdateRepository(repo, false); err != nil {
  606. return fmt.Errorf("UpdateRepository: %v", err)
  607. }
  608. isNewBranch := false
  609. opType := ActionCommitRepo
  610. // Check it's tag push or branch.
  611. if strings.HasPrefix(opts.RefFullName, git.TagPrefix) {
  612. opType = ActionPushTag
  613. if opts.NewCommitID == git.EmptySHA {
  614. opType = ActionDeleteTag
  615. }
  616. opts.Commits = &PushCommits{}
  617. } else if opts.NewCommitID == git.EmptySHA {
  618. opType = ActionDeleteBranch
  619. opts.Commits = &PushCommits{}
  620. } else {
  621. // if not the first commit, set the compare URL.
  622. if opts.OldCommitID == git.EmptySHA {
  623. isNewBranch = true
  624. } else {
  625. opts.Commits.CompareURL = repo.ComposeCompareURL(opts.OldCommitID, opts.NewCommitID)
  626. }
  627. if err = UpdateIssuesCommit(pusher, repo, opts.Commits.Commits, refName); err != nil {
  628. log.Error("updateIssuesCommit: %v", err)
  629. }
  630. }
  631. if len(opts.Commits.Commits) > setting.UI.FeedMaxCommitNum {
  632. opts.Commits.Commits = opts.Commits.Commits[:setting.UI.FeedMaxCommitNum]
  633. }
  634. data, err := json.Marshal(opts.Commits)
  635. if err != nil {
  636. return fmt.Errorf("Marshal: %v", err)
  637. }
  638. if err = NotifyWatchers(&Action{
  639. ActUserID: pusher.ID,
  640. ActUser: pusher,
  641. OpType: opType,
  642. Content: string(data),
  643. RepoID: repo.ID,
  644. Repo: repo,
  645. RefName: refName,
  646. IsPrivate: repo.IsPrivate,
  647. }); err != nil {
  648. return fmt.Errorf("NotifyWatchers: %v", err)
  649. }
  650. defer func() {
  651. go HookQueue.Add(repo.ID)
  652. }()
  653. apiPusher := pusher.APIFormat()
  654. apiRepo := repo.APIFormat(AccessModeNone)
  655. var shaSum string
  656. var isHookEventPush = false
  657. switch opType {
  658. case ActionCommitRepo: // Push
  659. isHookEventPush = true
  660. if isNewBranch {
  661. gitRepo, err := git.OpenRepository(repo.RepoPath())
  662. if err != nil {
  663. log.Error("OpenRepository[%s]: %v", repo.RepoPath(), err)
  664. }
  665. shaSum, err = gitRepo.GetBranchCommitID(refName)
  666. if err != nil {
  667. log.Error("GetBranchCommitID[%s]: %v", opts.RefFullName, err)
  668. }
  669. gitRepo.Close()
  670. if err = PrepareWebhooks(repo, HookEventCreate, &api.CreatePayload{
  671. Ref: refName,
  672. Sha: shaSum,
  673. RefType: "branch",
  674. Repo: apiRepo,
  675. Sender: apiPusher,
  676. }); err != nil {
  677. return fmt.Errorf("PrepareWebhooks: %v", err)
  678. }
  679. }
  680. case ActionDeleteBranch: // Delete Branch
  681. isHookEventPush = true
  682. if err = PrepareWebhooks(repo, HookEventDelete, &api.DeletePayload{
  683. Ref: refName,
  684. RefType: "branch",
  685. PusherType: api.PusherTypeUser,
  686. Repo: apiRepo,
  687. Sender: apiPusher,
  688. }); err != nil {
  689. return fmt.Errorf("PrepareWebhooks.(delete branch): %v", err)
  690. }
  691. case ActionPushTag: // Create
  692. isHookEventPush = true
  693. gitRepo, err := git.OpenRepository(repo.RepoPath())
  694. if err != nil {
  695. log.Error("OpenRepository[%s]: %v", repo.RepoPath(), err)
  696. }
  697. shaSum, err = gitRepo.GetTagCommitID(refName)
  698. if err != nil {
  699. log.Error("GetTagCommitID[%s]: %v", opts.RefFullName, err)
  700. }
  701. gitRepo.Close()
  702. if err = PrepareWebhooks(repo, HookEventCreate, &api.CreatePayload{
  703. Ref: refName,
  704. Sha: shaSum,
  705. RefType: "tag",
  706. Repo: apiRepo,
  707. Sender: apiPusher,
  708. }); err != nil {
  709. return fmt.Errorf("PrepareWebhooks: %v", err)
  710. }
  711. case ActionDeleteTag: // Delete Tag
  712. isHookEventPush = true
  713. if err = PrepareWebhooks(repo, HookEventDelete, &api.DeletePayload{
  714. Ref: refName,
  715. RefType: "tag",
  716. PusherType: api.PusherTypeUser,
  717. Repo: apiRepo,
  718. Sender: apiPusher,
  719. }); err != nil {
  720. return fmt.Errorf("PrepareWebhooks.(delete tag): %v", err)
  721. }
  722. }
  723. if isHookEventPush {
  724. if err = PrepareWebhooks(repo, HookEventPush, &api.PushPayload{
  725. Ref: opts.RefFullName,
  726. Before: opts.OldCommitID,
  727. After: opts.NewCommitID,
  728. CompareURL: setting.AppURL + opts.Commits.CompareURL,
  729. Commits: opts.Commits.ToAPIPayloadCommits(repo.HTMLURL()),
  730. Repo: apiRepo,
  731. Pusher: apiPusher,
  732. Sender: apiPusher,
  733. }); err != nil {
  734. return fmt.Errorf("PrepareWebhooks: %v", err)
  735. }
  736. }
  737. return nil
  738. }
  739. func transferRepoAction(e Engine, doer, oldOwner *User, repo *Repository) (err error) {
  740. if err = notifyWatchers(e, &Action{
  741. ActUserID: doer.ID,
  742. ActUser: doer,
  743. OpType: ActionTransferRepo,
  744. RepoID: repo.ID,
  745. Repo: repo,
  746. IsPrivate: repo.IsPrivate,
  747. Content: path.Join(oldOwner.Name, repo.Name),
  748. }); err != nil {
  749. return fmt.Errorf("notifyWatchers: %v", err)
  750. }
  751. // Remove watch for organization.
  752. if oldOwner.IsOrganization() {
  753. if err = watchRepo(e, oldOwner.ID, repo.ID, false); err != nil {
  754. return fmt.Errorf("watchRepo [false]: %v", err)
  755. }
  756. }
  757. return nil
  758. }
  759. // TransferRepoAction adds new action for transferring repository,
  760. // the Owner field of repository is assumed to be new owner.
  761. func TransferRepoAction(doer, oldOwner *User, repo *Repository) error {
  762. return transferRepoAction(x, doer, oldOwner, repo)
  763. }
  764. func mergePullRequestAction(e Engine, doer *User, repo *Repository, issue *Issue) error {
  765. return notifyWatchers(e, &Action{
  766. ActUserID: doer.ID,
  767. ActUser: doer,
  768. OpType: ActionMergePullRequest,
  769. Content: fmt.Sprintf("%d|%s", issue.Index, issue.Title),
  770. RepoID: repo.ID,
  771. Repo: repo,
  772. IsPrivate: repo.IsPrivate,
  773. })
  774. }
  775. // MergePullRequestAction adds new action for merging pull request.
  776. func MergePullRequestAction(actUser *User, repo *Repository, pull *Issue) error {
  777. return mergePullRequestAction(x, actUser, repo, pull)
  778. }
  779. func mirrorSyncAction(e Engine, opType ActionType, repo *Repository, refName string, data []byte) error {
  780. if err := notifyWatchers(e, &Action{
  781. ActUserID: repo.OwnerID,
  782. ActUser: repo.MustOwner(),
  783. OpType: opType,
  784. RepoID: repo.ID,
  785. Repo: repo,
  786. IsPrivate: repo.IsPrivate,
  787. RefName: refName,
  788. Content: string(data),
  789. }); err != nil {
  790. return fmt.Errorf("notifyWatchers: %v", err)
  791. }
  792. defer func() {
  793. go HookQueue.Add(repo.ID)
  794. }()
  795. return nil
  796. }
  797. // MirrorSyncPushActionOptions mirror synchronization action options.
  798. type MirrorSyncPushActionOptions struct {
  799. RefName string
  800. OldCommitID string
  801. NewCommitID string
  802. Commits *PushCommits
  803. }
  804. // MirrorSyncPushAction adds new action for mirror synchronization of pushed commits.
  805. func MirrorSyncPushAction(repo *Repository, opts MirrorSyncPushActionOptions) error {
  806. if len(opts.Commits.Commits) > setting.UI.FeedMaxCommitNum {
  807. opts.Commits.Commits = opts.Commits.Commits[:setting.UI.FeedMaxCommitNum]
  808. }
  809. apiCommits := opts.Commits.ToAPIPayloadCommits(repo.HTMLURL())
  810. opts.Commits.CompareURL = repo.ComposeCompareURL(opts.OldCommitID, opts.NewCommitID)
  811. apiPusher := repo.MustOwner().APIFormat()
  812. if err := PrepareWebhooks(repo, HookEventPush, &api.PushPayload{
  813. Ref: opts.RefName,
  814. Before: opts.OldCommitID,
  815. After: opts.NewCommitID,
  816. CompareURL: setting.AppURL + opts.Commits.CompareURL,
  817. Commits: apiCommits,
  818. Repo: repo.APIFormat(AccessModeOwner),
  819. Pusher: apiPusher,
  820. Sender: apiPusher,
  821. }); err != nil {
  822. return fmt.Errorf("PrepareWebhooks: %v", err)
  823. }
  824. data, err := json.Marshal(opts.Commits)
  825. if err != nil {
  826. return err
  827. }
  828. return mirrorSyncAction(x, ActionMirrorSyncPush, repo, opts.RefName, data)
  829. }
  830. // MirrorSyncCreateAction adds new action for mirror synchronization of new reference.
  831. func MirrorSyncCreateAction(repo *Repository, refName string) error {
  832. return mirrorSyncAction(x, ActionMirrorSyncCreate, repo, refName, nil)
  833. }
  834. // MirrorSyncDeleteAction adds new action for mirror synchronization of delete reference.
  835. func MirrorSyncDeleteAction(repo *Repository, refName string) error {
  836. return mirrorSyncAction(x, ActionMirrorSyncDelete, repo, refName, nil)
  837. }
  838. // GetFeedsOptions options for retrieving feeds
  839. type GetFeedsOptions struct {
  840. RequestedUser *User
  841. RequestingUserID int64
  842. IncludePrivate bool // include private actions
  843. OnlyPerformedBy bool // only actions performed by requested user
  844. IncludeDeleted bool // include deleted actions
  845. }
  846. // GetFeeds returns actions according to the provided options
  847. func GetFeeds(opts GetFeedsOptions) ([]*Action, error) {
  848. cond := builder.NewCond()
  849. var repoIDs []int64
  850. if opts.RequestedUser.IsOrganization() {
  851. env, err := opts.RequestedUser.AccessibleReposEnv(opts.RequestingUserID)
  852. if err != nil {
  853. return nil, fmt.Errorf("AccessibleReposEnv: %v", err)
  854. }
  855. if repoIDs, err = env.RepoIDs(1, opts.RequestedUser.NumRepos); err != nil {
  856. return nil, fmt.Errorf("GetUserRepositories: %v", err)
  857. }
  858. cond = cond.And(builder.In("repo_id", repoIDs))
  859. }
  860. cond = cond.And(builder.Eq{"user_id": opts.RequestedUser.ID})
  861. if opts.OnlyPerformedBy {
  862. cond = cond.And(builder.Eq{"act_user_id": opts.RequestedUser.ID})
  863. }
  864. if !opts.IncludePrivate {
  865. cond = cond.And(builder.Eq{"is_private": false})
  866. }
  867. if !opts.IncludeDeleted {
  868. cond = cond.And(builder.Eq{"is_deleted": false})
  869. }
  870. actions := make([]*Action, 0, 20)
  871. if err := x.Limit(20).Desc("id").Where(cond).Find(&actions); err != nil {
  872. return nil, fmt.Errorf("Find: %v", err)
  873. }
  874. if err := ActionList(actions).LoadAttributes(); err != nil {
  875. return nil, fmt.Errorf("LoadAttributes: %v", err)
  876. }
  877. return actions, nil
  878. }