選択できるのは25トピックまでです。 トピックは、先頭が英数字で、英数字とダッシュ('-')を使用した35文字以内のものにしてください。

issue.go 47KB

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