Fork to maintain patches against the official gitea for https://code.ceondo.com https://github.com/go-gitea/gitea

issue.go 43KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704
  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. if err = UpdateIssueCols(issue, "name"); err != nil {
  551. return fmt.Errorf("UpdateIssueCols: %v", err)
  552. }
  553. if issue.IsPull {
  554. issue.PullRequest.Issue = issue
  555. err = PrepareWebhooks(issue.Repo, HookEventPullRequest, &api.PullRequestPayload{
  556. Action: api.HookIssueEdited,
  557. Index: issue.Index,
  558. Changes: &api.ChangesPayload{
  559. Title: &api.ChangesFromPayload{
  560. From: oldTitle,
  561. },
  562. },
  563. PullRequest: issue.PullRequest.APIFormat(),
  564. Repository: issue.Repo.APIFormat(AccessModeNone),
  565. Sender: doer.APIFormat(),
  566. })
  567. }
  568. if err != nil {
  569. log.Error(4, "PrepareWebhooks [is_pull: %v]: %v", issue.IsPull, err)
  570. } else {
  571. go HookQueue.Add(issue.RepoID)
  572. }
  573. return nil
  574. }
  575. // ChangeContent changes issue content, as the given user.
  576. func (issue *Issue) ChangeContent(doer *User, content string) (err error) {
  577. oldContent := issue.Content
  578. issue.Content = content
  579. if err = UpdateIssueCols(issue, "content"); err != nil {
  580. return fmt.Errorf("UpdateIssueCols: %v", err)
  581. }
  582. if issue.IsPull {
  583. issue.PullRequest.Issue = issue
  584. err = PrepareWebhooks(issue.Repo, HookEventPullRequest, &api.PullRequestPayload{
  585. Action: api.HookIssueEdited,
  586. Index: issue.Index,
  587. Changes: &api.ChangesPayload{
  588. Body: &api.ChangesFromPayload{
  589. From: oldContent,
  590. },
  591. },
  592. PullRequest: issue.PullRequest.APIFormat(),
  593. Repository: issue.Repo.APIFormat(AccessModeNone),
  594. Sender: doer.APIFormat(),
  595. })
  596. }
  597. if err != nil {
  598. log.Error(4, "PrepareWebhooks [is_pull: %v]: %v", issue.IsPull, err)
  599. } else {
  600. go HookQueue.Add(issue.RepoID)
  601. }
  602. return nil
  603. }
  604. // ChangeAssignee changes the Asssignee field of this issue.
  605. func (issue *Issue) ChangeAssignee(doer *User, assigneeID int64) (err error) {
  606. var oldAssigneeID = issue.AssigneeID
  607. issue.AssigneeID = assigneeID
  608. if err = UpdateIssueUserByAssignee(issue); err != nil {
  609. return fmt.Errorf("UpdateIssueUserByAssignee: %v", err)
  610. }
  611. sess := x.NewSession()
  612. defer sess.Close()
  613. if err = issue.loadRepo(sess); err != nil {
  614. return fmt.Errorf("loadRepo: %v", err)
  615. }
  616. if _, err = createAssigneeComment(sess, doer, issue.Repo, issue, oldAssigneeID, assigneeID); err != nil {
  617. return fmt.Errorf("createAssigneeComment: %v", err)
  618. }
  619. issue.Assignee, err = GetUserByID(issue.AssigneeID)
  620. if err != nil && !IsErrUserNotExist(err) {
  621. log.Error(4, "GetUserByID [assignee_id: %v]: %v", issue.AssigneeID, err)
  622. return nil
  623. }
  624. // Error not nil here means user does not exist, which is remove assignee.
  625. isRemoveAssignee := err != nil
  626. if issue.IsPull {
  627. issue.PullRequest.Issue = issue
  628. apiPullRequest := &api.PullRequestPayload{
  629. Index: issue.Index,
  630. PullRequest: issue.PullRequest.APIFormat(),
  631. Repository: issue.Repo.APIFormat(AccessModeNone),
  632. Sender: doer.APIFormat(),
  633. }
  634. if isRemoveAssignee {
  635. apiPullRequest.Action = api.HookIssueUnassigned
  636. } else {
  637. apiPullRequest.Action = api.HookIssueAssigned
  638. }
  639. err = PrepareWebhooks(issue.Repo, HookEventPullRequest, apiPullRequest)
  640. }
  641. if err != nil {
  642. log.Error(4, "PrepareWebhooks [is_pull: %v, remove_assignee: %v]: %v", issue.IsPull, isRemoveAssignee, err)
  643. } else {
  644. go HookQueue.Add(issue.RepoID)
  645. }
  646. return nil
  647. }
  648. // NewIssueOptions represents the options of a new issue.
  649. type NewIssueOptions struct {
  650. Repo *Repository
  651. Issue *Issue
  652. LableIDs []int64
  653. Attachments []string // In UUID format.
  654. IsPull bool
  655. }
  656. func newIssue(e *xorm.Session, doer *User, opts NewIssueOptions) (err error) {
  657. opts.Issue.Title = strings.TrimSpace(opts.Issue.Title)
  658. opts.Issue.Index = opts.Repo.NextIssueIndex()
  659. if opts.Issue.MilestoneID > 0 {
  660. milestone, err := getMilestoneByRepoID(e, opts.Issue.RepoID, opts.Issue.MilestoneID)
  661. if err != nil && !IsErrMilestoneNotExist(err) {
  662. return fmt.Errorf("getMilestoneByID: %v", err)
  663. }
  664. // Assume milestone is invalid and drop silently.
  665. opts.Issue.MilestoneID = 0
  666. if milestone != nil {
  667. opts.Issue.MilestoneID = milestone.ID
  668. opts.Issue.Milestone = milestone
  669. }
  670. }
  671. if opts.Issue.AssigneeID > 0 {
  672. assignee, err := getUserByID(e, opts.Issue.AssigneeID)
  673. if err != nil && !IsErrUserNotExist(err) {
  674. return fmt.Errorf("getUserByID: %v", err)
  675. }
  676. // Assume assignee is invalid and drop silently.
  677. opts.Issue.AssigneeID = 0
  678. if assignee != nil {
  679. valid, err := hasAccess(e, assignee, opts.Repo, AccessModeWrite)
  680. if err != nil {
  681. return fmt.Errorf("hasAccess [user_id: %d, repo_id: %d]: %v", assignee.ID, opts.Repo.ID, err)
  682. }
  683. if valid {
  684. opts.Issue.AssigneeID = assignee.ID
  685. opts.Issue.Assignee = assignee
  686. }
  687. }
  688. }
  689. // Milestone and assignee validation should happen before insert actual object.
  690. if _, err = e.Insert(opts.Issue); err != nil {
  691. return err
  692. }
  693. if opts.Issue.MilestoneID > 0 {
  694. if err = changeMilestoneAssign(e, doer, opts.Issue, -1); err != nil {
  695. return err
  696. }
  697. }
  698. if opts.Issue.AssigneeID > 0 {
  699. if err = opts.Issue.loadRepo(e); err != nil {
  700. return err
  701. }
  702. if _, err = createAssigneeComment(e, doer, opts.Issue.Repo, opts.Issue, -1, opts.Issue.AssigneeID); err != nil {
  703. return err
  704. }
  705. }
  706. if opts.IsPull {
  707. _, err = e.Exec("UPDATE `repository` SET num_pulls = num_pulls + 1 WHERE id = ?", opts.Issue.RepoID)
  708. } else {
  709. _, err = e.Exec("UPDATE `repository` SET num_issues = num_issues + 1 WHERE id = ?", opts.Issue.RepoID)
  710. }
  711. if err != nil {
  712. return err
  713. }
  714. if len(opts.LableIDs) > 0 {
  715. // During the session, SQLite3 driver cannot handle retrieve objects after update something.
  716. // So we have to get all needed labels first.
  717. labels := make([]*Label, 0, len(opts.LableIDs))
  718. if err = e.In("id", opts.LableIDs).Find(&labels); err != nil {
  719. return fmt.Errorf("find all labels [label_ids: %v]: %v", opts.LableIDs, err)
  720. }
  721. if err = opts.Issue.loadPoster(e); err != nil {
  722. return err
  723. }
  724. for _, label := range labels {
  725. // Silently drop invalid labels.
  726. if label.RepoID != opts.Repo.ID {
  727. continue
  728. }
  729. if err = opts.Issue.addLabel(e, label, opts.Issue.Poster); err != nil {
  730. return fmt.Errorf("addLabel [id: %d]: %v", label.ID, err)
  731. }
  732. }
  733. }
  734. if err = newIssueUsers(e, opts.Repo, opts.Issue); err != nil {
  735. return err
  736. }
  737. UpdateIssueIndexer(opts.Issue)
  738. if len(opts.Attachments) > 0 {
  739. attachments, err := getAttachmentsByUUIDs(e, opts.Attachments)
  740. if err != nil {
  741. return fmt.Errorf("getAttachmentsByUUIDs [uuids: %v]: %v", opts.Attachments, err)
  742. }
  743. for i := 0; i < len(attachments); i++ {
  744. attachments[i].IssueID = opts.Issue.ID
  745. if _, err = e.Id(attachments[i].ID).Update(attachments[i]); err != nil {
  746. return fmt.Errorf("update attachment [id: %d]: %v", attachments[i].ID, err)
  747. }
  748. }
  749. }
  750. return opts.Issue.loadAttributes(e)
  751. }
  752. // NewIssue creates new issue with labels for repository.
  753. func NewIssue(repo *Repository, issue *Issue, labelIDs []int64, uuids []string) (err error) {
  754. sess := x.NewSession()
  755. defer sessionRelease(sess)
  756. if err = sess.Begin(); err != nil {
  757. return err
  758. }
  759. if err = newIssue(sess, issue.Poster, NewIssueOptions{
  760. Repo: repo,
  761. Issue: issue,
  762. LableIDs: labelIDs,
  763. Attachments: uuids,
  764. }); err != nil {
  765. return fmt.Errorf("newIssue: %v", err)
  766. }
  767. if err = sess.Commit(); err != nil {
  768. return fmt.Errorf("Commit: %v", err)
  769. }
  770. if err = NotifyWatchers(&Action{
  771. ActUserID: issue.Poster.ID,
  772. ActUserName: issue.Poster.Name,
  773. OpType: ActionCreateIssue,
  774. Content: fmt.Sprintf("%d|%s", issue.Index, issue.Title),
  775. RepoID: repo.ID,
  776. RepoUserName: repo.Owner.Name,
  777. RepoName: repo.Name,
  778. IsPrivate: repo.IsPrivate,
  779. }); err != nil {
  780. log.Error(4, "NotifyWatchers: %v", err)
  781. }
  782. if err = issue.MailParticipants(); err != nil {
  783. log.Error(4, "MailParticipants: %v", err)
  784. }
  785. return nil
  786. }
  787. // GetIssueByRef returns an Issue specified by a GFM reference.
  788. // See https://help.github.com/articles/writing-on-github#references for more information on the syntax.
  789. func GetIssueByRef(ref string) (*Issue, error) {
  790. n := strings.IndexByte(ref, byte('#'))
  791. if n == -1 {
  792. return nil, errMissingIssueNumber
  793. }
  794. index, err := com.StrTo(ref[n+1:]).Int64()
  795. if err != nil {
  796. return nil, err
  797. }
  798. repo, err := GetRepositoryByRef(ref[:n])
  799. if err != nil {
  800. return nil, err
  801. }
  802. issue, err := GetIssueByIndex(repo.ID, index)
  803. if err != nil {
  804. return nil, err
  805. }
  806. return issue, issue.LoadAttributes()
  807. }
  808. // GetRawIssueByIndex returns raw issue without loading attributes by index in a repository.
  809. func GetRawIssueByIndex(repoID, index int64) (*Issue, error) {
  810. issue := &Issue{
  811. RepoID: repoID,
  812. Index: index,
  813. }
  814. has, err := x.Get(issue)
  815. if err != nil {
  816. return nil, err
  817. } else if !has {
  818. return nil, ErrIssueNotExist{0, repoID, index}
  819. }
  820. return issue, nil
  821. }
  822. // GetIssueByIndex returns issue by index in a repository.
  823. func GetIssueByIndex(repoID, index int64) (*Issue, error) {
  824. issue, err := GetRawIssueByIndex(repoID, index)
  825. if err != nil {
  826. return nil, err
  827. }
  828. return issue, issue.LoadAttributes()
  829. }
  830. func getIssueByID(e Engine, id int64) (*Issue, error) {
  831. issue := new(Issue)
  832. has, err := e.Id(id).Get(issue)
  833. if err != nil {
  834. return nil, err
  835. } else if !has {
  836. return nil, ErrIssueNotExist{id, 0, 0}
  837. }
  838. return issue, issue.LoadAttributes()
  839. }
  840. // GetIssueByID returns an issue by given ID.
  841. func GetIssueByID(id int64) (*Issue, error) {
  842. return getIssueByID(x, id)
  843. }
  844. // IssuesOptions represents options of an issue.
  845. type IssuesOptions struct {
  846. RepoID int64
  847. AssigneeID int64
  848. PosterID int64
  849. MentionedID int64
  850. MilestoneID int64
  851. RepoIDs []int64
  852. Page int
  853. IsClosed util.OptionalBool
  854. IsPull util.OptionalBool
  855. Labels string
  856. SortType string
  857. IssueIDs []int64
  858. }
  859. // sortIssuesSession sort an issues-related session based on the provided
  860. // sortType string
  861. func sortIssuesSession(sess *xorm.Session, sortType string) {
  862. switch sortType {
  863. case "oldest":
  864. sess.Asc("issue.created_unix")
  865. case "recentupdate":
  866. sess.Desc("issue.updated_unix")
  867. case "leastupdate":
  868. sess.Asc("issue.updated_unix")
  869. case "mostcomment":
  870. sess.Desc("issue.num_comments")
  871. case "leastcomment":
  872. sess.Asc("issue.num_comments")
  873. case "priority":
  874. sess.Desc("issue.priority")
  875. default:
  876. sess.Desc("issue.created_unix")
  877. }
  878. }
  879. // Issues returns a list of issues by given conditions.
  880. func Issues(opts *IssuesOptions) ([]*Issue, error) {
  881. var sess *xorm.Session
  882. if opts.Page >= 0 {
  883. var start int
  884. if opts.Page == 0 {
  885. start = 0
  886. } else {
  887. start = (opts.Page - 1) * setting.UI.IssuePagingNum
  888. }
  889. sess = x.Limit(setting.UI.IssuePagingNum, start)
  890. } else {
  891. sess = x.NewSession()
  892. defer sess.Close()
  893. }
  894. if len(opts.IssueIDs) > 0 {
  895. sess.In("issue.id", opts.IssueIDs)
  896. }
  897. if opts.RepoID > 0 {
  898. sess.And("issue.repo_id=?", opts.RepoID)
  899. } else if len(opts.RepoIDs) > 0 {
  900. // In case repository IDs are provided but actually no repository has issue.
  901. sess.In("issue.repo_id", opts.RepoIDs)
  902. }
  903. switch opts.IsClosed {
  904. case util.OptionalBoolTrue:
  905. sess.And("issue.is_closed=?", true)
  906. case util.OptionalBoolFalse:
  907. sess.And("issue.is_closed=?", false)
  908. }
  909. if opts.AssigneeID > 0 {
  910. sess.And("issue.assignee_id=?", opts.AssigneeID)
  911. }
  912. if opts.PosterID > 0 {
  913. sess.And("issue.poster_id=?", opts.PosterID)
  914. }
  915. if opts.MentionedID > 0 {
  916. sess.Join("INNER", "issue_user", "issue.id = issue_user.issue_id").
  917. And("issue_user.is_mentioned = ?", true).
  918. And("issue_user.uid = ?", opts.MentionedID)
  919. }
  920. if opts.MilestoneID > 0 {
  921. sess.And("issue.milestone_id=?", opts.MilestoneID)
  922. }
  923. switch opts.IsPull {
  924. case util.OptionalBoolTrue:
  925. sess.And("issue.is_pull=?", true)
  926. case util.OptionalBoolFalse:
  927. sess.And("issue.is_pull=?", false)
  928. }
  929. sortIssuesSession(sess, opts.SortType)
  930. if len(opts.Labels) > 0 && opts.Labels != "0" {
  931. labelIDs, err := base.StringsToInt64s(strings.Split(opts.Labels, ","))
  932. if err != nil {
  933. return nil, err
  934. }
  935. if len(labelIDs) > 0 {
  936. sess.
  937. Join("INNER", "issue_label", "issue.id = issue_label.issue_id").
  938. In("issue_label.label_id", labelIDs)
  939. }
  940. }
  941. issues := make([]*Issue, 0, setting.UI.IssuePagingNum)
  942. if err := sess.Find(&issues); err != nil {
  943. return nil, fmt.Errorf("Find: %v", err)
  944. }
  945. // FIXME: use IssueList to improve performance.
  946. for i := range issues {
  947. if err := issues[i].LoadAttributes(); err != nil {
  948. return nil, fmt.Errorf("LoadAttributes [%d]: %v", issues[i].ID, err)
  949. }
  950. }
  951. return issues, nil
  952. }
  953. // UpdateIssueMentions extracts mentioned people from content and
  954. // updates issue-user relations for them.
  955. func UpdateIssueMentions(e Engine, issueID int64, mentions []string) error {
  956. if len(mentions) == 0 {
  957. return nil
  958. }
  959. for i := range mentions {
  960. mentions[i] = strings.ToLower(mentions[i])
  961. }
  962. users := make([]*User, 0, len(mentions))
  963. if err := e.In("lower_name", mentions).Asc("lower_name").Find(&users); err != nil {
  964. return fmt.Errorf("find mentioned users: %v", err)
  965. }
  966. ids := make([]int64, 0, len(mentions))
  967. for _, user := range users {
  968. ids = append(ids, user.ID)
  969. if !user.IsOrganization() || user.NumMembers == 0 {
  970. continue
  971. }
  972. memberIDs := make([]int64, 0, user.NumMembers)
  973. orgUsers, err := GetOrgUsersByOrgID(user.ID)
  974. if err != nil {
  975. return fmt.Errorf("GetOrgUsersByOrgID [%d]: %v", user.ID, err)
  976. }
  977. for _, orgUser := range orgUsers {
  978. memberIDs = append(memberIDs, orgUser.ID)
  979. }
  980. ids = append(ids, memberIDs...)
  981. }
  982. if err := UpdateIssueUsersByMentions(e, issueID, ids); err != nil {
  983. return fmt.Errorf("UpdateIssueUsersByMentions: %v", err)
  984. }
  985. return nil
  986. }
  987. // IssueStats represents issue statistic information.
  988. type IssueStats struct {
  989. OpenCount, ClosedCount int64
  990. AllCount int64
  991. AssignCount int64
  992. CreateCount int64
  993. MentionCount int64
  994. }
  995. // Filter modes.
  996. const (
  997. FilterModeAll = iota
  998. FilterModeAssign
  999. FilterModeCreate
  1000. FilterModeMention
  1001. )
  1002. func parseCountResult(results []map[string][]byte) int64 {
  1003. if len(results) == 0 {
  1004. return 0
  1005. }
  1006. for _, result := range results[0] {
  1007. return com.StrTo(string(result)).MustInt64()
  1008. }
  1009. return 0
  1010. }
  1011. // IssueStatsOptions contains parameters accepted by GetIssueStats.
  1012. type IssueStatsOptions struct {
  1013. RepoID int64
  1014. Labels string
  1015. MilestoneID int64
  1016. AssigneeID int64
  1017. MentionedID int64
  1018. PosterID int64
  1019. IsPull bool
  1020. IssueIDs []int64
  1021. }
  1022. // GetIssueStats returns issue statistic information by given conditions.
  1023. func GetIssueStats(opts *IssueStatsOptions) (*IssueStats, error) {
  1024. stats := &IssueStats{}
  1025. countSession := func(opts *IssueStatsOptions) *xorm.Session {
  1026. sess := x.
  1027. Where("issue.repo_id = ?", opts.RepoID).
  1028. And("is_pull = ?", opts.IsPull)
  1029. if len(opts.IssueIDs) > 0 {
  1030. sess.In("issue.id", opts.IssueIDs)
  1031. }
  1032. if len(opts.Labels) > 0 && opts.Labels != "0" {
  1033. labelIDs, err := base.StringsToInt64s(strings.Split(opts.Labels, ","))
  1034. if err != nil {
  1035. log.Warn("Malformed Labels argument: %s", opts.Labels)
  1036. } else if len(labelIDs) > 0 {
  1037. sess.Join("INNER", "issue_label", "issue.id = issue_id").
  1038. In("label_id", labelIDs)
  1039. }
  1040. }
  1041. if opts.MilestoneID > 0 {
  1042. sess.And("issue.milestone_id = ?", opts.MilestoneID)
  1043. }
  1044. if opts.AssigneeID > 0 {
  1045. sess.And("assignee_id = ?", opts.AssigneeID)
  1046. }
  1047. if opts.PosterID > 0 {
  1048. sess.And("poster_id = ?", opts.PosterID)
  1049. }
  1050. if opts.MentionedID > 0 {
  1051. sess.Join("INNER", "issue_user", "issue.id = issue_user.issue_id").
  1052. And("issue_user.uid = ?", opts.MentionedID).
  1053. And("issue_user.is_mentioned = ?", true)
  1054. }
  1055. return sess
  1056. }
  1057. var err error
  1058. stats.OpenCount, err = countSession(opts).
  1059. And("is_closed = ?", false).
  1060. Count(&Issue{})
  1061. if err != nil {
  1062. return nil, err
  1063. }
  1064. stats.ClosedCount, err = countSession(opts).
  1065. And("is_closed = ?", true).
  1066. Count(&Issue{})
  1067. if err != nil {
  1068. return nil, err
  1069. }
  1070. return stats, nil
  1071. }
  1072. // GetUserIssueStats returns issue statistic information for dashboard by given conditions.
  1073. func GetUserIssueStats(repoID, uid int64, repoIDs []int64, filterMode int, isPull bool) *IssueStats {
  1074. stats := &IssueStats{}
  1075. countSession := func(isClosed, isPull bool, repoID int64, repoIDs []int64) *xorm.Session {
  1076. sess := x.
  1077. Where("issue.is_closed = ?", isClosed).
  1078. And("issue.is_pull = ?", isPull)
  1079. if repoID > 0 {
  1080. sess.And("repo_id = ?", repoID)
  1081. } else if len(repoIDs) > 0 {
  1082. sess.In("repo_id", repoIDs)
  1083. }
  1084. return sess
  1085. }
  1086. stats.AssignCount, _ = countSession(false, isPull, repoID, repoIDs).
  1087. And("assignee_id = ?", uid).
  1088. Count(&Issue{})
  1089. stats.CreateCount, _ = countSession(false, isPull, repoID, repoIDs).
  1090. And("poster_id = ?", uid).
  1091. Count(&Issue{})
  1092. openCountSession := countSession(false, isPull, repoID, repoIDs)
  1093. closedCountSession := countSession(true, isPull, repoID, repoIDs)
  1094. switch filterMode {
  1095. case FilterModeAssign:
  1096. openCountSession.And("assignee_id = ?", uid)
  1097. closedCountSession.And("assignee_id = ?", uid)
  1098. case FilterModeCreate:
  1099. openCountSession.And("poster_id = ?", uid)
  1100. closedCountSession.And("poster_id = ?", uid)
  1101. }
  1102. stats.OpenCount, _ = openCountSession.Count(&Issue{})
  1103. stats.ClosedCount, _ = closedCountSession.Count(&Issue{})
  1104. return stats
  1105. }
  1106. // GetRepoIssueStats returns number of open and closed repository issues by given filter mode.
  1107. func GetRepoIssueStats(repoID, uid int64, filterMode int, isPull bool) (numOpen int64, numClosed int64) {
  1108. countSession := func(isClosed, isPull bool, repoID int64) *xorm.Session {
  1109. sess := x.
  1110. Where("issue.repo_id = ?", isClosed).
  1111. And("is_pull = ?", isPull).
  1112. And("repo_id = ?", repoID)
  1113. return sess
  1114. }
  1115. openCountSession := countSession(false, isPull, repoID)
  1116. closedCountSession := countSession(true, isPull, repoID)
  1117. switch filterMode {
  1118. case FilterModeAssign:
  1119. openCountSession.And("assignee_id = ?", uid)
  1120. closedCountSession.And("assignee_id = ?", uid)
  1121. case FilterModeCreate:
  1122. openCountSession.And("poster_id = ?", uid)
  1123. closedCountSession.And("poster_id = ?", uid)
  1124. }
  1125. openResult, _ := openCountSession.Count(&Issue{})
  1126. closedResult, _ := closedCountSession.Count(&Issue{})
  1127. return openResult, closedResult
  1128. }
  1129. func updateIssue(e Engine, issue *Issue) error {
  1130. _, err := e.Id(issue.ID).AllCols().Update(issue)
  1131. if err != nil {
  1132. return err
  1133. }
  1134. UpdateIssueIndexer(issue)
  1135. return nil
  1136. }
  1137. // UpdateIssue updates all fields of given issue.
  1138. func UpdateIssue(issue *Issue) error {
  1139. return updateIssue(x, issue)
  1140. }
  1141. // _____ .__.__ __
  1142. // / \ |__| | ____ _______/ |_ ____ ____ ____
  1143. // / \ / \| | | _/ __ \ / ___/\ __\/ _ \ / \_/ __ \
  1144. // / Y \ | |_\ ___/ \___ \ | | ( <_> ) | \ ___/
  1145. // \____|__ /__|____/\___ >____ > |__| \____/|___| /\___ >
  1146. // \/ \/ \/ \/ \/
  1147. // Milestone represents a milestone of repository.
  1148. type Milestone struct {
  1149. ID int64 `xorm:"pk autoincr"`
  1150. RepoID int64 `xorm:"INDEX"`
  1151. Name string
  1152. Content string `xorm:"TEXT"`
  1153. RenderedContent string `xorm:"-"`
  1154. IsClosed bool
  1155. NumIssues int
  1156. NumClosedIssues int
  1157. NumOpenIssues int `xorm:"-"`
  1158. Completeness int // Percentage(1-100).
  1159. IsOverDue bool `xorm:"-"`
  1160. DeadlineString string `xorm:"-"`
  1161. Deadline time.Time `xorm:"-"`
  1162. DeadlineUnix int64
  1163. ClosedDate time.Time `xorm:"-"`
  1164. ClosedDateUnix int64
  1165. }
  1166. // BeforeInsert is invoked from XORM before inserting an object of this type.
  1167. func (m *Milestone) BeforeInsert() {
  1168. m.DeadlineUnix = m.Deadline.Unix()
  1169. }
  1170. // BeforeUpdate is invoked from XORM before updating this object.
  1171. func (m *Milestone) BeforeUpdate() {
  1172. if m.NumIssues > 0 {
  1173. m.Completeness = m.NumClosedIssues * 100 / m.NumIssues
  1174. } else {
  1175. m.Completeness = 0
  1176. }
  1177. m.DeadlineUnix = m.Deadline.Unix()
  1178. m.ClosedDateUnix = m.ClosedDate.Unix()
  1179. }
  1180. // AfterSet is invoked from XORM after setting the value of a field of
  1181. // this object.
  1182. func (m *Milestone) AfterSet(colName string, _ xorm.Cell) {
  1183. switch colName {
  1184. case "num_closed_issues":
  1185. m.NumOpenIssues = m.NumIssues - m.NumClosedIssues
  1186. case "deadline_unix":
  1187. m.Deadline = time.Unix(m.DeadlineUnix, 0).Local()
  1188. if m.Deadline.Year() == 9999 {
  1189. return
  1190. }
  1191. m.DeadlineString = m.Deadline.Format("2006-01-02")
  1192. if time.Now().Local().After(m.Deadline) {
  1193. m.IsOverDue = true
  1194. }
  1195. case "closed_date_unix":
  1196. m.ClosedDate = time.Unix(m.ClosedDateUnix, 0).Local()
  1197. }
  1198. }
  1199. // State returns string representation of milestone status.
  1200. func (m *Milestone) State() api.StateType {
  1201. if m.IsClosed {
  1202. return api.StateClosed
  1203. }
  1204. return api.StateOpen
  1205. }
  1206. // APIFormat returns this Milestone in API format.
  1207. func (m *Milestone) APIFormat() *api.Milestone {
  1208. apiMilestone := &api.Milestone{
  1209. ID: m.ID,
  1210. State: m.State(),
  1211. Title: m.Name,
  1212. Description: m.Content,
  1213. OpenIssues: m.NumOpenIssues,
  1214. ClosedIssues: m.NumClosedIssues,
  1215. }
  1216. if m.IsClosed {
  1217. apiMilestone.Closed = &m.ClosedDate
  1218. }
  1219. if m.Deadline.Year() < 9999 {
  1220. apiMilestone.Deadline = &m.Deadline
  1221. }
  1222. return apiMilestone
  1223. }
  1224. // NewMilestone creates new milestone of repository.
  1225. func NewMilestone(m *Milestone) (err error) {
  1226. sess := x.NewSession()
  1227. defer sessionRelease(sess)
  1228. if err = sess.Begin(); err != nil {
  1229. return err
  1230. }
  1231. if _, err = sess.Insert(m); err != nil {
  1232. return err
  1233. }
  1234. if _, err = sess.Exec("UPDATE `repository` SET num_milestones = num_milestones + 1 WHERE id = ?", m.RepoID); err != nil {
  1235. return err
  1236. }
  1237. return sess.Commit()
  1238. }
  1239. func getMilestoneByRepoID(e Engine, repoID, id int64) (*Milestone, error) {
  1240. m := &Milestone{
  1241. ID: id,
  1242. RepoID: repoID,
  1243. }
  1244. has, err := e.Get(m)
  1245. if err != nil {
  1246. return nil, err
  1247. } else if !has {
  1248. return nil, ErrMilestoneNotExist{id, repoID}
  1249. }
  1250. return m, nil
  1251. }
  1252. // GetMilestoneByRepoID returns the milestone in a repository.
  1253. func GetMilestoneByRepoID(repoID, id int64) (*Milestone, error) {
  1254. return getMilestoneByRepoID(x, repoID, id)
  1255. }
  1256. // GetMilestonesByRepoID returns all milestones of a repository.
  1257. func GetMilestonesByRepoID(repoID int64) ([]*Milestone, error) {
  1258. miles := make([]*Milestone, 0, 10)
  1259. return miles, x.Where("repo_id = ?", repoID).Find(&miles)
  1260. }
  1261. // GetMilestones returns a list of milestones of given repository and status.
  1262. func GetMilestones(repoID int64, page int, isClosed bool, sortType string) ([]*Milestone, error) {
  1263. miles := make([]*Milestone, 0, setting.UI.IssuePagingNum)
  1264. sess := x.Where("repo_id = ? AND is_closed = ?", repoID, isClosed)
  1265. if page > 0 {
  1266. sess = sess.Limit(setting.UI.IssuePagingNum, (page-1)*setting.UI.IssuePagingNum)
  1267. }
  1268. switch sortType {
  1269. case "furthestduedate":
  1270. sess.Desc("deadline_unix")
  1271. case "leastcomplete":
  1272. sess.Asc("completeness")
  1273. case "mostcomplete":
  1274. sess.Desc("completeness")
  1275. case "leastissues":
  1276. sess.Asc("num_issues")
  1277. case "mostissues":
  1278. sess.Desc("num_issues")
  1279. default:
  1280. sess.Asc("deadline_unix")
  1281. }
  1282. return miles, sess.Find(&miles)
  1283. }
  1284. func updateMilestone(e Engine, m *Milestone) error {
  1285. _, err := e.Id(m.ID).AllCols().Update(m)
  1286. return err
  1287. }
  1288. // UpdateMilestone updates information of given milestone.
  1289. func UpdateMilestone(m *Milestone) error {
  1290. return updateMilestone(x, m)
  1291. }
  1292. func countRepoMilestones(e Engine, repoID int64) int64 {
  1293. count, _ := e.
  1294. Where("repo_id=?", repoID).
  1295. Count(new(Milestone))
  1296. return count
  1297. }
  1298. // CountRepoMilestones returns number of milestones in given repository.
  1299. func CountRepoMilestones(repoID int64) int64 {
  1300. return countRepoMilestones(x, repoID)
  1301. }
  1302. func countRepoClosedMilestones(e Engine, repoID int64) int64 {
  1303. closed, _ := e.
  1304. Where("repo_id=? AND is_closed=?", repoID, true).
  1305. Count(new(Milestone))
  1306. return closed
  1307. }
  1308. // CountRepoClosedMilestones returns number of closed milestones in given repository.
  1309. func CountRepoClosedMilestones(repoID int64) int64 {
  1310. return countRepoClosedMilestones(x, repoID)
  1311. }
  1312. // MilestoneStats returns number of open and closed milestones of given repository.
  1313. func MilestoneStats(repoID int64) (open int64, closed int64) {
  1314. open, _ = x.
  1315. Where("repo_id=? AND is_closed=?", repoID, false).
  1316. Count(new(Milestone))
  1317. return open, CountRepoClosedMilestones(repoID)
  1318. }
  1319. // ChangeMilestoneStatus changes the milestone open/closed status.
  1320. func ChangeMilestoneStatus(m *Milestone, isClosed bool) (err error) {
  1321. repo, err := GetRepositoryByID(m.RepoID)
  1322. if err != nil {
  1323. return err
  1324. }
  1325. sess := x.NewSession()
  1326. defer sessionRelease(sess)
  1327. if err = sess.Begin(); err != nil {
  1328. return err
  1329. }
  1330. m.IsClosed = isClosed
  1331. if err = updateMilestone(sess, m); err != nil {
  1332. return err
  1333. }
  1334. repo.NumMilestones = int(countRepoMilestones(sess, repo.ID))
  1335. repo.NumClosedMilestones = int(countRepoClosedMilestones(sess, repo.ID))
  1336. if _, err = sess.Id(repo.ID).AllCols().Update(repo); err != nil {
  1337. return err
  1338. }
  1339. return sess.Commit()
  1340. }
  1341. func changeMilestoneIssueStats(e *xorm.Session, issue *Issue) error {
  1342. if issue.MilestoneID == 0 {
  1343. return nil
  1344. }
  1345. m, err := getMilestoneByRepoID(e, issue.RepoID, issue.MilestoneID)
  1346. if err != nil {
  1347. return err
  1348. }
  1349. if issue.IsClosed {
  1350. m.NumOpenIssues--
  1351. m.NumClosedIssues++
  1352. } else {
  1353. m.NumOpenIssues++
  1354. m.NumClosedIssues--
  1355. }
  1356. return updateMilestone(e, m)
  1357. }
  1358. // ChangeMilestoneIssueStats updates the open/closed issues counter and progress
  1359. // for the milestone associated with the given issue.
  1360. func ChangeMilestoneIssueStats(issue *Issue) (err error) {
  1361. sess := x.NewSession()
  1362. defer sessionRelease(sess)
  1363. if err = sess.Begin(); err != nil {
  1364. return err
  1365. }
  1366. if err = changeMilestoneIssueStats(sess, issue); err != nil {
  1367. return err
  1368. }
  1369. return sess.Commit()
  1370. }
  1371. func changeMilestoneAssign(e *xorm.Session, doer *User, issue *Issue, oldMilestoneID int64) error {
  1372. if oldMilestoneID > 0 {
  1373. m, err := getMilestoneByRepoID(e, issue.RepoID, oldMilestoneID)
  1374. if err != nil {
  1375. return err
  1376. }
  1377. m.NumIssues--
  1378. if issue.IsClosed {
  1379. m.NumClosedIssues--
  1380. }
  1381. if err = updateMilestone(e, m); err != nil {
  1382. return err
  1383. }
  1384. }
  1385. if issue.MilestoneID > 0 {
  1386. m, err := getMilestoneByRepoID(e, issue.RepoID, issue.MilestoneID)
  1387. if err != nil {
  1388. return err
  1389. }
  1390. m.NumIssues++
  1391. if issue.IsClosed {
  1392. m.NumClosedIssues++
  1393. }
  1394. if err = updateMilestone(e, m); err != nil {
  1395. return err
  1396. }
  1397. }
  1398. if err := issue.loadRepo(e); err != nil {
  1399. return err
  1400. }
  1401. if oldMilestoneID > 0 || issue.MilestoneID > 0 {
  1402. if _, err := createMilestoneComment(e, doer, issue.Repo, issue, oldMilestoneID, issue.MilestoneID); err != nil {
  1403. return err
  1404. }
  1405. }
  1406. return updateIssue(e, issue)
  1407. }
  1408. // ChangeMilestoneAssign changes assignment of milestone for issue.
  1409. func ChangeMilestoneAssign(issue *Issue, doer *User, oldMilestoneID int64) (err error) {
  1410. sess := x.NewSession()
  1411. defer sess.Close()
  1412. if err = sess.Begin(); err != nil {
  1413. return err
  1414. }
  1415. if err = changeMilestoneAssign(sess, doer, issue, oldMilestoneID); err != nil {
  1416. return err
  1417. }
  1418. return sess.Commit()
  1419. }
  1420. // DeleteMilestoneByRepoID deletes a milestone from a repository.
  1421. func DeleteMilestoneByRepoID(repoID, id int64) error {
  1422. m, err := GetMilestoneByRepoID(repoID, id)
  1423. if err != nil {
  1424. if IsErrMilestoneNotExist(err) {
  1425. return nil
  1426. }
  1427. return err
  1428. }
  1429. repo, err := GetRepositoryByID(m.RepoID)
  1430. if err != nil {
  1431. return err
  1432. }
  1433. sess := x.NewSession()
  1434. defer sessionRelease(sess)
  1435. if err = sess.Begin(); err != nil {
  1436. return err
  1437. }
  1438. if _, err = sess.Id(m.ID).Delete(new(Milestone)); err != nil {
  1439. return err
  1440. }
  1441. repo.NumMilestones = int(countRepoMilestones(sess, repo.ID))
  1442. repo.NumClosedMilestones = int(countRepoClosedMilestones(sess, repo.ID))
  1443. if _, err = sess.Id(repo.ID).AllCols().Update(repo); err != nil {
  1444. return err
  1445. }
  1446. if _, err = sess.Exec("UPDATE `issue` SET milestone_id = 0 WHERE milestone_id = ?", m.ID); err != nil {
  1447. return err
  1448. }
  1449. return sess.Commit()
  1450. }