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.

1051 lines
26 KiB

API add/generalize pagination (#9452) * paginate results * fixed deadlock * prevented breaking change * updated swagger * go fmt * fixed find topic * go mod tidy * go mod vendor with go1.13.5 * fixed repo find topics * fixed unit test * added Limit method to Engine struct; use engine variable when provided; fixed gitignore * use ItemsPerPage for default pagesize; fix GetWatchers, getOrgUsersByOrgID and GetStargazers; fix GetAllCommits headers; reverted some changed behaviors * set Page value on Home route * improved memory allocations * fixed response headers * removed logfiles * fixed import order * import order * improved swagger * added function to get models.ListOptions from context * removed pagesize diff on unit test * fixed imports * removed unnecessary struct field * fixed go fmt * scoped PR * code improvements * code improvements * go mod tidy * fixed import order * fixed commit statuses session * fixed files headers * fixed headers; added pagination for notifications * go mod tidy * go fmt * removed Private from user search options; added setting.UI.IssuePagingNum as default valeu on repo's issues list * Apply suggestions from code review Co-Authored-By: 6543 <6543@obermui.de> Co-Authored-By: zeripath <art27@cantab.net> * fixed build error * CI.restart() * fixed merge conflicts resolve * fixed conflicts resolve * improved FindTrackedTimesOptions.ToOptions() method * added backwards compatibility on ListReleases request; fixed issue tracked time ToSession * fixed build error; fixed swagger template * fixed swagger template * fixed ListReleases backwards compatibility * added page to user search route Co-authored-by: techknowlogick <matti@mdranta.net> Co-authored-by: 6543 <6543@obermui.de> Co-authored-by: zeripath <art27@cantab.net>
4 years ago
API add/generalize pagination (#9452) * paginate results * fixed deadlock * prevented breaking change * updated swagger * go fmt * fixed find topic * go mod tidy * go mod vendor with go1.13.5 * fixed repo find topics * fixed unit test * added Limit method to Engine struct; use engine variable when provided; fixed gitignore * use ItemsPerPage for default pagesize; fix GetWatchers, getOrgUsersByOrgID and GetStargazers; fix GetAllCommits headers; reverted some changed behaviors * set Page value on Home route * improved memory allocations * fixed response headers * removed logfiles * fixed import order * import order * improved swagger * added function to get models.ListOptions from context * removed pagesize diff on unit test * fixed imports * removed unnecessary struct field * fixed go fmt * scoped PR * code improvements * code improvements * go mod tidy * fixed import order * fixed commit statuses session * fixed files headers * fixed headers; added pagination for notifications * go mod tidy * go fmt * removed Private from user search options; added setting.UI.IssuePagingNum as default valeu on repo's issues list * Apply suggestions from code review Co-Authored-By: 6543 <6543@obermui.de> Co-Authored-By: zeripath <art27@cantab.net> * fixed build error * CI.restart() * fixed merge conflicts resolve * fixed conflicts resolve * improved FindTrackedTimesOptions.ToOptions() method * added backwards compatibility on ListReleases request; fixed issue tracked time ToSession * fixed build error; fixed swagger template * fixed swagger template * fixed ListReleases backwards compatibility * added page to user search route Co-authored-by: techknowlogick <matti@mdranta.net> Co-authored-by: 6543 <6543@obermui.de> Co-authored-by: zeripath <art27@cantab.net>
4 years ago
Better logging (#6038) (#6095) * Panic don't fatal on create new logger Fixes #5854 Signed-off-by: Andrew Thornton <art27@cantab.net> * partial broken * Update the logging infrastrcture Signed-off-by: Andrew Thornton <art27@cantab.net> * Reset the skip levels for Fatal and Error Signed-off-by: Andrew Thornton <art27@cantab.net> * broken ncsa * More log.Error fixes Signed-off-by: Andrew Thornton <art27@cantab.net> * Remove nal * set log-levels to lowercase * Make console_test test all levels * switch to lowercased levels * OK now working * Fix vetting issues * Fix lint * Fix tests * change default logging to match current gitea * Improve log testing Signed-off-by: Andrew Thornton <art27@cantab.net> * reset error skip levels to 0 * Update documentation and access logger configuration * Redirect the router log back to gitea if redirect macaron log but also allow setting the log level - i.e. TRACE * Fix broken level caching * Refactor the router log * Add Router logger * Add colorizing options * Adjust router colors * Only create logger if they will be used * update app.ini.sample * rename Attribute ColorAttribute * Change from white to green for function * Set fatal/error levels * Restore initial trace logger * Fix Trace arguments in modules/auth/auth.go * Properly handle XORMLogger * Improve admin/config page * fix fmt * Add auto-compression of old logs * Update error log levels * Remove the unnecessary skip argument from Error, Fatal and Critical * Add stacktrace support * Fix tests * Remove x/sync from vendors? * Add stderr option to console logger * Use filepath.ToSlash to protect against Windows in tests * Remove prefixed underscores from names in colors.go * Remove not implemented database logger This was removed from Gogs on 4 Mar 2016 but left in the configuration since then. * Ensure that log paths are relative to ROOT_PATH * use path.Join * rename jsonConfig to logConfig * Rename "config" to "jsonConfig" to make it clearer * Requested changes * Requested changes: XormLogger * Try to color the windows terminal If successful default to colorizing the console logs * fixup * Colorize initially too * update vendor * Colorize logs on default and remove if this is not a colorizing logger * Fix documentation * fix test * Use go-isatty to detect if on windows we are on msys or cygwin * Fix spelling mistake * Add missing vendors * More changes * Rationalise the ANSI writer protection * Adjust colors on advice from @0x5c * Make Flags a comma separated list * Move to use the windows constant for ENABLE_VIRTUAL_TERMINAL_PROCESSING * Ensure matching is done on the non-colored message - to simpify EXPRESSION
5 years ago
API add/generalize pagination (#9452) * paginate results * fixed deadlock * prevented breaking change * updated swagger * go fmt * fixed find topic * go mod tidy * go mod vendor with go1.13.5 * fixed repo find topics * fixed unit test * added Limit method to Engine struct; use engine variable when provided; fixed gitignore * use ItemsPerPage for default pagesize; fix GetWatchers, getOrgUsersByOrgID and GetStargazers; fix GetAllCommits headers; reverted some changed behaviors * set Page value on Home route * improved memory allocations * fixed response headers * removed logfiles * fixed import order * import order * improved swagger * added function to get models.ListOptions from context * removed pagesize diff on unit test * fixed imports * removed unnecessary struct field * fixed go fmt * scoped PR * code improvements * code improvements * go mod tidy * fixed import order * fixed commit statuses session * fixed files headers * fixed headers; added pagination for notifications * go mod tidy * go fmt * removed Private from user search options; added setting.UI.IssuePagingNum as default valeu on repo's issues list * Apply suggestions from code review Co-Authored-By: 6543 <6543@obermui.de> Co-Authored-By: zeripath <art27@cantab.net> * fixed build error * CI.restart() * fixed merge conflicts resolve * fixed conflicts resolve * improved FindTrackedTimesOptions.ToOptions() method * added backwards compatibility on ListReleases request; fixed issue tracked time ToSession * fixed build error; fixed swagger template * fixed swagger template * fixed ListReleases backwards compatibility * added page to user search route Co-authored-by: techknowlogick <matti@mdranta.net> Co-authored-by: 6543 <6543@obermui.de> Co-authored-by: zeripath <art27@cantab.net>
4 years ago
API add/generalize pagination (#9452) * paginate results * fixed deadlock * prevented breaking change * updated swagger * go fmt * fixed find topic * go mod tidy * go mod vendor with go1.13.5 * fixed repo find topics * fixed unit test * added Limit method to Engine struct; use engine variable when provided; fixed gitignore * use ItemsPerPage for default pagesize; fix GetWatchers, getOrgUsersByOrgID and GetStargazers; fix GetAllCommits headers; reverted some changed behaviors * set Page value on Home route * improved memory allocations * fixed response headers * removed logfiles * fixed import order * import order * improved swagger * added function to get models.ListOptions from context * removed pagesize diff on unit test * fixed imports * removed unnecessary struct field * fixed go fmt * scoped PR * code improvements * code improvements * go mod tidy * fixed import order * fixed commit statuses session * fixed files headers * fixed headers; added pagination for notifications * go mod tidy * go fmt * removed Private from user search options; added setting.UI.IssuePagingNum as default valeu on repo's issues list * Apply suggestions from code review Co-Authored-By: 6543 <6543@obermui.de> Co-Authored-By: zeripath <art27@cantab.net> * fixed build error * CI.restart() * fixed merge conflicts resolve * fixed conflicts resolve * improved FindTrackedTimesOptions.ToOptions() method * added backwards compatibility on ListReleases request; fixed issue tracked time ToSession * fixed build error; fixed swagger template * fixed swagger template * fixed ListReleases backwards compatibility * added page to user search route Co-authored-by: techknowlogick <matti@mdranta.net> Co-authored-by: 6543 <6543@obermui.de> Co-authored-by: zeripath <art27@cantab.net>
4 years ago
API add/generalize pagination (#9452) * paginate results * fixed deadlock * prevented breaking change * updated swagger * go fmt * fixed find topic * go mod tidy * go mod vendor with go1.13.5 * fixed repo find topics * fixed unit test * added Limit method to Engine struct; use engine variable when provided; fixed gitignore * use ItemsPerPage for default pagesize; fix GetWatchers, getOrgUsersByOrgID and GetStargazers; fix GetAllCommits headers; reverted some changed behaviors * set Page value on Home route * improved memory allocations * fixed response headers * removed logfiles * fixed import order * import order * improved swagger * added function to get models.ListOptions from context * removed pagesize diff on unit test * fixed imports * removed unnecessary struct field * fixed go fmt * scoped PR * code improvements * code improvements * go mod tidy * fixed import order * fixed commit statuses session * fixed files headers * fixed headers; added pagination for notifications * go mod tidy * go fmt * removed Private from user search options; added setting.UI.IssuePagingNum as default valeu on repo's issues list * Apply suggestions from code review Co-Authored-By: 6543 <6543@obermui.de> Co-Authored-By: zeripath <art27@cantab.net> * fixed build error * CI.restart() * fixed merge conflicts resolve * fixed conflicts resolve * improved FindTrackedTimesOptions.ToOptions() method * added backwards compatibility on ListReleases request; fixed issue tracked time ToSession * fixed build error; fixed swagger template * fixed swagger template * fixed ListReleases backwards compatibility * added page to user search route Co-authored-by: techknowlogick <matti@mdranta.net> Co-authored-by: 6543 <6543@obermui.de> Co-authored-by: zeripath <art27@cantab.net>
4 years ago
API add/generalize pagination (#9452) * paginate results * fixed deadlock * prevented breaking change * updated swagger * go fmt * fixed find topic * go mod tidy * go mod vendor with go1.13.5 * fixed repo find topics * fixed unit test * added Limit method to Engine struct; use engine variable when provided; fixed gitignore * use ItemsPerPage for default pagesize; fix GetWatchers, getOrgUsersByOrgID and GetStargazers; fix GetAllCommits headers; reverted some changed behaviors * set Page value on Home route * improved memory allocations * fixed response headers * removed logfiles * fixed import order * import order * improved swagger * added function to get models.ListOptions from context * removed pagesize diff on unit test * fixed imports * removed unnecessary struct field * fixed go fmt * scoped PR * code improvements * code improvements * go mod tidy * fixed import order * fixed commit statuses session * fixed files headers * fixed headers; added pagination for notifications * go mod tidy * go fmt * removed Private from user search options; added setting.UI.IssuePagingNum as default valeu on repo's issues list * Apply suggestions from code review Co-Authored-By: 6543 <6543@obermui.de> Co-Authored-By: zeripath <art27@cantab.net> * fixed build error * CI.restart() * fixed merge conflicts resolve * fixed conflicts resolve * improved FindTrackedTimesOptions.ToOptions() method * added backwards compatibility on ListReleases request; fixed issue tracked time ToSession * fixed build error; fixed swagger template * fixed swagger template * fixed ListReleases backwards compatibility * added page to user search route Co-authored-by: techknowlogick <matti@mdranta.net> Co-authored-by: 6543 <6543@obermui.de> Co-authored-by: zeripath <art27@cantab.net>
4 years ago
API add/generalize pagination (#9452) * paginate results * fixed deadlock * prevented breaking change * updated swagger * go fmt * fixed find topic * go mod tidy * go mod vendor with go1.13.5 * fixed repo find topics * fixed unit test * added Limit method to Engine struct; use engine variable when provided; fixed gitignore * use ItemsPerPage for default pagesize; fix GetWatchers, getOrgUsersByOrgID and GetStargazers; fix GetAllCommits headers; reverted some changed behaviors * set Page value on Home route * improved memory allocations * fixed response headers * removed logfiles * fixed import order * import order * improved swagger * added function to get models.ListOptions from context * removed pagesize diff on unit test * fixed imports * removed unnecessary struct field * fixed go fmt * scoped PR * code improvements * code improvements * go mod tidy * fixed import order * fixed commit statuses session * fixed files headers * fixed headers; added pagination for notifications * go mod tidy * go fmt * removed Private from user search options; added setting.UI.IssuePagingNum as default valeu on repo's issues list * Apply suggestions from code review Co-Authored-By: 6543 <6543@obermui.de> Co-Authored-By: zeripath <art27@cantab.net> * fixed build error * CI.restart() * fixed merge conflicts resolve * fixed conflicts resolve * improved FindTrackedTimesOptions.ToOptions() method * added backwards compatibility on ListReleases request; fixed issue tracked time ToSession * fixed build error; fixed swagger template * fixed swagger template * fixed ListReleases backwards compatibility * added page to user search route Co-authored-by: techknowlogick <matti@mdranta.net> Co-authored-by: 6543 <6543@obermui.de> Co-authored-by: zeripath <art27@cantab.net>
4 years ago
API add/generalize pagination (#9452) * paginate results * fixed deadlock * prevented breaking change * updated swagger * go fmt * fixed find topic * go mod tidy * go mod vendor with go1.13.5 * fixed repo find topics * fixed unit test * added Limit method to Engine struct; use engine variable when provided; fixed gitignore * use ItemsPerPage for default pagesize; fix GetWatchers, getOrgUsersByOrgID and GetStargazers; fix GetAllCommits headers; reverted some changed behaviors * set Page value on Home route * improved memory allocations * fixed response headers * removed logfiles * fixed import order * import order * improved swagger * added function to get models.ListOptions from context * removed pagesize diff on unit test * fixed imports * removed unnecessary struct field * fixed go fmt * scoped PR * code improvements * code improvements * go mod tidy * fixed import order * fixed commit statuses session * fixed files headers * fixed headers; added pagination for notifications * go mod tidy * go fmt * removed Private from user search options; added setting.UI.IssuePagingNum as default valeu on repo's issues list * Apply suggestions from code review Co-Authored-By: 6543 <6543@obermui.de> Co-Authored-By: zeripath <art27@cantab.net> * fixed build error * CI.restart() * fixed merge conflicts resolve * fixed conflicts resolve * improved FindTrackedTimesOptions.ToOptions() method * added backwards compatibility on ListReleases request; fixed issue tracked time ToSession * fixed build error; fixed swagger template * fixed swagger template * fixed ListReleases backwards compatibility * added page to user search route Co-authored-by: techknowlogick <matti@mdranta.net> Co-authored-by: 6543 <6543@obermui.de> Co-authored-by: zeripath <art27@cantab.net>
4 years ago
API add/generalize pagination (#9452) * paginate results * fixed deadlock * prevented breaking change * updated swagger * go fmt * fixed find topic * go mod tidy * go mod vendor with go1.13.5 * fixed repo find topics * fixed unit test * added Limit method to Engine struct; use engine variable when provided; fixed gitignore * use ItemsPerPage for default pagesize; fix GetWatchers, getOrgUsersByOrgID and GetStargazers; fix GetAllCommits headers; reverted some changed behaviors * set Page value on Home route * improved memory allocations * fixed response headers * removed logfiles * fixed import order * import order * improved swagger * added function to get models.ListOptions from context * removed pagesize diff on unit test * fixed imports * removed unnecessary struct field * fixed go fmt * scoped PR * code improvements * code improvements * go mod tidy * fixed import order * fixed commit statuses session * fixed files headers * fixed headers; added pagination for notifications * go mod tidy * go fmt * removed Private from user search options; added setting.UI.IssuePagingNum as default valeu on repo's issues list * Apply suggestions from code review Co-Authored-By: 6543 <6543@obermui.de> Co-Authored-By: zeripath <art27@cantab.net> * fixed build error * CI.restart() * fixed merge conflicts resolve * fixed conflicts resolve * improved FindTrackedTimesOptions.ToOptions() method * added backwards compatibility on ListReleases request; fixed issue tracked time ToSession * fixed build error; fixed swagger template * fixed swagger template * fixed ListReleases backwards compatibility * added page to user search route Co-authored-by: techknowlogick <matti@mdranta.net> Co-authored-by: 6543 <6543@obermui.de> Co-authored-by: zeripath <art27@cantab.net>
4 years ago
  1. // Copyright 2018 The Gitea Authors. All rights reserved.
  2. // Copyright 2016 The Gogs Authors. All rights reserved.
  3. // Use of this source code is governed by a MIT-style
  4. // license that can be found in the LICENSE file.
  5. package models
  6. import (
  7. "errors"
  8. "fmt"
  9. "sort"
  10. "strings"
  11. "code.gitea.io/gitea/modules/log"
  12. "code.gitea.io/gitea/modules/setting"
  13. "xorm.io/builder"
  14. "xorm.io/xorm"
  15. )
  16. const ownerTeamName = "Owners"
  17. // Team represents a organization team.
  18. type Team struct {
  19. ID int64 `xorm:"pk autoincr"`
  20. OrgID int64 `xorm:"INDEX"`
  21. LowerName string
  22. Name string
  23. Description string
  24. Authorize AccessMode
  25. Repos []*Repository `xorm:"-"`
  26. Members []*User `xorm:"-"`
  27. NumRepos int
  28. NumMembers int
  29. Units []*TeamUnit `xorm:"-"`
  30. IncludesAllRepositories bool `xorm:"NOT NULL DEFAULT false"`
  31. CanCreateOrgRepo bool `xorm:"NOT NULL DEFAULT false"`
  32. }
  33. // SearchTeamOptions holds the search options
  34. type SearchTeamOptions struct {
  35. ListOptions
  36. UserID int64
  37. Keyword string
  38. OrgID int64
  39. IncludeDesc bool
  40. }
  41. // SearchMembersOptions holds the search options
  42. type SearchMembersOptions struct {
  43. ListOptions
  44. }
  45. // SearchTeam search for teams. Caller is responsible to check permissions.
  46. func SearchTeam(opts *SearchTeamOptions) ([]*Team, int64, error) {
  47. if opts.Page <= 0 {
  48. opts.Page = 1
  49. }
  50. if opts.PageSize == 0 {
  51. // Default limit
  52. opts.PageSize = 10
  53. }
  54. var cond = builder.NewCond()
  55. if len(opts.Keyword) > 0 {
  56. lowerKeyword := strings.ToLower(opts.Keyword)
  57. var keywordCond builder.Cond = builder.Like{"lower_name", lowerKeyword}
  58. if opts.IncludeDesc {
  59. keywordCond = keywordCond.Or(builder.Like{"LOWER(description)", lowerKeyword})
  60. }
  61. cond = cond.And(keywordCond)
  62. }
  63. cond = cond.And(builder.Eq{"org_id": opts.OrgID})
  64. sess := x.NewSession()
  65. defer sess.Close()
  66. count, err := sess.
  67. Where(cond).
  68. Count(new(Team))
  69. if err != nil {
  70. return nil, 0, err
  71. }
  72. sess = sess.Where(cond)
  73. if opts.PageSize == -1 {
  74. opts.PageSize = int(count)
  75. } else {
  76. sess = sess.Limit(opts.PageSize, (opts.Page-1)*opts.PageSize)
  77. }
  78. teams := make([]*Team, 0, opts.PageSize)
  79. if err = sess.
  80. OrderBy("lower_name").
  81. Find(&teams); err != nil {
  82. return nil, 0, err
  83. }
  84. return teams, count, nil
  85. }
  86. // ColorFormat provides a basic color format for a Team
  87. func (t *Team) ColorFormat(s fmt.State) {
  88. log.ColorFprintf(s, "%d:%s (OrgID: %d) %-v",
  89. log.NewColoredIDValue(t.ID),
  90. t.Name,
  91. log.NewColoredIDValue(t.OrgID),
  92. t.Authorize)
  93. }
  94. // GetUnits return a list of available units for a team
  95. func (t *Team) GetUnits() error {
  96. return t.getUnits(x)
  97. }
  98. func (t *Team) getUnits(e Engine) (err error) {
  99. if t.Units != nil {
  100. return nil
  101. }
  102. t.Units, err = getUnitsByTeamID(e, t.ID)
  103. return err
  104. }
  105. // GetUnitNames returns the team units names
  106. func (t *Team) GetUnitNames() (res []string) {
  107. for _, u := range t.Units {
  108. res = append(res, Units[u.Type].NameKey)
  109. }
  110. return
  111. }
  112. // HasWriteAccess returns true if team has at least write level access mode.
  113. func (t *Team) HasWriteAccess() bool {
  114. return t.Authorize >= AccessModeWrite
  115. }
  116. // IsOwnerTeam returns true if team is owner team.
  117. func (t *Team) IsOwnerTeam() bool {
  118. return t.Name == ownerTeamName
  119. }
  120. // IsMember returns true if given user is a member of team.
  121. func (t *Team) IsMember(userID int64) bool {
  122. isMember, err := IsTeamMember(t.OrgID, t.ID, userID)
  123. if err != nil {
  124. log.Error("IsMember: %v", err)
  125. return false
  126. }
  127. return isMember
  128. }
  129. func (t *Team) getRepositories(e Engine) error {
  130. if t.Repos != nil {
  131. return nil
  132. }
  133. return e.Join("INNER", "team_repo", "repository.id = team_repo.repo_id").
  134. Where("team_repo.team_id=?", t.ID).
  135. OrderBy("repository.name").
  136. Find(&t.Repos)
  137. }
  138. // GetRepositories returns paginated repositories in team of organization.
  139. func (t *Team) GetRepositories(opts *SearchTeamOptions) error {
  140. if opts.Page == 0 {
  141. return t.getRepositories(x)
  142. }
  143. return t.getRepositories(opts.getPaginatedSession())
  144. }
  145. func (t *Team) getMembers(e Engine) (err error) {
  146. t.Members, err = getTeamMembers(e, t.ID)
  147. return err
  148. }
  149. // GetMembers returns paginated members in team of organization.
  150. func (t *Team) GetMembers(opts *SearchMembersOptions) (err error) {
  151. if opts.Page == 0 {
  152. return t.getMembers(x)
  153. }
  154. return t.getMembers(opts.getPaginatedSession())
  155. }
  156. // AddMember adds new membership of the team to the organization,
  157. // the user will have membership to the organization automatically when needed.
  158. func (t *Team) AddMember(userID int64) error {
  159. return AddTeamMember(t, userID)
  160. }
  161. // RemoveMember removes member from team of organization.
  162. func (t *Team) RemoveMember(userID int64) error {
  163. return RemoveTeamMember(t, userID)
  164. }
  165. func (t *Team) hasRepository(e Engine, repoID int64) bool {
  166. return hasTeamRepo(e, t.OrgID, t.ID, repoID)
  167. }
  168. // HasRepository returns true if given repository belong to team.
  169. func (t *Team) HasRepository(repoID int64) bool {
  170. return t.hasRepository(x, repoID)
  171. }
  172. func (t *Team) addRepository(e Engine, repo *Repository) (err error) {
  173. if err = addTeamRepo(e, t.OrgID, t.ID, repo.ID); err != nil {
  174. return err
  175. }
  176. if _, err = e.Incr("num_repos").ID(t.ID).Update(new(Team)); err != nil {
  177. return fmt.Errorf("update team: %v", err)
  178. }
  179. t.NumRepos++
  180. if err = repo.recalculateTeamAccesses(e, 0); err != nil {
  181. return fmt.Errorf("recalculateAccesses: %v", err)
  182. }
  183. // Make all team members watch this repo if enabled in global settings
  184. if setting.Service.AutoWatchNewRepos {
  185. if err = t.getMembers(e); err != nil {
  186. return fmt.Errorf("getMembers: %v", err)
  187. }
  188. for _, u := range t.Members {
  189. if err = watchRepo(e, u.ID, repo.ID, true); err != nil {
  190. return fmt.Errorf("watchRepo: %v", err)
  191. }
  192. }
  193. }
  194. return nil
  195. }
  196. // addAllRepositories adds all repositories to the team.
  197. // If the team already has some repositories they will be left unchanged.
  198. func (t *Team) addAllRepositories(e Engine) error {
  199. var orgRepos []Repository
  200. if err := e.Where("owner_id = ?", t.OrgID).Find(&orgRepos); err != nil {
  201. return fmt.Errorf("get org repos: %v", err)
  202. }
  203. for _, repo := range orgRepos {
  204. if !t.hasRepository(e, repo.ID) {
  205. if err := t.addRepository(e, &repo); err != nil {
  206. return fmt.Errorf("addRepository: %v", err)
  207. }
  208. }
  209. }
  210. return nil
  211. }
  212. // AddAllRepositories adds all repositories to the team
  213. func (t *Team) AddAllRepositories() (err error) {
  214. sess := x.NewSession()
  215. defer sess.Close()
  216. if err = sess.Begin(); err != nil {
  217. return err
  218. }
  219. if err = t.addAllRepositories(sess); err != nil {
  220. return err
  221. }
  222. return sess.Commit()
  223. }
  224. // AddRepository adds new repository to team of organization.
  225. func (t *Team) AddRepository(repo *Repository) (err error) {
  226. if repo.OwnerID != t.OrgID {
  227. return errors.New("Repository does not belong to organization")
  228. } else if t.HasRepository(repo.ID) {
  229. return nil
  230. }
  231. sess := x.NewSession()
  232. defer sess.Close()
  233. if err = sess.Begin(); err != nil {
  234. return err
  235. }
  236. if err = t.addRepository(sess, repo); err != nil {
  237. return err
  238. }
  239. return sess.Commit()
  240. }
  241. // RemoveAllRepositories removes all repositories from team and recalculates access
  242. func (t *Team) RemoveAllRepositories() (err error) {
  243. if t.IncludesAllRepositories {
  244. return nil
  245. }
  246. sess := x.NewSession()
  247. defer sess.Close()
  248. if err = sess.Begin(); err != nil {
  249. return err
  250. }
  251. if err = t.removeAllRepositories(sess); err != nil {
  252. return err
  253. }
  254. return sess.Commit()
  255. }
  256. // removeAllRepositories removes all repositories from team and recalculates access
  257. // Note: Shall not be called if team includes all repositories
  258. func (t *Team) removeAllRepositories(e Engine) (err error) {
  259. // Delete all accesses.
  260. for _, repo := range t.Repos {
  261. if err := repo.recalculateTeamAccesses(e, t.ID); err != nil {
  262. return err
  263. }
  264. // Remove watches from all users and now unaccessible repos
  265. for _, user := range t.Members {
  266. has, err := hasAccess(e, user.ID, repo)
  267. if err != nil {
  268. return err
  269. } else if has {
  270. continue
  271. }
  272. if err = watchRepo(e, user.ID, repo.ID, false); err != nil {
  273. return err
  274. }
  275. // Remove all IssueWatches a user has subscribed to in the repositories
  276. if err = removeIssueWatchersByRepoID(e, user.ID, repo.ID); err != nil {
  277. return err
  278. }
  279. }
  280. }
  281. // Delete team-repo
  282. if _, err := e.
  283. Where("team_id=?", t.ID).
  284. Delete(new(TeamRepo)); err != nil {
  285. return err
  286. }
  287. t.NumRepos = 0
  288. if _, err = e.ID(t.ID).Cols("num_repos").Update(t); err != nil {
  289. return err
  290. }
  291. return nil
  292. }
  293. // removeRepository removes a repository from a team and recalculates access
  294. // Note: Repository shall not be removed from team if it includes all repositories (unless the repository is deleted)
  295. func (t *Team) removeRepository(e Engine, repo *Repository, recalculate bool) (err error) {
  296. if err = removeTeamRepo(e, t.ID, repo.ID); err != nil {
  297. return err
  298. }
  299. t.NumRepos--
  300. if _, err = e.ID(t.ID).Cols("num_repos").Update(t); err != nil {
  301. return err
  302. }
  303. // Don't need to recalculate when delete a repository from organization.
  304. if recalculate {
  305. if err = repo.recalculateTeamAccesses(e, t.ID); err != nil {
  306. return err
  307. }
  308. }
  309. teamUsers, err := getTeamUsersByTeamID(e, t.ID)
  310. if err != nil {
  311. return fmt.Errorf("getTeamUsersByTeamID: %v", err)
  312. }
  313. for _, teamUser := range teamUsers {
  314. has, err := hasAccess(e, teamUser.UID, repo)
  315. if err != nil {
  316. return err
  317. } else if has {
  318. continue
  319. }
  320. if err = watchRepo(e, teamUser.UID, repo.ID, false); err != nil {
  321. return err
  322. }
  323. // Remove all IssueWatches a user has subscribed to in the repositories
  324. if err := removeIssueWatchersByRepoID(e, teamUser.UID, repo.ID); err != nil {
  325. return err
  326. }
  327. }
  328. return nil
  329. }
  330. // RemoveRepository removes repository from team of organization.
  331. // If the team shall include all repositories the request is ignored.
  332. func (t *Team) RemoveRepository(repoID int64) error {
  333. if !t.HasRepository(repoID) {
  334. return nil
  335. }
  336. if t.IncludesAllRepositories {
  337. return nil
  338. }
  339. repo, err := GetRepositoryByID(repoID)
  340. if err != nil {
  341. return err
  342. }
  343. sess := x.NewSession()
  344. defer sess.Close()
  345. if err = sess.Begin(); err != nil {
  346. return err
  347. }
  348. if err = t.removeRepository(sess, repo, true); err != nil {
  349. return err
  350. }
  351. return sess.Commit()
  352. }
  353. // UnitEnabled returns if the team has the given unit type enabled
  354. func (t *Team) UnitEnabled(tp UnitType) bool {
  355. return t.unitEnabled(x, tp)
  356. }
  357. func (t *Team) unitEnabled(e Engine, tp UnitType) bool {
  358. if err := t.getUnits(e); err != nil {
  359. log.Warn("Error loading team (ID: %d) units: %s", t.ID, err.Error())
  360. }
  361. for _, unit := range t.Units {
  362. if unit.Type == tp {
  363. return true
  364. }
  365. }
  366. return false
  367. }
  368. // IsUsableTeamName tests if a name could be as team name
  369. func IsUsableTeamName(name string) error {
  370. switch name {
  371. case "new":
  372. return ErrNameReserved{name}
  373. default:
  374. return nil
  375. }
  376. }
  377. // NewTeam creates a record of new team.
  378. // It's caller's responsibility to assign organization ID.
  379. func NewTeam(t *Team) (err error) {
  380. if len(t.Name) == 0 {
  381. return errors.New("empty team name")
  382. }
  383. if err = IsUsableTeamName(t.Name); err != nil {
  384. return err
  385. }
  386. has, err := x.ID(t.OrgID).Get(new(User))
  387. if err != nil {
  388. return err
  389. }
  390. if !has {
  391. return ErrOrgNotExist{t.OrgID, ""}
  392. }
  393. t.LowerName = strings.ToLower(t.Name)
  394. has, err = x.
  395. Where("org_id=?", t.OrgID).
  396. And("lower_name=?", t.LowerName).
  397. Get(new(Team))
  398. if err != nil {
  399. return err
  400. }
  401. if has {
  402. return ErrTeamAlreadyExist{t.OrgID, t.LowerName}
  403. }
  404. sess := x.NewSession()
  405. defer sess.Close()
  406. if err = sess.Begin(); err != nil {
  407. return err
  408. }
  409. if _, err = sess.Insert(t); err != nil {
  410. errRollback := sess.Rollback()
  411. if errRollback != nil {
  412. log.Error("NewTeam sess.Rollback: %v", errRollback)
  413. }
  414. return err
  415. }
  416. // insert units for team
  417. if len(t.Units) > 0 {
  418. for _, unit := range t.Units {
  419. unit.TeamID = t.ID
  420. }
  421. if _, err = sess.Insert(&t.Units); err != nil {
  422. errRollback := sess.Rollback()
  423. if errRollback != nil {
  424. log.Error("NewTeam sess.Rollback: %v", errRollback)
  425. }
  426. return err
  427. }
  428. }
  429. // Add all repositories to the team if it has access to all of them.
  430. if t.IncludesAllRepositories {
  431. err = t.addAllRepositories(sess)
  432. if err != nil {
  433. return fmt.Errorf("addAllRepositories: %v", err)
  434. }
  435. }
  436. // Update organization number of teams.
  437. if _, err = sess.Exec("UPDATE `user` SET num_teams=num_teams+1 WHERE id = ?", t.OrgID); err != nil {
  438. errRollback := sess.Rollback()
  439. if errRollback != nil {
  440. log.Error("NewTeam sess.Rollback: %v", errRollback)
  441. }
  442. return err
  443. }
  444. return sess.Commit()
  445. }
  446. func getTeam(e Engine, orgID int64, name string) (*Team, error) {
  447. t := &Team{
  448. OrgID: orgID,
  449. LowerName: strings.ToLower(name),
  450. }
  451. has, err := e.Get(t)
  452. if err != nil {
  453. return nil, err
  454. } else if !has {
  455. return nil, ErrTeamNotExist{orgID, 0, name}
  456. }
  457. return t, nil
  458. }
  459. // GetTeam returns team by given team name and organization.
  460. func GetTeam(orgID int64, name string) (*Team, error) {
  461. return getTeam(x, orgID, name)
  462. }
  463. // getOwnerTeam returns team by given team name and organization.
  464. func getOwnerTeam(e Engine, orgID int64) (*Team, error) {
  465. return getTeam(e, orgID, ownerTeamName)
  466. }
  467. func getTeamByID(e Engine, teamID int64) (*Team, error) {
  468. t := new(Team)
  469. has, err := e.ID(teamID).Get(t)
  470. if err != nil {
  471. return nil, err
  472. } else if !has {
  473. return nil, ErrTeamNotExist{0, teamID, ""}
  474. }
  475. return t, nil
  476. }
  477. // GetTeamByID returns team by given ID.
  478. func GetTeamByID(teamID int64) (*Team, error) {
  479. return getTeamByID(x, teamID)
  480. }
  481. // UpdateTeam updates information of team.
  482. func UpdateTeam(t *Team, authChanged bool, includeAllChanged bool) (err error) {
  483. if len(t.Name) == 0 {
  484. return errors.New("empty team name")
  485. }
  486. if len(t.Description) > 255 {
  487. t.Description = t.Description[:255]
  488. }
  489. sess := x.NewSession()
  490. defer sess.Close()
  491. if err = sess.Begin(); err != nil {
  492. return err
  493. }
  494. t.LowerName = strings.ToLower(t.Name)
  495. has, err := sess.
  496. Where("org_id=?", t.OrgID).
  497. And("lower_name=?", t.LowerName).
  498. And("id!=?", t.ID).
  499. Get(new(Team))
  500. if err != nil {
  501. return err
  502. } else if has {
  503. return ErrTeamAlreadyExist{t.OrgID, t.LowerName}
  504. }
  505. if _, err = sess.ID(t.ID).Cols("name", "lower_name", "description",
  506. "can_create_org_repo", "authorize", "includes_all_repositories").Update(t); err != nil {
  507. return fmt.Errorf("update: %v", err)
  508. }
  509. // update units for team
  510. if len(t.Units) > 0 {
  511. for _, unit := range t.Units {
  512. unit.TeamID = t.ID
  513. }
  514. // Delete team-unit.
  515. if _, err := sess.
  516. Where("team_id=?", t.ID).
  517. Delete(new(TeamUnit)); err != nil {
  518. return err
  519. }
  520. if _, err = sess.Cols("org_id", "team_id", "type").Insert(&t.Units); err != nil {
  521. errRollback := sess.Rollback()
  522. if errRollback != nil {
  523. log.Error("UpdateTeam sess.Rollback: %v", errRollback)
  524. }
  525. return err
  526. }
  527. }
  528. // Update access for team members if needed.
  529. if authChanged {
  530. if err = t.getRepositories(sess); err != nil {
  531. return fmt.Errorf("getRepositories: %v", err)
  532. }
  533. for _, repo := range t.Repos {
  534. if err = repo.recalculateTeamAccesses(sess, 0); err != nil {
  535. return fmt.Errorf("recalculateTeamAccesses: %v", err)
  536. }
  537. }
  538. }
  539. // Add all repositories to the team if it has access to all of them.
  540. if includeAllChanged && t.IncludesAllRepositories {
  541. err = t.addAllRepositories(sess)
  542. if err != nil {
  543. return fmt.Errorf("addAllRepositories: %v", err)
  544. }
  545. }
  546. return sess.Commit()
  547. }
  548. // DeleteTeam deletes given team.
  549. // It's caller's responsibility to assign organization ID.
  550. func DeleteTeam(t *Team) error {
  551. if err := t.GetRepositories(&SearchTeamOptions{}); err != nil {
  552. return err
  553. }
  554. sess := x.NewSession()
  555. defer sess.Close()
  556. if err := sess.Begin(); err != nil {
  557. return err
  558. }
  559. if err := t.getMembers(sess); err != nil {
  560. return err
  561. }
  562. if err := t.removeAllRepositories(sess); err != nil {
  563. return err
  564. }
  565. // Delete team-user.
  566. if _, err := sess.
  567. Where("org_id=?", t.OrgID).
  568. Where("team_id=?", t.ID).
  569. Delete(new(TeamUser)); err != nil {
  570. return err
  571. }
  572. // Delete team-unit.
  573. if _, err := sess.
  574. Where("team_id=?", t.ID).
  575. Delete(new(TeamUnit)); err != nil {
  576. return err
  577. }
  578. // Delete team.
  579. if _, err := sess.ID(t.ID).Delete(new(Team)); err != nil {
  580. return err
  581. }
  582. // Update organization number of teams.
  583. if _, err := sess.Exec("UPDATE `user` SET num_teams=num_teams-1 WHERE id=?", t.OrgID); err != nil {
  584. return err
  585. }
  586. return sess.Commit()
  587. }
  588. // ___________ ____ ___
  589. // \__ ___/___ _____ _____ | | \______ ___________
  590. // | |_/ __ \\__ \ / \| | / ___// __ \_ __ \
  591. // | |\ ___/ / __ \| Y Y \ | /\___ \\ ___/| | \/
  592. // |____| \___ >____ /__|_| /______//____ >\___ >__|
  593. // \/ \/ \/ \/ \/
  594. // TeamUser represents an team-user relation.
  595. type TeamUser struct {
  596. ID int64 `xorm:"pk autoincr"`
  597. OrgID int64 `xorm:"INDEX"`
  598. TeamID int64 `xorm:"UNIQUE(s)"`
  599. UID int64 `xorm:"UNIQUE(s)"`
  600. }
  601. func isTeamMember(e Engine, orgID, teamID, userID int64) (bool, error) {
  602. return e.
  603. Where("org_id=?", orgID).
  604. And("team_id=?", teamID).
  605. And("uid=?", userID).
  606. Table("team_user").
  607. Exist()
  608. }
  609. // IsTeamMember returns true if given user is a member of team.
  610. func IsTeamMember(orgID, teamID, userID int64) (bool, error) {
  611. return isTeamMember(x, orgID, teamID, userID)
  612. }
  613. func getTeamUsersByTeamID(e Engine, teamID int64) ([]*TeamUser, error) {
  614. teamUsers := make([]*TeamUser, 0, 10)
  615. return teamUsers, e.
  616. Where("team_id=?", teamID).
  617. Find(&teamUsers)
  618. }
  619. func getTeamMembers(e Engine, teamID int64) (_ []*User, err error) {
  620. teamUsers, err := getTeamUsersByTeamID(e, teamID)
  621. if err != nil {
  622. return nil, fmt.Errorf("get team-users: %v", err)
  623. }
  624. members := make([]*User, len(teamUsers))
  625. for i, teamUser := range teamUsers {
  626. member, err := getUserByID(e, teamUser.UID)
  627. if err != nil {
  628. return nil, fmt.Errorf("get user '%d': %v", teamUser.UID, err)
  629. }
  630. members[i] = member
  631. }
  632. sort.Slice(members, func(i, j int) bool {
  633. return members[i].DisplayName() < members[j].DisplayName()
  634. })
  635. return members, nil
  636. }
  637. // GetTeamMembers returns all members in given team of organization.
  638. func GetTeamMembers(teamID int64) ([]*User, error) {
  639. return getTeamMembers(x, teamID)
  640. }
  641. func getUserTeams(e Engine, userID int64, listOptions ListOptions) (teams []*Team, err error) {
  642. sess := e.
  643. Join("INNER", "team_user", "team_user.team_id = team.id").
  644. Where("team_user.uid=?", userID)
  645. if listOptions.Page != 0 {
  646. sess = listOptions.setSessionPagination(sess)
  647. }
  648. return teams, sess.Find(&teams)
  649. }
  650. func getUserOrgTeams(e Engine, orgID, userID int64) (teams []*Team, err error) {
  651. return teams, e.
  652. Join("INNER", "team_user", "team_user.team_id = team.id").
  653. Where("team.org_id = ?", orgID).
  654. And("team_user.uid=?", userID).
  655. Find(&teams)
  656. }
  657. func getUserRepoTeams(e Engine, orgID, userID, repoID int64) (teams []*Team, err error) {
  658. return teams, e.
  659. Join("INNER", "team_user", "team_user.team_id = team.id").
  660. Join("INNER", "team_repo", "team_repo.team_id = team.id").
  661. Where("team.org_id = ?", orgID).
  662. And("team_user.uid=?", userID).
  663. And("team_repo.repo_id=?", repoID).
  664. Find(&teams)
  665. }
  666. // GetUserOrgTeams returns all teams that user belongs to in given organization.
  667. func GetUserOrgTeams(orgID, userID int64) ([]*Team, error) {
  668. return getUserOrgTeams(x, orgID, userID)
  669. }
  670. // GetUserTeams returns all teams that user belongs across all organizations.
  671. func GetUserTeams(userID int64, listOptions ListOptions) ([]*Team, error) {
  672. return getUserTeams(x, userID, listOptions)
  673. }
  674. // AddTeamMember adds new membership of given team to given organization,
  675. // the user will have membership to given organization automatically when needed.
  676. func AddTeamMember(team *Team, userID int64) error {
  677. isAlreadyMember, err := IsTeamMember(team.OrgID, team.ID, userID)
  678. if err != nil || isAlreadyMember {
  679. return err
  680. }
  681. if err := AddOrgUser(team.OrgID, userID); err != nil {
  682. return err
  683. }
  684. // Get team and its repositories.
  685. if err := team.GetRepositories(&SearchTeamOptions{}); err != nil {
  686. return err
  687. }
  688. sess := x.NewSession()
  689. defer sess.Close()
  690. if err := sess.Begin(); err != nil {
  691. return err
  692. }
  693. if _, err := sess.Insert(&TeamUser{
  694. UID: userID,
  695. OrgID: team.OrgID,
  696. TeamID: team.ID,
  697. }); err != nil {
  698. return err
  699. } else if _, err := sess.Incr("num_members").ID(team.ID).Update(new(Team)); err != nil {
  700. return err
  701. }
  702. team.NumMembers++
  703. // Give access to team repositories.
  704. for _, repo := range team.Repos {
  705. if err := repo.recalculateUserAccess(sess, userID); err != nil {
  706. return err
  707. }
  708. if setting.Service.AutoWatchNewRepos {
  709. if err = watchRepo(sess, userID, repo.ID, true); err != nil {
  710. return err
  711. }
  712. }
  713. }
  714. return sess.Commit()
  715. }
  716. func removeTeamMember(e *xorm.Session, team *Team, userID int64) error {
  717. isMember, err := isTeamMember(e, team.OrgID, team.ID, userID)
  718. if err != nil || !isMember {
  719. return err
  720. }
  721. // Check if the user to delete is the last member in owner team.
  722. if team.IsOwnerTeam() && team.NumMembers == 1 {
  723. return ErrLastOrgOwner{UID: userID}
  724. }
  725. team.NumMembers--
  726. if err := team.getRepositories(e); err != nil {
  727. return err
  728. }
  729. if _, err := e.Delete(&TeamUser{
  730. UID: userID,
  731. OrgID: team.OrgID,
  732. TeamID: team.ID,
  733. }); err != nil {
  734. return err
  735. } else if _, err = e.
  736. ID(team.ID).
  737. Cols("num_members").
  738. Update(team); err != nil {
  739. return err
  740. }
  741. // Delete access to team repositories.
  742. for _, repo := range team.Repos {
  743. if err := repo.recalculateUserAccess(e, userID); err != nil {
  744. return err
  745. }
  746. // Remove watches from now unaccessible
  747. has, err := hasAccess(e, userID, repo)
  748. if err != nil {
  749. return err
  750. } else if has {
  751. continue
  752. }
  753. if err = watchRepo(e, userID, repo.ID, false); err != nil {
  754. return err
  755. }
  756. // Remove all IssueWatches a user has subscribed to in the repositories
  757. if err := removeIssueWatchersByRepoID(e, userID, repo.ID); err != nil {
  758. return err
  759. }
  760. }
  761. // Check if the user is a member of any team in the organization.
  762. if count, err := e.Count(&TeamUser{
  763. UID: userID,
  764. OrgID: team.OrgID,
  765. }); err != nil {
  766. return err
  767. } else if count == 0 {
  768. return removeOrgUser(e, team.OrgID, userID)
  769. }
  770. return nil
  771. }
  772. // RemoveTeamMember removes member from given team of given organization.
  773. func RemoveTeamMember(team *Team, userID int64) error {
  774. sess := x.NewSession()
  775. defer sess.Close()
  776. if err := sess.Begin(); err != nil {
  777. return err
  778. }
  779. if err := removeTeamMember(sess, team, userID); err != nil {
  780. return err
  781. }
  782. return sess.Commit()
  783. }
  784. // IsUserInTeams returns if a user in some teams
  785. func IsUserInTeams(userID int64, teamIDs []int64) (bool, error) {
  786. return isUserInTeams(x, userID, teamIDs)
  787. }
  788. func isUserInTeams(e Engine, userID int64, teamIDs []int64) (bool, error) {
  789. return e.Where("uid=?", userID).In("team_id", teamIDs).Exist(new(TeamUser))
  790. }
  791. // UsersInTeamsCount counts the number of users which are in userIDs and teamIDs
  792. func UsersInTeamsCount(userIDs []int64, teamIDs []int64) (int64, error) {
  793. var ids []int64
  794. if err := x.In("uid", userIDs).In("team_id", teamIDs).
  795. Table("team_user").
  796. Cols("uid").GroupBy("uid").Find(&ids); err != nil {
  797. return 0, err
  798. }
  799. return int64(len(ids)), nil
  800. }
  801. // ___________ __________
  802. // \__ ___/___ _____ _____\______ \ ____ ______ ____
  803. // | |_/ __ \\__ \ / \| _// __ \\____ \ / _ \
  804. // | |\ ___/ / __ \| Y Y \ | \ ___/| |_> > <_> )
  805. // |____| \___ >____ /__|_| /____|_ /\___ > __/ \____/
  806. // \/ \/ \/ \/ \/|__|
  807. // TeamRepo represents an team-repository relation.
  808. type TeamRepo struct {
  809. ID int64 `xorm:"pk autoincr"`
  810. OrgID int64 `xorm:"INDEX"`
  811. TeamID int64 `xorm:"UNIQUE(s)"`
  812. RepoID int64 `xorm:"UNIQUE(s)"`
  813. }
  814. func hasTeamRepo(e Engine, orgID, teamID, repoID int64) bool {
  815. has, _ := e.
  816. Where("org_id=?", orgID).
  817. And("team_id=?", teamID).
  818. And("repo_id=?", repoID).
  819. Get(new(TeamRepo))
  820. return has
  821. }
  822. // HasTeamRepo returns true if given repository belongs to team.
  823. func HasTeamRepo(orgID, teamID, repoID int64) bool {
  824. return hasTeamRepo(x, orgID, teamID, repoID)
  825. }
  826. func addTeamRepo(e Engine, orgID, teamID, repoID int64) error {
  827. _, err := e.InsertOne(&TeamRepo{
  828. OrgID: orgID,
  829. TeamID: teamID,
  830. RepoID: repoID,
  831. })
  832. return err
  833. }
  834. func removeTeamRepo(e Engine, teamID, repoID int64) error {
  835. _, err := e.Delete(&TeamRepo{
  836. TeamID: teamID,
  837. RepoID: repoID,
  838. })
  839. return err
  840. }
  841. // GetTeamsWithAccessToRepo returns all teams in an organization that have given access level to the repository.
  842. func GetTeamsWithAccessToRepo(orgID, repoID int64, mode AccessMode) ([]*Team, error) {
  843. teams := make([]*Team, 0, 5)
  844. return teams, x.Where("team.authorize >= ?", mode).
  845. Join("INNER", "team_repo", "team_repo.team_id = team.id").
  846. And("team_repo.org_id = ?", orgID).
  847. And("team_repo.repo_id = ?", repoID).
  848. Find(&teams)
  849. }
  850. // ___________ ____ ___ .__ __
  851. // \__ ___/___ _____ _____ | | \____ |__|/ |_
  852. // | |_/ __ \\__ \ / \| | / \| \ __\
  853. // | |\ ___/ / __ \| Y Y \ | / | \ || |
  854. // |____| \___ >____ /__|_| /______/|___| /__||__|
  855. // \/ \/ \/ \/
  856. // TeamUnit describes all units of a repository
  857. type TeamUnit struct {
  858. ID int64 `xorm:"pk autoincr"`
  859. OrgID int64 `xorm:"INDEX"`
  860. TeamID int64 `xorm:"UNIQUE(s)"`
  861. Type UnitType `xorm:"UNIQUE(s)"`
  862. }
  863. // Unit returns Unit
  864. func (t *TeamUnit) Unit() Unit {
  865. return Units[t.Type]
  866. }
  867. func getUnitsByTeamID(e Engine, teamID int64) (units []*TeamUnit, err error) {
  868. return units, e.Where("team_id = ?", teamID).Find(&units)
  869. }
  870. // UpdateTeamUnits updates a teams's units
  871. func UpdateTeamUnits(team *Team, units []TeamUnit) (err error) {
  872. sess := x.NewSession()
  873. defer sess.Close()
  874. if err = sess.Begin(); err != nil {
  875. return err
  876. }
  877. if _, err = sess.Where("team_id = ?", team.ID).Delete(new(TeamUnit)); err != nil {
  878. return err
  879. }
  880. if _, err = sess.Insert(units); err != nil {
  881. errRollback := sess.Rollback()
  882. if errRollback != nil {
  883. log.Error("UpdateTeamUnits sess.Rollback: %v", errRollback)
  884. }
  885. return err
  886. }
  887. return sess.Commit()
  888. }