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.3KB

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