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 47 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
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
9 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
9 years ago
9 years ago
10 years ago
11 years ago
11 years ago
11 years ago
11 years ago
9 years ago
10 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792
  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. "strings"
  9. "time"
  10. api "code.gitea.io/sdk/gitea"
  11. "github.com/Unknwon/com"
  12. "github.com/go-xorm/xorm"
  13. "code.gitea.io/gitea/modules/base"
  14. "code.gitea.io/gitea/modules/log"
  15. "code.gitea.io/gitea/modules/setting"
  16. "code.gitea.io/gitea/modules/util"
  17. )
  18. var (
  19. errMissingIssueNumber = errors.New("No issue number specified")
  20. )
  21. // Issue represents an issue or pull request of repository.
  22. type Issue struct {
  23. ID int64 `xorm:"pk autoincr"`
  24. RepoID int64 `xorm:"INDEX UNIQUE(repo_index)"`
  25. Repo *Repository `xorm:"-"`
  26. Index int64 `xorm:"UNIQUE(repo_index)"` // Index in one repository.
  27. PosterID int64 `xorm:"INDEX"`
  28. Poster *User `xorm:"-"`
  29. Title string `xorm:"name"`
  30. Content string `xorm:"TEXT"`
  31. RenderedContent string `xorm:"-"`
  32. Labels []*Label `xorm:"-"`
  33. MilestoneID int64 `xorm:"INDEX"`
  34. Milestone *Milestone `xorm:"-"`
  35. Priority int
  36. AssigneeID int64 `xorm:"INDEX"`
  37. Assignee *User `xorm:"-"`
  38. IsClosed bool `xorm:"INDEX"`
  39. IsRead bool `xorm:"-"`
  40. IsPull bool `xorm:"INDEX"` // Indicates whether is a pull request or not.
  41. PullRequest *PullRequest `xorm:"-"`
  42. NumComments int
  43. Deadline time.Time `xorm:"-"`
  44. DeadlineUnix int64 `xorm:"INDEX"`
  45. Created time.Time `xorm:"-"`
  46. CreatedUnix int64 `xorm:"INDEX"`
  47. Updated time.Time `xorm:"-"`
  48. UpdatedUnix int64 `xorm:"INDEX"`
  49. Attachments []*Attachment `xorm:"-"`
  50. Comments []*Comment `xorm:"-"`
  51. }
  52. // BeforeInsert is invoked from XORM before inserting an object of this type.
  53. func (issue *Issue) BeforeInsert() {
  54. issue.CreatedUnix = time.Now().Unix()
  55. issue.UpdatedUnix = issue.CreatedUnix
  56. }
  57. // BeforeUpdate is invoked from XORM before updating this object.
  58. func (issue *Issue) BeforeUpdate() {
  59. issue.UpdatedUnix = time.Now().Unix()
  60. issue.DeadlineUnix = issue.Deadline.Unix()
  61. }
  62. // AfterSet is invoked from XORM after setting the value of a field of
  63. // this object.
  64. func (issue *Issue) AfterSet(colName string, _ xorm.Cell) {
  65. switch colName {
  66. case "deadline_unix":
  67. issue.Deadline = time.Unix(issue.DeadlineUnix, 0).Local()
  68. case "created_unix":
  69. issue.Created = time.Unix(issue.CreatedUnix, 0).Local()
  70. case "updated_unix":
  71. issue.Updated = time.Unix(issue.UpdatedUnix, 0).Local()
  72. }
  73. }
  74. func (issue *Issue) loadRepo(e Engine) (err error) {
  75. if issue.Repo == nil {
  76. issue.Repo, err = getRepositoryByID(e, issue.RepoID)
  77. if err != nil {
  78. return fmt.Errorf("getRepositoryByID [%d]: %v", issue.RepoID, err)
  79. }
  80. }
  81. return nil
  82. }
  83. // GetPullRequest returns the issue pull request
  84. func (issue *Issue) GetPullRequest() (pr *PullRequest, err error) {
  85. if !issue.IsPull {
  86. return nil, fmt.Errorf("Issue is not a pull request")
  87. }
  88. pr, err = getPullRequestByIssueID(x, issue.ID)
  89. return
  90. }
  91. func (issue *Issue) loadAttributes(e Engine) (err error) {
  92. if err := issue.loadRepo(e); err != nil {
  93. return err
  94. }
  95. if issue.Poster == nil {
  96. issue.Poster, err = getUserByID(e, issue.PosterID)
  97. if err != nil {
  98. issue.PosterID = -1
  99. issue.Poster = NewGhostUser()
  100. if !IsErrUserNotExist(err) {
  101. return fmt.Errorf("getUserByID.(poster) [%d]: %v", issue.PosterID, err)
  102. }
  103. err = nil
  104. return
  105. }
  106. }
  107. if issue.Labels == nil {
  108. issue.Labels, err = getLabelsByIssueID(e, issue.ID)
  109. if err != nil {
  110. return fmt.Errorf("getLabelsByIssueID [%d]: %v", issue.ID, err)
  111. }
  112. }
  113. if issue.Milestone == nil && issue.MilestoneID > 0 {
  114. issue.Milestone, err = getMilestoneByRepoID(e, issue.RepoID, issue.MilestoneID)
  115. if err != nil {
  116. return fmt.Errorf("getMilestoneByRepoID [repo_id: %d, milestone_id: %d]: %v", issue.RepoID, issue.MilestoneID, err)
  117. }
  118. }
  119. if issue.Assignee == nil && issue.AssigneeID > 0 {
  120. issue.Assignee, err = getUserByID(e, issue.AssigneeID)
  121. if err != nil {
  122. return fmt.Errorf("getUserByID.(assignee) [%d]: %v", issue.AssigneeID, err)
  123. }
  124. }
  125. if issue.IsPull && issue.PullRequest == nil {
  126. // It is possible pull request is not yet created.
  127. issue.PullRequest, err = getPullRequestByIssueID(e, issue.ID)
  128. if err != nil && !IsErrPullRequestNotExist(err) {
  129. return fmt.Errorf("getPullRequestByIssueID [%d]: %v", issue.ID, err)
  130. }
  131. }
  132. if issue.Attachments == nil {
  133. issue.Attachments, err = getAttachmentsByIssueID(e, issue.ID)
  134. if err != nil {
  135. return fmt.Errorf("getAttachmentsByIssueID [%d]: %v", issue.ID, err)
  136. }
  137. }
  138. if issue.Comments == nil {
  139. issue.Comments, err = getCommentsByIssueID(e, issue.ID)
  140. if err != nil {
  141. return fmt.Errorf("getCommentsByIssueID [%d]: %v", issue.ID, err)
  142. }
  143. }
  144. return nil
  145. }
  146. // LoadAttributes loads the attribute of this issue.
  147. func (issue *Issue) LoadAttributes() error {
  148. return issue.loadAttributes(x)
  149. }
  150. // HTMLURL returns the absolute URL to this issue.
  151. func (issue *Issue) HTMLURL() string {
  152. var path string
  153. if issue.IsPull {
  154. path = "pulls"
  155. } else {
  156. path = "issues"
  157. }
  158. return fmt.Sprintf("%s/%s/%d", issue.Repo.HTMLURL(), path, issue.Index)
  159. }
  160. // DiffURL returns the absolute URL to this diff
  161. func (issue *Issue) DiffURL() string {
  162. if issue.IsPull {
  163. return fmt.Sprintf("%s/pulls/%d.diff", issue.Repo.HTMLURL(), issue.Index)
  164. }
  165. return ""
  166. }
  167. // PatchURL returns the absolute URL to this patch
  168. func (issue *Issue) PatchURL() string {
  169. if issue.IsPull {
  170. return fmt.Sprintf("%s/pulls/%d.patch", issue.Repo.HTMLURL(), issue.Index)
  171. }
  172. return ""
  173. }
  174. // State returns string representation of issue status.
  175. func (issue *Issue) State() api.StateType {
  176. if issue.IsClosed {
  177. return api.StateClosed
  178. }
  179. return api.StateOpen
  180. }
  181. // APIFormat assumes some fields assigned with values:
  182. // Required - Poster, Labels,
  183. // Optional - Milestone, Assignee, PullRequest
  184. func (issue *Issue) APIFormat() *api.Issue {
  185. apiLabels := make([]*api.Label, len(issue.Labels))
  186. for i := range issue.Labels {
  187. apiLabels[i] = issue.Labels[i].APIFormat()
  188. }
  189. apiIssue := &api.Issue{
  190. ID: issue.ID,
  191. Index: issue.Index,
  192. Poster: issue.Poster.APIFormat(),
  193. Title: issue.Title,
  194. Body: issue.Content,
  195. Labels: apiLabels,
  196. State: issue.State(),
  197. Comments: issue.NumComments,
  198. Created: issue.Created,
  199. Updated: issue.Updated,
  200. }
  201. if issue.Milestone != nil {
  202. apiIssue.Milestone = issue.Milestone.APIFormat()
  203. }
  204. if issue.Assignee != nil {
  205. apiIssue.Assignee = issue.Assignee.APIFormat()
  206. }
  207. if issue.IsPull {
  208. apiIssue.PullRequest = &api.PullRequestMeta{
  209. HasMerged: issue.PullRequest.HasMerged,
  210. }
  211. if issue.PullRequest.HasMerged {
  212. apiIssue.PullRequest.Merged = &issue.PullRequest.Merged
  213. }
  214. }
  215. return apiIssue
  216. }
  217. // HashTag returns unique hash tag for issue.
  218. func (issue *Issue) HashTag() string {
  219. return "issue-" + com.ToStr(issue.ID)
  220. }
  221. // IsPoster returns true if given user by ID is the poster.
  222. func (issue *Issue) IsPoster(uid int64) bool {
  223. return issue.PosterID == uid
  224. }
  225. func (issue *Issue) hasLabel(e Engine, labelID int64) bool {
  226. return hasIssueLabel(e, issue.ID, labelID)
  227. }
  228. // HasLabel returns true if issue has been labeled by given ID.
  229. func (issue *Issue) HasLabel(labelID int64) bool {
  230. return issue.hasLabel(x, labelID)
  231. }
  232. func (issue *Issue) sendLabelUpdatedWebhook(doer *User) {
  233. var err error
  234. if issue.IsPull {
  235. err = issue.PullRequest.LoadIssue()
  236. if err != nil {
  237. log.Error(4, "LoadIssue: %v", err)
  238. return
  239. }
  240. err = PrepareWebhooks(issue.Repo, HookEventPullRequest, &api.PullRequestPayload{
  241. Action: api.HookIssueLabelUpdated,
  242. Index: issue.Index,
  243. PullRequest: issue.PullRequest.APIFormat(),
  244. Repository: issue.Repo.APIFormat(AccessModeNone),
  245. Sender: doer.APIFormat(),
  246. })
  247. }
  248. if err != nil {
  249. log.Error(4, "PrepareWebhooks [is_pull: %v]: %v", issue.IsPull, err)
  250. } else {
  251. go HookQueue.Add(issue.RepoID)
  252. }
  253. }
  254. func (issue *Issue) addLabel(e *xorm.Session, label *Label) error {
  255. return newIssueLabel(e, issue, label)
  256. }
  257. // AddLabel adds a new label to the issue.
  258. func (issue *Issue) AddLabel(doer *User, label *Label) error {
  259. if err := NewIssueLabel(issue, label); err != nil {
  260. return err
  261. }
  262. issue.sendLabelUpdatedWebhook(doer)
  263. return nil
  264. }
  265. func (issue *Issue) addLabels(e *xorm.Session, labels []*Label) error {
  266. return newIssueLabels(e, issue, labels)
  267. }
  268. // AddLabels adds a list of new labels to the issue.
  269. func (issue *Issue) AddLabels(doer *User, labels []*Label) error {
  270. if err := NewIssueLabels(issue, labels); err != nil {
  271. return err
  272. }
  273. issue.sendLabelUpdatedWebhook(doer)
  274. return nil
  275. }
  276. func (issue *Issue) getLabels(e Engine) (err error) {
  277. if len(issue.Labels) > 0 {
  278. return nil
  279. }
  280. issue.Labels, err = getLabelsByIssueID(e, issue.ID)
  281. if err != nil {
  282. return fmt.Errorf("getLabelsByIssueID: %v", err)
  283. }
  284. return nil
  285. }
  286. func (issue *Issue) removeLabel(e *xorm.Session, label *Label) error {
  287. return deleteIssueLabel(e, issue, label)
  288. }
  289. // RemoveLabel removes a label from issue by given ID.
  290. func (issue *Issue) RemoveLabel(doer *User, label *Label) error {
  291. if err := issue.loadRepo(x); err != nil {
  292. return err
  293. }
  294. if has, err := HasAccess(doer, issue.Repo, AccessModeWrite); err != nil {
  295. return err
  296. } else if !has {
  297. return ErrLabelNotExist{}
  298. }
  299. if err := DeleteIssueLabel(issue, label); err != nil {
  300. return err
  301. }
  302. issue.sendLabelUpdatedWebhook(doer)
  303. return nil
  304. }
  305. func (issue *Issue) clearLabels(e *xorm.Session) (err error) {
  306. if err = issue.getLabels(e); err != nil {
  307. return fmt.Errorf("getLabels: %v", err)
  308. }
  309. for i := range issue.Labels {
  310. if err = issue.removeLabel(e, issue.Labels[i]); err != nil {
  311. return fmt.Errorf("removeLabel: %v", err)
  312. }
  313. }
  314. return nil
  315. }
  316. // ClearLabels removes all issue labels as the given user.
  317. // Triggers appropriate WebHooks, if any.
  318. func (issue *Issue) ClearLabels(doer *User) (err error) {
  319. sess := x.NewSession()
  320. defer sessionRelease(sess)
  321. if err = sess.Begin(); err != nil {
  322. return err
  323. }
  324. if err := issue.loadRepo(sess); err != nil {
  325. return err
  326. }
  327. if has, err := hasAccess(sess, doer, issue.Repo, AccessModeWrite); err != nil {
  328. return err
  329. } else if !has {
  330. return ErrLabelNotExist{}
  331. }
  332. if err = issue.clearLabels(sess); err != nil {
  333. return err
  334. }
  335. if err = sess.Commit(); err != nil {
  336. return fmt.Errorf("Commit: %v", err)
  337. }
  338. if issue.IsPull {
  339. err = issue.PullRequest.LoadIssue()
  340. if err != nil {
  341. log.Error(4, "LoadIssue: %v", err)
  342. return
  343. }
  344. err = PrepareWebhooks(issue.Repo, HookEventPullRequest, &api.PullRequestPayload{
  345. Action: api.HookIssueLabelCleared,
  346. Index: issue.Index,
  347. PullRequest: issue.PullRequest.APIFormat(),
  348. Repository: issue.Repo.APIFormat(AccessModeNone),
  349. Sender: doer.APIFormat(),
  350. })
  351. }
  352. if err != nil {
  353. log.Error(4, "PrepareWebhooks [is_pull: %v]: %v", issue.IsPull, err)
  354. } else {
  355. go HookQueue.Add(issue.RepoID)
  356. }
  357. return nil
  358. }
  359. // ReplaceLabels removes all current labels and add new labels to the issue.
  360. // Triggers appropriate WebHooks, if any.
  361. func (issue *Issue) ReplaceLabels(labels []*Label) (err error) {
  362. sess := x.NewSession()
  363. defer sessionRelease(sess)
  364. if err = sess.Begin(); err != nil {
  365. return err
  366. }
  367. if err = issue.clearLabels(sess); err != nil {
  368. return fmt.Errorf("clearLabels: %v", err)
  369. } else if err = issue.addLabels(sess, labels); err != nil {
  370. return fmt.Errorf("addLabels: %v", err)
  371. }
  372. return sess.Commit()
  373. }
  374. // GetAssignee sets the Assignee attribute of this issue.
  375. func (issue *Issue) GetAssignee() (err error) {
  376. if issue.AssigneeID == 0 || issue.Assignee != nil {
  377. return nil
  378. }
  379. issue.Assignee, err = GetUserByID(issue.AssigneeID)
  380. if IsErrUserNotExist(err) {
  381. return nil
  382. }
  383. return err
  384. }
  385. // ReadBy sets issue to be read by given user.
  386. func (issue *Issue) ReadBy(userID int64) error {
  387. if err := UpdateIssueUserByRead(userID, issue.ID); err != nil {
  388. return err
  389. }
  390. if err := setNotificationStatusReadIfUnread(x, userID, issue.ID); err != nil {
  391. return err
  392. }
  393. return nil
  394. }
  395. func updateIssueCols(e Engine, issue *Issue, cols ...string) error {
  396. if _, err := e.Id(issue.ID).Cols(cols...).Update(issue); err != nil {
  397. return err
  398. }
  399. UpdateIssueIndexer(issue)
  400. return nil
  401. }
  402. // UpdateIssueCols only updates values of specific columns for given issue.
  403. func UpdateIssueCols(issue *Issue, cols ...string) error {
  404. return updateIssueCols(x, issue, cols...)
  405. }
  406. func (issue *Issue) changeStatus(e *xorm.Session, doer *User, repo *Repository, isClosed bool) (err error) {
  407. // Nothing should be performed if current status is same as target status
  408. if issue.IsClosed == isClosed {
  409. return nil
  410. }
  411. issue.IsClosed = isClosed
  412. if err = updateIssueCols(e, issue, "is_closed"); err != nil {
  413. return err
  414. } else if err = updateIssueUsersByStatus(e, issue.ID, isClosed); err != nil {
  415. return err
  416. }
  417. // Update issue count of labels
  418. if err = issue.getLabels(e); err != nil {
  419. return err
  420. }
  421. for idx := range issue.Labels {
  422. if issue.IsClosed {
  423. issue.Labels[idx].NumClosedIssues++
  424. } else {
  425. issue.Labels[idx].NumClosedIssues--
  426. }
  427. if err = updateLabel(e, issue.Labels[idx]); err != nil {
  428. return err
  429. }
  430. }
  431. // Update issue count of milestone
  432. if err = changeMilestoneIssueStats(e, issue); err != nil {
  433. return err
  434. }
  435. // New action comment
  436. if _, err = createStatusComment(e, doer, repo, issue); err != nil {
  437. return err
  438. }
  439. return nil
  440. }
  441. // ChangeStatus changes issue status to open or closed.
  442. func (issue *Issue) ChangeStatus(doer *User, repo *Repository, isClosed bool) (err error) {
  443. sess := x.NewSession()
  444. defer sessionRelease(sess)
  445. if err = sess.Begin(); err != nil {
  446. return err
  447. }
  448. if err = issue.changeStatus(sess, doer, repo, isClosed); err != nil {
  449. return err
  450. }
  451. if err = sess.Commit(); err != nil {
  452. return fmt.Errorf("Commit: %v", err)
  453. }
  454. if issue.IsPull {
  455. // Merge pull request calls issue.changeStatus so we need to handle separately.
  456. issue.PullRequest.Issue = issue
  457. apiPullRequest := &api.PullRequestPayload{
  458. Index: issue.Index,
  459. PullRequest: issue.PullRequest.APIFormat(),
  460. Repository: repo.APIFormat(AccessModeNone),
  461. Sender: doer.APIFormat(),
  462. }
  463. if isClosed {
  464. apiPullRequest.Action = api.HookIssueClosed
  465. } else {
  466. apiPullRequest.Action = api.HookIssueReOpened
  467. }
  468. err = PrepareWebhooks(repo, HookEventPullRequest, apiPullRequest)
  469. }
  470. if err != nil {
  471. log.Error(4, "PrepareWebhooks [is_pull: %v, is_closed: %v]: %v", issue.IsPull, isClosed, err)
  472. } else {
  473. go HookQueue.Add(repo.ID)
  474. }
  475. return nil
  476. }
  477. // ChangeTitle changes the title of this issue, as the given user.
  478. func (issue *Issue) ChangeTitle(doer *User, title string) (err error) {
  479. oldTitle := issue.Title
  480. issue.Title = title
  481. if err = UpdateIssueCols(issue, "name"); err != nil {
  482. return fmt.Errorf("UpdateIssueCols: %v", err)
  483. }
  484. if issue.IsPull {
  485. issue.PullRequest.Issue = issue
  486. err = PrepareWebhooks(issue.Repo, HookEventPullRequest, &api.PullRequestPayload{
  487. Action: api.HookIssueEdited,
  488. Index: issue.Index,
  489. Changes: &api.ChangesPayload{
  490. Title: &api.ChangesFromPayload{
  491. From: oldTitle,
  492. },
  493. },
  494. PullRequest: issue.PullRequest.APIFormat(),
  495. Repository: issue.Repo.APIFormat(AccessModeNone),
  496. Sender: doer.APIFormat(),
  497. })
  498. }
  499. if err != nil {
  500. log.Error(4, "PrepareWebhooks [is_pull: %v]: %v", issue.IsPull, err)
  501. } else {
  502. go HookQueue.Add(issue.RepoID)
  503. }
  504. return nil
  505. }
  506. // ChangeContent changes issue content, as the given user.
  507. func (issue *Issue) ChangeContent(doer *User, content string) (err error) {
  508. oldContent := issue.Content
  509. issue.Content = content
  510. if err = UpdateIssueCols(issue, "content"); err != nil {
  511. return fmt.Errorf("UpdateIssueCols: %v", err)
  512. }
  513. if issue.IsPull {
  514. issue.PullRequest.Issue = issue
  515. err = PrepareWebhooks(issue.Repo, HookEventPullRequest, &api.PullRequestPayload{
  516. Action: api.HookIssueEdited,
  517. Index: issue.Index,
  518. Changes: &api.ChangesPayload{
  519. Body: &api.ChangesFromPayload{
  520. From: oldContent,
  521. },
  522. },
  523. PullRequest: issue.PullRequest.APIFormat(),
  524. Repository: issue.Repo.APIFormat(AccessModeNone),
  525. Sender: doer.APIFormat(),
  526. })
  527. }
  528. if err != nil {
  529. log.Error(4, "PrepareWebhooks [is_pull: %v]: %v", issue.IsPull, err)
  530. } else {
  531. go HookQueue.Add(issue.RepoID)
  532. }
  533. return nil
  534. }
  535. // ChangeAssignee changes the Asssignee field of this issue.
  536. func (issue *Issue) ChangeAssignee(doer *User, assigneeID int64) (err error) {
  537. issue.AssigneeID = assigneeID
  538. if err = UpdateIssueUserByAssignee(issue); err != nil {
  539. return fmt.Errorf("UpdateIssueUserByAssignee: %v", err)
  540. }
  541. issue.Assignee, err = GetUserByID(issue.AssigneeID)
  542. if err != nil && !IsErrUserNotExist(err) {
  543. log.Error(4, "GetUserByID [assignee_id: %v]: %v", issue.AssigneeID, err)
  544. return nil
  545. }
  546. // Error not nil here means user does not exist, which is remove assignee.
  547. isRemoveAssignee := err != nil
  548. if issue.IsPull {
  549. issue.PullRequest.Issue = issue
  550. apiPullRequest := &api.PullRequestPayload{
  551. Index: issue.Index,
  552. PullRequest: issue.PullRequest.APIFormat(),
  553. Repository: issue.Repo.APIFormat(AccessModeNone),
  554. Sender: doer.APIFormat(),
  555. }
  556. if isRemoveAssignee {
  557. apiPullRequest.Action = api.HookIssueUnassigned
  558. } else {
  559. apiPullRequest.Action = api.HookIssueAssigned
  560. }
  561. err = PrepareWebhooks(issue.Repo, HookEventPullRequest, apiPullRequest)
  562. }
  563. if err != nil {
  564. log.Error(4, "PrepareWebhooks [is_pull: %v, remove_assignee: %v]: %v", issue.IsPull, isRemoveAssignee, err)
  565. } else {
  566. go HookQueue.Add(issue.RepoID)
  567. }
  568. return nil
  569. }
  570. // NewIssueOptions represents the options of a new issue.
  571. type NewIssueOptions struct {
  572. Repo *Repository
  573. Issue *Issue
  574. LableIDs []int64
  575. Attachments []string // In UUID format.
  576. IsPull bool
  577. }
  578. func newIssue(e *xorm.Session, opts NewIssueOptions) (err error) {
  579. opts.Issue.Title = strings.TrimSpace(opts.Issue.Title)
  580. opts.Issue.Index = opts.Repo.NextIssueIndex()
  581. if opts.Issue.MilestoneID > 0 {
  582. milestone, err := getMilestoneByRepoID(e, opts.Issue.RepoID, opts.Issue.MilestoneID)
  583. if err != nil && !IsErrMilestoneNotExist(err) {
  584. return fmt.Errorf("getMilestoneByID: %v", err)
  585. }
  586. // Assume milestone is invalid and drop silently.
  587. opts.Issue.MilestoneID = 0
  588. if milestone != nil {
  589. opts.Issue.MilestoneID = milestone.ID
  590. opts.Issue.Milestone = milestone
  591. if err = changeMilestoneAssign(e, opts.Issue, -1); err != nil {
  592. return err
  593. }
  594. }
  595. }
  596. if opts.Issue.AssigneeID > 0 {
  597. assignee, err := getUserByID(e, opts.Issue.AssigneeID)
  598. if err != nil && !IsErrUserNotExist(err) {
  599. return fmt.Errorf("getUserByID: %v", err)
  600. }
  601. // Assume assignee is invalid and drop silently.
  602. opts.Issue.AssigneeID = 0
  603. if assignee != nil {
  604. valid, err := hasAccess(e, assignee, opts.Repo, AccessModeWrite)
  605. if err != nil {
  606. return fmt.Errorf("hasAccess [user_id: %d, repo_id: %d]: %v", assignee.ID, opts.Repo.ID, err)
  607. }
  608. if valid {
  609. opts.Issue.AssigneeID = assignee.ID
  610. opts.Issue.Assignee = assignee
  611. }
  612. }
  613. }
  614. // Milestone and assignee validation should happen before insert actual object.
  615. if _, err = e.Insert(opts.Issue); err != nil {
  616. return err
  617. }
  618. if opts.IsPull {
  619. _, err = e.Exec("UPDATE `repository` SET num_pulls = num_pulls + 1 WHERE id = ?", opts.Issue.RepoID)
  620. } else {
  621. _, err = e.Exec("UPDATE `repository` SET num_issues = num_issues + 1 WHERE id = ?", opts.Issue.RepoID)
  622. }
  623. if err != nil {
  624. return err
  625. }
  626. if len(opts.LableIDs) > 0 {
  627. // During the session, SQLite3 driver cannot handle retrieve objects after update something.
  628. // So we have to get all needed labels first.
  629. labels := make([]*Label, 0, len(opts.LableIDs))
  630. if err = e.In("id", opts.LableIDs).Find(&labels); err != nil {
  631. return fmt.Errorf("find all labels [label_ids: %v]: %v", opts.LableIDs, err)
  632. }
  633. for _, label := range labels {
  634. // Silently drop invalid labels.
  635. if label.RepoID != opts.Repo.ID {
  636. continue
  637. }
  638. if err = opts.Issue.addLabel(e, label); err != nil {
  639. return fmt.Errorf("addLabel [id: %d]: %v", label.ID, err)
  640. }
  641. }
  642. }
  643. if err = newIssueUsers(e, opts.Repo, opts.Issue); err != nil {
  644. return err
  645. }
  646. UpdateIssueIndexer(opts.Issue)
  647. if len(opts.Attachments) > 0 {
  648. attachments, err := getAttachmentsByUUIDs(e, opts.Attachments)
  649. if err != nil {
  650. return fmt.Errorf("getAttachmentsByUUIDs [uuids: %v]: %v", opts.Attachments, err)
  651. }
  652. for i := 0; i < len(attachments); i++ {
  653. attachments[i].IssueID = opts.Issue.ID
  654. if _, err = e.Id(attachments[i].ID).Update(attachments[i]); err != nil {
  655. return fmt.Errorf("update attachment [id: %d]: %v", attachments[i].ID, err)
  656. }
  657. }
  658. }
  659. return opts.Issue.loadAttributes(e)
  660. }
  661. // NewIssue creates new issue with labels for repository.
  662. func NewIssue(repo *Repository, issue *Issue, labelIDs []int64, uuids []string) (err error) {
  663. sess := x.NewSession()
  664. defer sessionRelease(sess)
  665. if err = sess.Begin(); err != nil {
  666. return err
  667. }
  668. if err = newIssue(sess, NewIssueOptions{
  669. Repo: repo,
  670. Issue: issue,
  671. LableIDs: labelIDs,
  672. Attachments: uuids,
  673. }); err != nil {
  674. return fmt.Errorf("newIssue: %v", err)
  675. }
  676. if err = sess.Commit(); err != nil {
  677. return fmt.Errorf("Commit: %v", err)
  678. }
  679. if err = NotifyWatchers(&Action{
  680. ActUserID: issue.Poster.ID,
  681. ActUserName: issue.Poster.Name,
  682. OpType: ActionCreateIssue,
  683. Content: fmt.Sprintf("%d|%s", issue.Index, issue.Title),
  684. RepoID: repo.ID,
  685. RepoUserName: repo.Owner.Name,
  686. RepoName: repo.Name,
  687. IsPrivate: repo.IsPrivate,
  688. }); err != nil {
  689. log.Error(4, "NotifyWatchers: %v", err)
  690. }
  691. if err = issue.MailParticipants(); err != nil {
  692. log.Error(4, "MailParticipants: %v", err)
  693. }
  694. return nil
  695. }
  696. // GetIssueByRef returns an Issue specified by a GFM reference.
  697. // See https://help.github.com/articles/writing-on-github#references for more information on the syntax.
  698. func GetIssueByRef(ref string) (*Issue, error) {
  699. n := strings.IndexByte(ref, byte('#'))
  700. if n == -1 {
  701. return nil, errMissingIssueNumber
  702. }
  703. index, err := com.StrTo(ref[n+1:]).Int64()
  704. if err != nil {
  705. return nil, err
  706. }
  707. repo, err := GetRepositoryByRef(ref[:n])
  708. if err != nil {
  709. return nil, err
  710. }
  711. issue, err := GetIssueByIndex(repo.ID, index)
  712. if err != nil {
  713. return nil, err
  714. }
  715. return issue, issue.LoadAttributes()
  716. }
  717. // GetRawIssueByIndex returns raw issue without loading attributes by index in a repository.
  718. func GetRawIssueByIndex(repoID, index int64) (*Issue, error) {
  719. issue := &Issue{
  720. RepoID: repoID,
  721. Index: index,
  722. }
  723. has, err := x.Get(issue)
  724. if err != nil {
  725. return nil, err
  726. } else if !has {
  727. return nil, ErrIssueNotExist{0, repoID, index}
  728. }
  729. return issue, nil
  730. }
  731. // GetIssueByIndex returns issue by index in a repository.
  732. func GetIssueByIndex(repoID, index int64) (*Issue, error) {
  733. issue, err := GetRawIssueByIndex(repoID, index)
  734. if err != nil {
  735. return nil, err
  736. }
  737. return issue, issue.LoadAttributes()
  738. }
  739. func getIssueByID(e Engine, id int64) (*Issue, error) {
  740. issue := new(Issue)
  741. has, err := e.Id(id).Get(issue)
  742. if err != nil {
  743. return nil, err
  744. } else if !has {
  745. return nil, ErrIssueNotExist{id, 0, 0}
  746. }
  747. return issue, issue.LoadAttributes()
  748. }
  749. // GetIssueByID returns an issue by given ID.
  750. func GetIssueByID(id int64) (*Issue, error) {
  751. return getIssueByID(x, id)
  752. }
  753. // IssuesOptions represents options of an issue.
  754. type IssuesOptions struct {
  755. RepoID int64
  756. AssigneeID int64
  757. PosterID int64
  758. MentionedID int64
  759. MilestoneID int64
  760. RepoIDs []int64
  761. Page int
  762. IsClosed util.OptionalBool
  763. IsPull util.OptionalBool
  764. Labels string
  765. SortType string
  766. IssueIDs []int64
  767. }
  768. // sortIssuesSession sort an issues-related session based on the provided
  769. // sortType string
  770. func sortIssuesSession(sess *xorm.Session, sortType string) {
  771. switch sortType {
  772. case "oldest":
  773. sess.Asc("issue.created_unix")
  774. case "recentupdate":
  775. sess.Desc("issue.updated_unix")
  776. case "leastupdate":
  777. sess.Asc("issue.updated_unix")
  778. case "mostcomment":
  779. sess.Desc("issue.num_comments")
  780. case "leastcomment":
  781. sess.Asc("issue.num_comments")
  782. case "priority":
  783. sess.Desc("issue.priority")
  784. default:
  785. sess.Desc("issue.created_unix")
  786. }
  787. }
  788. // Issues returns a list of issues by given conditions.
  789. func Issues(opts *IssuesOptions) ([]*Issue, error) {
  790. var sess *xorm.Session
  791. if opts.Page >= 0 {
  792. var start int
  793. if opts.Page == 0 {
  794. start = 0
  795. } else {
  796. start = (opts.Page - 1) * setting.UI.IssuePagingNum
  797. }
  798. sess = x.Limit(setting.UI.IssuePagingNum, start)
  799. } else {
  800. sess = x.NewSession()
  801. defer sess.Close()
  802. }
  803. if len(opts.IssueIDs) > 0 {
  804. sess.In("issue.id", opts.IssueIDs)
  805. }
  806. if opts.RepoID > 0 {
  807. sess.And("issue.repo_id=?", opts.RepoID)
  808. } else if len(opts.RepoIDs) > 0 {
  809. // In case repository IDs are provided but actually no repository has issue.
  810. sess.In("issue.repo_id", opts.RepoIDs)
  811. }
  812. switch opts.IsClosed {
  813. case util.OptionalBoolTrue:
  814. sess.And("issue.is_closed=?", true)
  815. case util.OptionalBoolFalse:
  816. sess.And("issue.is_closed=?", false)
  817. }
  818. if opts.AssigneeID > 0 {
  819. sess.And("issue.assignee_id=?", opts.AssigneeID)
  820. }
  821. if opts.PosterID > 0 {
  822. sess.And("issue.poster_id=?", opts.PosterID)
  823. }
  824. if opts.MentionedID > 0 {
  825. sess.Join("INNER", "issue_user", "issue.id = issue_user.issue_id").
  826. And("issue_user.is_mentioned = ?", true).
  827. And("issue_user.uid = ?", opts.MentionedID)
  828. }
  829. if opts.MilestoneID > 0 {
  830. sess.And("issue.milestone_id=?", opts.MilestoneID)
  831. }
  832. switch opts.IsPull {
  833. case util.OptionalBoolTrue:
  834. sess.And("issue.is_pull=?", true)
  835. case util.OptionalBoolFalse:
  836. sess.And("issue.is_pull=?", false)
  837. }
  838. sortIssuesSession(sess, opts.SortType)
  839. if len(opts.Labels) > 0 && opts.Labels != "0" {
  840. labelIDs, err := base.StringsToInt64s(strings.Split(opts.Labels, ","))
  841. if err != nil {
  842. return nil, err
  843. }
  844. if len(labelIDs) > 0 {
  845. sess.
  846. Join("INNER", "issue_label", "issue.id = issue_label.issue_id").
  847. In("issue_label.label_id", labelIDs)
  848. }
  849. }
  850. issues := make([]*Issue, 0, setting.UI.IssuePagingNum)
  851. if err := sess.Find(&issues); err != nil {
  852. return nil, fmt.Errorf("Find: %v", err)
  853. }
  854. // FIXME: use IssueList to improve performance.
  855. for i := range issues {
  856. if err := issues[i].LoadAttributes(); err != nil {
  857. return nil, fmt.Errorf("LoadAttributes [%d]: %v", issues[i].ID, err)
  858. }
  859. }
  860. return issues, nil
  861. }
  862. // .___ ____ ___
  863. // | | ______ ________ __ ____ | | \______ ___________
  864. // | |/ ___// ___/ | \_/ __ \| | / ___// __ \_ __ \
  865. // | |\___ \ \___ \| | /\ ___/| | /\___ \\ ___/| | \/
  866. // |___/____ >____ >____/ \___ >______//____ >\___ >__|
  867. // \/ \/ \/ \/ \/
  868. // IssueUser represents an issue-user relation.
  869. type IssueUser struct {
  870. ID int64 `xorm:"pk autoincr"`
  871. UID int64 `xorm:"INDEX"` // User ID.
  872. IssueID int64
  873. RepoID int64 `xorm:"INDEX"`
  874. MilestoneID int64
  875. IsRead bool
  876. IsAssigned bool
  877. IsMentioned bool
  878. IsPoster bool
  879. IsClosed bool
  880. }
  881. func newIssueUsers(e *xorm.Session, repo *Repository, issue *Issue) error {
  882. assignees, err := repo.getAssignees(e)
  883. if err != nil {
  884. return fmt.Errorf("getAssignees: %v", err)
  885. }
  886. // Poster can be anyone, append later if not one of assignees.
  887. isPosterAssignee := false
  888. // Leave a seat for poster itself to append later, but if poster is one of assignee
  889. // and just waste 1 unit is cheaper than re-allocate memory once.
  890. issueUsers := make([]*IssueUser, 0, len(assignees)+1)
  891. for _, assignee := range assignees {
  892. isPoster := assignee.ID == issue.PosterID
  893. issueUsers = append(issueUsers, &IssueUser{
  894. IssueID: issue.ID,
  895. RepoID: repo.ID,
  896. UID: assignee.ID,
  897. IsPoster: isPoster,
  898. IsAssigned: assignee.ID == issue.AssigneeID,
  899. })
  900. if !isPosterAssignee && isPoster {
  901. isPosterAssignee = true
  902. }
  903. }
  904. if !isPosterAssignee {
  905. issueUsers = append(issueUsers, &IssueUser{
  906. IssueID: issue.ID,
  907. RepoID: repo.ID,
  908. UID: issue.PosterID,
  909. IsPoster: true,
  910. })
  911. }
  912. if _, err = e.Insert(issueUsers); err != nil {
  913. return err
  914. }
  915. return nil
  916. }
  917. // NewIssueUsers adds new issue-user relations for new issue of repository.
  918. func NewIssueUsers(repo *Repository, issue *Issue) (err error) {
  919. sess := x.NewSession()
  920. defer sessionRelease(sess)
  921. if err = sess.Begin(); err != nil {
  922. return err
  923. }
  924. if err = newIssueUsers(sess, repo, issue); err != nil {
  925. return err
  926. }
  927. return sess.Commit()
  928. }
  929. // PairsContains returns true when pairs list contains given issue.
  930. func PairsContains(ius []*IssueUser, issueID, uid int64) int {
  931. for i := range ius {
  932. if ius[i].IssueID == issueID &&
  933. ius[i].UID == uid {
  934. return i
  935. }
  936. }
  937. return -1
  938. }
  939. // GetIssueUsers returns issue-user pairs by given repository and user.
  940. func GetIssueUsers(rid, uid int64, isClosed bool) ([]*IssueUser, error) {
  941. ius := make([]*IssueUser, 0, 10)
  942. err := x.Where("is_closed=?", isClosed).Find(&ius, &IssueUser{RepoID: rid, UID: uid})
  943. return ius, err
  944. }
  945. // GetIssueUserPairsByRepoIds returns issue-user pairs by given repository IDs.
  946. func GetIssueUserPairsByRepoIds(rids []int64, isClosed bool, page int) ([]*IssueUser, error) {
  947. if len(rids) == 0 {
  948. return []*IssueUser{}, nil
  949. }
  950. ius := make([]*IssueUser, 0, 10)
  951. sess := x.
  952. Limit(20, (page-1)*20).
  953. Where("is_closed=?", isClosed).
  954. In("repo_id", rids)
  955. err := sess.Find(&ius)
  956. return ius, err
  957. }
  958. // GetIssueUserPairsByMode returns issue-user pairs by given repository and user.
  959. func GetIssueUserPairsByMode(uid, rid int64, isClosed bool, page, filterMode int) ([]*IssueUser, error) {
  960. ius := make([]*IssueUser, 0, 10)
  961. sess := x.
  962. Limit(20, (page-1)*20).
  963. Where("uid=?", uid).
  964. And("is_closed=?", isClosed)
  965. if rid > 0 {
  966. sess.And("repo_id=?", rid)
  967. }
  968. switch filterMode {
  969. case FilterModeAssign:
  970. sess.And("is_assigned=?", true)
  971. case FilterModeCreate:
  972. sess.And("is_poster=?", true)
  973. default:
  974. return ius, nil
  975. }
  976. err := sess.Find(&ius)
  977. return ius, err
  978. }
  979. // UpdateIssueMentions extracts mentioned people from content and
  980. // updates issue-user relations for them.
  981. func UpdateIssueMentions(e Engine, issueID int64, mentions []string) error {
  982. if len(mentions) == 0 {
  983. return nil
  984. }
  985. for i := range mentions {
  986. mentions[i] = strings.ToLower(mentions[i])
  987. }
  988. users := make([]*User, 0, len(mentions))
  989. if err := e.In("lower_name", mentions).Asc("lower_name").Find(&users); err != nil {
  990. return fmt.Errorf("find mentioned users: %v", err)
  991. }
  992. ids := make([]int64, 0, len(mentions))
  993. for _, user := range users {
  994. ids = append(ids, user.ID)
  995. if !user.IsOrganization() || user.NumMembers == 0 {
  996. continue
  997. }
  998. memberIDs := make([]int64, 0, user.NumMembers)
  999. orgUsers, err := GetOrgUsersByOrgID(user.ID)
  1000. if err != nil {
  1001. return fmt.Errorf("GetOrgUsersByOrgID [%d]: %v", user.ID, err)
  1002. }
  1003. for _, orgUser := range orgUsers {
  1004. memberIDs = append(memberIDs, orgUser.ID)
  1005. }
  1006. ids = append(ids, memberIDs...)
  1007. }
  1008. if err := UpdateIssueUsersByMentions(e, issueID, ids); err != nil {
  1009. return fmt.Errorf("UpdateIssueUsersByMentions: %v", err)
  1010. }
  1011. return nil
  1012. }
  1013. // IssueStats represents issue statistic information.
  1014. type IssueStats struct {
  1015. OpenCount, ClosedCount int64
  1016. AllCount int64
  1017. AssignCount int64
  1018. CreateCount int64
  1019. MentionCount int64
  1020. }
  1021. // Filter modes.
  1022. const (
  1023. FilterModeAll = iota
  1024. FilterModeAssign
  1025. FilterModeCreate
  1026. FilterModeMention
  1027. )
  1028. func parseCountResult(results []map[string][]byte) int64 {
  1029. if len(results) == 0 {
  1030. return 0
  1031. }
  1032. for _, result := range results[0] {
  1033. return com.StrTo(string(result)).MustInt64()
  1034. }
  1035. return 0
  1036. }
  1037. // IssueStatsOptions contains parameters accepted by GetIssueStats.
  1038. type IssueStatsOptions struct {
  1039. RepoID int64
  1040. Labels string
  1041. MilestoneID int64
  1042. AssigneeID int64
  1043. MentionedID int64
  1044. PosterID int64
  1045. IsPull bool
  1046. IssueIDs []int64
  1047. }
  1048. // GetIssueStats returns issue statistic information by given conditions.
  1049. func GetIssueStats(opts *IssueStatsOptions) (*IssueStats, error) {
  1050. stats := &IssueStats{}
  1051. countSession := func(opts *IssueStatsOptions) *xorm.Session {
  1052. sess := x.
  1053. Where("issue.repo_id = ?", opts.RepoID).
  1054. And("is_pull = ?", opts.IsPull)
  1055. if len(opts.IssueIDs) > 0 {
  1056. sess.In("issue.id", opts.IssueIDs)
  1057. }
  1058. if len(opts.Labels) > 0 && opts.Labels != "0" {
  1059. labelIDs, err := base.StringsToInt64s(strings.Split(opts.Labels, ","))
  1060. if err != nil {
  1061. log.Warn("Malformed Labels argument: %s", opts.Labels)
  1062. } else if len(labelIDs) > 0 {
  1063. sess.Join("INNER", "issue_label", "issue.id = issue_id").
  1064. In("label_id", labelIDs)
  1065. }
  1066. }
  1067. if opts.MilestoneID > 0 {
  1068. sess.And("issue.milestone_id = ?", opts.MilestoneID)
  1069. }
  1070. if opts.AssigneeID > 0 {
  1071. sess.And("assignee_id = ?", opts.AssigneeID)
  1072. }
  1073. if opts.PosterID > 0 {
  1074. sess.And("poster_id = ?", opts.PosterID)
  1075. }
  1076. if opts.MentionedID > 0 {
  1077. sess.Join("INNER", "issue_user", "issue.id = issue_user.issue_id").
  1078. And("issue_user.uid = ?", opts.MentionedID).
  1079. And("issue_user.is_mentioned = ?", true)
  1080. }
  1081. return sess
  1082. }
  1083. var err error
  1084. stats.OpenCount, err = countSession(opts).
  1085. And("is_closed = ?", false).
  1086. Count(&Issue{})
  1087. if err != nil {
  1088. return nil, err
  1089. }
  1090. stats.ClosedCount, err = countSession(opts).
  1091. And("is_closed = ?", true).
  1092. Count(&Issue{})
  1093. if err != nil {
  1094. return nil, err
  1095. }
  1096. return stats, nil
  1097. }
  1098. // GetUserIssueStats returns issue statistic information for dashboard by given conditions.
  1099. func GetUserIssueStats(repoID, uid int64, repoIDs []int64, filterMode int, isPull bool) *IssueStats {
  1100. stats := &IssueStats{}
  1101. countSession := func(isClosed, isPull bool, repoID int64, repoIDs []int64) *xorm.Session {
  1102. sess := x.
  1103. Where("issue.is_closed = ?", isClosed).
  1104. And("issue.is_pull = ?", isPull)
  1105. if repoID > 0 {
  1106. sess.And("repo_id = ?", repoID)
  1107. } else if len(repoIDs) > 0 {
  1108. sess.In("repo_id", repoIDs)
  1109. }
  1110. return sess
  1111. }
  1112. stats.AssignCount, _ = countSession(false, isPull, repoID, repoIDs).
  1113. And("assignee_id = ?", uid).
  1114. Count(&Issue{})
  1115. stats.CreateCount, _ = countSession(false, isPull, repoID, repoIDs).
  1116. And("poster_id = ?", uid).
  1117. Count(&Issue{})
  1118. openCountSession := countSession(false, isPull, repoID, repoIDs)
  1119. closedCountSession := countSession(true, isPull, repoID, repoIDs)
  1120. switch filterMode {
  1121. case FilterModeAssign:
  1122. openCountSession.And("assignee_id = ?", uid)
  1123. closedCountSession.And("assignee_id = ?", uid)
  1124. case FilterModeCreate:
  1125. openCountSession.And("poster_id = ?", uid)
  1126. closedCountSession.And("poster_id = ?", uid)
  1127. }
  1128. stats.OpenCount, _ = openCountSession.Count(&Issue{})
  1129. stats.ClosedCount, _ = closedCountSession.Count(&Issue{})
  1130. return stats
  1131. }
  1132. // GetRepoIssueStats returns number of open and closed repository issues by given filter mode.
  1133. func GetRepoIssueStats(repoID, uid int64, filterMode int, isPull bool) (numOpen int64, numClosed int64) {
  1134. countSession := func(isClosed, isPull bool, repoID int64) *xorm.Session {
  1135. sess := x.
  1136. Where("issue.repo_id = ?", isClosed).
  1137. And("is_pull = ?", isPull).
  1138. And("repo_id = ?", repoID)
  1139. return sess
  1140. }
  1141. openCountSession := countSession(false, isPull, repoID)
  1142. closedCountSession := countSession(true, isPull, repoID)
  1143. switch filterMode {
  1144. case FilterModeAssign:
  1145. openCountSession.And("assignee_id = ?", uid)
  1146. closedCountSession.And("assignee_id = ?", uid)
  1147. case FilterModeCreate:
  1148. openCountSession.And("poster_id = ?", uid)
  1149. closedCountSession.And("poster_id = ?", uid)
  1150. }
  1151. openResult, _ := openCountSession.Count(&Issue{})
  1152. closedResult, _ := closedCountSession.Count(&Issue{})
  1153. return openResult, closedResult
  1154. }
  1155. func updateIssue(e Engine, issue *Issue) error {
  1156. _, err := e.Id(issue.ID).AllCols().Update(issue)
  1157. if err != nil {
  1158. return err
  1159. }
  1160. UpdateIssueIndexer(issue)
  1161. return nil
  1162. }
  1163. // UpdateIssue updates all fields of given issue.
  1164. func UpdateIssue(issue *Issue) error {
  1165. return updateIssue(x, issue)
  1166. }
  1167. func updateIssueUsersByStatus(e Engine, issueID int64, isClosed bool) error {
  1168. _, err := e.Exec("UPDATE `issue_user` SET is_closed=? WHERE issue_id=?", isClosed, issueID)
  1169. return err
  1170. }
  1171. // UpdateIssueUsersByStatus updates issue-user relations by issue status.
  1172. func UpdateIssueUsersByStatus(issueID int64, isClosed bool) error {
  1173. return updateIssueUsersByStatus(x, issueID, isClosed)
  1174. }
  1175. func updateIssueUserByAssignee(e *xorm.Session, issue *Issue) (err error) {
  1176. if _, err = e.Exec("UPDATE `issue_user` SET is_assigned = ? WHERE issue_id = ?", false, issue.ID); err != nil {
  1177. return err
  1178. }
  1179. // Assignee ID equals to 0 means clear assignee.
  1180. if issue.AssigneeID > 0 {
  1181. if _, err = e.Exec("UPDATE `issue_user` SET is_assigned = ? WHERE uid = ? AND issue_id = ?", true, issue.AssigneeID, issue.ID); err != nil {
  1182. return err
  1183. }
  1184. }
  1185. return updateIssue(e, issue)
  1186. }
  1187. // UpdateIssueUserByAssignee updates issue-user relation for assignee.
  1188. func UpdateIssueUserByAssignee(issue *Issue) (err error) {
  1189. sess := x.NewSession()
  1190. defer sessionRelease(sess)
  1191. if err = sess.Begin(); err != nil {
  1192. return err
  1193. }
  1194. if err = updateIssueUserByAssignee(sess, issue); err != nil {
  1195. return err
  1196. }
  1197. return sess.Commit()
  1198. }
  1199. // UpdateIssueUserByRead updates issue-user relation for reading.
  1200. func UpdateIssueUserByRead(uid, issueID int64) error {
  1201. _, err := x.Exec("UPDATE `issue_user` SET is_read=? WHERE uid=? AND issue_id=?", true, uid, issueID)
  1202. return err
  1203. }
  1204. // UpdateIssueUsersByMentions updates issue-user pairs by mentioning.
  1205. func UpdateIssueUsersByMentions(e Engine, issueID int64, uids []int64) error {
  1206. for _, uid := range uids {
  1207. iu := &IssueUser{
  1208. UID: uid,
  1209. IssueID: issueID,
  1210. }
  1211. has, err := e.Get(iu)
  1212. if err != nil {
  1213. return err
  1214. }
  1215. iu.IsMentioned = true
  1216. if has {
  1217. _, err = e.Id(iu.ID).AllCols().Update(iu)
  1218. } else {
  1219. _, err = e.Insert(iu)
  1220. }
  1221. if err != nil {
  1222. return err
  1223. }
  1224. }
  1225. return nil
  1226. }
  1227. // _____ .__.__ __
  1228. // / \ |__| | ____ _______/ |_ ____ ____ ____
  1229. // / \ / \| | | _/ __ \ / ___/\ __\/ _ \ / \_/ __ \
  1230. // / Y \ | |_\ ___/ \___ \ | | ( <_> ) | \ ___/
  1231. // \____|__ /__|____/\___ >____ > |__| \____/|___| /\___ >
  1232. // \/ \/ \/ \/ \/
  1233. // Milestone represents a milestone of repository.
  1234. type Milestone struct {
  1235. ID int64 `xorm:"pk autoincr"`
  1236. RepoID int64 `xorm:"INDEX"`
  1237. Name string
  1238. Content string `xorm:"TEXT"`
  1239. RenderedContent string `xorm:"-"`
  1240. IsClosed bool
  1241. NumIssues int
  1242. NumClosedIssues int
  1243. NumOpenIssues int `xorm:"-"`
  1244. Completeness int // Percentage(1-100).
  1245. IsOverDue bool `xorm:"-"`
  1246. DeadlineString string `xorm:"-"`
  1247. Deadline time.Time `xorm:"-"`
  1248. DeadlineUnix int64
  1249. ClosedDate time.Time `xorm:"-"`
  1250. ClosedDateUnix int64
  1251. }
  1252. // BeforeInsert is invoked from XORM before inserting an object of this type.
  1253. func (m *Milestone) BeforeInsert() {
  1254. m.DeadlineUnix = m.Deadline.Unix()
  1255. }
  1256. // BeforeUpdate is invoked from XORM before updating this object.
  1257. func (m *Milestone) BeforeUpdate() {
  1258. if m.NumIssues > 0 {
  1259. m.Completeness = m.NumClosedIssues * 100 / m.NumIssues
  1260. } else {
  1261. m.Completeness = 0
  1262. }
  1263. m.DeadlineUnix = m.Deadline.Unix()
  1264. m.ClosedDateUnix = m.ClosedDate.Unix()
  1265. }
  1266. // AfterSet is invoked from XORM after setting the value of a field of
  1267. // this object.
  1268. func (m *Milestone) AfterSet(colName string, _ xorm.Cell) {
  1269. switch colName {
  1270. case "num_closed_issues":
  1271. m.NumOpenIssues = m.NumIssues - m.NumClosedIssues
  1272. case "deadline_unix":
  1273. m.Deadline = time.Unix(m.DeadlineUnix, 0).Local()
  1274. if m.Deadline.Year() == 9999 {
  1275. return
  1276. }
  1277. m.DeadlineString = m.Deadline.Format("2006-01-02")
  1278. if time.Now().Local().After(m.Deadline) {
  1279. m.IsOverDue = true
  1280. }
  1281. case "closed_date_unix":
  1282. m.ClosedDate = time.Unix(m.ClosedDateUnix, 0).Local()
  1283. }
  1284. }
  1285. // State returns string representation of milestone status.
  1286. func (m *Milestone) State() api.StateType {
  1287. if m.IsClosed {
  1288. return api.StateClosed
  1289. }
  1290. return api.StateOpen
  1291. }
  1292. // APIFormat returns this Milestone in API format.
  1293. func (m *Milestone) APIFormat() *api.Milestone {
  1294. apiMilestone := &api.Milestone{
  1295. ID: m.ID,
  1296. State: m.State(),
  1297. Title: m.Name,
  1298. Description: m.Content,
  1299. OpenIssues: m.NumOpenIssues,
  1300. ClosedIssues: m.NumClosedIssues,
  1301. }
  1302. if m.IsClosed {
  1303. apiMilestone.Closed = &m.ClosedDate
  1304. }
  1305. if m.Deadline.Year() < 9999 {
  1306. apiMilestone.Deadline = &m.Deadline
  1307. }
  1308. return apiMilestone
  1309. }
  1310. // NewMilestone creates new milestone of repository.
  1311. func NewMilestone(m *Milestone) (err error) {
  1312. sess := x.NewSession()
  1313. defer sessionRelease(sess)
  1314. if err = sess.Begin(); err != nil {
  1315. return err
  1316. }
  1317. if _, err = sess.Insert(m); err != nil {
  1318. return err
  1319. }
  1320. if _, err = sess.Exec("UPDATE `repository` SET num_milestones = num_milestones + 1 WHERE id = ?", m.RepoID); err != nil {
  1321. return err
  1322. }
  1323. return sess.Commit()
  1324. }
  1325. func getMilestoneByRepoID(e Engine, repoID, id int64) (*Milestone, error) {
  1326. m := &Milestone{
  1327. ID: id,
  1328. RepoID: repoID,
  1329. }
  1330. has, err := e.Get(m)
  1331. if err != nil {
  1332. return nil, err
  1333. } else if !has {
  1334. return nil, ErrMilestoneNotExist{id, repoID}
  1335. }
  1336. return m, nil
  1337. }
  1338. // GetMilestoneByRepoID returns the milestone in a repository.
  1339. func GetMilestoneByRepoID(repoID, id int64) (*Milestone, error) {
  1340. return getMilestoneByRepoID(x, repoID, id)
  1341. }
  1342. // GetMilestonesByRepoID returns all milestones of a repository.
  1343. func GetMilestonesByRepoID(repoID int64) ([]*Milestone, error) {
  1344. miles := make([]*Milestone, 0, 10)
  1345. return miles, x.Where("repo_id = ?", repoID).Find(&miles)
  1346. }
  1347. // GetMilestones returns a list of milestones of given repository and status.
  1348. func GetMilestones(repoID int64, page int, isClosed bool, sortType string) ([]*Milestone, error) {
  1349. miles := make([]*Milestone, 0, setting.UI.IssuePagingNum)
  1350. sess := x.Where("repo_id = ? AND is_closed = ?", repoID, isClosed)
  1351. if page > 0 {
  1352. sess = sess.Limit(setting.UI.IssuePagingNum, (page-1)*setting.UI.IssuePagingNum)
  1353. }
  1354. switch sortType {
  1355. case "furthestduedate":
  1356. sess.Desc("deadline_unix")
  1357. case "leastcomplete":
  1358. sess.Asc("completeness")
  1359. case "mostcomplete":
  1360. sess.Desc("completeness")
  1361. case "leastissues":
  1362. sess.Asc("num_issues")
  1363. case "mostissues":
  1364. sess.Desc("num_issues")
  1365. default:
  1366. sess.Asc("deadline_unix")
  1367. }
  1368. return miles, sess.Find(&miles)
  1369. }
  1370. func updateMilestone(e Engine, m *Milestone) error {
  1371. _, err := e.Id(m.ID).AllCols().Update(m)
  1372. return err
  1373. }
  1374. // UpdateMilestone updates information of given milestone.
  1375. func UpdateMilestone(m *Milestone) error {
  1376. return updateMilestone(x, m)
  1377. }
  1378. func countRepoMilestones(e Engine, repoID int64) int64 {
  1379. count, _ := e.
  1380. Where("repo_id=?", repoID).
  1381. Count(new(Milestone))
  1382. return count
  1383. }
  1384. // CountRepoMilestones returns number of milestones in given repository.
  1385. func CountRepoMilestones(repoID int64) int64 {
  1386. return countRepoMilestones(x, repoID)
  1387. }
  1388. func countRepoClosedMilestones(e Engine, repoID int64) int64 {
  1389. closed, _ := e.
  1390. Where("repo_id=? AND is_closed=?", repoID, true).
  1391. Count(new(Milestone))
  1392. return closed
  1393. }
  1394. // CountRepoClosedMilestones returns number of closed milestones in given repository.
  1395. func CountRepoClosedMilestones(repoID int64) int64 {
  1396. return countRepoClosedMilestones(x, repoID)
  1397. }
  1398. // MilestoneStats returns number of open and closed milestones of given repository.
  1399. func MilestoneStats(repoID int64) (open int64, closed int64) {
  1400. open, _ = x.
  1401. Where("repo_id=? AND is_closed=?", repoID, false).
  1402. Count(new(Milestone))
  1403. return open, CountRepoClosedMilestones(repoID)
  1404. }
  1405. // ChangeMilestoneStatus changes the milestone open/closed status.
  1406. func ChangeMilestoneStatus(m *Milestone, isClosed bool) (err error) {
  1407. repo, err := GetRepositoryByID(m.RepoID)
  1408. if err != nil {
  1409. return err
  1410. }
  1411. sess := x.NewSession()
  1412. defer sessionRelease(sess)
  1413. if err = sess.Begin(); err != nil {
  1414. return err
  1415. }
  1416. m.IsClosed = isClosed
  1417. if err = updateMilestone(sess, m); err != nil {
  1418. return err
  1419. }
  1420. repo.NumMilestones = int(countRepoMilestones(sess, repo.ID))
  1421. repo.NumClosedMilestones = int(countRepoClosedMilestones(sess, repo.ID))
  1422. if _, err = sess.Id(repo.ID).AllCols().Update(repo); err != nil {
  1423. return err
  1424. }
  1425. return sess.Commit()
  1426. }
  1427. func changeMilestoneIssueStats(e *xorm.Session, issue *Issue) error {
  1428. if issue.MilestoneID == 0 {
  1429. return nil
  1430. }
  1431. m, err := getMilestoneByRepoID(e, issue.RepoID, issue.MilestoneID)
  1432. if err != nil {
  1433. return err
  1434. }
  1435. if issue.IsClosed {
  1436. m.NumOpenIssues--
  1437. m.NumClosedIssues++
  1438. } else {
  1439. m.NumOpenIssues++
  1440. m.NumClosedIssues--
  1441. }
  1442. return updateMilestone(e, m)
  1443. }
  1444. // ChangeMilestoneIssueStats updates the open/closed issues counter and progress
  1445. // for the milestone associated with the given issue.
  1446. func ChangeMilestoneIssueStats(issue *Issue) (err error) {
  1447. sess := x.NewSession()
  1448. defer sessionRelease(sess)
  1449. if err = sess.Begin(); err != nil {
  1450. return err
  1451. }
  1452. if err = changeMilestoneIssueStats(sess, issue); err != nil {
  1453. return err
  1454. }
  1455. return sess.Commit()
  1456. }
  1457. func changeMilestoneAssign(e *xorm.Session, issue *Issue, oldMilestoneID int64) error {
  1458. if oldMilestoneID > 0 {
  1459. m, err := getMilestoneByRepoID(e, issue.RepoID, oldMilestoneID)
  1460. if err != nil {
  1461. return err
  1462. }
  1463. m.NumIssues--
  1464. if issue.IsClosed {
  1465. m.NumClosedIssues--
  1466. }
  1467. if err = updateMilestone(e, m); err != nil {
  1468. return err
  1469. } else if _, err = e.Exec("UPDATE `issue_user` SET milestone_id = 0 WHERE issue_id = ?", issue.ID); err != nil {
  1470. return err
  1471. }
  1472. }
  1473. if issue.MilestoneID > 0 {
  1474. m, err := getMilestoneByRepoID(e, issue.RepoID, issue.MilestoneID)
  1475. if err != nil {
  1476. return err
  1477. }
  1478. m.NumIssues++
  1479. if issue.IsClosed {
  1480. m.NumClosedIssues++
  1481. }
  1482. if err = updateMilestone(e, m); err != nil {
  1483. return err
  1484. } else if _, err = e.Exec("UPDATE `issue_user` SET milestone_id = ? WHERE issue_id = ?", m.ID, issue.ID); err != nil {
  1485. return err
  1486. }
  1487. }
  1488. return updateIssue(e, issue)
  1489. }
  1490. // ChangeMilestoneAssign changes assignment of milestone for issue.
  1491. func ChangeMilestoneAssign(issue *Issue, oldMilestoneID int64) (err error) {
  1492. sess := x.NewSession()
  1493. defer sess.Close()
  1494. if err = sess.Begin(); err != nil {
  1495. return err
  1496. }
  1497. if err = changeMilestoneAssign(sess, issue, oldMilestoneID); err != nil {
  1498. return err
  1499. }
  1500. return sess.Commit()
  1501. }
  1502. // DeleteMilestoneByRepoID deletes a milestone from a repository.
  1503. func DeleteMilestoneByRepoID(repoID, id int64) error {
  1504. m, err := GetMilestoneByRepoID(repoID, id)
  1505. if err != nil {
  1506. if IsErrMilestoneNotExist(err) {
  1507. return nil
  1508. }
  1509. return err
  1510. }
  1511. repo, err := GetRepositoryByID(m.RepoID)
  1512. if err != nil {
  1513. return err
  1514. }
  1515. sess := x.NewSession()
  1516. defer sessionRelease(sess)
  1517. if err = sess.Begin(); err != nil {
  1518. return err
  1519. }
  1520. if _, err = sess.Id(m.ID).Delete(new(Milestone)); err != nil {
  1521. return err
  1522. }
  1523. repo.NumMilestones = int(countRepoMilestones(sess, repo.ID))
  1524. repo.NumClosedMilestones = int(countRepoClosedMilestones(sess, repo.ID))
  1525. if _, err = sess.Id(repo.ID).AllCols().Update(repo); err != nil {
  1526. return err
  1527. }
  1528. if _, err = sess.Exec("UPDATE `issue` SET milestone_id = 0 WHERE milestone_id = ?", m.ID); err != nil {
  1529. return err
  1530. } else if _, err = sess.Exec("UPDATE `issue_user` SET milestone_id = 0 WHERE milestone_id = ?", m.ID); err != nil {
  1531. return err
  1532. }
  1533. return sess.Commit()
  1534. }