repo_branch.go 7.7 KB

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