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

issue.go 44 kB

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