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.

1998 lines
52 KiB

10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
9 years ago
9 years ago
9 years ago
9 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
9 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
9 years ago
9 years ago
9 years ago
  1. // Copyright 2014 The Gogs Authors. All rights reserved.
  2. // Use of this source code is governed by a MIT-style
  3. // license that can be found in the LICENSE file.
  4. package models
  5. import (
  6. "bytes"
  7. "errors"
  8. "fmt"
  9. "io"
  10. "io/ioutil"
  11. "mime/multipart"
  12. "os"
  13. "path"
  14. "strings"
  15. "time"
  16. "github.com/Unknwon/com"
  17. "github.com/go-xorm/xorm"
  18. "github.com/gogits/gogs/modules/base"
  19. "github.com/gogits/gogs/modules/git"
  20. "github.com/gogits/gogs/modules/log"
  21. "github.com/gogits/gogs/modules/process"
  22. "github.com/gogits/gogs/modules/setting"
  23. gouuid "github.com/gogits/gogs/modules/uuid"
  24. )
  25. var (
  26. ErrWrongIssueCounter = errors.New("Invalid number of issues for this milestone")
  27. ErrAttachmentNotLinked = errors.New("Attachment does not belong to this issue")
  28. ErrMissingIssueNumber = errors.New("No issue number specified")
  29. )
  30. // Issue represents an issue or pull request of repository.
  31. type Issue struct {
  32. ID int64 `xorm:"pk autoincr"`
  33. RepoID int64 `xorm:"INDEX"`
  34. Index int64 // Index in one repository.
  35. Name string
  36. Repo *Repository `xorm:"-"`
  37. PosterID int64
  38. Poster *User `xorm:"-"`
  39. Labels []*Label `xorm:"-"`
  40. MilestoneID int64
  41. Milestone *Milestone `xorm:"-"`
  42. AssigneeID int64
  43. Assignee *User `xorm:"-"`
  44. IsRead bool `xorm:"-"`
  45. IsPull bool // Indicates whether is a pull request or not.
  46. *PullRequest `xorm:"-"`
  47. IsClosed bool
  48. Content string `xorm:"TEXT"`
  49. RenderedContent string `xorm:"-"`
  50. Priority int
  51. NumComments int
  52. Deadline time.Time
  53. Created time.Time `xorm:"CREATED"`
  54. Updated time.Time `xorm:"UPDATED"`
  55. Attachments []*Attachment `xorm:"-"`
  56. Comments []*Comment `xorm:"-"`
  57. }
  58. func (i *Issue) AfterSet(colName string, _ xorm.Cell) {
  59. var err error
  60. switch colName {
  61. case "id":
  62. i.Attachments, err = GetAttachmentsByIssueID(i.ID)
  63. if err != nil {
  64. log.Error(3, "GetAttachmentsByIssueID[%d]: %v", i.ID, err)
  65. }
  66. i.Comments, err = GetCommentsByIssueID(i.ID)
  67. if err != nil {
  68. log.Error(3, "GetCommentsByIssueID[%d]: %v", i.ID, err)
  69. }
  70. case "milestone_id":
  71. if i.MilestoneID == 0 {
  72. return
  73. }
  74. i.Milestone, err = GetMilestoneByID(i.MilestoneID)
  75. if err != nil {
  76. log.Error(3, "GetMilestoneById[%d]: %v", i.ID, err)
  77. }
  78. case "assignee_id":
  79. if i.AssigneeID == 0 {
  80. return
  81. }
  82. i.Assignee, err = GetUserByID(i.AssigneeID)
  83. if err != nil {
  84. log.Error(3, "GetUserByID[%d]: %v", i.ID, err)
  85. }
  86. case "is_pull":
  87. if !i.IsPull {
  88. return
  89. }
  90. i.PullRequest, err = GetPullRequestByPullID(i.ID)
  91. if err != nil {
  92. log.Error(3, "GetPullRequestByPullID[%d]: %v", i.ID, err)
  93. }
  94. case "created":
  95. i.Created = regulateTimeZone(i.Created)
  96. }
  97. }
  98. // HashTag returns unique hash tag for issue.
  99. func (i *Issue) HashTag() string {
  100. return "issue-" + com.ToStr(i.ID)
  101. }
  102. // IsPoster returns true if given user by ID is the poster.
  103. func (i *Issue) IsPoster(uid int64) bool {
  104. return i.PosterID == uid
  105. }
  106. func (i *Issue) GetPoster() (err error) {
  107. i.Poster, err = GetUserByID(i.PosterID)
  108. if IsErrUserNotExist(err) {
  109. i.PosterID = -1
  110. i.Poster = NewFakeUser()
  111. return nil
  112. }
  113. return err
  114. }
  115. func (i *Issue) hasLabel(e Engine, labelID int64) bool {
  116. return hasIssueLabel(e, i.ID, labelID)
  117. }
  118. // HasLabel returns true if issue has been labeled by given ID.
  119. func (i *Issue) HasLabel(labelID int64) bool {
  120. return i.hasLabel(x, labelID)
  121. }
  122. func (i *Issue) addLabel(e *xorm.Session, label *Label) error {
  123. return newIssueLabel(e, i, label)
  124. }
  125. // AddLabel adds new label to issue by given ID.
  126. func (i *Issue) AddLabel(label *Label) (err error) {
  127. sess := x.NewSession()
  128. defer sessionRelease(sess)
  129. if err = sess.Begin(); err != nil {
  130. return err
  131. }
  132. if err = i.addLabel(sess, label); err != nil {
  133. return err
  134. }
  135. return sess.Commit()
  136. }
  137. func (i *Issue) getLabels(e Engine) (err error) {
  138. if len(i.Labels) > 0 {
  139. return nil
  140. }
  141. i.Labels, err = getLabelsByIssueID(e, i.ID)
  142. if err != nil {
  143. return fmt.Errorf("getLabelsByIssueID: %v", err)
  144. }
  145. return nil
  146. }
  147. // GetLabels retrieves all labels of issue and assign to corresponding field.
  148. func (i *Issue) GetLabels() error {
  149. return i.getLabels(x)
  150. }
  151. func (i *Issue) removeLabel(e *xorm.Session, label *Label) error {
  152. return deleteIssueLabel(e, i, label)
  153. }
  154. // RemoveLabel removes a label from issue by given ID.
  155. func (i *Issue) RemoveLabel(label *Label) (err error) {
  156. sess := x.NewSession()
  157. defer sessionRelease(sess)
  158. if err = sess.Begin(); err != nil {
  159. return err
  160. }
  161. if err = i.removeLabel(sess, label); err != nil {
  162. return err
  163. }
  164. return sess.Commit()
  165. }
  166. func (i *Issue) ClearLabels() (err error) {
  167. sess := x.NewSession()
  168. defer sessionRelease(sess)
  169. if err = sess.Begin(); err != nil {
  170. return err
  171. }
  172. if err = i.getLabels(sess); err != nil {
  173. return err
  174. }
  175. for idx := range i.Labels {
  176. if err = i.removeLabel(sess, i.Labels[idx]); err != nil {
  177. return err
  178. }
  179. }
  180. return sess.Commit()
  181. }
  182. func (i *Issue) GetAssignee() (err error) {
  183. if i.AssigneeID == 0 || i.Assignee != nil {
  184. return nil
  185. }
  186. i.Assignee, err = GetUserByID(i.AssigneeID)
  187. if IsErrUserNotExist(err) {
  188. return nil
  189. }
  190. return err
  191. }
  192. // ReadBy sets issue to be read by given user.
  193. func (i *Issue) ReadBy(uid int64) error {
  194. return UpdateIssueUserByRead(uid, i.ID)
  195. }
  196. func (i *Issue) changeStatus(e *xorm.Session, doer *User, isClosed bool) (err error) {
  197. if i.IsClosed == isClosed {
  198. return nil
  199. }
  200. i.IsClosed = isClosed
  201. if err = updateIssue(e, i); err != nil {
  202. return err
  203. } else if err = updateIssueUsersByStatus(e, i.ID, isClosed); err != nil {
  204. return err
  205. }
  206. // Update labels.
  207. if err = i.getLabels(e); err != nil {
  208. return err
  209. }
  210. for idx := range i.Labels {
  211. if i.IsClosed {
  212. i.Labels[idx].NumClosedIssues++
  213. } else {
  214. i.Labels[idx].NumClosedIssues--
  215. }
  216. if err = updateLabel(e, i.Labels[idx]); err != nil {
  217. return err
  218. }
  219. }
  220. // Update milestone.
  221. if err = changeMilestoneIssueStats(e, i); err != nil {
  222. return err
  223. }
  224. // New action comment.
  225. if _, err = createStatusComment(e, doer, i.Repo, i); err != nil {
  226. return err
  227. }
  228. return nil
  229. }
  230. // ChangeStatus changes issue status to open/closed.
  231. func (i *Issue) ChangeStatus(doer *User, isClosed bool) (err error) {
  232. sess := x.NewSession()
  233. defer sessionRelease(sess)
  234. if err = sess.Begin(); err != nil {
  235. return err
  236. }
  237. if err = i.changeStatus(sess, doer, isClosed); err != nil {
  238. return err
  239. }
  240. return sess.Commit()
  241. }
  242. // It's caller's responsibility to create action.
  243. func newIssue(e *xorm.Session, repo *Repository, issue *Issue, labelIDs []int64, uuids []string, isPull bool) (err error) {
  244. if _, err = e.Insert(issue); err != nil {
  245. return err
  246. }
  247. if isPull {
  248. _, err = e.Exec("UPDATE `repository` SET num_pulls=num_pulls+1 WHERE id=?", issue.RepoID)
  249. } else {
  250. _, err = e.Exec("UPDATE `repository` SET num_issues=num_issues+1 WHERE id=?", issue.RepoID)
  251. }
  252. if err != nil {
  253. return err
  254. }
  255. var label *Label
  256. for _, id := range labelIDs {
  257. if id == 0 {
  258. continue
  259. }
  260. label, err = getLabelByID(e, id)
  261. if err != nil {
  262. return err
  263. }
  264. if err = issue.addLabel(e, label); err != nil {
  265. return fmt.Errorf("addLabel: %v", err)
  266. }
  267. }
  268. if issue.MilestoneID > 0 {
  269. if err = changeMilestoneAssign(e, 0, issue); err != nil {
  270. return err
  271. }
  272. }
  273. if err = newIssueUsers(e, repo, issue); err != nil {
  274. return err
  275. }
  276. // Check attachments.
  277. attachments := make([]*Attachment, 0, len(uuids))
  278. for _, uuid := range uuids {
  279. attach, err := getAttachmentByUUID(e, uuid)
  280. if err != nil {
  281. if IsErrAttachmentNotExist(err) {
  282. continue
  283. }
  284. return fmt.Errorf("getAttachmentByUUID[%s]: %v", uuid, err)
  285. }
  286. attachments = append(attachments, attach)
  287. }
  288. for i := range attachments {
  289. attachments[i].IssueID = issue.ID
  290. // No assign value could be 0, so ignore AllCols().
  291. if _, err = e.Id(attachments[i].ID).Update(attachments[i]); err != nil {
  292. return fmt.Errorf("update attachment[%d]: %v", attachments[i].ID, err)
  293. }
  294. }
  295. return nil
  296. }
  297. // NewIssue creates new issue with labels for repository.
  298. func NewIssue(repo *Repository, issue *Issue, labelIDs []int64, uuids []string) (err error) {
  299. sess := x.NewSession()
  300. defer sessionRelease(sess)
  301. if err = sess.Begin(); err != nil {
  302. return err
  303. }
  304. if err = newIssue(sess, repo, issue, labelIDs, uuids, false); err != nil {
  305. return fmt.Errorf("newIssue: %v", err)
  306. }
  307. // Notify watchers.
  308. act := &Action{
  309. ActUserID: issue.Poster.Id,
  310. ActUserName: issue.Poster.Name,
  311. ActEmail: issue.Poster.Email,
  312. OpType: CREATE_ISSUE,
  313. Content: fmt.Sprintf("%d|%s", issue.Index, issue.Name),
  314. RepoID: repo.ID,
  315. RepoUserName: repo.Owner.Name,
  316. RepoName: repo.Name,
  317. IsPrivate: repo.IsPrivate,
  318. }
  319. if err = notifyWatchers(sess, act); err != nil {
  320. return err
  321. }
  322. return sess.Commit()
  323. }
  324. // GetIssueByRef returns an Issue specified by a GFM reference.
  325. // See https://help.github.com/articles/writing-on-github#references for more information on the syntax.
  326. func GetIssueByRef(ref string) (*Issue, error) {
  327. n := strings.IndexByte(ref, byte('#'))
  328. if n == -1 {
  329. return nil, ErrMissingIssueNumber
  330. }
  331. index, err := com.StrTo(ref[n+1:]).Int64()
  332. if err != nil {
  333. return nil, err
  334. }
  335. repo, err := GetRepositoryByRef(ref[:n])
  336. if err != nil {
  337. return nil, err
  338. }
  339. issue, err := GetIssueByIndex(repo.ID, index)
  340. if err != nil {
  341. return nil, err
  342. }
  343. issue.Repo = repo
  344. return issue, nil
  345. }
  346. // GetIssueByIndex returns issue by given index in repository.
  347. func GetIssueByIndex(repoID, index int64) (*Issue, error) {
  348. issue := &Issue{
  349. RepoID: repoID,
  350. Index: index,
  351. }
  352. has, err := x.Get(issue)
  353. if err != nil {
  354. return nil, err
  355. } else if !has {
  356. return nil, ErrIssueNotExist{0, repoID, index}
  357. }
  358. return issue, nil
  359. }
  360. // GetIssueByID returns an issue by given ID.
  361. func GetIssueByID(id int64) (*Issue, error) {
  362. issue := new(Issue)
  363. has, err := x.Id(id).Get(issue)
  364. if err != nil {
  365. return nil, err
  366. } else if !has {
  367. return nil, ErrIssueNotExist{id, 0, 0}
  368. }
  369. return issue, nil
  370. }
  371. type IssuesOptions struct {
  372. UserID int64
  373. AssigneeID int64
  374. RepoID int64
  375. PosterID int64
  376. MilestoneID int64
  377. RepoIDs []int64
  378. Page int
  379. IsClosed bool
  380. IsMention bool
  381. IsPull bool
  382. Labels string
  383. SortType string
  384. }
  385. // Issues returns a list of issues by given conditions.
  386. func Issues(opts *IssuesOptions) ([]*Issue, error) {
  387. sess := x.Limit(setting.IssuePagingNum, (opts.Page-1)*setting.IssuePagingNum)
  388. if opts.RepoID > 0 {
  389. sess.Where("issue.repo_id=?", opts.RepoID).And("issue.is_closed=?", opts.IsClosed)
  390. } else if opts.RepoIDs != nil {
  391. // In case repository IDs are provided but actually no repository has issue.
  392. if len(opts.RepoIDs) == 0 {
  393. return make([]*Issue, 0), nil
  394. }
  395. sess.Where("issue.repo_id IN ("+strings.Join(base.Int64sToStrings(opts.RepoIDs), ",")+")").And("issue.is_closed=?", opts.IsClosed)
  396. } else {
  397. sess.Where("issue.is_closed=?", opts.IsClosed)
  398. }
  399. if opts.AssigneeID > 0 {
  400. sess.And("issue.assignee_id=?", opts.AssigneeID)
  401. } else if opts.PosterID > 0 {
  402. sess.And("issue.poster_id=?", opts.PosterID)
  403. }
  404. if opts.MilestoneID > 0 {
  405. sess.And("issue.milestone_id=?", opts.MilestoneID)
  406. }
  407. sess.And("issue.is_pull=?", opts.IsPull)
  408. switch opts.SortType {
  409. case "oldest":
  410. sess.Asc("created")
  411. case "recentupdate":
  412. sess.Desc("updated")
  413. case "leastupdate":
  414. sess.Asc("updated")
  415. case "mostcomment":
  416. sess.Desc("num_comments")
  417. case "leastcomment":
  418. sess.Asc("num_comments")
  419. case "priority":
  420. sess.Desc("priority")
  421. default:
  422. sess.Desc("created")
  423. }
  424. labelIDs := base.StringsToInt64s(strings.Split(opts.Labels, ","))
  425. if len(labelIDs) > 0 {
  426. validJoin := false
  427. queryStr := "issue.id=issue_label.issue_id"
  428. for _, id := range labelIDs {
  429. if id == 0 {
  430. continue
  431. }
  432. validJoin = true
  433. queryStr += " AND issue_label.label_id=" + com.ToStr(id)
  434. }
  435. if validJoin {
  436. sess.Join("INNER", "issue_label", queryStr)
  437. }
  438. }
  439. if opts.IsMention {
  440. queryStr := "issue.id=issue_user.issue_id AND issue_user.is_mentioned=1"
  441. if opts.UserID > 0 {
  442. queryStr += " AND issue_user.uid=" + com.ToStr(opts.UserID)
  443. }
  444. sess.Join("INNER", "issue_user", queryStr)
  445. }
  446. issues := make([]*Issue, 0, setting.IssuePagingNum)
  447. return issues, sess.Find(&issues)
  448. }
  449. type IssueStatus int
  450. const (
  451. IS_OPEN = iota + 1
  452. IS_CLOSE
  453. )
  454. // GetIssueCountByPoster returns number of issues of repository by poster.
  455. func GetIssueCountByPoster(uid, rid int64, isClosed bool) int64 {
  456. count, _ := x.Where("repo_id=?", rid).And("poster_id=?", uid).And("is_closed=?", isClosed).Count(new(Issue))
  457. return count
  458. }
  459. // .___ ____ ___
  460. // | | ______ ________ __ ____ | | \______ ___________
  461. // | |/ ___// ___/ | \_/ __ \| | / ___// __ \_ __ \
  462. // | |\___ \ \___ \| | /\ ___/| | /\___ \\ ___/| | \/
  463. // |___/____ >____ >____/ \___ >______//____ >\___ >__|
  464. // \/ \/ \/ \/ \/
  465. // IssueUser represents an issue-user relation.
  466. type IssueUser struct {
  467. ID int64 `xorm:"pk autoincr"`
  468. UID int64 `xorm:"uid INDEX"` // User ID.
  469. IssueID int64
  470. RepoID int64 `xorm:"INDEX"`
  471. MilestoneID int64
  472. IsRead bool
  473. IsAssigned bool
  474. IsMentioned bool
  475. IsPoster bool
  476. IsClosed bool
  477. }
  478. func newIssueUsers(e *xorm.Session, repo *Repository, issue *Issue) error {
  479. users, err := repo.GetAssignees()
  480. if err != nil {
  481. return err
  482. }
  483. iu := &IssueUser{
  484. IssueID: issue.ID,
  485. RepoID: repo.ID,
  486. }
  487. // Poster can be anyone.
  488. isNeedAddPoster := true
  489. for _, u := range users {
  490. iu.ID = 0
  491. iu.UID = u.Id
  492. iu.IsPoster = iu.UID == issue.PosterID
  493. if isNeedAddPoster && iu.IsPoster {
  494. isNeedAddPoster = false
  495. }
  496. iu.IsAssigned = iu.UID == issue.AssigneeID
  497. if _, err = e.Insert(iu); err != nil {
  498. return err
  499. }
  500. }
  501. if isNeedAddPoster {
  502. iu.ID = 0
  503. iu.UID = issue.PosterID
  504. iu.IsPoster = true
  505. if _, err = e.Insert(iu); err != nil {
  506. return err
  507. }
  508. }
  509. return nil
  510. }
  511. // NewIssueUsers adds new issue-user relations for new issue of repository.
  512. func NewIssueUsers(repo *Repository, issue *Issue) (err error) {
  513. sess := x.NewSession()
  514. defer sessionRelease(sess)
  515. if err = sess.Begin(); err != nil {
  516. return err
  517. }
  518. if err = newIssueUsers(sess, repo, issue); err != nil {
  519. return err
  520. }
  521. return sess.Commit()
  522. }
  523. // PairsContains returns true when pairs list contains given issue.
  524. func PairsContains(ius []*IssueUser, issueId, uid int64) int {
  525. for i := range ius {
  526. if ius[i].IssueID == issueId &&
  527. ius[i].UID == uid {
  528. return i
  529. }
  530. }
  531. return -1
  532. }
  533. // GetIssueUsers returns issue-user pairs by given repository and user.
  534. func GetIssueUsers(rid, uid int64, isClosed bool) ([]*IssueUser, error) {
  535. ius := make([]*IssueUser, 0, 10)
  536. err := x.Where("is_closed=?", isClosed).Find(&ius, &IssueUser{RepoID: rid, UID: uid})
  537. return ius, err
  538. }
  539. // GetIssueUserPairsByRepoIds returns issue-user pairs by given repository IDs.
  540. func GetIssueUserPairsByRepoIds(rids []int64, isClosed bool, page int) ([]*IssueUser, error) {
  541. if len(rids) == 0 {
  542. return []*IssueUser{}, nil
  543. }
  544. buf := bytes.NewBufferString("")
  545. for _, rid := range rids {
  546. buf.WriteString("repo_id=")
  547. buf.WriteString(com.ToStr(rid))
  548. buf.WriteString(" OR ")
  549. }
  550. cond := strings.TrimSuffix(buf.String(), " OR ")
  551. ius := make([]*IssueUser, 0, 10)
  552. sess := x.Limit(20, (page-1)*20).Where("is_closed=?", isClosed)
  553. if len(cond) > 0 {
  554. sess.And(cond)
  555. }
  556. err := sess.Find(&ius)
  557. return ius, err
  558. }
  559. // GetIssueUserPairsByMode returns issue-user pairs by given repository and user.
  560. func GetIssueUserPairsByMode(uid, rid int64, isClosed bool, page, filterMode int) ([]*IssueUser, error) {
  561. ius := make([]*IssueUser, 0, 10)
  562. sess := x.Limit(20, (page-1)*20).Where("uid=?", uid).And("is_closed=?", isClosed)
  563. if rid > 0 {
  564. sess.And("repo_id=?", rid)
  565. }
  566. switch filterMode {
  567. case FM_ASSIGN:
  568. sess.And("is_assigned=?", true)
  569. case FM_CREATE:
  570. sess.And("is_poster=?", true)
  571. default:
  572. return ius, nil
  573. }
  574. err := sess.Find(&ius)
  575. return ius, err
  576. }
  577. // IssueStats represents issue statistic information.
  578. type IssueStats struct {
  579. OpenCount, ClosedCount int64
  580. AllCount int64
  581. AssignCount int64
  582. CreateCount int64
  583. MentionCount int64
  584. }
  585. // Filter modes.
  586. const (
  587. FM_ALL = iota
  588. FM_ASSIGN
  589. FM_CREATE
  590. FM_MENTION
  591. )
  592. func parseCountResult(results []map[string][]byte) int64 {
  593. if len(results) == 0 {
  594. return 0
  595. }
  596. for _, result := range results[0] {
  597. return com.StrTo(string(result)).MustInt64()
  598. }
  599. return 0
  600. }
  601. type IssueStatsOptions struct {
  602. RepoID int64
  603. UserID int64
  604. LabelID int64
  605. MilestoneID int64
  606. AssigneeID int64
  607. FilterMode int
  608. IsPull bool
  609. }
  610. // GetIssueStats returns issue statistic information by given conditions.
  611. func GetIssueStats(opts *IssueStatsOptions) *IssueStats {
  612. stats := &IssueStats{}
  613. queryStr := "SELECT COUNT(*) FROM `issue` "
  614. if opts.LabelID > 0 {
  615. queryStr += "INNER JOIN `issue_label` ON `issue`.id=`issue_label`.issue_id AND `issue_label`.label_id=" + com.ToStr(opts.LabelID)
  616. }
  617. baseCond := " WHERE issue.repo_id=" + com.ToStr(opts.RepoID) + " AND issue.is_closed=?"
  618. if opts.MilestoneID > 0 {
  619. baseCond += " AND issue.milestone_id=" + com.ToStr(opts.MilestoneID)
  620. }
  621. if opts.AssigneeID > 0 {
  622. baseCond += " AND assignee_id=" + com.ToStr(opts.AssigneeID)
  623. }
  624. if opts.IsPull {
  625. baseCond += " AND issue.is_pull=1"
  626. } else {
  627. baseCond += " AND issue.is_pull=0"
  628. }
  629. switch opts.FilterMode {
  630. case FM_ALL, FM_ASSIGN:
  631. results, _ := x.Query(queryStr+baseCond, false)
  632. stats.OpenCount = parseCountResult(results)
  633. results, _ = x.Query(queryStr+baseCond, true)
  634. stats.ClosedCount = parseCountResult(results)
  635. case FM_CREATE:
  636. baseCond += " AND poster_id=?"
  637. results, _ := x.Query(queryStr+baseCond, false, opts.UserID)
  638. stats.OpenCount = parseCountResult(results)
  639. results, _ = x.Query(queryStr+baseCond, true, opts.UserID)
  640. stats.ClosedCount = parseCountResult(results)
  641. case FM_MENTION:
  642. queryStr += " INNER JOIN `issue_user` ON `issue`.id=`issue_user`.issue_id"
  643. baseCond += " AND `issue_user`.uid=? AND `issue_user`.is_mentioned=?"
  644. results, _ := x.Query(queryStr+baseCond, false, opts.UserID, true)
  645. stats.OpenCount = parseCountResult(results)
  646. results, _ = x.Query(queryStr+baseCond, true, opts.UserID, true)
  647. stats.ClosedCount = parseCountResult(results)
  648. }
  649. return stats
  650. }
  651. // GetUserIssueStats returns issue statistic information for dashboard by given conditions.
  652. func GetUserIssueStats(repoID, uid int64, repoIDs []int64, filterMode int, isPull bool) *IssueStats {
  653. stats := &IssueStats{}
  654. queryStr := "SELECT COUNT(*) FROM `issue` "
  655. baseCond := " WHERE issue.is_closed=?"
  656. if repoID > 0 {
  657. baseCond += " AND issue.repo_id=" + com.ToStr(repoID)
  658. } else {
  659. baseCond += " AND issue.repo_id IN (" + strings.Join(base.Int64sToStrings(repoIDs), ",") + ")"
  660. }
  661. if isPull {
  662. baseCond += " AND issue.is_pull=1"
  663. } else {
  664. baseCond += " AND issue.is_pull=0"
  665. }
  666. results, _ := x.Query(queryStr+baseCond+" AND assignee_id=?", false, uid)
  667. stats.AssignCount = parseCountResult(results)
  668. results, _ = x.Query(queryStr+baseCond+" AND poster_id=?", false, uid)
  669. stats.CreateCount = parseCountResult(results)
  670. switch filterMode {
  671. case FM_ASSIGN:
  672. baseCond += " AND assignee_id=" + com.ToStr(uid)
  673. case FM_CREATE:
  674. baseCond += " AND poster_id=" + com.ToStr(uid)
  675. }
  676. results, _ = x.Query(queryStr+baseCond, false)
  677. stats.OpenCount = parseCountResult(results)
  678. results, _ = x.Query(queryStr+baseCond, true)
  679. stats.ClosedCount = parseCountResult(results)
  680. return stats
  681. }
  682. // GetRepoIssueStats returns number of open and closed repository issues by given filter mode.
  683. func GetRepoIssueStats(repoID, uid int64, filterMode int, isPull bool) (numOpen int64, numClosed int64) {
  684. queryStr := "SELECT COUNT(*) FROM `issue` "
  685. baseCond := " WHERE issue.repo_id=? AND issue.is_closed=?"
  686. if isPull {
  687. baseCond += " AND issue.is_pull=1"
  688. } else {
  689. baseCond += " AND issue.is_pull=0"
  690. }
  691. switch filterMode {
  692. case FM_ASSIGN:
  693. baseCond += " AND assignee_id=" + com.ToStr(uid)
  694. case FM_CREATE:
  695. baseCond += " AND poster_id=" + com.ToStr(uid)
  696. }
  697. results, _ := x.Query(queryStr+baseCond, repoID, false)
  698. numOpen = parseCountResult(results)
  699. results, _ = x.Query(queryStr+baseCond, repoID, true)
  700. numClosed = parseCountResult(results)
  701. return numOpen, numClosed
  702. }
  703. func updateIssue(e Engine, issue *Issue) error {
  704. _, err := e.Id(issue.ID).AllCols().Update(issue)
  705. return err
  706. }
  707. // UpdateIssue updates information of issue.
  708. func UpdateIssue(issue *Issue) error {
  709. return updateIssue(x, issue)
  710. }
  711. func updateIssueUsersByStatus(e Engine, issueID int64, isClosed bool) error {
  712. _, err := e.Exec("UPDATE `issue_user` SET is_closed=? WHERE issue_id=?", isClosed, issueID)
  713. return err
  714. }
  715. // UpdateIssueUsersByStatus updates issue-user relations by issue status.
  716. func UpdateIssueUsersByStatus(issueID int64, isClosed bool) error {
  717. return updateIssueUsersByStatus(x, issueID, isClosed)
  718. }
  719. func updateIssueUserByAssignee(e *xorm.Session, issue *Issue) (err error) {
  720. if _, err = e.Exec("UPDATE `issue_user` SET is_assigned=? WHERE issue_id=?", false, issue.ID); err != nil {
  721. return err
  722. }
  723. // Assignee ID equals to 0 means clear assignee.
  724. if issue.AssigneeID > 0 {
  725. if _, err = e.Exec("UPDATE `issue_user` SET is_assigned=? WHERE uid=? AND issue_id=?", true, issue.AssigneeID, issue.ID); err != nil {
  726. return err
  727. }
  728. }
  729. return updateIssue(e, issue)
  730. }
  731. // UpdateIssueUserByAssignee updates issue-user relation for assignee.
  732. func UpdateIssueUserByAssignee(issue *Issue) (err error) {
  733. sess := x.NewSession()
  734. defer sessionRelease(sess)
  735. if err = sess.Begin(); err != nil {
  736. return err
  737. }
  738. if err = updateIssueUserByAssignee(sess, issue); err != nil {
  739. return err
  740. }
  741. return sess.Commit()
  742. }
  743. // UpdateIssueUserByRead updates issue-user relation for reading.
  744. func UpdateIssueUserByRead(uid, issueID int64) error {
  745. _, err := x.Exec("UPDATE `issue_user` SET is_read=? WHERE uid=? AND issue_id=?", true, uid, issueID)
  746. return err
  747. }
  748. // UpdateIssueUsersByMentions updates issue-user pairs by mentioning.
  749. func UpdateIssueUsersByMentions(uids []int64, iid int64) error {
  750. for _, uid := range uids {
  751. iu := &IssueUser{UID: uid, IssueID: iid}
  752. has, err := x.Get(iu)
  753. if err != nil {
  754. return err
  755. }
  756. iu.IsMentioned = true
  757. if has {
  758. _, err = x.Id(iu.ID).AllCols().Update(iu)
  759. } else {
  760. _, err = x.Insert(iu)
  761. }
  762. if err != nil {
  763. return err
  764. }
  765. }
  766. return nil
  767. }
  768. // __________ .__ .__ __________ __
  769. // \______ \__ __| | | |\______ \ ____ ________ __ ____ _______/ |_
  770. // | ___/ | \ | | | | _// __ \/ ____/ | \_/ __ \ / ___/\ __\
  771. // | | | | / |_| |_| | \ ___< <_| | | /\ ___/ \___ \ | |
  772. // |____| |____/|____/____/____|_ /\___ >__ |____/ \___ >____ > |__|
  773. // \/ \/ |__| \/ \/
  774. type PullRequestType int
  775. const (
  776. PULL_REQUEST_GOGS = iota
  777. PLLL_ERQUEST_GIT
  778. )
  779. // PullRequest represents relation between pull request and repositories.
  780. type PullRequest struct {
  781. ID int64 `xorm:"pk autoincr"`
  782. PullID int64 `xorm:"INDEX"`
  783. Pull *Issue `xorm:"-"`
  784. PullIndex int64
  785. HeadRepoID int64
  786. HeadRepo *Repository `xorm:"-"`
  787. BaseRepoID int64
  788. HeadUserName string
  789. HeadBarcnh string
  790. BaseBranch string
  791. MergeBase string `xorm:"VARCHAR(40)"`
  792. MergedCommitID string `xorm:"VARCHAR(40)"`
  793. Type PullRequestType
  794. CanAutoMerge bool
  795. HasMerged bool
  796. Merged time.Time
  797. MergerID int64
  798. Merger *User `xorm:"-"`
  799. }
  800. func (pr *PullRequest) AfterSet(colName string, _ xorm.Cell) {
  801. var err error
  802. switch colName {
  803. case "head_repo_id":
  804. pr.HeadRepo, err = GetRepositoryByID(pr.HeadRepoID)
  805. if err != nil {
  806. log.Error(3, "GetRepositoryByID[%d]: %v", pr.ID, err)
  807. }
  808. case "merger_id":
  809. if !pr.HasMerged {
  810. return
  811. }
  812. pr.Merger, err = GetUserByID(pr.MergerID)
  813. if err != nil {
  814. if IsErrUserNotExist(err) {
  815. pr.MergerID = -1
  816. pr.Merger = NewFakeUser()
  817. } else {
  818. log.Error(3, "GetUserByID[%d]: %v", pr.ID, err)
  819. }
  820. }
  821. case "merged":
  822. if !pr.HasMerged {
  823. return
  824. }
  825. pr.Merged = regulateTimeZone(pr.Merged)
  826. }
  827. }
  828. // Merge merges pull request to base repository.
  829. func (pr *PullRequest) Merge(doer *User, baseGitRepo *git.Repository) (err error) {
  830. sess := x.NewSession()
  831. defer sessionRelease(sess)
  832. if err = sess.Begin(); err != nil {
  833. return err
  834. }
  835. if err = pr.Pull.changeStatus(sess, doer, true); err != nil {
  836. return fmt.Errorf("Pull.changeStatus: %v", err)
  837. }
  838. headRepoPath := RepoPath(pr.HeadUserName, pr.HeadRepo.Name)
  839. headGitRepo, err := git.OpenRepository(headRepoPath)
  840. if err != nil {
  841. return fmt.Errorf("OpenRepository: %v", err)
  842. }
  843. pr.MergedCommitID, err = headGitRepo.GetCommitIdOfBranch(pr.HeadBarcnh)
  844. if err != nil {
  845. return fmt.Errorf("GetCommitIdOfBranch: %v", err)
  846. }
  847. if err = mergePullRequestAction(sess, doer, pr.Pull.Repo, pr.Pull); err != nil {
  848. return fmt.Errorf("mergePullRequestAction: %v", err)
  849. }
  850. pr.HasMerged = true
  851. pr.Merged = time.Now()
  852. pr.MergerID = doer.Id
  853. if _, err = sess.Id(pr.ID).AllCols().Update(pr); err != nil {
  854. return fmt.Errorf("update pull request: %v", err)
  855. }
  856. // Clone base repo.
  857. tmpBasePath := path.Join("data/tmp/repos", com.ToStr(time.Now().Nanosecond())+".git")
  858. os.MkdirAll(path.Dir(tmpBasePath), os.ModePerm)
  859. defer os.RemoveAll(path.Dir(tmpBasePath))
  860. var stderr string
  861. if _, stderr, err = process.ExecTimeout(5*time.Minute,
  862. fmt.Sprintf("PullRequest.Merge(git clone): %s", tmpBasePath),
  863. "git", "clone", baseGitRepo.Path, tmpBasePath); err != nil {
  864. return fmt.Errorf("git clone: %s", stderr)
  865. }
  866. // Check out base branch.
  867. if _, stderr, err = process.ExecDir(-1, tmpBasePath,
  868. fmt.Sprintf("PullRequest.Merge(git checkout): %s", tmpBasePath),
  869. "git", "checkout", pr.BaseBranch); err != nil {
  870. return fmt.Errorf("git checkout: %s", stderr)
  871. }
  872. // Pull commits.
  873. if _, stderr, err = process.ExecDir(-1, tmpBasePath,
  874. fmt.Sprintf("PullRequest.Merge(git pull): %s", tmpBasePath),
  875. "git", "pull", headRepoPath, pr.HeadBarcnh); err != nil {
  876. return fmt.Errorf("git pull: %s", stderr)
  877. }
  878. // Push back to upstream.
  879. if _, stderr, err = process.ExecDir(-1, tmpBasePath,
  880. fmt.Sprintf("PullRequest.Merge(git push): %s", tmpBasePath),
  881. "git", "push", baseGitRepo.Path, pr.BaseBranch); err != nil {
  882. return fmt.Errorf("git push: %s", stderr)
  883. }
  884. return sess.Commit()
  885. }
  886. // NewPullRequest creates new pull request with labels for repository.
  887. func NewPullRequest(repo *Repository, pull *Issue, labelIDs []int64, uuids []string, pr *PullRequest, patch []byte) (err error) {
  888. sess := x.NewSession()
  889. defer sessionRelease(sess)
  890. if err = sess.Begin(); err != nil {
  891. return err
  892. }
  893. if err = newIssue(sess, repo, pull, labelIDs, uuids, true); err != nil {
  894. return fmt.Errorf("newIssue: %v", err)
  895. }
  896. // Notify watchers.
  897. act := &Action{
  898. ActUserID: pull.Poster.Id,
  899. ActUserName: pull.Poster.Name,
  900. ActEmail: pull.Poster.Email,
  901. OpType: CREATE_PULL_REQUEST,
  902. Content: fmt.Sprintf("%d|%s", pull.Index, pull.Name),
  903. RepoID: repo.ID,
  904. RepoUserName: repo.Owner.Name,
  905. RepoName: repo.Name,
  906. IsPrivate: repo.IsPrivate,
  907. }
  908. if err = notifyWatchers(sess, act); err != nil {
  909. return err
  910. }
  911. // Test apply patch.
  912. repoPath, err := repo.RepoPath()
  913. if err != nil {
  914. return fmt.Errorf("RepoPath: %v", err)
  915. }
  916. patchPath := path.Join(repoPath, "pulls", com.ToStr(pr.ID)+".patch")
  917. os.MkdirAll(path.Dir(patchPath), os.ModePerm)
  918. if err = ioutil.WriteFile(patchPath, patch, 0644); err != nil {
  919. return fmt.Errorf("save patch: %v", err)
  920. }
  921. defer os.Remove(patchPath)
  922. stdout, stderr, err := process.ExecDir(-1, repoPath,
  923. fmt.Sprintf("NewPullRequest(git apply --check): %d", repo.ID),
  924. "git", "apply", "--check", "-v", patchPath)
  925. if err != nil {
  926. if strings.Contains(stderr, "fatal:") {
  927. return fmt.Errorf("git apply --check: %v - %s", err, stderr)
  928. }
  929. }
  930. pr.CanAutoMerge = !strings.Contains(stdout, "error: patch failed:")
  931. pr.PullID = pull.ID
  932. pr.PullIndex = pull.Index
  933. if _, err = sess.Insert(pr); err != nil {
  934. return fmt.Errorf("insert pull repo: %v", err)
  935. }
  936. return sess.Commit()
  937. }
  938. // GetUnmergedPullRequest returnss a pull request hasn't been merged by given info.
  939. func GetUnmergedPullRequest(headRepoID, baseRepoID int64, headBranch, baseBranch string) (*PullRequest, error) {
  940. pr := &PullRequest{
  941. HeadRepoID: headRepoID,
  942. BaseRepoID: baseRepoID,
  943. HeadBarcnh: headBranch,
  944. BaseBranch: baseBranch,
  945. }
  946. has, err := x.Where("has_merged=?", false).Get(pr)
  947. if err != nil {
  948. return nil, err
  949. } else if !has {
  950. return nil, ErrPullRequestNotExist{0, 0, headRepoID, baseRepoID, headBranch, baseBranch}
  951. }
  952. return pr, nil
  953. }
  954. // GetPullRequestByPullID returns pull repo by given pull ID.
  955. func GetPullRequestByPullID(pullID int64) (*PullRequest, error) {
  956. pr := new(PullRequest)
  957. has, err := x.Where("pull_id=?", pullID).Get(pr)
  958. if err != nil {
  959. return nil, err
  960. } else if !has {
  961. return nil, ErrPullRequestNotExist{0, pullID, 0, 0, "", ""}
  962. }
  963. return pr, nil
  964. }
  965. // .____ ___. .__
  966. // | | _____ \_ |__ ____ | |
  967. // | | \__ \ | __ \_/ __ \| |
  968. // | |___ / __ \| \_\ \ ___/| |__
  969. // |_______ (____ /___ /\___ >____/
  970. // \/ \/ \/ \/
  971. // Label represents a label of repository for issues.
  972. type Label struct {
  973. ID int64 `xorm:"pk autoincr"`
  974. RepoID int64 `xorm:"INDEX"`
  975. Name string
  976. Color string `xorm:"VARCHAR(7)"`
  977. NumIssues int
  978. NumClosedIssues int
  979. NumOpenIssues int `xorm:"-"`
  980. IsChecked bool `xorm:"-"`
  981. }
  982. // CalOpenIssues calculates the open issues of label.
  983. func (m *Label) CalOpenIssues() {
  984. m.NumOpenIssues = m.NumIssues - m.NumClosedIssues
  985. }
  986. // NewLabel creates new label of repository.
  987. func NewLabel(l *Label) error {
  988. _, err := x.Insert(l)
  989. return err
  990. }
  991. func getLabelByID(e Engine, id int64) (*Label, error) {
  992. if id <= 0 {
  993. return nil, ErrLabelNotExist{id}
  994. }
  995. l := &Label{ID: id}
  996. has, err := x.Get(l)
  997. if err != nil {
  998. return nil, err
  999. } else if !has {
  1000. return nil, ErrLabelNotExist{l.ID}
  1001. }
  1002. return l, nil
  1003. }
  1004. // GetLabelByID returns a label by given ID.
  1005. func GetLabelByID(id int64) (*Label, error) {
  1006. return getLabelByID(x, id)
  1007. }
  1008. // GetLabelsByRepoID returns all labels that belong to given repository by ID.
  1009. func GetLabelsByRepoID(repoID int64) ([]*Label, error) {
  1010. labels := make([]*Label, 0, 10)
  1011. return labels, x.Where("repo_id=?", repoID).Find(&labels)
  1012. }
  1013. func getLabelsByIssueID(e Engine, issueID int64) ([]*Label, error) {
  1014. issueLabels, err := getIssueLabels(e, issueID)
  1015. if err != nil {
  1016. return nil, fmt.Errorf("getIssueLabels: %v", err)
  1017. }
  1018. var label *Label
  1019. labels := make([]*Label, 0, len(issueLabels))
  1020. for idx := range issueLabels {
  1021. label, err = getLabelByID(e, issueLabels[idx].LabelID)
  1022. if err != nil && !IsErrLabelNotExist(err) {
  1023. return nil, fmt.Errorf("getLabelByID: %v", err)
  1024. }
  1025. labels = append(labels, label)
  1026. }
  1027. return labels, nil
  1028. }
  1029. // GetLabelsByIssueID returns all labels that belong to given issue by ID.
  1030. func GetLabelsByIssueID(issueID int64) ([]*Label, error) {
  1031. return getLabelsByIssueID(x, issueID)
  1032. }
  1033. func updateLabel(e Engine, l *Label) error {
  1034. _, err := e.Id(l.ID).AllCols().Update(l)
  1035. return err
  1036. }
  1037. // UpdateLabel updates label information.
  1038. func UpdateLabel(l *Label) error {
  1039. return updateLabel(x, l)
  1040. }
  1041. // DeleteLabel delete a label of given repository.
  1042. func DeleteLabel(repoID, labelID int64) error {
  1043. l, err := GetLabelByID(labelID)
  1044. if err != nil {
  1045. if IsErrLabelNotExist(err) {
  1046. return nil
  1047. }
  1048. return err
  1049. }
  1050. sess := x.NewSession()
  1051. defer sessionRelease(sess)
  1052. if err = sess.Begin(); err != nil {
  1053. return err
  1054. }
  1055. if _, err = x.Where("label_id=?", labelID).Delete(new(IssueLabel)); err != nil {
  1056. return err
  1057. } else if _, err = sess.Delete(l); err != nil {
  1058. return err
  1059. }
  1060. return sess.Commit()
  1061. }
  1062. // .___ .____ ___. .__
  1063. // | | ______ ________ __ ____ | | _____ \_ |__ ____ | |
  1064. // | |/ ___// ___/ | \_/ __ \| | \__ \ | __ \_/ __ \| |
  1065. // | |\___ \ \___ \| | /\ ___/| |___ / __ \| \_\ \ ___/| |__
  1066. // |___/____ >____ >____/ \___ >_______ (____ /___ /\___ >____/
  1067. // \/ \/ \/ \/ \/ \/ \/
  1068. // IssueLabel represetns an issue-lable relation.
  1069. type IssueLabel struct {
  1070. ID int64 `xorm:"pk autoincr"`
  1071. IssueID int64 `xorm:"UNIQUE(s)"`
  1072. LabelID int64 `xorm:"UNIQUE(s)"`
  1073. }
  1074. func hasIssueLabel(e Engine, issueID, labelID int64) bool {
  1075. has, _ := e.Where("issue_id=? AND label_id=?", issueID, labelID).Get(new(IssueLabel))
  1076. return has
  1077. }
  1078. // HasIssueLabel returns true if issue has been labeled.
  1079. func HasIssueLabel(issueID, labelID int64) bool {
  1080. return hasIssueLabel(x, issueID, labelID)
  1081. }
  1082. func newIssueLabel(e *xorm.Session, issue *Issue, label *Label) (err error) {
  1083. if _, err = e.Insert(&IssueLabel{
  1084. IssueID: issue.ID,
  1085. LabelID: label.ID,
  1086. }); err != nil {
  1087. return err
  1088. }
  1089. label.NumIssues++
  1090. if issue.IsClosed {
  1091. label.NumClosedIssues++
  1092. }
  1093. return updateLabel(e, label)
  1094. }
  1095. // NewIssueLabel creates a new issue-label relation.
  1096. func NewIssueLabel(issue *Issue, label *Label) (err error) {
  1097. sess := x.NewSession()
  1098. defer sessionRelease(sess)
  1099. if err = sess.Begin(); err != nil {
  1100. return err
  1101. }
  1102. if err = newIssueLabel(sess, issue, label); err != nil {
  1103. return err
  1104. }
  1105. return sess.Commit()
  1106. }
  1107. func getIssueLabels(e Engine, issueID int64) ([]*IssueLabel, error) {
  1108. issueLabels := make([]*IssueLabel, 0, 10)
  1109. return issueLabels, e.Where("issue_id=?", issueID).Asc("label_id").Find(&issueLabels)
  1110. }
  1111. // GetIssueLabels returns all issue-label relations of given issue by ID.
  1112. func GetIssueLabels(issueID int64) ([]*IssueLabel, error) {
  1113. return getIssueLabels(x, issueID)
  1114. }
  1115. func deleteIssueLabel(e *xorm.Session, issue *Issue, label *Label) (err error) {
  1116. if _, err = e.Delete(&IssueLabel{
  1117. IssueID: issue.ID,
  1118. LabelID: label.ID,
  1119. }); err != nil {
  1120. return err
  1121. }
  1122. label.NumIssues--
  1123. if issue.IsClosed {
  1124. label.NumClosedIssues--
  1125. }
  1126. return updateLabel(e, label)
  1127. }
  1128. // DeleteIssueLabel deletes issue-label relation.
  1129. func DeleteIssueLabel(issue *Issue, label *Label) (err error) {
  1130. sess := x.NewSession()
  1131. defer sessionRelease(sess)
  1132. if err = sess.Begin(); err != nil {
  1133. return err
  1134. }
  1135. if err = deleteIssueLabel(sess, issue, label); err != nil {
  1136. return err
  1137. }
  1138. return sess.Commit()
  1139. }
  1140. // _____ .__.__ __
  1141. // / \ |__| | ____ _______/ |_ ____ ____ ____
  1142. // / \ / \| | | _/ __ \ / ___/\ __\/ _ \ / \_/ __ \
  1143. // / Y \ | |_\ ___/ \___ \ | | ( <_> ) | \ ___/
  1144. // \____|__ /__|____/\___ >____ > |__| \____/|___| /\___ >
  1145. // \/ \/ \/ \/ \/
  1146. // Milestone represents a milestone of repository.
  1147. type Milestone struct {
  1148. ID int64 `xorm:"pk autoincr"`
  1149. RepoID int64 `xorm:"INDEX"`
  1150. Name string
  1151. Content string `xorm:"TEXT"`
  1152. RenderedContent string `xorm:"-"`
  1153. IsClosed bool
  1154. NumIssues int
  1155. NumClosedIssues int
  1156. NumOpenIssues int `xorm:"-"`
  1157. Completeness int // Percentage(1-100).
  1158. Deadline time.Time
  1159. DeadlineString string `xorm:"-"`
  1160. IsOverDue bool `xorm:"-"`
  1161. ClosedDate time.Time
  1162. }
  1163. func (m *Milestone) BeforeUpdate() {
  1164. if m.NumIssues > 0 {
  1165. m.Completeness = m.NumClosedIssues * 100 / m.NumIssues
  1166. } else {
  1167. m.Completeness = 0
  1168. }
  1169. }
  1170. func (m *Milestone) AfterSet(colName string, _ xorm.Cell) {
  1171. if colName == "deadline" {
  1172. if m.Deadline.Year() == 9999 {
  1173. return
  1174. }
  1175. m.DeadlineString = m.Deadline.Format("2006-01-02")
  1176. if time.Now().After(m.Deadline) {
  1177. m.IsOverDue = true
  1178. }
  1179. }
  1180. }
  1181. // CalOpenIssues calculates the open issues of milestone.
  1182. func (m *Milestone) CalOpenIssues() {
  1183. m.NumOpenIssues = m.NumIssues - m.NumClosedIssues
  1184. }
  1185. // NewMilestone creates new milestone of repository.
  1186. func NewMilestone(m *Milestone) (err error) {
  1187. sess := x.NewSession()
  1188. defer sessionRelease(sess)
  1189. if err = sess.Begin(); err != nil {
  1190. return err
  1191. }
  1192. if _, err = sess.Insert(m); err != nil {
  1193. return err
  1194. }
  1195. if _, err = sess.Exec("UPDATE `repository` SET num_milestones=num_milestones+1 WHERE id=?", m.RepoID); err != nil {
  1196. return err
  1197. }
  1198. return sess.Commit()
  1199. }
  1200. func getMilestoneByID(e Engine, id int64) (*Milestone, error) {
  1201. m := &Milestone{ID: id}
  1202. has, err := e.Get(m)
  1203. if err != nil {
  1204. return nil, err
  1205. } else if !has {
  1206. return nil, ErrMilestoneNotExist{id, 0}
  1207. }
  1208. return m, nil
  1209. }
  1210. // GetMilestoneByID returns the milestone of given ID.
  1211. func GetMilestoneByID(id int64) (*Milestone, error) {
  1212. return getMilestoneByID(x, id)
  1213. }
  1214. // GetRepoMilestoneByID returns the milestone of given ID and repository.
  1215. func GetRepoMilestoneByID(repoID, milestoneID int64) (*Milestone, error) {
  1216. m := &Milestone{ID: milestoneID, RepoID: repoID}
  1217. has, err := x.Get(m)
  1218. if err != nil {
  1219. return nil, err
  1220. } else if !has {
  1221. return nil, ErrMilestoneNotExist{milestoneID, repoID}
  1222. }
  1223. return m, nil
  1224. }
  1225. // GetAllRepoMilestones returns all milestones of given repository.
  1226. func GetAllRepoMilestones(repoID int64) ([]*Milestone, error) {
  1227. miles := make([]*Milestone, 0, 10)
  1228. return miles, x.Where("repo_id=?", repoID).Find(&miles)
  1229. }
  1230. // GetMilestones returns a list of milestones of given repository and status.
  1231. func GetMilestones(repoID int64, page int, isClosed bool) ([]*Milestone, error) {
  1232. miles := make([]*Milestone, 0, setting.IssuePagingNum)
  1233. sess := x.Where("repo_id=? AND is_closed=?", repoID, isClosed)
  1234. if page > 0 {
  1235. sess = sess.Limit(setting.IssuePagingNum, (page-1)*setting.IssuePagingNum)
  1236. }
  1237. return miles, sess.Find(&miles)
  1238. }
  1239. func updateMilestone(e Engine, m *Milestone) error {
  1240. _, err := e.Id(m.ID).AllCols().Update(m)
  1241. return err
  1242. }
  1243. // UpdateMilestone updates information of given milestone.
  1244. func UpdateMilestone(m *Milestone) error {
  1245. return updateMilestone(x, m)
  1246. }
  1247. func countRepoMilestones(e Engine, repoID int64) int64 {
  1248. count, _ := e.Where("repo_id=?", repoID).Count(new(Milestone))
  1249. return count
  1250. }
  1251. // CountRepoMilestones returns number of milestones in given repository.
  1252. func CountRepoMilestones(repoID int64) int64 {
  1253. return countRepoMilestones(x, repoID)
  1254. }
  1255. func countRepoClosedMilestones(e Engine, repoID int64) int64 {
  1256. closed, _ := e.Where("repo_id=? AND is_closed=?", repoID, true).Count(new(Milestone))
  1257. return closed
  1258. }
  1259. // CountRepoClosedMilestones returns number of closed milestones in given repository.
  1260. func CountRepoClosedMilestones(repoID int64) int64 {
  1261. return countRepoClosedMilestones(x, repoID)
  1262. }
  1263. // MilestoneStats returns number of open and closed milestones of given repository.
  1264. func MilestoneStats(repoID int64) (open int64, closed int64) {
  1265. open, _ = x.Where("repo_id=? AND is_closed=?", repoID, false).Count(new(Milestone))
  1266. return open, CountRepoClosedMilestones(repoID)
  1267. }
  1268. // ChangeMilestoneStatus changes the milestone open/closed status.
  1269. func ChangeMilestoneStatus(m *Milestone, isClosed bool) (err error) {
  1270. repo, err := GetRepositoryByID(m.RepoID)
  1271. if err != nil {
  1272. return err
  1273. }
  1274. sess := x.NewSession()
  1275. defer sessionRelease(sess)
  1276. if err = sess.Begin(); err != nil {
  1277. return err
  1278. }
  1279. m.IsClosed = isClosed
  1280. if err = updateMilestone(sess, m); err != nil {
  1281. return err
  1282. }
  1283. repo.NumMilestones = int(countRepoMilestones(sess, repo.ID))
  1284. repo.NumClosedMilestones = int(countRepoClosedMilestones(sess, repo.ID))
  1285. if _, err = sess.Id(repo.ID).AllCols().Update(repo); err != nil {
  1286. return err
  1287. }
  1288. return sess.Commit()
  1289. }
  1290. func changeMilestoneIssueStats(e *xorm.Session, issue *Issue) error {
  1291. if issue.MilestoneID == 0 {
  1292. return nil
  1293. }
  1294. m, err := getMilestoneByID(e, issue.MilestoneID)
  1295. if err != nil {
  1296. return err
  1297. }
  1298. if issue.IsClosed {
  1299. m.NumOpenIssues--
  1300. m.NumClosedIssues++
  1301. } else {
  1302. m.NumOpenIssues++
  1303. m.NumClosedIssues--
  1304. }
  1305. return updateMilestone(e, m)
  1306. }
  1307. // ChangeMilestoneIssueStats updates the open/closed issues counter and progress
  1308. // for the milestone associated witht the given issue.
  1309. func ChangeMilestoneIssueStats(issue *Issue) (err error) {
  1310. sess := x.NewSession()
  1311. defer sessionRelease(sess)
  1312. if err = sess.Begin(); err != nil {
  1313. return err
  1314. }
  1315. if err = changeMilestoneIssueStats(sess, issue); err != nil {
  1316. return err
  1317. }
  1318. return sess.Commit()
  1319. }
  1320. func changeMilestoneAssign(e *xorm.Session, oldMid int64, issue *Issue) error {
  1321. if oldMid > 0 {
  1322. m, err := getMilestoneByID(e, oldMid)
  1323. if err != nil {
  1324. return err
  1325. }
  1326. m.NumIssues--
  1327. if issue.IsClosed {
  1328. m.NumClosedIssues--
  1329. }
  1330. if err = updateMilestone(e, m); err != nil {
  1331. return err
  1332. } else if _, err = e.Exec("UPDATE `issue_user` SET milestone_id=0 WHERE issue_id=?", issue.ID); err != nil {
  1333. return err
  1334. }
  1335. }
  1336. if issue.MilestoneID > 0 {
  1337. m, err := getMilestoneByID(e, issue.MilestoneID)
  1338. if err != nil {
  1339. return err
  1340. }
  1341. m.NumIssues++
  1342. if issue.IsClosed {
  1343. m.NumClosedIssues++
  1344. }
  1345. if m.NumIssues == 0 {
  1346. return ErrWrongIssueCounter
  1347. }
  1348. if err = updateMilestone(e, m); err != nil {
  1349. return err
  1350. } else if _, err = e.Exec("UPDATE `issue_user` SET milestone_id=? WHERE issue_id=?", m.ID, issue.ID); err != nil {
  1351. return err
  1352. }
  1353. }
  1354. return updateIssue(e, issue)
  1355. }
  1356. // ChangeMilestoneAssign changes assignment of milestone for issue.
  1357. func ChangeMilestoneAssign(oldMid int64, issue *Issue) (err error) {
  1358. sess := x.NewSession()
  1359. defer sess.Close()
  1360. if err = sess.Begin(); err != nil {
  1361. return err
  1362. }
  1363. if err = changeMilestoneAssign(sess, oldMid, issue); err != nil {
  1364. return err
  1365. }
  1366. return sess.Commit()
  1367. }
  1368. // DeleteMilestoneByID deletes a milestone by given ID.
  1369. func DeleteMilestoneByID(mid int64) error {
  1370. m, err := GetMilestoneByID(mid)
  1371. if err != nil {
  1372. if IsErrMilestoneNotExist(err) {
  1373. return nil
  1374. }
  1375. return err
  1376. }
  1377. repo, err := GetRepositoryByID(m.RepoID)
  1378. if err != nil {
  1379. return err
  1380. }
  1381. sess := x.NewSession()
  1382. defer sessionRelease(sess)
  1383. if err = sess.Begin(); err != nil {
  1384. return err
  1385. }
  1386. if _, err = sess.Id(m.ID).Delete(m); err != nil {
  1387. return err
  1388. }
  1389. repo.NumMilestones = int(countRepoMilestones(sess, repo.ID))
  1390. repo.NumClosedMilestones = int(countRepoClosedMilestones(sess, repo.ID))
  1391. if _, err = sess.Id(repo.ID).AllCols().Update(repo); err != nil {
  1392. return err
  1393. }
  1394. if _, err = sess.Exec("UPDATE `issue` SET milestone_id=0 WHERE milestone_id=?", m.ID); err != nil {
  1395. return err
  1396. } else if _, err = sess.Exec("UPDATE `issue_user` SET milestone_id=0 WHERE milestone_id=?", m.ID); err != nil {
  1397. return err
  1398. }
  1399. return sess.Commit()
  1400. }
  1401. // _________ __
  1402. // \_ ___ \ ____ _____ _____ ____ _____/ |_
  1403. // / \ \/ / _ \ / \ / \_/ __ \ / \ __\
  1404. // \ \___( <_> ) Y Y \ Y Y \ ___/| | \ |
  1405. // \______ /\____/|__|_| /__|_| /\___ >___| /__|
  1406. // \/ \/ \/ \/ \/
  1407. // CommentType defines whether a comment is just a simple comment, an action (like close) or a reference.
  1408. type CommentType int
  1409. const (
  1410. // Plain comment, can be associated with a commit (CommitId > 0) and a line (Line > 0)
  1411. COMMENT_TYPE_COMMENT CommentType = iota
  1412. COMMENT_TYPE_REOPEN
  1413. COMMENT_TYPE_CLOSE
  1414. // References.
  1415. COMMENT_TYPE_ISSUE_REF
  1416. // Reference from a commit (not part of a pull request)
  1417. COMMENT_TYPE_COMMIT_REF
  1418. // Reference from a comment
  1419. COMMENT_TYPE_COMMENT_REF
  1420. // Reference from a pull request
  1421. COMMENT_TYPE_PULL_REF
  1422. )
  1423. type CommentTag int
  1424. const (
  1425. COMMENT_TAG_NONE CommentTag = iota
  1426. COMMENT_TAG_POSTER
  1427. COMMENT_TAG_ADMIN
  1428. COMMENT_TAG_OWNER
  1429. )
  1430. // Comment represents a comment in commit and issue page.
  1431. type Comment struct {
  1432. ID int64 `xorm:"pk autoincr"`
  1433. Type CommentType
  1434. PosterID int64
  1435. Poster *User `xorm:"-"`
  1436. IssueID int64 `xorm:"INDEX"`
  1437. CommitID int64
  1438. Line int64
  1439. Content string `xorm:"TEXT"`
  1440. RenderedContent string `xorm:"-"`
  1441. Created time.Time `xorm:"CREATED"`
  1442. Attachments []*Attachment `xorm:"-"`
  1443. // For view issue page.
  1444. ShowTag CommentTag `xorm:"-"`
  1445. }
  1446. func (c *Comment) AfterSet(colName string, _ xorm.Cell) {
  1447. var err error
  1448. switch colName {
  1449. case "id":
  1450. c.Attachments, err = GetAttachmentsByCommentID(c.ID)
  1451. if err != nil {
  1452. log.Error(3, "GetAttachmentsByCommentID[%d]: %v", c.ID, err)
  1453. }
  1454. case "poster_id":
  1455. c.Poster, err = GetUserByID(c.PosterID)
  1456. if err != nil {
  1457. if IsErrUserNotExist(err) {
  1458. c.PosterID = -1
  1459. c.Poster = NewFakeUser()
  1460. } else {
  1461. log.Error(3, "GetUserByID[%d]: %v", c.ID, err)
  1462. }
  1463. }
  1464. case "created":
  1465. c.Created = regulateTimeZone(c.Created)
  1466. }
  1467. }
  1468. func (c *Comment) AfterDelete() {
  1469. _, err := DeleteAttachmentsByComment(c.ID, true)
  1470. if err != nil {
  1471. log.Info("Could not delete files for comment %d on issue #%d: %s", c.ID, c.IssueID, err)
  1472. }
  1473. }
  1474. // HashTag returns unique hash tag for comment.
  1475. func (c *Comment) HashTag() string {
  1476. return "issuecomment-" + com.ToStr(c.ID)
  1477. }
  1478. // EventTag returns unique event hash tag for comment.
  1479. func (c *Comment) EventTag() string {
  1480. return "event-" + com.ToStr(c.ID)
  1481. }
  1482. func createComment(e *xorm.Session, u *User, repo *Repository, issue *Issue, commitID, line int64, cmtType CommentType, content string, uuids []string) (_ *Comment, err error) {
  1483. comment := &Comment{
  1484. PosterID: u.Id,
  1485. Type: cmtType,
  1486. IssueID: issue.ID,
  1487. CommitID: commitID,
  1488. Line: line,
  1489. Content: content,
  1490. }
  1491. if _, err = e.Insert(comment); err != nil {
  1492. return nil, err
  1493. }
  1494. // Check comment type.
  1495. switch cmtType {
  1496. case COMMENT_TYPE_COMMENT:
  1497. if _, err = e.Exec("UPDATE `issue` SET num_comments=num_comments+1 WHERE id=?", issue.ID); err != nil {
  1498. return nil, err
  1499. }
  1500. // Check attachments.
  1501. attachments := make([]*Attachment, 0, len(uuids))
  1502. for _, uuid := range uuids {
  1503. attach, err := getAttachmentByUUID(e, uuid)
  1504. if err != nil {
  1505. if IsErrAttachmentNotExist(err) {
  1506. continue
  1507. }
  1508. return nil, fmt.Errorf("getAttachmentByUUID[%s]: %v", uuid, err)
  1509. }
  1510. attachments = append(attachments, attach)
  1511. }
  1512. for i := range attachments {
  1513. attachments[i].IssueID = issue.ID
  1514. attachments[i].CommentID = comment.ID
  1515. // No assign value could be 0, so ignore AllCols().
  1516. if _, err = e.Id(attachments[i].ID).Update(attachments[i]); err != nil {
  1517. return nil, fmt.Errorf("update attachment[%d]: %v", attachments[i].ID, err)
  1518. }
  1519. }
  1520. // Notify watchers.
  1521. act := &Action{
  1522. ActUserID: u.Id,
  1523. ActUserName: u.LowerName,
  1524. ActEmail: u.Email,
  1525. OpType: COMMENT_ISSUE,
  1526. Content: fmt.Sprintf("%d|%s", issue.Index, strings.Split(content, "\n")[0]),
  1527. RepoID: repo.ID,
  1528. RepoUserName: repo.Owner.LowerName,
  1529. RepoName: repo.LowerName,
  1530. IsPrivate: repo.IsPrivate,
  1531. }
  1532. if err = notifyWatchers(e, act); err != nil {
  1533. return nil, err
  1534. }
  1535. case COMMENT_TYPE_REOPEN:
  1536. if issue.IsPull {
  1537. _, err = e.Exec("UPDATE `repository` SET num_closed_pulls=num_closed_pulls-1 WHERE id=?", repo.ID)
  1538. } else {
  1539. _, err = e.Exec("UPDATE `repository` SET num_closed_issues=num_closed_issues-1 WHERE id=?", repo.ID)
  1540. }
  1541. if err != nil {
  1542. return nil, err
  1543. }
  1544. case COMMENT_TYPE_CLOSE:
  1545. if issue.IsPull {
  1546. _, err = e.Exec("UPDATE `repository` SET num_closed_pulls=num_closed_pulls+1 WHERE id=?", repo.ID)
  1547. } else {
  1548. _, err = e.Exec("UPDATE `repository` SET num_closed_issues=num_closed_issues+1 WHERE id=?", repo.ID)
  1549. }
  1550. if err != nil {
  1551. return nil, err
  1552. }
  1553. }
  1554. return comment, nil
  1555. }
  1556. func createStatusComment(e *xorm.Session, doer *User, repo *Repository, issue *Issue) (*Comment, error) {
  1557. cmtType := COMMENT_TYPE_CLOSE
  1558. if !issue.IsClosed {
  1559. cmtType = COMMENT_TYPE_REOPEN
  1560. }
  1561. return createComment(e, doer, repo, issue, 0, 0, cmtType, "", nil)
  1562. }
  1563. // CreateComment creates comment of issue or commit.
  1564. func CreateComment(doer *User, repo *Repository, issue *Issue, commitID, line int64, cmtType CommentType, content string, attachments []string) (comment *Comment, err error) {
  1565. sess := x.NewSession()
  1566. defer sessionRelease(sess)
  1567. if err = sess.Begin(); err != nil {
  1568. return nil, err
  1569. }
  1570. comment, err = createComment(sess, doer, repo, issue, commitID, line, cmtType, content, attachments)
  1571. if err != nil {
  1572. return nil, err
  1573. }
  1574. return comment, sess.Commit()
  1575. }
  1576. // CreateIssueComment creates a plain issue comment.
  1577. func CreateIssueComment(doer *User, repo *Repository, issue *Issue, content string, attachments []string) (*Comment, error) {
  1578. return CreateComment(doer, repo, issue, 0, 0, COMMENT_TYPE_COMMENT, content, attachments)
  1579. }
  1580. // GetCommentByID returns the comment by given ID.
  1581. func GetCommentByID(id int64) (*Comment, error) {
  1582. c := new(Comment)
  1583. has, err := x.Id(id).Get(c)
  1584. if err != nil {
  1585. return nil, err
  1586. } else if !has {
  1587. return nil, ErrCommentNotExist{id}
  1588. }
  1589. return c, nil
  1590. }
  1591. // GetCommentsByIssueID returns all comments of issue by given ID.
  1592. func GetCommentsByIssueID(issueID int64) ([]*Comment, error) {
  1593. comments := make([]*Comment, 0, 10)
  1594. return comments, x.Where("issue_id=?", issueID).Asc("created").Find(&comments)
  1595. }
  1596. // UpdateComment updates information of comment.
  1597. func UpdateComment(c *Comment) error {
  1598. _, err := x.Id(c.ID).AllCols().Update(c)
  1599. return err
  1600. }
  1601. // Attachment represent a attachment of issue/comment/release.
  1602. type Attachment struct {
  1603. ID int64 `xorm:"pk autoincr"`
  1604. UUID string `xorm:"uuid UNIQUE"`
  1605. IssueID int64 `xorm:"INDEX"`
  1606. CommentID int64
  1607. ReleaseID int64 `xorm:"INDEX"`
  1608. Name string
  1609. Created time.Time `xorm:"CREATED"`
  1610. }
  1611. // AttachmentLocalPath returns where attachment is stored in local file system based on given UUID.
  1612. func AttachmentLocalPath(uuid string) string {
  1613. return path.Join(setting.AttachmentPath, uuid[0:1], uuid[1:2], uuid)
  1614. }
  1615. // LocalPath returns where attachment is stored in local file system.
  1616. func (attach *Attachment) LocalPath() string {
  1617. return AttachmentLocalPath(attach.UUID)
  1618. }
  1619. // NewAttachment creates a new attachment object.
  1620. func NewAttachment(name string, buf []byte, file multipart.File) (_ *Attachment, err error) {
  1621. attach := &Attachment{
  1622. UUID: gouuid.NewV4().String(),
  1623. Name: name,
  1624. }
  1625. if err = os.MkdirAll(path.Dir(attach.LocalPath()), os.ModePerm); err != nil {
  1626. return nil, fmt.Errorf("MkdirAll: %v", err)
  1627. }
  1628. fw, err := os.Create(attach.LocalPath())
  1629. if err != nil {
  1630. return nil, fmt.Errorf("Create: %v", err)
  1631. }
  1632. defer fw.Close()
  1633. if _, err = fw.Write(buf); err != nil {
  1634. return nil, fmt.Errorf("Write: %v", err)
  1635. } else if _, err = io.Copy(fw, file); err != nil {
  1636. return nil, fmt.Errorf("Copy: %v", err)
  1637. }
  1638. sess := x.NewSession()
  1639. defer sessionRelease(sess)
  1640. if err := sess.Begin(); err != nil {
  1641. return nil, err
  1642. }
  1643. if _, err := sess.Insert(attach); err != nil {
  1644. return nil, err
  1645. }
  1646. return attach, sess.Commit()
  1647. }
  1648. func getAttachmentByUUID(e Engine, uuid string) (*Attachment, error) {
  1649. attach := &Attachment{UUID: uuid}
  1650. has, err := x.Get(attach)
  1651. if err != nil {
  1652. return nil, err
  1653. } else if !has {
  1654. return nil, ErrAttachmentNotExist{0, uuid}
  1655. }
  1656. return attach, nil
  1657. }
  1658. // GetAttachmentByUUID returns attachment by given UUID.
  1659. func GetAttachmentByUUID(uuid string) (*Attachment, error) {
  1660. return getAttachmentByUUID(x, uuid)
  1661. }
  1662. // GetAttachmentsByIssueID returns all attachments for given issue by ID.
  1663. func GetAttachmentsByIssueID(issueID int64) ([]*Attachment, error) {
  1664. attachments := make([]*Attachment, 0, 10)
  1665. return attachments, x.Where("issue_id=? AND comment_id=0", issueID).Find(&attachments)
  1666. }
  1667. // GetAttachmentsByCommentID returns all attachments if comment by given ID.
  1668. func GetAttachmentsByCommentID(commentID int64) ([]*Attachment, error) {
  1669. attachments := make([]*Attachment, 0, 10)
  1670. return attachments, x.Where("comment_id=?", commentID).Find(&attachments)
  1671. }
  1672. // DeleteAttachment deletes the given attachment and optionally the associated file.
  1673. func DeleteAttachment(a *Attachment, remove bool) error {
  1674. _, err := DeleteAttachments([]*Attachment{a}, remove)
  1675. return err
  1676. }
  1677. // DeleteAttachments deletes the given attachments and optionally the associated files.
  1678. func DeleteAttachments(attachments []*Attachment, remove bool) (int, error) {
  1679. for i, a := range attachments {
  1680. if remove {
  1681. if err := os.Remove(a.LocalPath()); err != nil {
  1682. return i, err
  1683. }
  1684. }
  1685. if _, err := x.Delete(a.ID); err != nil {
  1686. return i, err
  1687. }
  1688. }
  1689. return len(attachments), nil
  1690. }
  1691. // DeleteAttachmentsByIssue deletes all attachments associated with the given issue.
  1692. func DeleteAttachmentsByIssue(issueId int64, remove bool) (int, error) {
  1693. attachments, err := GetAttachmentsByIssueID(issueId)
  1694. if err != nil {
  1695. return 0, err
  1696. }
  1697. return DeleteAttachments(attachments, remove)
  1698. }
  1699. // DeleteAttachmentsByComment deletes all attachments associated with the given comment.
  1700. func DeleteAttachmentsByComment(commentId int64, remove bool) (int, error) {
  1701. attachments, err := GetAttachmentsByCommentID(commentId)
  1702. if err != nil {
  1703. return 0, err
  1704. }
  1705. return DeleteAttachments(attachments, remove)
  1706. }