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

branches.go 16 kB

Better logging (#6038) (#6095) * Panic don't fatal on create new logger Fixes #5854 Signed-off-by: Andrew Thornton <art27@cantab.net> * partial broken * Update the logging infrastrcture Signed-off-by: Andrew Thornton <art27@cantab.net> * Reset the skip levels for Fatal and Error Signed-off-by: Andrew Thornton <art27@cantab.net> * broken ncsa * More log.Error fixes Signed-off-by: Andrew Thornton <art27@cantab.net> * Remove nal * set log-levels to lowercase * Make console_test test all levels * switch to lowercased levels * OK now working * Fix vetting issues * Fix lint * Fix tests * change default logging to match current gitea * Improve log testing Signed-off-by: Andrew Thornton <art27@cantab.net> * reset error skip levels to 0 * Update documentation and access logger configuration * Redirect the router log back to gitea if redirect macaron log but also allow setting the log level - i.e. TRACE * Fix broken level caching * Refactor the router log * Add Router logger * Add colorizing options * Adjust router colors * Only create logger if they will be used * update app.ini.sample * rename Attribute ColorAttribute * Change from white to green for function * Set fatal/error levels * Restore initial trace logger * Fix Trace arguments in modules/auth/auth.go * Properly handle XORMLogger * Improve admin/config page * fix fmt * Add auto-compression of old logs * Update error log levels * Remove the unnecessary skip argument from Error, Fatal and Critical * Add stacktrace support * Fix tests * Remove x/sync from vendors? * Add stderr option to console logger * Use filepath.ToSlash to protect against Windows in tests * Remove prefixed underscores from names in colors.go * Remove not implemented database logger This was removed from Gogs on 4 Mar 2016 but left in the configuration since then. * Ensure that log paths are relative to ROOT_PATH * use path.Join * rename jsonConfig to logConfig * Rename "config" to "jsonConfig" to make it clearer * Requested changes * Requested changes: XormLogger * Try to color the windows terminal If successful default to colorizing the console logs * fixup * Colorize initially too * update vendor * Colorize logs on default and remove if this is not a colorizing logger * Fix documentation * fix test * Use go-isatty to detect if on windows we are on msys or cygwin * Fix spelling mistake * Add missing vendors * More changes * Rationalise the ANSI writer protection * Adjust colors on advice from @0x5c * Make Flags a comma separated list * Move to use the windows constant for ENABLE_VIRTUAL_TERMINAL_PROCESSING * Ensure matching is done on the non-colored message - to simpify EXPRESSION
6 years ago
Better logging (#6038) (#6095) * Panic don't fatal on create new logger Fixes #5854 Signed-off-by: Andrew Thornton <art27@cantab.net> * partial broken * Update the logging infrastrcture Signed-off-by: Andrew Thornton <art27@cantab.net> * Reset the skip levels for Fatal and Error Signed-off-by: Andrew Thornton <art27@cantab.net> * broken ncsa * More log.Error fixes Signed-off-by: Andrew Thornton <art27@cantab.net> * Remove nal * set log-levels to lowercase * Make console_test test all levels * switch to lowercased levels * OK now working * Fix vetting issues * Fix lint * Fix tests * change default logging to match current gitea * Improve log testing Signed-off-by: Andrew Thornton <art27@cantab.net> * reset error skip levels to 0 * Update documentation and access logger configuration * Redirect the router log back to gitea if redirect macaron log but also allow setting the log level - i.e. TRACE * Fix broken level caching * Refactor the router log * Add Router logger * Add colorizing options * Adjust router colors * Only create logger if they will be used * update app.ini.sample * rename Attribute ColorAttribute * Change from white to green for function * Set fatal/error levels * Restore initial trace logger * Fix Trace arguments in modules/auth/auth.go * Properly handle XORMLogger * Improve admin/config page * fix fmt * Add auto-compression of old logs * Update error log levels * Remove the unnecessary skip argument from Error, Fatal and Critical * Add stacktrace support * Fix tests * Remove x/sync from vendors? * Add stderr option to console logger * Use filepath.ToSlash to protect against Windows in tests * Remove prefixed underscores from names in colors.go * Remove not implemented database logger This was removed from Gogs on 4 Mar 2016 but left in the configuration since then. * Ensure that log paths are relative to ROOT_PATH * use path.Join * rename jsonConfig to logConfig * Rename "config" to "jsonConfig" to make it clearer * Requested changes * Requested changes: XormLogger * Try to color the windows terminal If successful default to colorizing the console logs * fixup * Colorize initially too * update vendor * Colorize logs on default and remove if this is not a colorizing logger * Fix documentation * fix test * Use go-isatty to detect if on windows we are on msys or cygwin * Fix spelling mistake * Add missing vendors * More changes * Rationalise the ANSI writer protection * Adjust colors on advice from @0x5c * Make Flags a comma separated list * Move to use the windows constant for ENABLE_VIRTUAL_TERMINAL_PROCESSING * Ensure matching is done on the non-colored message - to simpify EXPRESSION
6 years ago
Better logging (#6038) (#6095) * Panic don't fatal on create new logger Fixes #5854 Signed-off-by: Andrew Thornton <art27@cantab.net> * partial broken * Update the logging infrastrcture Signed-off-by: Andrew Thornton <art27@cantab.net> * Reset the skip levels for Fatal and Error Signed-off-by: Andrew Thornton <art27@cantab.net> * broken ncsa * More log.Error fixes Signed-off-by: Andrew Thornton <art27@cantab.net> * Remove nal * set log-levels to lowercase * Make console_test test all levels * switch to lowercased levels * OK now working * Fix vetting issues * Fix lint * Fix tests * change default logging to match current gitea * Improve log testing Signed-off-by: Andrew Thornton <art27@cantab.net> * reset error skip levels to 0 * Update documentation and access logger configuration * Redirect the router log back to gitea if redirect macaron log but also allow setting the log level - i.e. TRACE * Fix broken level caching * Refactor the router log * Add Router logger * Add colorizing options * Adjust router colors * Only create logger if they will be used * update app.ini.sample * rename Attribute ColorAttribute * Change from white to green for function * Set fatal/error levels * Restore initial trace logger * Fix Trace arguments in modules/auth/auth.go * Properly handle XORMLogger * Improve admin/config page * fix fmt * Add auto-compression of old logs * Update error log levels * Remove the unnecessary skip argument from Error, Fatal and Critical * Add stacktrace support * Fix tests * Remove x/sync from vendors? * Add stderr option to console logger * Use filepath.ToSlash to protect against Windows in tests * Remove prefixed underscores from names in colors.go * Remove not implemented database logger This was removed from Gogs on 4 Mar 2016 but left in the configuration since then. * Ensure that log paths are relative to ROOT_PATH * use path.Join * rename jsonConfig to logConfig * Rename "config" to "jsonConfig" to make it clearer * Requested changes * Requested changes: XormLogger * Try to color the windows terminal If successful default to colorizing the console logs * fixup * Colorize initially too * update vendor * Colorize logs on default and remove if this is not a colorizing logger * Fix documentation * fix test * Use go-isatty to detect if on windows we are on msys or cygwin * Fix spelling mistake * Add missing vendors * More changes * Rationalise the ANSI writer protection * Adjust colors on advice from @0x5c * Make Flags a comma separated list * Move to use the windows constant for ENABLE_VIRTUAL_TERMINAL_PROCESSING * Ensure matching is done on the non-colored message - to simpify EXPRESSION
6 years ago
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546
  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. "context"
  7. "fmt"
  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/timeutil"
  13. "code.gitea.io/gitea/modules/util"
  14. "github.com/unknwon/com"
  15. )
  16. const (
  17. // ProtectedBranchRepoID protected Repo ID
  18. ProtectedBranchRepoID = "GITEA_REPO_ID"
  19. // ProtectedBranchPRID protected Repo PR ID
  20. ProtectedBranchPRID = "GITEA_PR_ID"
  21. )
  22. // ProtectedBranch struct
  23. type ProtectedBranch struct {
  24. ID int64 `xorm:"pk autoincr"`
  25. RepoID int64 `xorm:"UNIQUE(s)"`
  26. BranchName string `xorm:"UNIQUE(s)"`
  27. CanPush bool `xorm:"NOT NULL DEFAULT false"`
  28. EnableWhitelist bool
  29. WhitelistUserIDs []int64 `xorm:"JSON TEXT"`
  30. WhitelistTeamIDs []int64 `xorm:"JSON TEXT"`
  31. EnableMergeWhitelist bool `xorm:"NOT NULL DEFAULT false"`
  32. WhitelistDeployKeys bool `xorm:"NOT NULL DEFAULT false"`
  33. MergeWhitelistUserIDs []int64 `xorm:"JSON TEXT"`
  34. MergeWhitelistTeamIDs []int64 `xorm:"JSON TEXT"`
  35. EnableStatusCheck bool `xorm:"NOT NULL DEFAULT false"`
  36. StatusCheckContexts []string `xorm:"JSON TEXT"`
  37. EnableApprovalsWhitelist bool `xorm:"NOT NULL DEFAULT false"`
  38. ApprovalsWhitelistUserIDs []int64 `xorm:"JSON TEXT"`
  39. ApprovalsWhitelistTeamIDs []int64 `xorm:"JSON TEXT"`
  40. RequiredApprovals int64 `xorm:"NOT NULL DEFAULT 0"`
  41. BlockOnRejectedReviews bool `xorm:"NOT NULL DEFAULT false"`
  42. DismissStaleApprovals bool `xorm:"NOT NULL DEFAULT false"`
  43. CreatedUnix timeutil.TimeStamp `xorm:"created"`
  44. UpdatedUnix timeutil.TimeStamp `xorm:"updated"`
  45. }
  46. // IsProtected returns if the branch is protected
  47. func (protectBranch *ProtectedBranch) IsProtected() bool {
  48. return protectBranch.ID > 0
  49. }
  50. // CanUserPush returns if some user could push to this protected branch
  51. func (protectBranch *ProtectedBranch) CanUserPush(userID int64) bool {
  52. if !protectBranch.CanPush {
  53. return false
  54. }
  55. if !protectBranch.EnableWhitelist {
  56. if user, err := GetUserByID(userID); err != nil {
  57. log.Error("GetUserByID: %v", err)
  58. return false
  59. } else if repo, err := GetRepositoryByID(protectBranch.RepoID); err != nil {
  60. log.Error("GetRepositoryByID: %v", err)
  61. return false
  62. } else if writeAccess, err := HasAccessUnit(user, repo, UnitTypeCode, AccessModeWrite); err != nil {
  63. log.Error("HasAccessUnit: %v", err)
  64. return false
  65. } else {
  66. return writeAccess
  67. }
  68. }
  69. if base.Int64sContains(protectBranch.WhitelistUserIDs, userID) {
  70. return true
  71. }
  72. if len(protectBranch.WhitelistTeamIDs) == 0 {
  73. return false
  74. }
  75. in, err := IsUserInTeams(userID, protectBranch.WhitelistTeamIDs)
  76. if err != nil {
  77. log.Error("IsUserInTeams: %v", err)
  78. return false
  79. }
  80. return in
  81. }
  82. // IsUserMergeWhitelisted checks if some user is whitelisted to merge to this branch
  83. func (protectBranch *ProtectedBranch) IsUserMergeWhitelisted(userID int64) bool {
  84. if !protectBranch.EnableMergeWhitelist {
  85. return true
  86. }
  87. if base.Int64sContains(protectBranch.MergeWhitelistUserIDs, userID) {
  88. return true
  89. }
  90. if len(protectBranch.MergeWhitelistTeamIDs) == 0 {
  91. return false
  92. }
  93. in, err := IsUserInTeams(userID, protectBranch.MergeWhitelistTeamIDs)
  94. if err != nil {
  95. log.Error("IsUserInTeams: %v", err)
  96. return false
  97. }
  98. return in
  99. }
  100. // IsUserOfficialReviewer check if user is official reviewer for the branch (counts towards required approvals)
  101. func (protectBranch *ProtectedBranch) IsUserOfficialReviewer(user *User) (bool, error) {
  102. return protectBranch.isUserOfficialReviewer(x, user)
  103. }
  104. func (protectBranch *ProtectedBranch) isUserOfficialReviewer(e Engine, user *User) (bool, error) {
  105. repo, err := getRepositoryByID(e, protectBranch.RepoID)
  106. if err != nil {
  107. return false, err
  108. }
  109. if !protectBranch.EnableApprovalsWhitelist {
  110. // Anyone with write access is considered official reviewer
  111. writeAccess, err := hasAccessUnit(e, user, repo, UnitTypeCode, AccessModeWrite)
  112. if err != nil {
  113. return false, err
  114. }
  115. return writeAccess, nil
  116. }
  117. if base.Int64sContains(protectBranch.ApprovalsWhitelistUserIDs, user.ID) {
  118. return true, nil
  119. }
  120. inTeam, err := isUserInTeams(e, user.ID, protectBranch.ApprovalsWhitelistTeamIDs)
  121. if err != nil {
  122. return false, err
  123. }
  124. return inTeam, nil
  125. }
  126. // HasEnoughApprovals returns true if pr has enough granted approvals.
  127. func (protectBranch *ProtectedBranch) HasEnoughApprovals(pr *PullRequest) bool {
  128. if protectBranch.RequiredApprovals == 0 {
  129. return true
  130. }
  131. return protectBranch.GetGrantedApprovalsCount(pr) >= protectBranch.RequiredApprovals
  132. }
  133. // GetGrantedApprovalsCount returns the number of granted approvals for pr. A granted approval must be authored by a user in an approval whitelist.
  134. func (protectBranch *ProtectedBranch) GetGrantedApprovalsCount(pr *PullRequest) int64 {
  135. sess := x.Where("issue_id = ?", pr.IssueID).
  136. And("type = ?", ReviewTypeApprove).
  137. And("official = ?", true)
  138. if protectBranch.DismissStaleApprovals {
  139. sess = sess.And("stale = ?", false)
  140. }
  141. approvals, err := sess.Count(new(Review))
  142. if err != nil {
  143. log.Error("GetGrantedApprovalsCount: %v", err)
  144. return 0
  145. }
  146. return approvals
  147. }
  148. // MergeBlockedByRejectedReview returns true if merge is blocked by rejected reviews
  149. func (protectBranch *ProtectedBranch) MergeBlockedByRejectedReview(pr *PullRequest) bool {
  150. if !protectBranch.BlockOnRejectedReviews {
  151. return false
  152. }
  153. rejectExist, err := x.Where("issue_id = ?", pr.IssueID).
  154. And("type = ?", ReviewTypeReject).
  155. And("official = ?", true).
  156. Exist(new(Review))
  157. if err != nil {
  158. log.Error("MergeBlockedByRejectedReview: %v", err)
  159. return true
  160. }
  161. return rejectExist
  162. }
  163. // GetProtectedBranchByRepoID getting protected branch by repo ID
  164. func GetProtectedBranchByRepoID(repoID int64) ([]*ProtectedBranch, error) {
  165. protectedBranches := make([]*ProtectedBranch, 0)
  166. return protectedBranches, x.Where("repo_id = ?", repoID).Desc("updated_unix").Find(&protectedBranches)
  167. }
  168. // GetProtectedBranchBy getting protected branch by ID/Name
  169. func GetProtectedBranchBy(repoID int64, branchName string) (*ProtectedBranch, error) {
  170. return getProtectedBranchBy(x, repoID, branchName)
  171. }
  172. func getProtectedBranchBy(e Engine, repoID int64, branchName string) (*ProtectedBranch, error) {
  173. rel := &ProtectedBranch{RepoID: repoID, BranchName: branchName}
  174. has, err := e.Get(rel)
  175. if err != nil {
  176. return nil, err
  177. }
  178. if !has {
  179. return nil, nil
  180. }
  181. return rel, nil
  182. }
  183. // GetProtectedBranchByID getting protected branch by ID
  184. func GetProtectedBranchByID(id int64) (*ProtectedBranch, error) {
  185. rel := &ProtectedBranch{ID: id}
  186. has, err := x.Get(rel)
  187. if err != nil {
  188. return nil, err
  189. }
  190. if !has {
  191. return nil, nil
  192. }
  193. return rel, nil
  194. }
  195. // WhitelistOptions represent all sorts of whitelists used for protected branches
  196. type WhitelistOptions struct {
  197. UserIDs []int64
  198. TeamIDs []int64
  199. MergeUserIDs []int64
  200. MergeTeamIDs []int64
  201. ApprovalsUserIDs []int64
  202. ApprovalsTeamIDs []int64
  203. }
  204. // UpdateProtectBranch saves branch protection options of repository.
  205. // If ID is 0, it creates a new record. Otherwise, updates existing record.
  206. // This function also performs check if whitelist user and team's IDs have been changed
  207. // to avoid unnecessary whitelist delete and regenerate.
  208. func UpdateProtectBranch(repo *Repository, protectBranch *ProtectedBranch, opts WhitelistOptions) (err error) {
  209. if err = repo.GetOwner(); err != nil {
  210. return fmt.Errorf("GetOwner: %v", err)
  211. }
  212. whitelist, err := updateUserWhitelist(repo, protectBranch.WhitelistUserIDs, opts.UserIDs)
  213. if err != nil {
  214. return err
  215. }
  216. protectBranch.WhitelistUserIDs = whitelist
  217. whitelist, err = updateUserWhitelist(repo, protectBranch.MergeWhitelistUserIDs, opts.MergeUserIDs)
  218. if err != nil {
  219. return err
  220. }
  221. protectBranch.MergeWhitelistUserIDs = whitelist
  222. whitelist, err = updateApprovalWhitelist(repo, protectBranch.ApprovalsWhitelistUserIDs, opts.ApprovalsUserIDs)
  223. if err != nil {
  224. return err
  225. }
  226. protectBranch.ApprovalsWhitelistUserIDs = whitelist
  227. // if the repo is in an organization
  228. whitelist, err = updateTeamWhitelist(repo, protectBranch.WhitelistTeamIDs, opts.TeamIDs)
  229. if err != nil {
  230. return err
  231. }
  232. protectBranch.WhitelistTeamIDs = whitelist
  233. whitelist, err = updateTeamWhitelist(repo, protectBranch.MergeWhitelistTeamIDs, opts.MergeTeamIDs)
  234. if err != nil {
  235. return err
  236. }
  237. protectBranch.MergeWhitelistTeamIDs = whitelist
  238. whitelist, err = updateTeamWhitelist(repo, protectBranch.ApprovalsWhitelistTeamIDs, opts.ApprovalsTeamIDs)
  239. if err != nil {
  240. return err
  241. }
  242. protectBranch.ApprovalsWhitelistTeamIDs = whitelist
  243. // Make sure protectBranch.ID is not 0 for whitelists
  244. if protectBranch.ID == 0 {
  245. if _, err = x.Insert(protectBranch); err != nil {
  246. return fmt.Errorf("Insert: %v", err)
  247. }
  248. return nil
  249. }
  250. if _, err = x.ID(protectBranch.ID).AllCols().Update(protectBranch); err != nil {
  251. return fmt.Errorf("Update: %v", err)
  252. }
  253. return nil
  254. }
  255. // GetProtectedBranches get all protected branches
  256. func (repo *Repository) GetProtectedBranches() ([]*ProtectedBranch, error) {
  257. protectedBranches := make([]*ProtectedBranch, 0)
  258. return protectedBranches, x.Find(&protectedBranches, &ProtectedBranch{RepoID: repo.ID})
  259. }
  260. // GetBranchProtection get the branch protection of a branch
  261. func (repo *Repository) GetBranchProtection(branchName string) (*ProtectedBranch, error) {
  262. return GetProtectedBranchBy(repo.ID, branchName)
  263. }
  264. // IsProtectedBranch checks if branch is protected
  265. func (repo *Repository) IsProtectedBranch(branchName string, doer *User) (bool, error) {
  266. if doer == nil {
  267. return true, nil
  268. }
  269. protectedBranch := &ProtectedBranch{
  270. RepoID: repo.ID,
  271. BranchName: branchName,
  272. }
  273. has, err := x.Exist(protectedBranch)
  274. if err != nil {
  275. return true, err
  276. }
  277. return has, nil
  278. }
  279. // IsProtectedBranchForPush checks if branch is protected for push
  280. func (repo *Repository) IsProtectedBranchForPush(branchName string, doer *User) (bool, error) {
  281. if doer == nil {
  282. return true, nil
  283. }
  284. protectedBranch := &ProtectedBranch{
  285. RepoID: repo.ID,
  286. BranchName: branchName,
  287. }
  288. has, err := x.Get(protectedBranch)
  289. if err != nil {
  290. return true, err
  291. } else if has {
  292. return !protectedBranch.CanUserPush(doer.ID), nil
  293. }
  294. return false, nil
  295. }
  296. // updateApprovalWhitelist checks whether the user whitelist changed and returns a whitelist with
  297. // the users from newWhitelist which have explicit read or write access to the repo.
  298. func updateApprovalWhitelist(repo *Repository, currentWhitelist, newWhitelist []int64) (whitelist []int64, err error) {
  299. hasUsersChanged := !util.IsSliceInt64Eq(currentWhitelist, newWhitelist)
  300. if !hasUsersChanged {
  301. return currentWhitelist, nil
  302. }
  303. whitelist = make([]int64, 0, len(newWhitelist))
  304. for _, userID := range newWhitelist {
  305. if reader, err := repo.IsReader(userID); err != nil {
  306. return nil, err
  307. } else if !reader {
  308. continue
  309. }
  310. whitelist = append(whitelist, userID)
  311. }
  312. return
  313. }
  314. // updateUserWhitelist checks whether the user whitelist changed and returns a whitelist with
  315. // the users from newWhitelist which have write access to the repo.
  316. func updateUserWhitelist(repo *Repository, currentWhitelist, newWhitelist []int64) (whitelist []int64, err error) {
  317. hasUsersChanged := !util.IsSliceInt64Eq(currentWhitelist, newWhitelist)
  318. if !hasUsersChanged {
  319. return currentWhitelist, nil
  320. }
  321. whitelist = make([]int64, 0, len(newWhitelist))
  322. for _, userID := range newWhitelist {
  323. user, err := GetUserByID(userID)
  324. if err != nil {
  325. return nil, fmt.Errorf("GetUserByID [user_id: %d, repo_id: %d]: %v", userID, repo.ID, err)
  326. }
  327. perm, err := GetUserRepoPermission(repo, user)
  328. if err != nil {
  329. return nil, fmt.Errorf("GetUserRepoPermission [user_id: %d, repo_id: %d]: %v", userID, repo.ID, err)
  330. }
  331. if !perm.CanWrite(UnitTypeCode) {
  332. continue // Drop invalid user ID
  333. }
  334. whitelist = append(whitelist, userID)
  335. }
  336. return
  337. }
  338. // updateTeamWhitelist checks whether the team whitelist changed and returns a whitelist with
  339. // the teams from newWhitelist which have write access to the repo.
  340. func updateTeamWhitelist(repo *Repository, currentWhitelist, newWhitelist []int64) (whitelist []int64, err error) {
  341. hasTeamsChanged := !util.IsSliceInt64Eq(currentWhitelist, newWhitelist)
  342. if !hasTeamsChanged {
  343. return currentWhitelist, nil
  344. }
  345. teams, err := GetTeamsWithAccessToRepo(repo.OwnerID, repo.ID, AccessModeRead)
  346. if err != nil {
  347. return nil, fmt.Errorf("GetTeamsWithAccessToRepo [org_id: %d, repo_id: %d]: %v", repo.OwnerID, repo.ID, err)
  348. }
  349. whitelist = make([]int64, 0, len(teams))
  350. for i := range teams {
  351. if com.IsSliceContainsInt64(newWhitelist, teams[i].ID) {
  352. whitelist = append(whitelist, teams[i].ID)
  353. }
  354. }
  355. return
  356. }
  357. // DeleteProtectedBranch removes ProtectedBranch relation between the user and repository.
  358. func (repo *Repository) DeleteProtectedBranch(id int64) (err error) {
  359. protectedBranch := &ProtectedBranch{
  360. RepoID: repo.ID,
  361. ID: id,
  362. }
  363. sess := x.NewSession()
  364. defer sess.Close()
  365. if err = sess.Begin(); err != nil {
  366. return err
  367. }
  368. if affected, err := sess.Delete(protectedBranch); err != nil {
  369. return err
  370. } else if affected != 1 {
  371. return fmt.Errorf("delete protected branch ID(%v) failed", id)
  372. }
  373. return sess.Commit()
  374. }
  375. // DeletedBranch struct
  376. type DeletedBranch struct {
  377. ID int64 `xorm:"pk autoincr"`
  378. RepoID int64 `xorm:"UNIQUE(s) INDEX NOT NULL"`
  379. Name string `xorm:"UNIQUE(s) NOT NULL"`
  380. Commit string `xorm:"UNIQUE(s) NOT NULL"`
  381. DeletedByID int64 `xorm:"INDEX"`
  382. DeletedBy *User `xorm:"-"`
  383. DeletedUnix timeutil.TimeStamp `xorm:"INDEX created"`
  384. }
  385. // AddDeletedBranch adds a deleted branch to the database
  386. func (repo *Repository) AddDeletedBranch(branchName, commit string, deletedByID int64) error {
  387. deletedBranch := &DeletedBranch{
  388. RepoID: repo.ID,
  389. Name: branchName,
  390. Commit: commit,
  391. DeletedByID: deletedByID,
  392. }
  393. sess := x.NewSession()
  394. defer sess.Close()
  395. if err := sess.Begin(); err != nil {
  396. return err
  397. }
  398. if _, err := sess.InsertOne(deletedBranch); err != nil {
  399. return err
  400. }
  401. return sess.Commit()
  402. }
  403. // GetDeletedBranches returns all the deleted branches
  404. func (repo *Repository) GetDeletedBranches() ([]*DeletedBranch, error) {
  405. deletedBranches := make([]*DeletedBranch, 0)
  406. return deletedBranches, x.Where("repo_id = ?", repo.ID).Desc("deleted_unix").Find(&deletedBranches)
  407. }
  408. // GetDeletedBranchByID get a deleted branch by its ID
  409. func (repo *Repository) GetDeletedBranchByID(ID int64) (*DeletedBranch, error) {
  410. deletedBranch := &DeletedBranch{ID: ID}
  411. has, err := x.Get(deletedBranch)
  412. if err != nil {
  413. return nil, err
  414. }
  415. if !has {
  416. return nil, nil
  417. }
  418. return deletedBranch, nil
  419. }
  420. // RemoveDeletedBranch removes a deleted branch from the database
  421. func (repo *Repository) RemoveDeletedBranch(id int64) (err error) {
  422. deletedBranch := &DeletedBranch{
  423. RepoID: repo.ID,
  424. ID: id,
  425. }
  426. sess := x.NewSession()
  427. defer sess.Close()
  428. if err = sess.Begin(); err != nil {
  429. return err
  430. }
  431. if affected, err := sess.Delete(deletedBranch); err != nil {
  432. return err
  433. } else if affected != 1 {
  434. return fmt.Errorf("remove deleted branch ID(%v) failed", id)
  435. }
  436. return sess.Commit()
  437. }
  438. // LoadUser loads the user that deleted the branch
  439. // When there's no user found it returns a NewGhostUser
  440. func (deletedBranch *DeletedBranch) LoadUser() {
  441. user, err := GetUserByID(deletedBranch.DeletedByID)
  442. if err != nil {
  443. user = NewGhostUser()
  444. }
  445. deletedBranch.DeletedBy = user
  446. }
  447. // RemoveDeletedBranch removes all deleted branches
  448. func RemoveDeletedBranch(repoID int64, branch string) error {
  449. _, err := x.Where("repo_id=? AND name=?", repoID, branch).Delete(new(DeletedBranch))
  450. return err
  451. }
  452. // RemoveOldDeletedBranches removes old deleted branches
  453. func RemoveOldDeletedBranches(ctx context.Context) {
  454. // Nothing to do for shutdown or terminate
  455. log.Trace("Doing: DeletedBranchesCleanup")
  456. deleteBefore := time.Now().Add(-setting.Cron.DeletedBranchesCleanup.OlderThan)
  457. _, err := x.Where("deleted_unix < ?", deleteBefore.Unix()).Delete(new(DeletedBranch))
  458. if err != nil {
  459. log.Error("DeletedBranchesCleanup: %v", err)
  460. }
  461. }