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

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