issue.go 50 KB

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