issue.go 27 KB

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