issue.go 30 KB

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