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.

mini_org.go 1.9KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677
  1. // Copyright 2022 The Gitea Authors. All rights reserved.
  2. // SPDX-License-Identifier: MIT
  3. package organization
  4. import (
  5. "fmt"
  6. "strings"
  7. "code.gitea.io/gitea/models/db"
  8. repo_model "code.gitea.io/gitea/models/repo"
  9. "code.gitea.io/gitea/models/unit"
  10. user_model "code.gitea.io/gitea/models/user"
  11. "xorm.io/builder"
  12. )
  13. // MinimalOrg represents a simple organization with only the needed columns
  14. type MinimalOrg = Organization
  15. // GetUserOrgsList returns all organizations the given user has access to
  16. func GetUserOrgsList(user *user_model.User) ([]*MinimalOrg, error) {
  17. schema, err := db.TableInfo(new(user_model.User))
  18. if err != nil {
  19. return nil, err
  20. }
  21. outputCols := []string{
  22. "id",
  23. "name",
  24. "full_name",
  25. "visibility",
  26. "avatar",
  27. "avatar_email",
  28. "use_custom_avatar",
  29. }
  30. groupByCols := &strings.Builder{}
  31. for _, col := range outputCols {
  32. fmt.Fprintf(groupByCols, "`%s`.%s,", schema.Name, col)
  33. }
  34. groupByStr := groupByCols.String()
  35. groupByStr = groupByStr[0 : len(groupByStr)-1]
  36. sess := db.GetEngine(db.DefaultContext)
  37. sess = sess.Select(groupByStr+", count(distinct repo_id) as org_count").
  38. Table("user").
  39. Join("INNER", "team", "`team`.org_id = `user`.id").
  40. Join("INNER", "team_user", "`team`.id = `team_user`.team_id").
  41. Join("LEFT", builder.
  42. Select("id as repo_id, owner_id as repo_owner_id").
  43. From("repository").
  44. Where(repo_model.AccessibleRepositoryCondition(user, unit.TypeInvalid)), "`repository`.repo_owner_id = `team`.org_id").
  45. Where("`team_user`.uid = ?", user.ID).
  46. GroupBy(groupByStr)
  47. type OrgCount struct {
  48. Organization `xorm:"extends"`
  49. OrgCount int
  50. }
  51. orgCounts := make([]*OrgCount, 0, 10)
  52. if err := sess.
  53. Asc("`user`.name").
  54. Find(&orgCounts); err != nil {
  55. return nil, err
  56. }
  57. orgs := make([]*MinimalOrg, len(orgCounts))
  58. for i, orgCount := range orgCounts {
  59. orgCount.Organization.NumRepos = orgCount.OrgCount
  60. orgs[i] = &orgCount.Organization
  61. }
  62. return orgs, nil
  63. }