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
8 years ago
11 years ago
11 years ago
11 years ago
9 years ago
8 years ago
8 years ago
8 years ago
8 years ago
8 years ago
8 years ago
8 years ago
11 years ago
8 years ago
11 years ago
8 years ago
8 years ago
8 years ago
8 years ago
8 years ago
8 years ago
8 years ago
8 years ago
8 years ago
8 years ago
8 years ago
8 years ago
8 years ago
11 years ago
11 years ago
11 years ago
11 years ago
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449
  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, byte('#'))
  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. repo, err := GetRepositoryByRef(ref[:n])
  839. if err != nil {
  840. return nil, err
  841. }
  842. return GetIssueByIndex(repo.ID, index)
  843. }
  844. // GetRawIssueByIndex returns raw issue without loading attributes by index in a repository.
  845. func GetRawIssueByIndex(repoID, index int64) (*Issue, error) {
  846. issue := &Issue{
  847. RepoID: repoID,
  848. Index: index,
  849. }
  850. has, err := x.Get(issue)
  851. if err != nil {
  852. return nil, err
  853. } else if !has {
  854. return nil, ErrIssueNotExist{0, repoID, index}
  855. }
  856. return issue, nil
  857. }
  858. // GetIssueByIndex returns issue by index in a repository.
  859. func GetIssueByIndex(repoID, index int64) (*Issue, error) {
  860. issue, err := GetRawIssueByIndex(repoID, index)
  861. if err != nil {
  862. return nil, err
  863. }
  864. return issue, issue.LoadAttributes()
  865. }
  866. func getIssueByID(e Engine, id int64) (*Issue, error) {
  867. issue := new(Issue)
  868. has, err := e.ID(id).Get(issue)
  869. if err != nil {
  870. return nil, err
  871. } else if !has {
  872. return nil, ErrIssueNotExist{id, 0, 0}
  873. }
  874. return issue, issue.loadAttributes(e)
  875. }
  876. // GetIssueByID returns an issue by given ID.
  877. func GetIssueByID(id int64) (*Issue, error) {
  878. return getIssueByID(x, id)
  879. }
  880. func getIssuesByIDs(e Engine, issueIDs []int64) ([]*Issue, error) {
  881. issues := make([]*Issue, 0, 10)
  882. return issues, e.In("id", issueIDs).Find(&issues)
  883. }
  884. // GetIssuesByIDs return issues with the given IDs.
  885. func GetIssuesByIDs(issueIDs []int64) ([]*Issue, error) {
  886. return getIssuesByIDs(x, issueIDs)
  887. }
  888. // IssuesOptions represents options of an issue.
  889. type IssuesOptions struct {
  890. RepoID int64
  891. AssigneeID int64
  892. PosterID int64
  893. MentionedID int64
  894. MilestoneID int64
  895. RepoIDs []int64
  896. Page int
  897. PageSize int
  898. IsClosed util.OptionalBool
  899. IsPull util.OptionalBool
  900. Labels string
  901. SortType string
  902. IssueIDs []int64
  903. }
  904. // sortIssuesSession sort an issues-related session based on the provided
  905. // sortType string
  906. func sortIssuesSession(sess *xorm.Session, sortType string) {
  907. switch sortType {
  908. case "oldest":
  909. sess.Asc("issue.created_unix")
  910. case "recentupdate":
  911. sess.Desc("issue.updated_unix")
  912. case "leastupdate":
  913. sess.Asc("issue.updated_unix")
  914. case "mostcomment":
  915. sess.Desc("issue.num_comments")
  916. case "leastcomment":
  917. sess.Asc("issue.num_comments")
  918. case "priority":
  919. sess.Desc("issue.priority")
  920. default:
  921. sess.Desc("issue.created_unix")
  922. }
  923. }
  924. func (opts *IssuesOptions) setupSession(sess *xorm.Session) error {
  925. if opts.Page >= 0 && opts.PageSize > 0 {
  926. var start int
  927. if opts.Page == 0 {
  928. start = 0
  929. } else {
  930. start = (opts.Page - 1) * opts.PageSize
  931. }
  932. sess.Limit(opts.PageSize, start)
  933. }
  934. if len(opts.IssueIDs) > 0 {
  935. sess.In("issue.id", opts.IssueIDs)
  936. }
  937. if opts.RepoID > 0 {
  938. sess.And("issue.repo_id=?", opts.RepoID)
  939. } else if len(opts.RepoIDs) > 0 {
  940. // In case repository IDs are provided but actually no repository has issue.
  941. sess.In("issue.repo_id", opts.RepoIDs)
  942. }
  943. switch opts.IsClosed {
  944. case util.OptionalBoolTrue:
  945. sess.And("issue.is_closed=?", true)
  946. case util.OptionalBoolFalse:
  947. sess.And("issue.is_closed=?", false)
  948. }
  949. if opts.AssigneeID > 0 {
  950. sess.And("issue.assignee_id=?", opts.AssigneeID)
  951. }
  952. if opts.PosterID > 0 {
  953. sess.And("issue.poster_id=?", opts.PosterID)
  954. }
  955. if opts.MentionedID > 0 {
  956. sess.Join("INNER", "issue_user", "issue.id = issue_user.issue_id").
  957. And("issue_user.is_mentioned = ?", true).
  958. And("issue_user.uid = ?", opts.MentionedID)
  959. }
  960. if opts.MilestoneID > 0 {
  961. sess.And("issue.milestone_id=?", opts.MilestoneID)
  962. }
  963. switch opts.IsPull {
  964. case util.OptionalBoolTrue:
  965. sess.And("issue.is_pull=?", true)
  966. case util.OptionalBoolFalse:
  967. sess.And("issue.is_pull=?", false)
  968. }
  969. if len(opts.Labels) > 0 && opts.Labels != "0" {
  970. labelIDs, err := base.StringsToInt64s(strings.Split(opts.Labels, ","))
  971. if err != nil {
  972. return err
  973. }
  974. if len(labelIDs) > 0 {
  975. sess.
  976. Join("INNER", "issue_label", "issue.id = issue_label.issue_id").
  977. In("issue_label.label_id", labelIDs)
  978. }
  979. }
  980. return nil
  981. }
  982. // CountIssuesByRepo map from repoID to number of issues matching the options
  983. func CountIssuesByRepo(opts *IssuesOptions) (map[int64]int64, error) {
  984. sess := x.NewSession()
  985. defer sess.Close()
  986. if err := opts.setupSession(sess); err != nil {
  987. return nil, err
  988. }
  989. countsSlice := make([]*struct {
  990. RepoID int64
  991. Count int64
  992. }, 0, 10)
  993. if err := sess.GroupBy("issue.repo_id").
  994. Select("issue.repo_id AS repo_id, COUNT(*) AS count").
  995. Table("issue").
  996. Find(&countsSlice); err != nil {
  997. return nil, err
  998. }
  999. countMap := make(map[int64]int64, len(countsSlice))
  1000. for _, c := range countsSlice {
  1001. countMap[c.RepoID] = c.Count
  1002. }
  1003. return countMap, nil
  1004. }
  1005. // Issues returns a list of issues by given conditions.
  1006. func Issues(opts *IssuesOptions) ([]*Issue, error) {
  1007. sess := x.NewSession()
  1008. defer sess.Close()
  1009. if err := opts.setupSession(sess); err != nil {
  1010. return nil, err
  1011. }
  1012. sortIssuesSession(sess, opts.SortType)
  1013. issues := make([]*Issue, 0, setting.UI.IssuePagingNum)
  1014. if err := sess.Find(&issues); err != nil {
  1015. return nil, fmt.Errorf("Find: %v", err)
  1016. }
  1017. if err := IssueList(issues).LoadAttributes(); err != nil {
  1018. return nil, fmt.Errorf("LoadAttributes: %v", err)
  1019. }
  1020. return issues, nil
  1021. }
  1022. // GetParticipantsByIssueID returns all users who are participated in comments of an issue.
  1023. func GetParticipantsByIssueID(issueID int64) ([]*User, error) {
  1024. return getParticipantsByIssueID(x, issueID)
  1025. }
  1026. func getParticipantsByIssueID(e Engine, issueID int64) ([]*User, error) {
  1027. userIDs := make([]int64, 0, 5)
  1028. if err := e.Table("comment").Cols("poster_id").
  1029. Where("`comment`.issue_id = ?", issueID).
  1030. And("`comment`.type = ?", CommentTypeComment).
  1031. And("`user`.is_active = ?", true).
  1032. And("`user`.prohibit_login = ?", false).
  1033. Join("INNER", "user", "`user`.id = `comment`.poster_id").
  1034. Distinct("poster_id").
  1035. Find(&userIDs); err != nil {
  1036. return nil, fmt.Errorf("get poster IDs: %v", err)
  1037. }
  1038. if len(userIDs) == 0 {
  1039. return nil, nil
  1040. }
  1041. users := make([]*User, 0, len(userIDs))
  1042. return users, e.In("id", userIDs).Find(&users)
  1043. }
  1044. // UpdateIssueMentions extracts mentioned people from content and
  1045. // updates issue-user relations for them.
  1046. func UpdateIssueMentions(e Engine, issueID int64, mentions []string) error {
  1047. if len(mentions) == 0 {
  1048. return nil
  1049. }
  1050. for i := range mentions {
  1051. mentions[i] = strings.ToLower(mentions[i])
  1052. }
  1053. users := make([]*User, 0, len(mentions))
  1054. if err := e.In("lower_name", mentions).Asc("lower_name").Find(&users); err != nil {
  1055. return fmt.Errorf("find mentioned users: %v", err)
  1056. }
  1057. ids := make([]int64, 0, len(mentions))
  1058. for _, user := range users {
  1059. ids = append(ids, user.ID)
  1060. if !user.IsOrganization() || user.NumMembers == 0 {
  1061. continue
  1062. }
  1063. memberIDs := make([]int64, 0, user.NumMembers)
  1064. orgUsers, err := GetOrgUsersByOrgID(user.ID)
  1065. if err != nil {
  1066. return fmt.Errorf("GetOrgUsersByOrgID [%d]: %v", user.ID, err)
  1067. }
  1068. for _, orgUser := range orgUsers {
  1069. memberIDs = append(memberIDs, orgUser.ID)
  1070. }
  1071. ids = append(ids, memberIDs...)
  1072. }
  1073. if err := UpdateIssueUsersByMentions(e, issueID, ids); err != nil {
  1074. return fmt.Errorf("UpdateIssueUsersByMentions: %v", err)
  1075. }
  1076. return nil
  1077. }
  1078. // IssueStats represents issue statistic information.
  1079. type IssueStats struct {
  1080. OpenCount, ClosedCount int64
  1081. YourRepositoriesCount int64
  1082. AssignCount int64
  1083. CreateCount int64
  1084. MentionCount int64
  1085. }
  1086. // Filter modes.
  1087. const (
  1088. FilterModeAll = iota
  1089. FilterModeAssign
  1090. FilterModeCreate
  1091. FilterModeMention
  1092. )
  1093. func parseCountResult(results []map[string][]byte) int64 {
  1094. if len(results) == 0 {
  1095. return 0
  1096. }
  1097. for _, result := range results[0] {
  1098. return com.StrTo(string(result)).MustInt64()
  1099. }
  1100. return 0
  1101. }
  1102. // IssueStatsOptions contains parameters accepted by GetIssueStats.
  1103. type IssueStatsOptions struct {
  1104. RepoID int64
  1105. Labels string
  1106. MilestoneID int64
  1107. AssigneeID int64
  1108. MentionedID int64
  1109. PosterID int64
  1110. IsPull bool
  1111. IssueIDs []int64
  1112. }
  1113. // GetIssueStats returns issue statistic information by given conditions.
  1114. func GetIssueStats(opts *IssueStatsOptions) (*IssueStats, error) {
  1115. stats := &IssueStats{}
  1116. countSession := func(opts *IssueStatsOptions) *xorm.Session {
  1117. sess := x.
  1118. Where("issue.repo_id = ?", opts.RepoID).
  1119. And("issue.is_pull = ?", opts.IsPull)
  1120. if len(opts.IssueIDs) > 0 {
  1121. sess.In("issue.id", opts.IssueIDs)
  1122. }
  1123. if len(opts.Labels) > 0 && opts.Labels != "0" {
  1124. labelIDs, err := base.StringsToInt64s(strings.Split(opts.Labels, ","))
  1125. if err != nil {
  1126. log.Warn("Malformed Labels argument: %s", opts.Labels)
  1127. } else if len(labelIDs) > 0 {
  1128. sess.Join("INNER", "issue_label", "issue.id = issue_label.issue_id").
  1129. In("issue_label.label_id", labelIDs)
  1130. }
  1131. }
  1132. if opts.MilestoneID > 0 {
  1133. sess.And("issue.milestone_id = ?", opts.MilestoneID)
  1134. }
  1135. if opts.AssigneeID > 0 {
  1136. sess.And("issue.assignee_id = ?", opts.AssigneeID)
  1137. }
  1138. if opts.PosterID > 0 {
  1139. sess.And("issue.poster_id = ?", opts.PosterID)
  1140. }
  1141. if opts.MentionedID > 0 {
  1142. sess.Join("INNER", "issue_user", "issue.id = issue_user.issue_id").
  1143. And("issue_user.uid = ?", opts.MentionedID).
  1144. And("issue_user.is_mentioned = ?", true)
  1145. }
  1146. return sess
  1147. }
  1148. var err error
  1149. stats.OpenCount, err = countSession(opts).
  1150. And("issue.is_closed = ?", false).
  1151. Count(new(Issue))
  1152. if err != nil {
  1153. return stats, err
  1154. }
  1155. stats.ClosedCount, err = countSession(opts).
  1156. And("issue.is_closed = ?", true).
  1157. Count(new(Issue))
  1158. return stats, err
  1159. }
  1160. // GetUserIssueStats returns issue statistic information for dashboard by given conditions.
  1161. func GetUserIssueStats(repoID, uid int64, repoIDs []int64, filterMode int, isPull bool) *IssueStats {
  1162. stats := &IssueStats{}
  1163. countSession := func(isClosed, isPull bool, repoID int64, repoIDs []int64) *xorm.Session {
  1164. sess := x.
  1165. Where("issue.is_closed = ?", isClosed).
  1166. And("issue.is_pull = ?", isPull)
  1167. if repoID > 0 {
  1168. sess.And("repo_id = ?", repoID)
  1169. } else if len(repoIDs) > 0 {
  1170. sess.In("repo_id", repoIDs)
  1171. }
  1172. return sess
  1173. }
  1174. stats.AssignCount, _ = countSession(false, isPull, repoID, nil).
  1175. And("assignee_id = ?", uid).
  1176. Count(new(Issue))
  1177. stats.CreateCount, _ = countSession(false, isPull, repoID, nil).
  1178. And("poster_id = ?", uid).
  1179. Count(new(Issue))
  1180. stats.YourRepositoriesCount, _ = countSession(false, isPull, repoID, repoIDs).
  1181. Count(new(Issue))
  1182. switch filterMode {
  1183. case FilterModeAll:
  1184. stats.OpenCount, _ = countSession(false, isPull, repoID, repoIDs).
  1185. Count(new(Issue))
  1186. stats.ClosedCount, _ = countSession(true, isPull, repoID, repoIDs).
  1187. Count(new(Issue))
  1188. case FilterModeAssign:
  1189. stats.OpenCount, _ = countSession(false, isPull, repoID, nil).
  1190. And("assignee_id = ?", uid).
  1191. Count(new(Issue))
  1192. stats.ClosedCount, _ = countSession(true, isPull, repoID, nil).
  1193. And("assignee_id = ?", uid).
  1194. Count(new(Issue))
  1195. case FilterModeCreate:
  1196. stats.OpenCount, _ = countSession(false, isPull, repoID, nil).
  1197. And("poster_id = ?", uid).
  1198. Count(new(Issue))
  1199. stats.ClosedCount, _ = countSession(true, isPull, repoID, nil).
  1200. And("poster_id = ?", uid).
  1201. Count(new(Issue))
  1202. }
  1203. return stats
  1204. }
  1205. // GetRepoIssueStats returns number of open and closed repository issues by given filter mode.
  1206. func GetRepoIssueStats(repoID, uid int64, filterMode int, isPull bool) (numOpen int64, numClosed int64) {
  1207. countSession := func(isClosed, isPull bool, repoID int64) *xorm.Session {
  1208. sess := x.
  1209. Where("is_closed = ?", isClosed).
  1210. And("is_pull = ?", isPull).
  1211. And("repo_id = ?", repoID)
  1212. return sess
  1213. }
  1214. openCountSession := countSession(false, isPull, repoID)
  1215. closedCountSession := countSession(true, isPull, repoID)
  1216. switch filterMode {
  1217. case FilterModeAssign:
  1218. openCountSession.And("assignee_id = ?", uid)
  1219. closedCountSession.And("assignee_id = ?", uid)
  1220. case FilterModeCreate:
  1221. openCountSession.And("poster_id = ?", uid)
  1222. closedCountSession.And("poster_id = ?", uid)
  1223. }
  1224. openResult, _ := openCountSession.Count(new(Issue))
  1225. closedResult, _ := closedCountSession.Count(new(Issue))
  1226. return openResult, closedResult
  1227. }
  1228. func updateIssue(e Engine, issue *Issue) error {
  1229. _, err := e.ID(issue.ID).AllCols().Update(issue)
  1230. if err != nil {
  1231. return err
  1232. }
  1233. UpdateIssueIndexer(issue.ID)
  1234. return nil
  1235. }
  1236. // UpdateIssue updates all fields of given issue.
  1237. func UpdateIssue(issue *Issue) error {
  1238. return updateIssue(x, issue)
  1239. }