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

467 lines
11 KiB

Shows total tracked time in issue and milestone list (#3341) * Show total tracked time in issue and milestone list Show total tracked time at issue page Signed-off-by: Jonas Franz <info@jonasfranz.software> * Optimizing TotalTimes by using SumInt Signed-off-by: Jonas Franz <info@jonasfranz.software> * Fixing wrong total times for milestones caused by a missing JOIN Adding unit tests for total times Signed-off-by: Jonas Franz <info@jonasfranz.software> * Logging error instead of ignoring it Signed-off-by: Jonas Franz <info@jonasfranz.software> * Correcting spelling mistakes Signed-off-by: Jonas Franz <info@jonasfranz.software> * Change error message to a short version Signed-off-by: Jonas Franz <info@jonasfranz.software> * Add error handling to TotalTimes Add variable for totalTimes Signed-off-by: Jonas Franz <info@jonasfranz.de> * Introduce TotalTrackedTimes as variable of issue Load TotalTrackedTimes by loading attributes of IssueList Load TotalTrackedTimes by loading attributes of single issue Add Sec2Time as helper to use it in templates Signed-off-by: Jonas Franz <info@jonasfranz.software> * Fixed test + gofmt Signed-off-by: Jonas Franz <info@jonasfranz.software> * Load TotalTrackedTimes via MilestoneList instead of single requests Signed-off-by: Jonas Franz <info@jonasfranz.software> * Add documentation for MilestoneList Signed-off-by: Jonas Franz <info@jonasfranz.software> * Add documentation for MilestoneList Signed-off-by: Jonas Franz <info@jonasfranz.software> * Fix test Signed-off-by: Jonas Franz <info@jonasfranz.software> * Change comment from SQL query to description Signed-off-by: Jonas Franz <info@jonasfranz.software> * Fix unit test by using int64 instead of int Signed-off-by: Jonas Franz <info@jonasfranz.software> * Fix unit test by using int64 instead of int Signed-off-by: Jonas Franz <info@jonasfranz.software> * Check if timetracker is enabled Signed-off-by: Jonas Franz <info@jonasfranz.software> * Fix test by enabling timetracking Signed-off-by: Jonas Franz <info@jonasfranz.de>
6 years ago
Shows total tracked time in issue and milestone list (#3341) * Show total tracked time in issue and milestone list Show total tracked time at issue page Signed-off-by: Jonas Franz <info@jonasfranz.software> * Optimizing TotalTimes by using SumInt Signed-off-by: Jonas Franz <info@jonasfranz.software> * Fixing wrong total times for milestones caused by a missing JOIN Adding unit tests for total times Signed-off-by: Jonas Franz <info@jonasfranz.software> * Logging error instead of ignoring it Signed-off-by: Jonas Franz <info@jonasfranz.software> * Correcting spelling mistakes Signed-off-by: Jonas Franz <info@jonasfranz.software> * Change error message to a short version Signed-off-by: Jonas Franz <info@jonasfranz.software> * Add error handling to TotalTimes Add variable for totalTimes Signed-off-by: Jonas Franz <info@jonasfranz.de> * Introduce TotalTrackedTimes as variable of issue Load TotalTrackedTimes by loading attributes of IssueList Load TotalTrackedTimes by loading attributes of single issue Add Sec2Time as helper to use it in templates Signed-off-by: Jonas Franz <info@jonasfranz.software> * Fixed test + gofmt Signed-off-by: Jonas Franz <info@jonasfranz.software> * Load TotalTrackedTimes via MilestoneList instead of single requests Signed-off-by: Jonas Franz <info@jonasfranz.software> * Add documentation for MilestoneList Signed-off-by: Jonas Franz <info@jonasfranz.software> * Add documentation for MilestoneList Signed-off-by: Jonas Franz <info@jonasfranz.software> * Fix test Signed-off-by: Jonas Franz <info@jonasfranz.software> * Change comment from SQL query to description Signed-off-by: Jonas Franz <info@jonasfranz.software> * Fix unit test by using int64 instead of int Signed-off-by: Jonas Franz <info@jonasfranz.software> * Fix unit test by using int64 instead of int Signed-off-by: Jonas Franz <info@jonasfranz.software> * Check if timetracker is enabled Signed-off-by: Jonas Franz <info@jonasfranz.software> * Fix test by enabling timetracking Signed-off-by: Jonas Franz <info@jonasfranz.de>
6 years ago
Shows total tracked time in issue and milestone list (#3341) * Show total tracked time in issue and milestone list Show total tracked time at issue page Signed-off-by: Jonas Franz <info@jonasfranz.software> * Optimizing TotalTimes by using SumInt Signed-off-by: Jonas Franz <info@jonasfranz.software> * Fixing wrong total times for milestones caused by a missing JOIN Adding unit tests for total times Signed-off-by: Jonas Franz <info@jonasfranz.software> * Logging error instead of ignoring it Signed-off-by: Jonas Franz <info@jonasfranz.software> * Correcting spelling mistakes Signed-off-by: Jonas Franz <info@jonasfranz.software> * Change error message to a short version Signed-off-by: Jonas Franz <info@jonasfranz.software> * Add error handling to TotalTimes Add variable for totalTimes Signed-off-by: Jonas Franz <info@jonasfranz.de> * Introduce TotalTrackedTimes as variable of issue Load TotalTrackedTimes by loading attributes of IssueList Load TotalTrackedTimes by loading attributes of single issue Add Sec2Time as helper to use it in templates Signed-off-by: Jonas Franz <info@jonasfranz.software> * Fixed test + gofmt Signed-off-by: Jonas Franz <info@jonasfranz.software> * Load TotalTrackedTimes via MilestoneList instead of single requests Signed-off-by: Jonas Franz <info@jonasfranz.software> * Add documentation for MilestoneList Signed-off-by: Jonas Franz <info@jonasfranz.software> * Add documentation for MilestoneList Signed-off-by: Jonas Franz <info@jonasfranz.software> * Fix test Signed-off-by: Jonas Franz <info@jonasfranz.software> * Change comment from SQL query to description Signed-off-by: Jonas Franz <info@jonasfranz.software> * Fix unit test by using int64 instead of int Signed-off-by: Jonas Franz <info@jonasfranz.software> * Fix unit test by using int64 instead of int Signed-off-by: Jonas Franz <info@jonasfranz.software> * Check if timetracker is enabled Signed-off-by: Jonas Franz <info@jonasfranz.software> * Fix test by enabling timetracking Signed-off-by: Jonas Franz <info@jonasfranz.de>
6 years ago
Shows total tracked time in issue and milestone list (#3341) * Show total tracked time in issue and milestone list Show total tracked time at issue page Signed-off-by: Jonas Franz <info@jonasfranz.software> * Optimizing TotalTimes by using SumInt Signed-off-by: Jonas Franz <info@jonasfranz.software> * Fixing wrong total times for milestones caused by a missing JOIN Adding unit tests for total times Signed-off-by: Jonas Franz <info@jonasfranz.software> * Logging error instead of ignoring it Signed-off-by: Jonas Franz <info@jonasfranz.software> * Correcting spelling mistakes Signed-off-by: Jonas Franz <info@jonasfranz.software> * Change error message to a short version Signed-off-by: Jonas Franz <info@jonasfranz.software> * Add error handling to TotalTimes Add variable for totalTimes Signed-off-by: Jonas Franz <info@jonasfranz.de> * Introduce TotalTrackedTimes as variable of issue Load TotalTrackedTimes by loading attributes of IssueList Load TotalTrackedTimes by loading attributes of single issue Add Sec2Time as helper to use it in templates Signed-off-by: Jonas Franz <info@jonasfranz.software> * Fixed test + gofmt Signed-off-by: Jonas Franz <info@jonasfranz.software> * Load TotalTrackedTimes via MilestoneList instead of single requests Signed-off-by: Jonas Franz <info@jonasfranz.software> * Add documentation for MilestoneList Signed-off-by: Jonas Franz <info@jonasfranz.software> * Add documentation for MilestoneList Signed-off-by: Jonas Franz <info@jonasfranz.software> * Fix test Signed-off-by: Jonas Franz <info@jonasfranz.software> * Change comment from SQL query to description Signed-off-by: Jonas Franz <info@jonasfranz.software> * Fix unit test by using int64 instead of int Signed-off-by: Jonas Franz <info@jonasfranz.software> * Fix unit test by using int64 instead of int Signed-off-by: Jonas Franz <info@jonasfranz.software> * Check if timetracker is enabled Signed-off-by: Jonas Franz <info@jonasfranz.software> * Fix test by enabling timetracking Signed-off-by: Jonas Franz <info@jonasfranz.de>
6 years ago
Better logging (#6038) (#6095) * Panic don't fatal on create new logger Fixes #5854 Signed-off-by: Andrew Thornton <art27@cantab.net> * partial broken * Update the logging infrastrcture Signed-off-by: Andrew Thornton <art27@cantab.net> * Reset the skip levels for Fatal and Error Signed-off-by: Andrew Thornton <art27@cantab.net> * broken ncsa * More log.Error fixes Signed-off-by: Andrew Thornton <art27@cantab.net> * Remove nal * set log-levels to lowercase * Make console_test test all levels * switch to lowercased levels * OK now working * Fix vetting issues * Fix lint * Fix tests * change default logging to match current gitea * Improve log testing Signed-off-by: Andrew Thornton <art27@cantab.net> * reset error skip levels to 0 * Update documentation and access logger configuration * Redirect the router log back to gitea if redirect macaron log but also allow setting the log level - i.e. TRACE * Fix broken level caching * Refactor the router log * Add Router logger * Add colorizing options * Adjust router colors * Only create logger if they will be used * update app.ini.sample * rename Attribute ColorAttribute * Change from white to green for function * Set fatal/error levels * Restore initial trace logger * Fix Trace arguments in modules/auth/auth.go * Properly handle XORMLogger * Improve admin/config page * fix fmt * Add auto-compression of old logs * Update error log levels * Remove the unnecessary skip argument from Error, Fatal and Critical * Add stacktrace support * Fix tests * Remove x/sync from vendors? * Add stderr option to console logger * Use filepath.ToSlash to protect against Windows in tests * Remove prefixed underscores from names in colors.go * Remove not implemented database logger This was removed from Gogs on 4 Mar 2016 but left in the configuration since then. * Ensure that log paths are relative to ROOT_PATH * use path.Join * rename jsonConfig to logConfig * Rename "config" to "jsonConfig" to make it clearer * Requested changes * Requested changes: XormLogger * Try to color the windows terminal If successful default to colorizing the console logs * fixup * Colorize initially too * update vendor * Colorize logs on default and remove if this is not a colorizing logger * Fix documentation * fix test * Use go-isatty to detect if on windows we are on msys or cygwin * Fix spelling mistake * Add missing vendors * More changes * Rationalise the ANSI writer protection * Adjust colors on advice from @0x5c * Make Flags a comma separated list * Move to use the windows constant for ENABLE_VIRTUAL_TERMINAL_PROCESSING * Ensure matching is done on the non-colored message - to simpify EXPRESSION
5 years ago
Better logging (#6038) (#6095) * Panic don't fatal on create new logger Fixes #5854 Signed-off-by: Andrew Thornton <art27@cantab.net> * partial broken * Update the logging infrastrcture Signed-off-by: Andrew Thornton <art27@cantab.net> * Reset the skip levels for Fatal and Error Signed-off-by: Andrew Thornton <art27@cantab.net> * broken ncsa * More log.Error fixes Signed-off-by: Andrew Thornton <art27@cantab.net> * Remove nal * set log-levels to lowercase * Make console_test test all levels * switch to lowercased levels * OK now working * Fix vetting issues * Fix lint * Fix tests * change default logging to match current gitea * Improve log testing Signed-off-by: Andrew Thornton <art27@cantab.net> * reset error skip levels to 0 * Update documentation and access logger configuration * Redirect the router log back to gitea if redirect macaron log but also allow setting the log level - i.e. TRACE * Fix broken level caching * Refactor the router log * Add Router logger * Add colorizing options * Adjust router colors * Only create logger if they will be used * update app.ini.sample * rename Attribute ColorAttribute * Change from white to green for function * Set fatal/error levels * Restore initial trace logger * Fix Trace arguments in modules/auth/auth.go * Properly handle XORMLogger * Improve admin/config page * fix fmt * Add auto-compression of old logs * Update error log levels * Remove the unnecessary skip argument from Error, Fatal and Critical * Add stacktrace support * Fix tests * Remove x/sync from vendors? * Add stderr option to console logger * Use filepath.ToSlash to protect against Windows in tests * Remove prefixed underscores from names in colors.go * Remove not implemented database logger This was removed from Gogs on 4 Mar 2016 but left in the configuration since then. * Ensure that log paths are relative to ROOT_PATH * use path.Join * rename jsonConfig to logConfig * Rename "config" to "jsonConfig" to make it clearer * Requested changes * Requested changes: XormLogger * Try to color the windows terminal If successful default to colorizing the console logs * fixup * Colorize initially too * update vendor * Colorize logs on default and remove if this is not a colorizing logger * Fix documentation * fix test * Use go-isatty to detect if on windows we are on msys or cygwin * Fix spelling mistake * Add missing vendors * More changes * Rationalise the ANSI writer protection * Adjust colors on advice from @0x5c * Make Flags a comma separated list * Move to use the windows constant for ENABLE_VIRTUAL_TERMINAL_PROCESSING * Ensure matching is done on the non-colored message - to simpify EXPRESSION
5 years ago
  1. // Copyright 2017 The Gitea 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. "fmt"
  7. "code.gitea.io/gitea/modules/log"
  8. "code.gitea.io/gitea/modules/setting"
  9. api "code.gitea.io/gitea/modules/structs"
  10. "code.gitea.io/gitea/modules/util"
  11. "github.com/go-xorm/xorm"
  12. )
  13. // Milestone represents a milestone of repository.
  14. type Milestone struct {
  15. ID int64 `xorm:"pk autoincr"`
  16. RepoID int64 `xorm:"INDEX"`
  17. Name string
  18. Content string `xorm:"TEXT"`
  19. RenderedContent string `xorm:"-"`
  20. IsClosed bool
  21. NumIssues int
  22. NumClosedIssues int
  23. NumOpenIssues int `xorm:"-"`
  24. Completeness int // Percentage(1-100).
  25. IsOverdue bool `xorm:"-"`
  26. DeadlineString string `xorm:"-"`
  27. DeadlineUnix util.TimeStamp
  28. ClosedDateUnix util.TimeStamp
  29. TotalTrackedTime int64 `xorm:"-"`
  30. }
  31. // BeforeUpdate is invoked from XORM before updating this object.
  32. func (m *Milestone) BeforeUpdate() {
  33. if m.NumIssues > 0 {
  34. m.Completeness = m.NumClosedIssues * 100 / m.NumIssues
  35. } else {
  36. m.Completeness = 0
  37. }
  38. }
  39. // AfterLoad is invoked from XORM after setting the value of a field of
  40. // this object.
  41. func (m *Milestone) AfterLoad() {
  42. m.NumOpenIssues = m.NumIssues - m.NumClosedIssues
  43. if m.DeadlineUnix.Year() == 9999 {
  44. return
  45. }
  46. m.DeadlineString = m.DeadlineUnix.Format("2006-01-02")
  47. if util.TimeStampNow() >= m.DeadlineUnix {
  48. m.IsOverdue = true
  49. }
  50. }
  51. // State returns string representation of milestone status.
  52. func (m *Milestone) State() api.StateType {
  53. if m.IsClosed {
  54. return api.StateClosed
  55. }
  56. return api.StateOpen
  57. }
  58. // APIFormat returns this Milestone in API format.
  59. func (m *Milestone) APIFormat() *api.Milestone {
  60. apiMilestone := &api.Milestone{
  61. ID: m.ID,
  62. State: m.State(),
  63. Title: m.Name,
  64. Description: m.Content,
  65. OpenIssues: m.NumOpenIssues,
  66. ClosedIssues: m.NumClosedIssues,
  67. }
  68. if m.IsClosed {
  69. apiMilestone.Closed = m.ClosedDateUnix.AsTimePtr()
  70. }
  71. if m.DeadlineUnix.Year() < 9999 {
  72. apiMilestone.Deadline = m.DeadlineUnix.AsTimePtr()
  73. }
  74. return apiMilestone
  75. }
  76. // NewMilestone creates new milestone of repository.
  77. func NewMilestone(m *Milestone) (err error) {
  78. sess := x.NewSession()
  79. defer sess.Close()
  80. if err = sess.Begin(); err != nil {
  81. return err
  82. }
  83. if _, err = sess.Insert(m); err != nil {
  84. return err
  85. }
  86. if _, err = sess.Exec("UPDATE `repository` SET num_milestones = num_milestones + 1 WHERE id = ?", m.RepoID); err != nil {
  87. return err
  88. }
  89. return sess.Commit()
  90. }
  91. func getMilestoneByRepoID(e Engine, repoID, id int64) (*Milestone, error) {
  92. m := &Milestone{
  93. ID: id,
  94. RepoID: repoID,
  95. }
  96. has, err := e.Get(m)
  97. if err != nil {
  98. return nil, err
  99. } else if !has {
  100. return nil, ErrMilestoneNotExist{id, repoID}
  101. }
  102. return m, nil
  103. }
  104. // GetMilestoneByRepoID returns the milestone in a repository.
  105. func GetMilestoneByRepoID(repoID, id int64) (*Milestone, error) {
  106. return getMilestoneByRepoID(x, repoID, id)
  107. }
  108. // GetMilestoneByID returns the milestone via id .
  109. func GetMilestoneByID(id int64) (*Milestone, error) {
  110. var m Milestone
  111. has, err := x.ID(id).Get(&m)
  112. if err != nil {
  113. return nil, err
  114. } else if !has {
  115. return nil, ErrMilestoneNotExist{id, 0}
  116. }
  117. return &m, nil
  118. }
  119. // MilestoneList is a list of milestones offering additional functionality
  120. type MilestoneList []*Milestone
  121. func (milestones MilestoneList) loadTotalTrackedTimes(e Engine) error {
  122. type totalTimesByMilestone struct {
  123. MilestoneID int64
  124. Time int64
  125. }
  126. if len(milestones) == 0 {
  127. return nil
  128. }
  129. var trackedTimes = make(map[int64]int64, len(milestones))
  130. // Get total tracked time by milestone_id
  131. rows, err := e.Table("issue").
  132. Join("INNER", "milestone", "issue.milestone_id = milestone.id").
  133. Join("LEFT", "tracked_time", "tracked_time.issue_id = issue.id").
  134. Select("milestone_id, sum(time) as time").
  135. In("milestone_id", milestones.getMilestoneIDs()).
  136. GroupBy("milestone_id").
  137. Rows(new(totalTimesByMilestone))
  138. if err != nil {
  139. return err
  140. }
  141. defer rows.Close()
  142. for rows.Next() {
  143. var totalTime totalTimesByMilestone
  144. err = rows.Scan(&totalTime)
  145. if err != nil {
  146. return err
  147. }
  148. trackedTimes[totalTime.MilestoneID] = totalTime.Time
  149. }
  150. for _, milestone := range milestones {
  151. milestone.TotalTrackedTime = trackedTimes[milestone.ID]
  152. }
  153. return nil
  154. }
  155. // LoadTotalTrackedTimes loads for every milestone in the list the TotalTrackedTime by a batch request
  156. func (milestones MilestoneList) LoadTotalTrackedTimes() error {
  157. return milestones.loadTotalTrackedTimes(x)
  158. }
  159. func (milestones MilestoneList) getMilestoneIDs() []int64 {
  160. var ids = make([]int64, 0, len(milestones))
  161. for _, ms := range milestones {
  162. ids = append(ids, ms.ID)
  163. }
  164. return ids
  165. }
  166. // GetMilestonesByRepoID returns all opened milestones of a repository.
  167. func GetMilestonesByRepoID(repoID int64) (MilestoneList, error) {
  168. miles := make([]*Milestone, 0, 10)
  169. return miles, x.Where("repo_id = ? AND is_closed = ?", repoID, false).
  170. Asc("deadline_unix").Asc("id").Find(&miles)
  171. }
  172. // GetMilestones returns a list of milestones of given repository and status.
  173. func GetMilestones(repoID int64, page int, isClosed bool, sortType string) (MilestoneList, error) {
  174. miles := make([]*Milestone, 0, setting.UI.IssuePagingNum)
  175. sess := x.Where("repo_id = ? AND is_closed = ?", repoID, isClosed)
  176. if page > 0 {
  177. sess = sess.Limit(setting.UI.IssuePagingNum, (page-1)*setting.UI.IssuePagingNum)
  178. }
  179. switch sortType {
  180. case "furthestduedate":
  181. sess.Desc("deadline_unix")
  182. case "leastcomplete":
  183. sess.Asc("completeness")
  184. case "mostcomplete":
  185. sess.Desc("completeness")
  186. case "leastissues":
  187. sess.Asc("num_issues")
  188. case "mostissues":
  189. sess.Desc("num_issues")
  190. default:
  191. sess.Asc("deadline_unix")
  192. }
  193. return miles, sess.Find(&miles)
  194. }
  195. func updateMilestone(e Engine, m *Milestone) error {
  196. _, err := e.ID(m.ID).AllCols().Update(m)
  197. return err
  198. }
  199. // UpdateMilestone updates information of given milestone.
  200. func UpdateMilestone(m *Milestone) error {
  201. return updateMilestone(x, m)
  202. }
  203. func countRepoMilestones(e Engine, repoID int64) (int64, error) {
  204. return e.
  205. Where("repo_id=?", repoID).
  206. Count(new(Milestone))
  207. }
  208. func countRepoClosedMilestones(e Engine, repoID int64) (int64, error) {
  209. return e.
  210. Where("repo_id=? AND is_closed=?", repoID, true).
  211. Count(new(Milestone))
  212. }
  213. // CountRepoClosedMilestones returns number of closed milestones in given repository.
  214. func CountRepoClosedMilestones(repoID int64) (int64, error) {
  215. return countRepoClosedMilestones(x, repoID)
  216. }
  217. // MilestoneStats returns number of open and closed milestones of given repository.
  218. func MilestoneStats(repoID int64) (open int64, closed int64, err error) {
  219. open, err = x.
  220. Where("repo_id=? AND is_closed=?", repoID, false).
  221. Count(new(Milestone))
  222. if err != nil {
  223. return 0, 0, nil
  224. }
  225. closed, err = CountRepoClosedMilestones(repoID)
  226. return open, closed, err
  227. }
  228. // ChangeMilestoneStatus changes the milestone open/closed status.
  229. func ChangeMilestoneStatus(m *Milestone, isClosed bool) (err error) {
  230. repo, err := GetRepositoryByID(m.RepoID)
  231. if err != nil {
  232. return err
  233. }
  234. sess := x.NewSession()
  235. defer sess.Close()
  236. if err = sess.Begin(); err != nil {
  237. return err
  238. }
  239. m.IsClosed = isClosed
  240. if err = updateMilestone(sess, m); err != nil {
  241. return err
  242. }
  243. numMilestones, err := countRepoMilestones(sess, repo.ID)
  244. if err != nil {
  245. return err
  246. }
  247. numClosedMilestones, err := countRepoClosedMilestones(sess, repo.ID)
  248. if err != nil {
  249. return err
  250. }
  251. repo.NumMilestones = int(numMilestones)
  252. repo.NumClosedMilestones = int(numClosedMilestones)
  253. if _, err = sess.ID(repo.ID).Cols("num_milestones, num_closed_milestones").Update(repo); err != nil {
  254. return err
  255. }
  256. return sess.Commit()
  257. }
  258. func changeMilestoneIssueStats(e *xorm.Session, issue *Issue) error {
  259. if issue.MilestoneID == 0 {
  260. return nil
  261. }
  262. m, err := getMilestoneByRepoID(e, issue.RepoID, issue.MilestoneID)
  263. if err != nil {
  264. return err
  265. }
  266. if issue.IsClosed {
  267. m.NumOpenIssues--
  268. m.NumClosedIssues++
  269. } else {
  270. m.NumOpenIssues++
  271. m.NumClosedIssues--
  272. }
  273. return updateMilestone(e, m)
  274. }
  275. func changeMilestoneAssign(e *xorm.Session, doer *User, issue *Issue, oldMilestoneID int64) error {
  276. if oldMilestoneID > 0 {
  277. m, err := getMilestoneByRepoID(e, issue.RepoID, oldMilestoneID)
  278. if err != nil {
  279. return err
  280. }
  281. m.NumIssues--
  282. if issue.IsClosed {
  283. m.NumClosedIssues--
  284. }
  285. if err = updateMilestone(e, m); err != nil {
  286. return err
  287. }
  288. }
  289. if issue.MilestoneID > 0 {
  290. m, err := getMilestoneByRepoID(e, issue.RepoID, issue.MilestoneID)
  291. if err != nil {
  292. return err
  293. }
  294. m.NumIssues++
  295. if issue.IsClosed {
  296. m.NumClosedIssues++
  297. }
  298. if err = updateMilestone(e, m); err != nil {
  299. return err
  300. }
  301. }
  302. if err := issue.loadRepo(e); err != nil {
  303. return err
  304. }
  305. if oldMilestoneID > 0 || issue.MilestoneID > 0 {
  306. if _, err := createMilestoneComment(e, doer, issue.Repo, issue, oldMilestoneID, issue.MilestoneID); err != nil {
  307. return err
  308. }
  309. }
  310. return updateIssueCols(e, issue, "milestone_id")
  311. }
  312. // ChangeMilestoneAssign changes assignment of milestone for issue.
  313. func ChangeMilestoneAssign(issue *Issue, doer *User, oldMilestoneID int64) (err error) {
  314. sess := x.NewSession()
  315. defer sess.Close()
  316. if err = sess.Begin(); err != nil {
  317. return err
  318. }
  319. if err = changeMilestoneAssign(sess, doer, issue, oldMilestoneID); err != nil {
  320. return err
  321. }
  322. if err = sess.Commit(); err != nil {
  323. return fmt.Errorf("Commit: %v", err)
  324. }
  325. var hookAction api.HookIssueAction
  326. if issue.MilestoneID > 0 {
  327. hookAction = api.HookIssueMilestoned
  328. } else {
  329. hookAction = api.HookIssueDemilestoned
  330. }
  331. if err = issue.LoadAttributes(); err != nil {
  332. return err
  333. }
  334. mode, _ := AccessLevel(doer, issue.Repo)
  335. if issue.IsPull {
  336. err = issue.PullRequest.LoadIssue()
  337. if err != nil {
  338. log.Error("LoadIssue: %v", err)
  339. return
  340. }
  341. err = PrepareWebhooks(issue.Repo, HookEventPullRequest, &api.PullRequestPayload{
  342. Action: hookAction,
  343. Index: issue.Index,
  344. PullRequest: issue.PullRequest.APIFormat(),
  345. Repository: issue.Repo.APIFormat(mode),
  346. Sender: doer.APIFormat(),
  347. })
  348. } else {
  349. err = PrepareWebhooks(issue.Repo, HookEventIssues, &api.IssuePayload{
  350. Action: hookAction,
  351. Index: issue.Index,
  352. Issue: issue.APIFormat(),
  353. Repository: issue.Repo.APIFormat(mode),
  354. Sender: doer.APIFormat(),
  355. })
  356. }
  357. if err != nil {
  358. log.Error("PrepareWebhooks [is_pull: %v]: %v", issue.IsPull, err)
  359. } else {
  360. go HookQueue.Add(issue.RepoID)
  361. }
  362. return nil
  363. }
  364. // DeleteMilestoneByRepoID deletes a milestone from a repository.
  365. func DeleteMilestoneByRepoID(repoID, id int64) error {
  366. m, err := GetMilestoneByRepoID(repoID, id)
  367. if err != nil {
  368. if IsErrMilestoneNotExist(err) {
  369. return nil
  370. }
  371. return err
  372. }
  373. repo, err := GetRepositoryByID(m.RepoID)
  374. if err != nil {
  375. return err
  376. }
  377. sess := x.NewSession()
  378. defer sess.Close()
  379. if err = sess.Begin(); err != nil {
  380. return err
  381. }
  382. if _, err = sess.ID(m.ID).Delete(new(Milestone)); err != nil {
  383. return err
  384. }
  385. numMilestones, err := countRepoMilestones(sess, repo.ID)
  386. if err != nil {
  387. return err
  388. }
  389. numClosedMilestones, err := countRepoClosedMilestones(sess, repo.ID)
  390. if err != nil {
  391. return err
  392. }
  393. repo.NumMilestones = int(numMilestones)
  394. repo.NumClosedMilestones = int(numClosedMilestones)
  395. if _, err = sess.ID(repo.ID).Cols("num_milestones, num_closed_milestones").Update(repo); err != nil {
  396. return err
  397. }
  398. if _, err = sess.Exec("UPDATE `issue` SET milestone_id = 0 WHERE milestone_id = ?", m.ID); err != nil {
  399. return err
  400. }
  401. return sess.Commit()
  402. }