本站源代码
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.

482 lines
12KB

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