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

issue.go 38 kB

11 years ago
11 years ago
11 years ago
11 years ago
9 years ago
11 years ago
11 years ago
11 years ago
10 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
11 years ago
9 years ago
11 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
11 years ago
11 years ago
11 years ago
11 years ago
12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463
  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. "errors"
  7. "fmt"
  8. "path"
  9. "sort"
  10. "strings"
  11. "time"
  12. api "code.gitea.io/sdk/gitea"
  13. "github.com/Unknwon/com"
  14. "github.com/go-xorm/xorm"
  15. "code.gitea.io/gitea/modules/base"
  16. "code.gitea.io/gitea/modules/log"
  17. "code.gitea.io/gitea/modules/setting"
  18. "code.gitea.io/gitea/modules/util"
  19. )
  20. var (
  21. errMissingIssueNumber = errors.New("No issue number specified")
  22. errInvalidIssueNumber = errors.New("Invalid issue number")
  23. )
  24. // Issue represents an issue or pull request of repository.
  25. type Issue struct {
  26. ID int64 `xorm:"pk autoincr"`
  27. RepoID int64 `xorm:"INDEX UNIQUE(repo_index)"`
  28. Repo *Repository `xorm:"-"`
  29. Index int64 `xorm:"UNIQUE(repo_index)"` // Index in one repository.
  30. PosterID int64 `xorm:"INDEX"`
  31. Poster *User `xorm:"-"`
  32. Title string `xorm:"name"`
  33. Content string `xorm:"TEXT"`
  34. RenderedContent string `xorm:"-"`
  35. Labels []*Label `xorm:"-"`
  36. MilestoneID int64 `xorm:"INDEX"`
  37. Milestone *Milestone `xorm:"-"`
  38. Priority int
  39. AssigneeID int64 `xorm:"INDEX"`
  40. Assignee *User `xorm:"-"`
  41. IsClosed bool `xorm:"INDEX"`
  42. IsRead bool `xorm:"-"`
  43. IsPull bool `xorm:"INDEX"` // Indicates whether is a pull request or not.
  44. PullRequest *PullRequest `xorm:"-"`
  45. NumComments int
  46. Ref string
  47. Deadline time.Time `xorm:"-"`
  48. DeadlineUnix int64 `xorm:"INDEX"`
  49. Created time.Time `xorm:"-"`
  50. CreatedUnix int64 `xorm:"INDEX"`
  51. Updated time.Time `xorm:"-"`
  52. UpdatedUnix int64 `xorm:"INDEX"`
  53. Attachments []*Attachment `xorm:"-"`
  54. Comments []*Comment `xorm:"-"`
  55. }
  56. // BeforeInsert is invoked from XORM before inserting an object of this type.
  57. func (issue *Issue) BeforeInsert() {
  58. issue.CreatedUnix = time.Now().Unix()
  59. issue.UpdatedUnix = issue.CreatedUnix
  60. }
  61. // BeforeUpdate is invoked from XORM before updating this object.
  62. func (issue *Issue) BeforeUpdate() {
  63. issue.UpdatedUnix = time.Now().Unix()
  64. issue.DeadlineUnix = issue.Deadline.Unix()
  65. }
  66. // AfterSet is invoked from XORM after setting the value of a field of
  67. // this object.
  68. func (issue *Issue) AfterSet(colName string, _ xorm.Cell) {
  69. switch colName {
  70. case "deadline_unix":
  71. issue.Deadline = time.Unix(issue.DeadlineUnix, 0).Local()
  72. case "created_unix":
  73. issue.Created = time.Unix(issue.CreatedUnix, 0).Local()
  74. case "updated_unix":
  75. issue.Updated = time.Unix(issue.UpdatedUnix, 0).Local()
  76. }
  77. }
  78. func (issue *Issue) loadRepo(e Engine) (err error) {
  79. if issue.Repo == nil {
  80. issue.Repo, err = getRepositoryByID(e, issue.RepoID)
  81. if err != nil {
  82. return fmt.Errorf("getRepositoryByID [%d]: %v", issue.RepoID, err)
  83. }
  84. }
  85. return nil
  86. }
  87. // GetPullRequest returns the issue pull request
  88. func (issue *Issue) GetPullRequest() (pr *PullRequest, err error) {
  89. if !issue.IsPull {
  90. return nil, fmt.Errorf("Issue is not a pull request")
  91. }
  92. pr, err = getPullRequestByIssueID(x, issue.ID)
  93. return
  94. }
  95. func (issue *Issue) loadLabels(e Engine) (err error) {
  96. if issue.Labels == nil {
  97. issue.Labels, err = getLabelsByIssueID(e, issue.ID)
  98. if err != nil {
  99. return fmt.Errorf("getLabelsByIssueID [%d]: %v", issue.ID, err)
  100. }
  101. }
  102. return nil
  103. }
  104. func (issue *Issue) loadPoster(e Engine) (err error) {
  105. if issue.Poster == nil {
  106. issue.Poster, err = getUserByID(e, issue.PosterID)
  107. if err != nil {
  108. issue.PosterID = -1
  109. issue.Poster = NewGhostUser()
  110. if !IsErrUserNotExist(err) {
  111. return fmt.Errorf("getUserByID.(poster) [%d]: %v", issue.PosterID, err)
  112. }
  113. err = nil
  114. return
  115. }
  116. }
  117. return
  118. }
  119. func (issue *Issue) loadAssignee(e Engine) (err error) {
  120. if issue.Assignee == nil && issue.AssigneeID > 0 {
  121. issue.Assignee, err = getUserByID(e, issue.AssigneeID)
  122. if err != nil {
  123. issue.AssigneeID = -1
  124. issue.Assignee = NewGhostUser()
  125. if !IsErrUserNotExist(err) {
  126. return fmt.Errorf("getUserByID.(assignee) [%d]: %v", issue.AssigneeID, err)
  127. }
  128. err = nil
  129. return
  130. }
  131. }
  132. return
  133. }
  134. func (issue *Issue) loadPullRequest(e Engine) (err error) {
  135. if issue.IsPull && issue.PullRequest == nil {
  136. issue.PullRequest, err = getPullRequestByIssueID(e, issue.ID)
  137. if err != nil {
  138. if IsErrPullRequestNotExist(err) {
  139. return err
  140. }
  141. return fmt.Errorf("getPullRequestByIssueID [%d]: %v", issue.ID, err)
  142. }
  143. }
  144. return nil
  145. }
  146. func (issue *Issue) loadAttributes(e Engine) (err error) {
  147. if err = issue.loadRepo(e); err != nil {
  148. return
  149. }
  150. if err = issue.loadPoster(e); err != nil {
  151. return
  152. }
  153. if err = issue.loadLabels(e); err != nil {
  154. return
  155. }
  156. if issue.Milestone == nil && issue.MilestoneID > 0 {
  157. issue.Milestone, err = getMilestoneByRepoID(e, issue.RepoID, issue.MilestoneID)
  158. if err != nil && !IsErrMilestoneNotExist(err) {
  159. return fmt.Errorf("getMilestoneByRepoID [repo_id: %d, milestone_id: %d]: %v", issue.RepoID, issue.MilestoneID, err)
  160. }
  161. }
  162. if err = issue.loadAssignee(e); err != nil {
  163. return
  164. }
  165. if err = issue.loadPullRequest(e); err != nil && !IsErrPullRequestNotExist(err) {
  166. // It is possible pull request is not yet created.
  167. return err
  168. }
  169. if issue.Attachments == nil {
  170. issue.Attachments, err = getAttachmentsByIssueID(e, issue.ID)
  171. if err != nil {
  172. return fmt.Errorf("getAttachmentsByIssueID [%d]: %v", issue.ID, err)
  173. }
  174. }
  175. if issue.Comments == nil {
  176. issue.Comments, err = findComments(e, FindCommentsOptions{
  177. IssueID: issue.ID,
  178. Type: CommentTypeUnknown,
  179. })
  180. if err != nil {
  181. return fmt.Errorf("getCommentsByIssueID [%d]: %v", issue.ID, err)
  182. }
  183. }
  184. return nil
  185. }
  186. // LoadAttributes loads the attribute of this issue.
  187. func (issue *Issue) LoadAttributes() error {
  188. return issue.loadAttributes(x)
  189. }
  190. // GetIsRead load the `IsRead` field of the issue
  191. func (issue *Issue) GetIsRead(userID int64) error {
  192. issueUser := &IssueUser{IssueID: issue.ID, UID: userID}
  193. if has, err := x.Get(issueUser); err != nil {
  194. return err
  195. } else if !has {
  196. issue.IsRead = false
  197. return nil
  198. }
  199. issue.IsRead = issueUser.IsRead
  200. return nil
  201. }
  202. // APIURL returns the absolute APIURL to this issue.
  203. func (issue *Issue) APIURL() string {
  204. return issue.Repo.APIURL() + "/" + path.Join("issues", fmt.Sprint(issue.ID))
  205. }
  206. // HTMLURL returns the absolute URL to this issue.
  207. func (issue *Issue) HTMLURL() string {
  208. var path string
  209. if issue.IsPull {
  210. path = "pulls"
  211. } else {
  212. path = "issues"
  213. }
  214. return fmt.Sprintf("%s/%s/%d", issue.Repo.HTMLURL(), path, issue.Index)
  215. }
  216. // DiffURL returns the absolute URL to this diff
  217. func (issue *Issue) DiffURL() string {
  218. if issue.IsPull {
  219. return fmt.Sprintf("%s/pulls/%d.diff", issue.Repo.HTMLURL(), issue.Index)
  220. }
  221. return ""
  222. }
  223. // PatchURL returns the absolute URL to this patch
  224. func (issue *Issue) PatchURL() string {
  225. if issue.IsPull {
  226. return fmt.Sprintf("%s/pulls/%d.patch", issue.Repo.HTMLURL(), issue.Index)
  227. }
  228. return ""
  229. }
  230. // State returns string representation of issue status.
  231. func (issue *Issue) State() api.StateType {
  232. if issue.IsClosed {
  233. return api.StateClosed
  234. }
  235. return api.StateOpen
  236. }
  237. // APIFormat assumes some fields assigned with values:
  238. // Required - Poster, Labels,
  239. // Optional - Milestone, Assignee, PullRequest
  240. func (issue *Issue) APIFormat() *api.Issue {
  241. apiLabels := make([]*api.Label, len(issue.Labels))
  242. for i := range issue.Labels {
  243. apiLabels[i] = issue.Labels[i].APIFormat()
  244. }
  245. apiIssue := &api.Issue{
  246. ID: issue.ID,
  247. URL: issue.APIURL(),
  248. Index: issue.Index,
  249. Poster: issue.Poster.APIFormat(),
  250. Title: issue.Title,
  251. Body: issue.Content,
  252. Labels: apiLabels,
  253. State: issue.State(),
  254. Comments: issue.NumComments,
  255. Created: issue.Created,
  256. Updated: issue.Updated,
  257. }
  258. if issue.Milestone != nil {
  259. apiIssue.Milestone = issue.Milestone.APIFormat()
  260. }
  261. if issue.Assignee != nil {
  262. apiIssue.Assignee = issue.Assignee.APIFormat()
  263. }
  264. if issue.IsPull {
  265. apiIssue.PullRequest = &api.PullRequestMeta{
  266. HasMerged: issue.PullRequest.HasMerged,
  267. }
  268. if issue.PullRequest.HasMerged {
  269. apiIssue.PullRequest.Merged = &issue.PullRequest.Merged
  270. }
  271. }
  272. return apiIssue
  273. }
  274. // HashTag returns unique hash tag for issue.
  275. func (issue *Issue) HashTag() string {
  276. return "issue-" + com.ToStr(issue.ID)
  277. }
  278. // IsPoster returns true if given user by ID is the poster.
  279. func (issue *Issue) IsPoster(uid int64) bool {
  280. return issue.PosterID == uid
  281. }
  282. func (issue *Issue) hasLabel(e Engine, labelID int64) bool {
  283. return hasIssueLabel(e, issue.ID, labelID)
  284. }
  285. // HasLabel returns true if issue has been labeled by given ID.
  286. func (issue *Issue) HasLabel(labelID int64) bool {
  287. return issue.hasLabel(x, labelID)
  288. }
  289. func (issue *Issue) sendLabelUpdatedWebhook(doer *User) {
  290. var err error
  291. if issue.IsPull {
  292. if err = issue.loadRepo(x); err != nil {
  293. log.Error(4, "loadRepo: %v", err)
  294. return
  295. }
  296. if err = issue.loadPullRequest(x); err != nil {
  297. log.Error(4, "loadPullRequest: %v", err)
  298. return
  299. }
  300. if err = issue.PullRequest.LoadIssue(); err != nil {
  301. log.Error(4, "LoadIssue: %v", err)
  302. return
  303. }
  304. err = PrepareWebhooks(issue.Repo, HookEventPullRequest, &api.PullRequestPayload{
  305. Action: api.HookIssueLabelUpdated,
  306. Index: issue.Index,
  307. PullRequest: issue.PullRequest.APIFormat(),
  308. Repository: issue.Repo.APIFormat(AccessModeNone),
  309. Sender: doer.APIFormat(),
  310. })
  311. }
  312. if err != nil {
  313. log.Error(4, "PrepareWebhooks [is_pull: %v]: %v", issue.IsPull, err)
  314. } else {
  315. go HookQueue.Add(issue.RepoID)
  316. }
  317. }
  318. func (issue *Issue) addLabel(e *xorm.Session, label *Label, doer *User) error {
  319. return newIssueLabel(e, issue, label, doer)
  320. }
  321. // AddLabel adds a new label to the issue.
  322. func (issue *Issue) AddLabel(doer *User, label *Label) error {
  323. if err := NewIssueLabel(issue, label, doer); err != nil {
  324. return err
  325. }
  326. issue.sendLabelUpdatedWebhook(doer)
  327. return nil
  328. }
  329. func (issue *Issue) addLabels(e *xorm.Session, labels []*Label, doer *User) error {
  330. return newIssueLabels(e, issue, labels, doer)
  331. }
  332. // AddLabels adds a list of new labels to the issue.
  333. func (issue *Issue) AddLabels(doer *User, labels []*Label) error {
  334. if err := NewIssueLabels(issue, labels, doer); err != nil {
  335. return err
  336. }
  337. issue.sendLabelUpdatedWebhook(doer)
  338. return nil
  339. }
  340. func (issue *Issue) getLabels(e Engine) (err error) {
  341. if len(issue.Labels) > 0 {
  342. return nil
  343. }
  344. issue.Labels, err = getLabelsByIssueID(e, issue.ID)
  345. if err != nil {
  346. return fmt.Errorf("getLabelsByIssueID: %v", err)
  347. }
  348. return nil
  349. }
  350. func (issue *Issue) removeLabel(e *xorm.Session, doer *User, label *Label) error {
  351. return deleteIssueLabel(e, issue, label, doer)
  352. }
  353. // RemoveLabel removes a label from issue by given ID.
  354. func (issue *Issue) RemoveLabel(doer *User, label *Label) error {
  355. if err := issue.loadRepo(x); err != nil {
  356. return err
  357. }
  358. if has, err := HasAccess(doer.ID, issue.Repo, AccessModeWrite); err != nil {
  359. return err
  360. } else if !has {
  361. return ErrLabelNotExist{}
  362. }
  363. if err := DeleteIssueLabel(issue, label, doer); err != nil {
  364. return err
  365. }
  366. issue.sendLabelUpdatedWebhook(doer)
  367. return nil
  368. }
  369. func (issue *Issue) clearLabels(e *xorm.Session, doer *User) (err error) {
  370. if err = issue.getLabels(e); err != nil {
  371. return fmt.Errorf("getLabels: %v", err)
  372. }
  373. for i := range issue.Labels {
  374. if err = issue.removeLabel(e, doer, issue.Labels[i]); err != nil {
  375. return fmt.Errorf("removeLabel: %v", err)
  376. }
  377. }
  378. return nil
  379. }
  380. // ClearLabels removes all issue labels as the given user.
  381. // Triggers appropriate WebHooks, if any.
  382. func (issue *Issue) ClearLabels(doer *User) (err error) {
  383. sess := x.NewSession()
  384. defer sess.Close()
  385. if err = sess.Begin(); err != nil {
  386. return err
  387. }
  388. if err := issue.loadRepo(sess); err != nil {
  389. return err
  390. } else if err = issue.loadPullRequest(sess); err != nil {
  391. return err
  392. }
  393. if has, err := hasAccess(sess, doer.ID, issue.Repo, AccessModeWrite); err != nil {
  394. return err
  395. } else if !has {
  396. return ErrLabelNotExist{}
  397. }
  398. if err = issue.clearLabels(sess, doer); err != nil {
  399. return err
  400. }
  401. if err = sess.Commit(); err != nil {
  402. return fmt.Errorf("Commit: %v", err)
  403. }
  404. if issue.IsPull {
  405. err = issue.PullRequest.LoadIssue()
  406. if err != nil {
  407. log.Error(4, "LoadIssue: %v", err)
  408. return
  409. }
  410. err = PrepareWebhooks(issue.Repo, HookEventPullRequest, &api.PullRequestPayload{
  411. Action: api.HookIssueLabelCleared,
  412. Index: issue.Index,
  413. PullRequest: issue.PullRequest.APIFormat(),
  414. Repository: issue.Repo.APIFormat(AccessModeNone),
  415. Sender: doer.APIFormat(),
  416. })
  417. }
  418. if err != nil {
  419. log.Error(4, "PrepareWebhooks [is_pull: %v]: %v", issue.IsPull, err)
  420. } else {
  421. go HookQueue.Add(issue.RepoID)
  422. }
  423. return nil
  424. }
  425. type labelSorter []*Label
  426. func (ts labelSorter) Len() int {
  427. return len([]*Label(ts))
  428. }
  429. func (ts labelSorter) Less(i, j int) bool {
  430. return []*Label(ts)[i].ID < []*Label(ts)[j].ID
  431. }
  432. func (ts labelSorter) Swap(i, j int) {
  433. []*Label(ts)[i], []*Label(ts)[j] = []*Label(ts)[j], []*Label(ts)[i]
  434. }
  435. // ReplaceLabels removes all current labels and add new labels to the issue.
  436. // Triggers appropriate WebHooks, if any.
  437. func (issue *Issue) ReplaceLabels(labels []*Label, doer *User) (err error) {
  438. sess := x.NewSession()
  439. defer sess.Close()
  440. if err = sess.Begin(); err != nil {
  441. return err
  442. }
  443. if err = issue.loadLabels(sess); err != nil {
  444. return err
  445. }
  446. sort.Sort(labelSorter(labels))
  447. sort.Sort(labelSorter(issue.Labels))
  448. var toAdd, toRemove []*Label
  449. addIndex, removeIndex := 0, 0
  450. for addIndex < len(labels) && removeIndex < len(issue.Labels) {
  451. addLabel := labels[addIndex]
  452. removeLabel := issue.Labels[removeIndex]
  453. if addLabel.ID == removeLabel.ID {
  454. addIndex++
  455. removeIndex++
  456. } else if addLabel.ID < removeLabel.ID {
  457. toAdd = append(toAdd, addLabel)
  458. addIndex++
  459. } else {
  460. toRemove = append(toRemove, removeLabel)
  461. removeIndex++
  462. }
  463. }
  464. toAdd = append(toAdd, labels[addIndex:]...)
  465. toRemove = append(toRemove, issue.Labels[removeIndex:]...)
  466. if len(toAdd) > 0 {
  467. if err = issue.addLabels(sess, toAdd, doer); err != nil {
  468. return fmt.Errorf("addLabels: %v", err)
  469. }
  470. }
  471. for _, l := range toRemove {
  472. if err = issue.removeLabel(sess, doer, l); err != nil {
  473. return fmt.Errorf("removeLabel: %v", err)
  474. }
  475. }
  476. return sess.Commit()
  477. }
  478. // GetAssignee sets the Assignee attribute of this issue.
  479. func (issue *Issue) GetAssignee() (err error) {
  480. if issue.AssigneeID == 0 || issue.Assignee != nil {
  481. return nil
  482. }
  483. issue.Assignee, err = GetUserByID(issue.AssigneeID)
  484. if IsErrUserNotExist(err) {
  485. return nil
  486. }
  487. return err
  488. }
  489. // ReadBy sets issue to be read by given user.
  490. func (issue *Issue) ReadBy(userID int64) error {
  491. if err := UpdateIssueUserByRead(userID, issue.ID); err != nil {
  492. return err
  493. }
  494. if err := setNotificationStatusReadIfUnread(x, userID, issue.ID); err != nil {
  495. return err
  496. }
  497. return nil
  498. }
  499. func updateIssueCols(e Engine, issue *Issue, cols ...string) error {
  500. cols = append(cols, "updated_unix")
  501. if _, err := e.Id(issue.ID).Cols(cols...).Update(issue); err != nil {
  502. return err
  503. }
  504. UpdateIssueIndexer(issue)
  505. return nil
  506. }
  507. // UpdateIssueCols only updates values of specific columns for given issue.
  508. func UpdateIssueCols(issue *Issue, cols ...string) error {
  509. return updateIssueCols(x, issue, cols...)
  510. }
  511. func (issue *Issue) changeStatus(e *xorm.Session, doer *User, repo *Repository, isClosed bool) (err error) {
  512. // Nothing should be performed if current status is same as target status
  513. if issue.IsClosed == isClosed {
  514. return nil
  515. }
  516. issue.IsClosed = isClosed
  517. if err = updateIssueCols(e, issue, "is_closed"); err != nil {
  518. return err
  519. }
  520. // Update issue count of labels
  521. if err = issue.getLabels(e); err != nil {
  522. return err
  523. }
  524. for idx := range issue.Labels {
  525. if issue.IsClosed {
  526. issue.Labels[idx].NumClosedIssues++
  527. } else {
  528. issue.Labels[idx].NumClosedIssues--
  529. }
  530. if err = updateLabel(e, issue.Labels[idx]); err != nil {
  531. return err
  532. }
  533. }
  534. // Update issue count of milestone
  535. if err = changeMilestoneIssueStats(e, issue); err != nil {
  536. return err
  537. }
  538. // New action comment
  539. if _, err = createStatusComment(e, doer, repo, issue); err != nil {
  540. return err
  541. }
  542. return nil
  543. }
  544. // ChangeStatus changes issue status to open or closed.
  545. func (issue *Issue) ChangeStatus(doer *User, repo *Repository, isClosed bool) (err error) {
  546. sess := x.NewSession()
  547. defer sess.Close()
  548. if err = sess.Begin(); err != nil {
  549. return err
  550. }
  551. if err = issue.changeStatus(sess, doer, repo, isClosed); err != nil {
  552. return err
  553. }
  554. if err = sess.Commit(); err != nil {
  555. return fmt.Errorf("Commit: %v", err)
  556. }
  557. if issue.IsPull {
  558. // Merge pull request calls issue.changeStatus so we need to handle separately.
  559. issue.PullRequest.Issue = issue
  560. apiPullRequest := &api.PullRequestPayload{
  561. Index: issue.Index,
  562. PullRequest: issue.PullRequest.APIFormat(),
  563. Repository: repo.APIFormat(AccessModeNone),
  564. Sender: doer.APIFormat(),
  565. }
  566. if isClosed {
  567. apiPullRequest.Action = api.HookIssueClosed
  568. } else {
  569. apiPullRequest.Action = api.HookIssueReOpened
  570. }
  571. err = PrepareWebhooks(repo, HookEventPullRequest, apiPullRequest)
  572. }
  573. if err != nil {
  574. log.Error(4, "PrepareWebhooks [is_pull: %v, is_closed: %v]: %v", issue.IsPull, isClosed, err)
  575. } else {
  576. go HookQueue.Add(repo.ID)
  577. }
  578. return nil
  579. }
  580. // ChangeTitle changes the title of this issue, as the given user.
  581. func (issue *Issue) ChangeTitle(doer *User, title string) (err error) {
  582. oldTitle := issue.Title
  583. issue.Title = title
  584. sess := x.NewSession()
  585. defer sess.Close()
  586. if err = sess.Begin(); err != nil {
  587. return err
  588. }
  589. if err = updateIssueCols(sess, issue, "name"); err != nil {
  590. return fmt.Errorf("updateIssueCols: %v", err)
  591. }
  592. if _, err = createChangeTitleComment(sess, doer, issue.Repo, issue, oldTitle, title); err != nil {
  593. return fmt.Errorf("createChangeTitleComment: %v", err)
  594. }
  595. if err = sess.Commit(); err != nil {
  596. return err
  597. }
  598. if issue.IsPull {
  599. issue.PullRequest.Issue = issue
  600. err = PrepareWebhooks(issue.Repo, HookEventPullRequest, &api.PullRequestPayload{
  601. Action: api.HookIssueEdited,
  602. Index: issue.Index,
  603. Changes: &api.ChangesPayload{
  604. Title: &api.ChangesFromPayload{
  605. From: oldTitle,
  606. },
  607. },
  608. PullRequest: issue.PullRequest.APIFormat(),
  609. Repository: issue.Repo.APIFormat(AccessModeNone),
  610. Sender: doer.APIFormat(),
  611. })
  612. }
  613. if err != nil {
  614. log.Error(4, "PrepareWebhooks [is_pull: %v]: %v", issue.IsPull, err)
  615. } else {
  616. go HookQueue.Add(issue.RepoID)
  617. }
  618. return nil
  619. }
  620. // AddDeletePRBranchComment adds delete branch comment for pull request issue
  621. func AddDeletePRBranchComment(doer *User, repo *Repository, issueID int64, branchName string) error {
  622. issue, err := getIssueByID(x, issueID)
  623. if err != nil {
  624. return err
  625. }
  626. sess := x.NewSession()
  627. defer sess.Close()
  628. if err := sess.Begin(); err != nil {
  629. return err
  630. }
  631. if _, err := createDeleteBranchComment(sess, doer, repo, issue, branchName); err != nil {
  632. return err
  633. }
  634. return sess.Commit()
  635. }
  636. // ChangeContent changes issue content, as the given user.
  637. func (issue *Issue) ChangeContent(doer *User, content string) (err error) {
  638. oldContent := issue.Content
  639. issue.Content = content
  640. if err = UpdateIssueCols(issue, "content"); err != nil {
  641. return fmt.Errorf("UpdateIssueCols: %v", err)
  642. }
  643. if issue.IsPull {
  644. issue.PullRequest.Issue = issue
  645. err = PrepareWebhooks(issue.Repo, HookEventPullRequest, &api.PullRequestPayload{
  646. Action: api.HookIssueEdited,
  647. Index: issue.Index,
  648. Changes: &api.ChangesPayload{
  649. Body: &api.ChangesFromPayload{
  650. From: oldContent,
  651. },
  652. },
  653. PullRequest: issue.PullRequest.APIFormat(),
  654. Repository: issue.Repo.APIFormat(AccessModeNone),
  655. Sender: doer.APIFormat(),
  656. })
  657. }
  658. if err != nil {
  659. log.Error(4, "PrepareWebhooks [is_pull: %v]: %v", issue.IsPull, err)
  660. } else {
  661. go HookQueue.Add(issue.RepoID)
  662. }
  663. return nil
  664. }
  665. // ChangeAssignee changes the Assignee field of this issue.
  666. func (issue *Issue) ChangeAssignee(doer *User, assigneeID int64) (err error) {
  667. var oldAssigneeID = issue.AssigneeID
  668. issue.AssigneeID = assigneeID
  669. if err = UpdateIssueUserByAssignee(issue); err != nil {
  670. return fmt.Errorf("UpdateIssueUserByAssignee: %v", err)
  671. }
  672. sess := x.NewSession()
  673. defer sess.Close()
  674. if err = issue.loadRepo(sess); err != nil {
  675. return fmt.Errorf("loadRepo: %v", err)
  676. }
  677. if _, err = createAssigneeComment(sess, doer, issue.Repo, issue, oldAssigneeID, assigneeID); err != nil {
  678. return fmt.Errorf("createAssigneeComment: %v", err)
  679. }
  680. issue.Assignee, err = GetUserByID(issue.AssigneeID)
  681. if err != nil && !IsErrUserNotExist(err) {
  682. log.Error(4, "GetUserByID [assignee_id: %v]: %v", issue.AssigneeID, err)
  683. return nil
  684. }
  685. // Error not nil here means user does not exist, which is remove assignee.
  686. isRemoveAssignee := err != nil
  687. if issue.IsPull {
  688. issue.PullRequest.Issue = issue
  689. apiPullRequest := &api.PullRequestPayload{
  690. Index: issue.Index,
  691. PullRequest: issue.PullRequest.APIFormat(),
  692. Repository: issue.Repo.APIFormat(AccessModeNone),
  693. Sender: doer.APIFormat(),
  694. }
  695. if isRemoveAssignee {
  696. apiPullRequest.Action = api.HookIssueUnassigned
  697. } else {
  698. apiPullRequest.Action = api.HookIssueAssigned
  699. }
  700. if err := PrepareWebhooks(issue.Repo, HookEventPullRequest, apiPullRequest); err != nil {
  701. log.Error(4, "PrepareWebhooks [is_pull: %v, remove_assignee: %v]: %v", issue.IsPull, isRemoveAssignee, err)
  702. return nil
  703. }
  704. }
  705. go HookQueue.Add(issue.RepoID)
  706. return nil
  707. }
  708. // NewIssueOptions represents the options of a new issue.
  709. type NewIssueOptions struct {
  710. Repo *Repository
  711. Issue *Issue
  712. LabelIDs []int64
  713. Attachments []string // In UUID format.
  714. IsPull bool
  715. }
  716. func newIssue(e *xorm.Session, doer *User, opts NewIssueOptions) (err error) {
  717. opts.Issue.Title = strings.TrimSpace(opts.Issue.Title)
  718. opts.Issue.Index = opts.Repo.NextIssueIndex()
  719. if opts.Issue.MilestoneID > 0 {
  720. milestone, err := getMilestoneByRepoID(e, opts.Issue.RepoID, opts.Issue.MilestoneID)
  721. if err != nil && !IsErrMilestoneNotExist(err) {
  722. return fmt.Errorf("getMilestoneByID: %v", err)
  723. }
  724. // Assume milestone is invalid and drop silently.
  725. opts.Issue.MilestoneID = 0
  726. if milestone != nil {
  727. opts.Issue.MilestoneID = milestone.ID
  728. opts.Issue.Milestone = milestone
  729. }
  730. }
  731. if assigneeID := opts.Issue.AssigneeID; assigneeID > 0 {
  732. valid, err := hasAccess(e, assigneeID, opts.Repo, AccessModeWrite)
  733. if err != nil {
  734. return fmt.Errorf("hasAccess [user_id: %d, repo_id: %d]: %v", assigneeID, opts.Repo.ID, err)
  735. }
  736. if !valid {
  737. opts.Issue.AssigneeID = 0
  738. opts.Issue.Assignee = nil
  739. }
  740. }
  741. // Milestone and assignee validation should happen before insert actual object.
  742. if _, err = e.Insert(opts.Issue); err != nil {
  743. return err
  744. }
  745. if opts.Issue.MilestoneID > 0 {
  746. if err = changeMilestoneAssign(e, doer, opts.Issue, -1); err != nil {
  747. return err
  748. }
  749. }
  750. if opts.Issue.AssigneeID > 0 {
  751. if err = opts.Issue.loadRepo(e); err != nil {
  752. return err
  753. }
  754. if _, err = createAssigneeComment(e, doer, opts.Issue.Repo, opts.Issue, -1, opts.Issue.AssigneeID); err != nil {
  755. return err
  756. }
  757. }
  758. if opts.IsPull {
  759. _, err = e.Exec("UPDATE `repository` SET num_pulls = num_pulls + 1 WHERE id = ?", opts.Issue.RepoID)
  760. } else {
  761. _, err = e.Exec("UPDATE `repository` SET num_issues = num_issues + 1 WHERE id = ?", opts.Issue.RepoID)
  762. }
  763. if err != nil {
  764. return err
  765. }
  766. if len(opts.LabelIDs) > 0 {
  767. // During the session, SQLite3 driver cannot handle retrieve objects after update something.
  768. // So we have to get all needed labels first.
  769. labels := make([]*Label, 0, len(opts.LabelIDs))
  770. if err = e.In("id", opts.LabelIDs).Find(&labels); err != nil {
  771. return fmt.Errorf("find all labels [label_ids: %v]: %v", opts.LabelIDs, err)
  772. }
  773. if err = opts.Issue.loadPoster(e); err != nil {
  774. return err
  775. }
  776. for _, label := range labels {
  777. // Silently drop invalid labels.
  778. if label.RepoID != opts.Repo.ID {
  779. continue
  780. }
  781. if err = opts.Issue.addLabel(e, label, opts.Issue.Poster); err != nil {
  782. return fmt.Errorf("addLabel [id: %d]: %v", label.ID, err)
  783. }
  784. }
  785. }
  786. if err = newIssueUsers(e, opts.Repo, opts.Issue); err != nil {
  787. return err
  788. }
  789. UpdateIssueIndexer(opts.Issue)
  790. if len(opts.Attachments) > 0 {
  791. attachments, err := getAttachmentsByUUIDs(e, opts.Attachments)
  792. if err != nil {
  793. return fmt.Errorf("getAttachmentsByUUIDs [uuids: %v]: %v", opts.Attachments, err)
  794. }
  795. for i := 0; i < len(attachments); i++ {
  796. attachments[i].IssueID = opts.Issue.ID
  797. if _, err = e.Id(attachments[i].ID).Update(attachments[i]); err != nil {
  798. return fmt.Errorf("update attachment [id: %d]: %v", attachments[i].ID, err)
  799. }
  800. }
  801. }
  802. return opts.Issue.loadAttributes(e)
  803. }
  804. // NewIssue creates new issue with labels for repository.
  805. func NewIssue(repo *Repository, issue *Issue, labelIDs []int64, uuids []string) (err error) {
  806. sess := x.NewSession()
  807. defer sess.Close()
  808. if err = sess.Begin(); err != nil {
  809. return err
  810. }
  811. if err = newIssue(sess, issue.Poster, NewIssueOptions{
  812. Repo: repo,
  813. Issue: issue,
  814. LabelIDs: labelIDs,
  815. Attachments: uuids,
  816. }); err != nil {
  817. return fmt.Errorf("newIssue: %v", err)
  818. }
  819. if err = sess.Commit(); err != nil {
  820. return fmt.Errorf("Commit: %v", err)
  821. }
  822. if err = NotifyWatchers(&Action{
  823. ActUserID: issue.Poster.ID,
  824. ActUser: issue.Poster,
  825. OpType: ActionCreateIssue,
  826. Content: fmt.Sprintf("%d|%s", issue.Index, issue.Title),
  827. RepoID: repo.ID,
  828. Repo: repo,
  829. IsPrivate: repo.IsPrivate,
  830. }); err != nil {
  831. log.Error(4, "NotifyWatchers: %v", err)
  832. }
  833. if err = issue.MailParticipants(); err != nil {
  834. log.Error(4, "MailParticipants: %v", err)
  835. }
  836. return nil
  837. }
  838. // GetIssueByRef returns an Issue specified by a GFM reference.
  839. // See https://help.github.com/articles/writing-on-github#references for more information on the syntax.
  840. func GetIssueByRef(ref string) (*Issue, error) {
  841. n := strings.IndexByte(ref, byte('#'))
  842. if n == -1 {
  843. return nil, errMissingIssueNumber
  844. }
  845. index, err := com.StrTo(ref[n+1:]).Int64()
  846. if err != nil {
  847. return nil, errInvalidIssueNumber
  848. }
  849. repo, err := GetRepositoryByRef(ref[:n])
  850. if err != nil {
  851. return nil, err
  852. }
  853. issue, err := GetIssueByIndex(repo.ID, index)
  854. if err != nil {
  855. return nil, err
  856. }
  857. return issue, issue.LoadAttributes()
  858. }
  859. // GetRawIssueByIndex returns raw issue without loading attributes by index in a repository.
  860. func GetRawIssueByIndex(repoID, index int64) (*Issue, error) {
  861. issue := &Issue{
  862. RepoID: repoID,
  863. Index: index,
  864. }
  865. has, err := x.Get(issue)
  866. if err != nil {
  867. return nil, err
  868. } else if !has {
  869. return nil, ErrIssueNotExist{0, repoID, index}
  870. }
  871. return issue, nil
  872. }
  873. // GetIssueByIndex returns issue by index in a repository.
  874. func GetIssueByIndex(repoID, index int64) (*Issue, error) {
  875. issue, err := GetRawIssueByIndex(repoID, index)
  876. if err != nil {
  877. return nil, err
  878. }
  879. return issue, issue.LoadAttributes()
  880. }
  881. func getIssueByID(e Engine, id int64) (*Issue, error) {
  882. issue := new(Issue)
  883. has, err := e.Id(id).Get(issue)
  884. if err != nil {
  885. return nil, err
  886. } else if !has {
  887. return nil, ErrIssueNotExist{id, 0, 0}
  888. }
  889. return issue, issue.loadAttributes(e)
  890. }
  891. // GetIssueByID returns an issue by given ID.
  892. func GetIssueByID(id int64) (*Issue, error) {
  893. return getIssueByID(x, id)
  894. }
  895. func getIssuesByIDs(e Engine, issueIDs []int64) ([]*Issue, error) {
  896. issues := make([]*Issue, 0, 10)
  897. return issues, e.In("id", issueIDs).Find(&issues)
  898. }
  899. // GetIssuesByIDs return issues with the given IDs.
  900. func GetIssuesByIDs(issueIDs []int64) ([]*Issue, error) {
  901. return getIssuesByIDs(x, issueIDs)
  902. }
  903. // IssuesOptions represents options of an issue.
  904. type IssuesOptions struct {
  905. RepoID int64
  906. AssigneeID int64
  907. PosterID int64
  908. MentionedID int64
  909. MilestoneID int64
  910. RepoIDs []int64
  911. Page int
  912. PageSize int
  913. IsClosed util.OptionalBool
  914. IsPull util.OptionalBool
  915. Labels string
  916. SortType string
  917. IssueIDs []int64
  918. }
  919. // sortIssuesSession sort an issues-related session based on the provided
  920. // sortType string
  921. func sortIssuesSession(sess *xorm.Session, sortType string) {
  922. switch sortType {
  923. case "oldest":
  924. sess.Asc("issue.created_unix")
  925. case "recentupdate":
  926. sess.Desc("issue.updated_unix")
  927. case "leastupdate":
  928. sess.Asc("issue.updated_unix")
  929. case "mostcomment":
  930. sess.Desc("issue.num_comments")
  931. case "leastcomment":
  932. sess.Asc("issue.num_comments")
  933. case "priority":
  934. sess.Desc("issue.priority")
  935. default:
  936. sess.Desc("issue.created_unix")
  937. }
  938. }
  939. func (opts *IssuesOptions) setupSession(sess *xorm.Session) error {
  940. if opts.Page >= 0 && opts.PageSize > 0 {
  941. var start int
  942. if opts.Page == 0 {
  943. start = 0
  944. } else {
  945. start = (opts.Page - 1) * opts.PageSize
  946. }
  947. sess.Limit(opts.PageSize, start)
  948. }
  949. if len(opts.IssueIDs) > 0 {
  950. sess.In("issue.id", opts.IssueIDs)
  951. }
  952. if opts.RepoID > 0 {
  953. sess.And("issue.repo_id=?", opts.RepoID)
  954. } else if len(opts.RepoIDs) > 0 {
  955. // In case repository IDs are provided but actually no repository has issue.
  956. sess.In("issue.repo_id", opts.RepoIDs)
  957. }
  958. switch opts.IsClosed {
  959. case util.OptionalBoolTrue:
  960. sess.And("issue.is_closed=?", true)
  961. case util.OptionalBoolFalse:
  962. sess.And("issue.is_closed=?", false)
  963. }
  964. if opts.AssigneeID > 0 {
  965. sess.And("issue.assignee_id=?", opts.AssigneeID)
  966. }
  967. if opts.PosterID > 0 {
  968. sess.And("issue.poster_id=?", opts.PosterID)
  969. }
  970. if opts.MentionedID > 0 {
  971. sess.Join("INNER", "issue_user", "issue.id = issue_user.issue_id").
  972. And("issue_user.is_mentioned = ?", true).
  973. And("issue_user.uid = ?", opts.MentionedID)
  974. }
  975. if opts.MilestoneID > 0 {
  976. sess.And("issue.milestone_id=?", opts.MilestoneID)
  977. }
  978. switch opts.IsPull {
  979. case util.OptionalBoolTrue:
  980. sess.And("issue.is_pull=?", true)
  981. case util.OptionalBoolFalse:
  982. sess.And("issue.is_pull=?", false)
  983. }
  984. if len(opts.Labels) > 0 && opts.Labels != "0" {
  985. labelIDs, err := base.StringsToInt64s(strings.Split(opts.Labels, ","))
  986. if err != nil {
  987. return err
  988. }
  989. if len(labelIDs) > 0 {
  990. sess.
  991. Join("INNER", "issue_label", "issue.id = issue_label.issue_id").
  992. In("issue_label.label_id", labelIDs)
  993. }
  994. }
  995. return nil
  996. }
  997. // CountIssuesByRepo map from repoID to number of issues matching the options
  998. func CountIssuesByRepo(opts *IssuesOptions) (map[int64]int64, error) {
  999. sess := x.NewSession()
  1000. defer sess.Close()
  1001. if err := opts.setupSession(sess); err != nil {
  1002. return nil, err
  1003. }
  1004. countsSlice := make([]*struct {
  1005. RepoID int64
  1006. Count int64
  1007. }, 0, 10)
  1008. if err := sess.GroupBy("issue.repo_id").
  1009. Select("issue.repo_id AS repo_id, COUNT(*) AS count").
  1010. Table("issue").
  1011. Find(&countsSlice); err != nil {
  1012. return nil, err
  1013. }
  1014. countMap := make(map[int64]int64, len(countsSlice))
  1015. for _, c := range countsSlice {
  1016. countMap[c.RepoID] = c.Count
  1017. }
  1018. return countMap, nil
  1019. }
  1020. // Issues returns a list of issues by given conditions.
  1021. func Issues(opts *IssuesOptions) ([]*Issue, error) {
  1022. sess := x.NewSession()
  1023. defer sess.Close()
  1024. if err := opts.setupSession(sess); err != nil {
  1025. return nil, err
  1026. }
  1027. sortIssuesSession(sess, opts.SortType)
  1028. issues := make([]*Issue, 0, setting.UI.IssuePagingNum)
  1029. if err := sess.Find(&issues); err != nil {
  1030. return nil, fmt.Errorf("Find: %v", err)
  1031. }
  1032. if err := IssueList(issues).LoadAttributes(); err != nil {
  1033. return nil, fmt.Errorf("LoadAttributes: %v", err)
  1034. }
  1035. return issues, nil
  1036. }
  1037. // GetParticipantsByIssueID returns all users who are participated in comments of an issue.
  1038. func GetParticipantsByIssueID(issueID int64) ([]*User, error) {
  1039. return getParticipantsByIssueID(x, issueID)
  1040. }
  1041. func getParticipantsByIssueID(e Engine, issueID int64) ([]*User, error) {
  1042. userIDs := make([]int64, 0, 5)
  1043. if err := e.Table("comment").Cols("poster_id").
  1044. Where("issue_id = ?", issueID).
  1045. And("type = ?", CommentTypeComment).
  1046. Distinct("poster_id").
  1047. Find(&userIDs); err != nil {
  1048. return nil, fmt.Errorf("get poster IDs: %v", err)
  1049. }
  1050. if len(userIDs) == 0 {
  1051. return nil, nil
  1052. }
  1053. users := make([]*User, 0, len(userIDs))
  1054. return users, e.In("id", userIDs).Find(&users)
  1055. }
  1056. // UpdateIssueMentions extracts mentioned people from content and
  1057. // updates issue-user relations for them.
  1058. func UpdateIssueMentions(e Engine, issueID int64, mentions []string) error {
  1059. if len(mentions) == 0 {
  1060. return nil
  1061. }
  1062. for i := range mentions {
  1063. mentions[i] = strings.ToLower(mentions[i])
  1064. }
  1065. users := make([]*User, 0, len(mentions))
  1066. if err := e.In("lower_name", mentions).Asc("lower_name").Find(&users); err != nil {
  1067. return fmt.Errorf("find mentioned users: %v", err)
  1068. }
  1069. ids := make([]int64, 0, len(mentions))
  1070. for _, user := range users {
  1071. ids = append(ids, user.ID)
  1072. if !user.IsOrganization() || user.NumMembers == 0 {
  1073. continue
  1074. }
  1075. memberIDs := make([]int64, 0, user.NumMembers)
  1076. orgUsers, err := GetOrgUsersByOrgID(user.ID)
  1077. if err != nil {
  1078. return fmt.Errorf("GetOrgUsersByOrgID [%d]: %v", user.ID, err)
  1079. }
  1080. for _, orgUser := range orgUsers {
  1081. memberIDs = append(memberIDs, orgUser.ID)
  1082. }
  1083. ids = append(ids, memberIDs...)
  1084. }
  1085. if err := UpdateIssueUsersByMentions(e, issueID, ids); err != nil {
  1086. return fmt.Errorf("UpdateIssueUsersByMentions: %v", err)
  1087. }
  1088. return nil
  1089. }
  1090. // IssueStats represents issue statistic information.
  1091. type IssueStats struct {
  1092. OpenCount, ClosedCount int64
  1093. YourRepositoriesCount int64
  1094. AssignCount int64
  1095. CreateCount int64
  1096. MentionCount int64
  1097. }
  1098. // Filter modes.
  1099. const (
  1100. FilterModeAll = iota
  1101. FilterModeAssign
  1102. FilterModeCreate
  1103. FilterModeMention
  1104. )
  1105. func parseCountResult(results []map[string][]byte) int64 {
  1106. if len(results) == 0 {
  1107. return 0
  1108. }
  1109. for _, result := range results[0] {
  1110. return com.StrTo(string(result)).MustInt64()
  1111. }
  1112. return 0
  1113. }
  1114. // IssueStatsOptions contains parameters accepted by GetIssueStats.
  1115. type IssueStatsOptions struct {
  1116. RepoID int64
  1117. Labels string
  1118. MilestoneID int64
  1119. AssigneeID int64
  1120. MentionedID int64
  1121. PosterID int64
  1122. IsPull bool
  1123. IssueIDs []int64
  1124. }
  1125. // GetIssueStats returns issue statistic information by given conditions.
  1126. func GetIssueStats(opts *IssueStatsOptions) (*IssueStats, error) {
  1127. stats := &IssueStats{}
  1128. countSession := func(opts *IssueStatsOptions) *xorm.Session {
  1129. sess := x.
  1130. Where("issue.repo_id = ?", opts.RepoID).
  1131. And("issue.is_pull = ?", opts.IsPull)
  1132. if len(opts.IssueIDs) > 0 {
  1133. sess.In("issue.id", opts.IssueIDs)
  1134. }
  1135. if len(opts.Labels) > 0 && opts.Labels != "0" {
  1136. labelIDs, err := base.StringsToInt64s(strings.Split(opts.Labels, ","))
  1137. if err != nil {
  1138. log.Warn("Malformed Labels argument: %s", opts.Labels)
  1139. } else if len(labelIDs) > 0 {
  1140. sess.Join("INNER", "issue_label", "issue.id = issue_label.issue_id").
  1141. In("issue_label.label_id", labelIDs)
  1142. }
  1143. }
  1144. if opts.MilestoneID > 0 {
  1145. sess.And("issue.milestone_id = ?", opts.MilestoneID)
  1146. }
  1147. if opts.AssigneeID > 0 {
  1148. sess.And("issue.assignee_id = ?", opts.AssigneeID)
  1149. }
  1150. if opts.PosterID > 0 {
  1151. sess.And("issue.poster_id = ?", opts.PosterID)
  1152. }
  1153. if opts.MentionedID > 0 {
  1154. sess.Join("INNER", "issue_user", "issue.id = issue_user.issue_id").
  1155. And("issue_user.uid = ?", opts.MentionedID).
  1156. And("issue_user.is_mentioned = ?", true)
  1157. }
  1158. return sess
  1159. }
  1160. var err error
  1161. stats.OpenCount, err = countSession(opts).
  1162. And("issue.is_closed = ?", false).
  1163. Count(new(Issue))
  1164. if err != nil {
  1165. return stats, err
  1166. }
  1167. stats.ClosedCount, err = countSession(opts).
  1168. And("issue.is_closed = ?", true).
  1169. Count(new(Issue))
  1170. return stats, err
  1171. }
  1172. // GetUserIssueStats returns issue statistic information for dashboard by given conditions.
  1173. func GetUserIssueStats(repoID, uid int64, repoIDs []int64, filterMode int, isPull bool) *IssueStats {
  1174. stats := &IssueStats{}
  1175. countSession := func(isClosed, isPull bool, repoID int64, repoIDs []int64) *xorm.Session {
  1176. sess := x.
  1177. Where("issue.is_closed = ?", isClosed).
  1178. And("issue.is_pull = ?", isPull)
  1179. if repoID > 0 {
  1180. sess.And("repo_id = ?", repoID)
  1181. } else if len(repoIDs) > 0 {
  1182. sess.In("repo_id", repoIDs)
  1183. }
  1184. return sess
  1185. }
  1186. stats.AssignCount, _ = countSession(false, isPull, repoID, nil).
  1187. And("assignee_id = ?", uid).
  1188. Count(new(Issue))
  1189. stats.CreateCount, _ = countSession(false, isPull, repoID, nil).
  1190. And("poster_id = ?", uid).
  1191. Count(new(Issue))
  1192. stats.YourRepositoriesCount, _ = countSession(false, isPull, repoID, repoIDs).
  1193. Count(new(Issue))
  1194. switch filterMode {
  1195. case FilterModeAll:
  1196. stats.OpenCount, _ = countSession(false, isPull, repoID, repoIDs).
  1197. Count(new(Issue))
  1198. stats.ClosedCount, _ = countSession(true, isPull, repoID, repoIDs).
  1199. Count(new(Issue))
  1200. case FilterModeAssign:
  1201. stats.OpenCount, _ = countSession(false, isPull, repoID, nil).
  1202. And("assignee_id = ?", uid).
  1203. Count(new(Issue))
  1204. stats.ClosedCount, _ = countSession(true, isPull, repoID, nil).
  1205. And("assignee_id = ?", uid).
  1206. Count(new(Issue))
  1207. case FilterModeCreate:
  1208. stats.OpenCount, _ = countSession(false, isPull, repoID, nil).
  1209. And("poster_id = ?", uid).
  1210. Count(new(Issue))
  1211. stats.ClosedCount, _ = countSession(true, isPull, repoID, nil).
  1212. And("poster_id = ?", uid).
  1213. Count(new(Issue))
  1214. }
  1215. return stats
  1216. }
  1217. // GetRepoIssueStats returns number of open and closed repository issues by given filter mode.
  1218. func GetRepoIssueStats(repoID, uid int64, filterMode int, isPull bool) (numOpen int64, numClosed int64) {
  1219. countSession := func(isClosed, isPull bool, repoID int64) *xorm.Session {
  1220. sess := x.
  1221. Where("is_closed = ?", isClosed).
  1222. And("is_pull = ?", isPull).
  1223. And("repo_id = ?", repoID)
  1224. return sess
  1225. }
  1226. openCountSession := countSession(false, isPull, repoID)
  1227. closedCountSession := countSession(true, isPull, repoID)
  1228. switch filterMode {
  1229. case FilterModeAssign:
  1230. openCountSession.And("assignee_id = ?", uid)
  1231. closedCountSession.And("assignee_id = ?", uid)
  1232. case FilterModeCreate:
  1233. openCountSession.And("poster_id = ?", uid)
  1234. closedCountSession.And("poster_id = ?", uid)
  1235. }
  1236. openResult, _ := openCountSession.Count(new(Issue))
  1237. closedResult, _ := closedCountSession.Count(new(Issue))
  1238. return openResult, closedResult
  1239. }
  1240. func updateIssue(e Engine, issue *Issue) error {
  1241. _, err := e.Id(issue.ID).AllCols().Update(issue)
  1242. if err != nil {
  1243. return err
  1244. }
  1245. UpdateIssueIndexer(issue)
  1246. return nil
  1247. }
  1248. // UpdateIssue updates all fields of given issue.
  1249. func UpdateIssue(issue *Issue) error {
  1250. return updateIssue(x, issue)
  1251. }