issue.go 29 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115
  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. ClosedDate time.Time
  560. }
  561. func (m *Milestone) BeforeSet(colName string, val xorm.Cell) {
  562. if colName == "deadline" {
  563. t := (*val).(time.Time)
  564. if t.Year() == 9999 {
  565. return
  566. }
  567. m.DeadlineString = t.Format("2006-01-02")
  568. }
  569. }
  570. // CalOpenIssues calculates the open issues of milestone.
  571. func (m *Milestone) CalOpenIssues() {
  572. m.NumOpenIssues = m.NumIssues - m.NumClosedIssues
  573. }
  574. // NewMilestone creates new milestone of repository.
  575. func NewMilestone(m *Milestone) (err error) {
  576. sess := x.NewSession()
  577. defer sess.Close()
  578. if err = sess.Begin(); err != nil {
  579. return err
  580. }
  581. if _, err = sess.Insert(m); err != nil {
  582. sess.Rollback()
  583. return err
  584. }
  585. rawSql := "UPDATE `repository` SET num_milestones = num_milestones + 1 WHERE id = ?"
  586. if _, err = sess.Exec(rawSql, m.RepoID); err != nil {
  587. sess.Rollback()
  588. return err
  589. }
  590. return sess.Commit()
  591. }
  592. // MilestoneById returns the milestone by given ID.
  593. func MilestoneById(id int64) (*Milestone, error) {
  594. m := &Milestone{ID: id}
  595. has, err := x.Get(m)
  596. if err != nil {
  597. return nil, err
  598. } else if !has {
  599. return nil, ErrMilestoneNotExist
  600. }
  601. return m, nil
  602. }
  603. // GetMilestoneByIndex returns the milestone of given repository and index.
  604. func GetMilestoneByIndex(repoId, idx int64) (*Milestone, error) {
  605. m := &Milestone{RepoID: repoId, Index: idx}
  606. has, err := x.Get(m)
  607. if err != nil {
  608. return nil, err
  609. } else if !has {
  610. return nil, ErrMilestoneNotExist
  611. }
  612. return m, nil
  613. }
  614. // GetMilestones returns a list of milestones of given repository and status.
  615. func GetMilestones(repoID int64, page int, isClosed bool) ([]*Milestone, error) {
  616. miles := make([]*Milestone, 0, setting.IssuePagingNum)
  617. sess := x.Where("repo_id=? AND is_closed=?", repoID, isClosed)
  618. if page > 0 {
  619. sess = sess.Limit(setting.IssuePagingNum, (page-1)*setting.IssuePagingNum)
  620. }
  621. return miles, sess.Find(&miles)
  622. }
  623. // UpdateMilestone updates information of given milestone.
  624. func UpdateMilestone(m *Milestone) error {
  625. _, err := x.Id(m.ID).AllCols().Update(m)
  626. return err
  627. }
  628. // CountClosedMilestones returns number of closed milestones in given repository.
  629. func CountClosedMilestones(repoID int64) int64 {
  630. closed, _ := x.Where("repo_id=? AND is_closed=?", repoID, true).Count(new(Milestone))
  631. return closed
  632. }
  633. // MilestoneStats returns number of open and closed milestones of given repository.
  634. func MilestoneStats(repoID int64) (open int64, closed int64) {
  635. open, _ = x.Where("repo_id=? AND is_closed=?", repoID, false).Count(new(Milestone))
  636. return open, CountClosedMilestones(repoID)
  637. }
  638. // ChangeMilestoneStatus changes the milestone open/closed status.
  639. func ChangeMilestoneStatus(m *Milestone, isClosed bool) (err error) {
  640. repo, err := GetRepositoryById(m.RepoID)
  641. if err != nil {
  642. return err
  643. }
  644. sess := x.NewSession()
  645. defer sessionRelease(sess)
  646. if err = sess.Begin(); err != nil {
  647. return err
  648. }
  649. m.IsClosed = isClosed
  650. if err = UpdateMilestone(m); err != nil {
  651. return err
  652. }
  653. repo.NumClosedMilestones = int(CountClosedMilestones(repo.Id))
  654. if _, err = sess.Id(repo.Id).AllCols().Update(repo); err != nil {
  655. return err
  656. }
  657. return sess.Commit()
  658. }
  659. // ChangeMilestoneIssueStats updates the open/closed issues counter and progress
  660. // for the milestone associated witht the given issue.
  661. func ChangeMilestoneIssueStats(issue *Issue) error {
  662. if issue.MilestoneId == 0 {
  663. return nil
  664. }
  665. m, err := MilestoneById(issue.MilestoneId)
  666. if err != nil {
  667. return err
  668. }
  669. if issue.IsClosed {
  670. m.NumOpenIssues--
  671. m.NumClosedIssues++
  672. } else {
  673. m.NumOpenIssues++
  674. m.NumClosedIssues--
  675. }
  676. m.Completeness = m.NumClosedIssues * 100 / m.NumIssues
  677. return UpdateMilestone(m)
  678. }
  679. // ChangeMilestoneAssign changes assignment of milestone for issue.
  680. func ChangeMilestoneAssign(oldMid, mid int64, issue *Issue) (err error) {
  681. sess := x.NewSession()
  682. defer sess.Close()
  683. if err = sess.Begin(); err != nil {
  684. return err
  685. }
  686. if oldMid > 0 {
  687. m, err := MilestoneById(oldMid)
  688. if err != nil {
  689. return err
  690. }
  691. m.NumIssues--
  692. if issue.IsClosed {
  693. m.NumClosedIssues--
  694. }
  695. if m.NumIssues > 0 {
  696. m.Completeness = m.NumClosedIssues * 100 / m.NumIssues
  697. } else {
  698. m.Completeness = 0
  699. }
  700. if _, err = sess.Id(m.ID).Cols("num_issues,num_completeness,num_closed_issues").Update(m); err != nil {
  701. sess.Rollback()
  702. return err
  703. }
  704. rawSql := "UPDATE `issue_user` SET milestone_id = 0 WHERE issue_id = ?"
  705. if _, err = sess.Exec(rawSql, issue.ID); err != nil {
  706. sess.Rollback()
  707. return err
  708. }
  709. }
  710. if mid > 0 {
  711. m, err := MilestoneById(mid)
  712. if err != nil {
  713. return err
  714. }
  715. m.NumIssues++
  716. if issue.IsClosed {
  717. m.NumClosedIssues++
  718. }
  719. if m.NumIssues == 0 {
  720. return ErrWrongIssueCounter
  721. }
  722. m.Completeness = m.NumClosedIssues * 100 / m.NumIssues
  723. if _, err = sess.Id(m.ID).Cols("num_issues,num_completeness,num_closed_issues").Update(m); err != nil {
  724. sess.Rollback()
  725. return err
  726. }
  727. rawSql := "UPDATE `issue_user` SET milestone_id = ? WHERE issue_id = ?"
  728. if _, err = sess.Exec(rawSql, m.ID, issue.ID); err != nil {
  729. sess.Rollback()
  730. return err
  731. }
  732. }
  733. return sess.Commit()
  734. }
  735. // DeleteMilestone deletes a milestone.
  736. func DeleteMilestone(m *Milestone) (err error) {
  737. sess := x.NewSession()
  738. defer sess.Close()
  739. if err = sess.Begin(); err != nil {
  740. return err
  741. }
  742. if _, err = sess.Delete(m); err != nil {
  743. sess.Rollback()
  744. return err
  745. }
  746. rawSql := "UPDATE `repository` SET num_milestones = num_milestones - 1 WHERE id = ?"
  747. if _, err = sess.Exec(rawSql, m.RepoID); err != nil {
  748. sess.Rollback()
  749. return err
  750. }
  751. rawSql = "UPDATE `issue` SET milestone_id = 0 WHERE milestone_id = ?"
  752. if _, err = sess.Exec(rawSql, m.ID); err != nil {
  753. sess.Rollback()
  754. return err
  755. }
  756. rawSql = "UPDATE `issue_user` SET milestone_id = 0 WHERE milestone_id = ?"
  757. if _, err = sess.Exec(rawSql, m.ID); err != nil {
  758. sess.Rollback()
  759. return err
  760. }
  761. return sess.Commit()
  762. }
  763. // _________ __
  764. // \_ ___ \ ____ _____ _____ ____ _____/ |_
  765. // / \ \/ / _ \ / \ / \_/ __ \ / \ __\
  766. // \ \___( <_> ) Y Y \ Y Y \ ___/| | \ |
  767. // \______ /\____/|__|_| /__|_| /\___ >___| /__|
  768. // \/ \/ \/ \/ \/
  769. // CommentType defines whether a comment is just a simple comment, an action (like close) or a reference.
  770. type CommentType int
  771. const (
  772. // Plain comment, can be associated with a commit (CommitId > 0) and a line (Line > 0)
  773. COMMENT_TYPE_COMMENT CommentType = iota
  774. COMMENT_TYPE_REOPEN
  775. COMMENT_TYPE_CLOSE
  776. // References.
  777. COMMENT_TYPE_ISSUE
  778. // Reference from some commit (not part of a pull request)
  779. COMMENT_TYPE_COMMIT
  780. // Reference from some pull request
  781. COMMENT_TYPE_PULL
  782. )
  783. // Comment represents a comment in commit and issue page.
  784. type Comment struct {
  785. Id int64
  786. Type CommentType
  787. PosterId int64
  788. Poster *User `xorm:"-"`
  789. IssueId int64
  790. CommitId int64
  791. Line int64
  792. Content string `xorm:"TEXT"`
  793. Created time.Time `xorm:"CREATED"`
  794. }
  795. // CreateComment creates comment of issue or commit.
  796. func CreateComment(userId, repoId, issueId, commitId, line int64, cmtType CommentType, content string, attachments []int64) (*Comment, error) {
  797. sess := x.NewSession()
  798. defer sessionRelease(sess)
  799. if err := sess.Begin(); err != nil {
  800. return nil, err
  801. }
  802. comment := &Comment{PosterId: userId, Type: cmtType, IssueId: issueId,
  803. CommitId: commitId, Line: line, Content: content}
  804. if _, err := sess.Insert(comment); err != nil {
  805. return nil, err
  806. }
  807. // Check comment type.
  808. switch cmtType {
  809. case COMMENT_TYPE_COMMENT:
  810. rawSql := "UPDATE `issue` SET num_comments = num_comments + 1 WHERE id = ?"
  811. if _, err := sess.Exec(rawSql, issueId); err != nil {
  812. return nil, err
  813. }
  814. if len(attachments) > 0 {
  815. rawSql = "UPDATE `attachment` SET comment_id = ? WHERE id IN (?)"
  816. astrs := make([]string, 0, len(attachments))
  817. for _, a := range attachments {
  818. astrs = append(astrs, strconv.FormatInt(a, 10))
  819. }
  820. if _, err := sess.Exec(rawSql, comment.Id, strings.Join(astrs, ",")); err != nil {
  821. return nil, err
  822. }
  823. }
  824. case COMMENT_TYPE_REOPEN:
  825. rawSql := "UPDATE `repository` SET num_closed_issues = num_closed_issues - 1 WHERE id = ?"
  826. if _, err := sess.Exec(rawSql, repoId); err != nil {
  827. return nil, err
  828. }
  829. case COMMENT_TYPE_CLOSE:
  830. rawSql := "UPDATE `repository` SET num_closed_issues = num_closed_issues + 1 WHERE id = ?"
  831. if _, err := sess.Exec(rawSql, repoId); err != nil {
  832. return nil, err
  833. }
  834. }
  835. return comment, sess.Commit()
  836. }
  837. // GetCommentById returns the comment with the given id
  838. func GetCommentById(commentId int64) (*Comment, error) {
  839. c := &Comment{Id: commentId}
  840. _, err := x.Get(c)
  841. return c, err
  842. }
  843. func (c *Comment) ContentHtml() template.HTML {
  844. return template.HTML(c.Content)
  845. }
  846. // GetIssueComments returns list of comment by given issue id.
  847. func GetIssueComments(issueId int64) ([]Comment, error) {
  848. comments := make([]Comment, 0, 10)
  849. err := x.Asc("created").Find(&comments, &Comment{IssueId: issueId})
  850. return comments, err
  851. }
  852. // Attachments returns the attachments for this comment.
  853. func (c *Comment) Attachments() []*Attachment {
  854. a, _ := GetAttachmentsByComment(c.Id)
  855. return a
  856. }
  857. func (c *Comment) AfterDelete() {
  858. _, err := DeleteAttachmentsByComment(c.Id, true)
  859. if err != nil {
  860. log.Info("Could not delete files for comment %d on issue #%d: %s", c.Id, c.IssueId, err)
  861. }
  862. }
  863. type Attachment struct {
  864. Id int64
  865. IssueId int64
  866. CommentId int64
  867. Name string
  868. Path string `xorm:"TEXT"`
  869. Created time.Time `xorm:"CREATED"`
  870. }
  871. // CreateAttachment creates a new attachment inside the database and
  872. func CreateAttachment(issueId, commentId int64, name, path string) (*Attachment, error) {
  873. sess := x.NewSession()
  874. defer sess.Close()
  875. if err := sess.Begin(); err != nil {
  876. return nil, err
  877. }
  878. a := &Attachment{IssueId: issueId, CommentId: commentId, Name: name, Path: path}
  879. if _, err := sess.Insert(a); err != nil {
  880. sess.Rollback()
  881. return nil, err
  882. }
  883. return a, sess.Commit()
  884. }
  885. // Attachment returns the attachment by given ID.
  886. func GetAttachmentById(id int64) (*Attachment, error) {
  887. m := &Attachment{Id: id}
  888. has, err := x.Get(m)
  889. if err != nil {
  890. return nil, err
  891. }
  892. if !has {
  893. return nil, ErrAttachmentNotExist
  894. }
  895. return m, nil
  896. }
  897. func GetAttachmentsForIssue(issueId int64) ([]*Attachment, error) {
  898. attachments := make([]*Attachment, 0, 10)
  899. err := x.Where("issue_id = ?", issueId).And("comment_id = 0").Find(&attachments)
  900. return attachments, err
  901. }
  902. // GetAttachmentsByIssue returns a list of attachments for the given issue
  903. func GetAttachmentsByIssue(issueId int64) ([]*Attachment, error) {
  904. attachments := make([]*Attachment, 0, 10)
  905. err := x.Where("issue_id = ?", issueId).And("comment_id > 0").Find(&attachments)
  906. return attachments, err
  907. }
  908. // GetAttachmentsByComment returns a list of attachments for the given comment
  909. func GetAttachmentsByComment(commentId int64) ([]*Attachment, error) {
  910. attachments := make([]*Attachment, 0, 10)
  911. err := x.Where("comment_id = ?", commentId).Find(&attachments)
  912. return attachments, err
  913. }
  914. // DeleteAttachment deletes the given attachment and optionally the associated file.
  915. func DeleteAttachment(a *Attachment, remove bool) error {
  916. _, err := DeleteAttachments([]*Attachment{a}, remove)
  917. return err
  918. }
  919. // DeleteAttachments deletes the given attachments and optionally the associated files.
  920. func DeleteAttachments(attachments []*Attachment, remove bool) (int, error) {
  921. for i, a := range attachments {
  922. if remove {
  923. if err := os.Remove(a.Path); err != nil {
  924. return i, err
  925. }
  926. }
  927. if _, err := x.Delete(a.Id); err != nil {
  928. return i, err
  929. }
  930. }
  931. return len(attachments), nil
  932. }
  933. // DeleteAttachmentsByIssue deletes all attachments associated with the given issue.
  934. func DeleteAttachmentsByIssue(issueId int64, remove bool) (int, error) {
  935. attachments, err := GetAttachmentsByIssue(issueId)
  936. if err != nil {
  937. return 0, err
  938. }
  939. return DeleteAttachments(attachments, remove)
  940. }
  941. // DeleteAttachmentsByComment deletes all attachments associated with the given comment.
  942. func DeleteAttachmentsByComment(commentId int64, remove bool) (int, error) {
  943. attachments, err := GetAttachmentsByComment(commentId)
  944. if err != nil {
  945. return 0, err
  946. }
  947. return DeleteAttachments(attachments, remove)
  948. }