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

issue.go 50KB

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