repo_branch.go 8.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273
  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. "gorm.io/gorm"
  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, errors.Newf("open repository: %v", err)
  23. }
  24. names, err := gitRepo.Branches()
  25. if err != nil {
  26. return nil, errors.Newf("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]any
  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 (r *Repository) GetBranch(name string) (*Branch, error) {
  52. if !git.RepoHasBranch(r.RepoPath(), name) {
  53. return nil, ErrBranchNotExist{args: map[string]any{"name": name}}
  54. }
  55. return &Branch{
  56. RepoPath: r.RepoPath(),
  57. Name: name,
  58. }, nil
  59. }
  60. func (r *Repository) GetBranches() ([]*Branch, error) {
  61. return GetBranchesByPath(r.RepoPath())
  62. }
  63. func (br *Branch) GetCommit() (*git.Commit, error) {
  64. gitRepo, err := git.Open(br.RepoPath)
  65. if err != nil {
  66. return nil, errors.Newf("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. var whitelist ProtectBranchWhitelist
  80. err := db.Where("repo_id = ?", repoID).Where("user_id = ?", userID).Where("name = ?", branch).First(&whitelist).Error
  81. return 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. err := db.Where("repo_id = ? AND name = ?", repoID, name).First(protectBranch).Error
  101. if errors.Is(err, gorm.ErrRecordNotFound) {
  102. return nil, ErrBranchNotExist{args: map[string]any{"name": name}}
  103. } else if err != nil {
  104. return nil, err
  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. return db.Transaction(func(tx *gorm.DB) error {
  120. if protectBranch.ID == 0 {
  121. if err := tx.Create(protectBranch).Error; err != nil {
  122. return errors.Newf("insert: %v", err)
  123. }
  124. }
  125. if err := tx.Model(&ProtectBranch{}).Where("id = ?", protectBranch.ID).Updates(protectBranch).Error; err != nil {
  126. return errors.Newf("update: %v", err)
  127. }
  128. return nil
  129. })
  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 errors.Newf("GetOwner: %v", err)
  138. } else if !repo.Owner.IsOrganization() {
  139. return errors.Newf("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 errors.Newf("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 = db.Create(protectBranch).Error; err != nil {
  180. return errors.Newf("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 errors.Newf("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. return db.Transaction(func(tx *gorm.DB) error {
  213. if err := tx.Model(&ProtectBranch{}).Where("id = ?", protectBranch.ID).Updates(protectBranch).Error; err != nil {
  214. return errors.Newf("Update: %v", err)
  215. }
  216. // Refresh whitelists
  217. if hasUsersChanged || hasTeamsChanged {
  218. if err := tx.Delete(&ProtectBranchWhitelist{}, "protect_branch_id = ?", protectBranch.ID).Error; err != nil {
  219. return errors.Newf("delete old protect branch whitelists: %v", err)
  220. }
  221. if len(whitelists) > 0 {
  222. if err := tx.Create(&whitelists).Error; err != nil {
  223. return errors.Newf("insert new protect branch whitelists: %v", err)
  224. }
  225. }
  226. }
  227. return nil
  228. })
  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, db.Where("repo_id = ? AND protected = ?", repoID, true).Order("name ASC").Find(&protectBranches).Error
  234. }