issue.go 29 KB

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