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

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504
  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/models/db"
  9. "code.gitea.io/gitea/models/perm"
  10. user_model "code.gitea.io/gitea/models/user"
  11. "code.gitea.io/gitea/modules/structs"
  12. "code.gitea.io/gitea/modules/util"
  13. "xorm.io/builder"
  14. )
  15. // RepositoryListDefaultPageSize is the default number of repositories
  16. // to load in memory when running administrative tasks on all (or almost
  17. // all) of them.
  18. // The number should be low enough to avoid filling up all RAM with
  19. // repository data...
  20. const RepositoryListDefaultPageSize = 64
  21. // RepositoryList contains a list of repositories
  22. type RepositoryList []*Repository
  23. func (repos RepositoryList) Len() int {
  24. return len(repos)
  25. }
  26. func (repos RepositoryList) Less(i, j int) bool {
  27. return repos[i].FullName() < repos[j].FullName()
  28. }
  29. func (repos RepositoryList) Swap(i, j int) {
  30. repos[i], repos[j] = repos[j], repos[i]
  31. }
  32. // RepositoryListOfMap make list from values of map
  33. func RepositoryListOfMap(repoMap map[int64]*Repository) RepositoryList {
  34. return RepositoryList(valuesRepository(repoMap))
  35. }
  36. func (repos RepositoryList) loadAttributes(e db.Engine) error {
  37. if len(repos) == 0 {
  38. return nil
  39. }
  40. set := make(map[int64]struct{})
  41. repoIDs := make([]int64, len(repos))
  42. for i := range repos {
  43. set[repos[i].OwnerID] = struct{}{}
  44. repoIDs[i] = repos[i].ID
  45. }
  46. // Load owners.
  47. users := make(map[int64]*user_model.User, len(set))
  48. if err := e.
  49. Where("id > 0").
  50. In("id", keysInt64(set)).
  51. Find(&users); err != nil {
  52. return fmt.Errorf("find users: %v", err)
  53. }
  54. for i := range repos {
  55. repos[i].Owner = users[repos[i].OwnerID]
  56. }
  57. // Load primary language.
  58. stats := make(LanguageStatList, 0, len(repos))
  59. if err := e.
  60. Where("`is_primary` = ? AND `language` != ?", true, "other").
  61. In("`repo_id`", repoIDs).
  62. Find(&stats); err != nil {
  63. return fmt.Errorf("find primary languages: %v", err)
  64. }
  65. stats.loadAttributes()
  66. for i := range repos {
  67. for _, st := range stats {
  68. if st.RepoID == repos[i].ID {
  69. repos[i].PrimaryLanguage = st
  70. break
  71. }
  72. }
  73. }
  74. return nil
  75. }
  76. // LoadAttributes loads the attributes for the given RepositoryList
  77. func (repos RepositoryList) LoadAttributes() error {
  78. return repos.loadAttributes(db.GetEngine(db.DefaultContext))
  79. }
  80. // MirrorRepositoryList contains the mirror repositories
  81. type MirrorRepositoryList []*Repository
  82. func (repos MirrorRepositoryList) loadAttributes(e db.Engine) error {
  83. if len(repos) == 0 {
  84. return nil
  85. }
  86. // Load mirrors.
  87. repoIDs := make([]int64, 0, len(repos))
  88. for i := range repos {
  89. if !repos[i].IsMirror {
  90. continue
  91. }
  92. repoIDs = append(repoIDs, repos[i].ID)
  93. }
  94. mirrors := make([]*Mirror, 0, len(repoIDs))
  95. if err := e.
  96. Where("id > 0").
  97. In("repo_id", repoIDs).
  98. Find(&mirrors); err != nil {
  99. return fmt.Errorf("find mirrors: %v", err)
  100. }
  101. set := make(map[int64]*Mirror)
  102. for i := range mirrors {
  103. set[mirrors[i].RepoID] = mirrors[i]
  104. }
  105. for i := range repos {
  106. repos[i].Mirror = set[repos[i].ID]
  107. }
  108. return nil
  109. }
  110. // LoadAttributes loads the attributes for the given MirrorRepositoryList
  111. func (repos MirrorRepositoryList) LoadAttributes() error {
  112. return repos.loadAttributes(db.GetEngine(db.DefaultContext))
  113. }
  114. // SearchRepoOptions holds the search options
  115. type SearchRepoOptions struct {
  116. db.ListOptions
  117. Actor *user_model.User
  118. Keyword string
  119. OwnerID int64
  120. PriorityOwnerID int64
  121. TeamID int64
  122. OrderBy db.SearchOrderBy
  123. Private bool // Include private repositories in results
  124. StarredByID int64
  125. WatchedByID int64
  126. AllPublic bool // Include also all public repositories of users and public organisations
  127. AllLimited bool // Include also all public repositories of limited organisations
  128. // None -> include public and private
  129. // True -> include just private
  130. // False -> include just public
  131. IsPrivate util.OptionalBool
  132. // None -> include collaborative AND non-collaborative
  133. // True -> include just collaborative
  134. // False -> include just non-collaborative
  135. Collaborate util.OptionalBool
  136. // None -> include forks AND non-forks
  137. // True -> include just forks
  138. // False -> include just non-forks
  139. Fork util.OptionalBool
  140. // None -> include templates AND non-templates
  141. // True -> include just templates
  142. // False -> include just non-templates
  143. Template util.OptionalBool
  144. // None -> include mirrors AND non-mirrors
  145. // True -> include just mirrors
  146. // False -> include just non-mirrors
  147. Mirror util.OptionalBool
  148. // None -> include archived AND non-archived
  149. // True -> include just archived
  150. // False -> include just non-archived
  151. Archived util.OptionalBool
  152. // only search topic name
  153. TopicOnly bool
  154. // include description in keyword search
  155. IncludeDescription bool
  156. // None -> include has milestones AND has no milestone
  157. // True -> include just has milestones
  158. // False -> include just has no milestone
  159. HasMilestones util.OptionalBool
  160. // LowerNames represents valid lower names to restrict to
  161. LowerNames []string
  162. }
  163. // SearchRepositoryCondition creates a query condition according search repository options
  164. func SearchRepositoryCondition(opts *SearchRepoOptions) builder.Cond {
  165. cond := builder.NewCond()
  166. if opts.Private {
  167. if opts.Actor != nil && !opts.Actor.IsAdmin && opts.Actor.ID != opts.OwnerID {
  168. // OK we're in the context of a User
  169. cond = cond.And(accessibleRepositoryCondition(opts.Actor))
  170. }
  171. } else {
  172. // Not looking at private organisations and users
  173. // We should be able to see all non-private repositories that
  174. // isn't in a private or limited organisation.
  175. cond = cond.And(
  176. builder.Eq{"is_private": false},
  177. builder.NotIn("owner_id", builder.Select("id").From("`user`").Where(
  178. builder.Or(builder.Eq{"visibility": structs.VisibleTypeLimited}, builder.Eq{"visibility": structs.VisibleTypePrivate}),
  179. )))
  180. }
  181. if opts.IsPrivate != util.OptionalBoolNone {
  182. cond = cond.And(builder.Eq{"is_private": opts.IsPrivate.IsTrue()})
  183. }
  184. if opts.Template != util.OptionalBoolNone {
  185. cond = cond.And(builder.Eq{"is_template": opts.Template == util.OptionalBoolTrue})
  186. }
  187. // Restrict to starred repositories
  188. if opts.StarredByID > 0 {
  189. cond = cond.And(builder.In("id", builder.Select("repo_id").From("star").Where(builder.Eq{"uid": opts.StarredByID})))
  190. }
  191. // Restrict to watched repositories
  192. if opts.WatchedByID > 0 {
  193. cond = cond.And(builder.In("id", builder.Select("repo_id").From("watch").Where(builder.Eq{"user_id": opts.WatchedByID})))
  194. }
  195. // Restrict repositories to those the OwnerID owns or contributes to as per opts.Collaborate
  196. if opts.OwnerID > 0 {
  197. accessCond := builder.NewCond()
  198. if opts.Collaborate != util.OptionalBoolTrue {
  199. accessCond = builder.Eq{"owner_id": opts.OwnerID}
  200. }
  201. if opts.Collaborate != util.OptionalBoolFalse {
  202. // A Collaboration is:
  203. collaborateCond := builder.And(
  204. // 1. Repository we don't own
  205. builder.Neq{"owner_id": opts.OwnerID},
  206. // 2. But we can see because of:
  207. builder.Or(
  208. // A. We have access
  209. builder.In("`repository`.id",
  210. builder.Select("`access`.repo_id").
  211. From("access").
  212. Where(builder.Eq{"`access`.user_id": opts.OwnerID})),
  213. // B. We are in a team for
  214. builder.In("`repository`.id", builder.Select("`team_repo`.repo_id").
  215. From("team_repo").
  216. Where(builder.Eq{"`team_user`.uid": opts.OwnerID}).
  217. Join("INNER", "team_user", "`team_user`.team_id = `team_repo`.team_id")),
  218. // C. Public repositories in private organizations that we are member of
  219. builder.And(
  220. builder.Eq{"`repository`.is_private": false},
  221. builder.In("`repository`.owner_id",
  222. builder.Select("`org_user`.org_id").
  223. From("org_user").
  224. Join("INNER", "`user`", "`user`.id = `org_user`.org_id").
  225. Where(builder.Eq{
  226. "`org_user`.uid": opts.OwnerID,
  227. "`user`.type": user_model.UserTypeOrganization,
  228. "`user`.visibility": structs.VisibleTypePrivate,
  229. })))),
  230. )
  231. if !opts.Private {
  232. 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))
  233. }
  234. accessCond = accessCond.Or(collaborateCond)
  235. }
  236. if opts.AllPublic {
  237. 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}))))
  238. }
  239. if opts.AllLimited {
  240. 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}))))
  241. }
  242. cond = cond.And(accessCond)
  243. }
  244. if opts.TeamID > 0 {
  245. cond = cond.And(builder.In("`repository`.id", builder.Select("`team_repo`.repo_id").From("team_repo").Where(builder.Eq{"`team_repo`.team_id": opts.TeamID})))
  246. }
  247. if opts.Keyword != "" {
  248. // separate keyword
  249. subQueryCond := builder.NewCond()
  250. for _, v := range strings.Split(opts.Keyword, ",") {
  251. if opts.TopicOnly {
  252. subQueryCond = subQueryCond.Or(builder.Eq{"topic.name": strings.ToLower(v)})
  253. } else {
  254. subQueryCond = subQueryCond.Or(builder.Like{"topic.name", strings.ToLower(v)})
  255. }
  256. }
  257. subQuery := builder.Select("repo_topic.repo_id").From("repo_topic").
  258. Join("INNER", "topic", "topic.id = repo_topic.topic_id").
  259. Where(subQueryCond).
  260. GroupBy("repo_topic.repo_id")
  261. keywordCond := builder.In("id", subQuery)
  262. if !opts.TopicOnly {
  263. likes := builder.NewCond()
  264. for _, v := range strings.Split(opts.Keyword, ",") {
  265. likes = likes.Or(builder.Like{"lower_name", strings.ToLower(v)})
  266. if opts.IncludeDescription {
  267. likes = likes.Or(builder.Like{"LOWER(description)", strings.ToLower(v)})
  268. }
  269. }
  270. keywordCond = keywordCond.Or(likes)
  271. }
  272. cond = cond.And(keywordCond)
  273. }
  274. if opts.Fork != util.OptionalBoolNone {
  275. cond = cond.And(builder.Eq{"is_fork": opts.Fork == util.OptionalBoolTrue})
  276. }
  277. if opts.Mirror != util.OptionalBoolNone {
  278. cond = cond.And(builder.Eq{"is_mirror": opts.Mirror == util.OptionalBoolTrue})
  279. }
  280. if opts.Actor != nil && opts.Actor.IsRestricted {
  281. cond = cond.And(accessibleRepositoryCondition(opts.Actor))
  282. }
  283. if opts.Archived != util.OptionalBoolNone {
  284. cond = cond.And(builder.Eq{"is_archived": opts.Archived == util.OptionalBoolTrue})
  285. }
  286. switch opts.HasMilestones {
  287. case util.OptionalBoolTrue:
  288. cond = cond.And(builder.Gt{"num_milestones": 0})
  289. case util.OptionalBoolFalse:
  290. cond = cond.And(builder.Eq{"num_milestones": 0}.Or(builder.IsNull{"num_milestones"}))
  291. }
  292. return cond
  293. }
  294. // SearchRepository returns repositories based on search options,
  295. // it returns results in given range and number of total results.
  296. func SearchRepository(opts *SearchRepoOptions) (RepositoryList, int64, error) {
  297. cond := SearchRepositoryCondition(opts)
  298. return SearchRepositoryByCondition(opts, cond, true)
  299. }
  300. // SearchRepositoryByCondition search repositories by condition
  301. func SearchRepositoryByCondition(opts *SearchRepoOptions, cond builder.Cond, loadAttributes bool) (RepositoryList, int64, error) {
  302. sess, count, err := searchRepositoryByCondition(opts, cond)
  303. if err != nil {
  304. return nil, 0, err
  305. }
  306. defaultSize := 50
  307. if opts.PageSize > 0 {
  308. defaultSize = opts.PageSize
  309. }
  310. repos := make(RepositoryList, 0, defaultSize)
  311. if err := sess.Find(&repos); err != nil {
  312. return nil, 0, fmt.Errorf("Repo: %v", err)
  313. }
  314. if opts.PageSize <= 0 {
  315. count = int64(len(repos))
  316. }
  317. if loadAttributes {
  318. if err := repos.loadAttributes(sess); err != nil {
  319. return nil, 0, fmt.Errorf("LoadAttributes: %v", err)
  320. }
  321. }
  322. return repos, count, nil
  323. }
  324. func searchRepositoryByCondition(opts *SearchRepoOptions, cond builder.Cond) (db.Engine, int64, error) {
  325. if opts.Page <= 0 {
  326. opts.Page = 1
  327. }
  328. if len(opts.OrderBy) == 0 {
  329. opts.OrderBy = db.SearchOrderByAlphabetically
  330. }
  331. if opts.PriorityOwnerID > 0 {
  332. opts.OrderBy = db.SearchOrderBy(fmt.Sprintf("CASE WHEN owner_id = %d THEN 0 ELSE owner_id END, %s", opts.PriorityOwnerID, opts.OrderBy))
  333. }
  334. sess := db.GetEngine(db.DefaultContext)
  335. var count int64
  336. if opts.PageSize > 0 {
  337. var err error
  338. count, err = sess.
  339. Where(cond).
  340. Count(new(Repository))
  341. if err != nil {
  342. return nil, 0, fmt.Errorf("Count: %v", err)
  343. }
  344. }
  345. sess = sess.Where(cond).OrderBy(opts.OrderBy.String())
  346. if opts.PageSize > 0 {
  347. sess = sess.Limit(opts.PageSize, (opts.Page-1)*opts.PageSize)
  348. }
  349. return sess, count, nil
  350. }
  351. // accessibleRepositoryCondition takes a user a returns a condition for checking if a repository is accessible
  352. func accessibleRepositoryCondition(user *user_model.User) builder.Cond {
  353. cond := builder.NewCond()
  354. if user == nil || !user.IsRestricted || user.ID <= 0 {
  355. orgVisibilityLimit := []structs.VisibleType{structs.VisibleTypePrivate}
  356. if user == nil || user.ID <= 0 {
  357. orgVisibilityLimit = append(orgVisibilityLimit, structs.VisibleTypeLimited)
  358. }
  359. // 1. Be able to see all non-private repositories that either:
  360. cond = cond.Or(builder.And(
  361. builder.Eq{"`repository`.is_private": false},
  362. // 2. Aren't in an private organisation or limited organisation if we're not logged in
  363. builder.NotIn("`repository`.owner_id", builder.Select("id").From("`user`").Where(
  364. builder.And(
  365. builder.Eq{"type": user_model.UserTypeOrganization},
  366. builder.In("visibility", orgVisibilityLimit)),
  367. ))))
  368. }
  369. if user != nil {
  370. cond = cond.Or(
  371. // 2. Be able to see all repositories that we have access to
  372. builder.In("`repository`.id", builder.Select("repo_id").
  373. From("`access`").
  374. Where(builder.And(
  375. builder.Eq{"user_id": user.ID},
  376. builder.Gt{"mode": int(perm.AccessModeNone)}))),
  377. // 3. Repositories that we directly own
  378. builder.Eq{"`repository`.owner_id": user.ID},
  379. // 4. Be able to see all repositories that we are in a team
  380. builder.In("`repository`.id", builder.Select("`team_repo`.repo_id").
  381. From("team_repo").
  382. Where(builder.Eq{"`team_user`.uid": user.ID}).
  383. Join("INNER", "team_user", "`team_user`.team_id = `team_repo`.team_id")),
  384. // 5. Be able to see all public repos in private organizations that we are an org_user of
  385. builder.And(builder.Eq{"`repository`.is_private": false},
  386. builder.In("`repository`.owner_id",
  387. builder.Select("`org_user`.org_id").
  388. From("org_user").
  389. Where(builder.Eq{"`org_user`.uid": user.ID}))))
  390. }
  391. return cond
  392. }
  393. // SearchRepositoryByName takes keyword and part of repository name to search,
  394. // it returns results in given range and number of total results.
  395. func SearchRepositoryByName(opts *SearchRepoOptions) (RepositoryList, int64, error) {
  396. opts.IncludeDescription = false
  397. return SearchRepository(opts)
  398. }
  399. // SearchRepositoryIDs takes keyword and part of repository name to search,
  400. // it returns results in given range and number of total results.
  401. func SearchRepositoryIDs(opts *SearchRepoOptions) ([]int64, int64, error) {
  402. opts.IncludeDescription = false
  403. cond := SearchRepositoryCondition(opts)
  404. sess, count, err := searchRepositoryByCondition(opts, cond)
  405. if err != nil {
  406. return nil, 0, err
  407. }
  408. defaultSize := 50
  409. if opts.PageSize > 0 {
  410. defaultSize = opts.PageSize
  411. }
  412. ids := make([]int64, 0, defaultSize)
  413. err = sess.Select("id").Table("repository").Find(&ids)
  414. if opts.PageSize <= 0 {
  415. count = int64(len(ids))
  416. }
  417. return ids, count, err
  418. }
  419. // AccessibleRepoIDsQuery queries accessible repository ids. Usable as a subquery wherever repo ids need to be filtered.
  420. func AccessibleRepoIDsQuery(user *user_model.User) *builder.Builder {
  421. // NB: Please note this code needs to still work if user is nil
  422. return builder.Select("id").From("repository").Where(accessibleRepositoryCondition(user))
  423. }
  424. // FindUserAccessibleRepoIDs find all accessible repositories' ID by user's id
  425. func FindUserAccessibleRepoIDs(user *user_model.User) ([]int64, error) {
  426. repoIDs := make([]int64, 0, 10)
  427. if err := db.GetEngine(db.DefaultContext).
  428. Table("repository").
  429. Cols("id").
  430. Where(accessibleRepositoryCondition(user)).
  431. Find(&repoIDs); err != nil {
  432. return nil, fmt.Errorf("FindUserAccesibleRepoIDs: %v", err)
  433. }
  434. return repoIDs, nil
  435. }