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

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