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.

1087 lines
27 KiB

10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
  1. // Copyright 2014 The Gogs Authors. All rights reserved.
  2. // Use of this source code is governed by a MIT-style
  3. // license that can be found in the LICENSE file.
  4. package models
  5. import (
  6. "bytes"
  7. "errors"
  8. "html/template"
  9. "os"
  10. "strconv"
  11. "strings"
  12. "time"
  13. "github.com/Unknwon/com"
  14. "github.com/go-xorm/xorm"
  15. "github.com/gogits/gogs/modules/log"
  16. )
  17. var (
  18. ErrIssueNotExist = errors.New("Issue does not exist")
  19. ErrLabelNotExist = errors.New("Label does not exist")
  20. ErrMilestoneNotExist = errors.New("Milestone does not exist")
  21. ErrWrongIssueCounter = errors.New("Invalid number of issues for this milestone")
  22. ErrAttachmentNotExist = errors.New("Attachment does not exist")
  23. ErrAttachmentNotLinked = errors.New("Attachment does not belong to this issue")
  24. ErrMissingIssueNumber = errors.New("No issue number specified")
  25. )
  26. // Issue represents an issue or pull request of repository.
  27. type Issue struct {
  28. Id int64
  29. RepoId int64 `xorm:"INDEX"`
  30. Index int64 // Index in one repository.
  31. Name string
  32. Repo *Repository `xorm:"-"`
  33. PosterId int64
  34. Poster *User `xorm:"-"`
  35. LabelIds string `xorm:"TEXT"`
  36. Labels []*Label `xorm:"-"`
  37. MilestoneId int64
  38. AssigneeId int64
  39. Assignee *User `xorm:"-"`
  40. IsRead bool `xorm:"-"`
  41. IsPull bool // Indicates whether is a pull request or not.
  42. IsClosed bool
  43. Content string `xorm:"TEXT"`
  44. RenderedContent string `xorm:"-"`
  45. Priority int
  46. NumComments int
  47. Deadline time.Time
  48. Created time.Time `xorm:"CREATED"`
  49. Updated time.Time `xorm:"UPDATED"`
  50. }
  51. func (i *Issue) GetPoster() (err error) {
  52. i.Poster, err = GetUserById(i.PosterId)
  53. if err == ErrUserNotExist {
  54. i.Poster = &User{Name: "FakeUser"}
  55. return nil
  56. }
  57. return err
  58. }
  59. func (i *Issue) GetLabels() error {
  60. if len(i.LabelIds) < 3 {
  61. return nil
  62. }
  63. strIds := strings.Split(strings.TrimSuffix(i.LabelIds[1:], "|"), "|$")
  64. i.Labels = make([]*Label, 0, len(strIds))
  65. for _, strId := range strIds {
  66. id, _ := com.StrTo(strId).Int64()
  67. if id > 0 {
  68. l, err := GetLabelById(id)
  69. if err != nil {
  70. if err == ErrLabelNotExist {
  71. continue
  72. }
  73. return err
  74. }
  75. i.Labels = append(i.Labels, l)
  76. }
  77. }
  78. return nil
  79. }
  80. func (i *Issue) GetAssignee() (err error) {
  81. if i.AssigneeId == 0 {
  82. return nil
  83. }
  84. i.Assignee, err = GetUserById(i.AssigneeId)
  85. if err == ErrUserNotExist {
  86. return nil
  87. }
  88. return err
  89. }
  90. func (i *Issue) Attachments() []*Attachment {
  91. a, _ := GetAttachmentsForIssue(i.Id)
  92. return a
  93. }
  94. func (i *Issue) AfterDelete() {
  95. _, err := DeleteAttachmentsByIssue(i.Id, true)
  96. if err != nil {
  97. log.Info("Could not delete files for issue #%d: %s", i.Id, err)
  98. }
  99. }
  100. // CreateIssue creates new issue for repository.
  101. func NewIssue(issue *Issue) (err error) {
  102. sess := x.NewSession()
  103. defer sess.Close()
  104. if err = sess.Begin(); err != nil {
  105. return err
  106. }
  107. if _, err = sess.Insert(issue); err != nil {
  108. sess.Rollback()
  109. return err
  110. }
  111. rawSql := "UPDATE `repository` SET num_issues = num_issues + 1 WHERE id = ?"
  112. if _, err = sess.Exec(rawSql, issue.RepoId); err != nil {
  113. sess.Rollback()
  114. return err
  115. }
  116. if err = sess.Commit(); err != nil {
  117. return err
  118. }
  119. if issue.MilestoneId > 0 {
  120. // FIXES(280): Update milestone counter.
  121. return ChangeMilestoneAssign(0, issue.MilestoneId, issue)
  122. }
  123. return
  124. }
  125. // GetIssueByRef returns an Issue specified by a GFM reference.
  126. // See https://help.github.com/articles/writing-on-github#references for more information on the syntax.
  127. func GetIssueByRef(ref string) (issue *Issue, err error) {
  128. var issueNumber int64
  129. var repo *Repository
  130. n := strings.IndexByte(ref, byte('#'))
  131. if n == -1 {
  132. return nil, ErrMissingIssueNumber
  133. }
  134. if issueNumber, err = strconv.ParseInt(ref[n+1:], 10, 64); err != nil {
  135. return
  136. }
  137. if repo, err = GetRepositoryByRef(ref[:n]); err != nil {
  138. return
  139. }
  140. return GetIssueByIndex(repo.Id, issueNumber)
  141. }
  142. // GetIssueByIndex returns issue by given index in repository.
  143. func GetIssueByIndex(rid, index int64) (*Issue, error) {
  144. issue := &Issue{RepoId: rid, Index: index}
  145. has, err := x.Get(issue)
  146. if err != nil {
  147. return nil, err
  148. } else if !has {
  149. return nil, ErrIssueNotExist
  150. }
  151. return issue, nil
  152. }
  153. // GetIssueById returns an issue by ID.
  154. func GetIssueById(id int64) (*Issue, error) {
  155. issue := &Issue{Id: id}
  156. has, err := x.Get(issue)
  157. if err != nil {
  158. return nil, err
  159. } else if !has {
  160. return nil, ErrIssueNotExist
  161. }
  162. return issue, nil
  163. }
  164. // GetIssues returns a list of issues by given conditions.
  165. func GetIssues(uid, rid, pid, mid int64, page int, isClosed bool, labelIds, sortType string) ([]Issue, error) {
  166. sess := x.Limit(20, (page-1)*20)
  167. if rid > 0 {
  168. sess.Where("repo_id=?", rid).And("is_closed=?", isClosed)
  169. } else {
  170. sess.Where("is_closed=?", isClosed)
  171. }
  172. if uid > 0 {
  173. sess.And("assignee_id=?", uid)
  174. } else if pid > 0 {
  175. sess.And("poster_id=?", pid)
  176. }
  177. if mid > 0 {
  178. sess.And("milestone_id=?", mid)
  179. }
  180. if len(labelIds) > 0 {
  181. for _, label := range strings.Split(labelIds, ",") {
  182. sess.And("label_ids like '%$" + label + "|%'")
  183. }
  184. }
  185. switch sortType {
  186. case "oldest":
  187. sess.Asc("created")
  188. case "recentupdate":
  189. sess.Desc("updated")
  190. case "leastupdate":
  191. sess.Asc("updated")
  192. case "mostcomment":
  193. sess.Desc("num_comments")
  194. case "leastcomment":
  195. sess.Asc("num_comments")
  196. case "priority":
  197. sess.Desc("priority")
  198. default:
  199. sess.Desc("created")
  200. }
  201. var issues []Issue
  202. err := sess.Find(&issues)
  203. return issues, err
  204. }
  205. type IssueStatus int
  206. const (
  207. IS_OPEN = iota + 1
  208. IS_CLOSE
  209. )
  210. // GetIssuesByLabel returns a list of issues by given label and repository.
  211. func GetIssuesByLabel(repoId int64, label string) ([]*Issue, error) {
  212. issues := make([]*Issue, 0, 10)
  213. err := x.Where("repo_id=?", repoId).And("label_ids like '%$" + label + "|%'").Find(&issues)
  214. return issues, err
  215. }
  216. // GetIssueCountByPoster returns number of issues of repository by poster.
  217. func GetIssueCountByPoster(uid, rid int64, isClosed bool) int64 {
  218. count, _ := x.Where("repo_id=?", rid).And("poster_id=?", uid).And("is_closed=?", isClosed).Count(new(Issue))
  219. return count
  220. }
  221. // .___ ____ ___
  222. // | | ______ ________ __ ____ | | \______ ___________
  223. // | |/ ___// ___/ | \_/ __ \| | / ___// __ \_ __ \
  224. // | |\___ \ \___ \| | /\ ___/| | /\___ \\ ___/| | \/
  225. // |___/____ >____ >____/ \___ >______//____ >\___ >__|
  226. // \/ \/ \/ \/ \/
  227. // IssueUser represents an issue-user relation.
  228. type IssueUser struct {
  229. Id int64
  230. Uid int64 `xorm:"INDEX"` // User ID.
  231. IssueId int64
  232. RepoId int64 `xorm:"INDEX"`
  233. MilestoneId int64
  234. IsRead bool
  235. IsAssigned bool
  236. IsMentioned bool
  237. IsPoster bool
  238. IsClosed bool
  239. }
  240. // NewIssueUserPairs adds new issue-user pairs for new issue of repository.
  241. func NewIssueUserPairs(rid, iid, oid, pid, aid int64, repoName string) (err error) {
  242. iu := &IssueUser{IssueId: iid, RepoId: rid}
  243. us, err := GetCollaborators(repoName)
  244. if err != nil {
  245. return err
  246. }
  247. isNeedAddPoster := true
  248. for _, u := range us {
  249. iu.Uid = u.Id
  250. iu.IsPoster = iu.Uid == pid
  251. if isNeedAddPoster && iu.IsPoster {
  252. isNeedAddPoster = false
  253. }
  254. iu.IsAssigned = iu.Uid == aid
  255. if _, err = x.Insert(iu); err != nil {
  256. return err
  257. }
  258. }
  259. if isNeedAddPoster {
  260. iu.Uid = pid
  261. iu.IsPoster = true
  262. iu.IsAssigned = iu.Uid == aid
  263. if _, err = x.Insert(iu); err != nil {
  264. return err
  265. }
  266. }
  267. return nil
  268. }
  269. // PairsContains returns true when pairs list contains given issue.
  270. func PairsContains(ius []*IssueUser, issueId int64) int {
  271. for i := range ius {
  272. if ius[i].IssueId == issueId {
  273. return i
  274. }
  275. }
  276. return -1
  277. }
  278. // GetIssueUserPairs returns issue-user pairs by given repository and user.
  279. func GetIssueUserPairs(rid, uid int64, isClosed bool) ([]*IssueUser, error) {
  280. ius := make([]*IssueUser, 0, 10)
  281. err := x.Where("is_closed=?", isClosed).Find(&ius, &IssueUser{RepoId: rid, Uid: uid})
  282. return ius, err
  283. }
  284. // GetIssueUserPairsByRepoIds returns issue-user pairs by given repository IDs.
  285. func GetIssueUserPairsByRepoIds(rids []int64, isClosed bool, page int) ([]*IssueUser, error) {
  286. if len(rids) == 0 {
  287. return []*IssueUser{}, nil
  288. }
  289. buf := bytes.NewBufferString("")
  290. for _, rid := range rids {
  291. buf.WriteString("repo_id=")
  292. buf.WriteString(com.ToStr(rid))
  293. buf.WriteString(" OR ")
  294. }
  295. cond := strings.TrimSuffix(buf.String(), " OR ")
  296. ius := make([]*IssueUser, 0, 10)
  297. sess := x.Limit(20, (page-1)*20).Where("is_closed=?", isClosed)
  298. if len(cond) > 0 {
  299. sess.And(cond)
  300. }
  301. err := sess.Find(&ius)
  302. return ius, err
  303. }
  304. // GetIssueUserPairsByMode returns issue-user pairs by given repository and user.
  305. func GetIssueUserPairsByMode(uid, rid int64, isClosed bool, page, filterMode int) ([]*IssueUser, error) {
  306. ius := make([]*IssueUser, 0, 10)
  307. sess := x.Limit(20, (page-1)*20).Where("uid=?", uid).And("is_closed=?", isClosed)
  308. if rid > 0 {
  309. sess.And("repo_id=?", rid)
  310. }
  311. switch filterMode {
  312. case FM_ASSIGN:
  313. sess.And("is_assigned=?", true)
  314. case FM_CREATE:
  315. sess.And("is_poster=?", true)
  316. default:
  317. return ius, nil
  318. }
  319. err := sess.Find(&ius)
  320. return ius, err
  321. }
  322. // IssueStats represents issue statistic information.
  323. type IssueStats struct {
  324. OpenCount, ClosedCount int64
  325. AllCount int64
  326. AssignCount int64
  327. CreateCount int64
  328. MentionCount int64
  329. }
  330. // Filter modes.
  331. const (
  332. FM_ASSIGN = iota + 1
  333. FM_CREATE
  334. FM_MENTION
  335. )
  336. // GetIssueStats returns issue statistic information by given conditions.
  337. func GetIssueStats(rid, uid int64, isShowClosed bool, filterMode int) *IssueStats {
  338. stats := &IssueStats{}
  339. issue := new(Issue)
  340. tmpSess := &xorm.Session{}
  341. sess := x.Where("repo_id=?", rid)
  342. *tmpSess = *sess
  343. stats.OpenCount, _ = tmpSess.And("is_closed=?", false).Count(issue)
  344. *tmpSess = *sess
  345. stats.ClosedCount, _ = tmpSess.And("is_closed=?", true).Count(issue)
  346. if isShowClosed {
  347. stats.AllCount = stats.ClosedCount
  348. } else {
  349. stats.AllCount = stats.OpenCount
  350. }
  351. if filterMode != FM_MENTION {
  352. sess = x.Where("repo_id=?", rid)
  353. switch filterMode {
  354. case FM_ASSIGN:
  355. sess.And("assignee_id=?", uid)
  356. case FM_CREATE:
  357. sess.And("poster_id=?", uid)
  358. default:
  359. goto nofilter
  360. }
  361. *tmpSess = *sess
  362. stats.OpenCount, _ = tmpSess.And("is_closed=?", false).Count(issue)
  363. *tmpSess = *sess
  364. stats.ClosedCount, _ = tmpSess.And("is_closed=?", true).Count(issue)
  365. } else {
  366. sess := x.Where("repo_id=?", rid).And("uid=?", uid).And("is_mentioned=?", true)
  367. *tmpSess = *sess
  368. stats.OpenCount, _ = tmpSess.And("is_closed=?", false).Count(new(IssueUser))
  369. *tmpSess = *sess
  370. stats.ClosedCount, _ = tmpSess.And("is_closed=?", true).Count(new(IssueUser))
  371. }
  372. nofilter:
  373. stats.AssignCount, _ = x.Where("repo_id=?", rid).And("is_closed=?", isShowClosed).And("assignee_id=?", uid).Count(issue)
  374. stats.CreateCount, _ = x.Where("repo_id=?", rid).And("is_closed=?", isShowClosed).And("poster_id=?", uid).Count(issue)
  375. stats.MentionCount, _ = x.Where("repo_id=?", rid).And("uid=?", uid).And("is_closed=?", isShowClosed).And("is_mentioned=?", true).Count(new(IssueUser))
  376. return stats
  377. }
  378. // GetUserIssueStats returns issue statistic information for dashboard by given conditions.
  379. func GetUserIssueStats(uid int64, filterMode int) *IssueStats {
  380. stats := &IssueStats{}
  381. issue := new(Issue)
  382. stats.AssignCount, _ = x.Where("assignee_id=?", uid).And("is_closed=?", false).Count(issue)
  383. stats.CreateCount, _ = x.Where("poster_id=?", uid).And("is_closed=?", false).Count(issue)
  384. return stats
  385. }
  386. // UpdateIssue updates information of issue.
  387. func UpdateIssue(issue *Issue) error {
  388. _, err := x.Id(issue.Id).AllCols().Update(issue)
  389. if err != nil {
  390. return err
  391. }
  392. return err
  393. }
  394. // UpdateIssueUserByStatus updates issue-user pairs by issue status.
  395. func UpdateIssueUserPairsByStatus(iid int64, isClosed bool) error {
  396. rawSql := "UPDATE `issue_user` SET is_closed = ? WHERE issue_id = ?"
  397. _, err := x.Exec(rawSql, isClosed, iid)
  398. return err
  399. }
  400. // UpdateIssueUserPairByAssignee updates issue-user pair for assigning.
  401. func UpdateIssueUserPairByAssignee(aid, iid int64) error {
  402. rawSql := "UPDATE `issue_user` SET is_assigned = ? WHERE issue_id = ?"
  403. if _, err := x.Exec(rawSql, false, iid); err != nil {
  404. return err
  405. }
  406. // Assignee ID equals to 0 means clear assignee.
  407. if aid == 0 {
  408. return nil
  409. }
  410. rawSql = "UPDATE `issue_user` SET is_assigned = true WHERE uid = ? AND issue_id = ?"
  411. _, err := x.Exec(rawSql, aid, iid)
  412. return err
  413. }
  414. // UpdateIssueUserPairByRead updates issue-user pair for reading.
  415. func UpdateIssueUserPairByRead(uid, iid int64) error {
  416. rawSql := "UPDATE `issue_user` SET is_read = ? WHERE uid = ? AND issue_id = ?"
  417. _, err := x.Exec(rawSql, true, uid, iid)
  418. return err
  419. }
  420. // UpdateIssueUserPairsByMentions updates issue-user pairs by mentioning.
  421. func UpdateIssueUserPairsByMentions(uids []int64, iid int64) error {
  422. for _, uid := range uids {
  423. iu := &IssueUser{Uid: uid, IssueId: iid}
  424. has, err := x.Get(iu)
  425. if err != nil {
  426. return err
  427. }
  428. iu.IsMentioned = true
  429. if has {
  430. _, err = x.Id(iu.Id).AllCols().Update(iu)
  431. } else {
  432. _, err = x.Insert(iu)
  433. }
  434. if err != nil {
  435. return err
  436. }
  437. }
  438. return nil
  439. }
  440. // .____ ___. .__
  441. // | | _____ \_ |__ ____ | |
  442. // | | \__ \ | __ \_/ __ \| |
  443. // | |___ / __ \| \_\ \ ___/| |__
  444. // |_______ (____ /___ /\___ >____/
  445. // \/ \/ \/ \/
  446. // Label represents a label of repository for issues.
  447. type Label struct {
  448. Id int64
  449. RepoId int64 `xorm:"INDEX"`
  450. Name string
  451. Color string `xorm:"VARCHAR(7)"`
  452. NumIssues int
  453. NumClosedIssues int
  454. NumOpenIssues int `xorm:"-"`
  455. IsChecked bool `xorm:"-"`
  456. }
  457. // CalOpenIssues calculates the open issues of label.
  458. func (m *Label) CalOpenIssues() {
  459. m.NumOpenIssues = m.NumIssues - m.NumClosedIssues
  460. }
  461. // NewLabel creates new label of repository.
  462. func NewLabel(l *Label) error {
  463. _, err := x.Insert(l)
  464. return err
  465. }
  466. // GetLabelById returns a label by given ID.
  467. func GetLabelById(id int64) (*Label, error) {
  468. if id <= 0 {
  469. return nil, ErrLabelNotExist
  470. }
  471. l := &Label{Id: id}
  472. has, err := x.Get(l)
  473. if err != nil {
  474. return nil, err
  475. } else if !has {
  476. return nil, ErrLabelNotExist
  477. }
  478. return l, nil
  479. }
  480. // GetLabels returns a list of labels of given repository ID.
  481. func GetLabels(repoId int64) ([]*Label, error) {
  482. labels := make([]*Label, 0, 10)
  483. err := x.Where("repo_id=?", repoId).Find(&labels)
  484. return labels, err
  485. }
  486. // UpdateLabel updates label information.
  487. func UpdateLabel(l *Label) error {
  488. _, err := x.Id(l.Id).Update(l)
  489. return err
  490. }
  491. // DeleteLabel delete a label of given repository.
  492. func DeleteLabel(repoId int64, strId string) error {
  493. id, _ := com.StrTo(strId).Int64()
  494. l, err := GetLabelById(id)
  495. if err != nil {
  496. if err == ErrLabelNotExist {
  497. return nil
  498. }
  499. return err
  500. }
  501. issues, err := GetIssuesByLabel(repoId, strId)
  502. if err != nil {
  503. return err
  504. }
  505. sess := x.NewSession()
  506. defer sess.Close()
  507. if err = sess.Begin(); err != nil {
  508. return err
  509. }
  510. for _, issue := range issues {
  511. issue.LabelIds = strings.Replace(issue.LabelIds, "$"+strId+"|", "", -1)
  512. if _, err = sess.Id(issue.Id).AllCols().Update(issue); err != nil {
  513. sess.Rollback()
  514. return err
  515. }
  516. }
  517. if _, err = sess.Delete(l); err != nil {
  518. sess.Rollback()
  519. return err
  520. }
  521. return sess.Commit()
  522. }
  523. // _____ .__.__ __
  524. // / \ |__| | ____ _______/ |_ ____ ____ ____
  525. // / \ / \| | | _/ __ \ / ___/\ __\/ _ \ / \_/ __ \
  526. // / Y \ | |_\ ___/ \___ \ | | ( <_> ) | \ ___/
  527. // \____|__ /__|____/\___ >____ > |__| \____/|___| /\___ >
  528. // \/ \/ \/ \/ \/
  529. // Milestone represents a milestone of repository.
  530. type Milestone struct {
  531. Id int64
  532. RepoId int64 `xorm:"INDEX"`
  533. Index int64
  534. Name string
  535. Content string
  536. RenderedContent string `xorm:"-"`
  537. IsClosed bool
  538. NumIssues int
  539. NumClosedIssues int
  540. NumOpenIssues int `xorm:"-"`
  541. Completeness int // Percentage(1-100).
  542. Deadline time.Time
  543. DeadlineString string `xorm:"-"`
  544. ClosedDate time.Time
  545. }
  546. // CalOpenIssues calculates the open issues of milestone.
  547. func (m *Milestone) CalOpenIssues() {
  548. m.NumOpenIssues = m.NumIssues - m.NumClosedIssues
  549. }
  550. // NewMilestone creates new milestone of repository.
  551. func NewMilestone(m *Milestone) (err error) {
  552. sess := x.NewSession()
  553. defer sess.Close()
  554. if err = sess.Begin(); err != nil {
  555. return err
  556. }
  557. if _, err = sess.Insert(m); err != nil {
  558. sess.Rollback()
  559. return err
  560. }
  561. rawSql := "UPDATE `repository` SET num_milestones = num_milestones + 1 WHERE id = ?"
  562. if _, err = sess.Exec(rawSql, m.RepoId); err != nil {
  563. sess.Rollback()
  564. return err
  565. }
  566. return sess.Commit()
  567. }
  568. // GetMilestoneById returns the milestone by given ID.
  569. func GetMilestoneById(id int64) (*Milestone, error) {
  570. m := &Milestone{Id: id}
  571. has, err := x.Get(m)
  572. if err != nil {
  573. return nil, err
  574. } else if !has {
  575. return nil, ErrMilestoneNotExist
  576. }
  577. return m, nil
  578. }
  579. // GetMilestoneByIndex returns the milestone of given repository and index.
  580. func GetMilestoneByIndex(repoId, idx int64) (*Milestone, error) {
  581. m := &Milestone{RepoId: repoId, Index: idx}
  582. has, err := x.Get(m)
  583. if err != nil {
  584. return nil, err
  585. } else if !has {
  586. return nil, ErrMilestoneNotExist
  587. }
  588. return m, nil
  589. }
  590. // GetMilestones returns a list of milestones of given repository and status.
  591. func GetMilestones(repoId int64, isClosed bool) ([]*Milestone, error) {
  592. miles := make([]*Milestone, 0, 10)
  593. err := x.Where("repo_id=?", repoId).And("is_closed=?", isClosed).Find(&miles)
  594. return miles, err
  595. }
  596. // UpdateMilestone updates information of given milestone.
  597. func UpdateMilestone(m *Milestone) error {
  598. _, err := x.Id(m.Id).Update(m)
  599. return err
  600. }
  601. // ChangeMilestoneStatus changes the milestone open/closed status.
  602. func ChangeMilestoneStatus(m *Milestone, isClosed bool) (err error) {
  603. repo, err := GetRepositoryById(m.RepoId)
  604. if err != nil {
  605. return err
  606. }
  607. sess := x.NewSession()
  608. defer sess.Close()
  609. if err = sess.Begin(); err != nil {
  610. return err
  611. }
  612. m.IsClosed = isClosed
  613. if _, err = sess.Id(m.Id).AllCols().Update(m); err != nil {
  614. sess.Rollback()
  615. return err
  616. }
  617. if isClosed {
  618. repo.NumClosedMilestones++
  619. } else {
  620. repo.NumClosedMilestones--
  621. }
  622. if _, err = sess.Id(repo.Id).Update(repo); err != nil {
  623. sess.Rollback()
  624. return err
  625. }
  626. return sess.Commit()
  627. }
  628. // ChangeMilestoneIssueStats updates the open/closed issues counter and progress for the
  629. // milestone associated witht the given issue.
  630. func ChangeMilestoneIssueStats(issue *Issue) error {
  631. if issue.MilestoneId == 0 {
  632. return nil
  633. }
  634. m, err := GetMilestoneById(issue.MilestoneId)
  635. if err != nil {
  636. return err
  637. }
  638. if issue.IsClosed {
  639. m.NumOpenIssues--
  640. m.NumClosedIssues++
  641. } else {
  642. m.NumOpenIssues++
  643. m.NumClosedIssues--
  644. }
  645. m.Completeness = m.NumClosedIssues * 100 / m.NumIssues
  646. return UpdateMilestone(m)
  647. }
  648. // ChangeMilestoneAssign changes assignment of milestone for issue.
  649. func ChangeMilestoneAssign(oldMid, mid int64, issue *Issue) (err error) {
  650. sess := x.NewSession()
  651. defer sess.Close()
  652. if err = sess.Begin(); err != nil {
  653. return err
  654. }
  655. if oldMid > 0 {
  656. m, err := GetMilestoneById(oldMid)
  657. if err != nil {
  658. return err
  659. }
  660. m.NumIssues--
  661. if issue.IsClosed {
  662. m.NumClosedIssues--
  663. }
  664. if m.NumIssues > 0 {
  665. m.Completeness = m.NumClosedIssues * 100 / m.NumIssues
  666. } else {
  667. m.Completeness = 0
  668. }
  669. if _, err = sess.Id(m.Id).Cols("num_issues,num_completeness,num_closed_issues").Update(m); err != nil {
  670. sess.Rollback()
  671. return err
  672. }
  673. rawSql := "UPDATE `issue_user` SET milestone_id = 0 WHERE issue_id = ?"
  674. if _, err = sess.Exec(rawSql, issue.Id); err != nil {
  675. sess.Rollback()
  676. return err
  677. }
  678. }
  679. if mid > 0 {
  680. m, err := GetMilestoneById(mid)
  681. if err != nil {
  682. return err
  683. }
  684. m.NumIssues++
  685. if issue.IsClosed {
  686. m.NumClosedIssues++
  687. }
  688. if m.NumIssues == 0 {
  689. return ErrWrongIssueCounter
  690. }
  691. m.Completeness = m.NumClosedIssues * 100 / m.NumIssues
  692. if _, err = sess.Id(m.Id).Cols("num_issues,num_completeness,num_closed_issues").Update(m); err != nil {
  693. sess.Rollback()
  694. return err
  695. }
  696. rawSql := "UPDATE `issue_user` SET milestone_id = ? WHERE issue_id = ?"
  697. if _, err = sess.Exec(rawSql, m.Id, issue.Id); err != nil {
  698. sess.Rollback()
  699. return err
  700. }
  701. }
  702. return sess.Commit()
  703. }
  704. // DeleteMilestone deletes a milestone.
  705. func DeleteMilestone(m *Milestone) (err error) {
  706. sess := x.NewSession()
  707. defer sess.Close()
  708. if err = sess.Begin(); err != nil {
  709. return err
  710. }
  711. if _, err = sess.Delete(m); err != nil {
  712. sess.Rollback()
  713. return err
  714. }
  715. rawSql := "UPDATE `repository` SET num_milestones = num_milestones - 1 WHERE id = ?"
  716. if _, err = sess.Exec(rawSql, m.RepoId); err != nil {
  717. sess.Rollback()
  718. return err
  719. }
  720. rawSql = "UPDATE `issue` SET milestone_id = 0 WHERE milestone_id = ?"
  721. if _, err = sess.Exec(rawSql, m.Id); err != nil {
  722. sess.Rollback()
  723. return err
  724. }
  725. rawSql = "UPDATE `issue_user` SET milestone_id = 0 WHERE milestone_id = ?"
  726. if _, err = sess.Exec(rawSql, m.Id); err != nil {
  727. sess.Rollback()
  728. return err
  729. }
  730. return sess.Commit()
  731. }
  732. // _________ __
  733. // \_ ___ \ ____ _____ _____ ____ _____/ |_
  734. // / \ \/ / _ \ / \ / \_/ __ \ / \ __\
  735. // \ \___( <_> ) Y Y \ Y Y \ ___/| | \ |
  736. // \______ /\____/|__|_| /__|_| /\___ >___| /__|
  737. // \/ \/ \/ \/ \/
  738. // CommentType defines whether a comment is just a simple comment, an action (like close) or a reference.
  739. type CommentType int
  740. const (
  741. // Plain comment, can be associated with a commit (CommitId > 0) and a line (Line > 0)
  742. COMMENT CommentType = iota
  743. // Reopen action
  744. REOPEN
  745. // Close action
  746. CLOSE
  747. // Reference from another issue
  748. ISSUE
  749. // Reference from some commit (not part of a pull request)
  750. COMMIT
  751. // Reference from some pull request
  752. PULL
  753. )
  754. // Comment represents a comment in commit and issue page.
  755. type Comment struct {
  756. Id int64
  757. Type CommentType
  758. PosterId int64
  759. Poster *User `xorm:"-"`
  760. IssueId int64
  761. CommitId int64
  762. Line int64
  763. Content string `xorm:"TEXT"`
  764. Created time.Time `xorm:"CREATED"`
  765. }
  766. // CreateComment creates comment of issue or commit.
  767. func CreateComment(userId, repoId, issueId, commitId, line int64, cmtType CommentType, content string, attachments []int64) (*Comment, error) {
  768. sess := x.NewSession()
  769. defer sess.Close()
  770. if err := sess.Begin(); err != nil {
  771. return nil, err
  772. }
  773. comment := &Comment{PosterId: userId, Type: cmtType, IssueId: issueId,
  774. CommitId: commitId, Line: line, Content: content}
  775. if _, err := sess.Insert(comment); err != nil {
  776. sess.Rollback()
  777. return nil, err
  778. }
  779. // Check comment type.
  780. switch cmtType {
  781. case COMMENT:
  782. rawSql := "UPDATE `issue` SET num_comments = num_comments + 1 WHERE id = ?"
  783. if _, err := sess.Exec(rawSql, issueId); err != nil {
  784. sess.Rollback()
  785. return nil, err
  786. }
  787. if len(attachments) > 0 {
  788. rawSql = "UPDATE `attachment` SET comment_id = ? WHERE id IN (?)"
  789. astrs := make([]string, 0, len(attachments))
  790. for _, a := range attachments {
  791. astrs = append(astrs, strconv.FormatInt(a, 10))
  792. }
  793. if _, err := sess.Exec(rawSql, comment.Id, strings.Join(astrs, ",")); err != nil {
  794. sess.Rollback()
  795. return nil, err
  796. }
  797. }
  798. case REOPEN:
  799. rawSql := "UPDATE `repository` SET num_closed_issues = num_closed_issues - 1 WHERE id = ?"
  800. if _, err := sess.Exec(rawSql, repoId); err != nil {
  801. sess.Rollback()
  802. return nil, err
  803. }
  804. case CLOSE:
  805. rawSql := "UPDATE `repository` SET num_closed_issues = num_closed_issues + 1 WHERE id = ?"
  806. if _, err := sess.Exec(rawSql, repoId); err != nil {
  807. sess.Rollback()
  808. return nil, err
  809. }
  810. }
  811. return comment, sess.Commit()
  812. }
  813. // GetCommentById returns the comment with the given id
  814. func GetCommentById(commentId int64) (*Comment, error) {
  815. c := &Comment{Id: commentId}
  816. _, err := x.Get(c)
  817. return c, err
  818. }
  819. func (c *Comment) ContentHtml() template.HTML {
  820. return template.HTML(c.Content)
  821. }
  822. // GetIssueComments returns list of comment by given issue id.
  823. func GetIssueComments(issueId int64) ([]Comment, error) {
  824. comments := make([]Comment, 0, 10)
  825. err := x.Asc("created").Find(&comments, &Comment{IssueId: issueId})
  826. return comments, err
  827. }
  828. // Attachments returns the attachments for this comment.
  829. func (c *Comment) Attachments() []*Attachment {
  830. a, _ := GetAttachmentsByComment(c.Id)
  831. return a
  832. }
  833. func (c *Comment) AfterDelete() {
  834. _, err := DeleteAttachmentsByComment(c.Id, true)
  835. if err != nil {
  836. log.Info("Could not delete files for comment %d on issue #%d: %s", c.Id, c.IssueId, err)
  837. }
  838. }
  839. type Attachment struct {
  840. Id int64
  841. IssueId int64
  842. CommentId int64
  843. Name string
  844. Path string `xorm:"TEXT"`
  845. Created time.Time `xorm:"CREATED"`
  846. }
  847. // CreateAttachment creates a new attachment inside the database and
  848. func CreateAttachment(issueId, commentId int64, name, path string) (*Attachment, error) {
  849. sess := x.NewSession()
  850. defer sess.Close()
  851. if err := sess.Begin(); err != nil {
  852. return nil, err
  853. }
  854. a := &Attachment{IssueId: issueId, CommentId: commentId, Name: name, Path: path}
  855. if _, err := sess.Insert(a); err != nil {
  856. sess.Rollback()
  857. return nil, err
  858. }
  859. return a, sess.Commit()
  860. }
  861. // Attachment returns the attachment by given ID.
  862. func GetAttachmentById(id int64) (*Attachment, error) {
  863. m := &Attachment{Id: id}
  864. has, err := x.Get(m)
  865. if err != nil {
  866. return nil, err
  867. }
  868. if !has {
  869. return nil, ErrAttachmentNotExist
  870. }
  871. return m, nil
  872. }
  873. func GetAttachmentsForIssue(issueId int64) ([]*Attachment, error) {
  874. attachments := make([]*Attachment, 0, 10)
  875. err := x.Where("issue_id = ?", issueId).And("comment_id = 0").Find(&attachments)
  876. return attachments, err
  877. }
  878. // GetAttachmentsByIssue returns a list of attachments for the given issue
  879. func GetAttachmentsByIssue(issueId int64) ([]*Attachment, error) {
  880. attachments := make([]*Attachment, 0, 10)
  881. err := x.Where("issue_id = ?", issueId).And("comment_id > 0").Find(&attachments)
  882. return attachments, err
  883. }
  884. // GetAttachmentsByComment returns a list of attachments for the given comment
  885. func GetAttachmentsByComment(commentId int64) ([]*Attachment, error) {
  886. attachments := make([]*Attachment, 0, 10)
  887. err := x.Where("comment_id = ?", commentId).Find(&attachments)
  888. return attachments, err
  889. }
  890. // DeleteAttachment deletes the given attachment and optionally the associated file.
  891. func DeleteAttachment(a *Attachment, remove bool) error {
  892. _, err := DeleteAttachments([]*Attachment{a}, remove)
  893. return err
  894. }
  895. // DeleteAttachments deletes the given attachments and optionally the associated files.
  896. func DeleteAttachments(attachments []*Attachment, remove bool) (int, error) {
  897. for i, a := range attachments {
  898. if remove {
  899. if err := os.Remove(a.Path); err != nil {
  900. return i, err
  901. }
  902. }
  903. if _, err := x.Delete(a.Id); err != nil {
  904. return i, err
  905. }
  906. }
  907. return len(attachments), nil
  908. }
  909. // DeleteAttachmentsByIssue deletes all attachments associated with the given issue.
  910. func DeleteAttachmentsByIssue(issueId int64, remove bool) (int, error) {
  911. attachments, err := GetAttachmentsByIssue(issueId)
  912. if err != nil {
  913. return 0, err
  914. }
  915. return DeleteAttachments(attachments, remove)
  916. }
  917. // DeleteAttachmentsByComment deletes all attachments associated with the given comment.
  918. func DeleteAttachmentsByComment(commentId int64, remove bool) (int, error) {
  919. attachments, err := GetAttachmentsByComment(commentId)
  920. if err != nil {
  921. return 0, err
  922. }
  923. return DeleteAttachments(attachments, remove)
  924. }