issue.go 30 KB

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