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 37 kB

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