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