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

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