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

302 lines
7.0KB

  1. // Copyright 2018 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. "regexp"
  8. "strings"
  9. "code.gitea.io/gitea/modules/timeutil"
  10. "xorm.io/builder"
  11. )
  12. func init() {
  13. tables = append(tables,
  14. new(Topic),
  15. new(RepoTopic),
  16. )
  17. }
  18. var topicPattern = regexp.MustCompile(`^[a-z0-9][a-z0-9-]*$`)
  19. // Topic represents a topic of repositories
  20. type Topic struct {
  21. ID int64
  22. Name string `xorm:"UNIQUE VARCHAR(25)"`
  23. RepoCount int
  24. CreatedUnix timeutil.TimeStamp `xorm:"INDEX created"`
  25. UpdatedUnix timeutil.TimeStamp `xorm:"INDEX updated"`
  26. }
  27. // RepoTopic represents associated repositories and topics
  28. type RepoTopic struct {
  29. RepoID int64 `xorm:"UNIQUE(s)"`
  30. TopicID int64 `xorm:"UNIQUE(s)"`
  31. }
  32. // ErrTopicNotExist represents an error that a topic is not exist
  33. type ErrTopicNotExist struct {
  34. Name string
  35. }
  36. // IsErrTopicNotExist checks if an error is an ErrTopicNotExist.
  37. func IsErrTopicNotExist(err error) bool {
  38. _, ok := err.(ErrTopicNotExist)
  39. return ok
  40. }
  41. // Error implements error interface
  42. func (err ErrTopicNotExist) Error() string {
  43. return fmt.Sprintf("topic is not exist [name: %s]", err.Name)
  44. }
  45. // ValidateTopic checks a topic by length and match pattern rules
  46. func ValidateTopic(topic string) bool {
  47. return len(topic) <= 35 && topicPattern.MatchString(topic)
  48. }
  49. // SanitizeAndValidateTopics sanitizes and checks an array or topics
  50. func SanitizeAndValidateTopics(topics []string) (validTopics []string, invalidTopics []string) {
  51. validTopics = make([]string, 0)
  52. mValidTopics := make(map[string]struct{})
  53. invalidTopics = make([]string, 0)
  54. for _, topic := range topics {
  55. topic = strings.TrimSpace(strings.ToLower(topic))
  56. // ignore empty string
  57. if len(topic) == 0 {
  58. continue
  59. }
  60. // ignore same topic twice
  61. if _, ok := mValidTopics[topic]; ok {
  62. continue
  63. }
  64. if ValidateTopic(topic) {
  65. validTopics = append(validTopics, topic)
  66. mValidTopics[topic] = struct{}{}
  67. } else {
  68. invalidTopics = append(invalidTopics, topic)
  69. }
  70. }
  71. return validTopics, invalidTopics
  72. }
  73. // GetTopicByName retrieves topic by name
  74. func GetTopicByName(name string) (*Topic, error) {
  75. var topic Topic
  76. if has, err := x.Where("name = ?", name).Get(&topic); err != nil {
  77. return nil, err
  78. } else if !has {
  79. return nil, ErrTopicNotExist{name}
  80. }
  81. return &topic, nil
  82. }
  83. // addTopicByNameToRepo adds a topic name to a repo and increments the topic count.
  84. // Returns topic after the addition
  85. func addTopicByNameToRepo(e Engine, repoID int64, topicName string) (*Topic, error) {
  86. var topic Topic
  87. has, err := e.Where("name = ?", topicName).Get(&topic)
  88. if err != nil {
  89. return nil, err
  90. }
  91. if !has {
  92. topic.Name = topicName
  93. topic.RepoCount = 1
  94. if _, err := e.Insert(&topic); err != nil {
  95. return nil, err
  96. }
  97. } else {
  98. topic.RepoCount++
  99. if _, err := e.ID(topic.ID).Cols("repo_count").Update(&topic); err != nil {
  100. return nil, err
  101. }
  102. }
  103. if _, err := e.Insert(&RepoTopic{
  104. RepoID: repoID,
  105. TopicID: topic.ID,
  106. }); err != nil {
  107. return nil, err
  108. }
  109. return &topic, nil
  110. }
  111. // removeTopicFromRepo remove a topic from a repo and decrements the topic repo count
  112. func removeTopicFromRepo(repoID int64, topic *Topic, e Engine) error {
  113. topic.RepoCount--
  114. if _, err := e.ID(topic.ID).Cols("repo_count").Update(topic); err != nil {
  115. return err
  116. }
  117. if _, err := e.Delete(&RepoTopic{
  118. RepoID: repoID,
  119. TopicID: topic.ID,
  120. }); err != nil {
  121. return err
  122. }
  123. return nil
  124. }
  125. // FindTopicOptions represents the options when fdin topics
  126. type FindTopicOptions struct {
  127. RepoID int64
  128. Keyword string
  129. Limit int
  130. Page int
  131. }
  132. func (opts *FindTopicOptions) toConds() builder.Cond {
  133. var cond = builder.NewCond()
  134. if opts.RepoID > 0 {
  135. cond = cond.And(builder.Eq{"repo_topic.repo_id": opts.RepoID})
  136. }
  137. if opts.Keyword != "" {
  138. cond = cond.And(builder.Like{"topic.name", opts.Keyword})
  139. }
  140. return cond
  141. }
  142. // FindTopics retrieves the topics via FindTopicOptions
  143. func FindTopics(opts *FindTopicOptions) (topics []*Topic, err error) {
  144. sess := x.Select("topic.*").Where(opts.toConds())
  145. if opts.RepoID > 0 {
  146. sess.Join("INNER", "repo_topic", "repo_topic.topic_id = topic.id")
  147. }
  148. if opts.Limit > 0 {
  149. sess.Limit(opts.Limit, opts.Page*opts.Limit)
  150. }
  151. return topics, sess.Desc("topic.repo_count").Find(&topics)
  152. }
  153. // GetRepoTopicByName retrives topic from name for a repo if it exist
  154. func GetRepoTopicByName(repoID int64, topicName string) (*Topic, error) {
  155. var cond = builder.NewCond()
  156. var topic Topic
  157. cond = cond.And(builder.Eq{"repo_topic.repo_id": repoID}).And(builder.Eq{"topic.name": topicName})
  158. sess := x.Table("topic").Where(cond)
  159. sess.Join("INNER", "repo_topic", "repo_topic.topic_id = topic.id")
  160. has, err := sess.Get(&topic)
  161. if has {
  162. return &topic, err
  163. }
  164. return nil, err
  165. }
  166. // AddTopic adds a topic name to a repository (if it does not already have it)
  167. func AddTopic(repoID int64, topicName string) (*Topic, error) {
  168. topic, err := GetRepoTopicByName(repoID, topicName)
  169. if err != nil {
  170. return nil, err
  171. }
  172. if topic != nil {
  173. // Repo already have topic
  174. return topic, nil
  175. }
  176. return addTopicByNameToRepo(x, repoID, topicName)
  177. }
  178. // DeleteTopic removes a topic name from a repository (if it has it)
  179. func DeleteTopic(repoID int64, topicName string) (*Topic, error) {
  180. topic, err := GetRepoTopicByName(repoID, topicName)
  181. if err != nil {
  182. return nil, err
  183. }
  184. if topic == nil {
  185. // Repo doesn't have topic, can't be removed
  186. return nil, nil
  187. }
  188. err = removeTopicFromRepo(repoID, topic, x)
  189. return topic, err
  190. }
  191. // SaveTopics save topics to a repository
  192. func SaveTopics(repoID int64, topicNames ...string) error {
  193. topics, err := FindTopics(&FindTopicOptions{
  194. RepoID: repoID,
  195. })
  196. if err != nil {
  197. return err
  198. }
  199. sess := x.NewSession()
  200. defer sess.Close()
  201. if err := sess.Begin(); err != nil {
  202. return err
  203. }
  204. var addedTopicNames []string
  205. for _, topicName := range topicNames {
  206. if strings.TrimSpace(topicName) == "" {
  207. continue
  208. }
  209. var found bool
  210. for _, t := range topics {
  211. if strings.EqualFold(topicName, t.Name) {
  212. found = true
  213. break
  214. }
  215. }
  216. if !found {
  217. addedTopicNames = append(addedTopicNames, topicName)
  218. }
  219. }
  220. var removeTopics []*Topic
  221. for _, t := range topics {
  222. var found bool
  223. for _, topicName := range topicNames {
  224. if strings.EqualFold(topicName, t.Name) {
  225. found = true
  226. break
  227. }
  228. }
  229. if !found {
  230. removeTopics = append(removeTopics, t)
  231. }
  232. }
  233. for _, topicName := range addedTopicNames {
  234. _, err := addTopicByNameToRepo(sess, repoID, topicName)
  235. if err != nil {
  236. return err
  237. }
  238. }
  239. for _, topic := range removeTopics {
  240. err := removeTopicFromRepo(repoID, topic, sess)
  241. if err != nil {
  242. return err
  243. }
  244. }
  245. topicNames = make([]string, 0, 25)
  246. if err := sess.Table("topic").Cols("name").
  247. Join("INNER", "repo_topic", "repo_topic.topic_id = topic.id").
  248. Where("repo_topic.repo_id = ?", repoID).Desc("topic.repo_count").Find(&topicNames); err != nil {
  249. return err
  250. }
  251. if _, err := sess.ID(repoID).Cols("topics").Update(&Repository{
  252. Topics: topicNames,
  253. }); err != nil {
  254. return err
  255. }
  256. return sess.Commit()
  257. }
上海开阖软件有限公司 沪ICP备12045867号-1