repo_branch.go 8.2 KB

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