issue.go 47 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808
  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. HeadBarcnh string `xorm:"UNIQUE(s)"`
  733. BaseBranch string `xorm:"UNIQUE(s)"`
  734. MergeBase string `xorm:"VARCHAR(40)"`
  735. Type PullRequestType
  736. CanAutoMerge bool
  737. }
  738. func (pr *PullRepo) AfterSet(colName string, _ xorm.Cell) {
  739. var err error
  740. switch colName {
  741. case "head_repo_id":
  742. pr.HeadRepo, err = GetRepositoryByID(pr.HeadRepoID)
  743. if err != nil {
  744. log.Error(3, "GetRepositoryByID[%d]: %v", pr.ID, err)
  745. }
  746. }
  747. }
  748. // NewPullRequest creates new pull request with labels for repository.
  749. func NewPullRequest(repo *Repository, pr *Issue, labelIDs []int64, uuids []string, pullRepo *PullRepo, patch []byte) (err error) {
  750. sess := x.NewSession()
  751. defer sessionRelease(sess)
  752. if err = sess.Begin(); err != nil {
  753. return err
  754. }
  755. if err = newIssue(sess, repo, pr, labelIDs, uuids); err != nil {
  756. return fmt.Errorf("newIssue: %v", err)
  757. }
  758. // Notify watchers.
  759. act := &Action{
  760. ActUserID: pr.Poster.Id,
  761. ActUserName: pr.Poster.Name,
  762. ActEmail: pr.Poster.Email,
  763. OpType: PULL_REQUEST,
  764. Content: fmt.Sprintf("%d|%s", pr.Index, pr.Name),
  765. RepoID: repo.ID,
  766. RepoUserName: repo.Owner.Name,
  767. RepoName: repo.Name,
  768. IsPrivate: repo.IsPrivate,
  769. }
  770. if err = notifyWatchers(sess, act); err != nil {
  771. return err
  772. }
  773. // Test apply patch.
  774. repoPath, err := repo.RepoPath()
  775. if err != nil {
  776. return fmt.Errorf("RepoPath: %v", err)
  777. }
  778. patchPath := path.Join(repoPath, "pulls", com.ToStr(pr.ID)+".patch")
  779. os.MkdirAll(path.Dir(patchPath), os.ModePerm)
  780. if err = ioutil.WriteFile(patchPath, patch, 0644); err != nil {
  781. return fmt.Errorf("save patch: %v", err)
  782. }
  783. defer os.Remove(patchPath)
  784. stdout, stderr, err := process.ExecDir(-1, repoPath,
  785. fmt.Sprintf("NewPullRequest(git apply --check): %d", repo.ID),
  786. "git", "apply", "--check", "-v", patchPath)
  787. if err != nil {
  788. if strings.Contains(stderr, "fatal:") {
  789. return fmt.Errorf("git apply --check: %v - %s", err, stderr)
  790. }
  791. }
  792. pullRepo.CanAutoMerge = !strings.Contains(stdout, "error: patch failed:")
  793. pullRepo.PullID = pr.ID
  794. if _, err = sess.Insert(pullRepo); err != nil {
  795. return fmt.Errorf("insert pull repo: %v", err)
  796. }
  797. return sess.Commit()
  798. }
  799. // GetPullRepoByPullID returns pull repo by given pull ID.
  800. func GetPullRepoByPullID(pullID int64) (*PullRepo, error) {
  801. pullRepo := new(PullRepo)
  802. has, err := x.Where("pull_id=?", pullID).Get(pullRepo)
  803. if err != nil {
  804. return nil, err
  805. } else if !has {
  806. return nil, ErrPullRepoNotExist{0, pullID}
  807. }
  808. return pullRepo, nil
  809. }
  810. // .____ ___. .__
  811. // | | _____ \_ |__ ____ | |
  812. // | | \__ \ | __ \_/ __ \| |
  813. // | |___ / __ \| \_\ \ ___/| |__
  814. // |_______ (____ /___ /\___ >____/
  815. // \/ \/ \/ \/
  816. // Label represents a label of repository for issues.
  817. type Label struct {
  818. ID int64 `xorm:"pk autoincr"`
  819. RepoID int64 `xorm:"INDEX"`
  820. Name string
  821. Color string `xorm:"VARCHAR(7)"`
  822. NumIssues int
  823. NumClosedIssues int
  824. NumOpenIssues int `xorm:"-"`
  825. IsChecked bool `xorm:"-"`
  826. }
  827. // CalOpenIssues calculates the open issues of label.
  828. func (m *Label) CalOpenIssues() {
  829. m.NumOpenIssues = m.NumIssues - m.NumClosedIssues
  830. }
  831. // NewLabel creates new label of repository.
  832. func NewLabel(l *Label) error {
  833. _, err := x.Insert(l)
  834. return err
  835. }
  836. func getLabelByID(e Engine, id int64) (*Label, error) {
  837. if id <= 0 {
  838. return nil, ErrLabelNotExist{id}
  839. }
  840. l := &Label{ID: id}
  841. has, err := x.Get(l)
  842. if err != nil {
  843. return nil, err
  844. } else if !has {
  845. return nil, ErrLabelNotExist{l.ID}
  846. }
  847. return l, nil
  848. }
  849. // GetLabelByID returns a label by given ID.
  850. func GetLabelByID(id int64) (*Label, error) {
  851. return getLabelByID(x, id)
  852. }
  853. // GetLabelsByRepoID returns all labels that belong to given repository by ID.
  854. func GetLabelsByRepoID(repoID int64) ([]*Label, error) {
  855. labels := make([]*Label, 0, 10)
  856. return labels, x.Where("repo_id=?", repoID).Find(&labels)
  857. }
  858. func getLabelsByIssueID(e Engine, issueID int64) ([]*Label, error) {
  859. issueLabels, err := getIssueLabels(e, issueID)
  860. if err != nil {
  861. return nil, fmt.Errorf("getIssueLabels: %v", err)
  862. }
  863. var label *Label
  864. labels := make([]*Label, 0, len(issueLabels))
  865. for idx := range issueLabels {
  866. label, err = getLabelByID(e, issueLabels[idx].LabelID)
  867. if err != nil && !IsErrLabelNotExist(err) {
  868. return nil, fmt.Errorf("getLabelByID: %v", err)
  869. }
  870. labels = append(labels, label)
  871. }
  872. return labels, nil
  873. }
  874. // GetLabelsByIssueID returns all labels that belong to given issue by ID.
  875. func GetLabelsByIssueID(issueID int64) ([]*Label, error) {
  876. return getLabelsByIssueID(x, issueID)
  877. }
  878. func updateLabel(e Engine, l *Label) error {
  879. _, err := e.Id(l.ID).AllCols().Update(l)
  880. return err
  881. }
  882. // UpdateLabel updates label information.
  883. func UpdateLabel(l *Label) error {
  884. return updateLabel(x, l)
  885. }
  886. // DeleteLabel delete a label of given repository.
  887. func DeleteLabel(repoID, labelID int64) error {
  888. l, err := GetLabelByID(labelID)
  889. if err != nil {
  890. if IsErrLabelNotExist(err) {
  891. return nil
  892. }
  893. return err
  894. }
  895. sess := x.NewSession()
  896. defer sessionRelease(sess)
  897. if err = sess.Begin(); err != nil {
  898. return err
  899. }
  900. if _, err = x.Where("label_id=?", labelID).Delete(new(IssueLabel)); err != nil {
  901. return err
  902. } else if _, err = sess.Delete(l); err != nil {
  903. return err
  904. }
  905. return sess.Commit()
  906. }
  907. // .___ .____ ___. .__
  908. // | | ______ ________ __ ____ | | _____ \_ |__ ____ | |
  909. // | |/ ___// ___/ | \_/ __ \| | \__ \ | __ \_/ __ \| |
  910. // | |\___ \ \___ \| | /\ ___/| |___ / __ \| \_\ \ ___/| |__
  911. // |___/____ >____ >____/ \___ >_______ (____ /___ /\___ >____/
  912. // \/ \/ \/ \/ \/ \/ \/
  913. // IssueLabel represetns an issue-lable relation.
  914. type IssueLabel struct {
  915. ID int64 `xorm:"pk autoincr"`
  916. IssueID int64 `xorm:"UNIQUE(s)"`
  917. LabelID int64 `xorm:"UNIQUE(s)"`
  918. }
  919. func hasIssueLabel(e Engine, issueID, labelID int64) bool {
  920. has, _ := e.Where("issue_id=? AND label_id=?", issueID, labelID).Get(new(IssueLabel))
  921. return has
  922. }
  923. // HasIssueLabel returns true if issue has been labeled.
  924. func HasIssueLabel(issueID, labelID int64) bool {
  925. return hasIssueLabel(x, issueID, labelID)
  926. }
  927. func newIssueLabel(e *xorm.Session, issue *Issue, label *Label) (err error) {
  928. if _, err = e.Insert(&IssueLabel{
  929. IssueID: issue.ID,
  930. LabelID: label.ID,
  931. }); err != nil {
  932. return err
  933. }
  934. label.NumIssues++
  935. if issue.IsClosed {
  936. label.NumClosedIssues++
  937. }
  938. return updateLabel(e, label)
  939. }
  940. // NewIssueLabel creates a new issue-label relation.
  941. func NewIssueLabel(issue *Issue, label *Label) (err error) {
  942. sess := x.NewSession()
  943. defer sessionRelease(sess)
  944. if err = sess.Begin(); err != nil {
  945. return err
  946. }
  947. if err = newIssueLabel(sess, issue, label); err != nil {
  948. return err
  949. }
  950. return sess.Commit()
  951. }
  952. func getIssueLabels(e Engine, issueID int64) ([]*IssueLabel, error) {
  953. issueLabels := make([]*IssueLabel, 0, 10)
  954. return issueLabels, e.Where("issue_id=?", issueID).Asc("label_id").Find(&issueLabels)
  955. }
  956. // GetIssueLabels returns all issue-label relations of given issue by ID.
  957. func GetIssueLabels(issueID int64) ([]*IssueLabel, error) {
  958. return getIssueLabels(x, issueID)
  959. }
  960. func deleteIssueLabel(e *xorm.Session, issue *Issue, label *Label) (err error) {
  961. if _, err = e.Delete(&IssueLabel{
  962. IssueID: issue.ID,
  963. LabelID: label.ID,
  964. }); err != nil {
  965. return err
  966. }
  967. label.NumIssues--
  968. if issue.IsClosed {
  969. label.NumClosedIssues--
  970. }
  971. return updateLabel(e, label)
  972. }
  973. // DeleteIssueLabel deletes issue-label relation.
  974. func DeleteIssueLabel(issue *Issue, label *Label) (err error) {
  975. sess := x.NewSession()
  976. defer sessionRelease(sess)
  977. if err = sess.Begin(); err != nil {
  978. return err
  979. }
  980. if err = deleteIssueLabel(sess, issue, label); err != nil {
  981. return err
  982. }
  983. return sess.Commit()
  984. }
  985. // _____ .__.__ __
  986. // / \ |__| | ____ _______/ |_ ____ ____ ____
  987. // / \ / \| | | _/ __ \ / ___/\ __\/ _ \ / \_/ __ \
  988. // / Y \ | |_\ ___/ \___ \ | | ( <_> ) | \ ___/
  989. // \____|__ /__|____/\___ >____ > |__| \____/|___| /\___ >
  990. // \/ \/ \/ \/ \/
  991. // Milestone represents a milestone of repository.
  992. type Milestone struct {
  993. ID int64 `xorm:"pk autoincr"`
  994. RepoID int64 `xorm:"INDEX"`
  995. Name string
  996. Content string `xorm:"TEXT"`
  997. RenderedContent string `xorm:"-"`
  998. IsClosed bool
  999. NumIssues int
  1000. NumClosedIssues int
  1001. NumOpenIssues int `xorm:"-"`
  1002. Completeness int // Percentage(1-100).
  1003. Deadline time.Time
  1004. DeadlineString string `xorm:"-"`
  1005. IsOverDue bool `xorm:"-"`
  1006. ClosedDate time.Time
  1007. }
  1008. func (m *Milestone) BeforeUpdate() {
  1009. if m.NumIssues > 0 {
  1010. m.Completeness = m.NumClosedIssues * 100 / m.NumIssues
  1011. } else {
  1012. m.Completeness = 0
  1013. }
  1014. }
  1015. func (m *Milestone) AfterSet(colName string, _ xorm.Cell) {
  1016. if colName == "deadline" {
  1017. if m.Deadline.Year() == 9999 {
  1018. return
  1019. }
  1020. m.DeadlineString = m.Deadline.Format("2006-01-02")
  1021. if time.Now().After(m.Deadline) {
  1022. m.IsOverDue = true
  1023. }
  1024. }
  1025. }
  1026. // CalOpenIssues calculates the open issues of milestone.
  1027. func (m *Milestone) CalOpenIssues() {
  1028. m.NumOpenIssues = m.NumIssues - m.NumClosedIssues
  1029. }
  1030. // NewMilestone creates new milestone of repository.
  1031. func NewMilestone(m *Milestone) (err error) {
  1032. sess := x.NewSession()
  1033. defer sessionRelease(sess)
  1034. if err = sess.Begin(); err != nil {
  1035. return err
  1036. }
  1037. if _, err = sess.Insert(m); err != nil {
  1038. return err
  1039. }
  1040. if _, err = sess.Exec("UPDATE `repository` SET num_milestones=num_milestones+1 WHERE id=?", m.RepoID); err != nil {
  1041. return err
  1042. }
  1043. return sess.Commit()
  1044. }
  1045. func getMilestoneByID(e Engine, id int64) (*Milestone, error) {
  1046. m := &Milestone{ID: id}
  1047. has, err := e.Get(m)
  1048. if err != nil {
  1049. return nil, err
  1050. } else if !has {
  1051. return nil, ErrMilestoneNotExist{id, 0}
  1052. }
  1053. return m, nil
  1054. }
  1055. // GetMilestoneByID returns the milestone of given ID.
  1056. func GetMilestoneByID(id int64) (*Milestone, error) {
  1057. return getMilestoneByID(x, id)
  1058. }
  1059. // GetRepoMilestoneByID returns the milestone of given ID and repository.
  1060. func GetRepoMilestoneByID(repoID, milestoneID int64) (*Milestone, error) {
  1061. m := &Milestone{ID: milestoneID, RepoID: repoID}
  1062. has, err := x.Get(m)
  1063. if err != nil {
  1064. return nil, err
  1065. } else if !has {
  1066. return nil, ErrMilestoneNotExist{milestoneID, repoID}
  1067. }
  1068. return m, nil
  1069. }
  1070. // GetAllRepoMilestones returns all milestones of given repository.
  1071. func GetAllRepoMilestones(repoID int64) ([]*Milestone, error) {
  1072. miles := make([]*Milestone, 0, 10)
  1073. return miles, x.Where("repo_id=?", repoID).Find(&miles)
  1074. }
  1075. // GetMilestones returns a list of milestones of given repository and status.
  1076. func GetMilestones(repoID int64, page int, isClosed bool) ([]*Milestone, error) {
  1077. miles := make([]*Milestone, 0, setting.IssuePagingNum)
  1078. sess := x.Where("repo_id=? AND is_closed=?", repoID, isClosed)
  1079. if page > 0 {
  1080. sess = sess.Limit(setting.IssuePagingNum, (page-1)*setting.IssuePagingNum)
  1081. }
  1082. return miles, sess.Find(&miles)
  1083. }
  1084. func updateMilestone(e Engine, m *Milestone) error {
  1085. _, err := e.Id(m.ID).AllCols().Update(m)
  1086. return err
  1087. }
  1088. // UpdateMilestone updates information of given milestone.
  1089. func UpdateMilestone(m *Milestone) error {
  1090. return updateMilestone(x, m)
  1091. }
  1092. func countRepoMilestones(e Engine, repoID int64) int64 {
  1093. count, _ := e.Where("repo_id=?", repoID).Count(new(Milestone))
  1094. return count
  1095. }
  1096. // CountRepoMilestones returns number of milestones in given repository.
  1097. func CountRepoMilestones(repoID int64) int64 {
  1098. return countRepoMilestones(x, repoID)
  1099. }
  1100. func countRepoClosedMilestones(e Engine, repoID int64) int64 {
  1101. closed, _ := e.Where("repo_id=? AND is_closed=?", repoID, true).Count(new(Milestone))
  1102. return closed
  1103. }
  1104. // CountRepoClosedMilestones returns number of closed milestones in given repository.
  1105. func CountRepoClosedMilestones(repoID int64) int64 {
  1106. return countRepoClosedMilestones(x, repoID)
  1107. }
  1108. // MilestoneStats returns number of open and closed milestones of given repository.
  1109. func MilestoneStats(repoID int64) (open int64, closed int64) {
  1110. open, _ = x.Where("repo_id=? AND is_closed=?", repoID, false).Count(new(Milestone))
  1111. return open, CountRepoClosedMilestones(repoID)
  1112. }
  1113. // ChangeMilestoneStatus changes the milestone open/closed status.
  1114. func ChangeMilestoneStatus(m *Milestone, isClosed bool) (err error) {
  1115. repo, err := GetRepositoryByID(m.RepoID)
  1116. if err != nil {
  1117. return err
  1118. }
  1119. sess := x.NewSession()
  1120. defer sessionRelease(sess)
  1121. if err = sess.Begin(); err != nil {
  1122. return err
  1123. }
  1124. m.IsClosed = isClosed
  1125. if err = updateMilestone(sess, m); err != nil {
  1126. return err
  1127. }
  1128. repo.NumMilestones = int(countRepoMilestones(sess, repo.ID))
  1129. repo.NumClosedMilestones = int(countRepoClosedMilestones(sess, repo.ID))
  1130. if _, err = sess.Id(repo.ID).AllCols().Update(repo); err != nil {
  1131. return err
  1132. }
  1133. return sess.Commit()
  1134. }
  1135. func changeMilestoneIssueStats(e *xorm.Session, issue *Issue) error {
  1136. if issue.MilestoneID == 0 {
  1137. return nil
  1138. }
  1139. m, err := getMilestoneByID(e, issue.MilestoneID)
  1140. if err != nil {
  1141. return err
  1142. }
  1143. if issue.IsClosed {
  1144. m.NumOpenIssues--
  1145. m.NumClosedIssues++
  1146. } else {
  1147. m.NumOpenIssues++
  1148. m.NumClosedIssues--
  1149. }
  1150. return updateMilestone(e, m)
  1151. }
  1152. // ChangeMilestoneIssueStats updates the open/closed issues counter and progress
  1153. // for the milestone associated witht the given issue.
  1154. func ChangeMilestoneIssueStats(issue *Issue) (err error) {
  1155. sess := x.NewSession()
  1156. defer sessionRelease(sess)
  1157. if err = sess.Begin(); err != nil {
  1158. return err
  1159. }
  1160. if err = changeMilestoneIssueStats(sess, issue); err != nil {
  1161. return err
  1162. }
  1163. return sess.Commit()
  1164. }
  1165. func changeMilestoneAssign(e *xorm.Session, oldMid int64, issue *Issue) error {
  1166. if oldMid > 0 {
  1167. m, err := getMilestoneByID(e, oldMid)
  1168. if err != nil {
  1169. return err
  1170. }
  1171. m.NumIssues--
  1172. if issue.IsClosed {
  1173. m.NumClosedIssues--
  1174. }
  1175. if err = updateMilestone(e, m); err != nil {
  1176. return err
  1177. } else if _, err = e.Exec("UPDATE `issue_user` SET milestone_id=0 WHERE issue_id=?", issue.ID); err != nil {
  1178. return err
  1179. }
  1180. }
  1181. if issue.MilestoneID > 0 {
  1182. m, err := getMilestoneByID(e, issue.MilestoneID)
  1183. if err != nil {
  1184. return err
  1185. }
  1186. m.NumIssues++
  1187. if issue.IsClosed {
  1188. m.NumClosedIssues++
  1189. }
  1190. if m.NumIssues == 0 {
  1191. return ErrWrongIssueCounter
  1192. }
  1193. if err = updateMilestone(e, m); err != nil {
  1194. return err
  1195. } else if _, err = e.Exec("UPDATE `issue_user` SET milestone_id=? WHERE issue_id=?", m.ID, issue.ID); err != nil {
  1196. return err
  1197. }
  1198. }
  1199. return updateIssue(e, issue)
  1200. }
  1201. // ChangeMilestoneAssign changes assignment of milestone for issue.
  1202. func ChangeMilestoneAssign(oldMid int64, issue *Issue) (err error) {
  1203. sess := x.NewSession()
  1204. defer sess.Close()
  1205. if err = sess.Begin(); err != nil {
  1206. return err
  1207. }
  1208. if err = changeMilestoneAssign(sess, oldMid, issue); err != nil {
  1209. return err
  1210. }
  1211. return sess.Commit()
  1212. }
  1213. // DeleteMilestoneByID deletes a milestone by given ID.
  1214. func DeleteMilestoneByID(mid int64) error {
  1215. m, err := GetMilestoneByID(mid)
  1216. if err != nil {
  1217. if IsErrMilestoneNotExist(err) {
  1218. return nil
  1219. }
  1220. return err
  1221. }
  1222. repo, err := GetRepositoryByID(m.RepoID)
  1223. if err != nil {
  1224. return err
  1225. }
  1226. sess := x.NewSession()
  1227. defer sessionRelease(sess)
  1228. if err = sess.Begin(); err != nil {
  1229. return err
  1230. }
  1231. if _, err = sess.Id(m.ID).Delete(m); err != nil {
  1232. return err
  1233. }
  1234. repo.NumMilestones = int(countRepoMilestones(sess, repo.ID))
  1235. repo.NumClosedMilestones = int(countRepoClosedMilestones(sess, repo.ID))
  1236. if _, err = sess.Id(repo.ID).AllCols().Update(repo); err != nil {
  1237. return err
  1238. }
  1239. if _, err = sess.Exec("UPDATE `issue` SET milestone_id=0 WHERE milestone_id=?", m.ID); err != nil {
  1240. return err
  1241. } else if _, err = sess.Exec("UPDATE `issue_user` SET milestone_id=0 WHERE milestone_id=?", m.ID); err != nil {
  1242. return err
  1243. }
  1244. return sess.Commit()
  1245. }
  1246. // _________ __
  1247. // \_ ___ \ ____ _____ _____ ____ _____/ |_
  1248. // / \ \/ / _ \ / \ / \_/ __ \ / \ __\
  1249. // \ \___( <_> ) Y Y \ Y Y \ ___/| | \ |
  1250. // \______ /\____/|__|_| /__|_| /\___ >___| /__|
  1251. // \/ \/ \/ \/ \/
  1252. // CommentType defines whether a comment is just a simple comment, an action (like close) or a reference.
  1253. type CommentType int
  1254. const (
  1255. // Plain comment, can be associated with a commit (CommitId > 0) and a line (Line > 0)
  1256. COMMENT_TYPE_COMMENT CommentType = iota
  1257. COMMENT_TYPE_REOPEN
  1258. COMMENT_TYPE_CLOSE
  1259. // References.
  1260. COMMENT_TYPE_ISSUE_REF
  1261. // Reference from a commit (not part of a pull request)
  1262. COMMENT_TYPE_COMMIT_REF
  1263. // Reference from a comment
  1264. COMMENT_TYPE_COMMENT_REF
  1265. // Reference from a pull request
  1266. COMMENT_TYPE_PULL_REF
  1267. )
  1268. type CommentTag int
  1269. const (
  1270. COMMENT_TAG_NONE CommentTag = iota
  1271. COMMENT_TAG_POSTER
  1272. COMMENT_TAG_ADMIN
  1273. COMMENT_TAG_OWNER
  1274. )
  1275. // Comment represents a comment in commit and issue page.
  1276. type Comment struct {
  1277. ID int64 `xorm:"pk autoincr"`
  1278. Type CommentType
  1279. PosterID int64
  1280. Poster *User `xorm:"-"`
  1281. IssueID int64 `xorm:"INDEX"`
  1282. CommitID int64
  1283. Line int64
  1284. Content string `xorm:"TEXT"`
  1285. RenderedContent string `xorm:"-"`
  1286. Created time.Time `xorm:"CREATED"`
  1287. Attachments []*Attachment `xorm:"-"`
  1288. // For view issue page.
  1289. ShowTag CommentTag `xorm:"-"`
  1290. }
  1291. func (c *Comment) AfterSet(colName string, _ xorm.Cell) {
  1292. var err error
  1293. switch colName {
  1294. case "id":
  1295. c.Attachments, err = GetAttachmentsByCommentID(c.ID)
  1296. if err != nil {
  1297. log.Error(3, "GetAttachmentsByCommentID[%d]: %v", c.ID, err)
  1298. }
  1299. case "poster_id":
  1300. c.Poster, err = GetUserByID(c.PosterID)
  1301. if err != nil {
  1302. if IsErrUserNotExist(err) {
  1303. c.PosterID = -1
  1304. c.Poster = NewFakeUser()
  1305. } else {
  1306. log.Error(3, "GetUserByID[%d]: %v", c.ID, err)
  1307. }
  1308. }
  1309. case "created":
  1310. c.Created = regulateTimeZone(c.Created)
  1311. }
  1312. }
  1313. func (c *Comment) AfterDelete() {
  1314. _, err := DeleteAttachmentsByComment(c.ID, true)
  1315. if err != nil {
  1316. log.Info("Could not delete files for comment %d on issue #%d: %s", c.ID, c.IssueID, err)
  1317. }
  1318. }
  1319. // HashTag returns unique hash tag for comment.
  1320. func (c *Comment) HashTag() string {
  1321. return "issuecomment-" + com.ToStr(c.ID)
  1322. }
  1323. // EventTag returns unique event hash tag for comment.
  1324. func (c *Comment) EventTag() string {
  1325. return "event-" + com.ToStr(c.ID)
  1326. }
  1327. func createComment(e *xorm.Session, u *User, repo *Repository, issue *Issue, commitID, line int64, cmtType CommentType, content string, uuids []string) (_ *Comment, err error) {
  1328. comment := &Comment{
  1329. PosterID: u.Id,
  1330. Type: cmtType,
  1331. IssueID: issue.ID,
  1332. CommitID: commitID,
  1333. Line: line,
  1334. Content: content,
  1335. }
  1336. if _, err = e.Insert(comment); err != nil {
  1337. return nil, err
  1338. }
  1339. // Check comment type.
  1340. switch cmtType {
  1341. case COMMENT_TYPE_COMMENT:
  1342. if _, err = e.Exec("UPDATE `issue` SET num_comments=num_comments+1 WHERE id=?", issue.ID); err != nil {
  1343. return nil, err
  1344. }
  1345. // Check attachments.
  1346. attachments := make([]*Attachment, 0, len(uuids))
  1347. for _, uuid := range uuids {
  1348. attach, err := getAttachmentByUUID(e, uuid)
  1349. if err != nil {
  1350. if IsErrAttachmentNotExist(err) {
  1351. continue
  1352. }
  1353. return nil, fmt.Errorf("getAttachmentByUUID[%s]: %v", uuid, err)
  1354. }
  1355. attachments = append(attachments, attach)
  1356. }
  1357. for i := range attachments {
  1358. attachments[i].IssueID = issue.ID
  1359. attachments[i].CommentID = comment.ID
  1360. // No assign value could be 0, so ignore AllCols().
  1361. if _, err = e.Id(attachments[i].ID).Update(attachments[i]); err != nil {
  1362. return nil, fmt.Errorf("update attachment[%d]: %v", attachments[i].ID, err)
  1363. }
  1364. }
  1365. // Notify watchers.
  1366. act := &Action{
  1367. ActUserID: u.Id,
  1368. ActUserName: u.LowerName,
  1369. ActEmail: u.Email,
  1370. OpType: COMMENT_ISSUE,
  1371. Content: fmt.Sprintf("%d|%s", issue.Index, strings.Split(content, "\n")[0]),
  1372. RepoID: repo.ID,
  1373. RepoUserName: repo.Owner.LowerName,
  1374. RepoName: repo.LowerName,
  1375. IsPrivate: repo.IsPrivate,
  1376. }
  1377. if err = notifyWatchers(e, act); err != nil {
  1378. return nil, err
  1379. }
  1380. case COMMENT_TYPE_REOPEN:
  1381. if _, err = e.Exec("UPDATE `repository` SET num_closed_issues=num_closed_issues-1 WHERE id=?", repo.ID); err != nil {
  1382. return nil, err
  1383. }
  1384. case COMMENT_TYPE_CLOSE:
  1385. if _, err = e.Exec("UPDATE `repository` SET num_closed_issues=num_closed_issues+1 WHERE id=?", repo.ID); err != nil {
  1386. return nil, err
  1387. }
  1388. }
  1389. return comment, nil
  1390. }
  1391. func createStatusComment(e *xorm.Session, doer *User, repo *Repository, issue *Issue) (*Comment, error) {
  1392. cmtType := COMMENT_TYPE_CLOSE
  1393. if !issue.IsClosed {
  1394. cmtType = COMMENT_TYPE_REOPEN
  1395. }
  1396. return createComment(e, doer, repo, issue, 0, 0, cmtType, "", nil)
  1397. }
  1398. // CreateComment creates comment of issue or commit.
  1399. func CreateComment(doer *User, repo *Repository, issue *Issue, commitID, line int64, cmtType CommentType, content string, attachments []string) (comment *Comment, err error) {
  1400. sess := x.NewSession()
  1401. defer sessionRelease(sess)
  1402. if err = sess.Begin(); err != nil {
  1403. return nil, err
  1404. }
  1405. comment, err = createComment(sess, doer, repo, issue, commitID, line, cmtType, content, attachments)
  1406. if err != nil {
  1407. return nil, err
  1408. }
  1409. return comment, sess.Commit()
  1410. }
  1411. // CreateIssueComment creates a plain issue comment.
  1412. func CreateIssueComment(doer *User, repo *Repository, issue *Issue, content string, attachments []string) (*Comment, error) {
  1413. return CreateComment(doer, repo, issue, 0, 0, COMMENT_TYPE_COMMENT, content, attachments)
  1414. }
  1415. // GetCommentByID returns the comment by given ID.
  1416. func GetCommentByID(id int64) (*Comment, error) {
  1417. c := new(Comment)
  1418. has, err := x.Id(id).Get(c)
  1419. if err != nil {
  1420. return nil, err
  1421. } else if !has {
  1422. return nil, ErrCommentNotExist{id}
  1423. }
  1424. return c, nil
  1425. }
  1426. // GetCommentsByIssueID returns all comments of issue by given ID.
  1427. func GetCommentsByIssueID(issueID int64) ([]*Comment, error) {
  1428. comments := make([]*Comment, 0, 10)
  1429. return comments, x.Where("issue_id=?", issueID).Asc("created").Find(&comments)
  1430. }
  1431. // UpdateComment updates information of comment.
  1432. func UpdateComment(c *Comment) error {
  1433. _, err := x.Id(c.ID).AllCols().Update(c)
  1434. return err
  1435. }
  1436. // Attachment represent a attachment of issue/comment/release.
  1437. type Attachment struct {
  1438. ID int64 `xorm:"pk autoincr"`
  1439. UUID string `xorm:"uuid UNIQUE"`
  1440. IssueID int64 `xorm:"INDEX"`
  1441. CommentID int64
  1442. ReleaseID int64 `xorm:"INDEX"`
  1443. Name string
  1444. Created time.Time `xorm:"CREATED"`
  1445. }
  1446. // AttachmentLocalPath returns where attachment is stored in local file system based on given UUID.
  1447. func AttachmentLocalPath(uuid string) string {
  1448. return path.Join(setting.AttachmentPath, uuid[0:1], uuid[1:2], uuid)
  1449. }
  1450. // LocalPath returns where attachment is stored in local file system.
  1451. func (attach *Attachment) LocalPath() string {
  1452. return AttachmentLocalPath(attach.UUID)
  1453. }
  1454. // NewAttachment creates a new attachment object.
  1455. func NewAttachment(name string, buf []byte, file multipart.File) (_ *Attachment, err error) {
  1456. attach := &Attachment{
  1457. UUID: gouuid.NewV4().String(),
  1458. Name: name,
  1459. }
  1460. if err = os.MkdirAll(path.Dir(attach.LocalPath()), os.ModePerm); err != nil {
  1461. return nil, fmt.Errorf("MkdirAll: %v", err)
  1462. }
  1463. fw, err := os.Create(attach.LocalPath())
  1464. if err != nil {
  1465. return nil, fmt.Errorf("Create: %v", err)
  1466. }
  1467. defer fw.Close()
  1468. if _, err = fw.Write(buf); err != nil {
  1469. return nil, fmt.Errorf("Write: %v", err)
  1470. } else if _, err = io.Copy(fw, file); err != nil {
  1471. return nil, fmt.Errorf("Copy: %v", err)
  1472. }
  1473. sess := x.NewSession()
  1474. defer sessionRelease(sess)
  1475. if err := sess.Begin(); err != nil {
  1476. return nil, err
  1477. }
  1478. if _, err := sess.Insert(attach); err != nil {
  1479. return nil, err
  1480. }
  1481. return attach, sess.Commit()
  1482. }
  1483. func getAttachmentByUUID(e Engine, uuid string) (*Attachment, error) {
  1484. attach := &Attachment{UUID: uuid}
  1485. has, err := x.Get(attach)
  1486. if err != nil {
  1487. return nil, err
  1488. } else if !has {
  1489. return nil, ErrAttachmentNotExist{0, uuid}
  1490. }
  1491. return attach, nil
  1492. }
  1493. // GetAttachmentByUUID returns attachment by given UUID.
  1494. func GetAttachmentByUUID(uuid string) (*Attachment, error) {
  1495. return getAttachmentByUUID(x, uuid)
  1496. }
  1497. // GetAttachmentsByIssueID returns all attachments for given issue by ID.
  1498. func GetAttachmentsByIssueID(issueID int64) ([]*Attachment, error) {
  1499. attachments := make([]*Attachment, 0, 10)
  1500. return attachments, x.Where("issue_id=? AND comment_id=0", issueID).Find(&attachments)
  1501. }
  1502. // GetAttachmentsByCommentID returns all attachments if comment by given ID.
  1503. func GetAttachmentsByCommentID(commentID int64) ([]*Attachment, error) {
  1504. attachments := make([]*Attachment, 0, 10)
  1505. return attachments, x.Where("comment_id=?", commentID).Find(&attachments)
  1506. }
  1507. // DeleteAttachment deletes the given attachment and optionally the associated file.
  1508. func DeleteAttachment(a *Attachment, remove bool) error {
  1509. _, err := DeleteAttachments([]*Attachment{a}, remove)
  1510. return err
  1511. }
  1512. // DeleteAttachments deletes the given attachments and optionally the associated files.
  1513. func DeleteAttachments(attachments []*Attachment, remove bool) (int, error) {
  1514. for i, a := range attachments {
  1515. if remove {
  1516. if err := os.Remove(a.LocalPath()); err != nil {
  1517. return i, err
  1518. }
  1519. }
  1520. if _, err := x.Delete(a.ID); err != nil {
  1521. return i, err
  1522. }
  1523. }
  1524. return len(attachments), nil
  1525. }
  1526. // DeleteAttachmentsByIssue deletes all attachments associated with the given issue.
  1527. func DeleteAttachmentsByIssue(issueId int64, remove bool) (int, error) {
  1528. attachments, err := GetAttachmentsByIssueID(issueId)
  1529. if err != nil {
  1530. return 0, err
  1531. }
  1532. return DeleteAttachments(attachments, remove)
  1533. }
  1534. // DeleteAttachmentsByComment deletes all attachments associated with the given comment.
  1535. func DeleteAttachmentsByComment(commentId int64, remove bool) (int, error) {
  1536. attachments, err := GetAttachmentsByCommentID(commentId)
  1537. if err != nil {
  1538. return 0, err
  1539. }
  1540. return DeleteAttachments(attachments, remove)
  1541. }