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.

topic.go 7.0KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300
  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. ListOptions
  128. RepoID int64
  129. Keyword string
  130. }
  131. func (opts *FindTopicOptions) toConds() builder.Cond {
  132. var cond = builder.NewCond()
  133. if opts.RepoID > 0 {
  134. cond = cond.And(builder.Eq{"repo_topic.repo_id": opts.RepoID})
  135. }
  136. if opts.Keyword != "" {
  137. cond = cond.And(builder.Like{"topic.name", opts.Keyword})
  138. }
  139. return cond
  140. }
  141. // FindTopics retrieves the topics via FindTopicOptions
  142. func FindTopics(opts *FindTopicOptions) (topics []*Topic, err error) {
  143. sess := x.Select("topic.*").Where(opts.toConds())
  144. if opts.RepoID > 0 {
  145. sess.Join("INNER", "repo_topic", "repo_topic.topic_id = topic.id")
  146. }
  147. if opts.PageSize != 0 && opts.Page != 0 {
  148. sess = opts.setSessionPagination(sess)
  149. }
  150. return topics, sess.Desc("topic.repo_count").Find(&topics)
  151. }
  152. // GetRepoTopicByName retrives topic from name for a repo if it exist
  153. func GetRepoTopicByName(repoID int64, topicName string) (*Topic, error) {
  154. var cond = builder.NewCond()
  155. var topic Topic
  156. cond = cond.And(builder.Eq{"repo_topic.repo_id": repoID}).And(builder.Eq{"topic.name": topicName})
  157. sess := x.Table("topic").Where(cond)
  158. sess.Join("INNER", "repo_topic", "repo_topic.topic_id = topic.id")
  159. has, err := sess.Get(&topic)
  160. if has {
  161. return &topic, err
  162. }
  163. return nil, err
  164. }
  165. // AddTopic adds a topic name to a repository (if it does not already have it)
  166. func AddTopic(repoID int64, topicName string) (*Topic, error) {
  167. topic, err := GetRepoTopicByName(repoID, topicName)
  168. if err != nil {
  169. return nil, err
  170. }
  171. if topic != nil {
  172. // Repo already have topic
  173. return topic, nil
  174. }
  175. return addTopicByNameToRepo(x, repoID, topicName)
  176. }
  177. // DeleteTopic removes a topic name from a repository (if it has it)
  178. func DeleteTopic(repoID int64, topicName string) (*Topic, error) {
  179. topic, err := GetRepoTopicByName(repoID, topicName)
  180. if err != nil {
  181. return nil, err
  182. }
  183. if topic == nil {
  184. // Repo doesn't have topic, can't be removed
  185. return nil, nil
  186. }
  187. err = removeTopicFromRepo(repoID, topic, x)
  188. return topic, err
  189. }
  190. // SaveTopics save topics to a repository
  191. func SaveTopics(repoID int64, topicNames ...string) error {
  192. topics, err := FindTopics(&FindTopicOptions{
  193. RepoID: repoID,
  194. })
  195. if err != nil {
  196. return err
  197. }
  198. sess := x.NewSession()
  199. defer sess.Close()
  200. if err := sess.Begin(); err != nil {
  201. return err
  202. }
  203. var addedTopicNames []string
  204. for _, topicName := range topicNames {
  205. if strings.TrimSpace(topicName) == "" {
  206. continue
  207. }
  208. var found bool
  209. for _, t := range topics {
  210. if strings.EqualFold(topicName, t.Name) {
  211. found = true
  212. break
  213. }
  214. }
  215. if !found {
  216. addedTopicNames = append(addedTopicNames, topicName)
  217. }
  218. }
  219. var removeTopics []*Topic
  220. for _, t := range topics {
  221. var found bool
  222. for _, topicName := range topicNames {
  223. if strings.EqualFold(topicName, t.Name) {
  224. found = true
  225. break
  226. }
  227. }
  228. if !found {
  229. removeTopics = append(removeTopics, t)
  230. }
  231. }
  232. for _, topicName := range addedTopicNames {
  233. _, err := addTopicByNameToRepo(sess, repoID, topicName)
  234. if err != nil {
  235. return err
  236. }
  237. }
  238. for _, topic := range removeTopics {
  239. err := removeTopicFromRepo(repoID, topic, sess)
  240. if err != nil {
  241. return err
  242. }
  243. }
  244. topicNames = make([]string, 0, 25)
  245. if err := sess.Table("topic").Cols("name").
  246. Join("INNER", "repo_topic", "repo_topic.topic_id = topic.id").
  247. Where("repo_topic.repo_id = ?", repoID).Desc("topic.repo_count").Find(&topicNames); err != nil {
  248. return err
  249. }
  250. if _, err := sess.ID(repoID).Cols("topics").Update(&Repository{
  251. Topics: topicNames,
  252. }); err != nil {
  253. return err
  254. }
  255. return sess.Commit()
  256. }