issue.go 52 KB

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