repo_branch.go 7.5 KB

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