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 32KB

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