issue.go 32 KB

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