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