issue.go 26 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018
  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. // GetIssueComments returns list of comment by given issue id.
  762. func GetIssueComments(issueId int64) ([]Comment, error) {
  763. comments := make([]Comment, 0, 10)
  764. err := x.Asc("created").Find(&comments, &Comment{IssueId: issueId})
  765. return comments, err
  766. }
  767. // Attachments returns the attachments for this comment.
  768. func (c *Comment) Attachments() []*Attachment {
  769. a, _ := GetAttachmentsByComment(c.Id)
  770. return a
  771. }
  772. func (c *Comment) AfterDelete() {
  773. _, err := DeleteAttachmentsByComment(c.Id, true)
  774. if err != nil {
  775. log.Info("Could not delete files for comment %d on issue #%d: %s", c.Id, c.IssueId, err)
  776. }
  777. }
  778. type Attachment struct {
  779. Id int64
  780. IssueId int64
  781. CommentId int64
  782. Name string
  783. Path string
  784. Created time.Time `xorm:"CREATED"`
  785. }
  786. // CreateAttachment creates a new attachment inside the database and
  787. func CreateAttachment(issueId, commentId int64, name, path string) (*Attachment, error) {
  788. sess := x.NewSession()
  789. defer sess.Close()
  790. if err := sess.Begin(); err != nil {
  791. return nil, err
  792. }
  793. a := &Attachment{IssueId: issueId, CommentId: commentId, Name: name, Path: path}
  794. if _, err := sess.Insert(a); err != nil {
  795. sess.Rollback()
  796. return nil, err
  797. }
  798. return a, sess.Commit()
  799. }
  800. // Attachment returns the attachment by given ID.
  801. func GetAttachmentById(id int64) (*Attachment, error) {
  802. m := &Attachment{Id: id}
  803. has, err := x.Get(m)
  804. if err != nil {
  805. return nil, err
  806. }
  807. if !has {
  808. return nil, ErrAttachmentNotExist
  809. }
  810. return m, nil
  811. }
  812. func GetAttachmentsForIssue(issueId int64) ([]*Attachment, error) {
  813. attachments := make([]*Attachment, 0, 10)
  814. err := x.Where("issue_id = ?", issueId).Where("comment_id = 0").Find(&attachments)
  815. return attachments, err
  816. }
  817. // GetAttachmentsByIssue returns a list of attachments for the given issue
  818. func GetAttachmentsByIssue(issueId int64) ([]*Attachment, error) {
  819. attachments := make([]*Attachment, 0, 10)
  820. err := x.Where("issue_id = ?", issueId).Where("comment_id > 0").Find(&attachments)
  821. return attachments, err
  822. }
  823. // GetAttachmentsByComment returns a list of attachments for the given comment
  824. func GetAttachmentsByComment(commentId int64) ([]*Attachment, error) {
  825. attachments := make([]*Attachment, 0, 10)
  826. err := x.Where("comment_id = ?", commentId).Find(&attachments)
  827. return attachments, err
  828. }
  829. // DeleteAttachment deletes the given attachment and optionally the associated file.
  830. func DeleteAttachment(a *Attachment, remove bool) error {
  831. _, err := DeleteAttachments([]*Attachment{a}, remove)
  832. return err
  833. }
  834. // DeleteAttachments deletes the given attachments and optionally the associated files.
  835. func DeleteAttachments(attachments []*Attachment, remove bool) (int, error) {
  836. for i, a := range attachments {
  837. if remove {
  838. if err := os.Remove(a.Path); err != nil {
  839. return i, err
  840. }
  841. }
  842. if _, err := x.Delete(a.Id); err != nil {
  843. return i, err
  844. }
  845. }
  846. return len(attachments), nil
  847. }
  848. // DeleteAttachmentsByIssue deletes all attachments associated with the given issue.
  849. func DeleteAttachmentsByIssue(issueId int64, remove bool) (int, error) {
  850. attachments, err := GetAttachmentsByIssue(issueId)
  851. if err != nil {
  852. return 0, err
  853. }
  854. return DeleteAttachments(attachments, remove)
  855. }
  856. // DeleteAttachmentsByComment deletes all attachments associated with the given comment.
  857. func DeleteAttachmentsByComment(commentId int64, remove bool) (int, error) {
  858. attachments, err := GetAttachmentsByComment(commentId)
  859. if err != nil {
  860. return 0, err
  861. }
  862. return DeleteAttachments(attachments, remove)
  863. }
  864. // AssignAttachment assigns the given attachment to the specified comment
  865. func AssignAttachment(issueId, commentId, attachmentId int64) error {
  866. a, err := GetAttachmentById(attachmentId)
  867. if err != nil {
  868. return err
  869. }
  870. if a.IssueId != issueId {
  871. return ErrAttachmentNotLinked
  872. }
  873. a.CommentId = commentId
  874. _, err = x.Id(a.Id).Update(a)
  875. return err
  876. }