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

issue.go 51 kB

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