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