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

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382
  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. ListOptions
  95. Actor *User
  96. Keyword string
  97. OwnerID int64
  98. PriorityOwnerID int64
  99. OrderBy SearchOrderBy
  100. Private bool // Include private repositories in results
  101. StarredByID int64
  102. IsProfile bool
  103. AllPublic bool // Include also all public repositories of users and public organisations
  104. AllLimited bool // Include also all public repositories of limited organisations
  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 templates AND non-templates
  114. // True -> include just templates
  115. // False -> include just non-templates
  116. Template util.OptionalBool
  117. // None -> include mirrors AND non-mirrors
  118. // True -> include just mirrors
  119. // False -> include just non-mirrors
  120. Mirror util.OptionalBool
  121. // only search topic name
  122. TopicOnly bool
  123. // include description in keyword search
  124. IncludeDescription bool
  125. }
  126. //SearchOrderBy is used to sort the result
  127. type SearchOrderBy string
  128. func (s SearchOrderBy) String() string {
  129. return string(s)
  130. }
  131. // Strings for sorting result
  132. const (
  133. SearchOrderByAlphabetically SearchOrderBy = "name ASC"
  134. SearchOrderByAlphabeticallyReverse SearchOrderBy = "name DESC"
  135. SearchOrderByLeastUpdated SearchOrderBy = "updated_unix ASC"
  136. SearchOrderByRecentUpdated SearchOrderBy = "updated_unix DESC"
  137. SearchOrderByOldest SearchOrderBy = "created_unix ASC"
  138. SearchOrderByNewest SearchOrderBy = "created_unix DESC"
  139. SearchOrderBySize SearchOrderBy = "size ASC"
  140. SearchOrderBySizeReverse SearchOrderBy = "size DESC"
  141. SearchOrderByID SearchOrderBy = "id ASC"
  142. SearchOrderByIDReverse SearchOrderBy = "id DESC"
  143. SearchOrderByStars SearchOrderBy = "num_stars ASC"
  144. SearchOrderByStarsReverse SearchOrderBy = "num_stars DESC"
  145. SearchOrderByForks SearchOrderBy = "num_forks ASC"
  146. SearchOrderByForksReverse SearchOrderBy = "num_forks DESC"
  147. )
  148. // SearchRepository returns repositories based on search options,
  149. // it returns results in given range and number of total results.
  150. func SearchRepository(opts *SearchRepoOptions) (RepositoryList, int64, error) {
  151. if opts.Page <= 0 {
  152. opts.Page = 1
  153. }
  154. var cond = builder.NewCond()
  155. if opts.Private {
  156. if opts.Actor != nil && !opts.Actor.IsAdmin && opts.Actor.ID != opts.OwnerID {
  157. // OK we're in the context of a User
  158. cond = cond.And(accessibleRepositoryCondition(opts.Actor))
  159. }
  160. } else {
  161. // Not looking at private organisations
  162. // We should be able to see all non-private repositories that either:
  163. cond = cond.And(builder.Eq{"is_private": false})
  164. accessCond := builder.Or(
  165. // A. Aren't in organisations __OR__
  166. builder.NotIn("owner_id", builder.Select("id").From("`user`").Where(builder.Eq{"type": UserTypeOrganization})),
  167. // B. Isn't a private or limited organisation.
  168. builder.NotIn("owner_id", builder.Select("id").From("`user`").Where(builder.Or(builder.Eq{"visibility": structs.VisibleTypeLimited}, builder.Eq{"visibility": structs.VisibleTypePrivate}))))
  169. cond = cond.And(accessCond)
  170. }
  171. if opts.Template != util.OptionalBoolNone {
  172. cond = cond.And(builder.Eq{"is_template": opts.Template == util.OptionalBoolTrue})
  173. }
  174. // Restrict to starred repositories
  175. if opts.StarredByID > 0 {
  176. cond = cond.And(builder.In("id", builder.Select("repo_id").From("star").Where(builder.Eq{"uid": opts.StarredByID})))
  177. }
  178. // Restrict repositories to those the OwnerID owns or contributes to as per opts.Collaborate
  179. if opts.OwnerID > 0 {
  180. var accessCond = builder.NewCond()
  181. if opts.Collaborate != util.OptionalBoolTrue {
  182. accessCond = builder.Eq{"owner_id": opts.OwnerID}
  183. }
  184. if opts.Collaborate != util.OptionalBoolFalse {
  185. collaborateCond := builder.And(
  186. builder.Or(
  187. builder.Expr("repository.id IN (SELECT repo_id FROM `access` WHERE access.user_id = ?)", opts.OwnerID),
  188. builder.In("id", builder.Select("`team_repo`.repo_id").
  189. From("team_repo").
  190. Where(builder.Eq{"`team_user`.uid": opts.OwnerID}).
  191. Join("INNER", "team_user", "`team_user`.team_id = `team_repo`.team_id"))),
  192. builder.Neq{"owner_id": opts.OwnerID})
  193. if !opts.Private {
  194. 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))
  195. }
  196. accessCond = accessCond.Or(collaborateCond)
  197. }
  198. if opts.AllPublic {
  199. accessCond = accessCond.Or(builder.Eq{"is_private": false}.And(builder.In("owner_id", builder.Select("`user`.id").From("`user`").Where(builder.Eq{"`user`.visibility": structs.VisibleTypePublic}))))
  200. }
  201. if opts.AllLimited {
  202. accessCond = accessCond.Or(builder.Eq{"is_private": false}.And(builder.In("owner_id", builder.Select("`user`.id").From("`user`").Where(builder.Eq{"`user`.visibility": structs.VisibleTypeLimited}))))
  203. }
  204. cond = cond.And(accessCond)
  205. }
  206. if opts.Keyword != "" {
  207. // separate keyword
  208. var subQueryCond = builder.NewCond()
  209. for _, v := range strings.Split(opts.Keyword, ",") {
  210. if opts.TopicOnly {
  211. subQueryCond = subQueryCond.Or(builder.Eq{"topic.name": strings.ToLower(v)})
  212. } else {
  213. subQueryCond = subQueryCond.Or(builder.Like{"topic.name", strings.ToLower(v)})
  214. }
  215. }
  216. subQuery := builder.Select("repo_topic.repo_id").From("repo_topic").
  217. Join("INNER", "topic", "topic.id = repo_topic.topic_id").
  218. Where(subQueryCond).
  219. GroupBy("repo_topic.repo_id")
  220. var keywordCond = builder.In("id", subQuery)
  221. if !opts.TopicOnly {
  222. var likes = builder.NewCond()
  223. for _, v := range strings.Split(opts.Keyword, ",") {
  224. likes = likes.Or(builder.Like{"lower_name", strings.ToLower(v)})
  225. if opts.IncludeDescription {
  226. likes = likes.Or(builder.Like{"LOWER(description)", strings.ToLower(v)})
  227. }
  228. }
  229. keywordCond = keywordCond.Or(likes)
  230. }
  231. cond = cond.And(keywordCond)
  232. }
  233. if opts.Fork != util.OptionalBoolNone {
  234. cond = cond.And(builder.Eq{"is_fork": opts.Fork == util.OptionalBoolTrue})
  235. }
  236. if opts.Mirror != util.OptionalBoolNone {
  237. cond = cond.And(builder.Eq{"is_mirror": opts.Mirror == util.OptionalBoolTrue})
  238. }
  239. if opts.Actor != nil && opts.Actor.IsRestricted {
  240. cond = cond.And(accessibleRepositoryCondition(opts.Actor))
  241. }
  242. if len(opts.OrderBy) == 0 {
  243. opts.OrderBy = SearchOrderByAlphabetically
  244. }
  245. if opts.PriorityOwnerID > 0 {
  246. opts.OrderBy = SearchOrderBy(fmt.Sprintf("CASE WHEN owner_id = %d THEN 0 ELSE owner_id END, %s", opts.PriorityOwnerID, opts.OrderBy))
  247. }
  248. sess := x.NewSession()
  249. defer sess.Close()
  250. count, err := sess.
  251. Where(cond).
  252. Count(new(Repository))
  253. if err != nil {
  254. return nil, 0, fmt.Errorf("Count: %v", err)
  255. }
  256. repos := make(RepositoryList, 0, opts.PageSize)
  257. if err = sess.
  258. Where(cond).
  259. OrderBy(opts.OrderBy.String()).
  260. Limit(opts.PageSize, (opts.Page-1)*opts.PageSize).
  261. Find(&repos); err != nil {
  262. return nil, 0, fmt.Errorf("Repo: %v", err)
  263. }
  264. if !opts.IsProfile {
  265. if err = repos.loadAttributes(sess); err != nil {
  266. return nil, 0, fmt.Errorf("LoadAttributes: %v", err)
  267. }
  268. }
  269. return repos, count, nil
  270. }
  271. // accessibleRepositoryCondition takes a user a returns a condition for checking if a repository is accessible
  272. func accessibleRepositoryCondition(user *User) builder.Cond {
  273. var cond = builder.NewCond()
  274. if user == nil || !user.IsRestricted || user.ID <= 0 {
  275. orgVisibilityLimit := []structs.VisibleType{structs.VisibleTypePrivate}
  276. if user == nil || user.ID <= 0 {
  277. orgVisibilityLimit = append(orgVisibilityLimit, structs.VisibleTypeLimited)
  278. }
  279. // 1. Be able to see all non-private repositories that either:
  280. cond = cond.Or(builder.And(
  281. builder.Eq{"`repository`.is_private": false},
  282. builder.Or(
  283. // A. Aren't in organisations __OR__
  284. builder.NotIn("`repository`.owner_id", builder.Select("id").From("`user`").Where(builder.Eq{"type": UserTypeOrganization})),
  285. // B. Isn't a private organisation. Limited is OK as long as we're logged in.
  286. builder.NotIn("`repository`.owner_id", builder.Select("id").From("`user`").Where(builder.In("visibility", orgVisibilityLimit))))))
  287. }
  288. if user != nil {
  289. // 2. Be able to see all repositories that we have access to
  290. cond = cond.Or(builder.Or(
  291. builder.In("`repository`.id", builder.Select("repo_id").
  292. From("`access`").
  293. Where(builder.And(
  294. builder.Eq{"user_id": user.ID},
  295. builder.Gt{"mode": int(AccessModeNone)}))),
  296. builder.In("`repository`.id", builder.Select("id").
  297. From("`repository`").
  298. Where(builder.Eq{"owner_id": user.ID}))))
  299. // 3. Be able to see all repositories that we are in a team
  300. cond = cond.Or(builder.In("`repository`.id", builder.Select("`team_repo`.repo_id").
  301. From("team_repo").
  302. Where(builder.Eq{"`team_user`.uid": user.ID}).
  303. Join("INNER", "team_user", "`team_user`.team_id = `team_repo`.team_id")))
  304. }
  305. return cond
  306. }
  307. // SearchRepositoryByName takes keyword and part of repository name to search,
  308. // it returns results in given range and number of total results.
  309. func SearchRepositoryByName(opts *SearchRepoOptions) (RepositoryList, int64, error) {
  310. opts.IncludeDescription = false
  311. return SearchRepository(opts)
  312. }
  313. // AccessibleRepoIDsQuery queries accessible repository ids. Usable as a subquery wherever repo ids need to be filtered.
  314. func AccessibleRepoIDsQuery(user *User) *builder.Builder {
  315. // NB: Please note this code needs to still work if user is nil
  316. return builder.Select("id").From("repository").Where(accessibleRepositoryCondition(user))
  317. }
  318. // FindUserAccessibleRepoIDs find all accessible repositories' ID by user's id
  319. func FindUserAccessibleRepoIDs(user *User) ([]int64, error) {
  320. repoIDs := make([]int64, 0, 10)
  321. if err := x.
  322. Table("repository").
  323. Cols("id").
  324. Where(accessibleRepositoryCondition(user)).
  325. Find(&repoIDs); err != nil {
  326. return nil, fmt.Errorf("FindUserAccesibleRepoIDs: %v", err)
  327. }
  328. return repoIDs, nil
  329. }