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