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 19 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
[Enhancement] Allow admin to merge pr with protected file changes (#12078) * [Enhancement] Allow admin to merge pr with protected file changes As tilte, show protected message in diff page and merge box. Signed-off-by: a1012112796 <1012112796@qq.com> * remove unused ver * Update options/locale/locale_en-US.ini Co-authored-by: Cirno the Strongest <1447794+CirnoT@users.noreply.github.com> * Add TrN * Apply suggestions from code review * fix lint * Update options/locale/locale_en-US.ini Co-authored-by: zeripath <art27@cantab.net> * Apply suggestions from code review * move pr proteced files check to TestPatch * Call TestPatch when protected branches settings changed * Apply review suggestion @CirnoT * move to service @lunny * slightly restructure routers/private/hook.go Adds a lot of comments and simplifies the logic Signed-off-by: Andrew Thornton <art27@cantab.net> * placate lint Signed-off-by: Andrew Thornton <art27@cantab.net> * skip duplicate protected files check * fix check logic * slight refactor of TestPatch Signed-off-by: Andrew Thornton <art27@cantab.net> * When checking for protected files changes in TestPatch use the temporary repository Signed-off-by: Andrew Thornton <art27@cantab.net> * fix introduced issue with hook Signed-off-by: Andrew Thornton <art27@cantab.net> * Remove the check on PR index being greater than 0 as it unnecessary Signed-off-by: Andrew Thornton <art27@cantab.net> Co-authored-by: techknowlogick <matti@mdranta.net> Co-authored-by: Cirno the Strongest <1447794+CirnoT@users.noreply.github.com> Co-authored-by: zeripath <art27@cantab.net> Co-authored-by: techknowlogick <techknowlogick@gitea.io>
4 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
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616
  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. "strings"
  9. "time"
  10. "code.gitea.io/gitea/modules/base"
  11. "code.gitea.io/gitea/modules/log"
  12. "code.gitea.io/gitea/modules/timeutil"
  13. "code.gitea.io/gitea/modules/util"
  14. "github.com/gobwas/glob"
  15. "github.com/unknwon/com"
  16. )
  17. // ProtectedBranch struct
  18. type ProtectedBranch struct {
  19. ID int64 `xorm:"pk autoincr"`
  20. RepoID int64 `xorm:"UNIQUE(s)"`
  21. BranchName string `xorm:"UNIQUE(s)"`
  22. CanPush bool `xorm:"NOT NULL DEFAULT false"`
  23. EnableWhitelist bool
  24. WhitelistUserIDs []int64 `xorm:"JSON TEXT"`
  25. WhitelistTeamIDs []int64 `xorm:"JSON TEXT"`
  26. EnableMergeWhitelist bool `xorm:"NOT NULL DEFAULT false"`
  27. WhitelistDeployKeys bool `xorm:"NOT NULL DEFAULT false"`
  28. MergeWhitelistUserIDs []int64 `xorm:"JSON TEXT"`
  29. MergeWhitelistTeamIDs []int64 `xorm:"JSON TEXT"`
  30. EnableStatusCheck bool `xorm:"NOT NULL DEFAULT false"`
  31. StatusCheckContexts []string `xorm:"JSON TEXT"`
  32. EnableApprovalsWhitelist bool `xorm:"NOT NULL DEFAULT false"`
  33. ApprovalsWhitelistUserIDs []int64 `xorm:"JSON TEXT"`
  34. ApprovalsWhitelistTeamIDs []int64 `xorm:"JSON TEXT"`
  35. RequiredApprovals int64 `xorm:"NOT NULL DEFAULT 0"`
  36. BlockOnRejectedReviews bool `xorm:"NOT NULL DEFAULT false"`
  37. BlockOnOfficialReviewRequests bool `xorm:"NOT NULL DEFAULT false"`
  38. BlockOnOutdatedBranch bool `xorm:"NOT NULL DEFAULT false"`
  39. DismissStaleApprovals bool `xorm:"NOT NULL DEFAULT false"`
  40. RequireSignedCommits bool `xorm:"NOT NULL DEFAULT false"`
  41. ProtectedFilePatterns string `xorm:"TEXT"`
  42. CreatedUnix timeutil.TimeStamp `xorm:"created"`
  43. UpdatedUnix timeutil.TimeStamp `xorm:"updated"`
  44. }
  45. // IsProtected returns if the branch is protected
  46. func (protectBranch *ProtectedBranch) IsProtected() bool {
  47. return protectBranch.ID > 0
  48. }
  49. // CanUserPush returns if some user could push to this protected branch
  50. func (protectBranch *ProtectedBranch) CanUserPush(userID int64) bool {
  51. if !protectBranch.CanPush {
  52. return false
  53. }
  54. if !protectBranch.EnableWhitelist {
  55. if user, err := GetUserByID(userID); err != nil {
  56. log.Error("GetUserByID: %v", err)
  57. return false
  58. } else if repo, err := GetRepositoryByID(protectBranch.RepoID); err != nil {
  59. log.Error("GetRepositoryByID: %v", err)
  60. return false
  61. } else if writeAccess, err := HasAccessUnit(user, repo, UnitTypeCode, AccessModeWrite); err != nil {
  62. log.Error("HasAccessUnit: %v", err)
  63. return false
  64. } else {
  65. return writeAccess
  66. }
  67. }
  68. if base.Int64sContains(protectBranch.WhitelistUserIDs, userID) {
  69. return true
  70. }
  71. if len(protectBranch.WhitelistTeamIDs) == 0 {
  72. return false
  73. }
  74. in, err := IsUserInTeams(userID, protectBranch.WhitelistTeamIDs)
  75. if err != nil {
  76. log.Error("IsUserInTeams: %v", err)
  77. return false
  78. }
  79. return in
  80. }
  81. // IsUserMergeWhitelisted checks if some user is whitelisted to merge to this branch
  82. func (protectBranch *ProtectedBranch) IsUserMergeWhitelisted(userID int64, permissionInRepo Permission) bool {
  83. if !protectBranch.EnableMergeWhitelist {
  84. // Then we need to fall back on whether the user has write permission
  85. return permissionInRepo.CanWrite(UnitTypeCode)
  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. // MergeBlockedByOfficialReviewRequests block merge because of some review request to official reviewer
  164. // of from official review
  165. func (protectBranch *ProtectedBranch) MergeBlockedByOfficialReviewRequests(pr *PullRequest) bool {
  166. if !protectBranch.BlockOnOfficialReviewRequests {
  167. return false
  168. }
  169. has, err := x.Where("issue_id = ?", pr.IssueID).
  170. And("type = ?", ReviewTypeRequest).
  171. And("official = ?", true).
  172. Exist(new(Review))
  173. if err != nil {
  174. log.Error("MergeBlockedByOfficialReviewRequests: %v", err)
  175. return true
  176. }
  177. return has
  178. }
  179. // MergeBlockedByOutdatedBranch returns true if merge is blocked by an outdated head branch
  180. func (protectBranch *ProtectedBranch) MergeBlockedByOutdatedBranch(pr *PullRequest) bool {
  181. return protectBranch.BlockOnOutdatedBranch && pr.CommitsBehind > 0
  182. }
  183. // GetProtectedFilePatterns parses a semicolon separated list of protected file patterns and returns a glob.Glob slice
  184. func (protectBranch *ProtectedBranch) GetProtectedFilePatterns() []glob.Glob {
  185. extarr := make([]glob.Glob, 0, 10)
  186. for _, expr := range strings.Split(strings.ToLower(protectBranch.ProtectedFilePatterns), ";") {
  187. expr = strings.TrimSpace(expr)
  188. if expr != "" {
  189. if g, err := glob.Compile(expr, '.', '/'); err != nil {
  190. log.Info("Invalid glob expresion '%s' (skipped): %v", expr, err)
  191. } else {
  192. extarr = append(extarr, g)
  193. }
  194. }
  195. }
  196. return extarr
  197. }
  198. // MergeBlockedByProtectedFiles returns true if merge is blocked by protected files change
  199. func (protectBranch *ProtectedBranch) MergeBlockedByProtectedFiles(pr *PullRequest) bool {
  200. glob := protectBranch.GetProtectedFilePatterns()
  201. if len(glob) == 0 {
  202. return false
  203. }
  204. return len(pr.ChangedProtectedFiles) > 0
  205. }
  206. // IsProtectedFile return if path is protected
  207. func (protectBranch *ProtectedBranch) IsProtectedFile(patterns []glob.Glob, path string) bool {
  208. if len(patterns) == 0 {
  209. patterns = protectBranch.GetProtectedFilePatterns()
  210. if len(patterns) == 0 {
  211. return false
  212. }
  213. }
  214. lpath := strings.ToLower(strings.TrimSpace(path))
  215. r := false
  216. for _, pat := range patterns {
  217. if pat.Match(lpath) {
  218. r = true
  219. break
  220. }
  221. }
  222. return r
  223. }
  224. // GetProtectedBranchByRepoID getting protected branch by repo ID
  225. func GetProtectedBranchByRepoID(repoID int64) ([]*ProtectedBranch, error) {
  226. protectedBranches := make([]*ProtectedBranch, 0)
  227. return protectedBranches, x.Where("repo_id = ?", repoID).Desc("updated_unix").Find(&protectedBranches)
  228. }
  229. // GetProtectedBranchBy getting protected branch by ID/Name
  230. func GetProtectedBranchBy(repoID int64, branchName string) (*ProtectedBranch, error) {
  231. return getProtectedBranchBy(x, repoID, branchName)
  232. }
  233. func getProtectedBranchBy(e Engine, repoID int64, branchName string) (*ProtectedBranch, error) {
  234. rel := &ProtectedBranch{RepoID: repoID, BranchName: branchName}
  235. has, err := e.Get(rel)
  236. if err != nil {
  237. return nil, err
  238. }
  239. if !has {
  240. return nil, nil
  241. }
  242. return rel, nil
  243. }
  244. // GetProtectedBranchByID getting protected branch by ID
  245. func GetProtectedBranchByID(id int64) (*ProtectedBranch, error) {
  246. rel := &ProtectedBranch{}
  247. has, err := x.ID(id).Get(rel)
  248. if err != nil {
  249. return nil, err
  250. }
  251. if !has {
  252. return nil, nil
  253. }
  254. return rel, nil
  255. }
  256. // WhitelistOptions represent all sorts of whitelists used for protected branches
  257. type WhitelistOptions struct {
  258. UserIDs []int64
  259. TeamIDs []int64
  260. MergeUserIDs []int64
  261. MergeTeamIDs []int64
  262. ApprovalsUserIDs []int64
  263. ApprovalsTeamIDs []int64
  264. }
  265. // UpdateProtectBranch saves branch protection options of repository.
  266. // If ID is 0, it creates a new record. Otherwise, updates existing record.
  267. // This function also performs check if whitelist user and team's IDs have been changed
  268. // to avoid unnecessary whitelist delete and regenerate.
  269. func UpdateProtectBranch(repo *Repository, protectBranch *ProtectedBranch, opts WhitelistOptions) (err error) {
  270. if err = repo.GetOwner(); err != nil {
  271. return fmt.Errorf("GetOwner: %v", err)
  272. }
  273. whitelist, err := updateUserWhitelist(repo, protectBranch.WhitelistUserIDs, opts.UserIDs)
  274. if err != nil {
  275. return err
  276. }
  277. protectBranch.WhitelistUserIDs = whitelist
  278. whitelist, err = updateUserWhitelist(repo, protectBranch.MergeWhitelistUserIDs, opts.MergeUserIDs)
  279. if err != nil {
  280. return err
  281. }
  282. protectBranch.MergeWhitelistUserIDs = whitelist
  283. whitelist, err = updateApprovalWhitelist(repo, protectBranch.ApprovalsWhitelistUserIDs, opts.ApprovalsUserIDs)
  284. if err != nil {
  285. return err
  286. }
  287. protectBranch.ApprovalsWhitelistUserIDs = whitelist
  288. // if the repo is in an organization
  289. whitelist, err = updateTeamWhitelist(repo, protectBranch.WhitelistTeamIDs, opts.TeamIDs)
  290. if err != nil {
  291. return err
  292. }
  293. protectBranch.WhitelistTeamIDs = whitelist
  294. whitelist, err = updateTeamWhitelist(repo, protectBranch.MergeWhitelistTeamIDs, opts.MergeTeamIDs)
  295. if err != nil {
  296. return err
  297. }
  298. protectBranch.MergeWhitelistTeamIDs = whitelist
  299. whitelist, err = updateTeamWhitelist(repo, protectBranch.ApprovalsWhitelistTeamIDs, opts.ApprovalsTeamIDs)
  300. if err != nil {
  301. return err
  302. }
  303. protectBranch.ApprovalsWhitelistTeamIDs = whitelist
  304. // Make sure protectBranch.ID is not 0 for whitelists
  305. if protectBranch.ID == 0 {
  306. if _, err = x.Insert(protectBranch); err != nil {
  307. return fmt.Errorf("Insert: %v", err)
  308. }
  309. return nil
  310. }
  311. if _, err = x.ID(protectBranch.ID).AllCols().Update(protectBranch); err != nil {
  312. return fmt.Errorf("Update: %v", err)
  313. }
  314. return nil
  315. }
  316. // GetProtectedBranches get all protected branches
  317. func (repo *Repository) GetProtectedBranches() ([]*ProtectedBranch, error) {
  318. protectedBranches := make([]*ProtectedBranch, 0)
  319. return protectedBranches, x.Find(&protectedBranches, &ProtectedBranch{RepoID: repo.ID})
  320. }
  321. // GetBranchProtection get the branch protection of a branch
  322. func (repo *Repository) GetBranchProtection(branchName string) (*ProtectedBranch, error) {
  323. return GetProtectedBranchBy(repo.ID, branchName)
  324. }
  325. // IsProtectedBranch checks if branch is protected
  326. func (repo *Repository) IsProtectedBranch(branchName string, doer *User) (bool, error) {
  327. if doer == nil {
  328. return true, nil
  329. }
  330. protectedBranch := &ProtectedBranch{
  331. RepoID: repo.ID,
  332. BranchName: branchName,
  333. }
  334. has, err := x.Exist(protectedBranch)
  335. if err != nil {
  336. return true, err
  337. }
  338. return has, nil
  339. }
  340. // IsProtectedBranchForPush checks if branch is protected for push
  341. func (repo *Repository) IsProtectedBranchForPush(branchName string, doer *User) (bool, error) {
  342. if doer == nil {
  343. return true, nil
  344. }
  345. protectedBranch := &ProtectedBranch{
  346. RepoID: repo.ID,
  347. BranchName: branchName,
  348. }
  349. has, err := x.Get(protectedBranch)
  350. if err != nil {
  351. return true, err
  352. } else if has {
  353. return !protectedBranch.CanUserPush(doer.ID), nil
  354. }
  355. return false, nil
  356. }
  357. // updateApprovalWhitelist checks whether the user whitelist changed and returns a whitelist with
  358. // the users from newWhitelist which have explicit read or write access to the repo.
  359. func updateApprovalWhitelist(repo *Repository, currentWhitelist, newWhitelist []int64) (whitelist []int64, err error) {
  360. hasUsersChanged := !util.IsSliceInt64Eq(currentWhitelist, newWhitelist)
  361. if !hasUsersChanged {
  362. return currentWhitelist, nil
  363. }
  364. whitelist = make([]int64, 0, len(newWhitelist))
  365. for _, userID := range newWhitelist {
  366. if reader, err := repo.IsReader(userID); err != nil {
  367. return nil, err
  368. } else if !reader {
  369. continue
  370. }
  371. whitelist = append(whitelist, userID)
  372. }
  373. return
  374. }
  375. // updateUserWhitelist checks whether the user whitelist changed and returns a whitelist with
  376. // the users from newWhitelist which have write access to the repo.
  377. func updateUserWhitelist(repo *Repository, currentWhitelist, newWhitelist []int64) (whitelist []int64, err error) {
  378. hasUsersChanged := !util.IsSliceInt64Eq(currentWhitelist, newWhitelist)
  379. if !hasUsersChanged {
  380. return currentWhitelist, nil
  381. }
  382. whitelist = make([]int64, 0, len(newWhitelist))
  383. for _, userID := range newWhitelist {
  384. user, err := GetUserByID(userID)
  385. if err != nil {
  386. return nil, fmt.Errorf("GetUserByID [user_id: %d, repo_id: %d]: %v", userID, repo.ID, err)
  387. }
  388. perm, err := GetUserRepoPermission(repo, user)
  389. if err != nil {
  390. return nil, fmt.Errorf("GetUserRepoPermission [user_id: %d, repo_id: %d]: %v", userID, repo.ID, err)
  391. }
  392. if !perm.CanWrite(UnitTypeCode) {
  393. continue // Drop invalid user ID
  394. }
  395. whitelist = append(whitelist, userID)
  396. }
  397. return
  398. }
  399. // updateTeamWhitelist checks whether the team whitelist changed and returns a whitelist with
  400. // the teams from newWhitelist which have write access to the repo.
  401. func updateTeamWhitelist(repo *Repository, currentWhitelist, newWhitelist []int64) (whitelist []int64, err error) {
  402. hasTeamsChanged := !util.IsSliceInt64Eq(currentWhitelist, newWhitelist)
  403. if !hasTeamsChanged {
  404. return currentWhitelist, nil
  405. }
  406. teams, err := GetTeamsWithAccessToRepo(repo.OwnerID, repo.ID, AccessModeRead)
  407. if err != nil {
  408. return nil, fmt.Errorf("GetTeamsWithAccessToRepo [org_id: %d, repo_id: %d]: %v", repo.OwnerID, repo.ID, err)
  409. }
  410. whitelist = make([]int64, 0, len(teams))
  411. for i := range teams {
  412. if com.IsSliceContainsInt64(newWhitelist, teams[i].ID) {
  413. whitelist = append(whitelist, teams[i].ID)
  414. }
  415. }
  416. return
  417. }
  418. // DeleteProtectedBranch removes ProtectedBranch relation between the user and repository.
  419. func (repo *Repository) DeleteProtectedBranch(id int64) (err error) {
  420. protectedBranch := &ProtectedBranch{
  421. RepoID: repo.ID,
  422. ID: id,
  423. }
  424. sess := x.NewSession()
  425. defer sess.Close()
  426. if err = sess.Begin(); err != nil {
  427. return err
  428. }
  429. if affected, err := sess.Delete(protectedBranch); err != nil {
  430. return err
  431. } else if affected != 1 {
  432. return fmt.Errorf("delete protected branch ID(%v) failed", id)
  433. }
  434. return sess.Commit()
  435. }
  436. // DeletedBranch struct
  437. type DeletedBranch struct {
  438. ID int64 `xorm:"pk autoincr"`
  439. RepoID int64 `xorm:"UNIQUE(s) INDEX NOT NULL"`
  440. Name string `xorm:"UNIQUE(s) NOT NULL"`
  441. Commit string `xorm:"UNIQUE(s) NOT NULL"`
  442. DeletedByID int64 `xorm:"INDEX"`
  443. DeletedBy *User `xorm:"-"`
  444. DeletedUnix timeutil.TimeStamp `xorm:"INDEX created"`
  445. }
  446. // AddDeletedBranch adds a deleted branch to the database
  447. func (repo *Repository) AddDeletedBranch(branchName, commit string, deletedByID int64) error {
  448. deletedBranch := &DeletedBranch{
  449. RepoID: repo.ID,
  450. Name: branchName,
  451. Commit: commit,
  452. DeletedByID: deletedByID,
  453. }
  454. sess := x.NewSession()
  455. defer sess.Close()
  456. if err := sess.Begin(); err != nil {
  457. return err
  458. }
  459. if _, err := sess.InsertOne(deletedBranch); err != nil {
  460. return err
  461. }
  462. return sess.Commit()
  463. }
  464. // GetDeletedBranches returns all the deleted branches
  465. func (repo *Repository) GetDeletedBranches() ([]*DeletedBranch, error) {
  466. deletedBranches := make([]*DeletedBranch, 0)
  467. return deletedBranches, x.Where("repo_id = ?", repo.ID).Desc("deleted_unix").Find(&deletedBranches)
  468. }
  469. // GetDeletedBranchByID get a deleted branch by its ID
  470. func (repo *Repository) GetDeletedBranchByID(id int64) (*DeletedBranch, error) {
  471. deletedBranch := &DeletedBranch{}
  472. has, err := x.ID(id).Get(deletedBranch)
  473. if err != nil {
  474. return nil, err
  475. }
  476. if !has {
  477. return nil, nil
  478. }
  479. return deletedBranch, nil
  480. }
  481. // RemoveDeletedBranch removes a deleted branch from the database
  482. func (repo *Repository) RemoveDeletedBranch(id int64) (err error) {
  483. deletedBranch := &DeletedBranch{
  484. RepoID: repo.ID,
  485. ID: id,
  486. }
  487. sess := x.NewSession()
  488. defer sess.Close()
  489. if err = sess.Begin(); err != nil {
  490. return err
  491. }
  492. if affected, err := sess.Delete(deletedBranch); err != nil {
  493. return err
  494. } else if affected != 1 {
  495. return fmt.Errorf("remove deleted branch ID(%v) failed", id)
  496. }
  497. return sess.Commit()
  498. }
  499. // LoadUser loads the user that deleted the branch
  500. // When there's no user found it returns a NewGhostUser
  501. func (deletedBranch *DeletedBranch) LoadUser() {
  502. user, err := GetUserByID(deletedBranch.DeletedByID)
  503. if err != nil {
  504. user = NewGhostUser()
  505. }
  506. deletedBranch.DeletedBy = user
  507. }
  508. // RemoveDeletedBranch removes all deleted branches
  509. func RemoveDeletedBranch(repoID int64, branch string) error {
  510. _, err := x.Where("repo_id=? AND name=?", repoID, branch).Delete(new(DeletedBranch))
  511. return err
  512. }
  513. // RemoveOldDeletedBranches removes old deleted branches
  514. func RemoveOldDeletedBranches(ctx context.Context, olderThan time.Duration) {
  515. // Nothing to do for shutdown or terminate
  516. log.Trace("Doing: DeletedBranchesCleanup")
  517. deleteBefore := time.Now().Add(-olderThan)
  518. _, err := x.Where("deleted_unix < ?", deleteBefore.Unix()).Delete(new(DeletedBranch))
  519. if err != nil {
  520. log.Error("DeletedBranchesCleanup: %v", err)
  521. }
  522. }