repo_branch.go 8.0 KB

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