issue.go 27 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087
  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. // Prevent SQL inject.
  183. if com.StrTo(label).MustInt() > 0 {
  184. sess.And("label_ids like '%$" + label + "|%'")
  185. }
  186. }
  187. }
  188. switch sortType {
  189. case "oldest":
  190. sess.Asc("created")
  191. case "recentupdate":
  192. sess.Desc("updated")
  193. case "leastupdate":
  194. sess.Asc("updated")
  195. case "mostcomment":
  196. sess.Desc("num_comments")
  197. case "leastcomment":
  198. sess.Asc("num_comments")
  199. case "priority":
  200. sess.Desc("priority")
  201. default:
  202. sess.Desc("created")
  203. }
  204. var issues []Issue
  205. err := sess.Find(&issues)
  206. return issues, err
  207. }
  208. type IssueStatus int
  209. const (
  210. IS_OPEN = iota + 1
  211. IS_CLOSE
  212. )
  213. // GetIssuesByLabel returns a list of issues by given label and repository.
  214. func GetIssuesByLabel(repoId int64, label string) ([]*Issue, error) {
  215. issues := make([]*Issue, 0, 10)
  216. err := x.Where("repo_id=?", repoId).And("label_ids like '%$" + label + "|%'").Find(&issues)
  217. return issues, err
  218. }
  219. // GetIssueCountByPoster returns number of issues of repository by poster.
  220. func GetIssueCountByPoster(uid, rid int64, isClosed bool) int64 {
  221. count, _ := x.Where("repo_id=?", rid).And("poster_id=?", uid).And("is_closed=?", isClosed).Count(new(Issue))
  222. return count
  223. }
  224. // .___ ____ ___
  225. // | | ______ ________ __ ____ | | \______ ___________
  226. // | |/ ___// ___/ | \_/ __ \| | / ___// __ \_ __ \
  227. // | |\___ \ \___ \| | /\ ___/| | /\___ \\ ___/| | \/
  228. // |___/____ >____ >____/ \___ >______//____ >\___ >__|
  229. // \/ \/ \/ \/ \/
  230. // IssueUser represents an issue-user relation.
  231. type IssueUser struct {
  232. Id int64
  233. Uid int64 `xorm:"INDEX"` // User ID.
  234. IssueId int64
  235. RepoId int64 `xorm:"INDEX"`
  236. MilestoneId int64
  237. IsRead bool
  238. IsAssigned bool
  239. IsMentioned bool
  240. IsPoster bool
  241. IsClosed bool
  242. }
  243. // NewIssueUserPairs adds new issue-user pairs for new issue of repository.
  244. func NewIssueUserPairs(repo *Repository, issueID, orgID, posterID, assigneeID int64) (err error) {
  245. users, err := repo.GetCollaborators()
  246. if err != nil {
  247. return err
  248. }
  249. iu := &IssueUser{
  250. IssueId: issueID,
  251. RepoId: repo.Id,
  252. }
  253. isNeedAddPoster := true
  254. for _, u := range users {
  255. iu.Uid = u.Id
  256. iu.IsPoster = iu.Uid == posterID
  257. if isNeedAddPoster && iu.IsPoster {
  258. isNeedAddPoster = false
  259. }
  260. iu.IsAssigned = iu.Uid == assigneeID
  261. if _, err = x.Insert(iu); err != nil {
  262. return err
  263. }
  264. }
  265. if isNeedAddPoster {
  266. iu.Uid = posterID
  267. iu.IsPoster = true
  268. iu.IsAssigned = iu.Uid == assigneeID
  269. if _, err = x.Insert(iu); err != nil {
  270. return err
  271. }
  272. }
  273. return nil
  274. }
  275. // PairsContains returns true when pairs list contains given issue.
  276. func PairsContains(ius []*IssueUser, issueId int64) int {
  277. for i := range ius {
  278. if ius[i].IssueId == issueId {
  279. return i
  280. }
  281. }
  282. return -1
  283. }
  284. // GetIssueUserPairs returns issue-user pairs by given repository and user.
  285. func GetIssueUserPairs(rid, uid int64, isClosed bool) ([]*IssueUser, error) {
  286. ius := make([]*IssueUser, 0, 10)
  287. err := x.Where("is_closed=?", isClosed).Find(&ius, &IssueUser{RepoId: rid, Uid: uid})
  288. return ius, err
  289. }
  290. // GetIssueUserPairsByRepoIds returns issue-user pairs by given repository IDs.
  291. func GetIssueUserPairsByRepoIds(rids []int64, isClosed bool, page int) ([]*IssueUser, error) {
  292. if len(rids) == 0 {
  293. return []*IssueUser{}, nil
  294. }
  295. buf := bytes.NewBufferString("")
  296. for _, rid := range rids {
  297. buf.WriteString("repo_id=")
  298. buf.WriteString(com.ToStr(rid))
  299. buf.WriteString(" OR ")
  300. }
  301. cond := strings.TrimSuffix(buf.String(), " OR ")
  302. ius := make([]*IssueUser, 0, 10)
  303. sess := x.Limit(20, (page-1)*20).Where("is_closed=?", isClosed)
  304. if len(cond) > 0 {
  305. sess.And(cond)
  306. }
  307. err := sess.Find(&ius)
  308. return ius, err
  309. }
  310. // GetIssueUserPairsByMode returns issue-user pairs by given repository and user.
  311. func GetIssueUserPairsByMode(uid, rid int64, isClosed bool, page, filterMode int) ([]*IssueUser, error) {
  312. ius := make([]*IssueUser, 0, 10)
  313. sess := x.Limit(20, (page-1)*20).Where("uid=?", uid).And("is_closed=?", isClosed)
  314. if rid > 0 {
  315. sess.And("repo_id=?", rid)
  316. }
  317. switch filterMode {
  318. case FM_ASSIGN:
  319. sess.And("is_assigned=?", true)
  320. case FM_CREATE:
  321. sess.And("is_poster=?", true)
  322. default:
  323. return ius, nil
  324. }
  325. err := sess.Find(&ius)
  326. return ius, err
  327. }
  328. // IssueStats represents issue statistic information.
  329. type IssueStats struct {
  330. OpenCount, ClosedCount int64
  331. AllCount int64
  332. AssignCount int64
  333. CreateCount int64
  334. MentionCount int64
  335. }
  336. // Filter modes.
  337. const (
  338. FM_ASSIGN = iota + 1
  339. FM_CREATE
  340. FM_MENTION
  341. )
  342. // GetIssueStats returns issue statistic information by given conditions.
  343. func GetIssueStats(rid, uid int64, isShowClosed bool, filterMode int) *IssueStats {
  344. stats := &IssueStats{}
  345. issue := new(Issue)
  346. tmpSess := &xorm.Session{}
  347. sess := x.Where("repo_id=?", rid)
  348. *tmpSess = *sess
  349. stats.OpenCount, _ = tmpSess.And("is_closed=?", false).Count(issue)
  350. *tmpSess = *sess
  351. stats.ClosedCount, _ = tmpSess.And("is_closed=?", true).Count(issue)
  352. if isShowClosed {
  353. stats.AllCount = stats.ClosedCount
  354. } else {
  355. stats.AllCount = stats.OpenCount
  356. }
  357. if filterMode != FM_MENTION {
  358. sess = x.Where("repo_id=?", rid)
  359. switch filterMode {
  360. case FM_ASSIGN:
  361. sess.And("assignee_id=?", uid)
  362. case FM_CREATE:
  363. sess.And("poster_id=?", uid)
  364. default:
  365. goto nofilter
  366. }
  367. *tmpSess = *sess
  368. stats.OpenCount, _ = tmpSess.And("is_closed=?", false).Count(issue)
  369. *tmpSess = *sess
  370. stats.ClosedCount, _ = tmpSess.And("is_closed=?", true).Count(issue)
  371. } else {
  372. sess := x.Where("repo_id=?", rid).And("uid=?", uid).And("is_mentioned=?", true)
  373. *tmpSess = *sess
  374. stats.OpenCount, _ = tmpSess.And("is_closed=?", false).Count(new(IssueUser))
  375. *tmpSess = *sess
  376. stats.ClosedCount, _ = tmpSess.And("is_closed=?", true).Count(new(IssueUser))
  377. }
  378. nofilter:
  379. stats.AssignCount, _ = x.Where("repo_id=?", rid).And("is_closed=?", isShowClosed).And("assignee_id=?", uid).Count(issue)
  380. stats.CreateCount, _ = x.Where("repo_id=?", rid).And("is_closed=?", isShowClosed).And("poster_id=?", uid).Count(issue)
  381. stats.MentionCount, _ = x.Where("repo_id=?", rid).And("uid=?", uid).And("is_closed=?", isShowClosed).And("is_mentioned=?", true).Count(new(IssueUser))
  382. return stats
  383. }
  384. // GetUserIssueStats returns issue statistic information for dashboard by given conditions.
  385. func GetUserIssueStats(uid int64, filterMode int) *IssueStats {
  386. stats := &IssueStats{}
  387. issue := new(Issue)
  388. stats.AssignCount, _ = x.Where("assignee_id=?", uid).And("is_closed=?", false).Count(issue)
  389. stats.CreateCount, _ = x.Where("poster_id=?", uid).And("is_closed=?", false).Count(issue)
  390. return stats
  391. }
  392. // UpdateIssue updates information of issue.
  393. func UpdateIssue(issue *Issue) error {
  394. _, err := x.Id(issue.Id).AllCols().Update(issue)
  395. if err != nil {
  396. return err
  397. }
  398. return err
  399. }
  400. // UpdateIssueUserByStatus updates issue-user pairs by issue status.
  401. func UpdateIssueUserPairsByStatus(iid int64, isClosed bool) error {
  402. rawSql := "UPDATE `issue_user` SET is_closed = ? WHERE issue_id = ?"
  403. _, err := x.Exec(rawSql, isClosed, iid)
  404. return err
  405. }
  406. // UpdateIssueUserPairByAssignee updates issue-user pair for assigning.
  407. func UpdateIssueUserPairByAssignee(aid, iid int64) error {
  408. rawSql := "UPDATE `issue_user` SET is_assigned = ? WHERE issue_id = ?"
  409. if _, err := x.Exec(rawSql, false, iid); err != nil {
  410. return err
  411. }
  412. // Assignee ID equals to 0 means clear assignee.
  413. if aid == 0 {
  414. return nil
  415. }
  416. rawSql = "UPDATE `issue_user` SET is_assigned = ? WHERE uid = ? AND issue_id = ?"
  417. _, err := x.Exec(rawSql, true, aid, iid)
  418. return err
  419. }
  420. // UpdateIssueUserPairByRead updates issue-user pair for reading.
  421. func UpdateIssueUserPairByRead(uid, iid int64) error {
  422. rawSql := "UPDATE `issue_user` SET is_read = ? WHERE uid = ? AND issue_id = ?"
  423. _, err := x.Exec(rawSql, true, uid, iid)
  424. return err
  425. }
  426. // UpdateIssueUserPairsByMentions updates issue-user pairs by mentioning.
  427. func UpdateIssueUserPairsByMentions(uids []int64, iid int64) error {
  428. for _, uid := range uids {
  429. iu := &IssueUser{Uid: uid, IssueId: iid}
  430. has, err := x.Get(iu)
  431. if err != nil {
  432. return err
  433. }
  434. iu.IsMentioned = true
  435. if has {
  436. _, err = x.Id(iu.Id).AllCols().Update(iu)
  437. } else {
  438. _, err = x.Insert(iu)
  439. }
  440. if err != nil {
  441. return err
  442. }
  443. }
  444. return nil
  445. }
  446. // .____ ___. .__
  447. // | | _____ \_ |__ ____ | |
  448. // | | \__ \ | __ \_/ __ \| |
  449. // | |___ / __ \| \_\ \ ___/| |__
  450. // |_______ (____ /___ /\___ >____/
  451. // \/ \/ \/ \/
  452. // Label represents a label of repository for issues.
  453. type Label struct {
  454. Id int64
  455. RepoId int64 `xorm:"INDEX"`
  456. Name string
  457. Color string `xorm:"VARCHAR(7)"`
  458. NumIssues int
  459. NumClosedIssues int
  460. NumOpenIssues int `xorm:"-"`
  461. IsChecked bool `xorm:"-"`
  462. }
  463. // CalOpenIssues calculates the open issues of label.
  464. func (m *Label) CalOpenIssues() {
  465. m.NumOpenIssues = m.NumIssues - m.NumClosedIssues
  466. }
  467. // NewLabel creates new label of repository.
  468. func NewLabel(l *Label) error {
  469. _, err := x.Insert(l)
  470. return err
  471. }
  472. // GetLabelById returns a label by given ID.
  473. func GetLabelById(id int64) (*Label, error) {
  474. if id <= 0 {
  475. return nil, ErrLabelNotExist
  476. }
  477. l := &Label{Id: id}
  478. has, err := x.Get(l)
  479. if err != nil {
  480. return nil, err
  481. } else if !has {
  482. return nil, ErrLabelNotExist
  483. }
  484. return l, nil
  485. }
  486. // GetLabels returns a list of labels of given repository ID.
  487. func GetLabels(repoId int64) ([]*Label, error) {
  488. labels := make([]*Label, 0, 10)
  489. err := x.Where("repo_id=?", repoId).Find(&labels)
  490. return labels, err
  491. }
  492. // UpdateLabel updates label information.
  493. func UpdateLabel(l *Label) error {
  494. _, err := x.Id(l.Id).AllCols().Update(l)
  495. return err
  496. }
  497. // DeleteLabel delete a label of given repository.
  498. func DeleteLabel(repoId int64, strId string) error {
  499. id, _ := com.StrTo(strId).Int64()
  500. l, err := GetLabelById(id)
  501. if err != nil {
  502. if err == ErrLabelNotExist {
  503. return nil
  504. }
  505. return err
  506. }
  507. issues, err := GetIssuesByLabel(repoId, strId)
  508. if err != nil {
  509. return err
  510. }
  511. sess := x.NewSession()
  512. defer sess.Close()
  513. if err = sess.Begin(); err != nil {
  514. return err
  515. }
  516. for _, issue := range issues {
  517. issue.LabelIds = strings.Replace(issue.LabelIds, "$"+strId+"|", "", -1)
  518. if _, err = sess.Id(issue.Id).AllCols().Update(issue); err != nil {
  519. sess.Rollback()
  520. return err
  521. }
  522. }
  523. if _, err = sess.Delete(l); err != nil {
  524. sess.Rollback()
  525. return err
  526. }
  527. return sess.Commit()
  528. }
  529. // _____ .__.__ __
  530. // / \ |__| | ____ _______/ |_ ____ ____ ____
  531. // / \ / \| | | _/ __ \ / ___/\ __\/ _ \ / \_/ __ \
  532. // / Y \ | |_\ ___/ \___ \ | | ( <_> ) | \ ___/
  533. // \____|__ /__|____/\___ >____ > |__| \____/|___| /\___ >
  534. // \/ \/ \/ \/ \/
  535. // Milestone represents a milestone of repository.
  536. type Milestone struct {
  537. Id int64
  538. RepoId int64 `xorm:"INDEX"`
  539. Index int64
  540. Name string
  541. Content string `xorm:"TEXT"`
  542. RenderedContent string `xorm:"-"`
  543. IsClosed bool
  544. NumIssues int
  545. NumClosedIssues int
  546. NumOpenIssues int `xorm:"-"`
  547. Completeness int // Percentage(1-100).
  548. Deadline time.Time
  549. DeadlineString string `xorm:"-"`
  550. ClosedDate time.Time
  551. }
  552. // CalOpenIssues calculates the open issues of milestone.
  553. func (m *Milestone) CalOpenIssues() {
  554. m.NumOpenIssues = m.NumIssues - m.NumClosedIssues
  555. }
  556. // NewMilestone creates new milestone of repository.
  557. func NewMilestone(m *Milestone) (err error) {
  558. sess := x.NewSession()
  559. defer sess.Close()
  560. if err = sess.Begin(); err != nil {
  561. return err
  562. }
  563. if _, err = sess.Insert(m); err != nil {
  564. sess.Rollback()
  565. return err
  566. }
  567. rawSql := "UPDATE `repository` SET num_milestones = num_milestones + 1 WHERE id = ?"
  568. if _, err = sess.Exec(rawSql, m.RepoId); err != nil {
  569. sess.Rollback()
  570. return err
  571. }
  572. return sess.Commit()
  573. }
  574. // GetMilestoneById returns the milestone by given ID.
  575. func GetMilestoneById(id int64) (*Milestone, error) {
  576. m := &Milestone{Id: id}
  577. has, err := x.Get(m)
  578. if err != nil {
  579. return nil, err
  580. } else if !has {
  581. return nil, ErrMilestoneNotExist
  582. }
  583. return m, nil
  584. }
  585. // GetMilestoneByIndex returns the milestone of given repository and index.
  586. func GetMilestoneByIndex(repoId, idx int64) (*Milestone, error) {
  587. m := &Milestone{RepoId: repoId, Index: idx}
  588. has, err := x.Get(m)
  589. if err != nil {
  590. return nil, err
  591. } else if !has {
  592. return nil, ErrMilestoneNotExist
  593. }
  594. return m, nil
  595. }
  596. // GetMilestones returns a list of milestones of given repository and status.
  597. func GetMilestones(repoId int64, isClosed bool) ([]*Milestone, error) {
  598. miles := make([]*Milestone, 0, 10)
  599. err := x.Where("repo_id=?", repoId).And("is_closed=?", isClosed).Find(&miles)
  600. return miles, err
  601. }
  602. // UpdateMilestone updates information of given milestone.
  603. func UpdateMilestone(m *Milestone) error {
  604. _, err := x.Id(m.Id).Update(m)
  605. return err
  606. }
  607. // ChangeMilestoneStatus changes the milestone open/closed status.
  608. func ChangeMilestoneStatus(m *Milestone, isClosed bool) (err error) {
  609. repo, err := GetRepositoryById(m.RepoId)
  610. if err != nil {
  611. return err
  612. }
  613. sess := x.NewSession()
  614. defer sess.Close()
  615. if err = sess.Begin(); err != nil {
  616. return err
  617. }
  618. m.IsClosed = isClosed
  619. if _, err = sess.Id(m.Id).AllCols().Update(m); err != nil {
  620. sess.Rollback()
  621. return err
  622. }
  623. if isClosed {
  624. repo.NumClosedMilestones++
  625. } else {
  626. repo.NumClosedMilestones--
  627. }
  628. if _, err = sess.Id(repo.Id).Update(repo); err != nil {
  629. sess.Rollback()
  630. return err
  631. }
  632. return sess.Commit()
  633. }
  634. // ChangeMilestoneIssueStats updates the open/closed issues counter and progress for the
  635. // milestone associated witht the given issue.
  636. func ChangeMilestoneIssueStats(issue *Issue) error {
  637. if issue.MilestoneId == 0 {
  638. return nil
  639. }
  640. m, err := GetMilestoneById(issue.MilestoneId)
  641. if err != nil {
  642. return err
  643. }
  644. if issue.IsClosed {
  645. m.NumOpenIssues--
  646. m.NumClosedIssues++
  647. } else {
  648. m.NumOpenIssues++
  649. m.NumClosedIssues--
  650. }
  651. m.Completeness = m.NumClosedIssues * 100 / m.NumIssues
  652. return UpdateMilestone(m)
  653. }
  654. // ChangeMilestoneAssign changes assignment of milestone for issue.
  655. func ChangeMilestoneAssign(oldMid, mid int64, issue *Issue) (err error) {
  656. sess := x.NewSession()
  657. defer sess.Close()
  658. if err = sess.Begin(); err != nil {
  659. return err
  660. }
  661. if oldMid > 0 {
  662. m, err := GetMilestoneById(oldMid)
  663. if err != nil {
  664. return err
  665. }
  666. m.NumIssues--
  667. if issue.IsClosed {
  668. m.NumClosedIssues--
  669. }
  670. if m.NumIssues > 0 {
  671. m.Completeness = m.NumClosedIssues * 100 / m.NumIssues
  672. } else {
  673. m.Completeness = 0
  674. }
  675. if _, err = sess.Id(m.Id).Cols("num_issues,num_completeness,num_closed_issues").Update(m); err != nil {
  676. sess.Rollback()
  677. return err
  678. }
  679. rawSql := "UPDATE `issue_user` SET milestone_id = 0 WHERE issue_id = ?"
  680. if _, err = sess.Exec(rawSql, issue.Id); err != nil {
  681. sess.Rollback()
  682. return err
  683. }
  684. }
  685. if mid > 0 {
  686. m, err := GetMilestoneById(mid)
  687. if err != nil {
  688. return err
  689. }
  690. m.NumIssues++
  691. if issue.IsClosed {
  692. m.NumClosedIssues++
  693. }
  694. if m.NumIssues == 0 {
  695. return ErrWrongIssueCounter
  696. }
  697. m.Completeness = m.NumClosedIssues * 100 / m.NumIssues
  698. if _, err = sess.Id(m.Id).Cols("num_issues,num_completeness,num_closed_issues").Update(m); err != nil {
  699. sess.Rollback()
  700. return err
  701. }
  702. rawSql := "UPDATE `issue_user` SET milestone_id = ? WHERE issue_id = ?"
  703. if _, err = sess.Exec(rawSql, m.Id, issue.Id); err != nil {
  704. sess.Rollback()
  705. return err
  706. }
  707. }
  708. return sess.Commit()
  709. }
  710. // DeleteMilestone deletes a milestone.
  711. func DeleteMilestone(m *Milestone) (err error) {
  712. sess := x.NewSession()
  713. defer sess.Close()
  714. if err = sess.Begin(); err != nil {
  715. return err
  716. }
  717. if _, err = sess.Delete(m); err != nil {
  718. sess.Rollback()
  719. return err
  720. }
  721. rawSql := "UPDATE `repository` SET num_milestones = num_milestones - 1 WHERE id = ?"
  722. if _, err = sess.Exec(rawSql, m.RepoId); err != nil {
  723. sess.Rollback()
  724. return err
  725. }
  726. rawSql = "UPDATE `issue` SET milestone_id = 0 WHERE milestone_id = ?"
  727. if _, err = sess.Exec(rawSql, m.Id); err != nil {
  728. sess.Rollback()
  729. return err
  730. }
  731. rawSql = "UPDATE `issue_user` SET milestone_id = 0 WHERE milestone_id = ?"
  732. if _, err = sess.Exec(rawSql, m.Id); err != nil {
  733. sess.Rollback()
  734. return err
  735. }
  736. return sess.Commit()
  737. }
  738. // _________ __
  739. // \_ ___ \ ____ _____ _____ ____ _____/ |_
  740. // / \ \/ / _ \ / \ / \_/ __ \ / \ __\
  741. // \ \___( <_> ) Y Y \ Y Y \ ___/| | \ |
  742. // \______ /\____/|__|_| /__|_| /\___ >___| /__|
  743. // \/ \/ \/ \/ \/
  744. // CommentType defines whether a comment is just a simple comment, an action (like close) or a reference.
  745. type CommentType int
  746. const (
  747. // Plain comment, can be associated with a commit (CommitId > 0) and a line (Line > 0)
  748. COMMENT_TYPE_COMMENT CommentType = iota
  749. COMMENT_TYPE_REOPEN
  750. COMMENT_TYPE_CLOSE
  751. // References.
  752. COMMENT_TYPE_ISSUE
  753. // Reference from some commit (not part of a pull request)
  754. COMMENT_TYPE_COMMIT
  755. // Reference from some pull request
  756. COMMENT_TYPE_PULL
  757. )
  758. // Comment represents a comment in commit and issue page.
  759. type Comment struct {
  760. Id int64
  761. Type CommentType
  762. PosterId int64
  763. Poster *User `xorm:"-"`
  764. IssueId int64
  765. CommitId int64
  766. Line int64
  767. Content string `xorm:"TEXT"`
  768. Created time.Time `xorm:"CREATED"`
  769. }
  770. // CreateComment creates comment of issue or commit.
  771. func CreateComment(userId, repoId, issueId, commitId, line int64, cmtType CommentType, content string, attachments []int64) (*Comment, error) {
  772. sess := x.NewSession()
  773. defer sess.Close()
  774. if err := sess.Begin(); err != nil {
  775. return nil, err
  776. }
  777. comment := &Comment{PosterId: userId, Type: cmtType, IssueId: issueId,
  778. CommitId: commitId, Line: line, Content: content}
  779. if _, err := sess.Insert(comment); err != nil {
  780. sess.Rollback()
  781. return nil, err
  782. }
  783. // Check comment type.
  784. switch cmtType {
  785. case COMMENT_TYPE_COMMENT:
  786. rawSql := "UPDATE `issue` SET num_comments = num_comments + 1 WHERE id = ?"
  787. if _, err := sess.Exec(rawSql, issueId); err != nil {
  788. sess.Rollback()
  789. return nil, err
  790. }
  791. if len(attachments) > 0 {
  792. rawSql = "UPDATE `attachment` SET comment_id = ? WHERE id IN (?)"
  793. astrs := make([]string, 0, len(attachments))
  794. for _, a := range attachments {
  795. astrs = append(astrs, strconv.FormatInt(a, 10))
  796. }
  797. if _, err := sess.Exec(rawSql, comment.Id, strings.Join(astrs, ",")); err != nil {
  798. sess.Rollback()
  799. return nil, err
  800. }
  801. }
  802. case COMMENT_TYPE_REOPEN:
  803. rawSql := "UPDATE `repository` SET num_closed_issues = num_closed_issues - 1 WHERE id = ?"
  804. if _, err := sess.Exec(rawSql, repoId); err != nil {
  805. sess.Rollback()
  806. return nil, err
  807. }
  808. case COMMENT_TYPE_CLOSE:
  809. rawSql := "UPDATE `repository` SET num_closed_issues = num_closed_issues + 1 WHERE id = ?"
  810. if _, err := sess.Exec(rawSql, repoId); err != nil {
  811. sess.Rollback()
  812. return nil, err
  813. }
  814. }
  815. return comment, sess.Commit()
  816. }
  817. // GetCommentById returns the comment with the given id
  818. func GetCommentById(commentId int64) (*Comment, error) {
  819. c := &Comment{Id: commentId}
  820. _, err := x.Get(c)
  821. return c, err
  822. }
  823. func (c *Comment) ContentHtml() template.HTML {
  824. return template.HTML(c.Content)
  825. }
  826. // GetIssueComments returns list of comment by given issue id.
  827. func GetIssueComments(issueId int64) ([]Comment, error) {
  828. comments := make([]Comment, 0, 10)
  829. err := x.Asc("created").Find(&comments, &Comment{IssueId: issueId})
  830. return comments, err
  831. }
  832. // Attachments returns the attachments for this comment.
  833. func (c *Comment) Attachments() []*Attachment {
  834. a, _ := GetAttachmentsByComment(c.Id)
  835. return a
  836. }
  837. func (c *Comment) AfterDelete() {
  838. _, err := DeleteAttachmentsByComment(c.Id, true)
  839. if err != nil {
  840. log.Info("Could not delete files for comment %d on issue #%d: %s", c.Id, c.IssueId, err)
  841. }
  842. }
  843. type Attachment struct {
  844. Id int64
  845. IssueId int64
  846. CommentId int64
  847. Name string
  848. Path string `xorm:"TEXT"`
  849. Created time.Time `xorm:"CREATED"`
  850. }
  851. // CreateAttachment creates a new attachment inside the database and
  852. func CreateAttachment(issueId, commentId int64, name, path string) (*Attachment, error) {
  853. sess := x.NewSession()
  854. defer sess.Close()
  855. if err := sess.Begin(); err != nil {
  856. return nil, err
  857. }
  858. a := &Attachment{IssueId: issueId, CommentId: commentId, Name: name, Path: path}
  859. if _, err := sess.Insert(a); err != nil {
  860. sess.Rollback()
  861. return nil, err
  862. }
  863. return a, sess.Commit()
  864. }
  865. // Attachment returns the attachment by given ID.
  866. func GetAttachmentById(id int64) (*Attachment, error) {
  867. m := &Attachment{Id: id}
  868. has, err := x.Get(m)
  869. if err != nil {
  870. return nil, err
  871. }
  872. if !has {
  873. return nil, ErrAttachmentNotExist
  874. }
  875. return m, nil
  876. }
  877. func GetAttachmentsForIssue(issueId int64) ([]*Attachment, error) {
  878. attachments := make([]*Attachment, 0, 10)
  879. err := x.Where("issue_id = ?", issueId).And("comment_id = 0").Find(&attachments)
  880. return attachments, err
  881. }
  882. // GetAttachmentsByIssue returns a list of attachments for the given issue
  883. func GetAttachmentsByIssue(issueId int64) ([]*Attachment, error) {
  884. attachments := make([]*Attachment, 0, 10)
  885. err := x.Where("issue_id = ?", issueId).And("comment_id > 0").Find(&attachments)
  886. return attachments, err
  887. }
  888. // GetAttachmentsByComment returns a list of attachments for the given comment
  889. func GetAttachmentsByComment(commentId int64) ([]*Attachment, error) {
  890. attachments := make([]*Attachment, 0, 10)
  891. err := x.Where("comment_id = ?", commentId).Find(&attachments)
  892. return attachments, err
  893. }
  894. // DeleteAttachment deletes the given attachment and optionally the associated file.
  895. func DeleteAttachment(a *Attachment, remove bool) error {
  896. _, err := DeleteAttachments([]*Attachment{a}, remove)
  897. return err
  898. }
  899. // DeleteAttachments deletes the given attachments and optionally the associated files.
  900. func DeleteAttachments(attachments []*Attachment, remove bool) (int, error) {
  901. for i, a := range attachments {
  902. if remove {
  903. if err := os.Remove(a.Path); err != nil {
  904. return i, err
  905. }
  906. }
  907. if _, err := x.Delete(a.Id); err != nil {
  908. return i, err
  909. }
  910. }
  911. return len(attachments), nil
  912. }
  913. // DeleteAttachmentsByIssue deletes all attachments associated with the given issue.
  914. func DeleteAttachmentsByIssue(issueId int64, remove bool) (int, error) {
  915. attachments, err := GetAttachmentsByIssue(issueId)
  916. if err != nil {
  917. return 0, err
  918. }
  919. return DeleteAttachments(attachments, remove)
  920. }
  921. // DeleteAttachmentsByComment deletes all attachments associated with the given comment.
  922. func DeleteAttachmentsByComment(commentId int64, remove bool) (int, error) {
  923. attachments, err := GetAttachmentsByComment(commentId)
  924. if err != nil {
  925. return 0, err
  926. }
  927. return DeleteAttachments(attachments, remove)
  928. }