You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

issue.go 30KB

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