repo_branch.go 7.6 KB

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