repo_branch.go 7.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260
  1. // Copyright 2015 The Gogs Authors. All rights reserved.
  2. // Copyright 2018 Gitote. All rights reserved.
  3. //
  4. // This source code is licensed under the MIT license found in the
  5. // LICENSE file in the root directory of this source tree.
  6. package models
  7. import (
  8. "fmt"
  9. "gitote/gitote/models/errors"
  10. "gitote/gitote/pkg/tool"
  11. "strings"
  12. "gitlab.com/gitote/com"
  13. "gitlab.com/gitote/git-module"
  14. )
  15. type Branch struct {
  16. RepoPath string
  17. Name string
  18. IsProtected bool
  19. Commit *git.Commit
  20. }
  21. // GetBranchesByPath returns a branch by it's path
  22. func GetBranchesByPath(path string) ([]*Branch, error) {
  23. gitRepo, err := git.OpenRepository(path)
  24. if err != nil {
  25. return nil, err
  26. }
  27. brs, err := gitRepo.GetBranches()
  28. if err != nil {
  29. return nil, err
  30. }
  31. branches := make([]*Branch, len(brs))
  32. for i := range brs {
  33. branches[i] = &Branch{
  34. RepoPath: path,
  35. Name: brs[i],
  36. }
  37. }
  38. return branches, nil
  39. }
  40. func (repo *Repository) GetBranch(br string) (*Branch, error) {
  41. if !git.IsBranchExist(repo.RepoPath(), br) {
  42. return nil, errors.ErrBranchNotExist{br}
  43. }
  44. return &Branch{
  45. RepoPath: repo.RepoPath(),
  46. Name: br,
  47. }, nil
  48. }
  49. func (repo *Repository) GetBranches() ([]*Branch, error) {
  50. return GetBranchesByPath(repo.RepoPath())
  51. }
  52. func (br *Branch) GetCommit() (*git.Commit, error) {
  53. gitRepo, err := git.OpenRepository(br.RepoPath)
  54. if err != nil {
  55. return nil, err
  56. }
  57. return gitRepo.GetBranchCommit(br.Name)
  58. }
  59. type ProtectBranchWhitelist struct {
  60. ID int64
  61. ProtectBranchID int64
  62. RepoID int64 `xorm:"UNIQUE(protect_branch_whitelist)"`
  63. Name string `xorm:"UNIQUE(protect_branch_whitelist)"`
  64. UserID int64 `xorm:"UNIQUE(protect_branch_whitelist)"`
  65. }
  66. // IsUserInProtectBranchWhitelist returns true if given user is in the whitelist of a branch in a repository.
  67. func IsUserInProtectBranchWhitelist(repoID, userID int64, branch string) bool {
  68. has, err := x.Where("repo_id = ?", repoID).And("user_id = ?", userID).And("name = ?", branch).Get(new(ProtectBranchWhitelist))
  69. return has && err == nil
  70. }
  71. // ProtectBranch contains options of a protected branch.
  72. type ProtectBranch struct {
  73. ID int64
  74. RepoID int64 `xorm:"UNIQUE(protect_branch)"`
  75. Name string `xorm:"UNIQUE(protect_branch)"`
  76. Protected bool
  77. RequirePullRequest bool
  78. EnableWhitelist bool
  79. WhitelistUserIDs string `xorm:"TEXT"`
  80. WhitelistTeamIDs string `xorm:"TEXT"`
  81. }
  82. // GetProtectBranchOfRepoByName returns *ProtectBranch by branch name in given repository.
  83. func GetProtectBranchOfRepoByName(repoID int64, name string) (*ProtectBranch, error) {
  84. protectBranch := &ProtectBranch{
  85. RepoID: repoID,
  86. Name: name,
  87. }
  88. has, err := x.Get(protectBranch)
  89. if err != nil {
  90. return nil, err
  91. } else if !has {
  92. return nil, errors.ErrBranchNotExist{name}
  93. }
  94. return protectBranch, nil
  95. }
  96. // IsBranchOfRepoRequirePullRequest returns true if branch requires pull request in given repository.
  97. func IsBranchOfRepoRequirePullRequest(repoID int64, name string) bool {
  98. protectBranch, err := GetProtectBranchOfRepoByName(repoID, name)
  99. if err != nil {
  100. return false
  101. }
  102. return protectBranch.Protected && protectBranch.RequirePullRequest
  103. }
  104. // UpdateProtectBranch saves branch protection options.
  105. // If ID is 0, it creates a new record. Otherwise, updates existing record.
  106. func UpdateProtectBranch(protectBranch *ProtectBranch) (err error) {
  107. sess := x.NewSession()
  108. defer sess.Close()
  109. if err = sess.Begin(); err != nil {
  110. return err
  111. }
  112. if protectBranch.ID == 0 {
  113. if _, err = sess.Insert(protectBranch); err != nil {
  114. return fmt.Errorf("Insert: %v", err)
  115. }
  116. }
  117. if _, err = sess.ID(protectBranch.ID).AllCols().Update(protectBranch); err != nil {
  118. return fmt.Errorf("Update: %v", err)
  119. }
  120. return sess.Commit()
  121. }
  122. // UpdateOrgProtectBranch saves branch protection options of organizational repository.
  123. // If ID is 0, it creates a new record. Otherwise, updates existing record.
  124. // This function also performs check if whitelist user and team's IDs have been changed
  125. // to avoid unnecessary whitelist delete and regenerate.
  126. func UpdateOrgProtectBranch(repo *Repository, protectBranch *ProtectBranch, whitelistUserIDs, whitelistTeamIDs string) (err error) {
  127. if err = repo.GetOwner(); err != nil {
  128. return fmt.Errorf("GetOwner: %v", err)
  129. } else if !repo.Owner.IsOrganization() {
  130. return fmt.Errorf("expect repository owner to be an organization")
  131. }
  132. hasUsersChanged := false
  133. validUserIDs := tool.StringsToInt64s(strings.Split(protectBranch.WhitelistUserIDs, ","))
  134. if protectBranch.WhitelistUserIDs != whitelistUserIDs {
  135. hasUsersChanged = true
  136. userIDs := tool.StringsToInt64s(strings.Split(whitelistUserIDs, ","))
  137. validUserIDs = make([]int64, 0, len(userIDs))
  138. for _, userID := range userIDs {
  139. has, err := HasAccess(userID, repo, AccessModeWrite)
  140. if err != nil {
  141. return fmt.Errorf("HasAccess [user_id: %d, repo_id: %d]: %v", userID, protectBranch.RepoID, err)
  142. } else if !has {
  143. continue // Drop invalid user ID
  144. }
  145. validUserIDs = append(validUserIDs, userID)
  146. }
  147. protectBranch.WhitelistUserIDs = strings.Join(tool.Int64sToStrings(validUserIDs), ",")
  148. }
  149. hasTeamsChanged := false
  150. validTeamIDs := tool.StringsToInt64s(strings.Split(protectBranch.WhitelistTeamIDs, ","))
  151. if protectBranch.WhitelistTeamIDs != whitelistTeamIDs {
  152. hasTeamsChanged = true
  153. teamIDs := tool.StringsToInt64s(strings.Split(whitelistTeamIDs, ","))
  154. teams, err := GetTeamsHaveAccessToRepo(repo.OwnerID, repo.ID, AccessModeWrite)
  155. if err != nil {
  156. return fmt.Errorf("GetTeamsHaveAccessToRepo [org_id: %d, repo_id: %d]: %v", repo.OwnerID, repo.ID, err)
  157. }
  158. validTeamIDs = make([]int64, 0, len(teams))
  159. for i := range teams {
  160. if teams[i].HasWriteAccess() && com.IsSliceContainsInt64(teamIDs, teams[i].ID) {
  161. validTeamIDs = append(validTeamIDs, teams[i].ID)
  162. }
  163. }
  164. protectBranch.WhitelistTeamIDs = strings.Join(tool.Int64sToStrings(validTeamIDs), ",")
  165. }
  166. // Make sure protectBranch.ID is not 0 for whitelists
  167. if protectBranch.ID == 0 {
  168. if _, err = x.Insert(protectBranch); err != nil {
  169. return fmt.Errorf("Insert: %v", err)
  170. }
  171. }
  172. // Merge users and members of teams
  173. var whitelists []*ProtectBranchWhitelist
  174. if hasUsersChanged || hasTeamsChanged {
  175. mergedUserIDs := make(map[int64]bool)
  176. for _, userID := range validUserIDs {
  177. // Empty whitelist users can cause an ID with 0
  178. if userID != 0 {
  179. mergedUserIDs[userID] = true
  180. }
  181. }
  182. for _, teamID := range validTeamIDs {
  183. members, err := GetTeamMembers(teamID)
  184. if err != nil {
  185. return fmt.Errorf("GetTeamMembers [team_id: %d]: %v", teamID, err)
  186. }
  187. for i := range members {
  188. mergedUserIDs[members[i].ID] = true
  189. }
  190. }
  191. whitelists = make([]*ProtectBranchWhitelist, 0, len(mergedUserIDs))
  192. for userID := range mergedUserIDs {
  193. whitelists = append(whitelists, &ProtectBranchWhitelist{
  194. ProtectBranchID: protectBranch.ID,
  195. RepoID: repo.ID,
  196. Name: protectBranch.Name,
  197. UserID: userID,
  198. })
  199. }
  200. }
  201. sess := x.NewSession()
  202. defer sess.Close()
  203. if err = sess.Begin(); err != nil {
  204. return err
  205. }
  206. if _, err = sess.ID(protectBranch.ID).AllCols().Update(protectBranch); err != nil {
  207. return fmt.Errorf("Update: %v", err)
  208. }
  209. // Refresh whitelists
  210. if hasUsersChanged || hasTeamsChanged {
  211. if _, err = sess.Delete(&ProtectBranchWhitelist{ProtectBranchID: protectBranch.ID}); err != nil {
  212. return fmt.Errorf("delete old protect branch whitelists: %v", err)
  213. } else if _, err = sess.Insert(whitelists); err != nil {
  214. return fmt.Errorf("insert new protect branch whitelists: %v", err)
  215. }
  216. }
  217. return sess.Commit()
  218. }
  219. // GetProtectBranchesByRepoID returns a list of *ProtectBranch in given repository.
  220. func GetProtectBranchesByRepoID(repoID int64) ([]*ProtectBranch, error) {
  221. protectBranches := make([]*ProtectBranch, 0, 2)
  222. return protectBranches, x.Where("repo_id = ? and protected = ?", repoID, true).Asc("name").Find(&protectBranches)
  223. }