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.

repo_list.go 9.4KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325
  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. "strings"
  8. "code.gitea.io/gitea/modules/structs"
  9. "code.gitea.io/gitea/modules/util"
  10. "github.com/go-xorm/builder"
  11. "github.com/go-xorm/core"
  12. )
  13. // RepositoryListDefaultPageSize is the default number of repositories
  14. // to load in memory when running administrative tasks on all (or almost
  15. // all) of them.
  16. // The number should be low enough to avoid filling up all RAM with
  17. // repository data...
  18. const RepositoryListDefaultPageSize = 64
  19. // RepositoryList contains a list of repositories
  20. type RepositoryList []*Repository
  21. func (repos RepositoryList) Len() int {
  22. return len(repos)
  23. }
  24. func (repos RepositoryList) Less(i, j int) bool {
  25. return repos[i].FullName() < repos[j].FullName()
  26. }
  27. func (repos RepositoryList) Swap(i, j int) {
  28. repos[i], repos[j] = repos[j], repos[i]
  29. }
  30. // RepositoryListOfMap make list from values of map
  31. func RepositoryListOfMap(repoMap map[int64]*Repository) RepositoryList {
  32. return RepositoryList(valuesRepository(repoMap))
  33. }
  34. func (repos RepositoryList) loadAttributes(e Engine) error {
  35. if len(repos) == 0 {
  36. return nil
  37. }
  38. // Load owners.
  39. set := make(map[int64]struct{})
  40. for i := range repos {
  41. set[repos[i].OwnerID] = struct{}{}
  42. }
  43. users := make(map[int64]*User, len(set))
  44. if err := e.
  45. Where("id > 0").
  46. In("id", keysInt64(set)).
  47. Find(&users); err != nil {
  48. return fmt.Errorf("find users: %v", err)
  49. }
  50. for i := range repos {
  51. repos[i].Owner = users[repos[i].OwnerID]
  52. }
  53. return nil
  54. }
  55. // LoadAttributes loads the attributes for the given RepositoryList
  56. func (repos RepositoryList) LoadAttributes() error {
  57. return repos.loadAttributes(x)
  58. }
  59. // MirrorRepositoryList contains the mirror repositories
  60. type MirrorRepositoryList []*Repository
  61. func (repos MirrorRepositoryList) loadAttributes(e Engine) error {
  62. if len(repos) == 0 {
  63. return nil
  64. }
  65. // Load mirrors.
  66. repoIDs := make([]int64, 0, len(repos))
  67. for i := range repos {
  68. if !repos[i].IsMirror {
  69. continue
  70. }
  71. repoIDs = append(repoIDs, repos[i].ID)
  72. }
  73. mirrors := make([]*Mirror, 0, len(repoIDs))
  74. if err := e.
  75. Where("id > 0").
  76. In("repo_id", repoIDs).
  77. Find(&mirrors); err != nil {
  78. return fmt.Errorf("find mirrors: %v", err)
  79. }
  80. set := make(map[int64]*Mirror)
  81. for i := range mirrors {
  82. set[mirrors[i].RepoID] = mirrors[i]
  83. }
  84. for i := range repos {
  85. repos[i].Mirror = set[repos[i].ID]
  86. }
  87. return nil
  88. }
  89. // LoadAttributes loads the attributes for the given MirrorRepositoryList
  90. func (repos MirrorRepositoryList) LoadAttributes() error {
  91. return repos.loadAttributes(x)
  92. }
  93. // SearchRepoOptions holds the search options
  94. type SearchRepoOptions struct {
  95. Keyword string
  96. OwnerID int64
  97. OrderBy SearchOrderBy
  98. Private bool // Include private repositories in results
  99. Starred bool
  100. Page int
  101. IsProfile bool
  102. AllPublic bool // Include also all public repositories
  103. PageSize int // Can be smaller than or equal to setting.ExplorePagingNum
  104. // None -> include collaborative AND non-collaborative
  105. // True -> include just collaborative
  106. // False -> incude just non-collaborative
  107. Collaborate util.OptionalBool
  108. // None -> include forks AND non-forks
  109. // True -> include just forks
  110. // False -> include just non-forks
  111. Fork util.OptionalBool
  112. // None -> include mirrors AND non-mirrors
  113. // True -> include just mirrors
  114. // False -> include just non-mirrors
  115. Mirror util.OptionalBool
  116. // only search topic name
  117. TopicOnly bool
  118. }
  119. //SearchOrderBy is used to sort the result
  120. type SearchOrderBy string
  121. func (s SearchOrderBy) String() string {
  122. return string(s)
  123. }
  124. // Strings for sorting result
  125. const (
  126. SearchOrderByAlphabetically SearchOrderBy = "name ASC"
  127. SearchOrderByAlphabeticallyReverse = "name DESC"
  128. SearchOrderByLeastUpdated = "updated_unix ASC"
  129. SearchOrderByRecentUpdated = "updated_unix DESC"
  130. SearchOrderByOldest = "created_unix ASC"
  131. SearchOrderByNewest = "created_unix DESC"
  132. SearchOrderBySize = "size ASC"
  133. SearchOrderBySizeReverse = "size DESC"
  134. SearchOrderByID = "id ASC"
  135. SearchOrderByIDReverse = "id DESC"
  136. SearchOrderByStars = "num_stars ASC"
  137. SearchOrderByStarsReverse = "num_stars DESC"
  138. SearchOrderByForks = "num_forks ASC"
  139. SearchOrderByForksReverse = "num_forks DESC"
  140. )
  141. // SearchRepositoryByName takes keyword and part of repository name to search,
  142. // it returns results in given range and number of total results.
  143. func SearchRepositoryByName(opts *SearchRepoOptions) (RepositoryList, int64, error) {
  144. if opts.Page <= 0 {
  145. opts.Page = 1
  146. }
  147. var cond = builder.NewCond()
  148. if !opts.Private {
  149. cond = cond.And(builder.Eq{"is_private": false})
  150. accessCond := builder.Or(
  151. builder.NotIn("owner_id", builder.Select("id").From("`user`").Where(builder.Or(builder.Eq{"visibility": structs.VisibleTypeLimited}, builder.Eq{"visibility": structs.VisibleTypePrivate}))),
  152. builder.NotIn("owner_id", builder.Select("id").From("`user`").Where(builder.Eq{"type": UserTypeOrganization})))
  153. cond = cond.And(accessCond)
  154. }
  155. if opts.OwnerID > 0 {
  156. if opts.Starred {
  157. cond = cond.And(builder.In("id", builder.Select("repo_id").From("star").Where(builder.Eq{"uid": opts.OwnerID})))
  158. } else {
  159. var accessCond = builder.NewCond()
  160. if opts.Collaborate != util.OptionalBoolTrue {
  161. accessCond = builder.Eq{"owner_id": opts.OwnerID}
  162. }
  163. if opts.Collaborate != util.OptionalBoolFalse {
  164. collaborateCond := builder.And(
  165. builder.Expr("repository.id IN (SELECT repo_id FROM `access` WHERE access.user_id = ?)", opts.OwnerID),
  166. builder.Neq{"owner_id": opts.OwnerID})
  167. if !opts.Private {
  168. collaborateCond = collaborateCond.And(builder.Expr("owner_id NOT IN (SELECT org_id FROM org_user WHERE org_user.uid = ? AND org_user.is_public = ?)", opts.OwnerID, false))
  169. }
  170. accessCond = accessCond.Or(collaborateCond)
  171. }
  172. var exprCond builder.Cond
  173. if DbCfg.Type == core.POSTGRES {
  174. exprCond = builder.Expr("org_user.org_id = \"user\".id")
  175. } else if DbCfg.Type == core.MSSQL {
  176. exprCond = builder.Expr("org_user.org_id = [user].id")
  177. } else {
  178. exprCond = builder.Eq{"org_user.org_id": "user.id"}
  179. }
  180. visibilityCond := builder.Or(
  181. builder.In("owner_id",
  182. builder.Select("org_id").From("org_user").
  183. LeftJoin("`user`", exprCond).
  184. Where(
  185. builder.And(
  186. builder.Eq{"uid": opts.OwnerID},
  187. builder.Eq{"visibility": structs.VisibleTypePrivate})),
  188. ),
  189. builder.In("owner_id",
  190. builder.Select("id").From("`user`").
  191. Where(
  192. builder.Or(
  193. builder.Eq{"visibility": structs.VisibleTypePublic},
  194. builder.Eq{"visibility": structs.VisibleTypeLimited})),
  195. ),
  196. builder.NotIn("owner_id", builder.Select("id").From("`user`").Where(builder.Eq{"type": UserTypeOrganization})),
  197. )
  198. cond = cond.And(visibilityCond)
  199. if opts.AllPublic {
  200. accessCond = accessCond.Or(builder.Eq{"is_private": false})
  201. }
  202. cond = cond.And(accessCond)
  203. }
  204. }
  205. if opts.Keyword != "" {
  206. // separate keyword
  207. var subQueryCond = builder.NewCond()
  208. for _, v := range strings.Split(opts.Keyword, ",") {
  209. subQueryCond = subQueryCond.Or(builder.Like{"topic.name", strings.ToLower(v)})
  210. }
  211. subQuery := builder.Select("repo_topic.repo_id").From("repo_topic").
  212. Join("INNER", "topic", "topic.id = repo_topic.topic_id").
  213. Where(subQueryCond).
  214. GroupBy("repo_topic.repo_id")
  215. var keywordCond = builder.In("id", subQuery)
  216. if !opts.TopicOnly {
  217. var likes = builder.NewCond()
  218. for _, v := range strings.Split(opts.Keyword, ",") {
  219. likes = likes.Or(builder.Like{"lower_name", strings.ToLower(v)})
  220. }
  221. keywordCond = keywordCond.Or(likes)
  222. }
  223. cond = cond.And(keywordCond)
  224. }
  225. if opts.Fork != util.OptionalBoolNone {
  226. cond = cond.And(builder.Eq{"is_fork": opts.Fork == util.OptionalBoolTrue})
  227. }
  228. if opts.Mirror != util.OptionalBoolNone {
  229. cond = cond.And(builder.Eq{"is_mirror": opts.Mirror == util.OptionalBoolTrue})
  230. }
  231. if len(opts.OrderBy) == 0 {
  232. opts.OrderBy = SearchOrderByAlphabetically
  233. }
  234. sess := x.NewSession()
  235. defer sess.Close()
  236. count, err := sess.
  237. Where(cond).
  238. Count(new(Repository))
  239. if err != nil {
  240. return nil, 0, fmt.Errorf("Count: %v", err)
  241. }
  242. repos := make(RepositoryList, 0, opts.PageSize)
  243. if err = sess.
  244. Where(cond).
  245. OrderBy(opts.OrderBy.String()).
  246. Limit(opts.PageSize, (opts.Page-1)*opts.PageSize).
  247. Find(&repos); err != nil {
  248. return nil, 0, fmt.Errorf("Repo: %v", err)
  249. }
  250. if !opts.IsProfile {
  251. if err = repos.loadAttributes(sess); err != nil {
  252. return nil, 0, fmt.Errorf("LoadAttributes: %v", err)
  253. }
  254. }
  255. return repos, count, nil
  256. }
  257. // FindUserAccessibleRepoIDs find all accessible repositories' ID by user's id
  258. func FindUserAccessibleRepoIDs(userID int64) ([]int64, error) {
  259. var accessCond builder.Cond = builder.Eq{"is_private": false}
  260. if userID > 0 {
  261. accessCond = accessCond.Or(
  262. builder.Eq{"owner_id": userID},
  263. builder.And(
  264. builder.Expr("id IN (SELECT repo_id FROM `access` WHERE access.user_id = ?)", userID),
  265. builder.Neq{"owner_id": userID},
  266. ),
  267. )
  268. }
  269. repoIDs := make([]int64, 0, 10)
  270. if err := x.
  271. Table("repository").
  272. Cols("id").
  273. Where(accessCond).
  274. Find(&repoIDs); err != nil {
  275. return nil, fmt.Errorf("FindUserAccesibleRepoIDs: %v", err)
  276. }
  277. return repoIDs, nil
  278. }