issue.go 47 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809
  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. "bytes"
  7. "errors"
  8. "fmt"
  9. "io"
  10. "io/ioutil"
  11. "mime/multipart"
  12. "os"
  13. "path"
  14. "strconv"
  15. "strings"
  16. "time"
  17. "github.com/Unknwon/com"
  18. "github.com/go-xorm/xorm"
  19. "github.com/gogits/gogs/modules/base"
  20. "github.com/gogits/gogs/modules/log"
  21. "github.com/gogits/gogs/modules/process"
  22. "github.com/gogits/gogs/modules/setting"
  23. gouuid "github.com/gogits/gogs/modules/uuid"
  24. )
  25. var (
  26. ErrWrongIssueCounter = errors.New("Invalid number of issues for this milestone")
  27. ErrAttachmentNotLinked = errors.New("Attachment does not belong to this issue")
  28. ErrMissingIssueNumber = errors.New("No issue number specified")
  29. )
  30. // Issue represents an issue or pull request of repository.
  31. type Issue struct {
  32. ID int64 `xorm:"pk autoincr"`
  33. RepoID int64 `xorm:"INDEX"`
  34. Index int64 // Index in one repository.
  35. Name string
  36. Repo *Repository `xorm:"-"`
  37. PosterID int64
  38. Poster *User `xorm:"-"`
  39. Labels []*Label `xorm:"-"`
  40. MilestoneID int64
  41. Milestone *Milestone `xorm:"-"`
  42. AssigneeID int64
  43. Assignee *User `xorm:"-"`
  44. IsRead bool `xorm:"-"`
  45. IsPull bool // Indicates whether is a pull request or not.
  46. PullRepo *PullRepo `xorm:"-"`
  47. IsClosed bool
  48. Content string `xorm:"TEXT"`
  49. RenderedContent string `xorm:"-"`
  50. Priority int
  51. NumComments int
  52. Deadline time.Time
  53. Created time.Time `xorm:"CREATED"`
  54. Updated time.Time `xorm:"UPDATED"`
  55. Attachments []*Attachment `xorm:"-"`
  56. Comments []*Comment `xorm:"-"`
  57. }
  58. func (i *Issue) AfterSet(colName string, _ xorm.Cell) {
  59. var err error
  60. switch colName {
  61. case "id":
  62. i.Attachments, err = GetAttachmentsByIssueID(i.ID)
  63. if err != nil {
  64. log.Error(3, "GetAttachmentsByIssueID[%d]: %v", i.ID, err)
  65. }
  66. i.Comments, err = GetCommentsByIssueID(i.ID)
  67. if err != nil {
  68. log.Error(3, "GetCommentsByIssueID[%d]: %v", i.ID, err)
  69. }
  70. case "milestone_id":
  71. if i.MilestoneID == 0 {
  72. return
  73. }
  74. i.Milestone, err = GetMilestoneByID(i.MilestoneID)
  75. if err != nil {
  76. log.Error(3, "GetMilestoneById[%d]: %v", i.ID, err)
  77. }
  78. case "assignee_id":
  79. if i.AssigneeID == 0 {
  80. return
  81. }
  82. i.Assignee, err = GetUserByID(i.AssigneeID)
  83. if err != nil {
  84. log.Error(3, "GetUserByID[%d]: %v", i.ID, err)
  85. }
  86. case "is_pull":
  87. i.PullRepo, err = GetPullRepoByPullID(i.ID)
  88. if err != nil {
  89. log.Error(3, "GetPullRepoByPullID[%d]: %v", i.ID, err)
  90. }
  91. case "created":
  92. i.Created = regulateTimeZone(i.Created)
  93. }
  94. }
  95. // HashTag returns unique hash tag for issue.
  96. func (i *Issue) HashTag() string {
  97. return "issue-" + com.ToStr(i.ID)
  98. }
  99. // IsPoster returns true if given user by ID is the poster.
  100. func (i *Issue) IsPoster(uid int64) bool {
  101. return i.PosterID == uid
  102. }
  103. func (i *Issue) GetPoster() (err error) {
  104. i.Poster, err = GetUserByID(i.PosterID)
  105. if IsErrUserNotExist(err) {
  106. i.PosterID = -1
  107. i.Poster = NewFakeUser()
  108. return nil
  109. }
  110. return err
  111. }
  112. func (i *Issue) hasLabel(e Engine, labelID int64) bool {
  113. return hasIssueLabel(e, i.ID, labelID)
  114. }
  115. // HasLabel returns true if issue has been labeled by given ID.
  116. func (i *Issue) HasLabel(labelID int64) bool {
  117. return i.hasLabel(x, labelID)
  118. }
  119. func (i *Issue) addLabel(e *xorm.Session, label *Label) error {
  120. return newIssueLabel(e, i, label)
  121. }
  122. // AddLabel adds new label to issue by given ID.
  123. func (i *Issue) AddLabel(label *Label) (err error) {
  124. sess := x.NewSession()
  125. defer sessionRelease(sess)
  126. if err = sess.Begin(); err != nil {
  127. return err
  128. }
  129. if err = i.addLabel(sess, label); err != nil {
  130. return err
  131. }
  132. return sess.Commit()
  133. }
  134. func (i *Issue) getLabels(e Engine) (err error) {
  135. if len(i.Labels) > 0 {
  136. return nil
  137. }
  138. i.Labels, err = getLabelsByIssueID(e, i.ID)
  139. if err != nil {
  140. return fmt.Errorf("getLabelsByIssueID: %v", err)
  141. }
  142. return nil
  143. }
  144. // GetLabels retrieves all labels of issue and assign to corresponding field.
  145. func (i *Issue) GetLabels() error {
  146. return i.getLabels(x)
  147. }
  148. func (i *Issue) removeLabel(e *xorm.Session, label *Label) error {
  149. return deleteIssueLabel(e, i, label)
  150. }
  151. // RemoveLabel removes a label from issue by given ID.
  152. func (i *Issue) RemoveLabel(label *Label) (err error) {
  153. sess := x.NewSession()
  154. defer sessionRelease(sess)
  155. if err = sess.Begin(); err != nil {
  156. return err
  157. }
  158. if err = i.removeLabel(sess, label); err != nil {
  159. return err
  160. }
  161. return sess.Commit()
  162. }
  163. func (i *Issue) ClearLabels() (err error) {
  164. sess := x.NewSession()
  165. defer sessionRelease(sess)
  166. if err = sess.Begin(); err != nil {
  167. return err
  168. }
  169. if err = i.getLabels(sess); err != nil {
  170. return err
  171. }
  172. for idx := range i.Labels {
  173. if err = i.removeLabel(sess, i.Labels[idx]); err != nil {
  174. return err
  175. }
  176. }
  177. return sess.Commit()
  178. }
  179. func (i *Issue) GetAssignee() (err error) {
  180. if i.AssigneeID == 0 || i.Assignee != nil {
  181. return nil
  182. }
  183. i.Assignee, err = GetUserByID(i.AssigneeID)
  184. if IsErrUserNotExist(err) {
  185. return nil
  186. }
  187. return err
  188. }
  189. // ReadBy sets issue to be read by given user.
  190. func (i *Issue) ReadBy(uid int64) error {
  191. return UpdateIssueUserByRead(uid, i.ID)
  192. }
  193. func (i *Issue) changeStatus(e *xorm.Session, doer *User, isClosed bool) (err error) {
  194. if i.IsClosed == isClosed {
  195. return nil
  196. }
  197. i.IsClosed = isClosed
  198. if err = updateIssue(e, i); err != nil {
  199. return err
  200. } else if err = updateIssueUsersByStatus(e, i.ID, isClosed); err != nil {
  201. return err
  202. }
  203. // Update labels.
  204. if err = i.getLabels(e); err != nil {
  205. return err
  206. }
  207. for idx := range i.Labels {
  208. if i.IsClosed {
  209. i.Labels[idx].NumClosedIssues++
  210. } else {
  211. i.Labels[idx].NumClosedIssues--
  212. }
  213. if err = updateLabel(e, i.Labels[idx]); err != nil {
  214. return err
  215. }
  216. }
  217. // Update milestone.
  218. if err = changeMilestoneIssueStats(e, i); err != nil {
  219. return err
  220. }
  221. // New action comment.
  222. if _, err = createStatusComment(e, doer, i.Repo, i); err != nil {
  223. return err
  224. }
  225. return nil
  226. }
  227. // ChangeStatus changes issue status to open/closed.
  228. func (i *Issue) ChangeStatus(doer *User, isClosed bool) (err error) {
  229. sess := x.NewSession()
  230. defer sessionRelease(sess)
  231. if err = sess.Begin(); err != nil {
  232. return err
  233. }
  234. if err = i.changeStatus(sess, doer, isClosed); err != nil {
  235. return err
  236. }
  237. return sess.Commit()
  238. }
  239. // It's caller's responsibility to create action.
  240. func newIssue(e *xorm.Session, repo *Repository, issue *Issue, labelIDs []int64, uuids []string) (err error) {
  241. if _, err = e.Insert(issue); err != nil {
  242. return err
  243. } else if _, err = e.Exec("UPDATE `repository` SET num_issues=num_issues+1 WHERE id=?", issue.RepoID); err != nil {
  244. return err
  245. }
  246. var label *Label
  247. for _, id := range labelIDs {
  248. if id == 0 {
  249. continue
  250. }
  251. label, err = getLabelByID(e, id)
  252. if err != nil {
  253. return err
  254. }
  255. if err = issue.addLabel(e, label); err != nil {
  256. return fmt.Errorf("addLabel: %v", err)
  257. }
  258. }
  259. if issue.MilestoneID > 0 {
  260. if err = changeMilestoneAssign(e, 0, issue); err != nil {
  261. return err
  262. }
  263. }
  264. if err = newIssueUsers(e, repo, issue); err != nil {
  265. return err
  266. }
  267. // Check attachments.
  268. attachments := make([]*Attachment, 0, len(uuids))
  269. for _, uuid := range uuids {
  270. attach, err := getAttachmentByUUID(e, uuid)
  271. if err != nil {
  272. if IsErrAttachmentNotExist(err) {
  273. continue
  274. }
  275. return fmt.Errorf("getAttachmentByUUID[%s]: %v", uuid, err)
  276. }
  277. attachments = append(attachments, attach)
  278. }
  279. for i := range attachments {
  280. attachments[i].IssueID = issue.ID
  281. // No assign value could be 0, so ignore AllCols().
  282. if _, err = e.Id(attachments[i].ID).Update(attachments[i]); err != nil {
  283. return fmt.Errorf("update attachment[%d]: %v", attachments[i].ID, err)
  284. }
  285. }
  286. return nil
  287. }
  288. // NewIssue creates new issue with labels for repository.
  289. func NewIssue(repo *Repository, issue *Issue, labelIDs []int64, uuids []string) (err error) {
  290. sess := x.NewSession()
  291. defer sessionRelease(sess)
  292. if err = sess.Begin(); err != nil {
  293. return err
  294. }
  295. if err = newIssue(sess, repo, issue, labelIDs, uuids); err != nil {
  296. return fmt.Errorf("newIssue: %v", err)
  297. }
  298. // Notify watchers.
  299. act := &Action{
  300. ActUserID: issue.Poster.Id,
  301. ActUserName: issue.Poster.Name,
  302. ActEmail: issue.Poster.Email,
  303. OpType: CREATE_ISSUE,
  304. Content: fmt.Sprintf("%d|%s", issue.Index, issue.Name),
  305. RepoID: repo.ID,
  306. RepoUserName: repo.Owner.Name,
  307. RepoName: repo.Name,
  308. IsPrivate: repo.IsPrivate,
  309. }
  310. if err = notifyWatchers(sess, act); err != nil {
  311. return err
  312. }
  313. return sess.Commit()
  314. }
  315. // GetIssueByRef returns an Issue specified by a GFM reference.
  316. // See https://help.github.com/articles/writing-on-github#references for more information on the syntax.
  317. func GetIssueByRef(ref string) (issue *Issue, err error) {
  318. var issueNumber int64
  319. var repo *Repository
  320. n := strings.IndexByte(ref, byte('#'))
  321. if n == -1 {
  322. return nil, ErrMissingIssueNumber
  323. }
  324. if issueNumber, err = strconv.ParseInt(ref[n+1:], 10, 64); err != nil {
  325. return
  326. }
  327. if repo, err = GetRepositoryByRef(ref[:n]); err != nil {
  328. return
  329. }
  330. return GetIssueByIndex(repo.ID, issueNumber)
  331. }
  332. // GetIssueByIndex returns issue by given index in repository.
  333. func GetIssueByIndex(repoID, index int64) (*Issue, error) {
  334. issue := &Issue{
  335. RepoID: repoID,
  336. Index: index,
  337. }
  338. has, err := x.Get(issue)
  339. if err != nil {
  340. return nil, err
  341. } else if !has {
  342. return nil, ErrIssueNotExist{0, repoID, index}
  343. }
  344. return issue, nil
  345. }
  346. // GetIssueByID returns an issue by given ID.
  347. func GetIssueByID(id int64) (*Issue, error) {
  348. issue := new(Issue)
  349. has, err := x.Id(id).Get(issue)
  350. if err != nil {
  351. return nil, err
  352. } else if !has {
  353. return nil, ErrIssueNotExist{id, 0, 0}
  354. }
  355. return issue, nil
  356. }
  357. // Issues returns a list of issues by given conditions.
  358. func Issues(uid, assigneeID, repoID, posterID, milestoneID int64, repoIDs []int64, page int, isClosed, isMention bool, labels, sortType string) ([]*Issue, error) {
  359. sess := x.Limit(setting.IssuePagingNum, (page-1)*setting.IssuePagingNum)
  360. if repoID > 0 {
  361. sess.Where("issue.repo_id=?", repoID).And("issue.is_closed=?", isClosed)
  362. } else if repoIDs != nil {
  363. // In case repository IDs are provided but actually no repository has issue.
  364. if len(repoIDs) == 0 {
  365. return make([]*Issue, 0), nil
  366. }
  367. sess.Where("issue.repo_id IN ("+strings.Join(base.Int64sToStrings(repoIDs), ",")+")").And("issue.is_closed=?", isClosed)
  368. } else {
  369. sess.Where("issue.is_closed=?", isClosed)
  370. }
  371. if assigneeID > 0 {
  372. sess.And("issue.assignee_id=?", assigneeID)
  373. } else if posterID > 0 {
  374. sess.And("issue.poster_id=?", posterID)
  375. }
  376. if milestoneID > 0 {
  377. sess.And("issue.milestone_id=?", milestoneID)
  378. }
  379. switch sortType {
  380. case "oldest":
  381. sess.Asc("created")
  382. case "recentupdate":
  383. sess.Desc("updated")
  384. case "leastupdate":
  385. sess.Asc("updated")
  386. case "mostcomment":
  387. sess.Desc("num_comments")
  388. case "leastcomment":
  389. sess.Asc("num_comments")
  390. case "priority":
  391. sess.Desc("priority")
  392. default:
  393. sess.Desc("created")
  394. }
  395. labelIDs := base.StringsToInt64s(strings.Split(labels, ","))
  396. if len(labelIDs) > 0 {
  397. validJoin := false
  398. queryStr := "issue.id=issue_label.issue_id"
  399. for _, id := range labelIDs {
  400. if id == 0 {
  401. continue
  402. }
  403. validJoin = true
  404. queryStr += " AND issue_label.label_id=" + com.ToStr(id)
  405. }
  406. if validJoin {
  407. sess.Join("INNER", "issue_label", queryStr)
  408. }
  409. }
  410. if isMention {
  411. queryStr := "issue.id=issue_user.issue_id AND issue_user.is_mentioned=1"
  412. if uid > 0 {
  413. queryStr += " AND issue_user.uid=" + com.ToStr(uid)
  414. }
  415. sess.Join("INNER", "issue_user", queryStr)
  416. }
  417. issues := make([]*Issue, 0, setting.IssuePagingNum)
  418. return issues, sess.Find(&issues)
  419. }
  420. type IssueStatus int
  421. const (
  422. IS_OPEN = iota + 1
  423. IS_CLOSE
  424. )
  425. // GetIssueCountByPoster returns number of issues of repository by poster.
  426. func GetIssueCountByPoster(uid, rid int64, isClosed bool) int64 {
  427. count, _ := x.Where("repo_id=?", rid).And("poster_id=?", uid).And("is_closed=?", isClosed).Count(new(Issue))
  428. return count
  429. }
  430. // .___ ____ ___
  431. // | | ______ ________ __ ____ | | \______ ___________
  432. // | |/ ___// ___/ | \_/ __ \| | / ___// __ \_ __ \
  433. // | |\___ \ \___ \| | /\ ___/| | /\___ \\ ___/| | \/
  434. // |___/____ >____ >____/ \___ >______//____ >\___ >__|
  435. // \/ \/ \/ \/ \/
  436. // IssueUser represents an issue-user relation.
  437. type IssueUser struct {
  438. ID int64 `xorm:"pk autoincr"`
  439. UID int64 `xorm:"uid INDEX"` // User ID.
  440. IssueID int64
  441. RepoID int64 `xorm:"INDEX"`
  442. MilestoneID int64
  443. IsRead bool
  444. IsAssigned bool
  445. IsMentioned bool
  446. IsPoster bool
  447. IsClosed bool
  448. }
  449. func newIssueUsers(e *xorm.Session, repo *Repository, issue *Issue) error {
  450. users, err := repo.GetAssignees()
  451. if err != nil {
  452. return err
  453. }
  454. iu := &IssueUser{
  455. IssueID: issue.ID,
  456. RepoID: repo.ID,
  457. }
  458. // Poster can be anyone.
  459. isNeedAddPoster := true
  460. for _, u := range users {
  461. iu.ID = 0
  462. iu.UID = u.Id
  463. iu.IsPoster = iu.UID == issue.PosterID
  464. if isNeedAddPoster && iu.IsPoster {
  465. isNeedAddPoster = false
  466. }
  467. iu.IsAssigned = iu.UID == issue.AssigneeID
  468. if _, err = e.Insert(iu); err != nil {
  469. return err
  470. }
  471. }
  472. if isNeedAddPoster {
  473. iu.ID = 0
  474. iu.UID = issue.PosterID
  475. iu.IsPoster = true
  476. if _, err = e.Insert(iu); err != nil {
  477. return err
  478. }
  479. }
  480. return nil
  481. }
  482. // NewIssueUsers adds new issue-user relations for new issue of repository.
  483. func NewIssueUsers(repo *Repository, issue *Issue) (err error) {
  484. sess := x.NewSession()
  485. defer sessionRelease(sess)
  486. if err = sess.Begin(); err != nil {
  487. return err
  488. }
  489. if err = newIssueUsers(sess, repo, issue); err != nil {
  490. return err
  491. }
  492. return sess.Commit()
  493. }
  494. // PairsContains returns true when pairs list contains given issue.
  495. func PairsContains(ius []*IssueUser, issueId, uid int64) int {
  496. for i := range ius {
  497. if ius[i].IssueID == issueId &&
  498. ius[i].UID == uid {
  499. return i
  500. }
  501. }
  502. return -1
  503. }
  504. // GetIssueUsers returns issue-user pairs by given repository and user.
  505. func GetIssueUsers(rid, uid int64, isClosed bool) ([]*IssueUser, error) {
  506. ius := make([]*IssueUser, 0, 10)
  507. err := x.Where("is_closed=?", isClosed).Find(&ius, &IssueUser{RepoID: rid, UID: uid})
  508. return ius, err
  509. }
  510. // GetIssueUserPairsByRepoIds returns issue-user pairs by given repository IDs.
  511. func GetIssueUserPairsByRepoIds(rids []int64, isClosed bool, page int) ([]*IssueUser, error) {
  512. if len(rids) == 0 {
  513. return []*IssueUser{}, nil
  514. }
  515. buf := bytes.NewBufferString("")
  516. for _, rid := range rids {
  517. buf.WriteString("repo_id=")
  518. buf.WriteString(com.ToStr(rid))
  519. buf.WriteString(" OR ")
  520. }
  521. cond := strings.TrimSuffix(buf.String(), " OR ")
  522. ius := make([]*IssueUser, 0, 10)
  523. sess := x.Limit(20, (page-1)*20).Where("is_closed=?", isClosed)
  524. if len(cond) > 0 {
  525. sess.And(cond)
  526. }
  527. err := sess.Find(&ius)
  528. return ius, err
  529. }
  530. // GetIssueUserPairsByMode returns issue-user pairs by given repository and user.
  531. func GetIssueUserPairsByMode(uid, rid int64, isClosed bool, page, filterMode int) ([]*IssueUser, error) {
  532. ius := make([]*IssueUser, 0, 10)
  533. sess := x.Limit(20, (page-1)*20).Where("uid=?", uid).And("is_closed=?", isClosed)
  534. if rid > 0 {
  535. sess.And("repo_id=?", rid)
  536. }
  537. switch filterMode {
  538. case FM_ASSIGN:
  539. sess.And("is_assigned=?", true)
  540. case FM_CREATE:
  541. sess.And("is_poster=?", true)
  542. default:
  543. return ius, nil
  544. }
  545. err := sess.Find(&ius)
  546. return ius, err
  547. }
  548. // IssueStats represents issue statistic information.
  549. type IssueStats struct {
  550. OpenCount, ClosedCount int64
  551. AllCount int64
  552. AssignCount int64
  553. CreateCount int64
  554. MentionCount int64
  555. }
  556. // Filter modes.
  557. const (
  558. FM_ALL = iota
  559. FM_ASSIGN
  560. FM_CREATE
  561. FM_MENTION
  562. )
  563. func parseCountResult(results []map[string][]byte) int64 {
  564. if len(results) == 0 {
  565. return 0
  566. }
  567. for _, result := range results[0] {
  568. return com.StrTo(string(result)).MustInt64()
  569. }
  570. return 0
  571. }
  572. // GetIssueStats returns issue statistic information by given conditions.
  573. func GetIssueStats(repoID, uid, labelID, milestoneID, assigneeID int64, filterMode int) *IssueStats {
  574. stats := &IssueStats{}
  575. queryStr := "SELECT COUNT(*) FROM `issue` "
  576. if labelID > 0 {
  577. queryStr += "INNER JOIN `issue_label` ON `issue`.id=`issue_label`.issue_id AND `issue_label`.label_id=" + com.ToStr(labelID)
  578. }
  579. baseCond := " WHERE issue.repo_id=? AND issue.is_closed=?"
  580. if milestoneID > 0 {
  581. baseCond += " AND issue.milestone_id=" + com.ToStr(milestoneID)
  582. }
  583. if assigneeID > 0 {
  584. baseCond += " AND assignee_id=" + com.ToStr(assigneeID)
  585. }
  586. switch filterMode {
  587. case FM_ALL, FM_ASSIGN:
  588. results, _ := x.Query(queryStr+baseCond, repoID, false)
  589. stats.OpenCount = parseCountResult(results)
  590. results, _ = x.Query(queryStr+baseCond, repoID, true)
  591. stats.ClosedCount = parseCountResult(results)
  592. case FM_CREATE:
  593. baseCond += " AND poster_id=?"
  594. results, _ := x.Query(queryStr+baseCond, repoID, false, uid)
  595. stats.OpenCount = parseCountResult(results)
  596. results, _ = x.Query(queryStr+baseCond, repoID, true, uid)
  597. stats.ClosedCount = parseCountResult(results)
  598. case FM_MENTION:
  599. queryStr += " INNER JOIN `issue_user` ON `issue`.id=`issue_user`.issue_id"
  600. baseCond += " AND `issue_user`.uid=? AND `issue_user`.is_mentioned=?"
  601. results, _ := x.Query(queryStr+baseCond, repoID, false, uid, true)
  602. stats.OpenCount = parseCountResult(results)
  603. results, _ = x.Query(queryStr+baseCond, repoID, true, uid, true)
  604. stats.ClosedCount = parseCountResult(results)
  605. }
  606. return stats
  607. }
  608. // GetUserIssueStats returns issue statistic information for dashboard by given conditions.
  609. func GetUserIssueStats(repoID, uid int64, repoIDs []int64, filterMode int) *IssueStats {
  610. stats := &IssueStats{}
  611. issue := new(Issue)
  612. stats.AssignCount, _ = x.Where("assignee_id=?", uid).And("is_closed=?", false).Count(issue)
  613. stats.CreateCount, _ = x.Where("poster_id=?", uid).And("is_closed=?", false).Count(issue)
  614. queryStr := "SELECT COUNT(*) FROM `issue` "
  615. baseCond := " WHERE issue.is_closed=?"
  616. if repoID > 0 {
  617. baseCond += " AND issue.repo_id=" + com.ToStr(repoID)
  618. } else {
  619. baseCond += " AND issue.repo_id IN (" + strings.Join(base.Int64sToStrings(repoIDs), ",") + ")"
  620. }
  621. switch filterMode {
  622. case FM_ASSIGN:
  623. baseCond += " AND assignee_id=" + com.ToStr(uid)
  624. case FM_CREATE:
  625. baseCond += " AND poster_id=" + com.ToStr(uid)
  626. }
  627. results, _ := x.Query(queryStr+baseCond, false)
  628. stats.OpenCount = parseCountResult(results)
  629. results, _ = x.Query(queryStr+baseCond, true)
  630. stats.ClosedCount = parseCountResult(results)
  631. return stats
  632. }
  633. // GetRepoIssueStats returns number of open and closed repository issues by given filter mode.
  634. func GetRepoIssueStats(repoID, uid int64, filterMode int) (numOpen int64, numClosed int64) {
  635. queryStr := "SELECT COUNT(*) FROM `issue` "
  636. baseCond := " WHERE issue.repo_id=? AND issue.is_closed=?"
  637. switch filterMode {
  638. case FM_ASSIGN:
  639. baseCond += " AND assignee_id=" + com.ToStr(uid)
  640. case FM_CREATE:
  641. baseCond += " AND poster_id=" + com.ToStr(uid)
  642. }
  643. results, _ := x.Query(queryStr+baseCond, repoID, false)
  644. numOpen = parseCountResult(results)
  645. results, _ = x.Query(queryStr+baseCond, repoID, true)
  646. numClosed = parseCountResult(results)
  647. return numOpen, numClosed
  648. }
  649. func updateIssue(e Engine, issue *Issue) error {
  650. _, err := e.Id(issue.ID).AllCols().Update(issue)
  651. return err
  652. }
  653. // UpdateIssue updates information of issue.
  654. func UpdateIssue(issue *Issue) error {
  655. return updateIssue(x, issue)
  656. }
  657. func updateIssueUsersByStatus(e Engine, issueID int64, isClosed bool) error {
  658. _, err := e.Exec("UPDATE `issue_user` SET is_closed=? WHERE issue_id=?", isClosed, issueID)
  659. return err
  660. }
  661. // UpdateIssueUsersByStatus updates issue-user relations by issue status.
  662. func UpdateIssueUsersByStatus(issueID int64, isClosed bool) error {
  663. return updateIssueUsersByStatus(x, issueID, isClosed)
  664. }
  665. func updateIssueUserByAssignee(e *xorm.Session, issue *Issue) (err error) {
  666. if _, err = e.Exec("UPDATE `issue_user` SET is_assigned=? WHERE issue_id=?", false, issue.ID); err != nil {
  667. return err
  668. }
  669. // Assignee ID equals to 0 means clear assignee.
  670. if issue.AssigneeID > 0 {
  671. if _, err = e.Exec("UPDATE `issue_user` SET is_assigned=? WHERE uid=? AND issue_id=?", true, issue.AssigneeID, issue.ID); err != nil {
  672. return err
  673. }
  674. }
  675. return updateIssue(e, issue)
  676. }
  677. // UpdateIssueUserByAssignee updates issue-user relation for assignee.
  678. func UpdateIssueUserByAssignee(issue *Issue) (err error) {
  679. sess := x.NewSession()
  680. defer sessionRelease(sess)
  681. if err = sess.Begin(); err != nil {
  682. return err
  683. }
  684. if err = updateIssueUserByAssignee(sess, issue); err != nil {
  685. return err
  686. }
  687. return sess.Commit()
  688. }
  689. // UpdateIssueUserByRead updates issue-user relation for reading.
  690. func UpdateIssueUserByRead(uid, issueID int64) error {
  691. _, err := x.Exec("UPDATE `issue_user` SET is_read=? WHERE uid=? AND issue_id=?", true, uid, issueID)
  692. return err
  693. }
  694. // UpdateIssueUsersByMentions updates issue-user pairs by mentioning.
  695. func UpdateIssueUsersByMentions(uids []int64, iid int64) error {
  696. for _, uid := range uids {
  697. iu := &IssueUser{UID: uid, IssueID: iid}
  698. has, err := x.Get(iu)
  699. if err != nil {
  700. return err
  701. }
  702. iu.IsMentioned = true
  703. if has {
  704. _, err = x.Id(iu.ID).AllCols().Update(iu)
  705. } else {
  706. _, err = x.Insert(iu)
  707. }
  708. if err != nil {
  709. return err
  710. }
  711. }
  712. return nil
  713. }
  714. // __________ .__ .__ __________ __
  715. // \______ \__ __| | | |\______ \ ____ ________ __ ____ _______/ |_
  716. // | ___/ | \ | | | | _// __ \/ ____/ | \_/ __ \ / ___/\ __\
  717. // | | | | / |_| |_| | \ ___< <_| | | /\ ___/ \___ \ | |
  718. // |____| |____/|____/____/____|_ /\___ >__ |____/ \___ >____ > |__|
  719. // \/ \/ |__| \/ \/
  720. type PullRequestType int
  721. const (
  722. PULL_REQUEST_GOGS = iota
  723. PLLL_ERQUEST_GIT
  724. )
  725. // PullRepo represents relation between pull request and repositories.
  726. type PullRepo struct {
  727. ID int64 `xorm:"pk autoincr"`
  728. PullID int64 `xorm:"INDEX"`
  729. HeadRepoID int64 `xorm:"UNIQUE(s)"`
  730. HeadRepo *Repository `xorm:"-"`
  731. BaseRepoID int64 `xorm:"UNIQUE(s)"`
  732. HeadUserName string
  733. HeadBarcnh string `xorm:"UNIQUE(s)"`
  734. BaseBranch string `xorm:"UNIQUE(s)"`
  735. MergeBase string `xorm:"VARCHAR(40)"`
  736. Type PullRequestType
  737. CanAutoMerge bool
  738. HasMerged bool
  739. }
  740. func (pr *PullRepo) AfterSet(colName string, _ xorm.Cell) {
  741. var err error
  742. switch colName {
  743. case "head_repo_id":
  744. pr.HeadRepo, err = GetRepositoryByID(pr.HeadRepoID)
  745. if err != nil {
  746. log.Error(3, "GetRepositoryByID[%d]: %v", pr.ID, err)
  747. }
  748. }
  749. }
  750. // NewPullRequest creates new pull request with labels for repository.
  751. func NewPullRequest(repo *Repository, pr *Issue, labelIDs []int64, uuids []string, pullRepo *PullRepo, patch []byte) (err error) {
  752. sess := x.NewSession()
  753. defer sessionRelease(sess)
  754. if err = sess.Begin(); err != nil {
  755. return err
  756. }
  757. if err = newIssue(sess, repo, pr, labelIDs, uuids); err != nil {
  758. return fmt.Errorf("newIssue: %v", err)
  759. }
  760. // Notify watchers.
  761. act := &Action{
  762. ActUserID: pr.Poster.Id,
  763. ActUserName: pr.Poster.Name,
  764. ActEmail: pr.Poster.Email,
  765. OpType: PULL_REQUEST,
  766. Content: fmt.Sprintf("%d|%s", pr.Index, pr.Name),
  767. RepoID: repo.ID,
  768. RepoUserName: repo.Owner.Name,
  769. RepoName: repo.Name,
  770. IsPrivate: repo.IsPrivate,
  771. }
  772. if err = notifyWatchers(sess, act); err != nil {
  773. return err
  774. }
  775. // Test apply patch.
  776. repoPath, err := repo.RepoPath()
  777. if err != nil {
  778. return fmt.Errorf("RepoPath: %v", err)
  779. }
  780. patchPath := path.Join(repoPath, "pulls", com.ToStr(pr.ID)+".patch")
  781. os.MkdirAll(path.Dir(patchPath), os.ModePerm)
  782. if err = ioutil.WriteFile(patchPath, patch, 0644); err != nil {
  783. return fmt.Errorf("save patch: %v", err)
  784. }
  785. defer os.Remove(patchPath)
  786. stdout, stderr, err := process.ExecDir(-1, repoPath,
  787. fmt.Sprintf("NewPullRequest(git apply --check): %d", repo.ID),
  788. "git", "apply", "--check", "-v", patchPath)
  789. if err != nil {
  790. if strings.Contains(stderr, "fatal:") {
  791. return fmt.Errorf("git apply --check: %v - %s", err, stderr)
  792. }
  793. }
  794. pullRepo.CanAutoMerge = !strings.Contains(stdout, "error: patch failed:")
  795. pullRepo.PullID = pr.ID
  796. if _, err = sess.Insert(pullRepo); err != nil {
  797. return fmt.Errorf("insert pull repo: %v", err)
  798. }
  799. return sess.Commit()
  800. }
  801. // GetPullRepoByPullID returns pull repo by given pull ID.
  802. func GetPullRepoByPullID(pullID int64) (*PullRepo, error) {
  803. pullRepo := new(PullRepo)
  804. has, err := x.Where("pull_id=?", pullID).Get(pullRepo)
  805. if err != nil {
  806. return nil, err
  807. } else if !has {
  808. return nil, ErrPullRepoNotExist{0, pullID}
  809. }
  810. return pullRepo, nil
  811. }
  812. // .____ ___. .__
  813. // | | _____ \_ |__ ____ | |
  814. // | | \__ \ | __ \_/ __ \| |
  815. // | |___ / __ \| \_\ \ ___/| |__
  816. // |_______ (____ /___ /\___ >____/
  817. // \/ \/ \/ \/
  818. // Label represents a label of repository for issues.
  819. type Label struct {
  820. ID int64 `xorm:"pk autoincr"`
  821. RepoID int64 `xorm:"INDEX"`
  822. Name string
  823. Color string `xorm:"VARCHAR(7)"`
  824. NumIssues int
  825. NumClosedIssues int
  826. NumOpenIssues int `xorm:"-"`
  827. IsChecked bool `xorm:"-"`
  828. }
  829. // CalOpenIssues calculates the open issues of label.
  830. func (m *Label) CalOpenIssues() {
  831. m.NumOpenIssues = m.NumIssues - m.NumClosedIssues
  832. }
  833. // NewLabel creates new label of repository.
  834. func NewLabel(l *Label) error {
  835. _, err := x.Insert(l)
  836. return err
  837. }
  838. func getLabelByID(e Engine, id int64) (*Label, error) {
  839. if id <= 0 {
  840. return nil, ErrLabelNotExist{id}
  841. }
  842. l := &Label{ID: id}
  843. has, err := x.Get(l)
  844. if err != nil {
  845. return nil, err
  846. } else if !has {
  847. return nil, ErrLabelNotExist{l.ID}
  848. }
  849. return l, nil
  850. }
  851. // GetLabelByID returns a label by given ID.
  852. func GetLabelByID(id int64) (*Label, error) {
  853. return getLabelByID(x, id)
  854. }
  855. // GetLabelsByRepoID returns all labels that belong to given repository by ID.
  856. func GetLabelsByRepoID(repoID int64) ([]*Label, error) {
  857. labels := make([]*Label, 0, 10)
  858. return labels, x.Where("repo_id=?", repoID).Find(&labels)
  859. }
  860. func getLabelsByIssueID(e Engine, issueID int64) ([]*Label, error) {
  861. issueLabels, err := getIssueLabels(e, issueID)
  862. if err != nil {
  863. return nil, fmt.Errorf("getIssueLabels: %v", err)
  864. }
  865. var label *Label
  866. labels := make([]*Label, 0, len(issueLabels))
  867. for idx := range issueLabels {
  868. label, err = getLabelByID(e, issueLabels[idx].LabelID)
  869. if err != nil && !IsErrLabelNotExist(err) {
  870. return nil, fmt.Errorf("getLabelByID: %v", err)
  871. }
  872. labels = append(labels, label)
  873. }
  874. return labels, nil
  875. }
  876. // GetLabelsByIssueID returns all labels that belong to given issue by ID.
  877. func GetLabelsByIssueID(issueID int64) ([]*Label, error) {
  878. return getLabelsByIssueID(x, issueID)
  879. }
  880. func updateLabel(e Engine, l *Label) error {
  881. _, err := e.Id(l.ID).AllCols().Update(l)
  882. return err
  883. }
  884. // UpdateLabel updates label information.
  885. func UpdateLabel(l *Label) error {
  886. return updateLabel(x, l)
  887. }
  888. // DeleteLabel delete a label of given repository.
  889. func DeleteLabel(repoID, labelID int64) error {
  890. l, err := GetLabelByID(labelID)
  891. if err != nil {
  892. if IsErrLabelNotExist(err) {
  893. return nil
  894. }
  895. return err
  896. }
  897. sess := x.NewSession()
  898. defer sessionRelease(sess)
  899. if err = sess.Begin(); err != nil {
  900. return err
  901. }
  902. if _, err = x.Where("label_id=?", labelID).Delete(new(IssueLabel)); err != nil {
  903. return err
  904. } else if _, err = sess.Delete(l); err != nil {
  905. return err
  906. }
  907. return sess.Commit()
  908. }
  909. // .___ .____ ___. .__
  910. // | | ______ ________ __ ____ | | _____ \_ |__ ____ | |
  911. // | |/ ___// ___/ | \_/ __ \| | \__ \ | __ \_/ __ \| |
  912. // | |\___ \ \___ \| | /\ ___/| |___ / __ \| \_\ \ ___/| |__
  913. // |___/____ >____ >____/ \___ >_______ (____ /___ /\___ >____/
  914. // \/ \/ \/ \/ \/ \/ \/
  915. // IssueLabel represetns an issue-lable relation.
  916. type IssueLabel struct {
  917. ID int64 `xorm:"pk autoincr"`
  918. IssueID int64 `xorm:"UNIQUE(s)"`
  919. LabelID int64 `xorm:"UNIQUE(s)"`
  920. }
  921. func hasIssueLabel(e Engine, issueID, labelID int64) bool {
  922. has, _ := e.Where("issue_id=? AND label_id=?", issueID, labelID).Get(new(IssueLabel))
  923. return has
  924. }
  925. // HasIssueLabel returns true if issue has been labeled.
  926. func HasIssueLabel(issueID, labelID int64) bool {
  927. return hasIssueLabel(x, issueID, labelID)
  928. }
  929. func newIssueLabel(e *xorm.Session, issue *Issue, label *Label) (err error) {
  930. if _, err = e.Insert(&IssueLabel{
  931. IssueID: issue.ID,
  932. LabelID: label.ID,
  933. }); err != nil {
  934. return err
  935. }
  936. label.NumIssues++
  937. if issue.IsClosed {
  938. label.NumClosedIssues++
  939. }
  940. return updateLabel(e, label)
  941. }
  942. // NewIssueLabel creates a new issue-label relation.
  943. func NewIssueLabel(issue *Issue, label *Label) (err error) {
  944. sess := x.NewSession()
  945. defer sessionRelease(sess)
  946. if err = sess.Begin(); err != nil {
  947. return err
  948. }
  949. if err = newIssueLabel(sess, issue, label); err != nil {
  950. return err
  951. }
  952. return sess.Commit()
  953. }
  954. func getIssueLabels(e Engine, issueID int64) ([]*IssueLabel, error) {
  955. issueLabels := make([]*IssueLabel, 0, 10)
  956. return issueLabels, e.Where("issue_id=?", issueID).Asc("label_id").Find(&issueLabels)
  957. }
  958. // GetIssueLabels returns all issue-label relations of given issue by ID.
  959. func GetIssueLabels(issueID int64) ([]*IssueLabel, error) {
  960. return getIssueLabels(x, issueID)
  961. }
  962. func deleteIssueLabel(e *xorm.Session, issue *Issue, label *Label) (err error) {
  963. if _, err = e.Delete(&IssueLabel{
  964. IssueID: issue.ID,
  965. LabelID: label.ID,
  966. }); err != nil {
  967. return err
  968. }
  969. label.NumIssues--
  970. if issue.IsClosed {
  971. label.NumClosedIssues--
  972. }
  973. return updateLabel(e, label)
  974. }
  975. // DeleteIssueLabel deletes issue-label relation.
  976. func DeleteIssueLabel(issue *Issue, label *Label) (err error) {
  977. sess := x.NewSession()
  978. defer sessionRelease(sess)
  979. if err = sess.Begin(); err != nil {
  980. return err
  981. }
  982. if err = deleteIssueLabel(sess, issue, label); err != nil {
  983. return err
  984. }
  985. return sess.Commit()
  986. }
  987. // _____ .__.__ __
  988. // / \ |__| | ____ _______/ |_ ____ ____ ____
  989. // / \ / \| | | _/ __ \ / ___/\ __\/ _ \ / \_/ __ \
  990. // / Y \ | |_\ ___/ \___ \ | | ( <_> ) | \ ___/
  991. // \____|__ /__|____/\___ >____ > |__| \____/|___| /\___ >
  992. // \/ \/ \/ \/ \/
  993. // Milestone represents a milestone of repository.
  994. type Milestone struct {
  995. ID int64 `xorm:"pk autoincr"`
  996. RepoID int64 `xorm:"INDEX"`
  997. Name string
  998. Content string `xorm:"TEXT"`
  999. RenderedContent string `xorm:"-"`
  1000. IsClosed bool
  1001. NumIssues int
  1002. NumClosedIssues int
  1003. NumOpenIssues int `xorm:"-"`
  1004. Completeness int // Percentage(1-100).
  1005. Deadline time.Time
  1006. DeadlineString string `xorm:"-"`
  1007. IsOverDue bool `xorm:"-"`
  1008. ClosedDate time.Time
  1009. }
  1010. func (m *Milestone) BeforeUpdate() {
  1011. if m.NumIssues > 0 {
  1012. m.Completeness = m.NumClosedIssues * 100 / m.NumIssues
  1013. } else {
  1014. m.Completeness = 0
  1015. }
  1016. }
  1017. func (m *Milestone) AfterSet(colName string, _ xorm.Cell) {
  1018. if colName == "deadline" {
  1019. if m.Deadline.Year() == 9999 {
  1020. return
  1021. }
  1022. m.DeadlineString = m.Deadline.Format("2006-01-02")
  1023. if time.Now().After(m.Deadline) {
  1024. m.IsOverDue = true
  1025. }
  1026. }
  1027. }
  1028. // CalOpenIssues calculates the open issues of milestone.
  1029. func (m *Milestone) CalOpenIssues() {
  1030. m.NumOpenIssues = m.NumIssues - m.NumClosedIssues
  1031. }
  1032. // NewMilestone creates new milestone of repository.
  1033. func NewMilestone(m *Milestone) (err error) {
  1034. sess := x.NewSession()
  1035. defer sessionRelease(sess)
  1036. if err = sess.Begin(); err != nil {
  1037. return err
  1038. }
  1039. if _, err = sess.Insert(m); err != nil {
  1040. return err
  1041. }
  1042. if _, err = sess.Exec("UPDATE `repository` SET num_milestones=num_milestones+1 WHERE id=?", m.RepoID); err != nil {
  1043. return err
  1044. }
  1045. return sess.Commit()
  1046. }
  1047. func getMilestoneByID(e Engine, id int64) (*Milestone, error) {
  1048. m := &Milestone{ID: id}
  1049. has, err := e.Get(m)
  1050. if err != nil {
  1051. return nil, err
  1052. } else if !has {
  1053. return nil, ErrMilestoneNotExist{id, 0}
  1054. }
  1055. return m, nil
  1056. }
  1057. // GetMilestoneByID returns the milestone of given ID.
  1058. func GetMilestoneByID(id int64) (*Milestone, error) {
  1059. return getMilestoneByID(x, id)
  1060. }
  1061. // GetRepoMilestoneByID returns the milestone of given ID and repository.
  1062. func GetRepoMilestoneByID(repoID, milestoneID int64) (*Milestone, error) {
  1063. m := &Milestone{ID: milestoneID, RepoID: repoID}
  1064. has, err := x.Get(m)
  1065. if err != nil {
  1066. return nil, err
  1067. } else if !has {
  1068. return nil, ErrMilestoneNotExist{milestoneID, repoID}
  1069. }
  1070. return m, nil
  1071. }
  1072. // GetAllRepoMilestones returns all milestones of given repository.
  1073. func GetAllRepoMilestones(repoID int64) ([]*Milestone, error) {
  1074. miles := make([]*Milestone, 0, 10)
  1075. return miles, x.Where("repo_id=?", repoID).Find(&miles)
  1076. }
  1077. // GetMilestones returns a list of milestones of given repository and status.
  1078. func GetMilestones(repoID int64, page int, isClosed bool) ([]*Milestone, error) {
  1079. miles := make([]*Milestone, 0, setting.IssuePagingNum)
  1080. sess := x.Where("repo_id=? AND is_closed=?", repoID, isClosed)
  1081. if page > 0 {
  1082. sess = sess.Limit(setting.IssuePagingNum, (page-1)*setting.IssuePagingNum)
  1083. }
  1084. return miles, sess.Find(&miles)
  1085. }
  1086. func updateMilestone(e Engine, m *Milestone) error {
  1087. _, err := e.Id(m.ID).AllCols().Update(m)
  1088. return err
  1089. }
  1090. // UpdateMilestone updates information of given milestone.
  1091. func UpdateMilestone(m *Milestone) error {
  1092. return updateMilestone(x, m)
  1093. }
  1094. func countRepoMilestones(e Engine, repoID int64) int64 {
  1095. count, _ := e.Where("repo_id=?", repoID).Count(new(Milestone))
  1096. return count
  1097. }
  1098. // CountRepoMilestones returns number of milestones in given repository.
  1099. func CountRepoMilestones(repoID int64) int64 {
  1100. return countRepoMilestones(x, repoID)
  1101. }
  1102. func countRepoClosedMilestones(e Engine, repoID int64) int64 {
  1103. closed, _ := e.Where("repo_id=? AND is_closed=?", repoID, true).Count(new(Milestone))
  1104. return closed
  1105. }
  1106. // CountRepoClosedMilestones returns number of closed milestones in given repository.
  1107. func CountRepoClosedMilestones(repoID int64) int64 {
  1108. return countRepoClosedMilestones(x, repoID)
  1109. }
  1110. // MilestoneStats returns number of open and closed milestones of given repository.
  1111. func MilestoneStats(repoID int64) (open int64, closed int64) {
  1112. open, _ = x.Where("repo_id=? AND is_closed=?", repoID, false).Count(new(Milestone))
  1113. return open, CountRepoClosedMilestones(repoID)
  1114. }
  1115. // ChangeMilestoneStatus changes the milestone open/closed status.
  1116. func ChangeMilestoneStatus(m *Milestone, isClosed bool) (err error) {
  1117. repo, err := GetRepositoryByID(m.RepoID)
  1118. if err != nil {
  1119. return err
  1120. }
  1121. sess := x.NewSession()
  1122. defer sessionRelease(sess)
  1123. if err = sess.Begin(); err != nil {
  1124. return err
  1125. }
  1126. m.IsClosed = isClosed
  1127. if err = updateMilestone(sess, m); err != nil {
  1128. return err
  1129. }
  1130. repo.NumMilestones = int(countRepoMilestones(sess, repo.ID))
  1131. repo.NumClosedMilestones = int(countRepoClosedMilestones(sess, repo.ID))
  1132. if _, err = sess.Id(repo.ID).AllCols().Update(repo); err != nil {
  1133. return err
  1134. }
  1135. return sess.Commit()
  1136. }
  1137. func changeMilestoneIssueStats(e *xorm.Session, issue *Issue) error {
  1138. if issue.MilestoneID == 0 {
  1139. return nil
  1140. }
  1141. m, err := getMilestoneByID(e, issue.MilestoneID)
  1142. if err != nil {
  1143. return err
  1144. }
  1145. if issue.IsClosed {
  1146. m.NumOpenIssues--
  1147. m.NumClosedIssues++
  1148. } else {
  1149. m.NumOpenIssues++
  1150. m.NumClosedIssues--
  1151. }
  1152. return updateMilestone(e, m)
  1153. }
  1154. // ChangeMilestoneIssueStats updates the open/closed issues counter and progress
  1155. // for the milestone associated witht the given issue.
  1156. func ChangeMilestoneIssueStats(issue *Issue) (err error) {
  1157. sess := x.NewSession()
  1158. defer sessionRelease(sess)
  1159. if err = sess.Begin(); err != nil {
  1160. return err
  1161. }
  1162. if err = changeMilestoneIssueStats(sess, issue); err != nil {
  1163. return err
  1164. }
  1165. return sess.Commit()
  1166. }
  1167. func changeMilestoneAssign(e *xorm.Session, oldMid int64, issue *Issue) error {
  1168. if oldMid > 0 {
  1169. m, err := getMilestoneByID(e, oldMid)
  1170. if err != nil {
  1171. return err
  1172. }
  1173. m.NumIssues--
  1174. if issue.IsClosed {
  1175. m.NumClosedIssues--
  1176. }
  1177. if err = updateMilestone(e, m); err != nil {
  1178. return err
  1179. } else if _, err = e.Exec("UPDATE `issue_user` SET milestone_id=0 WHERE issue_id=?", issue.ID); err != nil {
  1180. return err
  1181. }
  1182. }
  1183. if issue.MilestoneID > 0 {
  1184. m, err := getMilestoneByID(e, issue.MilestoneID)
  1185. if err != nil {
  1186. return err
  1187. }
  1188. m.NumIssues++
  1189. if issue.IsClosed {
  1190. m.NumClosedIssues++
  1191. }
  1192. if m.NumIssues == 0 {
  1193. return ErrWrongIssueCounter
  1194. }
  1195. if err = updateMilestone(e, m); err != nil {
  1196. return err
  1197. } else if _, err = e.Exec("UPDATE `issue_user` SET milestone_id=? WHERE issue_id=?", m.ID, issue.ID); err != nil {
  1198. return err
  1199. }
  1200. }
  1201. return updateIssue(e, issue)
  1202. }
  1203. // ChangeMilestoneAssign changes assignment of milestone for issue.
  1204. func ChangeMilestoneAssign(oldMid int64, issue *Issue) (err error) {
  1205. sess := x.NewSession()
  1206. defer sess.Close()
  1207. if err = sess.Begin(); err != nil {
  1208. return err
  1209. }
  1210. if err = changeMilestoneAssign(sess, oldMid, issue); err != nil {
  1211. return err
  1212. }
  1213. return sess.Commit()
  1214. }
  1215. // DeleteMilestoneByID deletes a milestone by given ID.
  1216. func DeleteMilestoneByID(mid int64) error {
  1217. m, err := GetMilestoneByID(mid)
  1218. if err != nil {
  1219. if IsErrMilestoneNotExist(err) {
  1220. return nil
  1221. }
  1222. return err
  1223. }
  1224. repo, err := GetRepositoryByID(m.RepoID)
  1225. if err != nil {
  1226. return err
  1227. }
  1228. sess := x.NewSession()
  1229. defer sessionRelease(sess)
  1230. if err = sess.Begin(); err != nil {
  1231. return err
  1232. }
  1233. if _, err = sess.Id(m.ID).Delete(m); err != nil {
  1234. return err
  1235. }
  1236. repo.NumMilestones = int(countRepoMilestones(sess, repo.ID))
  1237. repo.NumClosedMilestones = int(countRepoClosedMilestones(sess, repo.ID))
  1238. if _, err = sess.Id(repo.ID).AllCols().Update(repo); err != nil {
  1239. return err
  1240. }
  1241. if _, err = sess.Exec("UPDATE `issue` SET milestone_id=0 WHERE milestone_id=?", m.ID); err != nil {
  1242. return err
  1243. } else if _, err = sess.Exec("UPDATE `issue_user` SET milestone_id=0 WHERE milestone_id=?", m.ID); err != nil {
  1244. return err
  1245. }
  1246. return sess.Commit()
  1247. }
  1248. // _________ __
  1249. // \_ ___ \ ____ _____ _____ ____ _____/ |_
  1250. // / \ \/ / _ \ / \ / \_/ __ \ / \ __\
  1251. // \ \___( <_> ) Y Y \ Y Y \ ___/| | \ |
  1252. // \______ /\____/|__|_| /__|_| /\___ >___| /__|
  1253. // \/ \/ \/ \/ \/
  1254. // CommentType defines whether a comment is just a simple comment, an action (like close) or a reference.
  1255. type CommentType int
  1256. const (
  1257. // Plain comment, can be associated with a commit (CommitId > 0) and a line (Line > 0)
  1258. COMMENT_TYPE_COMMENT CommentType = iota
  1259. COMMENT_TYPE_REOPEN
  1260. COMMENT_TYPE_CLOSE
  1261. // References.
  1262. COMMENT_TYPE_ISSUE_REF
  1263. // Reference from a commit (not part of a pull request)
  1264. COMMENT_TYPE_COMMIT_REF
  1265. // Reference from a comment
  1266. COMMENT_TYPE_COMMENT_REF
  1267. // Reference from a pull request
  1268. COMMENT_TYPE_PULL_REF
  1269. )
  1270. type CommentTag int
  1271. const (
  1272. COMMENT_TAG_NONE CommentTag = iota
  1273. COMMENT_TAG_POSTER
  1274. COMMENT_TAG_ADMIN
  1275. COMMENT_TAG_OWNER
  1276. )
  1277. // Comment represents a comment in commit and issue page.
  1278. type Comment struct {
  1279. ID int64 `xorm:"pk autoincr"`
  1280. Type CommentType
  1281. PosterID int64
  1282. Poster *User `xorm:"-"`
  1283. IssueID int64 `xorm:"INDEX"`
  1284. CommitID int64
  1285. Line int64
  1286. Content string `xorm:"TEXT"`
  1287. RenderedContent string `xorm:"-"`
  1288. Created time.Time `xorm:"CREATED"`
  1289. Attachments []*Attachment `xorm:"-"`
  1290. // For view issue page.
  1291. ShowTag CommentTag `xorm:"-"`
  1292. }
  1293. func (c *Comment) AfterSet(colName string, _ xorm.Cell) {
  1294. var err error
  1295. switch colName {
  1296. case "id":
  1297. c.Attachments, err = GetAttachmentsByCommentID(c.ID)
  1298. if err != nil {
  1299. log.Error(3, "GetAttachmentsByCommentID[%d]: %v", c.ID, err)
  1300. }
  1301. case "poster_id":
  1302. c.Poster, err = GetUserByID(c.PosterID)
  1303. if err != nil {
  1304. if IsErrUserNotExist(err) {
  1305. c.PosterID = -1
  1306. c.Poster = NewFakeUser()
  1307. } else {
  1308. log.Error(3, "GetUserByID[%d]: %v", c.ID, err)
  1309. }
  1310. }
  1311. case "created":
  1312. c.Created = regulateTimeZone(c.Created)
  1313. }
  1314. }
  1315. func (c *Comment) AfterDelete() {
  1316. _, err := DeleteAttachmentsByComment(c.ID, true)
  1317. if err != nil {
  1318. log.Info("Could not delete files for comment %d on issue #%d: %s", c.ID, c.IssueID, err)
  1319. }
  1320. }
  1321. // HashTag returns unique hash tag for comment.
  1322. func (c *Comment) HashTag() string {
  1323. return "issuecomment-" + com.ToStr(c.ID)
  1324. }
  1325. // EventTag returns unique event hash tag for comment.
  1326. func (c *Comment) EventTag() string {
  1327. return "event-" + com.ToStr(c.ID)
  1328. }
  1329. func createComment(e *xorm.Session, u *User, repo *Repository, issue *Issue, commitID, line int64, cmtType CommentType, content string, uuids []string) (_ *Comment, err error) {
  1330. comment := &Comment{
  1331. PosterID: u.Id,
  1332. Type: cmtType,
  1333. IssueID: issue.ID,
  1334. CommitID: commitID,
  1335. Line: line,
  1336. Content: content,
  1337. }
  1338. if _, err = e.Insert(comment); err != nil {
  1339. return nil, err
  1340. }
  1341. // Check comment type.
  1342. switch cmtType {
  1343. case COMMENT_TYPE_COMMENT:
  1344. if _, err = e.Exec("UPDATE `issue` SET num_comments=num_comments+1 WHERE id=?", issue.ID); err != nil {
  1345. return nil, err
  1346. }
  1347. // Check attachments.
  1348. attachments := make([]*Attachment, 0, len(uuids))
  1349. for _, uuid := range uuids {
  1350. attach, err := getAttachmentByUUID(e, uuid)
  1351. if err != nil {
  1352. if IsErrAttachmentNotExist(err) {
  1353. continue
  1354. }
  1355. return nil, fmt.Errorf("getAttachmentByUUID[%s]: %v", uuid, err)
  1356. }
  1357. attachments = append(attachments, attach)
  1358. }
  1359. for i := range attachments {
  1360. attachments[i].IssueID = issue.ID
  1361. attachments[i].CommentID = comment.ID
  1362. // No assign value could be 0, so ignore AllCols().
  1363. if _, err = e.Id(attachments[i].ID).Update(attachments[i]); err != nil {
  1364. return nil, fmt.Errorf("update attachment[%d]: %v", attachments[i].ID, err)
  1365. }
  1366. }
  1367. // Notify watchers.
  1368. act := &Action{
  1369. ActUserID: u.Id,
  1370. ActUserName: u.LowerName,
  1371. ActEmail: u.Email,
  1372. OpType: COMMENT_ISSUE,
  1373. Content: fmt.Sprintf("%d|%s", issue.Index, strings.Split(content, "\n")[0]),
  1374. RepoID: repo.ID,
  1375. RepoUserName: repo.Owner.LowerName,
  1376. RepoName: repo.LowerName,
  1377. IsPrivate: repo.IsPrivate,
  1378. }
  1379. if err = notifyWatchers(e, act); err != nil {
  1380. return nil, err
  1381. }
  1382. case COMMENT_TYPE_REOPEN:
  1383. if _, err = e.Exec("UPDATE `repository` SET num_closed_issues=num_closed_issues-1 WHERE id=?", repo.ID); err != nil {
  1384. return nil, err
  1385. }
  1386. case COMMENT_TYPE_CLOSE:
  1387. if _, err = e.Exec("UPDATE `repository` SET num_closed_issues=num_closed_issues+1 WHERE id=?", repo.ID); err != nil {
  1388. return nil, err
  1389. }
  1390. }
  1391. return comment, nil
  1392. }
  1393. func createStatusComment(e *xorm.Session, doer *User, repo *Repository, issue *Issue) (*Comment, error) {
  1394. cmtType := COMMENT_TYPE_CLOSE
  1395. if !issue.IsClosed {
  1396. cmtType = COMMENT_TYPE_REOPEN
  1397. }
  1398. return createComment(e, doer, repo, issue, 0, 0, cmtType, "", nil)
  1399. }
  1400. // CreateComment creates comment of issue or commit.
  1401. func CreateComment(doer *User, repo *Repository, issue *Issue, commitID, line int64, cmtType CommentType, content string, attachments []string) (comment *Comment, err error) {
  1402. sess := x.NewSession()
  1403. defer sessionRelease(sess)
  1404. if err = sess.Begin(); err != nil {
  1405. return nil, err
  1406. }
  1407. comment, err = createComment(sess, doer, repo, issue, commitID, line, cmtType, content, attachments)
  1408. if err != nil {
  1409. return nil, err
  1410. }
  1411. return comment, sess.Commit()
  1412. }
  1413. // CreateIssueComment creates a plain issue comment.
  1414. func CreateIssueComment(doer *User, repo *Repository, issue *Issue, content string, attachments []string) (*Comment, error) {
  1415. return CreateComment(doer, repo, issue, 0, 0, COMMENT_TYPE_COMMENT, content, attachments)
  1416. }
  1417. // GetCommentByID returns the comment by given ID.
  1418. func GetCommentByID(id int64) (*Comment, error) {
  1419. c := new(Comment)
  1420. has, err := x.Id(id).Get(c)
  1421. if err != nil {
  1422. return nil, err
  1423. } else if !has {
  1424. return nil, ErrCommentNotExist{id}
  1425. }
  1426. return c, nil
  1427. }
  1428. // GetCommentsByIssueID returns all comments of issue by given ID.
  1429. func GetCommentsByIssueID(issueID int64) ([]*Comment, error) {
  1430. comments := make([]*Comment, 0, 10)
  1431. return comments, x.Where("issue_id=?", issueID).Asc("created").Find(&comments)
  1432. }
  1433. // UpdateComment updates information of comment.
  1434. func UpdateComment(c *Comment) error {
  1435. _, err := x.Id(c.ID).AllCols().Update(c)
  1436. return err
  1437. }
  1438. // Attachment represent a attachment of issue/comment/release.
  1439. type Attachment struct {
  1440. ID int64 `xorm:"pk autoincr"`
  1441. UUID string `xorm:"uuid UNIQUE"`
  1442. IssueID int64 `xorm:"INDEX"`
  1443. CommentID int64
  1444. ReleaseID int64 `xorm:"INDEX"`
  1445. Name string
  1446. Created time.Time `xorm:"CREATED"`
  1447. }
  1448. // AttachmentLocalPath returns where attachment is stored in local file system based on given UUID.
  1449. func AttachmentLocalPath(uuid string) string {
  1450. return path.Join(setting.AttachmentPath, uuid[0:1], uuid[1:2], uuid)
  1451. }
  1452. // LocalPath returns where attachment is stored in local file system.
  1453. func (attach *Attachment) LocalPath() string {
  1454. return AttachmentLocalPath(attach.UUID)
  1455. }
  1456. // NewAttachment creates a new attachment object.
  1457. func NewAttachment(name string, buf []byte, file multipart.File) (_ *Attachment, err error) {
  1458. attach := &Attachment{
  1459. UUID: gouuid.NewV4().String(),
  1460. Name: name,
  1461. }
  1462. if err = os.MkdirAll(path.Dir(attach.LocalPath()), os.ModePerm); err != nil {
  1463. return nil, fmt.Errorf("MkdirAll: %v", err)
  1464. }
  1465. fw, err := os.Create(attach.LocalPath())
  1466. if err != nil {
  1467. return nil, fmt.Errorf("Create: %v", err)
  1468. }
  1469. defer fw.Close()
  1470. if _, err = fw.Write(buf); err != nil {
  1471. return nil, fmt.Errorf("Write: %v", err)
  1472. } else if _, err = io.Copy(fw, file); err != nil {
  1473. return nil, fmt.Errorf("Copy: %v", err)
  1474. }
  1475. sess := x.NewSession()
  1476. defer sessionRelease(sess)
  1477. if err := sess.Begin(); err != nil {
  1478. return nil, err
  1479. }
  1480. if _, err := sess.Insert(attach); err != nil {
  1481. return nil, err
  1482. }
  1483. return attach, sess.Commit()
  1484. }
  1485. func getAttachmentByUUID(e Engine, uuid string) (*Attachment, error) {
  1486. attach := &Attachment{UUID: uuid}
  1487. has, err := x.Get(attach)
  1488. if err != nil {
  1489. return nil, err
  1490. } else if !has {
  1491. return nil, ErrAttachmentNotExist{0, uuid}
  1492. }
  1493. return attach, nil
  1494. }
  1495. // GetAttachmentByUUID returns attachment by given UUID.
  1496. func GetAttachmentByUUID(uuid string) (*Attachment, error) {
  1497. return getAttachmentByUUID(x, uuid)
  1498. }
  1499. // GetAttachmentsByIssueID returns all attachments for given issue by ID.
  1500. func GetAttachmentsByIssueID(issueID int64) ([]*Attachment, error) {
  1501. attachments := make([]*Attachment, 0, 10)
  1502. return attachments, x.Where("issue_id=? AND comment_id=0", issueID).Find(&attachments)
  1503. }
  1504. // GetAttachmentsByCommentID returns all attachments if comment by given ID.
  1505. func GetAttachmentsByCommentID(commentID int64) ([]*Attachment, error) {
  1506. attachments := make([]*Attachment, 0, 10)
  1507. return attachments, x.Where("comment_id=?", commentID).Find(&attachments)
  1508. }
  1509. // DeleteAttachment deletes the given attachment and optionally the associated file.
  1510. func DeleteAttachment(a *Attachment, remove bool) error {
  1511. _, err := DeleteAttachments([]*Attachment{a}, remove)
  1512. return err
  1513. }
  1514. // DeleteAttachments deletes the given attachments and optionally the associated files.
  1515. func DeleteAttachments(attachments []*Attachment, remove bool) (int, error) {
  1516. for i, a := range attachments {
  1517. if remove {
  1518. if err := os.Remove(a.LocalPath()); err != nil {
  1519. return i, err
  1520. }
  1521. }
  1522. if _, err := x.Delete(a.ID); err != nil {
  1523. return i, err
  1524. }
  1525. }
  1526. return len(attachments), nil
  1527. }
  1528. // DeleteAttachmentsByIssue deletes all attachments associated with the given issue.
  1529. func DeleteAttachmentsByIssue(issueId int64, remove bool) (int, error) {
  1530. attachments, err := GetAttachmentsByIssueID(issueId)
  1531. if err != nil {
  1532. return 0, err
  1533. }
  1534. return DeleteAttachments(attachments, remove)
  1535. }
  1536. // DeleteAttachmentsByComment deletes all attachments associated with the given comment.
  1537. func DeleteAttachmentsByComment(commentId int64, remove bool) (int, error) {
  1538. attachments, err := GetAttachmentsByCommentID(commentId)
  1539. if err != nil {
  1540. return 0, err
  1541. }
  1542. return DeleteAttachments(attachments, remove)
  1543. }