repo_branch.go 8.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276
  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 repostiory.
  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. has, err := HasAccess(userID, repo, ACCESS_MODE_WRITE)
  151. if err != nil {
  152. return fmt.Errorf("HasAccess [user_id: %d, repo_id: %d]: %v", userID, protectBranch.RepoID, err)
  153. } else if !has {
  154. continue // Drop invalid user ID
  155. }
  156. validUserIDs = append(validUserIDs, userID)
  157. }
  158. protectBranch.WhitelistUserIDs = strings.Join(tool.Int64sToStrings(validUserIDs), ",")
  159. }
  160. hasTeamsChanged := false
  161. validTeamIDs := tool.StringsToInt64s(strings.Split(protectBranch.WhitelistTeamIDs, ","))
  162. if protectBranch.WhitelistTeamIDs != whitelistTeamIDs {
  163. hasTeamsChanged = true
  164. teamIDs := tool.StringsToInt64s(strings.Split(whitelistTeamIDs, ","))
  165. teams, err := GetTeamsHaveAccessToRepo(repo.OwnerID, repo.ID, ACCESS_MODE_WRITE)
  166. if err != nil {
  167. return fmt.Errorf("GetTeamsHaveAccessToRepo [org_id: %d, repo_id: %d]: %v", repo.OwnerID, repo.ID, err)
  168. }
  169. validTeamIDs = make([]int64, 0, len(teams))
  170. for i := range teams {
  171. if teams[i].HasWriteAccess() && com.IsSliceContainsInt64(teamIDs, teams[i].ID) {
  172. validTeamIDs = append(validTeamIDs, teams[i].ID)
  173. }
  174. }
  175. protectBranch.WhitelistTeamIDs = strings.Join(tool.Int64sToStrings(validTeamIDs), ",")
  176. }
  177. // Make sure protectBranch.ID is not 0 for whitelists
  178. if protectBranch.ID == 0 {
  179. if _, err = x.Insert(protectBranch); err != nil {
  180. return fmt.Errorf("Insert: %v", err)
  181. }
  182. }
  183. // Merge users and members of teams
  184. var whitelists []*ProtectBranchWhitelist
  185. if hasUsersChanged || hasTeamsChanged {
  186. mergedUserIDs := make(map[int64]bool)
  187. for _, userID := range validUserIDs {
  188. // Empty whitelist users can cause an ID with 0
  189. if userID != 0 {
  190. mergedUserIDs[userID] = true
  191. }
  192. }
  193. for _, teamID := range validTeamIDs {
  194. members, err := GetTeamMembers(teamID)
  195. if err != nil {
  196. return fmt.Errorf("GetTeamMembers [team_id: %d]: %v", teamID, err)
  197. }
  198. for i := range members {
  199. mergedUserIDs[members[i].ID] = true
  200. }
  201. }
  202. whitelists = make([]*ProtectBranchWhitelist, 0, len(mergedUserIDs))
  203. for userID := range mergedUserIDs {
  204. whitelists = append(whitelists, &ProtectBranchWhitelist{
  205. ProtectBranchID: protectBranch.ID,
  206. RepoID: repo.ID,
  207. Name: protectBranch.Name,
  208. UserID: userID,
  209. })
  210. }
  211. }
  212. sess := x.NewSession()
  213. defer sess.Close()
  214. if err = sess.Begin(); err != nil {
  215. return err
  216. }
  217. if _, err = sess.ID(protectBranch.ID).AllCols().Update(protectBranch); err != nil {
  218. return fmt.Errorf("Update: %v", err)
  219. }
  220. // Refresh whitelists
  221. if hasUsersChanged || hasTeamsChanged {
  222. if _, err = sess.Delete(&ProtectBranchWhitelist{ProtectBranchID: protectBranch.ID}); err != nil {
  223. return fmt.Errorf("delete old protect branch whitelists: %v", err)
  224. } else if _, err = sess.Insert(whitelists); err != nil {
  225. return fmt.Errorf("insert new protect branch whitelists: %v", err)
  226. }
  227. }
  228. return sess.Commit()
  229. }
  230. // GetProtectBranchesByRepoID returns a list of *ProtectBranch in given repostiory.
  231. func GetProtectBranchesByRepoID(repoID int64) ([]*ProtectBranch, error) {
  232. protectBranches := make([]*ProtectBranch, 0, 2)
  233. return protectBranches, x.Where("repo_id = ? and protected = ?", repoID, true).Asc("name").Find(&protectBranches)
  234. }