1
0

repo_branch.go 8.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275
  1. package database
  2. import (
  3. "context"
  4. "fmt"
  5. "strings"
  6. "github.com/gogs/git-module"
  7. "github.com/unknwon/com"
  8. "gogs.io/gogs/internal/errutil"
  9. "gogs.io/gogs/internal/tool"
  10. )
  11. type Branch struct {
  12. RepoPath string
  13. Name string
  14. IsProtected bool
  15. Commit *git.Commit
  16. }
  17. func GetBranchesByPath(path string) ([]*Branch, error) {
  18. gitRepo, err := git.Open(path)
  19. if err != nil {
  20. return nil, fmt.Errorf("open repository: %v", err)
  21. }
  22. names, err := gitRepo.Branches()
  23. if err != nil {
  24. return nil, fmt.Errorf("list branches")
  25. }
  26. branches := make([]*Branch, len(names))
  27. for i := range names {
  28. branches[i] = &Branch{
  29. RepoPath: path,
  30. Name: names[i],
  31. }
  32. }
  33. return branches, nil
  34. }
  35. var _ errutil.NotFound = (*ErrBranchNotExist)(nil)
  36. type ErrBranchNotExist struct {
  37. args map[string]any
  38. }
  39. func IsErrBranchNotExist(err error) bool {
  40. _, ok := err.(ErrBranchNotExist)
  41. return ok
  42. }
  43. func (err ErrBranchNotExist) Error() string {
  44. return fmt.Sprintf("branch does not exist: %v", err.args)
  45. }
  46. func (ErrBranchNotExist) NotFound() bool {
  47. return true
  48. }
  49. func (r *Repository) GetBranch(name string) (*Branch, error) {
  50. if !git.RepoHasBranch(r.RepoPath(), name) {
  51. return nil, ErrBranchNotExist{args: map[string]any{"name": name}}
  52. }
  53. return &Branch{
  54. RepoPath: r.RepoPath(),
  55. Name: name,
  56. }, nil
  57. }
  58. func (r *Repository) GetBranches() ([]*Branch, error) {
  59. return GetBranchesByPath(r.RepoPath())
  60. }
  61. func (br *Branch) GetCommit() (*git.Commit, error) {
  62. gitRepo, err := git.Open(br.RepoPath)
  63. if err != nil {
  64. return nil, fmt.Errorf("open repository: %v", err)
  65. }
  66. return gitRepo.BranchCommit(br.Name)
  67. }
  68. type ProtectBranchWhitelist struct {
  69. ID int64
  70. ProtectBranchID int64
  71. RepoID int64 `xorm:"UNIQUE(protect_branch_whitelist)"`
  72. Name string `xorm:"UNIQUE(protect_branch_whitelist)"`
  73. UserID int64 `xorm:"UNIQUE(protect_branch_whitelist)"`
  74. }
  75. // IsUserInProtectBranchWhitelist returns true if given user is in the whitelist of a branch in a repository.
  76. func IsUserInProtectBranchWhitelist(repoID, userID int64, branch string) bool {
  77. has, err := x.Where("repo_id = ?", repoID).And("user_id = ?", userID).And("name = ?", branch).Get(new(ProtectBranchWhitelist))
  78. return has && err == nil
  79. }
  80. // ProtectBranch contains options of a protected branch.
  81. type ProtectBranch struct {
  82. ID int64
  83. RepoID int64 `xorm:"UNIQUE(protect_branch)"`
  84. Name string `xorm:"UNIQUE(protect_branch)"`
  85. Protected bool
  86. RequirePullRequest bool
  87. EnableWhitelist bool
  88. WhitelistUserIDs string `xorm:"TEXT"`
  89. WhitelistTeamIDs string `xorm:"TEXT"`
  90. }
  91. // GetProtectBranchOfRepoByName returns *ProtectBranch by branch name in given repository.
  92. func GetProtectBranchOfRepoByName(repoID int64, name string) (*ProtectBranch, error) {
  93. protectBranch := &ProtectBranch{
  94. RepoID: repoID,
  95. Name: name,
  96. }
  97. has, err := x.Get(protectBranch)
  98. if err != nil {
  99. return nil, err
  100. } else if !has {
  101. return nil, ErrBranchNotExist{args: map[string]any{"name": name}}
  102. }
  103. return protectBranch, nil
  104. }
  105. // IsBranchOfRepoRequirePullRequest returns true if branch requires pull request in given repository.
  106. func IsBranchOfRepoRequirePullRequest(repoID int64, name string) bool {
  107. protectBranch, err := GetProtectBranchOfRepoByName(repoID, name)
  108. if err != nil {
  109. return false
  110. }
  111. return protectBranch.Protected && protectBranch.RequirePullRequest
  112. }
  113. // UpdateProtectBranch saves branch protection options.
  114. // If ID is 0, it creates a new record. Otherwise, updates existing record.
  115. func UpdateProtectBranch(protectBranch *ProtectBranch) (err error) {
  116. sess := x.NewSession()
  117. defer sess.Close()
  118. if err = sess.Begin(); err != nil {
  119. return err
  120. }
  121. if protectBranch.ID == 0 {
  122. if _, err = sess.Insert(protectBranch); err != nil {
  123. return fmt.Errorf("insert: %v", err)
  124. }
  125. }
  126. if _, err = sess.ID(protectBranch.ID).AllCols().Update(protectBranch); err != nil {
  127. return fmt.Errorf("update: %v", err)
  128. }
  129. return sess.Commit()
  130. }
  131. // UpdateOrgProtectBranch saves branch protection options of organizational repository.
  132. // If ID is 0, it creates a new record. Otherwise, updates existing record.
  133. // This function also performs check if whitelist user and team's IDs have been changed
  134. // to avoid unnecessary whitelist delete and regenerate.
  135. func UpdateOrgProtectBranch(repo *Repository, protectBranch *ProtectBranch, whitelistUserIDs, whitelistTeamIDs string) (err error) {
  136. if err = repo.GetOwner(); err != nil {
  137. return fmt.Errorf("GetOwner: %v", err)
  138. } else if !repo.Owner.IsOrganization() {
  139. return fmt.Errorf("expect repository owner to be an organization")
  140. }
  141. hasUsersChanged := false
  142. validUserIDs := tool.StringsToInt64s(strings.Split(protectBranch.WhitelistUserIDs, ","))
  143. if protectBranch.WhitelistUserIDs != whitelistUserIDs {
  144. hasUsersChanged = true
  145. userIDs := tool.StringsToInt64s(strings.Split(whitelistUserIDs, ","))
  146. validUserIDs = make([]int64, 0, len(userIDs))
  147. for _, userID := range userIDs {
  148. if !Handle.Permissions().Authorize(context.TODO(), userID, repo.ID, AccessModeWrite,
  149. AccessModeOptions{
  150. OwnerID: repo.OwnerID,
  151. Private: repo.IsPrivate,
  152. },
  153. ) {
  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, AccessModeWrite)
  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 repository.
  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. }