issue.go 26 KB

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