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.

471 lines
12 KiB

8 years ago
  1. // Copyright 2016 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. "fmt"
  7. "html/template"
  8. "regexp"
  9. "strconv"
  10. "strings"
  11. api "code.gitea.io/gitea/modules/structs"
  12. "github.com/go-xorm/xorm"
  13. )
  14. var labelColorPattern = regexp.MustCompile("#([a-fA-F0-9]{6})")
  15. // GetLabelTemplateFile loads the label template file by given name,
  16. // then parses and returns a list of name-color pairs and optionally description.
  17. func GetLabelTemplateFile(name string) ([][3]string, error) {
  18. data, err := getRepoInitFile("label", name)
  19. if err != nil {
  20. return nil, fmt.Errorf("getRepoInitFile: %v", err)
  21. }
  22. lines := strings.Split(string(data), "\n")
  23. list := make([][3]string, 0, len(lines))
  24. for i := 0; i < len(lines); i++ {
  25. line := strings.TrimSpace(lines[i])
  26. if len(line) == 0 {
  27. continue
  28. }
  29. parts := strings.SplitN(line, ";", 2)
  30. fields := strings.SplitN(parts[0], " ", 2)
  31. if len(fields) != 2 {
  32. return nil, fmt.Errorf("line is malformed: %s", line)
  33. }
  34. if !labelColorPattern.MatchString(fields[0]) {
  35. return nil, fmt.Errorf("bad HTML color code in line: %s", line)
  36. }
  37. var description string
  38. if len(parts) > 1 {
  39. description = strings.TrimSpace(parts[1])
  40. }
  41. fields[1] = strings.TrimSpace(fields[1])
  42. list = append(list, [3]string{fields[1], fields[0], description})
  43. }
  44. return list, nil
  45. }
  46. // Label represents a label of repository for issues.
  47. type Label struct {
  48. ID int64 `xorm:"pk autoincr"`
  49. RepoID int64 `xorm:"INDEX"`
  50. Name string
  51. Description string
  52. Color string `xorm:"VARCHAR(7)"`
  53. NumIssues int
  54. NumClosedIssues int
  55. NumOpenIssues int `xorm:"-"`
  56. IsChecked bool `xorm:"-"`
  57. QueryString string
  58. IsSelected bool
  59. }
  60. // APIFormat converts a Label to the api.Label format
  61. func (label *Label) APIFormat() *api.Label {
  62. return &api.Label{
  63. ID: label.ID,
  64. Name: label.Name,
  65. Color: strings.TrimLeft(label.Color, "#"),
  66. Description: label.Description,
  67. }
  68. }
  69. // CalOpenIssues calculates the open issues of label.
  70. func (label *Label) CalOpenIssues() {
  71. label.NumOpenIssues = label.NumIssues - label.NumClosedIssues
  72. }
  73. // LoadSelectedLabelsAfterClick calculates the set of selected labels when a label is clicked
  74. func (label *Label) LoadSelectedLabelsAfterClick(currentSelectedLabels []int64) {
  75. var labelQuerySlice []string
  76. labelSelected := false
  77. labelID := strconv.FormatInt(label.ID, 10)
  78. for _, s := range currentSelectedLabels {
  79. if s == label.ID {
  80. labelSelected = true
  81. } else if s > 0 {
  82. labelQuerySlice = append(labelQuerySlice, strconv.FormatInt(s, 10))
  83. }
  84. }
  85. if !labelSelected {
  86. labelQuerySlice = append(labelQuerySlice, labelID)
  87. }
  88. label.IsSelected = labelSelected
  89. label.QueryString = strings.Join(labelQuerySlice, ",")
  90. }
  91. // ForegroundColor calculates the text color for labels based
  92. // on their background color.
  93. func (label *Label) ForegroundColor() template.CSS {
  94. if strings.HasPrefix(label.Color, "#") {
  95. if color, err := strconv.ParseUint(label.Color[1:], 16, 64); err == nil {
  96. r := float32(0xFF & (color >> 16))
  97. g := float32(0xFF & (color >> 8))
  98. b := float32(0xFF & color)
  99. luminance := (0.2126*r + 0.7152*g + 0.0722*b) / 255
  100. if luminance < 0.66 {
  101. return template.CSS("#fff")
  102. }
  103. }
  104. }
  105. // default to black
  106. return template.CSS("#000")
  107. }
  108. func initalizeLabels(e Engine, repoID int64, labelTemplate string) error {
  109. list, err := GetLabelTemplateFile(labelTemplate)
  110. if err != nil {
  111. return ErrIssueLabelTemplateLoad{labelTemplate, err}
  112. }
  113. labels := make([]*Label, len(list))
  114. for i := 0; i < len(list); i++ {
  115. labels[i] = &Label{
  116. RepoID: repoID,
  117. Name: list[i][0],
  118. Description: list[i][2],
  119. Color: list[i][1],
  120. }
  121. }
  122. for _, label := range labels {
  123. if err = newLabel(e, label); err != nil {
  124. return err
  125. }
  126. }
  127. return nil
  128. }
  129. // InitalizeLabels adds a label set to a repository using a template
  130. func InitalizeLabels(repoID int64, labelTemplate string) error {
  131. return initalizeLabels(x, repoID, labelTemplate)
  132. }
  133. func newLabel(e Engine, label *Label) error {
  134. _, err := e.Insert(label)
  135. return err
  136. }
  137. // NewLabel creates a new label for a repository
  138. func NewLabel(label *Label) error {
  139. return newLabel(x, label)
  140. }
  141. // NewLabels creates new labels for a repository.
  142. func NewLabels(labels ...*Label) error {
  143. sess := x.NewSession()
  144. defer sess.Close()
  145. if err := sess.Begin(); err != nil {
  146. return err
  147. }
  148. for _, label := range labels {
  149. if err := newLabel(sess, label); err != nil {
  150. return err
  151. }
  152. }
  153. return sess.Commit()
  154. }
  155. // getLabelInRepoByName returns a label by Name in given repository.
  156. // If pass repoID as 0, then ORM will ignore limitation of repository
  157. // and can return arbitrary label with any valid ID.
  158. func getLabelInRepoByName(e Engine, repoID int64, labelName string) (*Label, error) {
  159. if len(labelName) == 0 {
  160. return nil, ErrLabelNotExist{0, repoID}
  161. }
  162. l := &Label{
  163. Name: labelName,
  164. RepoID: repoID,
  165. }
  166. has, err := e.Get(l)
  167. if err != nil {
  168. return nil, err
  169. } else if !has {
  170. return nil, ErrLabelNotExist{0, l.RepoID}
  171. }
  172. return l, nil
  173. }
  174. // getLabelInRepoByID returns a label by ID in given repository.
  175. // If pass repoID as 0, then ORM will ignore limitation of repository
  176. // and can return arbitrary label with any valid ID.
  177. func getLabelInRepoByID(e Engine, repoID, labelID int64) (*Label, error) {
  178. if labelID <= 0 {
  179. return nil, ErrLabelNotExist{labelID, repoID}
  180. }
  181. l := &Label{
  182. ID: labelID,
  183. RepoID: repoID,
  184. }
  185. has, err := e.Get(l)
  186. if err != nil {
  187. return nil, err
  188. } else if !has {
  189. return nil, ErrLabelNotExist{l.ID, l.RepoID}
  190. }
  191. return l, nil
  192. }
  193. // GetLabelByID returns a label by given ID.
  194. func GetLabelByID(id int64) (*Label, error) {
  195. return getLabelInRepoByID(x, 0, id)
  196. }
  197. // GetLabelInRepoByName returns a label by name in given repository.
  198. func GetLabelInRepoByName(repoID int64, labelName string) (*Label, error) {
  199. return getLabelInRepoByName(x, repoID, labelName)
  200. }
  201. // GetLabelIDsInRepoByNames returns a list of labelIDs by names in a given
  202. // repository.
  203. // it silently ignores label names that do not belong to the repository.
  204. func GetLabelIDsInRepoByNames(repoID int64, labelNames []string) ([]int64, error) {
  205. labelIDs := make([]int64, 0, len(labelNames))
  206. return labelIDs, x.Table("label").
  207. Where("repo_id = ?", repoID).
  208. In("name", labelNames).
  209. Asc("name").
  210. Cols("id").
  211. Find(&labelIDs)
  212. }
  213. // GetLabelInRepoByID returns a label by ID in given repository.
  214. func GetLabelInRepoByID(repoID, labelID int64) (*Label, error) {
  215. return getLabelInRepoByID(x, repoID, labelID)
  216. }
  217. // GetLabelsInRepoByIDs returns a list of labels by IDs in given repository,
  218. // it silently ignores label IDs that do not belong to the repository.
  219. func GetLabelsInRepoByIDs(repoID int64, labelIDs []int64) ([]*Label, error) {
  220. labels := make([]*Label, 0, len(labelIDs))
  221. return labels, x.
  222. Where("repo_id = ?", repoID).
  223. In("id", labelIDs).
  224. Asc("name").
  225. Find(&labels)
  226. }
  227. // GetLabelsByRepoID returns all labels that belong to given repository by ID.
  228. func GetLabelsByRepoID(repoID int64, sortType string) ([]*Label, error) {
  229. labels := make([]*Label, 0, 10)
  230. sess := x.Where("repo_id = ?", repoID)
  231. switch sortType {
  232. case "reversealphabetically":
  233. sess.Desc("name")
  234. case "leastissues":
  235. sess.Asc("num_issues")
  236. case "mostissues":
  237. sess.Desc("num_issues")
  238. default:
  239. sess.Asc("name")
  240. }
  241. return labels, sess.Find(&labels)
  242. }
  243. func getLabelsByIssueID(e Engine, issueID int64) ([]*Label, error) {
  244. var labels []*Label
  245. return labels, e.Where("issue_label.issue_id = ?", issueID).
  246. Join("LEFT", "issue_label", "issue_label.label_id = label.id").
  247. Asc("label.name").
  248. Find(&labels)
  249. }
  250. // GetLabelsByIssueID returns all labels that belong to given issue by ID.
  251. func GetLabelsByIssueID(issueID int64) ([]*Label, error) {
  252. return getLabelsByIssueID(x, issueID)
  253. }
  254. func updateLabel(e Engine, l *Label) error {
  255. _, err := e.ID(l.ID).AllCols().Update(l)
  256. return err
  257. }
  258. // UpdateLabel updates label information.
  259. func UpdateLabel(l *Label) error {
  260. return updateLabel(x, l)
  261. }
  262. // DeleteLabel delete a label of given repository.
  263. func DeleteLabel(repoID, labelID int64) error {
  264. _, err := GetLabelInRepoByID(repoID, labelID)
  265. if err != nil {
  266. if IsErrLabelNotExist(err) {
  267. return nil
  268. }
  269. return err
  270. }
  271. sess := x.NewSession()
  272. defer sess.Close()
  273. if err = sess.Begin(); err != nil {
  274. return err
  275. }
  276. if _, err = sess.ID(labelID).Delete(new(Label)); err != nil {
  277. return err
  278. } else if _, err = sess.
  279. Where("label_id = ?", labelID).
  280. Delete(new(IssueLabel)); err != nil {
  281. return err
  282. }
  283. // Clear label id in comment table
  284. if _, err = sess.Where("label_id = ?", labelID).Cols("label_id").Update(&Comment{}); err != nil {
  285. return err
  286. }
  287. return sess.Commit()
  288. }
  289. // .___ .____ ___. .__
  290. // | | ______ ________ __ ____ | | _____ \_ |__ ____ | |
  291. // | |/ ___// ___/ | \_/ __ \| | \__ \ | __ \_/ __ \| |
  292. // | |\___ \ \___ \| | /\ ___/| |___ / __ \| \_\ \ ___/| |__
  293. // |___/____ >____ >____/ \___ >_______ (____ /___ /\___ >____/
  294. // \/ \/ \/ \/ \/ \/ \/
  295. // IssueLabel represents an issue-label relation.
  296. type IssueLabel struct {
  297. ID int64 `xorm:"pk autoincr"`
  298. IssueID int64 `xorm:"UNIQUE(s)"`
  299. LabelID int64 `xorm:"UNIQUE(s)"`
  300. }
  301. func hasIssueLabel(e Engine, issueID, labelID int64) bool {
  302. has, _ := e.Where("issue_id = ? AND label_id = ?", issueID, labelID).Get(new(IssueLabel))
  303. return has
  304. }
  305. // HasIssueLabel returns true if issue has been labeled.
  306. func HasIssueLabel(issueID, labelID int64) bool {
  307. return hasIssueLabel(x, issueID, labelID)
  308. }
  309. func newIssueLabel(e *xorm.Session, issue *Issue, label *Label, doer *User) (err error) {
  310. if _, err = e.Insert(&IssueLabel{
  311. IssueID: issue.ID,
  312. LabelID: label.ID,
  313. }); err != nil {
  314. return err
  315. }
  316. if err = issue.loadRepo(e); err != nil {
  317. return
  318. }
  319. if _, err = createLabelComment(e, doer, issue.Repo, issue, label, true); err != nil {
  320. return err
  321. }
  322. label.NumIssues++
  323. if issue.IsClosed {
  324. label.NumClosedIssues++
  325. }
  326. return updateLabel(e, label)
  327. }
  328. // NewIssueLabel creates a new issue-label relation.
  329. func NewIssueLabel(issue *Issue, label *Label, doer *User) (err error) {
  330. if HasIssueLabel(issue.ID, label.ID) {
  331. return nil
  332. }
  333. sess := x.NewSession()
  334. defer sess.Close()
  335. if err = sess.Begin(); err != nil {
  336. return err
  337. }
  338. if err = newIssueLabel(sess, issue, label, doer); err != nil {
  339. return err
  340. }
  341. return sess.Commit()
  342. }
  343. func newIssueLabels(e *xorm.Session, issue *Issue, labels []*Label, doer *User) (err error) {
  344. for i := range labels {
  345. if hasIssueLabel(e, issue.ID, labels[i].ID) {
  346. continue
  347. }
  348. if err = newIssueLabel(e, issue, labels[i], doer); err != nil {
  349. return fmt.Errorf("newIssueLabel: %v", err)
  350. }
  351. }
  352. return nil
  353. }
  354. // NewIssueLabels creates a list of issue-label relations.
  355. func NewIssueLabels(issue *Issue, labels []*Label, doer *User) (err error) {
  356. sess := x.NewSession()
  357. defer sess.Close()
  358. if err = sess.Begin(); err != nil {
  359. return err
  360. }
  361. if err = newIssueLabels(sess, issue, labels, doer); err != nil {
  362. return err
  363. }
  364. return sess.Commit()
  365. }
  366. func deleteIssueLabel(e *xorm.Session, issue *Issue, label *Label, doer *User) (err error) {
  367. if count, err := e.Delete(&IssueLabel{
  368. IssueID: issue.ID,
  369. LabelID: label.ID,
  370. }); err != nil {
  371. return err
  372. } else if count == 0 {
  373. return nil
  374. }
  375. if err = issue.loadRepo(e); err != nil {
  376. return
  377. }
  378. if _, err = createLabelComment(e, doer, issue.Repo, issue, label, false); err != nil {
  379. return err
  380. }
  381. label.NumIssues--
  382. if issue.IsClosed {
  383. label.NumClosedIssues--
  384. }
  385. return updateLabel(e, label)
  386. }
  387. // DeleteIssueLabel deletes issue-label relation.
  388. func DeleteIssueLabel(issue *Issue, label *Label, doer *User) (err error) {
  389. sess := x.NewSession()
  390. defer sess.Close()
  391. if err = sess.Begin(); err != nil {
  392. return err
  393. }
  394. if err = deleteIssueLabel(sess, issue, label, doer); err != nil {
  395. return err
  396. }
  397. return sess.Commit()
  398. }