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

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