repo_branch.go 8.1 KB

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