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

issue.go 43KB

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