Fork to maintain patches against the official gitea for https://code.ceondo.com https://github.com/go-gitea/gitea

issue.go 36KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399
  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. if err := PrepareWebhooks(issue.Repo, HookEventPullRequest, apiPullRequest); err != nil {
  668. log.Error(4, "PrepareWebhooks [is_pull: %v, remove_assignee: %v]: %v", issue.IsPull, isRemoveAssignee, err)
  669. return nil
  670. }
  671. }
  672. go HookQueue.Add(issue.RepoID)
  673. return nil
  674. }
  675. // NewIssueOptions represents the options of a new issue.
  676. type NewIssueOptions struct {
  677. Repo *Repository
  678. Issue *Issue
  679. LableIDs []int64
  680. Attachments []string // In UUID format.
  681. IsPull bool
  682. }
  683. func newIssue(e *xorm.Session, doer *User, opts NewIssueOptions) (err error) {
  684. opts.Issue.Title = strings.TrimSpace(opts.Issue.Title)
  685. opts.Issue.Index = opts.Repo.NextIssueIndex()
  686. if opts.Issue.MilestoneID > 0 {
  687. milestone, err := getMilestoneByRepoID(e, opts.Issue.RepoID, opts.Issue.MilestoneID)
  688. if err != nil && !IsErrMilestoneNotExist(err) {
  689. return fmt.Errorf("getMilestoneByID: %v", err)
  690. }
  691. // Assume milestone is invalid and drop silently.
  692. opts.Issue.MilestoneID = 0
  693. if milestone != nil {
  694. opts.Issue.MilestoneID = milestone.ID
  695. opts.Issue.Milestone = milestone
  696. }
  697. }
  698. if opts.Issue.AssigneeID > 0 {
  699. assignee, err := getUserByID(e, opts.Issue.AssigneeID)
  700. if err != nil && !IsErrUserNotExist(err) {
  701. return fmt.Errorf("getUserByID: %v", err)
  702. }
  703. // Assume assignee is invalid and drop silently.
  704. opts.Issue.AssigneeID = 0
  705. if assignee != nil {
  706. valid, err := hasAccess(e, assignee, opts.Repo, AccessModeWrite)
  707. if err != nil {
  708. return fmt.Errorf("hasAccess [user_id: %d, repo_id: %d]: %v", assignee.ID, opts.Repo.ID, err)
  709. }
  710. if valid {
  711. opts.Issue.AssigneeID = assignee.ID
  712. opts.Issue.Assignee = assignee
  713. }
  714. }
  715. }
  716. // Milestone and assignee validation should happen before insert actual object.
  717. if _, err = e.Insert(opts.Issue); err != nil {
  718. return err
  719. }
  720. if opts.Issue.MilestoneID > 0 {
  721. if err = changeMilestoneAssign(e, doer, opts.Issue, -1); err != nil {
  722. return err
  723. }
  724. }
  725. if opts.Issue.AssigneeID > 0 {
  726. if err = opts.Issue.loadRepo(e); err != nil {
  727. return err
  728. }
  729. if _, err = createAssigneeComment(e, doer, opts.Issue.Repo, opts.Issue, -1, opts.Issue.AssigneeID); err != nil {
  730. return err
  731. }
  732. }
  733. if opts.IsPull {
  734. _, err = e.Exec("UPDATE `repository` SET num_pulls = num_pulls + 1 WHERE id = ?", opts.Issue.RepoID)
  735. } else {
  736. _, err = e.Exec("UPDATE `repository` SET num_issues = num_issues + 1 WHERE id = ?", opts.Issue.RepoID)
  737. }
  738. if err != nil {
  739. return err
  740. }
  741. if len(opts.LableIDs) > 0 {
  742. // During the session, SQLite3 driver cannot handle retrieve objects after update something.
  743. // So we have to get all needed labels first.
  744. labels := make([]*Label, 0, len(opts.LableIDs))
  745. if err = e.In("id", opts.LableIDs).Find(&labels); err != nil {
  746. return fmt.Errorf("find all labels [label_ids: %v]: %v", opts.LableIDs, err)
  747. }
  748. if err = opts.Issue.loadPoster(e); err != nil {
  749. return err
  750. }
  751. for _, label := range labels {
  752. // Silently drop invalid labels.
  753. if label.RepoID != opts.Repo.ID {
  754. continue
  755. }
  756. if err = opts.Issue.addLabel(e, label, opts.Issue.Poster); err != nil {
  757. return fmt.Errorf("addLabel [id: %d]: %v", label.ID, err)
  758. }
  759. }
  760. }
  761. if err = newIssueUsers(e, opts.Repo, opts.Issue); err != nil {
  762. return err
  763. }
  764. UpdateIssueIndexer(opts.Issue)
  765. if len(opts.Attachments) > 0 {
  766. attachments, err := getAttachmentsByUUIDs(e, opts.Attachments)
  767. if err != nil {
  768. return fmt.Errorf("getAttachmentsByUUIDs [uuids: %v]: %v", opts.Attachments, err)
  769. }
  770. for i := 0; i < len(attachments); i++ {
  771. attachments[i].IssueID = opts.Issue.ID
  772. if _, err = e.Id(attachments[i].ID).Update(attachments[i]); err != nil {
  773. return fmt.Errorf("update attachment [id: %d]: %v", attachments[i].ID, err)
  774. }
  775. }
  776. }
  777. return opts.Issue.loadAttributes(e)
  778. }
  779. // NewIssue creates new issue with labels for repository.
  780. func NewIssue(repo *Repository, issue *Issue, labelIDs []int64, uuids []string) (err error) {
  781. sess := x.NewSession()
  782. defer sessionRelease(sess)
  783. if err = sess.Begin(); err != nil {
  784. return err
  785. }
  786. if err = newIssue(sess, issue.Poster, NewIssueOptions{
  787. Repo: repo,
  788. Issue: issue,
  789. LableIDs: labelIDs,
  790. Attachments: uuids,
  791. }); err != nil {
  792. return fmt.Errorf("newIssue: %v", err)
  793. }
  794. if err = sess.Commit(); err != nil {
  795. return fmt.Errorf("Commit: %v", err)
  796. }
  797. if err = NotifyWatchers(&Action{
  798. ActUserID: issue.Poster.ID,
  799. ActUserName: issue.Poster.Name,
  800. OpType: ActionCreateIssue,
  801. Content: fmt.Sprintf("%d|%s", issue.Index, issue.Title),
  802. RepoID: repo.ID,
  803. RepoUserName: repo.Owner.Name,
  804. RepoName: repo.Name,
  805. IsPrivate: repo.IsPrivate,
  806. }); err != nil {
  807. log.Error(4, "NotifyWatchers: %v", err)
  808. }
  809. if err = issue.MailParticipants(); err != nil {
  810. log.Error(4, "MailParticipants: %v", err)
  811. }
  812. return nil
  813. }
  814. // GetIssueByRef returns an Issue specified by a GFM reference.
  815. // See https://help.github.com/articles/writing-on-github#references for more information on the syntax.
  816. func GetIssueByRef(ref string) (*Issue, error) {
  817. n := strings.IndexByte(ref, byte('#'))
  818. if n == -1 {
  819. return nil, errMissingIssueNumber
  820. }
  821. index, err := com.StrTo(ref[n+1:]).Int64()
  822. if err != nil {
  823. return nil, err
  824. }
  825. repo, err := GetRepositoryByRef(ref[:n])
  826. if err != nil {
  827. return nil, err
  828. }
  829. issue, err := GetIssueByIndex(repo.ID, index)
  830. if err != nil {
  831. return nil, err
  832. }
  833. return issue, issue.LoadAttributes()
  834. }
  835. // GetRawIssueByIndex returns raw issue without loading attributes by index in a repository.
  836. func GetRawIssueByIndex(repoID, index int64) (*Issue, error) {
  837. issue := &Issue{
  838. RepoID: repoID,
  839. Index: index,
  840. }
  841. has, err := x.Get(issue)
  842. if err != nil {
  843. return nil, err
  844. } else if !has {
  845. return nil, ErrIssueNotExist{0, repoID, index}
  846. }
  847. return issue, nil
  848. }
  849. // GetIssueByIndex returns issue by index in a repository.
  850. func GetIssueByIndex(repoID, index int64) (*Issue, error) {
  851. issue, err := GetRawIssueByIndex(repoID, index)
  852. if err != nil {
  853. return nil, err
  854. }
  855. return issue, issue.LoadAttributes()
  856. }
  857. func getIssueByID(e Engine, id int64) (*Issue, error) {
  858. issue := new(Issue)
  859. has, err := e.Id(id).Get(issue)
  860. if err != nil {
  861. return nil, err
  862. } else if !has {
  863. return nil, ErrIssueNotExist{id, 0, 0}
  864. }
  865. return issue, issue.LoadAttributes()
  866. }
  867. // GetIssueByID returns an issue by given ID.
  868. func GetIssueByID(id int64) (*Issue, error) {
  869. return getIssueByID(x, id)
  870. }
  871. // IssuesOptions represents options of an issue.
  872. type IssuesOptions struct {
  873. RepoID int64
  874. AssigneeID int64
  875. PosterID int64
  876. MentionedID int64
  877. MilestoneID int64
  878. RepoIDs []int64
  879. Page int
  880. IsClosed util.OptionalBool
  881. IsPull util.OptionalBool
  882. Labels string
  883. SortType string
  884. IssueIDs []int64
  885. }
  886. // sortIssuesSession sort an issues-related session based on the provided
  887. // sortType string
  888. func sortIssuesSession(sess *xorm.Session, sortType string) {
  889. switch sortType {
  890. case "oldest":
  891. sess.Asc("issue.created_unix")
  892. case "recentupdate":
  893. sess.Desc("issue.updated_unix")
  894. case "leastupdate":
  895. sess.Asc("issue.updated_unix")
  896. case "mostcomment":
  897. sess.Desc("issue.num_comments")
  898. case "leastcomment":
  899. sess.Asc("issue.num_comments")
  900. case "priority":
  901. sess.Desc("issue.priority")
  902. default:
  903. sess.Desc("issue.created_unix")
  904. }
  905. }
  906. // Issues returns a list of issues by given conditions.
  907. func Issues(opts *IssuesOptions) ([]*Issue, error) {
  908. var sess *xorm.Session
  909. if opts.Page >= 0 {
  910. var start int
  911. if opts.Page == 0 {
  912. start = 0
  913. } else {
  914. start = (opts.Page - 1) * setting.UI.IssuePagingNum
  915. }
  916. sess = x.Limit(setting.UI.IssuePagingNum, start)
  917. } else {
  918. sess = x.NewSession()
  919. defer sess.Close()
  920. }
  921. if len(opts.IssueIDs) > 0 {
  922. sess.In("issue.id", opts.IssueIDs)
  923. }
  924. if opts.RepoID > 0 {
  925. sess.And("issue.repo_id=?", opts.RepoID)
  926. } else if len(opts.RepoIDs) > 0 {
  927. // In case repository IDs are provided but actually no repository has issue.
  928. sess.In("issue.repo_id", opts.RepoIDs)
  929. }
  930. switch opts.IsClosed {
  931. case util.OptionalBoolTrue:
  932. sess.And("issue.is_closed=?", true)
  933. case util.OptionalBoolFalse:
  934. sess.And("issue.is_closed=?", false)
  935. }
  936. if opts.AssigneeID > 0 {
  937. sess.And("issue.assignee_id=?", opts.AssigneeID)
  938. }
  939. if opts.PosterID > 0 {
  940. sess.And("issue.poster_id=?", opts.PosterID)
  941. }
  942. if opts.MentionedID > 0 {
  943. sess.Join("INNER", "issue_user", "issue.id = issue_user.issue_id").
  944. And("issue_user.is_mentioned = ?", true).
  945. And("issue_user.uid = ?", opts.MentionedID)
  946. }
  947. if opts.MilestoneID > 0 {
  948. sess.And("issue.milestone_id=?", opts.MilestoneID)
  949. }
  950. switch opts.IsPull {
  951. case util.OptionalBoolTrue:
  952. sess.And("issue.is_pull=?", true)
  953. case util.OptionalBoolFalse:
  954. sess.And("issue.is_pull=?", false)
  955. }
  956. sortIssuesSession(sess, opts.SortType)
  957. if len(opts.Labels) > 0 && opts.Labels != "0" {
  958. labelIDs, err := base.StringsToInt64s(strings.Split(opts.Labels, ","))
  959. if err != nil {
  960. return nil, err
  961. }
  962. if len(labelIDs) > 0 {
  963. sess.
  964. Join("INNER", "issue_label", "issue.id = issue_label.issue_id").
  965. In("issue_label.label_id", labelIDs)
  966. }
  967. }
  968. issues := make([]*Issue, 0, setting.UI.IssuePagingNum)
  969. if err := sess.Find(&issues); err != nil {
  970. return nil, fmt.Errorf("Find: %v", err)
  971. }
  972. if err := IssueList(issues).LoadAttributes(); err != nil {
  973. return nil, fmt.Errorf("LoadAttributes: %v", err)
  974. }
  975. return issues, nil
  976. }
  977. // UpdateIssueMentions extracts mentioned people from content and
  978. // updates issue-user relations for them.
  979. func UpdateIssueMentions(e Engine, issueID int64, mentions []string) error {
  980. if len(mentions) == 0 {
  981. return nil
  982. }
  983. for i := range mentions {
  984. mentions[i] = strings.ToLower(mentions[i])
  985. }
  986. users := make([]*User, 0, len(mentions))
  987. if err := e.In("lower_name", mentions).Asc("lower_name").Find(&users); err != nil {
  988. return fmt.Errorf("find mentioned users: %v", err)
  989. }
  990. ids := make([]int64, 0, len(mentions))
  991. for _, user := range users {
  992. ids = append(ids, user.ID)
  993. if !user.IsOrganization() || user.NumMembers == 0 {
  994. continue
  995. }
  996. memberIDs := make([]int64, 0, user.NumMembers)
  997. orgUsers, err := GetOrgUsersByOrgID(user.ID)
  998. if err != nil {
  999. return fmt.Errorf("GetOrgUsersByOrgID [%d]: %v", user.ID, err)
  1000. }
  1001. for _, orgUser := range orgUsers {
  1002. memberIDs = append(memberIDs, orgUser.ID)
  1003. }
  1004. ids = append(ids, memberIDs...)
  1005. }
  1006. if err := UpdateIssueUsersByMentions(e, issueID, ids); err != nil {
  1007. return fmt.Errorf("UpdateIssueUsersByMentions: %v", err)
  1008. }
  1009. return nil
  1010. }
  1011. // IssueStats represents issue statistic information.
  1012. type IssueStats struct {
  1013. OpenCount, ClosedCount int64
  1014. YourRepositoriesCount int64
  1015. AssignCount int64
  1016. CreateCount int64
  1017. MentionCount int64
  1018. }
  1019. // Filter modes.
  1020. const (
  1021. FilterModeAll = iota
  1022. FilterModeAssign
  1023. FilterModeCreate
  1024. FilterModeMention
  1025. )
  1026. func parseCountResult(results []map[string][]byte) int64 {
  1027. if len(results) == 0 {
  1028. return 0
  1029. }
  1030. for _, result := range results[0] {
  1031. return com.StrTo(string(result)).MustInt64()
  1032. }
  1033. return 0
  1034. }
  1035. // IssueStatsOptions contains parameters accepted by GetIssueStats.
  1036. type IssueStatsOptions struct {
  1037. FilterMode int
  1038. RepoID int64
  1039. Labels string
  1040. MilestoneID int64
  1041. AssigneeID int64
  1042. MentionedID int64
  1043. PosterID int64
  1044. IsPull bool
  1045. IssueIDs []int64
  1046. }
  1047. // GetIssueStats returns issue statistic information by given conditions.
  1048. func GetIssueStats(opts *IssueStatsOptions) (*IssueStats, error) {
  1049. stats := &IssueStats{}
  1050. countSession := func(opts *IssueStatsOptions) *xorm.Session {
  1051. sess := x.
  1052. Where("issue.repo_id = ?", opts.RepoID).
  1053. And("is_pull = ?", opts.IsPull)
  1054. if len(opts.IssueIDs) > 0 {
  1055. sess.In("issue.id", opts.IssueIDs)
  1056. }
  1057. if len(opts.Labels) > 0 && opts.Labels != "0" {
  1058. labelIDs, err := base.StringsToInt64s(strings.Split(opts.Labels, ","))
  1059. if err != nil {
  1060. log.Warn("Malformed Labels argument: %s", opts.Labels)
  1061. } else if len(labelIDs) > 0 {
  1062. sess.Join("INNER", "issue_label", "issue.id = issue_id").
  1063. In("label_id", labelIDs)
  1064. }
  1065. }
  1066. if opts.MilestoneID > 0 {
  1067. sess.And("issue.milestone_id = ?", opts.MilestoneID)
  1068. }
  1069. if opts.AssigneeID > 0 {
  1070. sess.And("assignee_id = ?", opts.AssigneeID)
  1071. }
  1072. if opts.PosterID > 0 {
  1073. sess.And("poster_id = ?", opts.PosterID)
  1074. }
  1075. if opts.MentionedID > 0 {
  1076. sess.Join("INNER", "issue_user", "issue.id = issue_user.issue_id").
  1077. And("issue_user.uid = ?", opts.MentionedID).
  1078. And("issue_user.is_mentioned = ?", true)
  1079. }
  1080. return sess
  1081. }
  1082. var err error
  1083. switch opts.FilterMode {
  1084. case FilterModeAll, FilterModeAssign:
  1085. stats.OpenCount, err = countSession(opts).
  1086. And("is_closed = ?", false).
  1087. Count(new(Issue))
  1088. stats.ClosedCount, err = countSession(opts).
  1089. And("is_closed = ?", true).
  1090. Count(new(Issue))
  1091. case FilterModeCreate:
  1092. stats.OpenCount, err = countSession(opts).
  1093. And("poster_id = ?", opts.PosterID).
  1094. And("is_closed = ?", false).
  1095. Count(new(Issue))
  1096. stats.ClosedCount, err = countSession(opts).
  1097. And("poster_id = ?", opts.PosterID).
  1098. And("is_closed = ?", true).
  1099. Count(new(Issue))
  1100. case FilterModeMention:
  1101. stats.OpenCount, err = countSession(opts).
  1102. Join("INNER", "issue_user", "issue.id = issue_user.issue_id").
  1103. And("issue_user.uid = ?", opts.PosterID).
  1104. And("issue_user.is_mentioned = ?", true).
  1105. And("issue.is_closed = ?", false).
  1106. Count(new(Issue))
  1107. stats.ClosedCount, err = countSession(opts).
  1108. Join("INNER", "issue_user", "issue.id = issue_user.issue_id").
  1109. And("issue_user.uid = ?", opts.PosterID).
  1110. And("issue_user.is_mentioned = ?", true).
  1111. And("issue.is_closed = ?", true).
  1112. Count(new(Issue))
  1113. }
  1114. return stats, err
  1115. }
  1116. // GetUserIssueStats returns issue statistic information for dashboard by given conditions.
  1117. func GetUserIssueStats(repoID, uid int64, repoIDs []int64, filterMode int, isPull bool) *IssueStats {
  1118. stats := &IssueStats{}
  1119. countSession := func(isClosed, isPull bool, repoID int64, repoIDs []int64) *xorm.Session {
  1120. sess := x.
  1121. Where("issue.is_closed = ?", isClosed).
  1122. And("issue.is_pull = ?", isPull)
  1123. if repoID > 0 {
  1124. sess.And("repo_id = ?", repoID)
  1125. } else if len(repoIDs) > 0 {
  1126. sess.In("repo_id", repoIDs)
  1127. }
  1128. return sess
  1129. }
  1130. stats.AssignCount, _ = countSession(false, isPull, repoID, nil).
  1131. And("assignee_id = ?", uid).
  1132. Count(new(Issue))
  1133. stats.CreateCount, _ = countSession(false, isPull, repoID, nil).
  1134. And("poster_id = ?", uid).
  1135. Count(new(Issue))
  1136. stats.YourRepositoriesCount, _ = countSession(false, isPull, repoID, repoIDs).
  1137. Count(new(Issue))
  1138. switch filterMode {
  1139. case FilterModeAll:
  1140. stats.OpenCount, _ = countSession(false, isPull, repoID, repoIDs).
  1141. Count(new(Issue))
  1142. stats.ClosedCount, _ = countSession(true, isPull, repoID, repoIDs).
  1143. Count(new(Issue))
  1144. case FilterModeAssign:
  1145. stats.OpenCount, _ = countSession(false, isPull, repoID, nil).
  1146. And("assignee_id = ?", uid).
  1147. Count(new(Issue))
  1148. stats.ClosedCount, _ = countSession(true, isPull, repoID, nil).
  1149. And("assignee_id = ?", uid).
  1150. Count(new(Issue))
  1151. case FilterModeCreate:
  1152. stats.OpenCount, _ = countSession(false, isPull, repoID, nil).
  1153. And("poster_id = ?", uid).
  1154. Count(new(Issue))
  1155. stats.ClosedCount, _ = countSession(true, isPull, repoID, nil).
  1156. And("poster_id = ?", uid).
  1157. Count(new(Issue))
  1158. }
  1159. return stats
  1160. }
  1161. // GetRepoIssueStats returns number of open and closed repository issues by given filter mode.
  1162. func GetRepoIssueStats(repoID, uid int64, filterMode int, isPull bool) (numOpen int64, numClosed int64) {
  1163. countSession := func(isClosed, isPull bool, repoID int64) *xorm.Session {
  1164. sess := x.
  1165. Where("is_closed = ?", isClosed).
  1166. And("is_pull = ?", isPull).
  1167. And("repo_id = ?", repoID)
  1168. return sess
  1169. }
  1170. openCountSession := countSession(false, isPull, repoID)
  1171. closedCountSession := countSession(true, isPull, repoID)
  1172. switch filterMode {
  1173. case FilterModeAssign:
  1174. openCountSession.And("assignee_id = ?", uid)
  1175. closedCountSession.And("assignee_id = ?", uid)
  1176. case FilterModeCreate:
  1177. openCountSession.And("poster_id = ?", uid)
  1178. closedCountSession.And("poster_id = ?", uid)
  1179. }
  1180. openResult, _ := openCountSession.Count(new(Issue))
  1181. closedResult, _ := closedCountSession.Count(new(Issue))
  1182. return openResult, closedResult
  1183. }
  1184. func updateIssue(e Engine, issue *Issue) error {
  1185. _, err := e.Id(issue.ID).AllCols().Update(issue)
  1186. if err != nil {
  1187. return err
  1188. }
  1189. UpdateIssueIndexer(issue)
  1190. return nil
  1191. }
  1192. // UpdateIssue updates all fields of given issue.
  1193. func UpdateIssue(issue *Issue) error {
  1194. return updateIssue(x, issue)
  1195. }