You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

issue.go 49KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870
  1. // Copyright 2014 The Gogs Authors. All rights reserved.
  2. // Use of this source code is governed by a MIT-style
  3. // license that can be found in the LICENSE file.
  4. package models
  5. import (
  6. "errors"
  7. "fmt"
  8. "path"
  9. "regexp"
  10. "sort"
  11. "strings"
  12. "code.gitea.io/gitea/modules/base"
  13. "code.gitea.io/gitea/modules/log"
  14. "code.gitea.io/gitea/modules/setting"
  15. api "code.gitea.io/gitea/modules/structs"
  16. "code.gitea.io/gitea/modules/util"
  17. "github.com/Unknwon/com"
  18. "github.com/go-xorm/xorm"
  19. "xorm.io/builder"
  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. OriginalAuthor string
  30. OriginalAuthorID int64
  31. Title string `xorm:"name"`
  32. Content string `xorm:"TEXT"`
  33. RenderedContent string `xorm:"-"`
  34. Labels []*Label `xorm:"-"`
  35. MilestoneID int64 `xorm:"INDEX"`
  36. Milestone *Milestone `xorm:"-"`
  37. Priority int
  38. AssigneeID int64 `xorm:"-"`
  39. Assignee *User `xorm:"-"`
  40. IsClosed bool `xorm:"INDEX"`
  41. IsRead bool `xorm:"-"`
  42. IsPull bool `xorm:"INDEX"` // Indicates whether is a pull request or not.
  43. PullRequest *PullRequest `xorm:"-"`
  44. NumComments int
  45. Ref string
  46. DeadlineUnix util.TimeStamp `xorm:"INDEX"`
  47. CreatedUnix util.TimeStamp `xorm:"INDEX created"`
  48. UpdatedUnix util.TimeStamp `xorm:"INDEX updated"`
  49. ClosedUnix util.TimeStamp `xorm:"INDEX"`
  50. Attachments []*Attachment `xorm:"-"`
  51. Comments []*Comment `xorm:"-"`
  52. Reactions ReactionList `xorm:"-"`
  53. TotalTrackedTime int64 `xorm:"-"`
  54. Assignees []*User `xorm:"-"`
  55. // IsLocked limits commenting abilities to users on an issue
  56. // with write access
  57. IsLocked bool `xorm:"NOT NULL DEFAULT false"`
  58. }
  59. var (
  60. issueTasksPat *regexp.Regexp
  61. issueTasksDonePat *regexp.Regexp
  62. )
  63. const issueTasksRegexpStr = `(^\s*[-*]\s\[[\sx]\]\s.)|(\n\s*[-*]\s\[[\sx]\]\s.)`
  64. const issueTasksDoneRegexpStr = `(^\s*[-*]\s\[[x]\]\s.)|(\n\s*[-*]\s\[[x]\]\s.)`
  65. func init() {
  66. issueTasksPat = regexp.MustCompile(issueTasksRegexpStr)
  67. issueTasksDonePat = regexp.MustCompile(issueTasksDoneRegexpStr)
  68. }
  69. func (issue *Issue) loadTotalTimes(e Engine) (err error) {
  70. opts := FindTrackedTimesOptions{IssueID: issue.ID}
  71. issue.TotalTrackedTime, err = opts.ToSession(e).SumInt(&TrackedTime{}, "time")
  72. if err != nil {
  73. return err
  74. }
  75. return nil
  76. }
  77. // IsOverdue checks if the issue is overdue
  78. func (issue *Issue) IsOverdue() bool {
  79. return util.TimeStampNow() >= issue.DeadlineUnix
  80. }
  81. // LoadRepo loads issue's repository
  82. func (issue *Issue) LoadRepo() error {
  83. return issue.loadRepo(x)
  84. }
  85. func (issue *Issue) loadRepo(e Engine) (err error) {
  86. if issue.Repo == nil {
  87. issue.Repo, err = getRepositoryByID(e, issue.RepoID)
  88. if err != nil {
  89. return fmt.Errorf("getRepositoryByID [%d]: %v", issue.RepoID, err)
  90. }
  91. }
  92. return nil
  93. }
  94. // IsTimetrackerEnabled returns true if the repo enables timetracking
  95. func (issue *Issue) IsTimetrackerEnabled() bool {
  96. return issue.isTimetrackerEnabled(x)
  97. }
  98. func (issue *Issue) isTimetrackerEnabled(e Engine) bool {
  99. if err := issue.loadRepo(e); err != nil {
  100. log.Error(fmt.Sprintf("loadRepo: %v", err))
  101. return false
  102. }
  103. return issue.Repo.IsTimetrackerEnabled()
  104. }
  105. // GetPullRequest returns the issue pull request
  106. func (issue *Issue) GetPullRequest() (pr *PullRequest, err error) {
  107. if !issue.IsPull {
  108. return nil, fmt.Errorf("Issue is not a pull request")
  109. }
  110. pr, err = getPullRequestByIssueID(x, issue.ID)
  111. if err != nil {
  112. return nil, err
  113. }
  114. pr.Issue = issue
  115. return
  116. }
  117. func (issue *Issue) loadLabels(e Engine) (err error) {
  118. if issue.Labels == nil {
  119. issue.Labels, err = getLabelsByIssueID(e, issue.ID)
  120. if err != nil {
  121. return fmt.Errorf("getLabelsByIssueID [%d]: %v", issue.ID, err)
  122. }
  123. }
  124. return nil
  125. }
  126. // LoadPoster loads poster
  127. func (issue *Issue) LoadPoster() error {
  128. return issue.loadPoster(x)
  129. }
  130. func (issue *Issue) loadPoster(e Engine) (err error) {
  131. if issue.Poster == nil {
  132. issue.Poster, err = getUserByID(e, issue.PosterID)
  133. if err != nil {
  134. issue.PosterID = -1
  135. issue.Poster = NewGhostUser()
  136. if !IsErrUserNotExist(err) {
  137. return fmt.Errorf("getUserByID.(poster) [%d]: %v", issue.PosterID, err)
  138. }
  139. err = nil
  140. return
  141. }
  142. }
  143. return
  144. }
  145. func (issue *Issue) loadPullRequest(e Engine) (err error) {
  146. if issue.IsPull && issue.PullRequest == nil {
  147. issue.PullRequest, err = getPullRequestByIssueID(e, issue.ID)
  148. if err != nil {
  149. if IsErrPullRequestNotExist(err) {
  150. return err
  151. }
  152. return fmt.Errorf("getPullRequestByIssueID [%d]: %v", issue.ID, err)
  153. }
  154. issue.PullRequest.Issue = issue
  155. }
  156. return nil
  157. }
  158. // LoadPullRequest loads pull request info
  159. func (issue *Issue) LoadPullRequest() error {
  160. return issue.loadPullRequest(x)
  161. }
  162. func (issue *Issue) loadComments(e Engine) (err error) {
  163. return issue.loadCommentsByType(e, CommentTypeUnknown)
  164. }
  165. // LoadDiscussComments loads discuss comments
  166. func (issue *Issue) LoadDiscussComments() error {
  167. return issue.loadCommentsByType(x, CommentTypeComment)
  168. }
  169. func (issue *Issue) loadCommentsByType(e Engine, tp CommentType) (err error) {
  170. if issue.Comments != nil {
  171. return nil
  172. }
  173. issue.Comments, err = findComments(e, FindCommentsOptions{
  174. IssueID: issue.ID,
  175. Type: tp,
  176. })
  177. return err
  178. }
  179. func (issue *Issue) loadReactions(e Engine) (err error) {
  180. if issue.Reactions != nil {
  181. return nil
  182. }
  183. reactions, err := findReactions(e, FindReactionsOptions{
  184. IssueID: issue.ID,
  185. })
  186. if err != nil {
  187. return err
  188. }
  189. // Load reaction user data
  190. if _, err := ReactionList(reactions).loadUsers(e); err != nil {
  191. return err
  192. }
  193. // Cache comments to map
  194. comments := make(map[int64]*Comment)
  195. for _, comment := range issue.Comments {
  196. comments[comment.ID] = comment
  197. }
  198. // Add reactions either to issue or comment
  199. for _, react := range reactions {
  200. if react.CommentID == 0 {
  201. issue.Reactions = append(issue.Reactions, react)
  202. } else if comment, ok := comments[react.CommentID]; ok {
  203. comment.Reactions = append(comment.Reactions, react)
  204. }
  205. }
  206. return nil
  207. }
  208. func (issue *Issue) loadAttributes(e Engine) (err error) {
  209. if err = issue.loadRepo(e); err != nil {
  210. return
  211. }
  212. if err = issue.loadPoster(e); err != nil {
  213. return
  214. }
  215. if err = issue.loadLabels(e); err != nil {
  216. return
  217. }
  218. if issue.Milestone == nil && issue.MilestoneID > 0 {
  219. issue.Milestone, err = getMilestoneByRepoID(e, issue.RepoID, issue.MilestoneID)
  220. if err != nil && !IsErrMilestoneNotExist(err) {
  221. return fmt.Errorf("getMilestoneByRepoID [repo_id: %d, milestone_id: %d]: %v", issue.RepoID, issue.MilestoneID, err)
  222. }
  223. }
  224. if err = issue.loadAssignees(e); err != nil {
  225. return
  226. }
  227. if err = issue.loadPullRequest(e); err != nil && !IsErrPullRequestNotExist(err) {
  228. // It is possible pull request is not yet created.
  229. return err
  230. }
  231. if issue.Attachments == nil {
  232. issue.Attachments, err = getAttachmentsByIssueID(e, issue.ID)
  233. if err != nil {
  234. return fmt.Errorf("getAttachmentsByIssueID [%d]: %v", issue.ID, err)
  235. }
  236. }
  237. if err = issue.loadComments(e); err != nil {
  238. return err
  239. }
  240. if err = CommentList(issue.Comments).loadAttributes(e); err != nil {
  241. return err
  242. }
  243. if issue.isTimetrackerEnabled(e) {
  244. if err = issue.loadTotalTimes(e); err != nil {
  245. return err
  246. }
  247. }
  248. return issue.loadReactions(e)
  249. }
  250. // LoadAttributes loads the attribute of this issue.
  251. func (issue *Issue) LoadAttributes() error {
  252. return issue.loadAttributes(x)
  253. }
  254. // GetIsRead load the `IsRead` field of the issue
  255. func (issue *Issue) GetIsRead(userID int64) error {
  256. issueUser := &IssueUser{IssueID: issue.ID, UID: userID}
  257. if has, err := x.Get(issueUser); err != nil {
  258. return err
  259. } else if !has {
  260. issue.IsRead = false
  261. return nil
  262. }
  263. issue.IsRead = issueUser.IsRead
  264. return nil
  265. }
  266. // APIURL returns the absolute APIURL to this issue.
  267. func (issue *Issue) APIURL() string {
  268. return issue.Repo.APIURL() + "/" + path.Join("issues", fmt.Sprint(issue.Index))
  269. }
  270. // HTMLURL returns the absolute URL to this issue.
  271. func (issue *Issue) HTMLURL() string {
  272. var path string
  273. if issue.IsPull {
  274. path = "pulls"
  275. } else {
  276. path = "issues"
  277. }
  278. return fmt.Sprintf("%s/%s/%d", issue.Repo.HTMLURL(), path, issue.Index)
  279. }
  280. // DiffURL returns the absolute URL to this diff
  281. func (issue *Issue) DiffURL() string {
  282. if issue.IsPull {
  283. return fmt.Sprintf("%s/pulls/%d.diff", issue.Repo.HTMLURL(), issue.Index)
  284. }
  285. return ""
  286. }
  287. // PatchURL returns the absolute URL to this patch
  288. func (issue *Issue) PatchURL() string {
  289. if issue.IsPull {
  290. return fmt.Sprintf("%s/pulls/%d.patch", issue.Repo.HTMLURL(), issue.Index)
  291. }
  292. return ""
  293. }
  294. // State returns string representation of issue status.
  295. func (issue *Issue) State() api.StateType {
  296. if issue.IsClosed {
  297. return api.StateClosed
  298. }
  299. return api.StateOpen
  300. }
  301. // APIFormat assumes some fields assigned with values:
  302. // Required - Poster, Labels,
  303. // Optional - Milestone, Assignee, PullRequest
  304. func (issue *Issue) APIFormat() *api.Issue {
  305. return issue.apiFormat(x)
  306. }
  307. func (issue *Issue) apiFormat(e Engine) *api.Issue {
  308. issue.loadLabels(e)
  309. apiLabels := make([]*api.Label, len(issue.Labels))
  310. for i := range issue.Labels {
  311. apiLabels[i] = issue.Labels[i].APIFormat()
  312. }
  313. issue.loadPoster(e)
  314. issue.loadRepo(e)
  315. apiIssue := &api.Issue{
  316. ID: issue.ID,
  317. URL: issue.APIURL(),
  318. Index: issue.Index,
  319. Poster: issue.Poster.APIFormat(),
  320. Title: issue.Title,
  321. Body: issue.Content,
  322. Labels: apiLabels,
  323. State: issue.State(),
  324. Comments: issue.NumComments,
  325. Created: issue.CreatedUnix.AsTime(),
  326. Updated: issue.UpdatedUnix.AsTime(),
  327. }
  328. if issue.ClosedUnix != 0 {
  329. apiIssue.Closed = issue.ClosedUnix.AsTimePtr()
  330. }
  331. if issue.Milestone != nil {
  332. apiIssue.Milestone = issue.Milestone.APIFormat()
  333. }
  334. issue.loadAssignees(e)
  335. if len(issue.Assignees) > 0 {
  336. for _, assignee := range issue.Assignees {
  337. apiIssue.Assignees = append(apiIssue.Assignees, assignee.APIFormat())
  338. }
  339. apiIssue.Assignee = issue.Assignees[0].APIFormat() // For compatibility, we're keeping the first assignee as `apiIssue.Assignee`
  340. }
  341. if issue.IsPull {
  342. issue.loadPullRequest(e)
  343. apiIssue.PullRequest = &api.PullRequestMeta{
  344. HasMerged: issue.PullRequest.HasMerged,
  345. }
  346. if issue.PullRequest.HasMerged {
  347. apiIssue.PullRequest.Merged = issue.PullRequest.MergedUnix.AsTimePtr()
  348. }
  349. }
  350. if issue.DeadlineUnix != 0 {
  351. apiIssue.Deadline = issue.DeadlineUnix.AsTimePtr()
  352. }
  353. return apiIssue
  354. }
  355. // HashTag returns unique hash tag for issue.
  356. func (issue *Issue) HashTag() string {
  357. return "issue-" + com.ToStr(issue.ID)
  358. }
  359. // IsPoster returns true if given user by ID is the poster.
  360. func (issue *Issue) IsPoster(uid int64) bool {
  361. return issue.PosterID == uid
  362. }
  363. func (issue *Issue) hasLabel(e Engine, labelID int64) bool {
  364. return hasIssueLabel(e, issue.ID, labelID)
  365. }
  366. // HasLabel returns true if issue has been labeled by given ID.
  367. func (issue *Issue) HasLabel(labelID int64) bool {
  368. return issue.hasLabel(x, labelID)
  369. }
  370. func (issue *Issue) sendLabelUpdatedWebhook(doer *User) {
  371. var err error
  372. if err = issue.loadRepo(x); err != nil {
  373. log.Error("loadRepo: %v", err)
  374. return
  375. }
  376. if err = issue.loadPoster(x); err != nil {
  377. log.Error("loadPoster: %v", err)
  378. return
  379. }
  380. mode, _ := AccessLevel(issue.Poster, issue.Repo)
  381. if issue.IsPull {
  382. if err = issue.loadPullRequest(x); err != nil {
  383. log.Error("loadPullRequest: %v", err)
  384. return
  385. }
  386. if err = issue.PullRequest.LoadIssue(); err != nil {
  387. log.Error("LoadIssue: %v", err)
  388. return
  389. }
  390. err = PrepareWebhooks(issue.Repo, HookEventPullRequest, &api.PullRequestPayload{
  391. Action: api.HookIssueLabelUpdated,
  392. Index: issue.Index,
  393. PullRequest: issue.PullRequest.APIFormat(),
  394. Repository: issue.Repo.APIFormat(AccessModeNone),
  395. Sender: doer.APIFormat(),
  396. })
  397. } else {
  398. err = PrepareWebhooks(issue.Repo, HookEventIssues, &api.IssuePayload{
  399. Action: api.HookIssueLabelUpdated,
  400. Index: issue.Index,
  401. Issue: issue.APIFormat(),
  402. Repository: issue.Repo.APIFormat(mode),
  403. Sender: doer.APIFormat(),
  404. })
  405. }
  406. if err != nil {
  407. log.Error("PrepareWebhooks [is_pull: %v]: %v", issue.IsPull, err)
  408. } else {
  409. go HookQueue.Add(issue.RepoID)
  410. }
  411. }
  412. // ReplyReference returns tokenized address to use for email reply headers
  413. func (issue *Issue) ReplyReference() string {
  414. var path string
  415. if issue.IsPull {
  416. path = "pulls"
  417. } else {
  418. path = "issues"
  419. }
  420. return fmt.Sprintf("%s/%s/%d@%s", issue.Repo.FullName(), path, issue.Index, setting.Domain)
  421. }
  422. func (issue *Issue) addLabel(e *xorm.Session, label *Label, doer *User) error {
  423. return newIssueLabel(e, issue, label, doer)
  424. }
  425. // AddLabel adds a new label to the issue.
  426. func (issue *Issue) AddLabel(doer *User, label *Label) error {
  427. if err := NewIssueLabel(issue, label, doer); err != nil {
  428. return err
  429. }
  430. issue.sendLabelUpdatedWebhook(doer)
  431. return nil
  432. }
  433. func (issue *Issue) addLabels(e *xorm.Session, labels []*Label, doer *User) error {
  434. return newIssueLabels(e, issue, labels, doer)
  435. }
  436. // AddLabels adds a list of new labels to the issue.
  437. func (issue *Issue) AddLabels(doer *User, labels []*Label) error {
  438. if err := NewIssueLabels(issue, labels, doer); err != nil {
  439. return err
  440. }
  441. issue.sendLabelUpdatedWebhook(doer)
  442. return nil
  443. }
  444. func (issue *Issue) getLabels(e Engine) (err error) {
  445. if len(issue.Labels) > 0 {
  446. return nil
  447. }
  448. issue.Labels, err = getLabelsByIssueID(e, issue.ID)
  449. if err != nil {
  450. return fmt.Errorf("getLabelsByIssueID: %v", err)
  451. }
  452. return nil
  453. }
  454. func (issue *Issue) removeLabel(e *xorm.Session, doer *User, label *Label) error {
  455. return deleteIssueLabel(e, issue, label, doer)
  456. }
  457. // RemoveLabel removes a label from issue by given ID.
  458. func (issue *Issue) RemoveLabel(doer *User, label *Label) error {
  459. if err := issue.loadRepo(x); err != nil {
  460. return err
  461. }
  462. perm, err := GetUserRepoPermission(issue.Repo, doer)
  463. if err != nil {
  464. return err
  465. }
  466. if !perm.CanWriteIssuesOrPulls(issue.IsPull) {
  467. return ErrLabelNotExist{}
  468. }
  469. if err := DeleteIssueLabel(issue, label, doer); err != nil {
  470. return err
  471. }
  472. issue.sendLabelUpdatedWebhook(doer)
  473. return nil
  474. }
  475. func (issue *Issue) clearLabels(e *xorm.Session, doer *User) (err error) {
  476. if err = issue.getLabels(e); err != nil {
  477. return fmt.Errorf("getLabels: %v", err)
  478. }
  479. for i := range issue.Labels {
  480. if err = issue.removeLabel(e, doer, issue.Labels[i]); err != nil {
  481. return fmt.Errorf("removeLabel: %v", err)
  482. }
  483. }
  484. return nil
  485. }
  486. // ClearLabels removes all issue labels as the given user.
  487. // Triggers appropriate WebHooks, if any.
  488. func (issue *Issue) ClearLabels(doer *User) (err error) {
  489. sess := x.NewSession()
  490. defer sess.Close()
  491. if err = sess.Begin(); err != nil {
  492. return err
  493. }
  494. if err := issue.loadRepo(sess); err != nil {
  495. return err
  496. } else if err = issue.loadPullRequest(sess); err != nil {
  497. return err
  498. }
  499. perm, err := getUserRepoPermission(sess, issue.Repo, doer)
  500. if err != nil {
  501. return err
  502. }
  503. if !perm.CanWriteIssuesOrPulls(issue.IsPull) {
  504. return ErrLabelNotExist{}
  505. }
  506. if err = issue.clearLabels(sess, doer); err != nil {
  507. return err
  508. }
  509. if err = sess.Commit(); err != nil {
  510. return fmt.Errorf("Commit: %v", err)
  511. }
  512. if err = issue.loadPoster(x); err != nil {
  513. return fmt.Errorf("loadPoster: %v", err)
  514. }
  515. mode, _ := AccessLevel(issue.Poster, issue.Repo)
  516. if issue.IsPull {
  517. err = issue.PullRequest.LoadIssue()
  518. if err != nil {
  519. log.Error("LoadIssue: %v", err)
  520. return
  521. }
  522. err = PrepareWebhooks(issue.Repo, HookEventPullRequest, &api.PullRequestPayload{
  523. Action: api.HookIssueLabelCleared,
  524. Index: issue.Index,
  525. PullRequest: issue.PullRequest.APIFormat(),
  526. Repository: issue.Repo.APIFormat(mode),
  527. Sender: doer.APIFormat(),
  528. })
  529. } else {
  530. err = PrepareWebhooks(issue.Repo, HookEventIssues, &api.IssuePayload{
  531. Action: api.HookIssueLabelCleared,
  532. Index: issue.Index,
  533. Issue: issue.APIFormat(),
  534. Repository: issue.Repo.APIFormat(mode),
  535. Sender: doer.APIFormat(),
  536. })
  537. }
  538. if err != nil {
  539. log.Error("PrepareWebhooks [is_pull: %v]: %v", issue.IsPull, err)
  540. } else {
  541. go HookQueue.Add(issue.RepoID)
  542. }
  543. return nil
  544. }
  545. type labelSorter []*Label
  546. func (ts labelSorter) Len() int {
  547. return len([]*Label(ts))
  548. }
  549. func (ts labelSorter) Less(i, j int) bool {
  550. return []*Label(ts)[i].ID < []*Label(ts)[j].ID
  551. }
  552. func (ts labelSorter) Swap(i, j int) {
  553. []*Label(ts)[i], []*Label(ts)[j] = []*Label(ts)[j], []*Label(ts)[i]
  554. }
  555. // ReplaceLabels removes all current labels and add new labels to the issue.
  556. // Triggers appropriate WebHooks, if any.
  557. func (issue *Issue) ReplaceLabels(labels []*Label, doer *User) (err error) {
  558. sess := x.NewSession()
  559. defer sess.Close()
  560. if err = sess.Begin(); err != nil {
  561. return err
  562. }
  563. if err = issue.loadLabels(sess); err != nil {
  564. return err
  565. }
  566. sort.Sort(labelSorter(labels))
  567. sort.Sort(labelSorter(issue.Labels))
  568. var toAdd, toRemove []*Label
  569. addIndex, removeIndex := 0, 0
  570. for addIndex < len(labels) && removeIndex < len(issue.Labels) {
  571. addLabel := labels[addIndex]
  572. removeLabel := issue.Labels[removeIndex]
  573. if addLabel.ID == removeLabel.ID {
  574. addIndex++
  575. removeIndex++
  576. } else if addLabel.ID < removeLabel.ID {
  577. toAdd = append(toAdd, addLabel)
  578. addIndex++
  579. } else {
  580. toRemove = append(toRemove, removeLabel)
  581. removeIndex++
  582. }
  583. }
  584. toAdd = append(toAdd, labels[addIndex:]...)
  585. toRemove = append(toRemove, issue.Labels[removeIndex:]...)
  586. if len(toAdd) > 0 {
  587. if err = issue.addLabels(sess, toAdd, doer); err != nil {
  588. return fmt.Errorf("addLabels: %v", err)
  589. }
  590. }
  591. for _, l := range toRemove {
  592. if err = issue.removeLabel(sess, doer, l); err != nil {
  593. return fmt.Errorf("removeLabel: %v", err)
  594. }
  595. }
  596. return sess.Commit()
  597. }
  598. // ReadBy sets issue to be read by given user.
  599. func (issue *Issue) ReadBy(userID int64) error {
  600. if err := UpdateIssueUserByRead(userID, issue.ID); err != nil {
  601. return err
  602. }
  603. return setNotificationStatusReadIfUnread(x, userID, issue.ID)
  604. }
  605. func updateIssueCols(e Engine, issue *Issue, cols ...string) error {
  606. if _, err := e.ID(issue.ID).Cols(cols...).Update(issue); err != nil {
  607. return err
  608. }
  609. return nil
  610. }
  611. // UpdateIssueCols only updates values of specific columns for given issue.
  612. func UpdateIssueCols(issue *Issue, cols ...string) error {
  613. return updateIssueCols(x, issue, cols...)
  614. }
  615. func (issue *Issue) changeStatus(e *xorm.Session, doer *User, isClosed bool) (err error) {
  616. // Reload the issue
  617. currentIssue, err := getIssueByID(e, issue.ID)
  618. if err != nil {
  619. return err
  620. }
  621. // Nothing should be performed if current status is same as target status
  622. if currentIssue.IsClosed == isClosed {
  623. return nil
  624. }
  625. // Check for open dependencies
  626. if isClosed && issue.Repo.isDependenciesEnabled(e) {
  627. // only check if dependencies are enabled and we're about to close an issue, otherwise reopening an issue would fail when there are unsatisfied dependencies
  628. noDeps, err := issueNoDependenciesLeft(e, issue)
  629. if err != nil {
  630. return err
  631. }
  632. if !noDeps {
  633. return ErrDependenciesLeft{issue.ID}
  634. }
  635. }
  636. issue.IsClosed = isClosed
  637. if isClosed {
  638. issue.ClosedUnix = util.TimeStampNow()
  639. } else {
  640. issue.ClosedUnix = 0
  641. }
  642. if err = updateIssueCols(e, issue, "is_closed", "closed_unix"); err != nil {
  643. return err
  644. }
  645. // Update issue count of labels
  646. if err = issue.getLabels(e); err != nil {
  647. return err
  648. }
  649. for idx := range issue.Labels {
  650. if issue.IsClosed {
  651. issue.Labels[idx].NumClosedIssues++
  652. } else {
  653. issue.Labels[idx].NumClosedIssues--
  654. }
  655. if err = updateLabel(e, issue.Labels[idx]); err != nil {
  656. return err
  657. }
  658. }
  659. // Update issue count of milestone
  660. if err = changeMilestoneIssueStats(e, issue); err != nil {
  661. return err
  662. }
  663. // New action comment
  664. if _, err = createStatusComment(e, doer, issue); err != nil {
  665. return err
  666. }
  667. return nil
  668. }
  669. // ChangeStatus changes issue status to open or closed.
  670. func (issue *Issue) ChangeStatus(doer *User, isClosed bool) (err error) {
  671. sess := x.NewSession()
  672. defer sess.Close()
  673. if err = sess.Begin(); err != nil {
  674. return err
  675. }
  676. if err = issue.loadRepo(sess); err != nil {
  677. return err
  678. }
  679. if err = issue.loadPoster(sess); err != nil {
  680. return err
  681. }
  682. if err = issue.changeStatus(sess, doer, isClosed); err != nil {
  683. return err
  684. }
  685. if err = sess.Commit(); err != nil {
  686. return fmt.Errorf("Commit: %v", err)
  687. }
  688. sess.Close()
  689. mode, _ := AccessLevel(issue.Poster, issue.Repo)
  690. if issue.IsPull {
  691. if err = issue.loadPullRequest(sess); err != nil {
  692. return err
  693. }
  694. // Merge pull request calls issue.changeStatus so we need to handle separately.
  695. apiPullRequest := &api.PullRequestPayload{
  696. Index: issue.Index,
  697. PullRequest: issue.PullRequest.APIFormat(),
  698. Repository: issue.Repo.APIFormat(mode),
  699. Sender: doer.APIFormat(),
  700. }
  701. if isClosed {
  702. apiPullRequest.Action = api.HookIssueClosed
  703. } else {
  704. apiPullRequest.Action = api.HookIssueReOpened
  705. }
  706. err = PrepareWebhooks(issue.Repo, HookEventPullRequest, apiPullRequest)
  707. } else {
  708. apiIssue := &api.IssuePayload{
  709. Index: issue.Index,
  710. Issue: issue.APIFormat(),
  711. Repository: issue.Repo.APIFormat(mode),
  712. Sender: doer.APIFormat(),
  713. }
  714. if isClosed {
  715. apiIssue.Action = api.HookIssueClosed
  716. } else {
  717. apiIssue.Action = api.HookIssueReOpened
  718. }
  719. err = PrepareWebhooks(issue.Repo, HookEventIssues, apiIssue)
  720. }
  721. if err != nil {
  722. log.Error("PrepareWebhooks [is_pull: %v, is_closed: %v]: %v", issue.IsPull, isClosed, err)
  723. } else {
  724. go HookQueue.Add(issue.Repo.ID)
  725. }
  726. return nil
  727. }
  728. // ChangeTitle changes the title of this issue, as the given user.
  729. func (issue *Issue) ChangeTitle(doer *User, title string) (err error) {
  730. oldTitle := issue.Title
  731. issue.Title = title
  732. sess := x.NewSession()
  733. defer sess.Close()
  734. if err = sess.Begin(); err != nil {
  735. return err
  736. }
  737. if err = updateIssueCols(sess, issue, "name"); err != nil {
  738. return fmt.Errorf("updateIssueCols: %v", err)
  739. }
  740. if err = issue.loadRepo(sess); err != nil {
  741. return fmt.Errorf("loadRepo: %v", err)
  742. }
  743. if _, err = createChangeTitleComment(sess, doer, issue.Repo, issue, oldTitle, title); err != nil {
  744. return fmt.Errorf("createChangeTitleComment: %v", err)
  745. }
  746. if err = sess.Commit(); err != nil {
  747. return err
  748. }
  749. mode, _ := AccessLevel(issue.Poster, issue.Repo)
  750. if issue.IsPull {
  751. if err = issue.loadPullRequest(sess); err != nil {
  752. return fmt.Errorf("loadPullRequest: %v", err)
  753. }
  754. issue.PullRequest.Issue = issue
  755. err = PrepareWebhooks(issue.Repo, HookEventPullRequest, &api.PullRequestPayload{
  756. Action: api.HookIssueEdited,
  757. Index: issue.Index,
  758. Changes: &api.ChangesPayload{
  759. Title: &api.ChangesFromPayload{
  760. From: oldTitle,
  761. },
  762. },
  763. PullRequest: issue.PullRequest.APIFormat(),
  764. Repository: issue.Repo.APIFormat(mode),
  765. Sender: doer.APIFormat(),
  766. })
  767. } else {
  768. err = PrepareWebhooks(issue.Repo, HookEventIssues, &api.IssuePayload{
  769. Action: api.HookIssueEdited,
  770. Index: issue.Index,
  771. Changes: &api.ChangesPayload{
  772. Title: &api.ChangesFromPayload{
  773. From: oldTitle,
  774. },
  775. },
  776. Issue: issue.APIFormat(),
  777. Repository: issue.Repo.APIFormat(mode),
  778. Sender: issue.Poster.APIFormat(),
  779. })
  780. }
  781. if err != nil {
  782. log.Error("PrepareWebhooks [is_pull: %v]: %v", issue.IsPull, err)
  783. } else {
  784. go HookQueue.Add(issue.RepoID)
  785. }
  786. return nil
  787. }
  788. // AddDeletePRBranchComment adds delete branch comment for pull request issue
  789. func AddDeletePRBranchComment(doer *User, repo *Repository, issueID int64, branchName string) error {
  790. issue, err := getIssueByID(x, issueID)
  791. if err != nil {
  792. return err
  793. }
  794. sess := x.NewSession()
  795. defer sess.Close()
  796. if err := sess.Begin(); err != nil {
  797. return err
  798. }
  799. if _, err := createDeleteBranchComment(sess, doer, repo, issue, branchName); err != nil {
  800. return err
  801. }
  802. return sess.Commit()
  803. }
  804. // ChangeContent changes issue content, as the given user.
  805. func (issue *Issue) ChangeContent(doer *User, content string) (err error) {
  806. oldContent := issue.Content
  807. issue.Content = content
  808. if err = UpdateIssueCols(issue, "content"); err != nil {
  809. return fmt.Errorf("UpdateIssueCols: %v", err)
  810. }
  811. mode, _ := AccessLevel(issue.Poster, issue.Repo)
  812. if issue.IsPull {
  813. issue.PullRequest.Issue = issue
  814. err = PrepareWebhooks(issue.Repo, HookEventPullRequest, &api.PullRequestPayload{
  815. Action: api.HookIssueEdited,
  816. Index: issue.Index,
  817. Changes: &api.ChangesPayload{
  818. Body: &api.ChangesFromPayload{
  819. From: oldContent,
  820. },
  821. },
  822. PullRequest: issue.PullRequest.APIFormat(),
  823. Repository: issue.Repo.APIFormat(mode),
  824. Sender: doer.APIFormat(),
  825. })
  826. } else {
  827. err = PrepareWebhooks(issue.Repo, HookEventIssues, &api.IssuePayload{
  828. Action: api.HookIssueEdited,
  829. Index: issue.Index,
  830. Changes: &api.ChangesPayload{
  831. Body: &api.ChangesFromPayload{
  832. From: oldContent,
  833. },
  834. },
  835. Issue: issue.APIFormat(),
  836. Repository: issue.Repo.APIFormat(mode),
  837. Sender: doer.APIFormat(),
  838. })
  839. }
  840. if err != nil {
  841. log.Error("PrepareWebhooks [is_pull: %v]: %v", issue.IsPull, err)
  842. } else {
  843. go HookQueue.Add(issue.RepoID)
  844. }
  845. return nil
  846. }
  847. // GetTasks returns the amount of tasks in the issues content
  848. func (issue *Issue) GetTasks() int {
  849. return len(issueTasksPat.FindAllStringIndex(issue.Content, -1))
  850. }
  851. // GetTasksDone returns the amount of completed tasks in the issues content
  852. func (issue *Issue) GetTasksDone() int {
  853. return len(issueTasksDonePat.FindAllStringIndex(issue.Content, -1))
  854. }
  855. // GetLastEventTimestamp returns the last user visible event timestamp, either the creation of this issue or the close.
  856. func (issue *Issue) GetLastEventTimestamp() util.TimeStamp {
  857. if issue.IsClosed {
  858. return issue.ClosedUnix
  859. }
  860. return issue.CreatedUnix
  861. }
  862. // GetLastEventLabel returns the localization label for the current issue.
  863. func (issue *Issue) GetLastEventLabel() string {
  864. if issue.IsClosed {
  865. if issue.IsPull && issue.PullRequest.HasMerged {
  866. return "repo.pulls.merged_by"
  867. }
  868. return "repo.issues.closed_by"
  869. }
  870. return "repo.issues.opened_by"
  871. }
  872. // GetLastEventLabelFake returns the localization label for the current issue without providing a link in the username.
  873. func (issue *Issue) GetLastEventLabelFake() string {
  874. if issue.IsClosed {
  875. if issue.IsPull && issue.PullRequest.HasMerged {
  876. return "repo.pulls.merged_by_fake"
  877. }
  878. return "repo.issues.closed_by_fake"
  879. }
  880. return "repo.issues.opened_by_fake"
  881. }
  882. // NewIssueOptions represents the options of a new issue.
  883. type NewIssueOptions struct {
  884. Repo *Repository
  885. Issue *Issue
  886. LabelIDs []int64
  887. AssigneeIDs []int64
  888. Attachments []string // In UUID format.
  889. IsPull bool
  890. }
  891. // GetMaxIndexOfIssue returns the max index on issue
  892. func GetMaxIndexOfIssue(repoID int64) (int64, error) {
  893. return getMaxIndexOfIssue(x, repoID)
  894. }
  895. func getMaxIndexOfIssue(e Engine, repoID int64) (int64, error) {
  896. var (
  897. maxIndex int64
  898. has bool
  899. err error
  900. )
  901. has, err = e.SQL("SELECT COALESCE((SELECT MAX(`index`) FROM issue WHERE repo_id = ?),0)", repoID).Get(&maxIndex)
  902. if err != nil {
  903. return 0, err
  904. } else if !has {
  905. return 0, errors.New("Retrieve Max index from issue failed")
  906. }
  907. return maxIndex, nil
  908. }
  909. func newIssue(e *xorm.Session, doer *User, opts NewIssueOptions) (err error) {
  910. opts.Issue.Title = strings.TrimSpace(opts.Issue.Title)
  911. maxIndex, err := getMaxIndexOfIssue(e, opts.Issue.RepoID)
  912. if err != nil {
  913. return err
  914. }
  915. opts.Issue.Index = maxIndex + 1
  916. if opts.Issue.MilestoneID > 0 {
  917. milestone, err := getMilestoneByRepoID(e, opts.Issue.RepoID, opts.Issue.MilestoneID)
  918. if err != nil && !IsErrMilestoneNotExist(err) {
  919. return fmt.Errorf("getMilestoneByID: %v", err)
  920. }
  921. // Assume milestone is invalid and drop silently.
  922. opts.Issue.MilestoneID = 0
  923. if milestone != nil {
  924. opts.Issue.MilestoneID = milestone.ID
  925. opts.Issue.Milestone = milestone
  926. }
  927. }
  928. // Keep the old assignee id thingy for compatibility reasons
  929. if opts.Issue.AssigneeID > 0 {
  930. isAdded := false
  931. // Check if the user has already been passed to issue.AssigneeIDs, if not, add it
  932. for _, aID := range opts.AssigneeIDs {
  933. if aID == opts.Issue.AssigneeID {
  934. isAdded = true
  935. break
  936. }
  937. }
  938. if !isAdded {
  939. opts.AssigneeIDs = append(opts.AssigneeIDs, opts.Issue.AssigneeID)
  940. }
  941. }
  942. // Check for and validate assignees
  943. if len(opts.AssigneeIDs) > 0 {
  944. for _, assigneeID := range opts.AssigneeIDs {
  945. user, err := getUserByID(e, assigneeID)
  946. if err != nil {
  947. return fmt.Errorf("getUserByID [user_id: %d, repo_id: %d]: %v", assigneeID, opts.Repo.ID, err)
  948. }
  949. valid, err := canBeAssigned(e, user, opts.Repo)
  950. if err != nil {
  951. return fmt.Errorf("canBeAssigned [user_id: %d, repo_id: %d]: %v", assigneeID, opts.Repo.ID, err)
  952. }
  953. if !valid {
  954. return ErrUserDoesNotHaveAccessToRepo{UserID: assigneeID, RepoName: opts.Repo.Name}
  955. }
  956. }
  957. }
  958. // Milestone and assignee validation should happen before insert actual object.
  959. if _, err = e.Insert(opts.Issue); err != nil {
  960. return err
  961. }
  962. if opts.Issue.MilestoneID > 0 {
  963. if err = changeMilestoneAssign(e, doer, opts.Issue, -1); err != nil {
  964. return err
  965. }
  966. }
  967. // Insert the assignees
  968. for _, assigneeID := range opts.AssigneeIDs {
  969. err = opts.Issue.changeAssignee(e, doer, assigneeID, true)
  970. if err != nil {
  971. return err
  972. }
  973. }
  974. if opts.IsPull {
  975. _, err = e.Exec("UPDATE `repository` SET num_pulls = num_pulls + 1 WHERE id = ?", opts.Issue.RepoID)
  976. } else {
  977. _, err = e.Exec("UPDATE `repository` SET num_issues = num_issues + 1 WHERE id = ?", opts.Issue.RepoID)
  978. }
  979. if err != nil {
  980. return err
  981. }
  982. if len(opts.LabelIDs) > 0 {
  983. // During the session, SQLite3 driver cannot handle retrieve objects after update something.
  984. // So we have to get all needed labels first.
  985. labels := make([]*Label, 0, len(opts.LabelIDs))
  986. if err = e.In("id", opts.LabelIDs).Find(&labels); err != nil {
  987. return fmt.Errorf("find all labels [label_ids: %v]: %v", opts.LabelIDs, err)
  988. }
  989. if err = opts.Issue.loadPoster(e); err != nil {
  990. return err
  991. }
  992. for _, label := range labels {
  993. // Silently drop invalid labels.
  994. if label.RepoID != opts.Repo.ID {
  995. continue
  996. }
  997. if err = opts.Issue.addLabel(e, label, opts.Issue.Poster); err != nil {
  998. return fmt.Errorf("addLabel [id: %d]: %v", label.ID, err)
  999. }
  1000. }
  1001. }
  1002. if err = newIssueUsers(e, opts.Repo, opts.Issue); err != nil {
  1003. return err
  1004. }
  1005. if len(opts.Attachments) > 0 {
  1006. attachments, err := getAttachmentsByUUIDs(e, opts.Attachments)
  1007. if err != nil {
  1008. return fmt.Errorf("getAttachmentsByUUIDs [uuids: %v]: %v", opts.Attachments, err)
  1009. }
  1010. for i := 0; i < len(attachments); i++ {
  1011. attachments[i].IssueID = opts.Issue.ID
  1012. if _, err = e.ID(attachments[i].ID).Update(attachments[i]); err != nil {
  1013. return fmt.Errorf("update attachment [id: %d]: %v", attachments[i].ID, err)
  1014. }
  1015. }
  1016. }
  1017. return opts.Issue.loadAttributes(e)
  1018. }
  1019. // NewIssue creates new issue with labels for repository.
  1020. func NewIssue(repo *Repository, issue *Issue, labelIDs []int64, assigneeIDs []int64, uuids []string) (err error) {
  1021. sess := x.NewSession()
  1022. defer sess.Close()
  1023. if err = sess.Begin(); err != nil {
  1024. return err
  1025. }
  1026. if err = newIssue(sess, issue.Poster, NewIssueOptions{
  1027. Repo: repo,
  1028. Issue: issue,
  1029. LabelIDs: labelIDs,
  1030. Attachments: uuids,
  1031. AssigneeIDs: assigneeIDs,
  1032. }); err != nil {
  1033. if IsErrUserDoesNotHaveAccessToRepo(err) {
  1034. return err
  1035. }
  1036. return fmt.Errorf("newIssue: %v", err)
  1037. }
  1038. if err = sess.Commit(); err != nil {
  1039. return fmt.Errorf("Commit: %v", err)
  1040. }
  1041. if err = NotifyWatchers(&Action{
  1042. ActUserID: issue.Poster.ID,
  1043. ActUser: issue.Poster,
  1044. OpType: ActionCreateIssue,
  1045. Content: fmt.Sprintf("%d|%s", issue.Index, issue.Title),
  1046. RepoID: repo.ID,
  1047. Repo: repo,
  1048. IsPrivate: repo.IsPrivate,
  1049. }); err != nil {
  1050. log.Error("NotifyWatchers: %v", err)
  1051. }
  1052. mode, _ := AccessLevel(issue.Poster, issue.Repo)
  1053. if err = PrepareWebhooks(repo, HookEventIssues, &api.IssuePayload{
  1054. Action: api.HookIssueOpened,
  1055. Index: issue.Index,
  1056. Issue: issue.APIFormat(),
  1057. Repository: repo.APIFormat(mode),
  1058. Sender: issue.Poster.APIFormat(),
  1059. }); err != nil {
  1060. log.Error("PrepareWebhooks: %v", err)
  1061. } else {
  1062. go HookQueue.Add(issue.RepoID)
  1063. }
  1064. return nil
  1065. }
  1066. // GetIssueByIndex returns raw issue without loading attributes by index in a repository.
  1067. func GetIssueByIndex(repoID, index int64) (*Issue, error) {
  1068. issue := &Issue{
  1069. RepoID: repoID,
  1070. Index: index,
  1071. }
  1072. has, err := x.Get(issue)
  1073. if err != nil {
  1074. return nil, err
  1075. } else if !has {
  1076. return nil, ErrIssueNotExist{0, repoID, index}
  1077. }
  1078. return issue, nil
  1079. }
  1080. // GetIssueWithAttrsByIndex returns issue by index in a repository.
  1081. func GetIssueWithAttrsByIndex(repoID, index int64) (*Issue, error) {
  1082. issue, err := GetIssueByIndex(repoID, index)
  1083. if err != nil {
  1084. return nil, err
  1085. }
  1086. return issue, issue.LoadAttributes()
  1087. }
  1088. func getIssueByID(e Engine, id int64) (*Issue, error) {
  1089. issue := new(Issue)
  1090. has, err := e.ID(id).Get(issue)
  1091. if err != nil {
  1092. return nil, err
  1093. } else if !has {
  1094. return nil, ErrIssueNotExist{id, 0, 0}
  1095. }
  1096. return issue, nil
  1097. }
  1098. // GetIssueWithAttrsByID returns an issue with attributes by given ID.
  1099. func GetIssueWithAttrsByID(id int64) (*Issue, error) {
  1100. issue, err := getIssueByID(x, id)
  1101. if err != nil {
  1102. return nil, err
  1103. }
  1104. return issue, issue.loadAttributes(x)
  1105. }
  1106. // GetIssueByID returns an issue by given ID.
  1107. func GetIssueByID(id int64) (*Issue, error) {
  1108. return getIssueByID(x, id)
  1109. }
  1110. func getIssuesByIDs(e Engine, issueIDs []int64) ([]*Issue, error) {
  1111. issues := make([]*Issue, 0, 10)
  1112. return issues, e.In("id", issueIDs).Find(&issues)
  1113. }
  1114. func getIssueIDsByRepoID(e Engine, repoID int64) ([]int64, error) {
  1115. var ids = make([]int64, 0, 10)
  1116. err := e.Table("issue").Where("repo_id = ?", repoID).Find(&ids)
  1117. return ids, err
  1118. }
  1119. // GetIssueIDsByRepoID returns all issue ids by repo id
  1120. func GetIssueIDsByRepoID(repoID int64) ([]int64, error) {
  1121. return getIssueIDsByRepoID(x, repoID)
  1122. }
  1123. // GetIssuesByIDs return issues with the given IDs.
  1124. func GetIssuesByIDs(issueIDs []int64) ([]*Issue, error) {
  1125. return getIssuesByIDs(x, issueIDs)
  1126. }
  1127. // IssuesOptions represents options of an issue.
  1128. type IssuesOptions struct {
  1129. RepoIDs []int64 // include all repos if empty
  1130. AssigneeID int64
  1131. PosterID int64
  1132. MentionedID int64
  1133. MilestoneID int64
  1134. Page int
  1135. PageSize int
  1136. IsClosed util.OptionalBool
  1137. IsPull util.OptionalBool
  1138. LabelIDs []int64
  1139. SortType string
  1140. IssueIDs []int64
  1141. }
  1142. // sortIssuesSession sort an issues-related session based on the provided
  1143. // sortType string
  1144. func sortIssuesSession(sess *xorm.Session, sortType string) {
  1145. switch sortType {
  1146. case "oldest":
  1147. sess.Asc("issue.created_unix")
  1148. case "recentupdate":
  1149. sess.Desc("issue.updated_unix")
  1150. case "leastupdate":
  1151. sess.Asc("issue.updated_unix")
  1152. case "mostcomment":
  1153. sess.Desc("issue.num_comments")
  1154. case "leastcomment":
  1155. sess.Asc("issue.num_comments")
  1156. case "priority":
  1157. sess.Desc("issue.priority")
  1158. case "nearduedate":
  1159. sess.Asc("issue.deadline_unix")
  1160. case "farduedate":
  1161. sess.Desc("issue.deadline_unix")
  1162. default:
  1163. sess.Desc("issue.created_unix")
  1164. }
  1165. }
  1166. func (opts *IssuesOptions) setupSession(sess *xorm.Session) {
  1167. if opts.Page >= 0 && opts.PageSize > 0 {
  1168. var start int
  1169. if opts.Page == 0 {
  1170. start = 0
  1171. } else {
  1172. start = (opts.Page - 1) * opts.PageSize
  1173. }
  1174. sess.Limit(opts.PageSize, start)
  1175. }
  1176. if len(opts.IssueIDs) > 0 {
  1177. sess.In("issue.id", opts.IssueIDs)
  1178. }
  1179. if len(opts.RepoIDs) > 0 {
  1180. // In case repository IDs are provided but actually no repository has issue.
  1181. sess.In("issue.repo_id", opts.RepoIDs)
  1182. }
  1183. switch opts.IsClosed {
  1184. case util.OptionalBoolTrue:
  1185. sess.And("issue.is_closed=?", true)
  1186. case util.OptionalBoolFalse:
  1187. sess.And("issue.is_closed=?", false)
  1188. }
  1189. if opts.AssigneeID > 0 {
  1190. sess.Join("INNER", "issue_assignees", "issue.id = issue_assignees.issue_id").
  1191. And("issue_assignees.assignee_id = ?", opts.AssigneeID)
  1192. }
  1193. if opts.PosterID > 0 {
  1194. sess.And("issue.poster_id=?", opts.PosterID)
  1195. }
  1196. if opts.MentionedID > 0 {
  1197. sess.Join("INNER", "issue_user", "issue.id = issue_user.issue_id").
  1198. And("issue_user.is_mentioned = ?", true).
  1199. And("issue_user.uid = ?", opts.MentionedID)
  1200. }
  1201. if opts.MilestoneID > 0 {
  1202. sess.And("issue.milestone_id=?", opts.MilestoneID)
  1203. }
  1204. switch opts.IsPull {
  1205. case util.OptionalBoolTrue:
  1206. sess.And("issue.is_pull=?", true)
  1207. case util.OptionalBoolFalse:
  1208. sess.And("issue.is_pull=?", false)
  1209. }
  1210. if opts.LabelIDs != nil {
  1211. for i, labelID := range opts.LabelIDs {
  1212. sess.Join("INNER", fmt.Sprintf("issue_label il%d", i),
  1213. fmt.Sprintf("issue.id = il%[1]d.issue_id AND il%[1]d.label_id = %[2]d", i, labelID))
  1214. }
  1215. }
  1216. }
  1217. // CountIssuesByRepo map from repoID to number of issues matching the options
  1218. func CountIssuesByRepo(opts *IssuesOptions) (map[int64]int64, error) {
  1219. sess := x.NewSession()
  1220. defer sess.Close()
  1221. opts.setupSession(sess)
  1222. countsSlice := make([]*struct {
  1223. RepoID int64
  1224. Count int64
  1225. }, 0, 10)
  1226. if err := sess.GroupBy("issue.repo_id").
  1227. Select("issue.repo_id AS repo_id, COUNT(*) AS count").
  1228. Table("issue").
  1229. Find(&countsSlice); err != nil {
  1230. return nil, err
  1231. }
  1232. countMap := make(map[int64]int64, len(countsSlice))
  1233. for _, c := range countsSlice {
  1234. countMap[c.RepoID] = c.Count
  1235. }
  1236. return countMap, nil
  1237. }
  1238. // Issues returns a list of issues by given conditions.
  1239. func Issues(opts *IssuesOptions) ([]*Issue, error) {
  1240. sess := x.NewSession()
  1241. defer sess.Close()
  1242. opts.setupSession(sess)
  1243. sortIssuesSession(sess, opts.SortType)
  1244. issues := make([]*Issue, 0, setting.UI.IssuePagingNum)
  1245. if err := sess.Find(&issues); err != nil {
  1246. return nil, fmt.Errorf("Find: %v", err)
  1247. }
  1248. sess.Close()
  1249. if err := IssueList(issues).LoadAttributes(); err != nil {
  1250. return nil, fmt.Errorf("LoadAttributes: %v", err)
  1251. }
  1252. return issues, nil
  1253. }
  1254. // GetParticipantsByIssueID returns all users who are participated in comments of an issue.
  1255. func GetParticipantsByIssueID(issueID int64) ([]*User, error) {
  1256. return getParticipantsByIssueID(x, issueID)
  1257. }
  1258. func getParticipantsByIssueID(e Engine, issueID int64) ([]*User, error) {
  1259. userIDs := make([]int64, 0, 5)
  1260. if err := e.Table("comment").Cols("poster_id").
  1261. Where("`comment`.issue_id = ?", issueID).
  1262. And("`comment`.type = ?", CommentTypeComment).
  1263. And("`user`.is_active = ?", true).
  1264. And("`user`.prohibit_login = ?", false).
  1265. Join("INNER", "`user`", "`user`.id = `comment`.poster_id").
  1266. Distinct("poster_id").
  1267. Find(&userIDs); err != nil {
  1268. return nil, fmt.Errorf("get poster IDs: %v", err)
  1269. }
  1270. if len(userIDs) == 0 {
  1271. return nil, nil
  1272. }
  1273. users := make([]*User, 0, len(userIDs))
  1274. return users, e.In("id", userIDs).Find(&users)
  1275. }
  1276. // UpdateIssueMentions extracts mentioned people from content and
  1277. // updates issue-user relations for them.
  1278. func UpdateIssueMentions(e Engine, issueID int64, mentions []string) error {
  1279. if len(mentions) == 0 {
  1280. return nil
  1281. }
  1282. for i := range mentions {
  1283. mentions[i] = strings.ToLower(mentions[i])
  1284. }
  1285. users := make([]*User, 0, len(mentions))
  1286. if err := e.In("lower_name", mentions).Asc("lower_name").Find(&users); err != nil {
  1287. return fmt.Errorf("find mentioned users: %v", err)
  1288. }
  1289. ids := make([]int64, 0, len(mentions))
  1290. for _, user := range users {
  1291. ids = append(ids, user.ID)
  1292. if !user.IsOrganization() || user.NumMembers == 0 {
  1293. continue
  1294. }
  1295. memberIDs := make([]int64, 0, user.NumMembers)
  1296. orgUsers, err := getOrgUsersByOrgID(e, user.ID)
  1297. if err != nil {
  1298. return fmt.Errorf("GetOrgUsersByOrgID [%d]: %v", user.ID, err)
  1299. }
  1300. for _, orgUser := range orgUsers {
  1301. memberIDs = append(memberIDs, orgUser.ID)
  1302. }
  1303. ids = append(ids, memberIDs...)
  1304. }
  1305. if err := UpdateIssueUsersByMentions(e, issueID, ids); err != nil {
  1306. return fmt.Errorf("UpdateIssueUsersByMentions: %v", err)
  1307. }
  1308. return nil
  1309. }
  1310. // IssueStats represents issue statistic information.
  1311. type IssueStats struct {
  1312. OpenCount, ClosedCount int64
  1313. YourRepositoriesCount int64
  1314. AssignCount int64
  1315. CreateCount int64
  1316. MentionCount int64
  1317. }
  1318. // Filter modes.
  1319. const (
  1320. FilterModeAll = iota
  1321. FilterModeAssign
  1322. FilterModeCreate
  1323. FilterModeMention
  1324. )
  1325. func parseCountResult(results []map[string][]byte) int64 {
  1326. if len(results) == 0 {
  1327. return 0
  1328. }
  1329. for _, result := range results[0] {
  1330. return com.StrTo(string(result)).MustInt64()
  1331. }
  1332. return 0
  1333. }
  1334. // IssueStatsOptions contains parameters accepted by GetIssueStats.
  1335. type IssueStatsOptions struct {
  1336. RepoID int64
  1337. Labels string
  1338. MilestoneID int64
  1339. AssigneeID int64
  1340. MentionedID int64
  1341. PosterID int64
  1342. IsPull util.OptionalBool
  1343. IssueIDs []int64
  1344. }
  1345. // GetIssueStats returns issue statistic information by given conditions.
  1346. func GetIssueStats(opts *IssueStatsOptions) (*IssueStats, error) {
  1347. stats := &IssueStats{}
  1348. countSession := func(opts *IssueStatsOptions) *xorm.Session {
  1349. sess := x.
  1350. Where("issue.repo_id = ?", opts.RepoID)
  1351. if len(opts.IssueIDs) > 0 {
  1352. sess.In("issue.id", opts.IssueIDs)
  1353. }
  1354. if len(opts.Labels) > 0 && opts.Labels != "0" {
  1355. labelIDs, err := base.StringsToInt64s(strings.Split(opts.Labels, ","))
  1356. if err != nil {
  1357. log.Warn("Malformed Labels argument: %s", opts.Labels)
  1358. } else {
  1359. for i, labelID := range labelIDs {
  1360. sess.Join("INNER", fmt.Sprintf("issue_label il%d", i),
  1361. fmt.Sprintf("issue.id = il%[1]d.issue_id AND il%[1]d.label_id = %[2]d", i, labelID))
  1362. }
  1363. }
  1364. }
  1365. if opts.MilestoneID > 0 {
  1366. sess.And("issue.milestone_id = ?", opts.MilestoneID)
  1367. }
  1368. if opts.AssigneeID > 0 {
  1369. sess.Join("INNER", "issue_assignees", "issue.id = issue_assignees.issue_id").
  1370. And("issue_assignees.assignee_id = ?", opts.AssigneeID)
  1371. }
  1372. if opts.PosterID > 0 {
  1373. sess.And("issue.poster_id = ?", opts.PosterID)
  1374. }
  1375. if opts.MentionedID > 0 {
  1376. sess.Join("INNER", "issue_user", "issue.id = issue_user.issue_id").
  1377. And("issue_user.uid = ?", opts.MentionedID).
  1378. And("issue_user.is_mentioned = ?", true)
  1379. }
  1380. switch opts.IsPull {
  1381. case util.OptionalBoolTrue:
  1382. sess.And("issue.is_pull=?", true)
  1383. case util.OptionalBoolFalse:
  1384. sess.And("issue.is_pull=?", false)
  1385. }
  1386. return sess
  1387. }
  1388. var err error
  1389. stats.OpenCount, err = countSession(opts).
  1390. And("issue.is_closed = ?", false).
  1391. Count(new(Issue))
  1392. if err != nil {
  1393. return stats, err
  1394. }
  1395. stats.ClosedCount, err = countSession(opts).
  1396. And("issue.is_closed = ?", true).
  1397. Count(new(Issue))
  1398. return stats, err
  1399. }
  1400. // UserIssueStatsOptions contains parameters accepted by GetUserIssueStats.
  1401. type UserIssueStatsOptions struct {
  1402. UserID int64
  1403. RepoID int64
  1404. UserRepoIDs []int64
  1405. FilterMode int
  1406. IsPull bool
  1407. IsClosed bool
  1408. }
  1409. // GetUserIssueStats returns issue statistic information for dashboard by given conditions.
  1410. func GetUserIssueStats(opts UserIssueStatsOptions) (*IssueStats, error) {
  1411. var err error
  1412. stats := &IssueStats{}
  1413. cond := builder.NewCond()
  1414. cond = cond.And(builder.Eq{"issue.is_pull": opts.IsPull})
  1415. if opts.RepoID > 0 {
  1416. cond = cond.And(builder.Eq{"issue.repo_id": opts.RepoID})
  1417. }
  1418. switch opts.FilterMode {
  1419. case FilterModeAll:
  1420. stats.OpenCount, err = x.Where(cond).And("is_closed = ?", false).
  1421. And(builder.In("issue.repo_id", opts.UserRepoIDs)).
  1422. Count(new(Issue))
  1423. if err != nil {
  1424. return nil, err
  1425. }
  1426. stats.ClosedCount, err = x.Where(cond).And("is_closed = ?", true).
  1427. And(builder.In("issue.repo_id", opts.UserRepoIDs)).
  1428. Count(new(Issue))
  1429. if err != nil {
  1430. return nil, err
  1431. }
  1432. case FilterModeAssign:
  1433. stats.OpenCount, err = x.Where(cond).And("is_closed = ?", false).
  1434. Join("INNER", "issue_assignees", "issue.id = issue_assignees.issue_id").
  1435. And("issue_assignees.assignee_id = ?", opts.UserID).
  1436. Count(new(Issue))
  1437. if err != nil {
  1438. return nil, err
  1439. }
  1440. stats.ClosedCount, err = x.Where(cond).And("is_closed = ?", true).
  1441. Join("INNER", "issue_assignees", "issue.id = issue_assignees.issue_id").
  1442. And("issue_assignees.assignee_id = ?", opts.UserID).
  1443. Count(new(Issue))
  1444. if err != nil {
  1445. return nil, err
  1446. }
  1447. case FilterModeCreate:
  1448. stats.OpenCount, err = x.Where(cond).And("is_closed = ?", false).
  1449. And("poster_id = ?", opts.UserID).
  1450. Count(new(Issue))
  1451. if err != nil {
  1452. return nil, err
  1453. }
  1454. stats.ClosedCount, err = x.Where(cond).And("is_closed = ?", true).
  1455. And("poster_id = ?", opts.UserID).
  1456. Count(new(Issue))
  1457. if err != nil {
  1458. return nil, err
  1459. }
  1460. }
  1461. cond = cond.And(builder.Eq{"issue.is_closed": opts.IsClosed})
  1462. stats.AssignCount, err = x.Where(cond).
  1463. Join("INNER", "issue_assignees", "issue.id = issue_assignees.issue_id").
  1464. And("issue_assignees.assignee_id = ?", opts.UserID).
  1465. Count(new(Issue))
  1466. if err != nil {
  1467. return nil, err
  1468. }
  1469. stats.CreateCount, err = x.Where(cond).
  1470. And("poster_id = ?", opts.UserID).
  1471. Count(new(Issue))
  1472. if err != nil {
  1473. return nil, err
  1474. }
  1475. stats.YourRepositoriesCount, err = x.Where(cond).
  1476. And(builder.In("issue.repo_id", opts.UserRepoIDs)).
  1477. Count(new(Issue))
  1478. if err != nil {
  1479. return nil, err
  1480. }
  1481. return stats, nil
  1482. }
  1483. // GetRepoIssueStats returns number of open and closed repository issues by given filter mode.
  1484. func GetRepoIssueStats(repoID, uid int64, filterMode int, isPull bool) (numOpen int64, numClosed int64) {
  1485. countSession := func(isClosed, isPull bool, repoID int64) *xorm.Session {
  1486. sess := x.
  1487. Where("is_closed = ?", isClosed).
  1488. And("is_pull = ?", isPull).
  1489. And("repo_id = ?", repoID)
  1490. return sess
  1491. }
  1492. openCountSession := countSession(false, isPull, repoID)
  1493. closedCountSession := countSession(true, isPull, repoID)
  1494. switch filterMode {
  1495. case FilterModeAssign:
  1496. openCountSession.Join("INNER", "issue_assignees", "issue.id = issue_assignees.issue_id").
  1497. And("issue_assignees.assignee_id = ?", uid)
  1498. closedCountSession.Join("INNER", "issue_assignees", "issue.id = issue_assignees.issue_id").
  1499. And("issue_assignees.assignee_id = ?", uid)
  1500. case FilterModeCreate:
  1501. openCountSession.And("poster_id = ?", uid)
  1502. closedCountSession.And("poster_id = ?", uid)
  1503. }
  1504. openResult, _ := openCountSession.Count(new(Issue))
  1505. closedResult, _ := closedCountSession.Count(new(Issue))
  1506. return openResult, closedResult
  1507. }
  1508. // SearchIssueIDsByKeyword search issues on database
  1509. func SearchIssueIDsByKeyword(kw string, repoID int64, limit, start int) (int64, []int64, error) {
  1510. var repoCond = builder.Eq{"repo_id": repoID}
  1511. var subQuery = builder.Select("id").From("issue").Where(repoCond)
  1512. var cond = builder.And(
  1513. repoCond,
  1514. builder.Or(
  1515. builder.Like{"name", kw},
  1516. builder.Like{"content", kw},
  1517. builder.In("id", builder.Select("issue_id").
  1518. From("comment").
  1519. Where(builder.And(
  1520. builder.Eq{"type": CommentTypeComment},
  1521. builder.In("issue_id", subQuery),
  1522. builder.Like{"content", kw},
  1523. )),
  1524. ),
  1525. ),
  1526. )
  1527. var ids = make([]int64, 0, limit)
  1528. err := x.Distinct("id").Table("issue").Where(cond).Limit(limit, start).Find(&ids)
  1529. if err != nil {
  1530. return 0, nil, err
  1531. }
  1532. total, err := x.Distinct("id").Table("issue").Where(cond).Count()
  1533. if err != nil {
  1534. return 0, nil, err
  1535. }
  1536. return total, ids, nil
  1537. }
  1538. func updateIssue(e Engine, issue *Issue) error {
  1539. _, err := e.ID(issue.ID).AllCols().Update(issue)
  1540. if err != nil {
  1541. return err
  1542. }
  1543. return nil
  1544. }
  1545. // UpdateIssue updates all fields of given issue.
  1546. func UpdateIssue(issue *Issue) error {
  1547. return updateIssue(x, issue)
  1548. }
  1549. // UpdateIssueDeadline updates an issue deadline and adds comments. Setting a deadline to 0 means deleting it.
  1550. func UpdateIssueDeadline(issue *Issue, deadlineUnix util.TimeStamp, doer *User) (err error) {
  1551. // if the deadline hasn't changed do nothing
  1552. if issue.DeadlineUnix == deadlineUnix {
  1553. return nil
  1554. }
  1555. sess := x.NewSession()
  1556. defer sess.Close()
  1557. if err := sess.Begin(); err != nil {
  1558. return err
  1559. }
  1560. // Update the deadline
  1561. if err = updateIssueCols(sess, &Issue{ID: issue.ID, DeadlineUnix: deadlineUnix}, "deadline_unix"); err != nil {
  1562. return err
  1563. }
  1564. // Make the comment
  1565. if _, err = createDeadlineComment(sess, doer, issue, deadlineUnix); err != nil {
  1566. return fmt.Errorf("createRemovedDueDateComment: %v", err)
  1567. }
  1568. return sess.Commit()
  1569. }
  1570. // Get Blocked By Dependencies, aka all issues this issue is blocked by.
  1571. func (issue *Issue) getBlockedByDependencies(e Engine) (issueDeps []*Issue, err error) {
  1572. return issueDeps, e.
  1573. Table("issue_dependency").
  1574. Select("issue.*").
  1575. Join("INNER", "issue", "issue.id = issue_dependency.dependency_id").
  1576. Where("issue_id = ?", issue.ID).
  1577. Find(&issueDeps)
  1578. }
  1579. // Get Blocking Dependencies, aka all issues this issue blocks.
  1580. func (issue *Issue) getBlockingDependencies(e Engine) (issueDeps []*Issue, err error) {
  1581. return issueDeps, e.
  1582. Table("issue_dependency").
  1583. Select("issue.*").
  1584. Join("INNER", "issue", "issue.id = issue_dependency.issue_id").
  1585. Where("dependency_id = ?", issue.ID).
  1586. Find(&issueDeps)
  1587. }
  1588. // BlockedByDependencies finds all Dependencies an issue is blocked by
  1589. func (issue *Issue) BlockedByDependencies() ([]*Issue, error) {
  1590. return issue.getBlockedByDependencies(x)
  1591. }
  1592. // BlockingDependencies returns all blocking dependencies, aka all other issues a given issue blocks
  1593. func (issue *Issue) BlockingDependencies() ([]*Issue, error) {
  1594. return issue.getBlockingDependencies(x)
  1595. }
  1596. func (issue *Issue) updateClosedNum(e Engine) (err error) {
  1597. if issue.IsPull {
  1598. _, err = e.Exec("UPDATE `repository` SET num_closed_pulls=(SELECT count(*) FROM issue WHERE repo_id=? AND is_pull=? AND is_closed=?) WHERE id=?",
  1599. issue.RepoID,
  1600. true,
  1601. true,
  1602. issue.RepoID,
  1603. )
  1604. } else {
  1605. _, err = e.Exec("UPDATE `repository` SET num_closed_issues=(SELECT count(*) FROM issue WHERE repo_id=? AND is_pull=? AND is_closed=?) WHERE id=?",
  1606. issue.RepoID,
  1607. false,
  1608. true,
  1609. issue.RepoID,
  1610. )
  1611. }
  1612. return
  1613. }