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
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538
  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. CreatedUnix timeutil.TimeStamp `xorm:"created"`
  42. UpdatedUnix timeutil.TimeStamp `xorm:"updated"`
  43. }
  44. // IsProtected returns if the branch is protected
  45. func (protectBranch *ProtectedBranch) IsProtected() bool {
  46. return protectBranch.ID > 0
  47. }
  48. // CanUserPush returns if some user could push to this protected branch
  49. func (protectBranch *ProtectedBranch) CanUserPush(userID int64) bool {
  50. if !protectBranch.CanPush {
  51. return false
  52. }
  53. if !protectBranch.EnableWhitelist {
  54. if user, err := GetUserByID(userID); err != nil {
  55. log.Error("GetUserByID: %v", err)
  56. return false
  57. } else if repo, err := GetRepositoryByID(protectBranch.RepoID); err != nil {
  58. log.Error("GetRepositoryByID: %v", err)
  59. return false
  60. } else if writeAccess, err := HasAccessUnit(user, repo, UnitTypeCode, AccessModeWrite); err != nil {
  61. log.Error("HasAccessUnit: %v", err)
  62. return false
  63. } else {
  64. return writeAccess
  65. }
  66. }
  67. if base.Int64sContains(protectBranch.WhitelistUserIDs, userID) {
  68. return true
  69. }
  70. if len(protectBranch.WhitelistTeamIDs) == 0 {
  71. return false
  72. }
  73. in, err := IsUserInTeams(userID, protectBranch.WhitelistTeamIDs)
  74. if err != nil {
  75. log.Error("IsUserInTeams: %v", err)
  76. return false
  77. }
  78. return in
  79. }
  80. // CanUserMerge returns if some user could merge a pull request to this protected branch
  81. func (protectBranch *ProtectedBranch) CanUserMerge(userID int64) bool {
  82. if !protectBranch.EnableMergeWhitelist {
  83. return true
  84. }
  85. if base.Int64sContains(protectBranch.MergeWhitelistUserIDs, userID) {
  86. return true
  87. }
  88. if len(protectBranch.MergeWhitelistTeamIDs) == 0 {
  89. return false
  90. }
  91. in, err := IsUserInTeams(userID, protectBranch.MergeWhitelistTeamIDs)
  92. if err != nil {
  93. log.Error("IsUserInTeams: %v", err)
  94. return false
  95. }
  96. return in
  97. }
  98. // IsUserOfficialReviewer check if user is official reviewer for the branch (counts towards required approvals)
  99. func (protectBranch *ProtectedBranch) IsUserOfficialReviewer(user *User) (bool, error) {
  100. return protectBranch.isUserOfficialReviewer(x, user)
  101. }
  102. func (protectBranch *ProtectedBranch) isUserOfficialReviewer(e Engine, user *User) (bool, error) {
  103. repo, err := getRepositoryByID(e, protectBranch.RepoID)
  104. if err != nil {
  105. return false, err
  106. }
  107. if !protectBranch.EnableApprovalsWhitelist {
  108. // Anyone with write access is considered official reviewer
  109. writeAccess, err := hasAccessUnit(e, user, repo, UnitTypeCode, AccessModeWrite)
  110. if err != nil {
  111. return false, err
  112. }
  113. return writeAccess, nil
  114. }
  115. if base.Int64sContains(protectBranch.ApprovalsWhitelistUserIDs, user.ID) {
  116. return true, nil
  117. }
  118. inTeam, err := isUserInTeams(e, user.ID, protectBranch.ApprovalsWhitelistTeamIDs)
  119. if err != nil {
  120. return false, err
  121. }
  122. return inTeam, nil
  123. }
  124. // HasEnoughApprovals returns true if pr has enough granted approvals.
  125. func (protectBranch *ProtectedBranch) HasEnoughApprovals(pr *PullRequest) bool {
  126. if protectBranch.RequiredApprovals == 0 {
  127. return true
  128. }
  129. return protectBranch.GetGrantedApprovalsCount(pr) >= protectBranch.RequiredApprovals
  130. }
  131. // GetGrantedApprovalsCount returns the number of granted approvals for pr. A granted approval must be authored by a user in an approval whitelist.
  132. func (protectBranch *ProtectedBranch) GetGrantedApprovalsCount(pr *PullRequest) int64 {
  133. approvals, err := x.Where("issue_id = ?", pr.IssueID).
  134. And("type = ?", ReviewTypeApprove).
  135. And("official = ?", true).
  136. Count(new(Review))
  137. if err != nil {
  138. log.Error("GetGrantedApprovalsCount: %v", err)
  139. return 0
  140. }
  141. return approvals
  142. }
  143. // GetProtectedBranchByRepoID getting protected branch by repo ID
  144. func GetProtectedBranchByRepoID(repoID int64) ([]*ProtectedBranch, error) {
  145. protectedBranches := make([]*ProtectedBranch, 0)
  146. return protectedBranches, x.Where("repo_id = ?", repoID).Desc("updated_unix").Find(&protectedBranches)
  147. }
  148. // GetProtectedBranchBy getting protected branch by ID/Name
  149. func GetProtectedBranchBy(repoID int64, branchName string) (*ProtectedBranch, error) {
  150. return getProtectedBranchBy(x, repoID, branchName)
  151. }
  152. func getProtectedBranchBy(e Engine, repoID int64, branchName string) (*ProtectedBranch, error) {
  153. rel := &ProtectedBranch{RepoID: repoID, BranchName: branchName}
  154. has, err := e.Get(rel)
  155. if err != nil {
  156. return nil, err
  157. }
  158. if !has {
  159. return nil, nil
  160. }
  161. return rel, nil
  162. }
  163. // GetProtectedBranchByID getting protected branch by ID
  164. func GetProtectedBranchByID(id int64) (*ProtectedBranch, error) {
  165. rel := &ProtectedBranch{ID: id}
  166. has, err := x.Get(rel)
  167. if err != nil {
  168. return nil, err
  169. }
  170. if !has {
  171. return nil, nil
  172. }
  173. return rel, nil
  174. }
  175. // WhitelistOptions represent all sorts of whitelists used for protected branches
  176. type WhitelistOptions struct {
  177. UserIDs []int64
  178. TeamIDs []int64
  179. MergeUserIDs []int64
  180. MergeTeamIDs []int64
  181. ApprovalsUserIDs []int64
  182. ApprovalsTeamIDs []int64
  183. }
  184. // UpdateProtectBranch saves branch protection options of repository.
  185. // If ID is 0, it creates a new record. Otherwise, updates existing record.
  186. // This function also performs check if whitelist user and team's IDs have been changed
  187. // to avoid unnecessary whitelist delete and regenerate.
  188. func UpdateProtectBranch(repo *Repository, protectBranch *ProtectedBranch, opts WhitelistOptions) (err error) {
  189. if err = repo.GetOwner(); err != nil {
  190. return fmt.Errorf("GetOwner: %v", err)
  191. }
  192. whitelist, err := updateUserWhitelist(repo, protectBranch.WhitelistUserIDs, opts.UserIDs)
  193. if err != nil {
  194. return err
  195. }
  196. protectBranch.WhitelistUserIDs = whitelist
  197. whitelist, err = updateUserWhitelist(repo, protectBranch.MergeWhitelistUserIDs, opts.MergeUserIDs)
  198. if err != nil {
  199. return err
  200. }
  201. protectBranch.MergeWhitelistUserIDs = whitelist
  202. whitelist, err = updateApprovalWhitelist(repo, protectBranch.ApprovalsWhitelistUserIDs, opts.ApprovalsUserIDs)
  203. if err != nil {
  204. return err
  205. }
  206. protectBranch.ApprovalsWhitelistUserIDs = whitelist
  207. // if the repo is in an organization
  208. whitelist, err = updateTeamWhitelist(repo, protectBranch.WhitelistTeamIDs, opts.TeamIDs)
  209. if err != nil {
  210. return err
  211. }
  212. protectBranch.WhitelistTeamIDs = whitelist
  213. whitelist, err = updateTeamWhitelist(repo, protectBranch.MergeWhitelistTeamIDs, opts.MergeTeamIDs)
  214. if err != nil {
  215. return err
  216. }
  217. protectBranch.MergeWhitelistTeamIDs = whitelist
  218. whitelist, err = updateTeamWhitelist(repo, protectBranch.ApprovalsWhitelistTeamIDs, opts.ApprovalsTeamIDs)
  219. if err != nil {
  220. return err
  221. }
  222. protectBranch.ApprovalsWhitelistTeamIDs = whitelist
  223. // Make sure protectBranch.ID is not 0 for whitelists
  224. if protectBranch.ID == 0 {
  225. if _, err = x.Insert(protectBranch); err != nil {
  226. return fmt.Errorf("Insert: %v", err)
  227. }
  228. return nil
  229. }
  230. if _, err = x.ID(protectBranch.ID).AllCols().Update(protectBranch); err != nil {
  231. return fmt.Errorf("Update: %v", err)
  232. }
  233. return nil
  234. }
  235. // GetProtectedBranches get all protected branches
  236. func (repo *Repository) GetProtectedBranches() ([]*ProtectedBranch, error) {
  237. protectedBranches := make([]*ProtectedBranch, 0)
  238. return protectedBranches, x.Find(&protectedBranches, &ProtectedBranch{RepoID: repo.ID})
  239. }
  240. // GetBranchProtection get the branch protection of a branch
  241. func (repo *Repository) GetBranchProtection(branchName string) (*ProtectedBranch, error) {
  242. return GetProtectedBranchBy(repo.ID, branchName)
  243. }
  244. // IsProtectedBranch checks if branch is protected
  245. func (repo *Repository) IsProtectedBranch(branchName string, doer *User) (bool, error) {
  246. if doer == nil {
  247. return true, nil
  248. }
  249. protectedBranch := &ProtectedBranch{
  250. RepoID: repo.ID,
  251. BranchName: branchName,
  252. }
  253. has, err := x.Exist(protectedBranch)
  254. if err != nil {
  255. return true, err
  256. }
  257. return has, nil
  258. }
  259. // IsProtectedBranchForPush checks if branch is protected for push
  260. func (repo *Repository) IsProtectedBranchForPush(branchName string, doer *User) (bool, error) {
  261. if doer == nil {
  262. return true, nil
  263. }
  264. protectedBranch := &ProtectedBranch{
  265. RepoID: repo.ID,
  266. BranchName: branchName,
  267. }
  268. has, err := x.Get(protectedBranch)
  269. if err != nil {
  270. return true, err
  271. } else if has {
  272. return !protectedBranch.CanUserPush(doer.ID), nil
  273. }
  274. return false, nil
  275. }
  276. // IsProtectedBranchForMerging checks if branch is protected for merging
  277. func (repo *Repository) IsProtectedBranchForMerging(pr *PullRequest, branchName string, doer *User) (bool, error) {
  278. if doer == nil {
  279. return true, nil
  280. }
  281. protectedBranch := &ProtectedBranch{
  282. RepoID: repo.ID,
  283. BranchName: branchName,
  284. }
  285. has, err := x.Get(protectedBranch)
  286. if err != nil {
  287. return true, err
  288. } else if has {
  289. return !protectedBranch.CanUserMerge(doer.ID) || !protectedBranch.HasEnoughApprovals(pr), nil
  290. }
  291. return false, nil
  292. }
  293. // updateApprovalWhitelist checks whether the user whitelist changed and returns a whitelist with
  294. // the users from newWhitelist which have explicit read or write access to the repo.
  295. func updateApprovalWhitelist(repo *Repository, currentWhitelist, newWhitelist []int64) (whitelist []int64, err error) {
  296. hasUsersChanged := !util.IsSliceInt64Eq(currentWhitelist, newWhitelist)
  297. if !hasUsersChanged {
  298. return currentWhitelist, nil
  299. }
  300. whitelist = make([]int64, 0, len(newWhitelist))
  301. for _, userID := range newWhitelist {
  302. if reader, err := repo.IsReader(userID); err != nil {
  303. return nil, err
  304. } else if !reader {
  305. continue
  306. }
  307. whitelist = append(whitelist, userID)
  308. }
  309. return
  310. }
  311. // updateUserWhitelist checks whether the user whitelist changed and returns a whitelist with
  312. // the users from newWhitelist which have write access to the repo.
  313. func updateUserWhitelist(repo *Repository, currentWhitelist, newWhitelist []int64) (whitelist []int64, err error) {
  314. hasUsersChanged := !util.IsSliceInt64Eq(currentWhitelist, newWhitelist)
  315. if !hasUsersChanged {
  316. return currentWhitelist, nil
  317. }
  318. whitelist = make([]int64, 0, len(newWhitelist))
  319. for _, userID := range newWhitelist {
  320. user, err := GetUserByID(userID)
  321. if err != nil {
  322. return nil, fmt.Errorf("GetUserByID [user_id: %d, repo_id: %d]: %v", userID, repo.ID, err)
  323. }
  324. perm, err := GetUserRepoPermission(repo, user)
  325. if err != nil {
  326. return nil, fmt.Errorf("GetUserRepoPermission [user_id: %d, repo_id: %d]: %v", userID, repo.ID, err)
  327. }
  328. if !perm.CanWrite(UnitTypeCode) {
  329. continue // Drop invalid user ID
  330. }
  331. whitelist = append(whitelist, userID)
  332. }
  333. return
  334. }
  335. // updateTeamWhitelist checks whether the team whitelist changed and returns a whitelist with
  336. // the teams from newWhitelist which have write access to the repo.
  337. func updateTeamWhitelist(repo *Repository, currentWhitelist, newWhitelist []int64) (whitelist []int64, err error) {
  338. hasTeamsChanged := !util.IsSliceInt64Eq(currentWhitelist, newWhitelist)
  339. if !hasTeamsChanged {
  340. return currentWhitelist, nil
  341. }
  342. teams, err := GetTeamsWithAccessToRepo(repo.OwnerID, repo.ID, AccessModeRead)
  343. if err != nil {
  344. return nil, fmt.Errorf("GetTeamsWithAccessToRepo [org_id: %d, repo_id: %d]: %v", repo.OwnerID, repo.ID, err)
  345. }
  346. whitelist = make([]int64, 0, len(teams))
  347. for i := range teams {
  348. if com.IsSliceContainsInt64(newWhitelist, teams[i].ID) {
  349. whitelist = append(whitelist, teams[i].ID)
  350. }
  351. }
  352. return
  353. }
  354. // DeleteProtectedBranch removes ProtectedBranch relation between the user and repository.
  355. func (repo *Repository) DeleteProtectedBranch(id int64) (err error) {
  356. protectedBranch := &ProtectedBranch{
  357. RepoID: repo.ID,
  358. ID: id,
  359. }
  360. sess := x.NewSession()
  361. defer sess.Close()
  362. if err = sess.Begin(); err != nil {
  363. return err
  364. }
  365. if affected, err := sess.Delete(protectedBranch); err != nil {
  366. return err
  367. } else if affected != 1 {
  368. return fmt.Errorf("delete protected branch ID(%v) failed", id)
  369. }
  370. return sess.Commit()
  371. }
  372. // DeletedBranch struct
  373. type DeletedBranch struct {
  374. ID int64 `xorm:"pk autoincr"`
  375. RepoID int64 `xorm:"UNIQUE(s) INDEX NOT NULL"`
  376. Name string `xorm:"UNIQUE(s) NOT NULL"`
  377. Commit string `xorm:"UNIQUE(s) NOT NULL"`
  378. DeletedByID int64 `xorm:"INDEX"`
  379. DeletedBy *User `xorm:"-"`
  380. DeletedUnix timeutil.TimeStamp `xorm:"INDEX created"`
  381. }
  382. // AddDeletedBranch adds a deleted branch to the database
  383. func (repo *Repository) AddDeletedBranch(branchName, commit string, deletedByID int64) error {
  384. deletedBranch := &DeletedBranch{
  385. RepoID: repo.ID,
  386. Name: branchName,
  387. Commit: commit,
  388. DeletedByID: deletedByID,
  389. }
  390. sess := x.NewSession()
  391. defer sess.Close()
  392. if err := sess.Begin(); err != nil {
  393. return err
  394. }
  395. if _, err := sess.InsertOne(deletedBranch); err != nil {
  396. return err
  397. }
  398. return sess.Commit()
  399. }
  400. // GetDeletedBranches returns all the deleted branches
  401. func (repo *Repository) GetDeletedBranches() ([]*DeletedBranch, error) {
  402. deletedBranches := make([]*DeletedBranch, 0)
  403. return deletedBranches, x.Where("repo_id = ?", repo.ID).Desc("deleted_unix").Find(&deletedBranches)
  404. }
  405. // GetDeletedBranchByID get a deleted branch by its ID
  406. func (repo *Repository) GetDeletedBranchByID(ID int64) (*DeletedBranch, error) {
  407. deletedBranch := &DeletedBranch{ID: ID}
  408. has, err := x.Get(deletedBranch)
  409. if err != nil {
  410. return nil, err
  411. }
  412. if !has {
  413. return nil, nil
  414. }
  415. return deletedBranch, nil
  416. }
  417. // RemoveDeletedBranch removes a deleted branch from the database
  418. func (repo *Repository) RemoveDeletedBranch(id int64) (err error) {
  419. deletedBranch := &DeletedBranch{
  420. RepoID: repo.ID,
  421. ID: id,
  422. }
  423. sess := x.NewSession()
  424. defer sess.Close()
  425. if err = sess.Begin(); err != nil {
  426. return err
  427. }
  428. if affected, err := sess.Delete(deletedBranch); err != nil {
  429. return err
  430. } else if affected != 1 {
  431. return fmt.Errorf("remove deleted branch ID(%v) failed", id)
  432. }
  433. return sess.Commit()
  434. }
  435. // LoadUser loads the user that deleted the branch
  436. // When there's no user found it returns a NewGhostUser
  437. func (deletedBranch *DeletedBranch) LoadUser() {
  438. user, err := GetUserByID(deletedBranch.DeletedByID)
  439. if err != nil {
  440. user = NewGhostUser()
  441. }
  442. deletedBranch.DeletedBy = user
  443. }
  444. // RemoveOldDeletedBranches removes old deleted branches
  445. func RemoveOldDeletedBranches(ctx context.Context) {
  446. // Nothing to do for shutdown or terminate
  447. log.Trace("Doing: DeletedBranchesCleanup")
  448. deleteBefore := time.Now().Add(-setting.Cron.DeletedBranchesCleanup.OlderThan)
  449. _, err := x.Where("deleted_unix < ?", deleteBefore.Unix()).Delete(new(DeletedBranch))
  450. if err != nil {
  451. log.Error("DeletedBranchesCleanup: %v", err)
  452. }
  453. }