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

issue.go 37KB

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