本站源代码
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.

1067 lines
28KB

  1. // Copyright 2018 The Gitea Authors.
  2. // Copyright 2016 The Gogs Authors.
  3. // All rights reserved.
  4. // Use of this source code is governed by a MIT-style
  5. // license that can be found in the LICENSE file.
  6. package models
  7. import (
  8. "fmt"
  9. "strings"
  10. "code.gitea.io/gitea/modules/git"
  11. "code.gitea.io/gitea/modules/log"
  12. "code.gitea.io/gitea/modules/markup/markdown"
  13. "code.gitea.io/gitea/modules/references"
  14. "code.gitea.io/gitea/modules/structs"
  15. api "code.gitea.io/gitea/modules/structs"
  16. "code.gitea.io/gitea/modules/timeutil"
  17. "github.com/unknwon/com"
  18. "xorm.io/builder"
  19. "xorm.io/xorm"
  20. )
  21. // CommentType defines whether a comment is just a simple comment, an action (like close) or a reference.
  22. type CommentType int
  23. // define unknown comment type
  24. const (
  25. CommentTypeUnknown CommentType = -1
  26. )
  27. // Enumerate all the comment types
  28. const (
  29. // Plain comment, can be associated with a commit (CommitID > 0) and a line (LineNum > 0)
  30. CommentTypeComment CommentType = iota
  31. CommentTypeReopen
  32. CommentTypeClose
  33. // References.
  34. CommentTypeIssueRef
  35. // Reference from a commit (not part of a pull request)
  36. CommentTypeCommitRef
  37. // Reference from a comment
  38. CommentTypeCommentRef
  39. // Reference from a pull request
  40. CommentTypePullRef
  41. // Labels changed
  42. CommentTypeLabel
  43. // Milestone changed
  44. CommentTypeMilestone
  45. // Assignees changed
  46. CommentTypeAssignees
  47. // Change Title
  48. CommentTypeChangeTitle
  49. // Delete Branch
  50. CommentTypeDeleteBranch
  51. // Start a stopwatch for time tracking
  52. CommentTypeStartTracking
  53. // Stop a stopwatch for time tracking
  54. CommentTypeStopTracking
  55. // Add time manual for time tracking
  56. CommentTypeAddTimeManual
  57. // Cancel a stopwatch for time tracking
  58. CommentTypeCancelTracking
  59. // Added a due date
  60. CommentTypeAddedDeadline
  61. // Modified the due date
  62. CommentTypeModifiedDeadline
  63. // Removed a due date
  64. CommentTypeRemovedDeadline
  65. // Dependency added
  66. CommentTypeAddDependency
  67. //Dependency removed
  68. CommentTypeRemoveDependency
  69. // Comment a line of code
  70. CommentTypeCode
  71. // Reviews a pull request by giving general feedback
  72. CommentTypeReview
  73. // Lock an issue, giving only collaborators access
  74. CommentTypeLock
  75. // Unlocks a previously locked issue
  76. CommentTypeUnlock
  77. )
  78. // CommentTag defines comment tag type
  79. type CommentTag int
  80. // Enumerate all the comment tag types
  81. const (
  82. CommentTagNone CommentTag = iota
  83. CommentTagPoster
  84. CommentTagWriter
  85. CommentTagOwner
  86. )
  87. // Comment represents a comment in commit and issue page.
  88. type Comment struct {
  89. ID int64 `xorm:"pk autoincr"`
  90. Type CommentType `xorm:"index"`
  91. PosterID int64 `xorm:"INDEX"`
  92. Poster *User `xorm:"-"`
  93. OriginalAuthor string
  94. OriginalAuthorID int64
  95. IssueID int64 `xorm:"INDEX"`
  96. Issue *Issue `xorm:"-"`
  97. LabelID int64
  98. Label *Label `xorm:"-"`
  99. OldMilestoneID int64
  100. MilestoneID int64
  101. OldMilestone *Milestone `xorm:"-"`
  102. Milestone *Milestone `xorm:"-"`
  103. AssigneeID int64
  104. RemovedAssignee bool
  105. Assignee *User `xorm:"-"`
  106. OldTitle string
  107. NewTitle string
  108. DependentIssueID int64
  109. DependentIssue *Issue `xorm:"-"`
  110. CommitID int64
  111. Line int64 // - previous line / + proposed line
  112. TreePath string
  113. Content string `xorm:"TEXT"`
  114. RenderedContent string `xorm:"-"`
  115. // Path represents the 4 lines of code cemented by this comment
  116. Patch string `xorm:"TEXT"`
  117. CreatedUnix timeutil.TimeStamp `xorm:"INDEX created"`
  118. UpdatedUnix timeutil.TimeStamp `xorm:"INDEX updated"`
  119. // Reference issue in commit message
  120. CommitSHA string `xorm:"VARCHAR(40)"`
  121. Attachments []*Attachment `xorm:"-"`
  122. Reactions ReactionList `xorm:"-"`
  123. // For view issue page.
  124. ShowTag CommentTag `xorm:"-"`
  125. Review *Review `xorm:"-"`
  126. ReviewID int64 `xorm:"index"`
  127. Invalidated bool
  128. // Reference an issue or pull from another comment, issue or PR
  129. // All information is about the origin of the reference
  130. RefRepoID int64 `xorm:"index"` // Repo where the referencing
  131. RefIssueID int64 `xorm:"index"`
  132. RefCommentID int64 `xorm:"index"` // 0 if origin is Issue title or content (or PR's)
  133. RefAction references.XRefAction `xorm:"SMALLINT"` // What hapens if RefIssueID resolves
  134. RefIsPull bool
  135. RefRepo *Repository `xorm:"-"`
  136. RefIssue *Issue `xorm:"-"`
  137. RefComment *Comment `xorm:"-"`
  138. }
  139. // LoadIssue loads issue from database
  140. func (c *Comment) LoadIssue() (err error) {
  141. return c.loadIssue(x)
  142. }
  143. func (c *Comment) loadIssue(e Engine) (err error) {
  144. if c.Issue != nil {
  145. return nil
  146. }
  147. c.Issue, err = getIssueByID(e, c.IssueID)
  148. return
  149. }
  150. func (c *Comment) loadPoster(e Engine) (err error) {
  151. if c.PosterID <= 0 || c.Poster != nil {
  152. return nil
  153. }
  154. c.Poster, err = getUserByID(e, c.PosterID)
  155. if err != nil {
  156. if IsErrUserNotExist(err) {
  157. c.PosterID = -1
  158. c.Poster = NewGhostUser()
  159. } else {
  160. log.Error("getUserByID[%d]: %v", c.ID, err)
  161. }
  162. }
  163. return err
  164. }
  165. // AfterDelete is invoked from XORM after the object is deleted.
  166. func (c *Comment) AfterDelete() {
  167. if c.ID <= 0 {
  168. return
  169. }
  170. _, err := DeleteAttachmentsByComment(c.ID, true)
  171. if err != nil {
  172. log.Info("Could not delete files for comment %d on issue #%d: %s", c.ID, c.IssueID, err)
  173. }
  174. }
  175. // HTMLURL formats a URL-string to the issue-comment
  176. func (c *Comment) HTMLURL() string {
  177. err := c.LoadIssue()
  178. if err != nil { // Silently dropping errors :unamused:
  179. log.Error("LoadIssue(%d): %v", c.IssueID, err)
  180. return ""
  181. }
  182. err = c.Issue.loadRepo(x)
  183. if err != nil { // Silently dropping errors :unamused:
  184. log.Error("loadRepo(%d): %v", c.Issue.RepoID, err)
  185. return ""
  186. }
  187. if c.Type == CommentTypeCode {
  188. if c.ReviewID == 0 {
  189. return fmt.Sprintf("%s/files#%s", c.Issue.HTMLURL(), c.HashTag())
  190. }
  191. if c.Review == nil {
  192. if err := c.LoadReview(); err != nil {
  193. log.Warn("LoadReview(%d): %v", c.ReviewID, err)
  194. return fmt.Sprintf("%s/files#%s", c.Issue.HTMLURL(), c.HashTag())
  195. }
  196. }
  197. if c.Review.Type <= ReviewTypePending {
  198. return fmt.Sprintf("%s/files#%s", c.Issue.HTMLURL(), c.HashTag())
  199. }
  200. }
  201. return fmt.Sprintf("%s#%s", c.Issue.HTMLURL(), c.HashTag())
  202. }
  203. // IssueURL formats a URL-string to the issue
  204. func (c *Comment) IssueURL() string {
  205. err := c.LoadIssue()
  206. if err != nil { // Silently dropping errors :unamused:
  207. log.Error("LoadIssue(%d): %v", c.IssueID, err)
  208. return ""
  209. }
  210. if c.Issue.IsPull {
  211. return ""
  212. }
  213. err = c.Issue.loadRepo(x)
  214. if err != nil { // Silently dropping errors :unamused:
  215. log.Error("loadRepo(%d): %v", c.Issue.RepoID, err)
  216. return ""
  217. }
  218. return c.Issue.HTMLURL()
  219. }
  220. // PRURL formats a URL-string to the pull-request
  221. func (c *Comment) PRURL() string {
  222. err := c.LoadIssue()
  223. if err != nil { // Silently dropping errors :unamused:
  224. log.Error("LoadIssue(%d): %v", c.IssueID, err)
  225. return ""
  226. }
  227. err = c.Issue.loadRepo(x)
  228. if err != nil { // Silently dropping errors :unamused:
  229. log.Error("loadRepo(%d): %v", c.Issue.RepoID, err)
  230. return ""
  231. }
  232. if !c.Issue.IsPull {
  233. return ""
  234. }
  235. return c.Issue.HTMLURL()
  236. }
  237. // APIFormat converts a Comment to the api.Comment format
  238. func (c *Comment) APIFormat() *api.Comment {
  239. return &api.Comment{
  240. ID: c.ID,
  241. Poster: c.Poster.APIFormat(),
  242. HTMLURL: c.HTMLURL(),
  243. IssueURL: c.IssueURL(),
  244. PRURL: c.PRURL(),
  245. Body: c.Content,
  246. Created: c.CreatedUnix.AsTime(),
  247. Updated: c.UpdatedUnix.AsTime(),
  248. }
  249. }
  250. // CommentHashTag returns unique hash tag for comment id.
  251. func CommentHashTag(id int64) string {
  252. return fmt.Sprintf("issuecomment-%d", id)
  253. }
  254. // HashTag returns unique hash tag for comment.
  255. func (c *Comment) HashTag() string {
  256. return CommentHashTag(c.ID)
  257. }
  258. // EventTag returns unique event hash tag for comment.
  259. func (c *Comment) EventTag() string {
  260. return "event-" + com.ToStr(c.ID)
  261. }
  262. // LoadLabel if comment.Type is CommentTypeLabel, then load Label
  263. func (c *Comment) LoadLabel() error {
  264. var label Label
  265. has, err := x.ID(c.LabelID).Get(&label)
  266. if err != nil {
  267. return err
  268. } else if has {
  269. c.Label = &label
  270. } else {
  271. // Ignore Label is deleted, but not clear this table
  272. log.Warn("Commit %d cannot load label %d", c.ID, c.LabelID)
  273. }
  274. return nil
  275. }
  276. // LoadMilestone if comment.Type is CommentTypeMilestone, then load milestone
  277. func (c *Comment) LoadMilestone() error {
  278. if c.OldMilestoneID > 0 {
  279. var oldMilestone Milestone
  280. has, err := x.ID(c.OldMilestoneID).Get(&oldMilestone)
  281. if err != nil {
  282. return err
  283. } else if has {
  284. c.OldMilestone = &oldMilestone
  285. }
  286. }
  287. if c.MilestoneID > 0 {
  288. var milestone Milestone
  289. has, err := x.ID(c.MilestoneID).Get(&milestone)
  290. if err != nil {
  291. return err
  292. } else if has {
  293. c.Milestone = &milestone
  294. }
  295. }
  296. return nil
  297. }
  298. // LoadPoster loads comment poster
  299. func (c *Comment) LoadPoster() error {
  300. return c.loadPoster(x)
  301. }
  302. // LoadAttachments loads attachments
  303. func (c *Comment) LoadAttachments() error {
  304. if len(c.Attachments) > 0 {
  305. return nil
  306. }
  307. var err error
  308. c.Attachments, err = getAttachmentsByCommentID(x, c.ID)
  309. if err != nil {
  310. log.Error("getAttachmentsByCommentID[%d]: %v", c.ID, err)
  311. }
  312. return nil
  313. }
  314. // UpdateAttachments update attachments by UUIDs for the comment
  315. func (c *Comment) UpdateAttachments(uuids []string) error {
  316. sess := x.NewSession()
  317. defer sess.Close()
  318. if err := sess.Begin(); err != nil {
  319. return err
  320. }
  321. attachments, err := getAttachmentsByUUIDs(sess, uuids)
  322. if err != nil {
  323. return fmt.Errorf("getAttachmentsByUUIDs [uuids: %v]: %v", uuids, err)
  324. }
  325. for i := 0; i < len(attachments); i++ {
  326. attachments[i].IssueID = c.IssueID
  327. attachments[i].CommentID = c.ID
  328. if err := updateAttachment(sess, attachments[i]); err != nil {
  329. return fmt.Errorf("update attachment [id: %d]: %v", attachments[i].ID, err)
  330. }
  331. }
  332. return sess.Commit()
  333. }
  334. // LoadAssigneeUser if comment.Type is CommentTypeAssignees, then load assignees
  335. func (c *Comment) LoadAssigneeUser() error {
  336. var err error
  337. if c.AssigneeID > 0 {
  338. c.Assignee, err = getUserByID(x, c.AssigneeID)
  339. if err != nil {
  340. if !IsErrUserNotExist(err) {
  341. return err
  342. }
  343. c.Assignee = NewGhostUser()
  344. }
  345. }
  346. return nil
  347. }
  348. // LoadDepIssueDetails loads Dependent Issue Details
  349. func (c *Comment) LoadDepIssueDetails() (err error) {
  350. if c.DependentIssueID <= 0 || c.DependentIssue != nil {
  351. return nil
  352. }
  353. c.DependentIssue, err = getIssueByID(x, c.DependentIssueID)
  354. return err
  355. }
  356. func (c *Comment) loadReactions(e Engine) (err error) {
  357. if c.Reactions != nil {
  358. return nil
  359. }
  360. c.Reactions, err = findReactions(e, FindReactionsOptions{
  361. IssueID: c.IssueID,
  362. CommentID: c.ID,
  363. })
  364. if err != nil {
  365. return err
  366. }
  367. // Load reaction user data
  368. if _, err := c.Reactions.LoadUsers(); err != nil {
  369. return err
  370. }
  371. return nil
  372. }
  373. // LoadReactions loads comment reactions
  374. func (c *Comment) LoadReactions() error {
  375. return c.loadReactions(x)
  376. }
  377. func (c *Comment) loadReview(e Engine) (err error) {
  378. if c.Review == nil {
  379. if c.Review, err = getReviewByID(e, c.ReviewID); err != nil {
  380. return err
  381. }
  382. }
  383. c.Review.Issue = c.Issue
  384. return nil
  385. }
  386. // LoadReview loads the associated review
  387. func (c *Comment) LoadReview() error {
  388. return c.loadReview(x)
  389. }
  390. func (c *Comment) checkInvalidation(doer *User, repo *git.Repository, branch string) error {
  391. // FIXME differentiate between previous and proposed line
  392. commit, err := repo.LineBlame(branch, repo.Path, c.TreePath, uint(c.UnsignedLine()))
  393. if err != nil {
  394. return err
  395. }
  396. if c.CommitSHA != "" && c.CommitSHA != commit.ID.String() {
  397. c.Invalidated = true
  398. return UpdateComment(c, doer)
  399. }
  400. return nil
  401. }
  402. // CheckInvalidation checks if the line of code comment got changed by another commit.
  403. // If the line got changed the comment is going to be invalidated.
  404. func (c *Comment) CheckInvalidation(repo *git.Repository, doer *User, branch string) error {
  405. return c.checkInvalidation(doer, repo, branch)
  406. }
  407. // DiffSide returns "previous" if Comment.Line is a LOC of the previous changes and "proposed" if it is a LOC of the proposed changes.
  408. func (c *Comment) DiffSide() string {
  409. if c.Line < 0 {
  410. return "previous"
  411. }
  412. return "proposed"
  413. }
  414. // UnsignedLine returns the LOC of the code comment without + or -
  415. func (c *Comment) UnsignedLine() uint64 {
  416. if c.Line < 0 {
  417. return uint64(c.Line * -1)
  418. }
  419. return uint64(c.Line)
  420. }
  421. // CodeCommentURL returns the url to a comment in code
  422. func (c *Comment) CodeCommentURL() string {
  423. err := c.LoadIssue()
  424. if err != nil { // Silently dropping errors :unamused:
  425. log.Error("LoadIssue(%d): %v", c.IssueID, err)
  426. return ""
  427. }
  428. err = c.Issue.loadRepo(x)
  429. if err != nil { // Silently dropping errors :unamused:
  430. log.Error("loadRepo(%d): %v", c.Issue.RepoID, err)
  431. return ""
  432. }
  433. return fmt.Sprintf("%s/files#%s", c.Issue.HTMLURL(), c.HashTag())
  434. }
  435. func createComment(e *xorm.Session, opts *CreateCommentOptions) (_ *Comment, err error) {
  436. var LabelID int64
  437. if opts.Label != nil {
  438. LabelID = opts.Label.ID
  439. }
  440. comment := &Comment{
  441. Type: opts.Type,
  442. PosterID: opts.Doer.ID,
  443. Poster: opts.Doer,
  444. IssueID: opts.Issue.ID,
  445. LabelID: LabelID,
  446. OldMilestoneID: opts.OldMilestoneID,
  447. MilestoneID: opts.MilestoneID,
  448. RemovedAssignee: opts.RemovedAssignee,
  449. AssigneeID: opts.AssigneeID,
  450. CommitID: opts.CommitID,
  451. CommitSHA: opts.CommitSHA,
  452. Line: opts.LineNum,
  453. Content: opts.Content,
  454. OldTitle: opts.OldTitle,
  455. NewTitle: opts.NewTitle,
  456. DependentIssueID: opts.DependentIssueID,
  457. TreePath: opts.TreePath,
  458. ReviewID: opts.ReviewID,
  459. Patch: opts.Patch,
  460. RefRepoID: opts.RefRepoID,
  461. RefIssueID: opts.RefIssueID,
  462. RefCommentID: opts.RefCommentID,
  463. RefAction: opts.RefAction,
  464. RefIsPull: opts.RefIsPull,
  465. }
  466. if _, err = e.Insert(comment); err != nil {
  467. return nil, err
  468. }
  469. if err = opts.Repo.getOwner(e); err != nil {
  470. return nil, err
  471. }
  472. if err = sendCreateCommentAction(e, opts, comment); err != nil {
  473. return nil, err
  474. }
  475. if err = comment.addCrossReferences(e, opts.Doer); err != nil {
  476. return nil, err
  477. }
  478. return comment, nil
  479. }
  480. func sendCreateCommentAction(e *xorm.Session, opts *CreateCommentOptions, comment *Comment) (err error) {
  481. // Compose comment action, could be plain comment, close or reopen issue/pull request.
  482. // This object will be used to notify watchers in the end of function.
  483. act := &Action{
  484. ActUserID: opts.Doer.ID,
  485. ActUser: opts.Doer,
  486. Content: fmt.Sprintf("%d|%s", opts.Issue.Index, strings.Split(opts.Content, "\n")[0]),
  487. RepoID: opts.Repo.ID,
  488. Repo: opts.Repo,
  489. Comment: comment,
  490. CommentID: comment.ID,
  491. IsPrivate: opts.Repo.IsPrivate,
  492. }
  493. // Check comment type.
  494. switch opts.Type {
  495. case CommentTypeCode:
  496. if comment.ReviewID != 0 {
  497. if comment.Review == nil {
  498. if err := comment.loadReview(e); err != nil {
  499. return err
  500. }
  501. }
  502. if comment.Review.Type <= ReviewTypePending {
  503. return nil
  504. }
  505. }
  506. fallthrough
  507. case CommentTypeComment:
  508. act.OpType = ActionCommentIssue
  509. if _, err = e.Exec("UPDATE `issue` SET num_comments=num_comments+1 WHERE id=?", opts.Issue.ID); err != nil {
  510. return err
  511. }
  512. // Check attachments
  513. attachments := make([]*Attachment, 0, len(opts.Attachments))
  514. for _, uuid := range opts.Attachments {
  515. attach, err := getAttachmentByUUID(e, uuid)
  516. if err != nil {
  517. if IsErrAttachmentNotExist(err) {
  518. continue
  519. }
  520. return fmt.Errorf("getAttachmentByUUID [%s]: %v", uuid, err)
  521. }
  522. attachments = append(attachments, attach)
  523. }
  524. for i := range attachments {
  525. attachments[i].IssueID = opts.Issue.ID
  526. attachments[i].CommentID = comment.ID
  527. // No assign value could be 0, so ignore AllCols().
  528. if _, err = e.ID(attachments[i].ID).Update(attachments[i]); err != nil {
  529. return fmt.Errorf("update attachment [%d]: %v", attachments[i].ID, err)
  530. }
  531. }
  532. case CommentTypeReopen:
  533. act.OpType = ActionReopenIssue
  534. if opts.Issue.IsPull {
  535. act.OpType = ActionReopenPullRequest
  536. }
  537. if err = opts.Issue.updateClosedNum(e); err != nil {
  538. return err
  539. }
  540. case CommentTypeClose:
  541. act.OpType = ActionCloseIssue
  542. if opts.Issue.IsPull {
  543. act.OpType = ActionClosePullRequest
  544. }
  545. if err = opts.Issue.updateClosedNum(e); err != nil {
  546. return err
  547. }
  548. }
  549. // update the issue's updated_unix column
  550. if err = updateIssueCols(e, opts.Issue, "updated_unix"); err != nil {
  551. return err
  552. }
  553. // Notify watchers for whatever action comes in, ignore if no action type.
  554. if act.OpType > 0 {
  555. if err = notifyWatchers(e, act); err != nil {
  556. log.Error("notifyWatchers: %v", err)
  557. }
  558. }
  559. return nil
  560. }
  561. func createStatusComment(e *xorm.Session, doer *User, issue *Issue) (*Comment, error) {
  562. cmtType := CommentTypeClose
  563. if !issue.IsClosed {
  564. cmtType = CommentTypeReopen
  565. }
  566. return createComment(e, &CreateCommentOptions{
  567. Type: cmtType,
  568. Doer: doer,
  569. Repo: issue.Repo,
  570. Issue: issue,
  571. })
  572. }
  573. func createLabelComment(e *xorm.Session, doer *User, repo *Repository, issue *Issue, label *Label, add bool) (*Comment, error) {
  574. var content string
  575. if add {
  576. content = "1"
  577. }
  578. return createComment(e, &CreateCommentOptions{
  579. Type: CommentTypeLabel,
  580. Doer: doer,
  581. Repo: repo,
  582. Issue: issue,
  583. Label: label,
  584. Content: content,
  585. })
  586. }
  587. func createMilestoneComment(e *xorm.Session, doer *User, repo *Repository, issue *Issue, oldMilestoneID, milestoneID int64) (*Comment, error) {
  588. return createComment(e, &CreateCommentOptions{
  589. Type: CommentTypeMilestone,
  590. Doer: doer,
  591. Repo: repo,
  592. Issue: issue,
  593. OldMilestoneID: oldMilestoneID,
  594. MilestoneID: milestoneID,
  595. })
  596. }
  597. func createAssigneeComment(e *xorm.Session, doer *User, repo *Repository, issue *Issue, assigneeID int64, removedAssignee bool) (*Comment, error) {
  598. return createComment(e, &CreateCommentOptions{
  599. Type: CommentTypeAssignees,
  600. Doer: doer,
  601. Repo: repo,
  602. Issue: issue,
  603. RemovedAssignee: removedAssignee,
  604. AssigneeID: assigneeID,
  605. })
  606. }
  607. func createDeadlineComment(e *xorm.Session, doer *User, issue *Issue, newDeadlineUnix timeutil.TimeStamp) (*Comment, error) {
  608. var content string
  609. var commentType CommentType
  610. // newDeadline = 0 means deleting
  611. if newDeadlineUnix == 0 {
  612. commentType = CommentTypeRemovedDeadline
  613. content = issue.DeadlineUnix.Format("2006-01-02")
  614. } else if issue.DeadlineUnix == 0 {
  615. // Check if the new date was added or modified
  616. // If the actual deadline is 0 => deadline added
  617. commentType = CommentTypeAddedDeadline
  618. content = newDeadlineUnix.Format("2006-01-02")
  619. } else { // Otherwise modified
  620. commentType = CommentTypeModifiedDeadline
  621. content = newDeadlineUnix.Format("2006-01-02") + "|" + issue.DeadlineUnix.Format("2006-01-02")
  622. }
  623. if err := issue.loadRepo(e); err != nil {
  624. return nil, err
  625. }
  626. return createComment(e, &CreateCommentOptions{
  627. Type: commentType,
  628. Doer: doer,
  629. Repo: issue.Repo,
  630. Issue: issue,
  631. Content: content,
  632. })
  633. }
  634. func createChangeTitleComment(e *xorm.Session, doer *User, repo *Repository, issue *Issue, oldTitle, newTitle string) (*Comment, error) {
  635. return createComment(e, &CreateCommentOptions{
  636. Type: CommentTypeChangeTitle,
  637. Doer: doer,
  638. Repo: repo,
  639. Issue: issue,
  640. OldTitle: oldTitle,
  641. NewTitle: newTitle,
  642. })
  643. }
  644. func createDeleteBranchComment(e *xorm.Session, doer *User, repo *Repository, issue *Issue, branchName string) (*Comment, error) {
  645. return createComment(e, &CreateCommentOptions{
  646. Type: CommentTypeDeleteBranch,
  647. Doer: doer,
  648. Repo: repo,
  649. Issue: issue,
  650. CommitSHA: branchName,
  651. })
  652. }
  653. // Creates issue dependency comment
  654. func createIssueDependencyComment(e *xorm.Session, doer *User, issue *Issue, dependentIssue *Issue, add bool) (err error) {
  655. cType := CommentTypeAddDependency
  656. if !add {
  657. cType = CommentTypeRemoveDependency
  658. }
  659. if err = issue.loadRepo(e); err != nil {
  660. return
  661. }
  662. // Make two comments, one in each issue
  663. _, err = createComment(e, &CreateCommentOptions{
  664. Type: cType,
  665. Doer: doer,
  666. Repo: issue.Repo,
  667. Issue: issue,
  668. DependentIssueID: dependentIssue.ID,
  669. })
  670. if err != nil {
  671. return
  672. }
  673. _, err = createComment(e, &CreateCommentOptions{
  674. Type: cType,
  675. Doer: doer,
  676. Repo: issue.Repo,
  677. Issue: dependentIssue,
  678. DependentIssueID: issue.ID,
  679. })
  680. if err != nil {
  681. return
  682. }
  683. return
  684. }
  685. // CreateCommentOptions defines options for creating comment
  686. type CreateCommentOptions struct {
  687. Type CommentType
  688. Doer *User
  689. Repo *Repository
  690. Issue *Issue
  691. Label *Label
  692. DependentIssueID int64
  693. OldMilestoneID int64
  694. MilestoneID int64
  695. AssigneeID int64
  696. RemovedAssignee bool
  697. OldTitle string
  698. NewTitle string
  699. CommitID int64
  700. CommitSHA string
  701. Patch string
  702. LineNum int64
  703. TreePath string
  704. ReviewID int64
  705. Content string
  706. Attachments []string // UUIDs of attachments
  707. RefRepoID int64
  708. RefIssueID int64
  709. RefCommentID int64
  710. RefAction references.XRefAction
  711. RefIsPull bool
  712. }
  713. // CreateComment creates comment of issue or commit.
  714. func CreateComment(opts *CreateCommentOptions) (comment *Comment, err error) {
  715. sess := x.NewSession()
  716. defer sess.Close()
  717. if err = sess.Begin(); err != nil {
  718. return nil, err
  719. }
  720. comment, err = createComment(sess, opts)
  721. if err != nil {
  722. return nil, err
  723. }
  724. if err = sess.Commit(); err != nil {
  725. return nil, err
  726. }
  727. return comment, nil
  728. }
  729. // CreateRefComment creates a commit reference comment to issue.
  730. func CreateRefComment(doer *User, repo *Repository, issue *Issue, content, commitSHA string) error {
  731. if len(commitSHA) == 0 {
  732. return fmt.Errorf("cannot create reference with empty commit SHA")
  733. }
  734. // Check if same reference from same commit has already existed.
  735. has, err := x.Get(&Comment{
  736. Type: CommentTypeCommitRef,
  737. IssueID: issue.ID,
  738. CommitSHA: commitSHA,
  739. })
  740. if err != nil {
  741. return fmt.Errorf("check reference comment: %v", err)
  742. } else if has {
  743. return nil
  744. }
  745. _, err = CreateComment(&CreateCommentOptions{
  746. Type: CommentTypeCommitRef,
  747. Doer: doer,
  748. Repo: repo,
  749. Issue: issue,
  750. CommitSHA: commitSHA,
  751. Content: content,
  752. })
  753. return err
  754. }
  755. // GetCommentByID returns the comment by given ID.
  756. func GetCommentByID(id int64) (*Comment, error) {
  757. c := new(Comment)
  758. has, err := x.ID(id).Get(c)
  759. if err != nil {
  760. return nil, err
  761. } else if !has {
  762. return nil, ErrCommentNotExist{id, 0}
  763. }
  764. return c, nil
  765. }
  766. // FindCommentsOptions describes the conditions to Find comments
  767. type FindCommentsOptions struct {
  768. RepoID int64
  769. IssueID int64
  770. ReviewID int64
  771. Since int64
  772. Type CommentType
  773. }
  774. func (opts *FindCommentsOptions) toConds() builder.Cond {
  775. var cond = builder.NewCond()
  776. if opts.RepoID > 0 {
  777. cond = cond.And(builder.Eq{"issue.repo_id": opts.RepoID})
  778. }
  779. if opts.IssueID > 0 {
  780. cond = cond.And(builder.Eq{"comment.issue_id": opts.IssueID})
  781. }
  782. if opts.ReviewID > 0 {
  783. cond = cond.And(builder.Eq{"comment.review_id": opts.ReviewID})
  784. }
  785. if opts.Since > 0 {
  786. cond = cond.And(builder.Gte{"comment.updated_unix": opts.Since})
  787. }
  788. if opts.Type != CommentTypeUnknown {
  789. cond = cond.And(builder.Eq{"comment.type": opts.Type})
  790. }
  791. return cond
  792. }
  793. func findComments(e Engine, opts FindCommentsOptions) ([]*Comment, error) {
  794. comments := make([]*Comment, 0, 10)
  795. sess := e.Where(opts.toConds())
  796. if opts.RepoID > 0 {
  797. sess.Join("INNER", "issue", "issue.id = comment.issue_id")
  798. }
  799. return comments, sess.
  800. Asc("comment.created_unix").
  801. Asc("comment.id").
  802. Find(&comments)
  803. }
  804. // FindComments returns all comments according options
  805. func FindComments(opts FindCommentsOptions) ([]*Comment, error) {
  806. return findComments(x, opts)
  807. }
  808. // UpdateComment updates information of comment.
  809. func UpdateComment(c *Comment, doer *User) error {
  810. sess := x.NewSession()
  811. defer sess.Close()
  812. if err := sess.Begin(); err != nil {
  813. return err
  814. }
  815. if _, err := sess.ID(c.ID).AllCols().Update(c); err != nil {
  816. return err
  817. }
  818. if err := c.loadIssue(sess); err != nil {
  819. return err
  820. }
  821. if err := c.neuterCrossReferences(sess); err != nil {
  822. return err
  823. }
  824. if err := c.addCrossReferences(sess, doer); err != nil {
  825. return err
  826. }
  827. if err := sess.Commit(); err != nil {
  828. return fmt.Errorf("Commit: %v", err)
  829. }
  830. return nil
  831. }
  832. // DeleteComment deletes the comment
  833. func DeleteComment(comment *Comment, doer *User) error {
  834. sess := x.NewSession()
  835. defer sess.Close()
  836. if err := sess.Begin(); err != nil {
  837. return err
  838. }
  839. if _, err := sess.Delete(&Comment{
  840. ID: comment.ID,
  841. }); err != nil {
  842. return err
  843. }
  844. if comment.Type == CommentTypeComment {
  845. if _, err := sess.Exec("UPDATE `issue` SET num_comments = num_comments - 1 WHERE id = ?", comment.IssueID); err != nil {
  846. return err
  847. }
  848. }
  849. if _, err := sess.Where("comment_id = ?", comment.ID).Cols("is_deleted").Update(&Action{IsDeleted: true}); err != nil {
  850. return err
  851. }
  852. if err := comment.neuterCrossReferences(sess); err != nil {
  853. return err
  854. }
  855. return sess.Commit()
  856. }
  857. // CodeComments represents comments on code by using this structure: FILENAME -> LINE (+ == proposed; - == previous) -> COMMENTS
  858. type CodeComments map[string]map[int64][]*Comment
  859. func fetchCodeComments(e Engine, issue *Issue, currentUser *User) (CodeComments, error) {
  860. return fetchCodeCommentsByReview(e, issue, currentUser, nil)
  861. }
  862. func fetchCodeCommentsByReview(e Engine, issue *Issue, currentUser *User, review *Review) (CodeComments, error) {
  863. pathToLineToComment := make(CodeComments)
  864. if review == nil {
  865. review = &Review{ID: 0}
  866. }
  867. //Find comments
  868. opts := FindCommentsOptions{
  869. Type: CommentTypeCode,
  870. IssueID: issue.ID,
  871. ReviewID: review.ID,
  872. }
  873. conds := opts.toConds()
  874. if review.ID == 0 {
  875. conds = conds.And(builder.Eq{"invalidated": false})
  876. }
  877. var comments []*Comment
  878. if err := e.Where(conds).
  879. Asc("comment.created_unix").
  880. Asc("comment.id").
  881. Find(&comments); err != nil {
  882. return nil, err
  883. }
  884. if err := CommentList(comments).loadPosters(e); err != nil {
  885. return nil, err
  886. }
  887. if err := issue.loadRepo(e); err != nil {
  888. return nil, err
  889. }
  890. if err := CommentList(comments).loadPosters(e); err != nil {
  891. return nil, err
  892. }
  893. // Find all reviews by ReviewID
  894. reviews := make(map[int64]*Review)
  895. var ids = make([]int64, 0, len(comments))
  896. for _, comment := range comments {
  897. if comment.ReviewID != 0 {
  898. ids = append(ids, comment.ReviewID)
  899. }
  900. }
  901. if err := e.In("id", ids).Find(&reviews); err != nil {
  902. return nil, err
  903. }
  904. for _, comment := range comments {
  905. if re, ok := reviews[comment.ReviewID]; ok && re != nil {
  906. // If the review is pending only the author can see the comments (except the review is set)
  907. if review.ID == 0 {
  908. if re.Type == ReviewTypePending &&
  909. (currentUser == nil || currentUser.ID != re.ReviewerID) {
  910. continue
  911. }
  912. }
  913. comment.Review = re
  914. }
  915. comment.RenderedContent = string(markdown.Render([]byte(comment.Content), issue.Repo.Link(),
  916. issue.Repo.ComposeMetas()))
  917. if pathToLineToComment[comment.TreePath] == nil {
  918. pathToLineToComment[comment.TreePath] = make(map[int64][]*Comment)
  919. }
  920. pathToLineToComment[comment.TreePath][comment.Line] = append(pathToLineToComment[comment.TreePath][comment.Line], comment)
  921. }
  922. return pathToLineToComment, nil
  923. }
  924. // FetchCodeComments will return a 2d-map: ["Path"]["Line"] = Comments at line
  925. func FetchCodeComments(issue *Issue, currentUser *User) (CodeComments, error) {
  926. return fetchCodeComments(x, issue, currentUser)
  927. }
  928. // UpdateCommentsMigrationsByType updates comments' migrations information via given git service type and original id and poster id
  929. func UpdateCommentsMigrationsByType(tp structs.GitServiceType, originalAuthorID string, posterID int64) error {
  930. _, err := x.Table("comment").
  931. Where(builder.In("issue_id",
  932. builder.Select("issue.id").
  933. From("issue").
  934. InnerJoin("repository", "issue.repo_id = repository.id").
  935. Where(builder.Eq{
  936. "repository.original_service_type": tp,
  937. }),
  938. )).
  939. And("comment.original_author_id = ?", originalAuthorID).
  940. Update(map[string]interface{}{
  941. "poster_id": posterID,
  942. "original_author": "",
  943. "original_author_id": 0,
  944. })
  945. return err
  946. }
上海开阖软件有限公司 沪ICP备12045867号-1