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

issue.go 38 kB

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