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