repo_branch.go 7.8 KB

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