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.

1667 lines
43 KiB

10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
Issue due date (#3794) * Started adding deadline to ui * Implemented basic issue due date managing * Improved UI for due date managing * Added at least write access to the repo in order to modify issue due dates * Ui improvements * Added issue comments creation when adding/modifying/removing a due date * Show due date in issue list * Added api support for issue due dates * Fixed lint suggestions * Added deadline to sdk * Updated css * Added support for adding/modifiying deadlines for pull requests via api * Fixed comments not created when updating or removing a deadline * update sdk (will do properly once go-gitea/go-sdk#103 is merged) * enhanced updateIssueDeadline * Removed unnessecary Issue.DeadlineString * UI improvements * Small improvments to comment creation + ui & validation improvements * Check if an issue is overdue is now a seperate function * Updated go-sdk with govendor as it was merged * Simplified isOverdue method * removed unessecary deadline to 0 set * Update swagger definitions * Added missing return * Added an explanary comment * Improved updateIssueDeadline method so it'll only update `deadline_unix` * Small changes and improvements * no need to explicitly load the issue when updating a deadline, just use whats already there * small optimisations * Added check if a deadline was modified before updating it * Moved comment creating logic into its own function * Code cleanup for creating deadline comment * locale improvement * When modifying a deadline, the old deadline is saved with the comment * small improvments to xorm session handling when updating an issue deadline + style nitpicks * style nitpicks * Moved checking for if the user has write acces to middleware
6 years ago
Shows total tracked time in issue and milestone list (#3341) * Show total tracked time in issue and milestone list Show total tracked time at issue page Signed-off-by: Jonas Franz <info@jonasfranz.software> * Optimizing TotalTimes by using SumInt Signed-off-by: Jonas Franz <info@jonasfranz.software> * Fixing wrong total times for milestones caused by a missing JOIN Adding unit tests for total times Signed-off-by: Jonas Franz <info@jonasfranz.software> * Logging error instead of ignoring it Signed-off-by: Jonas Franz <info@jonasfranz.software> * Correcting spelling mistakes Signed-off-by: Jonas Franz <info@jonasfranz.software> * Change error message to a short version Signed-off-by: Jonas Franz <info@jonasfranz.software> * Add error handling to TotalTimes Add variable for totalTimes Signed-off-by: Jonas Franz <info@jonasfranz.de> * Introduce TotalTrackedTimes as variable of issue Load TotalTrackedTimes by loading attributes of IssueList Load TotalTrackedTimes by loading attributes of single issue Add Sec2Time as helper to use it in templates Signed-off-by: Jonas Franz <info@jonasfranz.software> * Fixed test + gofmt Signed-off-by: Jonas Franz <info@jonasfranz.software> * Load TotalTrackedTimes via MilestoneList instead of single requests Signed-off-by: Jonas Franz <info@jonasfranz.software> * Add documentation for MilestoneList Signed-off-by: Jonas Franz <info@jonasfranz.software> * Add documentation for MilestoneList Signed-off-by: Jonas Franz <info@jonasfranz.software> * Fix test Signed-off-by: Jonas Franz <info@jonasfranz.software> * Change comment from SQL query to description Signed-off-by: Jonas Franz <info@jonasfranz.software> * Fix unit test by using int64 instead of int Signed-off-by: Jonas Franz <info@jonasfranz.software> * Fix unit test by using int64 instead of int Signed-off-by: Jonas Franz <info@jonasfranz.software> * Check if timetracker is enabled Signed-off-by: Jonas Franz <info@jonasfranz.software> * Fix test by enabling timetracking Signed-off-by: Jonas Franz <info@jonasfranz.de>
6 years ago
Shows total tracked time in issue and milestone list (#3341) * Show total tracked time in issue and milestone list Show total tracked time at issue page Signed-off-by: Jonas Franz <info@jonasfranz.software> * Optimizing TotalTimes by using SumInt Signed-off-by: Jonas Franz <info@jonasfranz.software> * Fixing wrong total times for milestones caused by a missing JOIN Adding unit tests for total times Signed-off-by: Jonas Franz <info@jonasfranz.software> * Logging error instead of ignoring it Signed-off-by: Jonas Franz <info@jonasfranz.software> * Correcting spelling mistakes Signed-off-by: Jonas Franz <info@jonasfranz.software> * Change error message to a short version Signed-off-by: Jonas Franz <info@jonasfranz.software> * Add error handling to TotalTimes Add variable for totalTimes Signed-off-by: Jonas Franz <info@jonasfranz.de> * Introduce TotalTrackedTimes as variable of issue Load TotalTrackedTimes by loading attributes of IssueList Load TotalTrackedTimes by loading attributes of single issue Add Sec2Time as helper to use it in templates Signed-off-by: Jonas Franz <info@jonasfranz.software> * Fixed test + gofmt Signed-off-by: Jonas Franz <info@jonasfranz.software> * Load TotalTrackedTimes via MilestoneList instead of single requests Signed-off-by: Jonas Franz <info@jonasfranz.software> * Add documentation for MilestoneList Signed-off-by: Jonas Franz <info@jonasfranz.software> * Add documentation for MilestoneList Signed-off-by: Jonas Franz <info@jonasfranz.software> * Fix test Signed-off-by: Jonas Franz <info@jonasfranz.software> * Change comment from SQL query to description Signed-off-by: Jonas Franz <info@jonasfranz.software> * Fix unit test by using int64 instead of int Signed-off-by: Jonas Franz <info@jonasfranz.software> * Fix unit test by using int64 instead of int Signed-off-by: Jonas Franz <info@jonasfranz.software> * Check if timetracker is enabled Signed-off-by: Jonas Franz <info@jonasfranz.software> * Fix test by enabling timetracking Signed-off-by: Jonas Franz <info@jonasfranz.de>
6 years ago
Issue due date (#3794) * Started adding deadline to ui * Implemented basic issue due date managing * Improved UI for due date managing * Added at least write access to the repo in order to modify issue due dates * Ui improvements * Added issue comments creation when adding/modifying/removing a due date * Show due date in issue list * Added api support for issue due dates * Fixed lint suggestions * Added deadline to sdk * Updated css * Added support for adding/modifiying deadlines for pull requests via api * Fixed comments not created when updating or removing a deadline * update sdk (will do properly once go-gitea/go-sdk#103 is merged) * enhanced updateIssueDeadline * Removed unnessecary Issue.DeadlineString * UI improvements * Small improvments to comment creation + ui & validation improvements * Check if an issue is overdue is now a seperate function * Updated go-sdk with govendor as it was merged * Simplified isOverdue method * removed unessecary deadline to 0 set * Update swagger definitions * Added missing return * Added an explanary comment * Improved updateIssueDeadline method so it'll only update `deadline_unix` * Small changes and improvements * no need to explicitly load the issue when updating a deadline, just use whats already there * small optimisations * Added check if a deadline was modified before updating it * Moved comment creating logic into its own function * Code cleanup for creating deadline comment * locale improvement * When modifying a deadline, the old deadline is saved with the comment * small improvments to xorm session handling when updating an issue deadline + style nitpicks * style nitpicks * Moved checking for if the user has write acces to middleware
6 years ago
Shows total tracked time in issue and milestone list (#3341) * Show total tracked time in issue and milestone list Show total tracked time at issue page Signed-off-by: Jonas Franz <info@jonasfranz.software> * Optimizing TotalTimes by using SumInt Signed-off-by: Jonas Franz <info@jonasfranz.software> * Fixing wrong total times for milestones caused by a missing JOIN Adding unit tests for total times Signed-off-by: Jonas Franz <info@jonasfranz.software> * Logging error instead of ignoring it Signed-off-by: Jonas Franz <info@jonasfranz.software> * Correcting spelling mistakes Signed-off-by: Jonas Franz <info@jonasfranz.software> * Change error message to a short version Signed-off-by: Jonas Franz <info@jonasfranz.software> * Add error handling to TotalTimes Add variable for totalTimes Signed-off-by: Jonas Franz <info@jonasfranz.de> * Introduce TotalTrackedTimes as variable of issue Load TotalTrackedTimes by loading attributes of IssueList Load TotalTrackedTimes by loading attributes of single issue Add Sec2Time as helper to use it in templates Signed-off-by: Jonas Franz <info@jonasfranz.software> * Fixed test + gofmt Signed-off-by: Jonas Franz <info@jonasfranz.software> * Load TotalTrackedTimes via MilestoneList instead of single requests Signed-off-by: Jonas Franz <info@jonasfranz.software> * Add documentation for MilestoneList Signed-off-by: Jonas Franz <info@jonasfranz.software> * Add documentation for MilestoneList Signed-off-by: Jonas Franz <info@jonasfranz.software> * Fix test Signed-off-by: Jonas Franz <info@jonasfranz.software> * Change comment from SQL query to description Signed-off-by: Jonas Franz <info@jonasfranz.software> * Fix unit test by using int64 instead of int Signed-off-by: Jonas Franz <info@jonasfranz.software> * Fix unit test by using int64 instead of int Signed-off-by: Jonas Franz <info@jonasfranz.software> * Check if timetracker is enabled Signed-off-by: Jonas Franz <info@jonasfranz.software> * Fix test by enabling timetracking Signed-off-by: Jonas Franz <info@jonasfranz.de>
6 years ago
Shows total tracked time in issue and milestone list (#3341) * Show total tracked time in issue and milestone list Show total tracked time at issue page Signed-off-by: Jonas Franz <info@jonasfranz.software> * Optimizing TotalTimes by using SumInt Signed-off-by: Jonas Franz <info@jonasfranz.software> * Fixing wrong total times for milestones caused by a missing JOIN Adding unit tests for total times Signed-off-by: Jonas Franz <info@jonasfranz.software> * Logging error instead of ignoring it Signed-off-by: Jonas Franz <info@jonasfranz.software> * Correcting spelling mistakes Signed-off-by: Jonas Franz <info@jonasfranz.software> * Change error message to a short version Signed-off-by: Jonas Franz <info@jonasfranz.software> * Add error handling to TotalTimes Add variable for totalTimes Signed-off-by: Jonas Franz <info@jonasfranz.de> * Introduce TotalTrackedTimes as variable of issue Load TotalTrackedTimes by loading attributes of IssueList Load TotalTrackedTimes by loading attributes of single issue Add Sec2Time as helper to use it in templates Signed-off-by: Jonas Franz <info@jonasfranz.software> * Fixed test + gofmt Signed-off-by: Jonas Franz <info@jonasfranz.software> * Load TotalTrackedTimes via MilestoneList instead of single requests Signed-off-by: Jonas Franz <info@jonasfranz.software> * Add documentation for MilestoneList Signed-off-by: Jonas Franz <info@jonasfranz.software> * Add documentation for MilestoneList Signed-off-by: Jonas Franz <info@jonasfranz.software> * Fix test Signed-off-by: Jonas Franz <info@jonasfranz.software> * Change comment from SQL query to description Signed-off-by: Jonas Franz <info@jonasfranz.software> * Fix unit test by using int64 instead of int Signed-off-by: Jonas Franz <info@jonasfranz.software> * Fix unit test by using int64 instead of int Signed-off-by: Jonas Franz <info@jonasfranz.software> * Check if timetracker is enabled Signed-off-by: Jonas Franz <info@jonasfranz.software> * Fix test by enabling timetracking Signed-off-by: Jonas Franz <info@jonasfranz.de>
6 years ago
8 years ago
7 years ago
7 years ago
Issue due date (#3794) * Started adding deadline to ui * Implemented basic issue due date managing * Improved UI for due date managing * Added at least write access to the repo in order to modify issue due dates * Ui improvements * Added issue comments creation when adding/modifying/removing a due date * Show due date in issue list * Added api support for issue due dates * Fixed lint suggestions * Added deadline to sdk * Updated css * Added support for adding/modifiying deadlines for pull requests via api * Fixed comments not created when updating or removing a deadline * update sdk (will do properly once go-gitea/go-sdk#103 is merged) * enhanced updateIssueDeadline * Removed unnessecary Issue.DeadlineString * UI improvements * Small improvments to comment creation + ui & validation improvements * Check if an issue is overdue is now a seperate function * Updated go-sdk with govendor as it was merged * Simplified isOverdue method * removed unessecary deadline to 0 set * Update swagger definitions * Added missing return * Added an explanary comment * Improved updateIssueDeadline method so it'll only update `deadline_unix` * Small changes and improvements * no need to explicitly load the issue when updating a deadline, just use whats already there * small optimisations * Added check if a deadline was modified before updating it * Moved comment creating logic into its own function * Code cleanup for creating deadline comment * locale improvement * When modifying a deadline, the old deadline is saved with the comment * small improvments to xorm session handling when updating an issue deadline + style nitpicks * style nitpicks * Moved checking for if the user has write acces to middleware
6 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
10 years ago
10 years ago
10 years ago
10 years ago
Issue due date (#3794) * Started adding deadline to ui * Implemented basic issue due date managing * Improved UI for due date managing * Added at least write access to the repo in order to modify issue due dates * Ui improvements * Added issue comments creation when adding/modifying/removing a due date * Show due date in issue list * Added api support for issue due dates * Fixed lint suggestions * Added deadline to sdk * Updated css * Added support for adding/modifiying deadlines for pull requests via api * Fixed comments not created when updating or removing a deadline * update sdk (will do properly once go-gitea/go-sdk#103 is merged) * enhanced updateIssueDeadline * Removed unnessecary Issue.DeadlineString * UI improvements * Small improvments to comment creation + ui & validation improvements * Check if an issue is overdue is now a seperate function * Updated go-sdk with govendor as it was merged * Simplified isOverdue method * removed unessecary deadline to 0 set * Update swagger definitions * Added missing return * Added an explanary comment * Improved updateIssueDeadline method so it'll only update `deadline_unix` * Small changes and improvements * no need to explicitly load the issue when updating a deadline, just use whats already there * small optimisations * Added check if a deadline was modified before updating it * Moved comment creating logic into its own function * Code cleanup for creating deadline comment * locale improvement * When modifying a deadline, the old deadline is saved with the comment * small improvments to xorm session handling when updating an issue deadline + style nitpicks * style nitpicks * Moved checking for if the user has write acces to middleware
6 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. "fmt"
  7. "path"
  8. "regexp"
  9. "sort"
  10. "strings"
  11. "code.gitea.io/gitea/modules/base"
  12. "code.gitea.io/gitea/modules/log"
  13. "code.gitea.io/gitea/modules/setting"
  14. "code.gitea.io/gitea/modules/util"
  15. api "code.gitea.io/sdk/gitea"
  16. "github.com/Unknwon/com"
  17. "github.com/go-xorm/builder"
  18. "github.com/go-xorm/xorm"
  19. )
  20. // Issue represents an issue or pull request of repository.
  21. type Issue struct {
  22. ID int64 `xorm:"pk autoincr"`
  23. RepoID int64 `xorm:"INDEX UNIQUE(repo_index)"`
  24. Repo *Repository `xorm:"-"`
  25. Index int64 `xorm:"UNIQUE(repo_index)"` // Index in one repository.
  26. PosterID int64 `xorm:"INDEX"`
  27. Poster *User `xorm:"-"`
  28. Title string `xorm:"name"`
  29. Content string `xorm:"TEXT"`
  30. RenderedContent string `xorm:"-"`
  31. Labels []*Label `xorm:"-"`
  32. MilestoneID int64 `xorm:"INDEX"`
  33. Milestone *Milestone `xorm:"-"`
  34. Priority int
  35. AssigneeID int64 `xorm:"-"`
  36. Assignee *User `xorm:"-"`
  37. IsClosed bool `xorm:"INDEX"`
  38. IsRead bool `xorm:"-"`
  39. IsPull bool `xorm:"INDEX"` // Indicates whether is a pull request or not.
  40. PullRequest *PullRequest `xorm:"-"`
  41. NumComments int
  42. Ref string
  43. DeadlineUnix util.TimeStamp `xorm:"INDEX"`
  44. CreatedUnix util.TimeStamp `xorm:"INDEX created"`
  45. UpdatedUnix util.TimeStamp `xorm:"INDEX updated"`
  46. ClosedUnix util.TimeStamp `xorm:"INDEX"`
  47. Attachments []*Attachment `xorm:"-"`
  48. Comments []*Comment `xorm:"-"`
  49. Reactions ReactionList `xorm:"-"`
  50. TotalTrackedTime int64 `xorm:"-"`
  51. Assignees []*User `xorm:"-"`
  52. }
  53. var (
  54. issueTasksPat *regexp.Regexp
  55. issueTasksDonePat *regexp.Regexp
  56. )
  57. const issueTasksRegexpStr = `(^\s*[-*]\s\[[\sx]\]\s.)|(\n\s*[-*]\s\[[\sx]\]\s.)`
  58. const issueTasksDoneRegexpStr = `(^\s*[-*]\s\[[x]\]\s.)|(\n\s*[-*]\s\[[x]\]\s.)`
  59. func init() {
  60. issueTasksPat = regexp.MustCompile(issueTasksRegexpStr)
  61. issueTasksDonePat = regexp.MustCompile(issueTasksDoneRegexpStr)
  62. }
  63. func (issue *Issue) loadTotalTimes(e Engine) (err error) {
  64. opts := FindTrackedTimesOptions{IssueID: issue.ID}
  65. issue.TotalTrackedTime, err = opts.ToSession(e).SumInt(&TrackedTime{}, "time")
  66. if err != nil {
  67. return err
  68. }
  69. return nil
  70. }
  71. // IsOverdue checks if the issue is overdue
  72. func (issue *Issue) IsOverdue() bool {
  73. return util.TimeStampNow() >= issue.DeadlineUnix
  74. }
  75. func (issue *Issue) loadRepo(e Engine) (err error) {
  76. if issue.Repo == nil {
  77. issue.Repo, err = getRepositoryByID(e, issue.RepoID)
  78. if err != nil {
  79. return fmt.Errorf("getRepositoryByID [%d]: %v", issue.RepoID, err)
  80. }
  81. }
  82. return nil
  83. }
  84. // IsTimetrackerEnabled returns true if the repo enables timetracking
  85. func (issue *Issue) IsTimetrackerEnabled() bool {
  86. if err := issue.loadRepo(x); err != nil {
  87. log.Error(4, fmt.Sprintf("loadRepo: %v", err))
  88. return false
  89. }
  90. return issue.Repo.IsTimetrackerEnabled()
  91. }
  92. // GetPullRequest returns the issue pull request
  93. func (issue *Issue) GetPullRequest() (pr *PullRequest, err error) {
  94. if !issue.IsPull {
  95. return nil, fmt.Errorf("Issue is not a pull request")
  96. }
  97. pr, err = getPullRequestByIssueID(x, issue.ID)
  98. if err != nil {
  99. return nil, err
  100. }
  101. pr.Issue = issue
  102. return
  103. }
  104. func (issue *Issue) loadLabels(e Engine) (err error) {
  105. if issue.Labels == nil {
  106. issue.Labels, err = getLabelsByIssueID(e, issue.ID)
  107. if err != nil {
  108. return fmt.Errorf("getLabelsByIssueID [%d]: %v", issue.ID, err)
  109. }
  110. }
  111. return nil
  112. }
  113. func (issue *Issue) loadPoster(e Engine) (err error) {
  114. if issue.Poster == nil {
  115. issue.Poster, err = getUserByID(e, issue.PosterID)
  116. if err != nil {
  117. issue.PosterID = -1
  118. issue.Poster = NewGhostUser()
  119. if !IsErrUserNotExist(err) {
  120. return fmt.Errorf("getUserByID.(poster) [%d]: %v", issue.PosterID, err)
  121. }
  122. err = nil
  123. return
  124. }
  125. }
  126. return
  127. }
  128. func (issue *Issue) loadPullRequest(e Engine) (err error) {
  129. if issue.IsPull && issue.PullRequest == nil {
  130. issue.PullRequest, err = getPullRequestByIssueID(e, issue.ID)
  131. if err != nil {
  132. if IsErrPullRequestNotExist(err) {
  133. return err
  134. }
  135. return fmt.Errorf("getPullRequestByIssueID [%d]: %v", issue.ID, err)
  136. }
  137. }
  138. return nil
  139. }
  140. func (issue *Issue) loadComments(e Engine) (err error) {
  141. if issue.Comments != nil {
  142. return nil
  143. }
  144. issue.Comments, err = findComments(e, FindCommentsOptions{
  145. IssueID: issue.ID,
  146. Type: CommentTypeUnknown,
  147. })
  148. return err
  149. }
  150. func (issue *Issue) loadReactions(e Engine) (err error) {
  151. if issue.Reactions != nil {
  152. return nil
  153. }
  154. reactions, err := findReactions(e, FindReactionsOptions{
  155. IssueID: issue.ID,
  156. })
  157. if err != nil {
  158. return err
  159. }
  160. // Load reaction user data
  161. if _, err := ReactionList(reactions).LoadUsers(); err != nil {
  162. return err
  163. }
  164. // Cache comments to map
  165. comments := make(map[int64]*Comment)
  166. for _, comment := range issue.Comments {
  167. comments[comment.ID] = comment
  168. }
  169. // Add reactions either to issue or comment
  170. for _, react := range reactions {
  171. if react.CommentID == 0 {
  172. issue.Reactions = append(issue.Reactions, react)
  173. } else if comment, ok := comments[react.CommentID]; ok {
  174. comment.Reactions = append(comment.Reactions, react)
  175. }
  176. }
  177. return nil
  178. }
  179. func (issue *Issue) loadAttributes(e Engine) (err error) {
  180. if err = issue.loadRepo(e); err != nil {
  181. return
  182. }
  183. if err = issue.loadPoster(e); err != nil {
  184. return
  185. }
  186. if err = issue.loadLabels(e); err != nil {
  187. return
  188. }
  189. if issue.Milestone == nil && issue.MilestoneID > 0 {
  190. issue.Milestone, err = getMilestoneByRepoID(e, issue.RepoID, issue.MilestoneID)
  191. if err != nil && !IsErrMilestoneNotExist(err) {
  192. return fmt.Errorf("getMilestoneByRepoID [repo_id: %d, milestone_id: %d]: %v", issue.RepoID, issue.MilestoneID, err)
  193. }
  194. }
  195. if err = issue.loadAssignees(e); err != nil {
  196. return
  197. }
  198. if err = issue.loadPullRequest(e); err != nil && !IsErrPullRequestNotExist(err) {
  199. // It is possible pull request is not yet created.
  200. return err
  201. }
  202. if issue.Attachments == nil {
  203. issue.Attachments, err = getAttachmentsByIssueID(e, issue.ID)
  204. if err != nil {
  205. return fmt.Errorf("getAttachmentsByIssueID [%d]: %v", issue.ID, err)
  206. }
  207. }
  208. if err = issue.loadComments(e); err != nil {
  209. return err
  210. }
  211. if issue.IsTimetrackerEnabled() {
  212. if err = issue.loadTotalTimes(e); err != nil {
  213. return err
  214. }
  215. }
  216. return issue.loadReactions(e)
  217. }
  218. // LoadAttributes loads the attribute of this issue.
  219. func (issue *Issue) LoadAttributes() error {
  220. return issue.loadAttributes(x)
  221. }
  222. // GetIsRead load the `IsRead` field of the issue
  223. func (issue *Issue) GetIsRead(userID int64) error {
  224. issueUser := &IssueUser{IssueID: issue.ID, UID: userID}
  225. if has, err := x.Get(issueUser); err != nil {
  226. return err
  227. } else if !has {
  228. issue.IsRead = false
  229. return nil
  230. }
  231. issue.IsRead = issueUser.IsRead
  232. return nil
  233. }
  234. // APIURL returns the absolute APIURL to this issue.
  235. func (issue *Issue) APIURL() string {
  236. return issue.Repo.APIURL() + "/" + path.Join("issues", fmt.Sprint(issue.Index))
  237. }
  238. // HTMLURL returns the absolute URL to this issue.
  239. func (issue *Issue) HTMLURL() string {
  240. var path string
  241. if issue.IsPull {
  242. path = "pulls"
  243. } else {
  244. path = "issues"
  245. }
  246. return fmt.Sprintf("%s/%s/%d", issue.Repo.HTMLURL(), path, issue.Index)
  247. }
  248. // DiffURL returns the absolute URL to this diff
  249. func (issue *Issue) DiffURL() string {
  250. if issue.IsPull {
  251. return fmt.Sprintf("%s/pulls/%d.diff", issue.Repo.HTMLURL(), issue.Index)
  252. }
  253. return ""
  254. }
  255. // PatchURL returns the absolute URL to this patch
  256. func (issue *Issue) PatchURL() string {
  257. if issue.IsPull {
  258. return fmt.Sprintf("%s/pulls/%d.patch", issue.Repo.HTMLURL(), issue.Index)
  259. }
  260. return ""
  261. }
  262. // State returns string representation of issue status.
  263. func (issue *Issue) State() api.StateType {
  264. if issue.IsClosed {
  265. return api.StateClosed
  266. }
  267. return api.StateOpen
  268. }
  269. // APIFormat assumes some fields assigned with values:
  270. // Required - Poster, Labels,
  271. // Optional - Milestone, Assignee, PullRequest
  272. func (issue *Issue) APIFormat() *api.Issue {
  273. apiLabels := make([]*api.Label, len(issue.Labels))
  274. for i := range issue.Labels {
  275. apiLabels[i] = issue.Labels[i].APIFormat()
  276. }
  277. apiIssue := &api.Issue{
  278. ID: issue.ID,
  279. URL: issue.APIURL(),
  280. Index: issue.Index,
  281. Poster: issue.Poster.APIFormat(),
  282. Title: issue.Title,
  283. Body: issue.Content,
  284. Labels: apiLabels,
  285. State: issue.State(),
  286. Comments: issue.NumComments,
  287. Created: issue.CreatedUnix.AsTime(),
  288. Updated: issue.UpdatedUnix.AsTime(),
  289. }
  290. if issue.ClosedUnix != 0 {
  291. apiIssue.Closed = issue.ClosedUnix.AsTimePtr()
  292. }
  293. if issue.Milestone != nil {
  294. apiIssue.Milestone = issue.Milestone.APIFormat()
  295. }
  296. if len(issue.Assignees) > 0 {
  297. for _, assignee := range issue.Assignees {
  298. apiIssue.Assignees = append(apiIssue.Assignees, assignee.APIFormat())
  299. }
  300. apiIssue.Assignee = issue.Assignees[0].APIFormat() // For compatibility, we're keeping the first assignee as `apiIssue.Assignee`
  301. }
  302. if issue.IsPull {
  303. apiIssue.PullRequest = &api.PullRequestMeta{
  304. HasMerged: issue.PullRequest.HasMerged,
  305. }
  306. if issue.PullRequest.HasMerged {
  307. apiIssue.PullRequest.Merged = issue.PullRequest.MergedUnix.AsTimePtr()
  308. }
  309. }
  310. if issue.DeadlineUnix != 0 {
  311. apiIssue.Deadline = issue.DeadlineUnix.AsTimePtr()
  312. }
  313. return apiIssue
  314. }
  315. // HashTag returns unique hash tag for issue.
  316. func (issue *Issue) HashTag() string {
  317. return "issue-" + com.ToStr(issue.ID)
  318. }
  319. // IsPoster returns true if given user by ID is the poster.
  320. func (issue *Issue) IsPoster(uid int64) bool {
  321. return issue.PosterID == uid
  322. }
  323. func (issue *Issue) hasLabel(e Engine, labelID int64) bool {
  324. return hasIssueLabel(e, issue.ID, labelID)
  325. }
  326. // HasLabel returns true if issue has been labeled by given ID.
  327. func (issue *Issue) HasLabel(labelID int64) bool {
  328. return issue.hasLabel(x, labelID)
  329. }
  330. func (issue *Issue) sendLabelUpdatedWebhook(doer *User) {
  331. var err error
  332. if err = issue.loadRepo(x); err != nil {
  333. log.Error(4, "loadRepo: %v", err)
  334. return
  335. }
  336. if err = issue.loadPoster(x); err != nil {
  337. log.Error(4, "loadPoster: %v", err)
  338. return
  339. }
  340. mode, _ := AccessLevel(issue.Poster, issue.Repo)
  341. if issue.IsPull {
  342. if err = issue.loadPullRequest(x); err != nil {
  343. log.Error(4, "loadPullRequest: %v", err)
  344. return
  345. }
  346. if err = issue.PullRequest.LoadIssue(); err != nil {
  347. log.Error(4, "LoadIssue: %v", err)
  348. return
  349. }
  350. err = PrepareWebhooks(issue.Repo, HookEventPullRequest, &api.PullRequestPayload{
  351. Action: api.HookIssueLabelUpdated,
  352. Index: issue.Index,
  353. PullRequest: issue.PullRequest.APIFormat(),
  354. Repository: issue.Repo.APIFormat(AccessModeNone),
  355. Sender: doer.APIFormat(),
  356. })
  357. } else {
  358. err = PrepareWebhooks(issue.Repo, HookEventIssues, &api.IssuePayload{
  359. Action: api.HookIssueLabelUpdated,
  360. Index: issue.Index,
  361. Issue: issue.APIFormat(),
  362. Repository: issue.Repo.APIFormat(mode),
  363. Sender: doer.APIFormat(),
  364. })
  365. }
  366. if err != nil {
  367. log.Error(4, "PrepareWebhooks [is_pull: %v]: %v", issue.IsPull, err)
  368. } else {
  369. go HookQueue.Add(issue.RepoID)
  370. }
  371. }
  372. func (issue *Issue) addLabel(e *xorm.Session, label *Label, doer *User) error {
  373. return newIssueLabel(e, issue, label, doer)
  374. }
  375. // AddLabel adds a new label to the issue.
  376. func (issue *Issue) AddLabel(doer *User, label *Label) error {
  377. if err := NewIssueLabel(issue, label, doer); err != nil {
  378. return err
  379. }
  380. issue.sendLabelUpdatedWebhook(doer)
  381. return nil
  382. }
  383. func (issue *Issue) addLabels(e *xorm.Session, labels []*Label, doer *User) error {
  384. return newIssueLabels(e, issue, labels, doer)
  385. }
  386. // AddLabels adds a list of new labels to the issue.
  387. func (issue *Issue) AddLabels(doer *User, labels []*Label) error {
  388. if err := NewIssueLabels(issue, labels, doer); err != nil {
  389. return err
  390. }
  391. issue.sendLabelUpdatedWebhook(doer)
  392. return nil
  393. }
  394. func (issue *Issue) getLabels(e Engine) (err error) {
  395. if len(issue.Labels) > 0 {
  396. return nil
  397. }
  398. issue.Labels, err = getLabelsByIssueID(e, issue.ID)
  399. if err != nil {
  400. return fmt.Errorf("getLabelsByIssueID: %v", err)
  401. }
  402. return nil
  403. }
  404. func (issue *Issue) removeLabel(e *xorm.Session, doer *User, label *Label) error {
  405. return deleteIssueLabel(e, issue, label, doer)
  406. }
  407. // RemoveLabel removes a label from issue by given ID.
  408. func (issue *Issue) RemoveLabel(doer *User, label *Label) error {
  409. if err := issue.loadRepo(x); err != nil {
  410. return err
  411. }
  412. perm, err := GetUserRepoPermission(issue.Repo, doer)
  413. if err != nil {
  414. return err
  415. }
  416. if !perm.CanWriteIssuesOrPulls(issue.IsPull) {
  417. return ErrLabelNotExist{}
  418. }
  419. if err := DeleteIssueLabel(issue, label, doer); err != nil {
  420. return err
  421. }
  422. issue.sendLabelUpdatedWebhook(doer)
  423. return nil
  424. }
  425. func (issue *Issue) clearLabels(e *xorm.Session, doer *User) (err error) {
  426. if err = issue.getLabels(e); err != nil {
  427. return fmt.Errorf("getLabels: %v", err)
  428. }
  429. for i := range issue.Labels {
  430. if err = issue.removeLabel(e, doer, issue.Labels[i]); err != nil {
  431. return fmt.Errorf("removeLabel: %v", err)
  432. }
  433. }
  434. return nil
  435. }
  436. // ClearLabels removes all issue labels as the given user.
  437. // Triggers appropriate WebHooks, if any.
  438. func (issue *Issue) ClearLabels(doer *User) (err error) {
  439. sess := x.NewSession()
  440. defer sess.Close()
  441. if err = sess.Begin(); err != nil {
  442. return err
  443. }
  444. if err := issue.loadRepo(sess); err != nil {
  445. return err
  446. } else if err = issue.loadPullRequest(sess); err != nil {
  447. return err
  448. }
  449. perm, err := getUserRepoPermission(sess, issue.Repo, doer)
  450. if err != nil {
  451. return err
  452. }
  453. if !perm.CanWriteIssuesOrPulls(issue.IsPull) {
  454. return ErrLabelNotExist{}
  455. }
  456. if err = issue.clearLabels(sess, doer); err != nil {
  457. return err
  458. }
  459. if err = sess.Commit(); err != nil {
  460. return fmt.Errorf("Commit: %v", err)
  461. }
  462. if err = issue.loadPoster(x); err != nil {
  463. return fmt.Errorf("loadPoster: %v", err)
  464. }
  465. mode, _ := AccessLevel(issue.Poster, issue.Repo)
  466. if issue.IsPull {
  467. err = issue.PullRequest.LoadIssue()
  468. if err != nil {
  469. log.Error(4, "LoadIssue: %v", err)
  470. return
  471. }
  472. err = PrepareWebhooks(issue.Repo, HookEventPullRequest, &api.PullRequestPayload{
  473. Action: api.HookIssueLabelCleared,
  474. Index: issue.Index,
  475. PullRequest: issue.PullRequest.APIFormat(),
  476. Repository: issue.Repo.APIFormat(mode),
  477. Sender: doer.APIFormat(),
  478. })
  479. } else {
  480. err = PrepareWebhooks(issue.Repo, HookEventIssues, &api.IssuePayload{
  481. Action: api.HookIssueLabelCleared,
  482. Index: issue.Index,
  483. Issue: issue.APIFormat(),
  484. Repository: issue.Repo.APIFormat(mode),
  485. Sender: doer.APIFormat(),
  486. })
  487. }
  488. if err != nil {
  489. log.Error(4, "PrepareWebhooks [is_pull: %v]: %v", issue.IsPull, err)
  490. } else {
  491. go HookQueue.Add(issue.RepoID)
  492. }
  493. return nil
  494. }
  495. type labelSorter []*Label
  496. func (ts labelSorter) Len() int {
  497. return len([]*Label(ts))
  498. }
  499. func (ts labelSorter) Less(i, j int) bool {
  500. return []*Label(ts)[i].ID < []*Label(ts)[j].ID
  501. }
  502. func (ts labelSorter) Swap(i, j int) {
  503. []*Label(ts)[i], []*Label(ts)[j] = []*Label(ts)[j], []*Label(ts)[i]
  504. }
  505. // ReplaceLabels removes all current labels and add new labels to the issue.
  506. // Triggers appropriate WebHooks, if any.
  507. func (issue *Issue) ReplaceLabels(labels []*Label, doer *User) (err error) {
  508. sess := x.NewSession()
  509. defer sess.Close()
  510. if err = sess.Begin(); err != nil {
  511. return err
  512. }
  513. if err = issue.loadLabels(sess); err != nil {
  514. return err
  515. }
  516. sort.Sort(labelSorter(labels))
  517. sort.Sort(labelSorter(issue.Labels))
  518. var toAdd, toRemove []*Label
  519. addIndex, removeIndex := 0, 0
  520. for addIndex < len(labels) && removeIndex < len(issue.Labels) {
  521. addLabel := labels[addIndex]
  522. removeLabel := issue.Labels[removeIndex]
  523. if addLabel.ID == removeLabel.ID {
  524. addIndex++
  525. removeIndex++
  526. } else if addLabel.ID < removeLabel.ID {
  527. toAdd = append(toAdd, addLabel)
  528. addIndex++
  529. } else {
  530. toRemove = append(toRemove, removeLabel)
  531. removeIndex++
  532. }
  533. }
  534. toAdd = append(toAdd, labels[addIndex:]...)
  535. toRemove = append(toRemove, issue.Labels[removeIndex:]...)
  536. if len(toAdd) > 0 {
  537. if err = issue.addLabels(sess, toAdd, doer); err != nil {
  538. return fmt.Errorf("addLabels: %v", err)
  539. }
  540. }
  541. for _, l := range toRemove {
  542. if err = issue.removeLabel(sess, doer, l); err != nil {
  543. return fmt.Errorf("removeLabel: %v", err)
  544. }
  545. }
  546. return sess.Commit()
  547. }
  548. // ReadBy sets issue to be read by given user.
  549. func (issue *Issue) ReadBy(userID int64) error {
  550. if err := UpdateIssueUserByRead(userID, issue.ID); err != nil {
  551. return err
  552. }
  553. return setNotificationStatusReadIfUnread(x, userID, issue.ID)
  554. }
  555. func updateIssueCols(e Engine, issue *Issue, cols ...string) error {
  556. if _, err := e.ID(issue.ID).Cols(cols...).Update(issue); err != nil {
  557. return err
  558. }
  559. UpdateIssueIndexerCols(issue.ID, cols...)
  560. return nil
  561. }
  562. // UpdateIssueCols only updates values of specific columns for given issue.
  563. func UpdateIssueCols(issue *Issue, cols ...string) error {
  564. return updateIssueCols(x, issue, cols...)
  565. }
  566. func (issue *Issue) changeStatus(e *xorm.Session, doer *User, repo *Repository, isClosed bool) (err error) {
  567. // Nothing should be performed if current status is same as target status
  568. if issue.IsClosed == isClosed {
  569. return nil
  570. }
  571. // Check for open dependencies
  572. if isClosed && issue.Repo.isDependenciesEnabled(e) {
  573. // only check if dependencies are enabled and we're about to close an issue, otherwise reopening an issue would fail when there are unsatisfied dependencies
  574. noDeps, err := issueNoDependenciesLeft(e, issue)
  575. if err != nil {
  576. return err
  577. }
  578. if !noDeps {
  579. return ErrDependenciesLeft{issue.ID}
  580. }
  581. }
  582. issue.IsClosed = isClosed
  583. if isClosed {
  584. issue.ClosedUnix = util.TimeStampNow()
  585. } else {
  586. issue.ClosedUnix = 0
  587. }
  588. if err = updateIssueCols(e, issue, "is_closed", "closed_unix"); err != nil {
  589. return err
  590. }
  591. // Update issue count of labels
  592. if err = issue.getLabels(e); err != nil {
  593. return err
  594. }
  595. for idx := range issue.Labels {
  596. if issue.IsClosed {
  597. issue.Labels[idx].NumClosedIssues++
  598. } else {
  599. issue.Labels[idx].NumClosedIssues--
  600. }
  601. if err = updateLabel(e, issue.Labels[idx]); err != nil {
  602. return err
  603. }
  604. }
  605. // Update issue count of milestone
  606. if err = changeMilestoneIssueStats(e, issue); err != nil {
  607. return err
  608. }
  609. // New action comment
  610. if _, err = createStatusComment(e, doer, repo, issue); err != nil {
  611. return err
  612. }
  613. return nil
  614. }
  615. // ChangeStatus changes issue status to open or closed.
  616. func (issue *Issue) ChangeStatus(doer *User, repo *Repository, isClosed bool) (err error) {
  617. sess := x.NewSession()
  618. defer sess.Close()
  619. if err = sess.Begin(); err != nil {
  620. return err
  621. }
  622. if err = issue.changeStatus(sess, doer, repo, isClosed); err != nil {
  623. return err
  624. }
  625. if err = sess.Commit(); err != nil {
  626. return fmt.Errorf("Commit: %v", err)
  627. }
  628. sess.Close()
  629. mode, _ := AccessLevel(issue.Poster, issue.Repo)
  630. if issue.IsPull {
  631. // Merge pull request calls issue.changeStatus so we need to handle separately.
  632. issue.PullRequest.Issue = issue
  633. apiPullRequest := &api.PullRequestPayload{
  634. Index: issue.Index,
  635. PullRequest: issue.PullRequest.APIFormat(),
  636. Repository: repo.APIFormat(mode),
  637. Sender: doer.APIFormat(),
  638. }
  639. if isClosed {
  640. apiPullRequest.Action = api.HookIssueClosed
  641. } else {
  642. apiPullRequest.Action = api.HookIssueReOpened
  643. }
  644. err = PrepareWebhooks(repo, HookEventPullRequest, apiPullRequest)
  645. } else {
  646. apiIssue := &api.IssuePayload{
  647. Index: issue.Index,
  648. Issue: issue.APIFormat(),
  649. Repository: repo.APIFormat(mode),
  650. Sender: doer.APIFormat(),
  651. }
  652. if isClosed {
  653. apiIssue.Action = api.HookIssueClosed
  654. } else {
  655. apiIssue.Action = api.HookIssueReOpened
  656. }
  657. err = PrepareWebhooks(repo, HookEventIssues, apiIssue)
  658. }
  659. if err != nil {
  660. log.Error(4, "PrepareWebhooks [is_pull: %v, is_closed: %v]: %v", issue.IsPull, isClosed, err)
  661. } else {
  662. go HookQueue.Add(repo.ID)
  663. }
  664. return nil
  665. }
  666. // ChangeTitle changes the title of this issue, as the given user.
  667. func (issue *Issue) ChangeTitle(doer *User, title string) (err error) {
  668. oldTitle := issue.Title
  669. issue.Title = title
  670. sess := x.NewSession()
  671. defer sess.Close()
  672. if err = sess.Begin(); err != nil {
  673. return err
  674. }
  675. if err = updateIssueCols(sess, issue, "name"); err != nil {
  676. return fmt.Errorf("updateIssueCols: %v", err)
  677. }
  678. if _, err = createChangeTitleComment(sess, doer, issue.Repo, issue, oldTitle, title); err != nil {
  679. return fmt.Errorf("createChangeTitleComment: %v", err)
  680. }
  681. if err = sess.Commit(); err != nil {
  682. return err
  683. }
  684. mode, _ := AccessLevel(issue.Poster, issue.Repo)
  685. if issue.IsPull {
  686. issue.PullRequest.Issue = issue
  687. err = PrepareWebhooks(issue.Repo, HookEventPullRequest, &api.PullRequestPayload{
  688. Action: api.HookIssueEdited,
  689. Index: issue.Index,
  690. Changes: &api.ChangesPayload{
  691. Title: &api.ChangesFromPayload{
  692. From: oldTitle,
  693. },
  694. },
  695. PullRequest: issue.PullRequest.APIFormat(),
  696. Repository: issue.Repo.APIFormat(mode),
  697. Sender: doer.APIFormat(),
  698. })
  699. } else {
  700. err = PrepareWebhooks(issue.Repo, HookEventIssues, &api.IssuePayload{
  701. Action: api.HookIssueEdited,
  702. Index: issue.Index,
  703. Changes: &api.ChangesPayload{
  704. Title: &api.ChangesFromPayload{
  705. From: oldTitle,
  706. },
  707. },
  708. Issue: issue.APIFormat(),
  709. Repository: issue.Repo.APIFormat(mode),
  710. Sender: issue.Poster.APIFormat(),
  711. })
  712. }
  713. if err != nil {
  714. log.Error(4, "PrepareWebhooks [is_pull: %v]: %v", issue.IsPull, err)
  715. } else {
  716. go HookQueue.Add(issue.RepoID)
  717. }
  718. return nil
  719. }
  720. // AddDeletePRBranchComment adds delete branch comment for pull request issue
  721. func AddDeletePRBranchComment(doer *User, repo *Repository, issueID int64, branchName string) error {
  722. issue, err := getIssueByID(x, issueID)
  723. if err != nil {
  724. return err
  725. }
  726. sess := x.NewSession()
  727. defer sess.Close()
  728. if err := sess.Begin(); err != nil {
  729. return err
  730. }
  731. if _, err := createDeleteBranchComment(sess, doer, repo, issue, branchName); err != nil {
  732. return err
  733. }
  734. return sess.Commit()
  735. }
  736. // ChangeContent changes issue content, as the given user.
  737. func (issue *Issue) ChangeContent(doer *User, content string) (err error) {
  738. oldContent := issue.Content
  739. issue.Content = content
  740. if err = UpdateIssueCols(issue, "content"); err != nil {
  741. return fmt.Errorf("UpdateIssueCols: %v", err)
  742. }
  743. mode, _ := AccessLevel(issue.Poster, issue.Repo)
  744. if issue.IsPull {
  745. issue.PullRequest.Issue = issue
  746. err = PrepareWebhooks(issue.Repo, HookEventPullRequest, &api.PullRequestPayload{
  747. Action: api.HookIssueEdited,
  748. Index: issue.Index,
  749. Changes: &api.ChangesPayload{
  750. Body: &api.ChangesFromPayload{
  751. From: oldContent,
  752. },
  753. },
  754. PullRequest: issue.PullRequest.APIFormat(),
  755. Repository: issue.Repo.APIFormat(mode),
  756. Sender: doer.APIFormat(),
  757. })
  758. } else {
  759. err = PrepareWebhooks(issue.Repo, HookEventIssues, &api.IssuePayload{
  760. Action: api.HookIssueEdited,
  761. Index: issue.Index,
  762. Changes: &api.ChangesPayload{
  763. Body: &api.ChangesFromPayload{
  764. From: oldContent,
  765. },
  766. },
  767. Issue: issue.APIFormat(),
  768. Repository: issue.Repo.APIFormat(mode),
  769. Sender: doer.APIFormat(),
  770. })
  771. }
  772. if err != nil {
  773. log.Error(4, "PrepareWebhooks [is_pull: %v]: %v", issue.IsPull, err)
  774. } else {
  775. go HookQueue.Add(issue.RepoID)
  776. }
  777. return nil
  778. }
  779. // GetTasks returns the amount of tasks in the issues content
  780. func (issue *Issue) GetTasks() int {
  781. return len(issueTasksPat.FindAllStringIndex(issue.Content, -1))
  782. }
  783. // GetTasksDone returns the amount of completed tasks in the issues content
  784. func (issue *Issue) GetTasksDone() int {
  785. return len(issueTasksDonePat.FindAllStringIndex(issue.Content, -1))
  786. }
  787. // NewIssueOptions represents the options of a new issue.
  788. type NewIssueOptions struct {
  789. Repo *Repository
  790. Issue *Issue
  791. LabelIDs []int64
  792. AssigneeIDs []int64
  793. Attachments []string // In UUID format.
  794. IsPull bool
  795. }
  796. func newIssue(e *xorm.Session, doer *User, opts NewIssueOptions) (err error) {
  797. opts.Issue.Title = strings.TrimSpace(opts.Issue.Title)
  798. opts.Issue.Index = opts.Repo.NextIssueIndex()
  799. if opts.Issue.MilestoneID > 0 {
  800. milestone, err := getMilestoneByRepoID(e, opts.Issue.RepoID, opts.Issue.MilestoneID)
  801. if err != nil && !IsErrMilestoneNotExist(err) {
  802. return fmt.Errorf("getMilestoneByID: %v", err)
  803. }
  804. // Assume milestone is invalid and drop silently.
  805. opts.Issue.MilestoneID = 0
  806. if milestone != nil {
  807. opts.Issue.MilestoneID = milestone.ID
  808. opts.Issue.Milestone = milestone
  809. }
  810. }
  811. // Keep the old assignee id thingy for compatibility reasons
  812. if opts.Issue.AssigneeID > 0 {
  813. isAdded := false
  814. // Check if the user has already been passed to issue.AssigneeIDs, if not, add it
  815. for _, aID := range opts.AssigneeIDs {
  816. if aID == opts.Issue.AssigneeID {
  817. isAdded = true
  818. break
  819. }
  820. }
  821. if !isAdded {
  822. opts.AssigneeIDs = append(opts.AssigneeIDs, opts.Issue.AssigneeID)
  823. }
  824. }
  825. // Check for and validate assignees
  826. if len(opts.AssigneeIDs) > 0 {
  827. for _, assigneeID := range opts.AssigneeIDs {
  828. user, err := getUserByID(e, assigneeID)
  829. if err != nil {
  830. return fmt.Errorf("getUserByID [user_id: %d, repo_id: %d]: %v", assigneeID, opts.Repo.ID, err)
  831. }
  832. valid, err := canBeAssigned(e, user, opts.Repo)
  833. if err != nil {
  834. return fmt.Errorf("canBeAssigned [user_id: %d, repo_id: %d]: %v", assigneeID, opts.Repo.ID, err)
  835. }
  836. if !valid {
  837. return ErrUserDoesNotHaveAccessToRepo{UserID: assigneeID, RepoName: opts.Repo.Name}
  838. }
  839. }
  840. }
  841. // Milestone and assignee validation should happen before insert actual object.
  842. if _, err = e.Insert(opts.Issue); err != nil {
  843. return err
  844. }
  845. if opts.Issue.MilestoneID > 0 {
  846. if err = changeMilestoneAssign(e, doer, opts.Issue, -1); err != nil {
  847. return err
  848. }
  849. }
  850. // Insert the assignees
  851. for _, assigneeID := range opts.AssigneeIDs {
  852. err = opts.Issue.changeAssignee(e, doer, assigneeID, true)
  853. if err != nil {
  854. return err
  855. }
  856. }
  857. if opts.IsPull {
  858. _, err = e.Exec("UPDATE `repository` SET num_pulls = num_pulls + 1 WHERE id = ?", opts.Issue.RepoID)
  859. } else {
  860. _, err = e.Exec("UPDATE `repository` SET num_issues = num_issues + 1 WHERE id = ?", opts.Issue.RepoID)
  861. }
  862. if err != nil {
  863. return err
  864. }
  865. if len(opts.LabelIDs) > 0 {
  866. // During the session, SQLite3 driver cannot handle retrieve objects after update something.
  867. // So we have to get all needed labels first.
  868. labels := make([]*Label, 0, len(opts.LabelIDs))
  869. if err = e.In("id", opts.LabelIDs).Find(&labels); err != nil {
  870. return fmt.Errorf("find all labels [label_ids: %v]: %v", opts.LabelIDs, err)
  871. }
  872. if err = opts.Issue.loadPoster(e); err != nil {
  873. return err
  874. }
  875. for _, label := range labels {
  876. // Silently drop invalid labels.
  877. if label.RepoID != opts.Repo.ID {
  878. continue
  879. }
  880. if err = opts.Issue.addLabel(e, label, opts.Issue.Poster); err != nil {
  881. return fmt.Errorf("addLabel [id: %d]: %v", label.ID, err)
  882. }
  883. }
  884. }
  885. if err = newIssueUsers(e, opts.Repo, opts.Issue); err != nil {
  886. return err
  887. }
  888. if len(opts.Attachments) > 0 {
  889. attachments, err := getAttachmentsByUUIDs(e, opts.Attachments)
  890. if err != nil {
  891. return fmt.Errorf("getAttachmentsByUUIDs [uuids: %v]: %v", opts.Attachments, err)
  892. }
  893. for i := 0; i < len(attachments); i++ {
  894. attachments[i].IssueID = opts.Issue.ID
  895. if _, err = e.ID(attachments[i].ID).Update(attachments[i]); err != nil {
  896. return fmt.Errorf("update attachment [id: %d]: %v", attachments[i].ID, err)
  897. }
  898. }
  899. }
  900. return opts.Issue.loadAttributes(e)
  901. }
  902. // NewIssue creates new issue with labels for repository.
  903. func NewIssue(repo *Repository, issue *Issue, labelIDs []int64, assigneeIDs []int64, uuids []string) (err error) {
  904. sess := x.NewSession()
  905. defer sess.Close()
  906. if err = sess.Begin(); err != nil {
  907. return err
  908. }
  909. if err = newIssue(sess, issue.Poster, NewIssueOptions{
  910. Repo: repo,
  911. Issue: issue,
  912. LabelIDs: labelIDs,
  913. Attachments: uuids,
  914. AssigneeIDs: assigneeIDs,
  915. }); err != nil {
  916. if IsErrUserDoesNotHaveAccessToRepo(err) {
  917. return err
  918. }
  919. return fmt.Errorf("newIssue: %v", err)
  920. }
  921. if err = sess.Commit(); err != nil {
  922. return fmt.Errorf("Commit: %v", err)
  923. }
  924. UpdateIssueIndexer(issue.ID)
  925. if err = NotifyWatchers(&Action{
  926. ActUserID: issue.Poster.ID,
  927. ActUser: issue.Poster,
  928. OpType: ActionCreateIssue,
  929. Content: fmt.Sprintf("%d|%s", issue.Index, issue.Title),
  930. RepoID: repo.ID,
  931. Repo: repo,
  932. IsPrivate: repo.IsPrivate,
  933. }); err != nil {
  934. log.Error(4, "NotifyWatchers: %v", err)
  935. }
  936. if err = issue.MailParticipants(); err != nil {
  937. log.Error(4, "MailParticipants: %v", err)
  938. }
  939. mode, _ := AccessLevel(issue.Poster, issue.Repo)
  940. if err = PrepareWebhooks(repo, HookEventIssues, &api.IssuePayload{
  941. Action: api.HookIssueOpened,
  942. Index: issue.Index,
  943. Issue: issue.APIFormat(),
  944. Repository: repo.APIFormat(mode),
  945. Sender: issue.Poster.APIFormat(),
  946. }); err != nil {
  947. log.Error(4, "PrepareWebhooks: %v", err)
  948. } else {
  949. go HookQueue.Add(issue.RepoID)
  950. }
  951. return nil
  952. }
  953. // GetRawIssueByIndex returns raw issue without loading attributes by index in a repository.
  954. func GetRawIssueByIndex(repoID, index int64) (*Issue, error) {
  955. issue := &Issue{
  956. RepoID: repoID,
  957. Index: index,
  958. }
  959. has, err := x.Get(issue)
  960. if err != nil {
  961. return nil, err
  962. } else if !has {
  963. return nil, ErrIssueNotExist{0, repoID, index}
  964. }
  965. return issue, nil
  966. }
  967. // GetIssueByIndex returns issue by index in a repository.
  968. func GetIssueByIndex(repoID, index int64) (*Issue, error) {
  969. issue, err := GetRawIssueByIndex(repoID, index)
  970. if err != nil {
  971. return nil, err
  972. }
  973. return issue, issue.LoadAttributes()
  974. }
  975. func getIssueByID(e Engine, id int64) (*Issue, error) {
  976. issue := new(Issue)
  977. has, err := e.ID(id).Get(issue)
  978. if err != nil {
  979. return nil, err
  980. } else if !has {
  981. return nil, ErrIssueNotExist{id, 0, 0}
  982. }
  983. return issue, issue.loadAttributes(e)
  984. }
  985. // GetIssueByID returns an issue by given ID.
  986. func GetIssueByID(id int64) (*Issue, error) {
  987. return getIssueByID(x, id)
  988. }
  989. func getIssuesByIDs(e Engine, issueIDs []int64) ([]*Issue, error) {
  990. issues := make([]*Issue, 0, 10)
  991. return issues, e.In("id", issueIDs).Find(&issues)
  992. }
  993. // GetIssuesByIDs return issues with the given IDs.
  994. func GetIssuesByIDs(issueIDs []int64) ([]*Issue, error) {
  995. return getIssuesByIDs(x, issueIDs)
  996. }
  997. // IssuesOptions represents options of an issue.
  998. type IssuesOptions struct {
  999. RepoIDs []int64 // include all repos if empty
  1000. AssigneeID int64
  1001. PosterID int64
  1002. MentionedID int64
  1003. MilestoneID int64
  1004. Page int
  1005. PageSize int
  1006. IsClosed util.OptionalBool
  1007. IsPull util.OptionalBool
  1008. Labels string
  1009. SortType string
  1010. IssueIDs []int64
  1011. }
  1012. // sortIssuesSession sort an issues-related session based on the provided
  1013. // sortType string
  1014. func sortIssuesSession(sess *xorm.Session, sortType string) {
  1015. switch sortType {
  1016. case "oldest":
  1017. sess.Asc("issue.created_unix")
  1018. case "recentupdate":
  1019. sess.Desc("issue.updated_unix")
  1020. case "leastupdate":
  1021. sess.Asc("issue.updated_unix")
  1022. case "mostcomment":
  1023. sess.Desc("issue.num_comments")
  1024. case "leastcomment":
  1025. sess.Asc("issue.num_comments")
  1026. case "priority":
  1027. sess.Desc("issue.priority")
  1028. default:
  1029. sess.Desc("issue.created_unix")
  1030. }
  1031. }
  1032. func (opts *IssuesOptions) setupSession(sess *xorm.Session) error {
  1033. if opts.Page >= 0 && opts.PageSize > 0 {
  1034. var start int
  1035. if opts.Page == 0 {
  1036. start = 0
  1037. } else {
  1038. start = (opts.Page - 1) * opts.PageSize
  1039. }
  1040. sess.Limit(opts.PageSize, start)
  1041. }
  1042. if len(opts.IssueIDs) > 0 {
  1043. sess.In("issue.id", opts.IssueIDs)
  1044. }
  1045. if len(opts.RepoIDs) > 0 {
  1046. // In case repository IDs are provided but actually no repository has issue.
  1047. sess.In("issue.repo_id", opts.RepoIDs)
  1048. }
  1049. switch opts.IsClosed {
  1050. case util.OptionalBoolTrue:
  1051. sess.And("issue.is_closed=?", true)
  1052. case util.OptionalBoolFalse:
  1053. sess.And("issue.is_closed=?", false)
  1054. }
  1055. if opts.AssigneeID > 0 {
  1056. sess.Join("INNER", "issue_assignees", "issue.id = issue_assignees.issue_id").
  1057. And("issue_assignees.assignee_id = ?", opts.AssigneeID)
  1058. }
  1059. if opts.PosterID > 0 {
  1060. sess.And("issue.poster_id=?", opts.PosterID)
  1061. }
  1062. if opts.MentionedID > 0 {
  1063. sess.Join("INNER", "issue_user", "issue.id = issue_user.issue_id").
  1064. And("issue_user.is_mentioned = ?", true).
  1065. And("issue_user.uid = ?", opts.MentionedID)
  1066. }
  1067. if opts.MilestoneID > 0 {
  1068. sess.And("issue.milestone_id=?", opts.MilestoneID)
  1069. }
  1070. switch opts.IsPull {
  1071. case util.OptionalBoolTrue:
  1072. sess.And("issue.is_pull=?", true)
  1073. case util.OptionalBoolFalse:
  1074. sess.And("issue.is_pull=?", false)
  1075. }
  1076. if len(opts.Labels) > 0 && opts.Labels != "0" {
  1077. labelIDs, err := base.StringsToInt64s(strings.Split(opts.Labels, ","))
  1078. if err != nil {
  1079. return err
  1080. }
  1081. if len(labelIDs) > 0 {
  1082. sess.
  1083. Join("INNER", "issue_label", "issue.id = issue_label.issue_id").
  1084. In("issue_label.label_id", labelIDs)
  1085. }
  1086. }
  1087. return nil
  1088. }
  1089. // CountIssuesByRepo map from repoID to number of issues matching the options
  1090. func CountIssuesByRepo(opts *IssuesOptions) (map[int64]int64, error) {
  1091. sess := x.NewSession()
  1092. defer sess.Close()
  1093. if err := opts.setupSession(sess); err != nil {
  1094. return nil, err
  1095. }
  1096. countsSlice := make([]*struct {
  1097. RepoID int64
  1098. Count int64
  1099. }, 0, 10)
  1100. if err := sess.GroupBy("issue.repo_id").
  1101. Select("issue.repo_id AS repo_id, COUNT(*) AS count").
  1102. Table("issue").
  1103. Find(&countsSlice); err != nil {
  1104. return nil, err
  1105. }
  1106. countMap := make(map[int64]int64, len(countsSlice))
  1107. for _, c := range countsSlice {
  1108. countMap[c.RepoID] = c.Count
  1109. }
  1110. return countMap, nil
  1111. }
  1112. // Issues returns a list of issues by given conditions.
  1113. func Issues(opts *IssuesOptions) ([]*Issue, error) {
  1114. sess := x.NewSession()
  1115. defer sess.Close()
  1116. if err := opts.setupSession(sess); err != nil {
  1117. return nil, err
  1118. }
  1119. sortIssuesSession(sess, opts.SortType)
  1120. issues := make([]*Issue, 0, setting.UI.IssuePagingNum)
  1121. if err := sess.Find(&issues); err != nil {
  1122. return nil, fmt.Errorf("Find: %v", err)
  1123. }
  1124. if err := IssueList(issues).LoadAttributes(); err != nil {
  1125. return nil, fmt.Errorf("LoadAttributes: %v", err)
  1126. }
  1127. return issues, nil
  1128. }
  1129. // GetParticipantsByIssueID returns all users who are participated in comments of an issue.
  1130. func GetParticipantsByIssueID(issueID int64) ([]*User, error) {
  1131. return getParticipantsByIssueID(x, issueID)
  1132. }
  1133. func getParticipantsByIssueID(e Engine, issueID int64) ([]*User, error) {
  1134. userIDs := make([]int64, 0, 5)
  1135. if err := e.Table("comment").Cols("poster_id").
  1136. Where("`comment`.issue_id = ?", issueID).
  1137. And("`comment`.type = ?", CommentTypeComment).
  1138. And("`user`.is_active = ?", true).
  1139. And("`user`.prohibit_login = ?", false).
  1140. Join("INNER", "`user`", "`user`.id = `comment`.poster_id").
  1141. Distinct("poster_id").
  1142. Find(&userIDs); err != nil {
  1143. return nil, fmt.Errorf("get poster IDs: %v", err)
  1144. }
  1145. if len(userIDs) == 0 {
  1146. return nil, nil
  1147. }
  1148. users := make([]*User, 0, len(userIDs))
  1149. return users, e.In("id", userIDs).Find(&users)
  1150. }
  1151. // UpdateIssueMentions extracts mentioned people from content and
  1152. // updates issue-user relations for them.
  1153. func UpdateIssueMentions(e Engine, issueID int64, mentions []string) error {
  1154. if len(mentions) == 0 {
  1155. return nil
  1156. }
  1157. for i := range mentions {
  1158. mentions[i] = strings.ToLower(mentions[i])
  1159. }
  1160. users := make([]*User, 0, len(mentions))
  1161. if err := e.In("lower_name", mentions).Asc("lower_name").Find(&users); err != nil {
  1162. return fmt.Errorf("find mentioned users: %v", err)
  1163. }
  1164. ids := make([]int64, 0, len(mentions))
  1165. for _, user := range users {
  1166. ids = append(ids, user.ID)
  1167. if !user.IsOrganization() || user.NumMembers == 0 {
  1168. continue
  1169. }
  1170. memberIDs := make([]int64, 0, user.NumMembers)
  1171. orgUsers, err := GetOrgUsersByOrgID(user.ID)
  1172. if err != nil {
  1173. return fmt.Errorf("GetOrgUsersByOrgID [%d]: %v", user.ID, err)
  1174. }
  1175. for _, orgUser := range orgUsers {
  1176. memberIDs = append(memberIDs, orgUser.ID)
  1177. }
  1178. ids = append(ids, memberIDs...)
  1179. }
  1180. if err := UpdateIssueUsersByMentions(e, issueID, ids); err != nil {
  1181. return fmt.Errorf("UpdateIssueUsersByMentions: %v", err)
  1182. }
  1183. return nil
  1184. }
  1185. // IssueStats represents issue statistic information.
  1186. type IssueStats struct {
  1187. OpenCount, ClosedCount int64
  1188. YourRepositoriesCount int64
  1189. AssignCount int64
  1190. CreateCount int64
  1191. MentionCount int64
  1192. }
  1193. // Filter modes.
  1194. const (
  1195. FilterModeAll = iota
  1196. FilterModeAssign
  1197. FilterModeCreate
  1198. FilterModeMention
  1199. )
  1200. func parseCountResult(results []map[string][]byte) int64 {
  1201. if len(results) == 0 {
  1202. return 0
  1203. }
  1204. for _, result := range results[0] {
  1205. return com.StrTo(string(result)).MustInt64()
  1206. }
  1207. return 0
  1208. }
  1209. // IssueStatsOptions contains parameters accepted by GetIssueStats.
  1210. type IssueStatsOptions struct {
  1211. RepoID int64
  1212. Labels string
  1213. MilestoneID int64
  1214. AssigneeID int64
  1215. MentionedID int64
  1216. PosterID int64
  1217. IsPull util.OptionalBool
  1218. IssueIDs []int64
  1219. }
  1220. // GetIssueStats returns issue statistic information by given conditions.
  1221. func GetIssueStats(opts *IssueStatsOptions) (*IssueStats, error) {
  1222. stats := &IssueStats{}
  1223. countSession := func(opts *IssueStatsOptions) *xorm.Session {
  1224. sess := x.
  1225. Where("issue.repo_id = ?", opts.RepoID)
  1226. if len(opts.IssueIDs) > 0 {
  1227. sess.In("issue.id", opts.IssueIDs)
  1228. }
  1229. if len(opts.Labels) > 0 && opts.Labels != "0" {
  1230. labelIDs, err := base.StringsToInt64s(strings.Split(opts.Labels, ","))
  1231. if err != nil {
  1232. log.Warn("Malformed Labels argument: %s", opts.Labels)
  1233. } else if len(labelIDs) > 0 {
  1234. sess.Join("INNER", "issue_label", "issue.id = issue_label.issue_id").
  1235. In("issue_label.label_id", labelIDs)
  1236. }
  1237. }
  1238. if opts.MilestoneID > 0 {
  1239. sess.And("issue.milestone_id = ?", opts.MilestoneID)
  1240. }
  1241. if opts.AssigneeID > 0 {
  1242. sess.Join("INNER", "issue_assignees", "issue.id = issue_assignees.issue_id").
  1243. And("issue_assignees.assignee_id = ?", opts.AssigneeID)
  1244. }
  1245. if opts.PosterID > 0 {
  1246. sess.And("issue.poster_id = ?", opts.PosterID)
  1247. }
  1248. if opts.MentionedID > 0 {
  1249. sess.Join("INNER", "issue_user", "issue.id = issue_user.issue_id").
  1250. And("issue_user.uid = ?", opts.MentionedID).
  1251. And("issue_user.is_mentioned = ?", true)
  1252. }
  1253. switch opts.IsPull {
  1254. case util.OptionalBoolTrue:
  1255. sess.And("issue.is_pull=?", true)
  1256. case util.OptionalBoolFalse:
  1257. sess.And("issue.is_pull=?", false)
  1258. }
  1259. return sess
  1260. }
  1261. var err error
  1262. stats.OpenCount, err = countSession(opts).
  1263. And("issue.is_closed = ?", false).
  1264. Count(new(Issue))
  1265. if err != nil {
  1266. return stats, err
  1267. }
  1268. stats.ClosedCount, err = countSession(opts).
  1269. And("issue.is_closed = ?", true).
  1270. Count(new(Issue))
  1271. return stats, err
  1272. }
  1273. // UserIssueStatsOptions contains parameters accepted by GetUserIssueStats.
  1274. type UserIssueStatsOptions struct {
  1275. UserID int64
  1276. RepoID int64
  1277. UserRepoIDs []int64
  1278. FilterMode int
  1279. IsPull bool
  1280. IsClosed bool
  1281. }
  1282. // GetUserIssueStats returns issue statistic information for dashboard by given conditions.
  1283. func GetUserIssueStats(opts UserIssueStatsOptions) (*IssueStats, error) {
  1284. var err error
  1285. stats := &IssueStats{}
  1286. cond := builder.NewCond()
  1287. cond = cond.And(builder.Eq{"issue.is_pull": opts.IsPull})
  1288. if opts.RepoID > 0 {
  1289. cond = cond.And(builder.Eq{"issue.repo_id": opts.RepoID})
  1290. }
  1291. switch opts.FilterMode {
  1292. case FilterModeAll:
  1293. stats.OpenCount, err = x.Where(cond).And("is_closed = ?", false).
  1294. And(builder.In("issue.repo_id", opts.UserRepoIDs)).
  1295. Count(new(Issue))
  1296. if err != nil {
  1297. return nil, err
  1298. }
  1299. stats.ClosedCount, err = x.Where(cond).And("is_closed = ?", true).
  1300. And(builder.In("issue.repo_id", opts.UserRepoIDs)).
  1301. Count(new(Issue))
  1302. if err != nil {
  1303. return nil, err
  1304. }
  1305. case FilterModeAssign:
  1306. stats.OpenCount, err = x.Where(cond).And("is_closed = ?", false).
  1307. Join("INNER", "issue_assignees", "issue.id = issue_assignees.issue_id").
  1308. And("issue_assignees.assignee_id = ?", opts.UserID).
  1309. Count(new(Issue))
  1310. if err != nil {
  1311. return nil, err
  1312. }
  1313. stats.ClosedCount, err = x.Where(cond).And("is_closed = ?", true).
  1314. Join("INNER", "issue_assignees", "issue.id = issue_assignees.issue_id").
  1315. And("issue_assignees.assignee_id = ?", opts.UserID).
  1316. Count(new(Issue))
  1317. if err != nil {
  1318. return nil, err
  1319. }
  1320. case FilterModeCreate:
  1321. stats.OpenCount, err = x.Where(cond).And("is_closed = ?", false).
  1322. And("poster_id = ?", opts.UserID).
  1323. Count(new(Issue))
  1324. if err != nil {
  1325. return nil, err
  1326. }
  1327. stats.ClosedCount, err = x.Where(cond).And("is_closed = ?", true).
  1328. And("poster_id = ?", opts.UserID).
  1329. Count(new(Issue))
  1330. if err != nil {
  1331. return nil, err
  1332. }
  1333. }
  1334. cond = cond.And(builder.Eq{"issue.is_closed": opts.IsClosed})
  1335. stats.AssignCount, err = x.Where(cond).
  1336. Join("INNER", "issue_assignees", "issue.id = issue_assignees.issue_id").
  1337. And("issue_assignees.assignee_id = ?", opts.UserID).
  1338. Count(new(Issue))
  1339. if err != nil {
  1340. return nil, err
  1341. }
  1342. stats.CreateCount, err = x.Where(cond).
  1343. And("poster_id = ?", opts.UserID).
  1344. Count(new(Issue))
  1345. if err != nil {
  1346. return nil, err
  1347. }
  1348. stats.YourRepositoriesCount, err = x.Where(cond).
  1349. And(builder.In("issue.repo_id", opts.UserRepoIDs)).
  1350. Count(new(Issue))
  1351. if err != nil {
  1352. return nil, err
  1353. }
  1354. return stats, nil
  1355. }
  1356. // GetRepoIssueStats returns number of open and closed repository issues by given filter mode.
  1357. func GetRepoIssueStats(repoID, uid int64, filterMode int, isPull bool) (numOpen int64, numClosed int64) {
  1358. countSession := func(isClosed, isPull bool, repoID int64) *xorm.Session {
  1359. sess := x.
  1360. Where("is_closed = ?", isClosed).
  1361. And("is_pull = ?", isPull).
  1362. And("repo_id = ?", repoID)
  1363. return sess
  1364. }
  1365. openCountSession := countSession(false, isPull, repoID)
  1366. closedCountSession := countSession(true, isPull, repoID)
  1367. switch filterMode {
  1368. case FilterModeAssign:
  1369. openCountSession.Join("INNER", "issue_assignees", "issue.id = issue_assignees.issue_id").
  1370. And("issue_assignees.assignee_id = ?", uid)
  1371. closedCountSession.Join("INNER", "issue_assignees", "issue.id = issue_assignees.issue_id").
  1372. And("issue_assignees.assignee_id = ?", uid)
  1373. case FilterModeCreate:
  1374. openCountSession.And("poster_id = ?", uid)
  1375. closedCountSession.And("poster_id = ?", uid)
  1376. }
  1377. openResult, _ := openCountSession.Count(new(Issue))
  1378. closedResult, _ := closedCountSession.Count(new(Issue))
  1379. return openResult, closedResult
  1380. }
  1381. func updateIssue(e Engine, issue *Issue) error {
  1382. _, err := e.ID(issue.ID).AllCols().Update(issue)
  1383. if err != nil {
  1384. return err
  1385. }
  1386. UpdateIssueIndexer(issue.ID)
  1387. return nil
  1388. }
  1389. // UpdateIssue updates all fields of given issue.
  1390. func UpdateIssue(issue *Issue) error {
  1391. return updateIssue(x, issue)
  1392. }
  1393. // UpdateIssueDeadline updates an issue deadline and adds comments. Setting a deadline to 0 means deleting it.
  1394. func UpdateIssueDeadline(issue *Issue, deadlineUnix util.TimeStamp, doer *User) (err error) {
  1395. // if the deadline hasn't changed do nothing
  1396. if issue.DeadlineUnix == deadlineUnix {
  1397. return nil
  1398. }
  1399. sess := x.NewSession()
  1400. defer sess.Close()
  1401. if err := sess.Begin(); err != nil {
  1402. return err
  1403. }
  1404. // Update the deadline
  1405. if err = updateIssueCols(sess, &Issue{ID: issue.ID, DeadlineUnix: deadlineUnix}, "deadline_unix"); err != nil {
  1406. return err
  1407. }
  1408. // Make the comment
  1409. if _, err = createDeadlineComment(sess, doer, issue, deadlineUnix); err != nil {
  1410. return fmt.Errorf("createRemovedDueDateComment: %v", err)
  1411. }
  1412. return sess.Commit()
  1413. }
  1414. // Get Blocked By Dependencies, aka all issues this issue is blocked by.
  1415. func (issue *Issue) getBlockedByDependencies(e Engine) (issueDeps []*Issue, err error) {
  1416. return issueDeps, e.
  1417. Table("issue_dependency").
  1418. Select("issue.*").
  1419. Join("INNER", "issue", "issue.id = issue_dependency.dependency_id").
  1420. Where("issue_id = ?", issue.ID).
  1421. Find(&issueDeps)
  1422. }
  1423. // Get Blocking Dependencies, aka all issues this issue blocks.
  1424. func (issue *Issue) getBlockingDependencies(e Engine) (issueDeps []*Issue, err error) {
  1425. return issueDeps, e.
  1426. Table("issue_dependency").
  1427. Select("issue.*").
  1428. Join("INNER", "issue", "issue.id = issue_dependency.issue_id").
  1429. Where("dependency_id = ?", issue.ID).
  1430. Find(&issueDeps)
  1431. }
  1432. // BlockedByDependencies finds all Dependencies an issue is blocked by
  1433. func (issue *Issue) BlockedByDependencies() ([]*Issue, error) {
  1434. return issue.getBlockedByDependencies(x)
  1435. }
  1436. // BlockingDependencies returns all blocking dependencies, aka all other issues a given issue blocks
  1437. func (issue *Issue) BlockingDependencies() ([]*Issue, error) {
  1438. return issue.getBlockingDependencies(x)
  1439. }