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

issue.go 53 kB

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