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 49 kB

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