repo_branch.go 7.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252
  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. }
  111. if _, err = sess.Id(protectBranch.ID).AllCols().Update(protectBranch); err != nil {
  112. return fmt.Errorf("Update: %v", err)
  113. }
  114. return sess.Commit()
  115. }
  116. // UpdateOrgProtectBranch saves branch protection options of organizational repository.
  117. // If ID is 0, it creates a new record. Otherwise, updates existing record.
  118. // This function also performs check if whitelist user and team's IDs have been changed
  119. // to avoid unnecessary whitelist delete and regenerate.
  120. func UpdateOrgProtectBranch(repo *Repository, protectBranch *ProtectBranch, whitelistUserIDs, whitelistTeamIDs string) (err error) {
  121. if err = repo.GetOwner(); err != nil {
  122. return fmt.Errorf("GetOwner: %v", err)
  123. } else if !repo.Owner.IsOrganization() {
  124. return fmt.Errorf("expect repository owner to be an organization")
  125. }
  126. hasUsersChanged := false
  127. validUserIDs := base.StringsToInt64s(strings.Split(protectBranch.WhitelistUserIDs, ","))
  128. if protectBranch.WhitelistUserIDs != whitelistUserIDs {
  129. hasUsersChanged = true
  130. userIDs := base.StringsToInt64s(strings.Split(whitelistUserIDs, ","))
  131. validUserIDs = make([]int64, 0, len(userIDs))
  132. for _, userID := range userIDs {
  133. has, err := HasAccess(userID, repo, ACCESS_MODE_WRITE)
  134. if err != nil {
  135. return fmt.Errorf("HasAccess [user_id: %d, repo_id: %d]: %v", userID, protectBranch.RepoID, err)
  136. } else if !has {
  137. continue // Drop invalid user ID
  138. }
  139. validUserIDs = append(validUserIDs, userID)
  140. }
  141. protectBranch.WhitelistUserIDs = strings.Join(base.Int64sToStrings(validUserIDs), ",")
  142. }
  143. hasTeamsChanged := false
  144. validTeamIDs := base.StringsToInt64s(strings.Split(protectBranch.WhitelistTeamIDs, ","))
  145. if protectBranch.WhitelistTeamIDs != whitelistTeamIDs {
  146. hasTeamsChanged = true
  147. teamIDs := base.StringsToInt64s(strings.Split(whitelistTeamIDs, ","))
  148. teams, err := GetTeamsHaveAccessToRepo(repo.OwnerID, repo.ID, ACCESS_MODE_WRITE)
  149. if err != nil {
  150. return fmt.Errorf("GetTeamsHaveAccessToRepo [org_id: %d, repo_id: %d]: %v", repo.OwnerID, repo.ID, err)
  151. }
  152. validTeamIDs = make([]int64, 0, len(teams))
  153. for i := range teams {
  154. if teams[i].HasWriteAccess() && com.IsSliceContainsInt64(teamIDs, teams[i].ID) {
  155. validTeamIDs = append(validTeamIDs, teams[i].ID)
  156. }
  157. }
  158. protectBranch.WhitelistTeamIDs = strings.Join(base.Int64sToStrings(validTeamIDs), ",")
  159. }
  160. // Merge users and members of teams
  161. var whitelists []*ProtectBranchWhitelist
  162. if hasUsersChanged || hasTeamsChanged {
  163. mergedUserIDs := make(map[int64]bool)
  164. for _, userID := range validUserIDs {
  165. // Empty whitelist users can cause an ID with 0
  166. if userID != 0 {
  167. mergedUserIDs[userID] = true
  168. }
  169. }
  170. for _, teamID := range validTeamIDs {
  171. members, err := GetTeamMembers(teamID)
  172. if err != nil {
  173. return fmt.Errorf("GetTeamMembers [team_id: %d]: %v", teamID, err)
  174. }
  175. for i := range members {
  176. mergedUserIDs[members[i].ID] = true
  177. }
  178. }
  179. whitelists = make([]*ProtectBranchWhitelist, 0, len(mergedUserIDs))
  180. for userID := range mergedUserIDs {
  181. whitelists = append(whitelists, &ProtectBranchWhitelist{
  182. ProtectBranchID: protectBranch.ID,
  183. RepoID: repo.ID,
  184. Name: protectBranch.Name,
  185. UserID: userID,
  186. })
  187. }
  188. }
  189. sess := x.NewSession()
  190. defer sessionRelease(sess)
  191. if err = sess.Begin(); err != nil {
  192. return err
  193. }
  194. if protectBranch.ID == 0 {
  195. if _, err = sess.Insert(protectBranch); err != nil {
  196. return fmt.Errorf("Insert: %v", err)
  197. }
  198. }
  199. if _, err = sess.Id(protectBranch.ID).AllCols().Update(protectBranch); err != nil {
  200. return fmt.Errorf("Update: %v", err)
  201. }
  202. // Refresh whitelists
  203. if hasUsersChanged || hasTeamsChanged {
  204. if _, err = sess.Delete(&ProtectBranchWhitelist{ProtectBranchID: protectBranch.ID}); err != nil {
  205. return fmt.Errorf("delete old protect branch whitelists: %v", err)
  206. } else if _, err = sess.Insert(whitelists); err != nil {
  207. return fmt.Errorf("insert new protect branch whitelists: %v", err)
  208. }
  209. }
  210. return sess.Commit()
  211. }
  212. // GetProtectBranchesByRepoID returns a list of *ProtectBranch in given repostiory.
  213. func GetProtectBranchesByRepoID(repoID int64) ([]*ProtectBranch, error) {
  214. protectBranches := make([]*ProtectBranch, 0, 2)
  215. return protectBranches, x.Where("repo_id = ?", repoID).Asc("name").Find(&protectBranches)
  216. }