您最多选择25个主题 主题必须以字母或数字开头,可以包含连字符 (-),并且长度不得超过35个字符

repo_list.go 15KB

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