repo_branch.go 8.1 KB

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