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

issue.go 36KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389
  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. addIndex, removeIndex := 0, 0
  409. for addIndex < len(labels) && removeIndex < len(issue.Labels) {
  410. addLabel := labels[addIndex]
  411. removeLabel := issue.Labels[removeIndex]
  412. if addLabel.ID == removeLabel.ID {
  413. addIndex++
  414. removeIndex++
  415. } else if addLabel.ID < removeLabel.ID {
  416. toAdd = append(toAdd, addLabel)
  417. addIndex++
  418. } else {
  419. toRemove = append(toRemove, removeLabel)
  420. removeIndex++
  421. }
  422. }
  423. toAdd = append(toAdd, labels[addIndex:]...)
  424. toRemove = append(toRemove, issue.Labels[removeIndex:]...)
  425. if len(toAdd) > 0 {
  426. if err = issue.addLabels(sess, toAdd, doer); err != nil {
  427. return fmt.Errorf("addLabels: %v", err)
  428. }
  429. }
  430. for _, l := range toRemove {
  431. if err = issue.removeLabel(sess, doer, l); err != nil {
  432. return fmt.Errorf("removeLabel: %v", err)
  433. }
  434. }
  435. return sess.Commit()
  436. }
  437. // GetAssignee sets the Assignee attribute of this issue.
  438. func (issue *Issue) GetAssignee() (err error) {
  439. if issue.AssigneeID == 0 || issue.Assignee != nil {
  440. return nil
  441. }
  442. issue.Assignee, err = GetUserByID(issue.AssigneeID)
  443. if IsErrUserNotExist(err) {
  444. return nil
  445. }
  446. return err
  447. }
  448. // ReadBy sets issue to be read by given user.
  449. func (issue *Issue) ReadBy(userID int64) error {
  450. if err := UpdateIssueUserByRead(userID, issue.ID); err != nil {
  451. return err
  452. }
  453. if err := setNotificationStatusReadIfUnread(x, userID, issue.ID); err != nil {
  454. return err
  455. }
  456. return nil
  457. }
  458. func updateIssueCols(e Engine, issue *Issue, cols ...string) error {
  459. if _, err := e.Id(issue.ID).Cols(cols...).Update(issue); err != nil {
  460. return err
  461. }
  462. UpdateIssueIndexer(issue)
  463. return nil
  464. }
  465. // UpdateIssueCols only updates values of specific columns for given issue.
  466. func UpdateIssueCols(issue *Issue, cols ...string) error {
  467. return updateIssueCols(x, issue, cols...)
  468. }
  469. func (issue *Issue) changeStatus(e *xorm.Session, doer *User, repo *Repository, isClosed bool) (err error) {
  470. // Nothing should be performed if current status is same as target status
  471. if issue.IsClosed == isClosed {
  472. return nil
  473. }
  474. issue.IsClosed = isClosed
  475. if err = updateIssueCols(e, issue, "is_closed"); err != nil {
  476. return err
  477. }
  478. // Update issue count of labels
  479. if err = issue.getLabels(e); err != nil {
  480. return err
  481. }
  482. for idx := range issue.Labels {
  483. if issue.IsClosed {
  484. issue.Labels[idx].NumClosedIssues++
  485. } else {
  486. issue.Labels[idx].NumClosedIssues--
  487. }
  488. if err = updateLabel(e, issue.Labels[idx]); err != nil {
  489. return err
  490. }
  491. }
  492. // Update issue count of milestone
  493. if err = changeMilestoneIssueStats(e, issue); err != nil {
  494. return err
  495. }
  496. // New action comment
  497. if _, err = createStatusComment(e, doer, repo, issue); err != nil {
  498. return err
  499. }
  500. return nil
  501. }
  502. // ChangeStatus changes issue status to open or closed.
  503. func (issue *Issue) ChangeStatus(doer *User, repo *Repository, isClosed bool) (err error) {
  504. sess := x.NewSession()
  505. defer sessionRelease(sess)
  506. if err = sess.Begin(); err != nil {
  507. return err
  508. }
  509. if err = issue.changeStatus(sess, doer, repo, isClosed); err != nil {
  510. return err
  511. }
  512. if err = sess.Commit(); err != nil {
  513. return fmt.Errorf("Commit: %v", err)
  514. }
  515. if issue.IsPull {
  516. // Merge pull request calls issue.changeStatus so we need to handle separately.
  517. issue.PullRequest.Issue = issue
  518. apiPullRequest := &api.PullRequestPayload{
  519. Index: issue.Index,
  520. PullRequest: issue.PullRequest.APIFormat(),
  521. Repository: repo.APIFormat(AccessModeNone),
  522. Sender: doer.APIFormat(),
  523. }
  524. if isClosed {
  525. apiPullRequest.Action = api.HookIssueClosed
  526. } else {
  527. apiPullRequest.Action = api.HookIssueReOpened
  528. }
  529. err = PrepareWebhooks(repo, HookEventPullRequest, apiPullRequest)
  530. }
  531. if err != nil {
  532. log.Error(4, "PrepareWebhooks [is_pull: %v, is_closed: %v]: %v", issue.IsPull, isClosed, err)
  533. } else {
  534. go HookQueue.Add(repo.ID)
  535. }
  536. return nil
  537. }
  538. // ChangeTitle changes the title of this issue, as the given user.
  539. func (issue *Issue) ChangeTitle(doer *User, title string) (err error) {
  540. oldTitle := issue.Title
  541. issue.Title = title
  542. sess := x.NewSession()
  543. defer sess.Close()
  544. if err = sess.Begin(); err != nil {
  545. return err
  546. }
  547. if err = updateIssueCols(sess, issue, "name"); err != nil {
  548. return fmt.Errorf("updateIssueCols: %v", err)
  549. }
  550. if _, err = createChangeTitleComment(sess, doer, issue.Repo, issue, oldTitle, title); err != nil {
  551. return fmt.Errorf("createChangeTitleComment: %v", err)
  552. }
  553. if err = sess.Commit(); err != nil {
  554. return err
  555. }
  556. if issue.IsPull {
  557. issue.PullRequest.Issue = issue
  558. err = PrepareWebhooks(issue.Repo, HookEventPullRequest, &api.PullRequestPayload{
  559. Action: api.HookIssueEdited,
  560. Index: issue.Index,
  561. Changes: &api.ChangesPayload{
  562. Title: &api.ChangesFromPayload{
  563. From: oldTitle,
  564. },
  565. },
  566. PullRequest: issue.PullRequest.APIFormat(),
  567. Repository: issue.Repo.APIFormat(AccessModeNone),
  568. Sender: doer.APIFormat(),
  569. })
  570. }
  571. if err != nil {
  572. log.Error(4, "PrepareWebhooks [is_pull: %v]: %v", issue.IsPull, err)
  573. } else {
  574. go HookQueue.Add(issue.RepoID)
  575. }
  576. return nil
  577. }
  578. // AddDeletePRBranchComment adds delete branch comment for pull request issue
  579. func AddDeletePRBranchComment(doer *User, repo *Repository, issueID int64, branchName string) error {
  580. issue, err := getIssueByID(x, issueID)
  581. if err != nil {
  582. return err
  583. }
  584. sess := x.NewSession()
  585. defer sess.Close()
  586. if err := sess.Begin(); err != nil {
  587. return err
  588. }
  589. if _, err := createDeleteBranchComment(sess, doer, repo, issue, branchName); err != nil {
  590. return err
  591. }
  592. return sess.Commit()
  593. }
  594. // ChangeContent changes issue content, as the given user.
  595. func (issue *Issue) ChangeContent(doer *User, content string) (err error) {
  596. oldContent := issue.Content
  597. issue.Content = content
  598. if err = UpdateIssueCols(issue, "content"); err != nil {
  599. return fmt.Errorf("UpdateIssueCols: %v", err)
  600. }
  601. if issue.IsPull {
  602. issue.PullRequest.Issue = issue
  603. err = PrepareWebhooks(issue.Repo, HookEventPullRequest, &api.PullRequestPayload{
  604. Action: api.HookIssueEdited,
  605. Index: issue.Index,
  606. Changes: &api.ChangesPayload{
  607. Body: &api.ChangesFromPayload{
  608. From: oldContent,
  609. },
  610. },
  611. PullRequest: issue.PullRequest.APIFormat(),
  612. Repository: issue.Repo.APIFormat(AccessModeNone),
  613. Sender: doer.APIFormat(),
  614. })
  615. }
  616. if err != nil {
  617. log.Error(4, "PrepareWebhooks [is_pull: %v]: %v", issue.IsPull, err)
  618. } else {
  619. go HookQueue.Add(issue.RepoID)
  620. }
  621. return nil
  622. }
  623. // ChangeAssignee changes the Asssignee field of this issue.
  624. func (issue *Issue) ChangeAssignee(doer *User, assigneeID int64) (err error) {
  625. var oldAssigneeID = issue.AssigneeID
  626. issue.AssigneeID = assigneeID
  627. if err = UpdateIssueUserByAssignee(issue); err != nil {
  628. return fmt.Errorf("UpdateIssueUserByAssignee: %v", err)
  629. }
  630. sess := x.NewSession()
  631. defer sess.Close()
  632. if err = issue.loadRepo(sess); err != nil {
  633. return fmt.Errorf("loadRepo: %v", err)
  634. }
  635. if _, err = createAssigneeComment(sess, doer, issue.Repo, issue, oldAssigneeID, assigneeID); err != nil {
  636. return fmt.Errorf("createAssigneeComment: %v", err)
  637. }
  638. issue.Assignee, err = GetUserByID(issue.AssigneeID)
  639. if err != nil && !IsErrUserNotExist(err) {
  640. log.Error(4, "GetUserByID [assignee_id: %v]: %v", issue.AssigneeID, err)
  641. return nil
  642. }
  643. // Error not nil here means user does not exist, which is remove assignee.
  644. isRemoveAssignee := err != nil
  645. if issue.IsPull {
  646. issue.PullRequest.Issue = issue
  647. apiPullRequest := &api.PullRequestPayload{
  648. Index: issue.Index,
  649. PullRequest: issue.PullRequest.APIFormat(),
  650. Repository: issue.Repo.APIFormat(AccessModeNone),
  651. Sender: doer.APIFormat(),
  652. }
  653. if isRemoveAssignee {
  654. apiPullRequest.Action = api.HookIssueUnassigned
  655. } else {
  656. apiPullRequest.Action = api.HookIssueAssigned
  657. }
  658. if err := PrepareWebhooks(issue.Repo, HookEventPullRequest, apiPullRequest); err != nil {
  659. log.Error(4, "PrepareWebhooks [is_pull: %v, remove_assignee: %v]: %v", issue.IsPull, isRemoveAssignee, err)
  660. return nil
  661. }
  662. }
  663. go HookQueue.Add(issue.RepoID)
  664. return nil
  665. }
  666. // NewIssueOptions represents the options of a new issue.
  667. type NewIssueOptions struct {
  668. Repo *Repository
  669. Issue *Issue
  670. LableIDs []int64
  671. Attachments []string // In UUID format.
  672. IsPull bool
  673. }
  674. func newIssue(e *xorm.Session, doer *User, opts NewIssueOptions) (err error) {
  675. opts.Issue.Title = strings.TrimSpace(opts.Issue.Title)
  676. opts.Issue.Index = opts.Repo.NextIssueIndex()
  677. if opts.Issue.MilestoneID > 0 {
  678. milestone, err := getMilestoneByRepoID(e, opts.Issue.RepoID, opts.Issue.MilestoneID)
  679. if err != nil && !IsErrMilestoneNotExist(err) {
  680. return fmt.Errorf("getMilestoneByID: %v", err)
  681. }
  682. // Assume milestone is invalid and drop silently.
  683. opts.Issue.MilestoneID = 0
  684. if milestone != nil {
  685. opts.Issue.MilestoneID = milestone.ID
  686. opts.Issue.Milestone = milestone
  687. }
  688. }
  689. if opts.Issue.AssigneeID > 0 {
  690. assignee, err := getUserByID(e, opts.Issue.AssigneeID)
  691. if err != nil && !IsErrUserNotExist(err) {
  692. return fmt.Errorf("getUserByID: %v", err)
  693. }
  694. // Assume assignee is invalid and drop silently.
  695. opts.Issue.AssigneeID = 0
  696. if assignee != nil {
  697. valid, err := hasAccess(e, assignee, opts.Repo, AccessModeWrite)
  698. if err != nil {
  699. return fmt.Errorf("hasAccess [user_id: %d, repo_id: %d]: %v", assignee.ID, opts.Repo.ID, err)
  700. }
  701. if valid {
  702. opts.Issue.AssigneeID = assignee.ID
  703. opts.Issue.Assignee = assignee
  704. }
  705. }
  706. }
  707. // Milestone and assignee validation should happen before insert actual object.
  708. if _, err = e.Insert(opts.Issue); err != nil {
  709. return err
  710. }
  711. if opts.Issue.MilestoneID > 0 {
  712. if err = changeMilestoneAssign(e, doer, opts.Issue, -1); err != nil {
  713. return err
  714. }
  715. }
  716. if opts.Issue.AssigneeID > 0 {
  717. if err = opts.Issue.loadRepo(e); err != nil {
  718. return err
  719. }
  720. if _, err = createAssigneeComment(e, doer, opts.Issue.Repo, opts.Issue, -1, opts.Issue.AssigneeID); err != nil {
  721. return err
  722. }
  723. }
  724. if opts.IsPull {
  725. _, err = e.Exec("UPDATE `repository` SET num_pulls = num_pulls + 1 WHERE id = ?", opts.Issue.RepoID)
  726. } else {
  727. _, err = e.Exec("UPDATE `repository` SET num_issues = num_issues + 1 WHERE id = ?", opts.Issue.RepoID)
  728. }
  729. if err != nil {
  730. return err
  731. }
  732. if len(opts.LableIDs) > 0 {
  733. // During the session, SQLite3 driver cannot handle retrieve objects after update something.
  734. // So we have to get all needed labels first.
  735. labels := make([]*Label, 0, len(opts.LableIDs))
  736. if err = e.In("id", opts.LableIDs).Find(&labels); err != nil {
  737. return fmt.Errorf("find all labels [label_ids: %v]: %v", opts.LableIDs, err)
  738. }
  739. if err = opts.Issue.loadPoster(e); err != nil {
  740. return err
  741. }
  742. for _, label := range labels {
  743. // Silently drop invalid labels.
  744. if label.RepoID != opts.Repo.ID {
  745. continue
  746. }
  747. if err = opts.Issue.addLabel(e, label, opts.Issue.Poster); err != nil {
  748. return fmt.Errorf("addLabel [id: %d]: %v", label.ID, err)
  749. }
  750. }
  751. }
  752. if err = newIssueUsers(e, opts.Repo, opts.Issue); err != nil {
  753. return err
  754. }
  755. UpdateIssueIndexer(opts.Issue)
  756. if len(opts.Attachments) > 0 {
  757. attachments, err := getAttachmentsByUUIDs(e, opts.Attachments)
  758. if err != nil {
  759. return fmt.Errorf("getAttachmentsByUUIDs [uuids: %v]: %v", opts.Attachments, err)
  760. }
  761. for i := 0; i < len(attachments); i++ {
  762. attachments[i].IssueID = opts.Issue.ID
  763. if _, err = e.Id(attachments[i].ID).Update(attachments[i]); err != nil {
  764. return fmt.Errorf("update attachment [id: %d]: %v", attachments[i].ID, err)
  765. }
  766. }
  767. }
  768. return opts.Issue.loadAttributes(e)
  769. }
  770. // NewIssue creates new issue with labels for repository.
  771. func NewIssue(repo *Repository, issue *Issue, labelIDs []int64, uuids []string) (err error) {
  772. sess := x.NewSession()
  773. defer sessionRelease(sess)
  774. if err = sess.Begin(); err != nil {
  775. return err
  776. }
  777. if err = newIssue(sess, issue.Poster, NewIssueOptions{
  778. Repo: repo,
  779. Issue: issue,
  780. LableIDs: labelIDs,
  781. Attachments: uuids,
  782. }); err != nil {
  783. return fmt.Errorf("newIssue: %v", err)
  784. }
  785. if err = sess.Commit(); err != nil {
  786. return fmt.Errorf("Commit: %v", err)
  787. }
  788. if err = NotifyWatchers(&Action{
  789. ActUserID: issue.Poster.ID,
  790. ActUserName: issue.Poster.Name,
  791. OpType: ActionCreateIssue,
  792. Content: fmt.Sprintf("%d|%s", issue.Index, issue.Title),
  793. RepoID: repo.ID,
  794. RepoUserName: repo.Owner.Name,
  795. RepoName: repo.Name,
  796. IsPrivate: repo.IsPrivate,
  797. }); err != nil {
  798. log.Error(4, "NotifyWatchers: %v", err)
  799. }
  800. if err = issue.MailParticipants(); err != nil {
  801. log.Error(4, "MailParticipants: %v", err)
  802. }
  803. return nil
  804. }
  805. // GetIssueByRef returns an Issue specified by a GFM reference.
  806. // See https://help.github.com/articles/writing-on-github#references for more information on the syntax.
  807. func GetIssueByRef(ref string) (*Issue, error) {
  808. n := strings.IndexByte(ref, byte('#'))
  809. if n == -1 {
  810. return nil, errMissingIssueNumber
  811. }
  812. index, err := com.StrTo(ref[n+1:]).Int64()
  813. if err != nil {
  814. return nil, err
  815. }
  816. repo, err := GetRepositoryByRef(ref[:n])
  817. if err != nil {
  818. return nil, err
  819. }
  820. issue, err := GetIssueByIndex(repo.ID, index)
  821. if err != nil {
  822. return nil, err
  823. }
  824. return issue, issue.LoadAttributes()
  825. }
  826. // GetRawIssueByIndex returns raw issue without loading attributes by index in a repository.
  827. func GetRawIssueByIndex(repoID, index int64) (*Issue, error) {
  828. issue := &Issue{
  829. RepoID: repoID,
  830. Index: index,
  831. }
  832. has, err := x.Get(issue)
  833. if err != nil {
  834. return nil, err
  835. } else if !has {
  836. return nil, ErrIssueNotExist{0, repoID, index}
  837. }
  838. return issue, nil
  839. }
  840. // GetIssueByIndex returns issue by index in a repository.
  841. func GetIssueByIndex(repoID, index int64) (*Issue, error) {
  842. issue, err := GetRawIssueByIndex(repoID, index)
  843. if err != nil {
  844. return nil, err
  845. }
  846. return issue, issue.LoadAttributes()
  847. }
  848. func getIssueByID(e Engine, id int64) (*Issue, error) {
  849. issue := new(Issue)
  850. has, err := e.Id(id).Get(issue)
  851. if err != nil {
  852. return nil, err
  853. } else if !has {
  854. return nil, ErrIssueNotExist{id, 0, 0}
  855. }
  856. return issue, issue.LoadAttributes()
  857. }
  858. // GetIssueByID returns an issue by given ID.
  859. func GetIssueByID(id int64) (*Issue, error) {
  860. return getIssueByID(x, id)
  861. }
  862. // IssuesOptions represents options of an issue.
  863. type IssuesOptions struct {
  864. RepoID int64
  865. AssigneeID int64
  866. PosterID int64
  867. MentionedID int64
  868. MilestoneID int64
  869. RepoIDs []int64
  870. Page int
  871. IsClosed util.OptionalBool
  872. IsPull util.OptionalBool
  873. Labels string
  874. SortType string
  875. IssueIDs []int64
  876. }
  877. // sortIssuesSession sort an issues-related session based on the provided
  878. // sortType string
  879. func sortIssuesSession(sess *xorm.Session, sortType string) {
  880. switch sortType {
  881. case "oldest":
  882. sess.Asc("issue.created_unix")
  883. case "recentupdate":
  884. sess.Desc("issue.updated_unix")
  885. case "leastupdate":
  886. sess.Asc("issue.updated_unix")
  887. case "mostcomment":
  888. sess.Desc("issue.num_comments")
  889. case "leastcomment":
  890. sess.Asc("issue.num_comments")
  891. case "priority":
  892. sess.Desc("issue.priority")
  893. default:
  894. sess.Desc("issue.created_unix")
  895. }
  896. }
  897. // Issues returns a list of issues by given conditions.
  898. func Issues(opts *IssuesOptions) ([]*Issue, error) {
  899. var sess *xorm.Session
  900. if opts.Page >= 0 {
  901. var start int
  902. if opts.Page == 0 {
  903. start = 0
  904. } else {
  905. start = (opts.Page - 1) * setting.UI.IssuePagingNum
  906. }
  907. sess = x.Limit(setting.UI.IssuePagingNum, start)
  908. } else {
  909. sess = x.NewSession()
  910. defer sess.Close()
  911. }
  912. if len(opts.IssueIDs) > 0 {
  913. sess.In("issue.id", opts.IssueIDs)
  914. }
  915. if opts.RepoID > 0 {
  916. sess.And("issue.repo_id=?", opts.RepoID)
  917. } else if len(opts.RepoIDs) > 0 {
  918. // In case repository IDs are provided but actually no repository has issue.
  919. sess.In("issue.repo_id", opts.RepoIDs)
  920. }
  921. switch opts.IsClosed {
  922. case util.OptionalBoolTrue:
  923. sess.And("issue.is_closed=?", true)
  924. case util.OptionalBoolFalse:
  925. sess.And("issue.is_closed=?", false)
  926. }
  927. if opts.AssigneeID > 0 {
  928. sess.And("issue.assignee_id=?", opts.AssigneeID)
  929. }
  930. if opts.PosterID > 0 {
  931. sess.And("issue.poster_id=?", opts.PosterID)
  932. }
  933. if opts.MentionedID > 0 {
  934. sess.Join("INNER", "issue_user", "issue.id = issue_user.issue_id").
  935. And("issue_user.is_mentioned = ?", true).
  936. And("issue_user.uid = ?", opts.MentionedID)
  937. }
  938. if opts.MilestoneID > 0 {
  939. sess.And("issue.milestone_id=?", opts.MilestoneID)
  940. }
  941. switch opts.IsPull {
  942. case util.OptionalBoolTrue:
  943. sess.And("issue.is_pull=?", true)
  944. case util.OptionalBoolFalse:
  945. sess.And("issue.is_pull=?", false)
  946. }
  947. sortIssuesSession(sess, opts.SortType)
  948. if len(opts.Labels) > 0 && opts.Labels != "0" {
  949. labelIDs, err := base.StringsToInt64s(strings.Split(opts.Labels, ","))
  950. if err != nil {
  951. return nil, err
  952. }
  953. if len(labelIDs) > 0 {
  954. sess.
  955. Join("INNER", "issue_label", "issue.id = issue_label.issue_id").
  956. In("issue_label.label_id", labelIDs)
  957. }
  958. }
  959. issues := make([]*Issue, 0, setting.UI.IssuePagingNum)
  960. if err := sess.Find(&issues); err != nil {
  961. return nil, fmt.Errorf("Find: %v", err)
  962. }
  963. if err := IssueList(issues).LoadAttributes(); err != nil {
  964. return nil, fmt.Errorf("LoadAttributes: %v", err)
  965. }
  966. return issues, nil
  967. }
  968. // UpdateIssueMentions extracts mentioned people from content and
  969. // updates issue-user relations for them.
  970. func UpdateIssueMentions(e Engine, issueID int64, mentions []string) error {
  971. if len(mentions) == 0 {
  972. return nil
  973. }
  974. for i := range mentions {
  975. mentions[i] = strings.ToLower(mentions[i])
  976. }
  977. users := make([]*User, 0, len(mentions))
  978. if err := e.In("lower_name", mentions).Asc("lower_name").Find(&users); err != nil {
  979. return fmt.Errorf("find mentioned users: %v", err)
  980. }
  981. ids := make([]int64, 0, len(mentions))
  982. for _, user := range users {
  983. ids = append(ids, user.ID)
  984. if !user.IsOrganization() || user.NumMembers == 0 {
  985. continue
  986. }
  987. memberIDs := make([]int64, 0, user.NumMembers)
  988. orgUsers, err := GetOrgUsersByOrgID(user.ID)
  989. if err != nil {
  990. return fmt.Errorf("GetOrgUsersByOrgID [%d]: %v", user.ID, err)
  991. }
  992. for _, orgUser := range orgUsers {
  993. memberIDs = append(memberIDs, orgUser.ID)
  994. }
  995. ids = append(ids, memberIDs...)
  996. }
  997. if err := UpdateIssueUsersByMentions(e, issueID, ids); err != nil {
  998. return fmt.Errorf("UpdateIssueUsersByMentions: %v", err)
  999. }
  1000. return nil
  1001. }
  1002. // IssueStats represents issue statistic information.
  1003. type IssueStats struct {
  1004. OpenCount, ClosedCount int64
  1005. YourRepositoriesCount int64
  1006. AssignCount int64
  1007. CreateCount int64
  1008. MentionCount int64
  1009. }
  1010. // Filter modes.
  1011. const (
  1012. FilterModeAll = iota
  1013. FilterModeAssign
  1014. FilterModeCreate
  1015. FilterModeMention
  1016. )
  1017. func parseCountResult(results []map[string][]byte) int64 {
  1018. if len(results) == 0 {
  1019. return 0
  1020. }
  1021. for _, result := range results[0] {
  1022. return com.StrTo(string(result)).MustInt64()
  1023. }
  1024. return 0
  1025. }
  1026. // IssueStatsOptions contains parameters accepted by GetIssueStats.
  1027. type IssueStatsOptions struct {
  1028. FilterMode int
  1029. RepoID int64
  1030. Labels string
  1031. MilestoneID int64
  1032. AssigneeID int64
  1033. MentionedID int64
  1034. PosterID int64
  1035. IsPull bool
  1036. IssueIDs []int64
  1037. }
  1038. // GetIssueStats returns issue statistic information by given conditions.
  1039. func GetIssueStats(opts *IssueStatsOptions) (*IssueStats, error) {
  1040. stats := &IssueStats{}
  1041. countSession := func(opts *IssueStatsOptions) *xorm.Session {
  1042. sess := x.
  1043. Where("issue.repo_id = ?", opts.RepoID).
  1044. And("is_pull = ?", opts.IsPull)
  1045. if len(opts.IssueIDs) > 0 {
  1046. sess.In("issue.id", opts.IssueIDs)
  1047. }
  1048. if len(opts.Labels) > 0 && opts.Labels != "0" {
  1049. labelIDs, err := base.StringsToInt64s(strings.Split(opts.Labels, ","))
  1050. if err != nil {
  1051. log.Warn("Malformed Labels argument: %s", opts.Labels)
  1052. } else if len(labelIDs) > 0 {
  1053. sess.Join("INNER", "issue_label", "issue.id = issue_id").
  1054. In("label_id", labelIDs)
  1055. }
  1056. }
  1057. if opts.MilestoneID > 0 {
  1058. sess.And("issue.milestone_id = ?", opts.MilestoneID)
  1059. }
  1060. if opts.AssigneeID > 0 {
  1061. sess.And("assignee_id = ?", opts.AssigneeID)
  1062. }
  1063. if opts.PosterID > 0 {
  1064. sess.And("poster_id = ?", opts.PosterID)
  1065. }
  1066. if opts.MentionedID > 0 {
  1067. sess.Join("INNER", "issue_user", "issue.id = issue_user.issue_id").
  1068. And("issue_user.uid = ?", opts.MentionedID).
  1069. And("issue_user.is_mentioned = ?", true)
  1070. }
  1071. return sess
  1072. }
  1073. var err error
  1074. switch opts.FilterMode {
  1075. case FilterModeAll, FilterModeAssign:
  1076. stats.OpenCount, err = countSession(opts).
  1077. And("is_closed = ?", false).
  1078. Count(new(Issue))
  1079. stats.ClosedCount, err = countSession(opts).
  1080. And("is_closed = ?", true).
  1081. Count(new(Issue))
  1082. case FilterModeCreate:
  1083. stats.OpenCount, err = countSession(opts).
  1084. And("poster_id = ?", opts.PosterID).
  1085. And("is_closed = ?", false).
  1086. Count(new(Issue))
  1087. stats.ClosedCount, err = countSession(opts).
  1088. And("poster_id = ?", opts.PosterID).
  1089. And("is_closed = ?", true).
  1090. Count(new(Issue))
  1091. case FilterModeMention:
  1092. stats.OpenCount, err = countSession(opts).
  1093. Join("INNER", "issue_user", "issue.id = issue_user.issue_id").
  1094. And("issue_user.uid = ?", opts.PosterID).
  1095. And("issue_user.is_mentioned = ?", true).
  1096. And("issue.is_closed = ?", false).
  1097. Count(new(Issue))
  1098. stats.ClosedCount, err = countSession(opts).
  1099. Join("INNER", "issue_user", "issue.id = issue_user.issue_id").
  1100. And("issue_user.uid = ?", opts.PosterID).
  1101. And("issue_user.is_mentioned = ?", true).
  1102. And("issue.is_closed = ?", true).
  1103. Count(new(Issue))
  1104. }
  1105. return stats, err
  1106. }
  1107. // GetUserIssueStats returns issue statistic information for dashboard by given conditions.
  1108. func GetUserIssueStats(repoID, uid int64, repoIDs []int64, filterMode int, isPull bool) *IssueStats {
  1109. stats := &IssueStats{}
  1110. countSession := func(isClosed, isPull bool, repoID int64, repoIDs []int64) *xorm.Session {
  1111. sess := x.
  1112. Where("issue.is_closed = ?", isClosed).
  1113. And("issue.is_pull = ?", isPull)
  1114. if repoID > 0 {
  1115. sess.And("repo_id = ?", repoID)
  1116. } else if len(repoIDs) > 0 {
  1117. sess.In("repo_id", repoIDs)
  1118. }
  1119. return sess
  1120. }
  1121. stats.AssignCount, _ = countSession(false, isPull, repoID, nil).
  1122. And("assignee_id = ?", uid).
  1123. Count(new(Issue))
  1124. stats.CreateCount, _ = countSession(false, isPull, repoID, nil).
  1125. And("poster_id = ?", uid).
  1126. Count(new(Issue))
  1127. stats.YourRepositoriesCount, _ = countSession(false, isPull, repoID, repoIDs).
  1128. Count(new(Issue))
  1129. switch filterMode {
  1130. case FilterModeAll:
  1131. stats.OpenCount, _ = countSession(false, isPull, repoID, repoIDs).
  1132. Count(new(Issue))
  1133. stats.ClosedCount, _ = countSession(true, isPull, repoID, repoIDs).
  1134. Count(new(Issue))
  1135. case FilterModeAssign:
  1136. stats.OpenCount, _ = countSession(false, isPull, repoID, nil).
  1137. And("assignee_id = ?", uid).
  1138. Count(new(Issue))
  1139. stats.ClosedCount, _ = countSession(true, isPull, repoID, nil).
  1140. And("assignee_id = ?", uid).
  1141. Count(new(Issue))
  1142. case FilterModeCreate:
  1143. stats.OpenCount, _ = countSession(false, isPull, repoID, nil).
  1144. And("poster_id = ?", uid).
  1145. Count(new(Issue))
  1146. stats.ClosedCount, _ = countSession(true, isPull, repoID, nil).
  1147. And("poster_id = ?", uid).
  1148. Count(new(Issue))
  1149. }
  1150. return stats
  1151. }
  1152. // GetRepoIssueStats returns number of open and closed repository issues by given filter mode.
  1153. func GetRepoIssueStats(repoID, uid int64, filterMode int, isPull bool) (numOpen int64, numClosed int64) {
  1154. countSession := func(isClosed, isPull bool, repoID int64) *xorm.Session {
  1155. sess := x.
  1156. Where("is_closed = ?", isClosed).
  1157. And("is_pull = ?", isPull).
  1158. And("repo_id = ?", repoID)
  1159. return sess
  1160. }
  1161. openCountSession := countSession(false, isPull, repoID)
  1162. closedCountSession := countSession(true, isPull, repoID)
  1163. switch filterMode {
  1164. case FilterModeAssign:
  1165. openCountSession.And("assignee_id = ?", uid)
  1166. closedCountSession.And("assignee_id = ?", uid)
  1167. case FilterModeCreate:
  1168. openCountSession.And("poster_id = ?", uid)
  1169. closedCountSession.And("poster_id = ?", uid)
  1170. }
  1171. openResult, _ := openCountSession.Count(new(Issue))
  1172. closedResult, _ := closedCountSession.Count(new(Issue))
  1173. return openResult, closedResult
  1174. }
  1175. func updateIssue(e Engine, issue *Issue) error {
  1176. _, err := e.Id(issue.ID).AllCols().Update(issue)
  1177. if err != nil {
  1178. return err
  1179. }
  1180. UpdateIssueIndexer(issue)
  1181. return nil
  1182. }
  1183. // UpdateIssue updates all fields of given issue.
  1184. func UpdateIssue(issue *Issue) error {
  1185. return updateIssue(x, issue)
  1186. }