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

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