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.

issue_comment.go 31KB

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