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 17 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
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567
  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. // CanUserMerge returns if some user could merge a pull request to this protected branch
  83. func (protectBranch *ProtectedBranch) CanUserMerge(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. // IsProtectedBranchForMerging checks if branch is protected for merging
  297. func (repo *Repository) IsProtectedBranchForMerging(pr *PullRequest, branchName string, doer *User) (bool, error) {
  298. if doer == nil {
  299. return true, nil
  300. }
  301. protectedBranch := &ProtectedBranch{
  302. RepoID: repo.ID,
  303. BranchName: branchName,
  304. }
  305. has, err := x.Get(protectedBranch)
  306. if err != nil {
  307. return true, err
  308. } else if has {
  309. return !protectedBranch.CanUserMerge(doer.ID) || !protectedBranch.HasEnoughApprovals(pr) || protectedBranch.MergeBlockedByRejectedReview(pr), nil
  310. }
  311. return false, nil
  312. }
  313. // updateApprovalWhitelist checks whether the user whitelist changed and returns a whitelist with
  314. // the users from newWhitelist which have explicit read or write access to the repo.
  315. func updateApprovalWhitelist(repo *Repository, currentWhitelist, newWhitelist []int64) (whitelist []int64, err error) {
  316. hasUsersChanged := !util.IsSliceInt64Eq(currentWhitelist, newWhitelist)
  317. if !hasUsersChanged {
  318. return currentWhitelist, nil
  319. }
  320. whitelist = make([]int64, 0, len(newWhitelist))
  321. for _, userID := range newWhitelist {
  322. if reader, err := repo.IsReader(userID); err != nil {
  323. return nil, err
  324. } else if !reader {
  325. continue
  326. }
  327. whitelist = append(whitelist, userID)
  328. }
  329. return
  330. }
  331. // updateUserWhitelist checks whether the user whitelist changed and returns a whitelist with
  332. // the users from newWhitelist which have write access to the repo.
  333. func updateUserWhitelist(repo *Repository, currentWhitelist, newWhitelist []int64) (whitelist []int64, err error) {
  334. hasUsersChanged := !util.IsSliceInt64Eq(currentWhitelist, newWhitelist)
  335. if !hasUsersChanged {
  336. return currentWhitelist, nil
  337. }
  338. whitelist = make([]int64, 0, len(newWhitelist))
  339. for _, userID := range newWhitelist {
  340. user, err := GetUserByID(userID)
  341. if err != nil {
  342. return nil, fmt.Errorf("GetUserByID [user_id: %d, repo_id: %d]: %v", userID, repo.ID, err)
  343. }
  344. perm, err := GetUserRepoPermission(repo, user)
  345. if err != nil {
  346. return nil, fmt.Errorf("GetUserRepoPermission [user_id: %d, repo_id: %d]: %v", userID, repo.ID, err)
  347. }
  348. if !perm.CanWrite(UnitTypeCode) {
  349. continue // Drop invalid user ID
  350. }
  351. whitelist = append(whitelist, userID)
  352. }
  353. return
  354. }
  355. // updateTeamWhitelist checks whether the team whitelist changed and returns a whitelist with
  356. // the teams from newWhitelist which have write access to the repo.
  357. func updateTeamWhitelist(repo *Repository, currentWhitelist, newWhitelist []int64) (whitelist []int64, err error) {
  358. hasTeamsChanged := !util.IsSliceInt64Eq(currentWhitelist, newWhitelist)
  359. if !hasTeamsChanged {
  360. return currentWhitelist, nil
  361. }
  362. teams, err := GetTeamsWithAccessToRepo(repo.OwnerID, repo.ID, AccessModeRead)
  363. if err != nil {
  364. return nil, fmt.Errorf("GetTeamsWithAccessToRepo [org_id: %d, repo_id: %d]: %v", repo.OwnerID, repo.ID, err)
  365. }
  366. whitelist = make([]int64, 0, len(teams))
  367. for i := range teams {
  368. if com.IsSliceContainsInt64(newWhitelist, teams[i].ID) {
  369. whitelist = append(whitelist, teams[i].ID)
  370. }
  371. }
  372. return
  373. }
  374. // DeleteProtectedBranch removes ProtectedBranch relation between the user and repository.
  375. func (repo *Repository) DeleteProtectedBranch(id int64) (err error) {
  376. protectedBranch := &ProtectedBranch{
  377. RepoID: repo.ID,
  378. ID: id,
  379. }
  380. sess := x.NewSession()
  381. defer sess.Close()
  382. if err = sess.Begin(); err != nil {
  383. return err
  384. }
  385. if affected, err := sess.Delete(protectedBranch); err != nil {
  386. return err
  387. } else if affected != 1 {
  388. return fmt.Errorf("delete protected branch ID(%v) failed", id)
  389. }
  390. return sess.Commit()
  391. }
  392. // DeletedBranch struct
  393. type DeletedBranch struct {
  394. ID int64 `xorm:"pk autoincr"`
  395. RepoID int64 `xorm:"UNIQUE(s) INDEX NOT NULL"`
  396. Name string `xorm:"UNIQUE(s) NOT NULL"`
  397. Commit string `xorm:"UNIQUE(s) NOT NULL"`
  398. DeletedByID int64 `xorm:"INDEX"`
  399. DeletedBy *User `xorm:"-"`
  400. DeletedUnix timeutil.TimeStamp `xorm:"INDEX created"`
  401. }
  402. // AddDeletedBranch adds a deleted branch to the database
  403. func (repo *Repository) AddDeletedBranch(branchName, commit string, deletedByID int64) error {
  404. deletedBranch := &DeletedBranch{
  405. RepoID: repo.ID,
  406. Name: branchName,
  407. Commit: commit,
  408. DeletedByID: deletedByID,
  409. }
  410. sess := x.NewSession()
  411. defer sess.Close()
  412. if err := sess.Begin(); err != nil {
  413. return err
  414. }
  415. if _, err := sess.InsertOne(deletedBranch); err != nil {
  416. return err
  417. }
  418. return sess.Commit()
  419. }
  420. // GetDeletedBranches returns all the deleted branches
  421. func (repo *Repository) GetDeletedBranches() ([]*DeletedBranch, error) {
  422. deletedBranches := make([]*DeletedBranch, 0)
  423. return deletedBranches, x.Where("repo_id = ?", repo.ID).Desc("deleted_unix").Find(&deletedBranches)
  424. }
  425. // GetDeletedBranchByID get a deleted branch by its ID
  426. func (repo *Repository) GetDeletedBranchByID(ID int64) (*DeletedBranch, error) {
  427. deletedBranch := &DeletedBranch{ID: ID}
  428. has, err := x.Get(deletedBranch)
  429. if err != nil {
  430. return nil, err
  431. }
  432. if !has {
  433. return nil, nil
  434. }
  435. return deletedBranch, nil
  436. }
  437. // RemoveDeletedBranch removes a deleted branch from the database
  438. func (repo *Repository) RemoveDeletedBranch(id int64) (err error) {
  439. deletedBranch := &DeletedBranch{
  440. RepoID: repo.ID,
  441. ID: id,
  442. }
  443. sess := x.NewSession()
  444. defer sess.Close()
  445. if err = sess.Begin(); err != nil {
  446. return err
  447. }
  448. if affected, err := sess.Delete(deletedBranch); err != nil {
  449. return err
  450. } else if affected != 1 {
  451. return fmt.Errorf("remove deleted branch ID(%v) failed", id)
  452. }
  453. return sess.Commit()
  454. }
  455. // LoadUser loads the user that deleted the branch
  456. // When there's no user found it returns a NewGhostUser
  457. func (deletedBranch *DeletedBranch) LoadUser() {
  458. user, err := GetUserByID(deletedBranch.DeletedByID)
  459. if err != nil {
  460. user = NewGhostUser()
  461. }
  462. deletedBranch.DeletedBy = user
  463. }
  464. // RemoveDeletedBranch removes all deleted branches
  465. func RemoveDeletedBranch(repoID int64, branch string) error {
  466. _, err := x.Where("repo_id=? AND name=?", repoID, branch).Delete(new(DeletedBranch))
  467. return err
  468. }
  469. // RemoveOldDeletedBranches removes old deleted branches
  470. func RemoveOldDeletedBranches(ctx context.Context) {
  471. // Nothing to do for shutdown or terminate
  472. log.Trace("Doing: DeletedBranchesCleanup")
  473. deleteBefore := time.Now().Add(-setting.Cron.DeletedBranchesCleanup.OlderThan)
  474. _, err := x.Where("deleted_unix < ?", deleteBefore.Unix()).Delete(new(DeletedBranch))
  475. if err != nil {
  476. log.Error("DeletedBranchesCleanup: %v", err)
  477. }
  478. }