Fork to maintain patches against the official gitea for https://code.ceondo.com https://github.com/go-gitea/gitea

branches.go 8.6KB

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