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

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