You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

branches.go 8.4KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294
  1. // Copyright 2016 The Gitea 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 models
  5. import (
  6. "fmt"
  7. "strings"
  8. "time"
  9. "code.gitea.io/gitea/modules/base"
  10. "code.gitea.io/gitea/modules/log"
  11. "code.gitea.io/gitea/modules/setting"
  12. "code.gitea.io/gitea/modules/util"
  13. "github.com/Unknwon/com"
  14. )
  15. const (
  16. // ProtectedBranchRepoID protected Repo ID
  17. ProtectedBranchRepoID = "GITEA_REPO_ID"
  18. )
  19. // ProtectedBranch struct
  20. type ProtectedBranch struct {
  21. ID int64 `xorm:"pk autoincr"`
  22. RepoID int64 `xorm:"UNIQUE(s)"`
  23. BranchName string `xorm:"UNIQUE(s)"`
  24. CanPush bool `xorm:"NOT NULL DEFAULT false"`
  25. EnableWhitelist bool
  26. WhitelistUserIDs []int64 `xorm:"JSON TEXT"`
  27. WhitelistTeamIDs []int64 `xorm:"JSON TEXT"`
  28. CreatedUnix util.TimeStamp `xorm:"created"`
  29. UpdatedUnix util.TimeStamp `xorm:"updated"`
  30. }
  31. // IsProtected returns if the branch is protected
  32. func (protectBranch *ProtectedBranch) IsProtected() bool {
  33. return protectBranch.ID > 0
  34. }
  35. // CanUserPush returns if some user could push to this protected branch
  36. func (protectBranch *ProtectedBranch) CanUserPush(userID int64) bool {
  37. if !protectBranch.EnableWhitelist {
  38. return false
  39. }
  40. if base.Int64sContains(protectBranch.WhitelistUserIDs, userID) {
  41. return true
  42. }
  43. if len(protectBranch.WhitelistTeamIDs) == 0 {
  44. return false
  45. }
  46. in, err := IsUserInTeams(userID, protectBranch.WhitelistTeamIDs)
  47. if err != nil {
  48. log.Error(1, "IsUserInTeams:", err)
  49. return false
  50. }
  51. return in
  52. }
  53. // GetProtectedBranchByRepoID getting protected branch by repo ID
  54. func GetProtectedBranchByRepoID(RepoID int64) ([]*ProtectedBranch, error) {
  55. protectedBranches := make([]*ProtectedBranch, 0)
  56. return protectedBranches, x.Where("repo_id = ?", RepoID).Desc("updated_unix").Find(&protectedBranches)
  57. }
  58. // GetProtectedBranchBy getting protected branch by ID/Name
  59. func GetProtectedBranchBy(repoID int64, BranchName string) (*ProtectedBranch, error) {
  60. rel := &ProtectedBranch{RepoID: repoID, BranchName: strings.ToLower(BranchName)}
  61. has, err := x.Get(rel)
  62. if err != nil {
  63. return nil, err
  64. }
  65. if !has {
  66. return nil, nil
  67. }
  68. return rel, nil
  69. }
  70. // GetProtectedBranchByID getting protected branch by ID
  71. func GetProtectedBranchByID(id int64) (*ProtectedBranch, error) {
  72. rel := &ProtectedBranch{ID: id}
  73. has, err := x.Get(rel)
  74. if err != nil {
  75. return nil, err
  76. }
  77. if !has {
  78. return nil, nil
  79. }
  80. return rel, nil
  81. }
  82. // UpdateProtectBranch saves branch protection options of repository.
  83. // If ID is 0, it creates a new record. Otherwise, updates existing record.
  84. // This function also performs check if whitelist user and team's IDs have been changed
  85. // to avoid unnecessary whitelist delete and regenerate.
  86. func UpdateProtectBranch(repo *Repository, protectBranch *ProtectedBranch, whitelistUserIDs, whitelistTeamIDs []int64) (err error) {
  87. if err = repo.GetOwner(); err != nil {
  88. return fmt.Errorf("GetOwner: %v", err)
  89. }
  90. hasUsersChanged := !util.IsSliceInt64Eq(protectBranch.WhitelistUserIDs, whitelistUserIDs)
  91. if hasUsersChanged {
  92. protectBranch.WhitelistUserIDs = make([]int64, 0, len(whitelistUserIDs))
  93. for _, userID := range whitelistUserIDs {
  94. has, err := hasAccess(x, userID, repo, AccessModeWrite)
  95. if err != nil {
  96. return fmt.Errorf("HasAccess [user_id: %d, repo_id: %d]: %v", userID, protectBranch.RepoID, err)
  97. } else if !has {
  98. continue // Drop invalid user ID
  99. }
  100. protectBranch.WhitelistUserIDs = append(protectBranch.WhitelistUserIDs, userID)
  101. }
  102. }
  103. // if the repo is in an orgniziation
  104. hasTeamsChanged := !util.IsSliceInt64Eq(protectBranch.WhitelistTeamIDs, whitelistTeamIDs)
  105. if hasTeamsChanged {
  106. teams, err := GetTeamsWithAccessToRepo(repo.OwnerID, repo.ID, AccessModeWrite)
  107. if err != nil {
  108. return fmt.Errorf("GetTeamsWithAccessToRepo [org_id: %d, repo_id: %d]: %v", repo.OwnerID, repo.ID, err)
  109. }
  110. protectBranch.WhitelistTeamIDs = make([]int64, 0, len(teams))
  111. for i := range teams {
  112. if teams[i].HasWriteAccess() && com.IsSliceContainsInt64(whitelistTeamIDs, teams[i].ID) {
  113. protectBranch.WhitelistTeamIDs = append(protectBranch.WhitelistTeamIDs, teams[i].ID)
  114. }
  115. }
  116. }
  117. // Make sure protectBranch.ID is not 0 for whitelists
  118. if protectBranch.ID == 0 {
  119. if _, err = x.Insert(protectBranch); err != nil {
  120. return fmt.Errorf("Insert: %v", err)
  121. }
  122. return nil
  123. }
  124. if _, err = x.ID(protectBranch.ID).AllCols().Update(protectBranch); err != nil {
  125. return fmt.Errorf("Update: %v", err)
  126. }
  127. return nil
  128. }
  129. // GetProtectedBranches get all protected branches
  130. func (repo *Repository) GetProtectedBranches() ([]*ProtectedBranch, error) {
  131. protectedBranches := make([]*ProtectedBranch, 0)
  132. return protectedBranches, x.Find(&protectedBranches, &ProtectedBranch{RepoID: repo.ID})
  133. }
  134. // IsProtectedBranch checks if branch is protected
  135. func (repo *Repository) IsProtectedBranch(branchName string, doer *User) (bool, error) {
  136. protectedBranch := &ProtectedBranch{
  137. RepoID: repo.ID,
  138. BranchName: branchName,
  139. }
  140. has, err := x.Get(protectedBranch)
  141. if err != nil {
  142. return true, err
  143. } else if has {
  144. return !protectedBranch.CanUserPush(doer.ID), nil
  145. }
  146. return false, nil
  147. }
  148. // DeleteProtectedBranch removes ProtectedBranch relation between the user and repository.
  149. func (repo *Repository) DeleteProtectedBranch(id int64) (err error) {
  150. protectedBranch := &ProtectedBranch{
  151. RepoID: repo.ID,
  152. ID: id,
  153. }
  154. sess := x.NewSession()
  155. defer sess.Close()
  156. if err = sess.Begin(); err != nil {
  157. return err
  158. }
  159. if affected, err := sess.Delete(protectedBranch); err != nil {
  160. return err
  161. } else if affected != 1 {
  162. return fmt.Errorf("delete protected branch ID(%v) failed", id)
  163. }
  164. return sess.Commit()
  165. }
  166. // DeletedBranch struct
  167. type DeletedBranch struct {
  168. ID int64 `xorm:"pk autoincr"`
  169. RepoID int64 `xorm:"UNIQUE(s) INDEX NOT NULL"`
  170. Name string `xorm:"UNIQUE(s) NOT NULL"`
  171. Commit string `xorm:"UNIQUE(s) NOT NULL"`
  172. DeletedByID int64 `xorm:"INDEX"`
  173. DeletedBy *User `xorm:"-"`
  174. DeletedUnix util.TimeStamp `xorm:"INDEX created"`
  175. }
  176. // AddDeletedBranch adds a deleted branch to the database
  177. func (repo *Repository) AddDeletedBranch(branchName, commit string, deletedByID int64) error {
  178. deletedBranch := &DeletedBranch{
  179. RepoID: repo.ID,
  180. Name: branchName,
  181. Commit: commit,
  182. DeletedByID: deletedByID,
  183. }
  184. sess := x.NewSession()
  185. defer sess.Close()
  186. if err := sess.Begin(); err != nil {
  187. return err
  188. }
  189. if _, err := sess.InsertOne(deletedBranch); err != nil {
  190. return err
  191. }
  192. return sess.Commit()
  193. }
  194. // GetDeletedBranches returns all the deleted branches
  195. func (repo *Repository) GetDeletedBranches() ([]*DeletedBranch, error) {
  196. deletedBranches := make([]*DeletedBranch, 0)
  197. return deletedBranches, x.Where("repo_id = ?", repo.ID).Desc("deleted_unix").Find(&deletedBranches)
  198. }
  199. // GetDeletedBranchByID get a deleted branch by its ID
  200. func (repo *Repository) GetDeletedBranchByID(ID int64) (*DeletedBranch, error) {
  201. deletedBranch := &DeletedBranch{ID: ID}
  202. has, err := x.Get(deletedBranch)
  203. if err != nil {
  204. return nil, err
  205. }
  206. if !has {
  207. return nil, nil
  208. }
  209. return deletedBranch, nil
  210. }
  211. // RemoveDeletedBranch removes a deleted branch from the database
  212. func (repo *Repository) RemoveDeletedBranch(id int64) (err error) {
  213. deletedBranch := &DeletedBranch{
  214. RepoID: repo.ID,
  215. ID: id,
  216. }
  217. sess := x.NewSession()
  218. defer sess.Close()
  219. if err = sess.Begin(); err != nil {
  220. return err
  221. }
  222. if affected, err := sess.Delete(deletedBranch); err != nil {
  223. return err
  224. } else if affected != 1 {
  225. return fmt.Errorf("remove deleted branch ID(%v) failed", id)
  226. }
  227. return sess.Commit()
  228. }
  229. // LoadUser loads the user that deleted the branch
  230. // When there's no user found it returns a NewGhostUser
  231. func (deletedBranch *DeletedBranch) LoadUser() {
  232. user, err := GetUserByID(deletedBranch.DeletedByID)
  233. if err != nil {
  234. user = NewGhostUser()
  235. }
  236. deletedBranch.DeletedBy = user
  237. }
  238. // RemoveOldDeletedBranches removes old deleted branches
  239. func RemoveOldDeletedBranches() {
  240. if !taskStatusTable.StartIfNotRunning(`deleted_branches_cleanup`) {
  241. return
  242. }
  243. defer taskStatusTable.Stop(`deleted_branches_cleanup`)
  244. log.Trace("Doing: DeletedBranchesCleanup")
  245. deleteBefore := time.Now().Add(-setting.Cron.DeletedBranchesCleanup.OlderThan)
  246. _, err := x.Where("deleted_unix < ?", deleteBefore.Unix()).Delete(new(DeletedBranch))
  247. if err != nil {
  248. log.Error(4, "DeletedBranchesCleanup: %v", err)
  249. }
  250. }