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 11KB

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