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
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615
  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. )
  16. // ProtectedBranch struct
  17. type ProtectedBranch struct {
  18. ID int64 `xorm:"pk autoincr"`
  19. RepoID int64 `xorm:"UNIQUE(s)"`
  20. BranchName string `xorm:"UNIQUE(s)"`
  21. CanPush bool `xorm:"NOT NULL DEFAULT false"`
  22. EnableWhitelist bool
  23. WhitelistUserIDs []int64 `xorm:"JSON TEXT"`
  24. WhitelistTeamIDs []int64 `xorm:"JSON TEXT"`
  25. EnableMergeWhitelist bool `xorm:"NOT NULL DEFAULT false"`
  26. WhitelistDeployKeys bool `xorm:"NOT NULL DEFAULT false"`
  27. MergeWhitelistUserIDs []int64 `xorm:"JSON TEXT"`
  28. MergeWhitelistTeamIDs []int64 `xorm:"JSON TEXT"`
  29. EnableStatusCheck bool `xorm:"NOT NULL DEFAULT false"`
  30. StatusCheckContexts []string `xorm:"JSON TEXT"`
  31. EnableApprovalsWhitelist bool `xorm:"NOT NULL DEFAULT false"`
  32. ApprovalsWhitelistUserIDs []int64 `xorm:"JSON TEXT"`
  33. ApprovalsWhitelistTeamIDs []int64 `xorm:"JSON TEXT"`
  34. RequiredApprovals int64 `xorm:"NOT NULL DEFAULT 0"`
  35. BlockOnRejectedReviews bool `xorm:"NOT NULL DEFAULT false"`
  36. BlockOnOfficialReviewRequests bool `xorm:"NOT NULL DEFAULT false"`
  37. BlockOnOutdatedBranch bool `xorm:"NOT NULL DEFAULT false"`
  38. DismissStaleApprovals bool `xorm:"NOT NULL DEFAULT false"`
  39. RequireSignedCommits bool `xorm:"NOT NULL DEFAULT false"`
  40. ProtectedFilePatterns string `xorm:"TEXT"`
  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. // IsUserMergeWhitelisted checks if some user is whitelisted to merge to this branch
  81. func (protectBranch *ProtectedBranch) IsUserMergeWhitelisted(userID int64, permissionInRepo Permission) bool {
  82. if !protectBranch.EnableMergeWhitelist {
  83. // Then we need to fall back on whether the user has write permission
  84. return permissionInRepo.CanWrite(UnitTypeCode)
  85. }
  86. if base.Int64sContains(protectBranch.MergeWhitelistUserIDs, userID) {
  87. return true
  88. }
  89. if len(protectBranch.MergeWhitelistTeamIDs) == 0 {
  90. return false
  91. }
  92. in, err := IsUserInTeams(userID, protectBranch.MergeWhitelistTeamIDs)
  93. if err != nil {
  94. log.Error("IsUserInTeams: %v", err)
  95. return false
  96. }
  97. return in
  98. }
  99. // IsUserOfficialReviewer check if user is official reviewer for the branch (counts towards required approvals)
  100. func (protectBranch *ProtectedBranch) IsUserOfficialReviewer(user *User) (bool, error) {
  101. return protectBranch.isUserOfficialReviewer(x, user)
  102. }
  103. func (protectBranch *ProtectedBranch) isUserOfficialReviewer(e Engine, user *User) (bool, error) {
  104. repo, err := getRepositoryByID(e, protectBranch.RepoID)
  105. if err != nil {
  106. return false, err
  107. }
  108. if !protectBranch.EnableApprovalsWhitelist {
  109. // Anyone with write access is considered official reviewer
  110. writeAccess, err := hasAccessUnit(e, user, repo, UnitTypeCode, AccessModeWrite)
  111. if err != nil {
  112. return false, err
  113. }
  114. return writeAccess, nil
  115. }
  116. if base.Int64sContains(protectBranch.ApprovalsWhitelistUserIDs, user.ID) {
  117. return true, nil
  118. }
  119. inTeam, err := isUserInTeams(e, user.ID, protectBranch.ApprovalsWhitelistTeamIDs)
  120. if err != nil {
  121. return false, err
  122. }
  123. return inTeam, nil
  124. }
  125. // HasEnoughApprovals returns true if pr has enough granted approvals.
  126. func (protectBranch *ProtectedBranch) HasEnoughApprovals(pr *PullRequest) bool {
  127. if protectBranch.RequiredApprovals == 0 {
  128. return true
  129. }
  130. return protectBranch.GetGrantedApprovalsCount(pr) >= protectBranch.RequiredApprovals
  131. }
  132. // GetGrantedApprovalsCount returns the number of granted approvals for pr. A granted approval must be authored by a user in an approval whitelist.
  133. func (protectBranch *ProtectedBranch) GetGrantedApprovalsCount(pr *PullRequest) int64 {
  134. sess := x.Where("issue_id = ?", pr.IssueID).
  135. And("type = ?", ReviewTypeApprove).
  136. And("official = ?", true)
  137. if protectBranch.DismissStaleApprovals {
  138. sess = sess.And("stale = ?", false)
  139. }
  140. approvals, err := sess.Count(new(Review))
  141. if err != nil {
  142. log.Error("GetGrantedApprovalsCount: %v", err)
  143. return 0
  144. }
  145. return approvals
  146. }
  147. // MergeBlockedByRejectedReview returns true if merge is blocked by rejected reviews
  148. func (protectBranch *ProtectedBranch) MergeBlockedByRejectedReview(pr *PullRequest) bool {
  149. if !protectBranch.BlockOnRejectedReviews {
  150. return false
  151. }
  152. rejectExist, err := x.Where("issue_id = ?", pr.IssueID).
  153. And("type = ?", ReviewTypeReject).
  154. And("official = ?", true).
  155. Exist(new(Review))
  156. if err != nil {
  157. log.Error("MergeBlockedByRejectedReview: %v", err)
  158. return true
  159. }
  160. return rejectExist
  161. }
  162. // MergeBlockedByOfficialReviewRequests block merge because of some review request to official reviewer
  163. // of from official review
  164. func (protectBranch *ProtectedBranch) MergeBlockedByOfficialReviewRequests(pr *PullRequest) bool {
  165. if !protectBranch.BlockOnOfficialReviewRequests {
  166. return false
  167. }
  168. has, err := x.Where("issue_id = ?", pr.IssueID).
  169. And("type = ?", ReviewTypeRequest).
  170. And("official = ?", true).
  171. Exist(new(Review))
  172. if err != nil {
  173. log.Error("MergeBlockedByOfficialReviewRequests: %v", err)
  174. return true
  175. }
  176. return has
  177. }
  178. // MergeBlockedByOutdatedBranch returns true if merge is blocked by an outdated head branch
  179. func (protectBranch *ProtectedBranch) MergeBlockedByOutdatedBranch(pr *PullRequest) bool {
  180. return protectBranch.BlockOnOutdatedBranch && pr.CommitsBehind > 0
  181. }
  182. // GetProtectedFilePatterns parses a semicolon separated list of protected file patterns and returns a glob.Glob slice
  183. func (protectBranch *ProtectedBranch) GetProtectedFilePatterns() []glob.Glob {
  184. extarr := make([]glob.Glob, 0, 10)
  185. for _, expr := range strings.Split(strings.ToLower(protectBranch.ProtectedFilePatterns), ";") {
  186. expr = strings.TrimSpace(expr)
  187. if expr != "" {
  188. if g, err := glob.Compile(expr, '.', '/'); err != nil {
  189. log.Info("Invalid glob expresion '%s' (skipped): %v", expr, err)
  190. } else {
  191. extarr = append(extarr, g)
  192. }
  193. }
  194. }
  195. return extarr
  196. }
  197. // MergeBlockedByProtectedFiles returns true if merge is blocked by protected files change
  198. func (protectBranch *ProtectedBranch) MergeBlockedByProtectedFiles(pr *PullRequest) bool {
  199. glob := protectBranch.GetProtectedFilePatterns()
  200. if len(glob) == 0 {
  201. return false
  202. }
  203. return len(pr.ChangedProtectedFiles) > 0
  204. }
  205. // IsProtectedFile return if path is protected
  206. func (protectBranch *ProtectedBranch) IsProtectedFile(patterns []glob.Glob, path string) bool {
  207. if len(patterns) == 0 {
  208. patterns = protectBranch.GetProtectedFilePatterns()
  209. if len(patterns) == 0 {
  210. return false
  211. }
  212. }
  213. lpath := strings.ToLower(strings.TrimSpace(path))
  214. r := false
  215. for _, pat := range patterns {
  216. if pat.Match(lpath) {
  217. r = true
  218. break
  219. }
  220. }
  221. return r
  222. }
  223. // GetProtectedBranchByRepoID getting protected branch by repo ID
  224. func GetProtectedBranchByRepoID(repoID int64) ([]*ProtectedBranch, error) {
  225. protectedBranches := make([]*ProtectedBranch, 0)
  226. return protectedBranches, x.Where("repo_id = ?", repoID).Desc("updated_unix").Find(&protectedBranches)
  227. }
  228. // GetProtectedBranchBy getting protected branch by ID/Name
  229. func GetProtectedBranchBy(repoID int64, branchName string) (*ProtectedBranch, error) {
  230. return getProtectedBranchBy(x, repoID, branchName)
  231. }
  232. func getProtectedBranchBy(e Engine, repoID int64, branchName string) (*ProtectedBranch, error) {
  233. rel := &ProtectedBranch{RepoID: repoID, BranchName: branchName}
  234. has, err := e.Get(rel)
  235. if err != nil {
  236. return nil, err
  237. }
  238. if !has {
  239. return nil, nil
  240. }
  241. return rel, nil
  242. }
  243. // GetProtectedBranchByID getting protected branch by ID
  244. func GetProtectedBranchByID(id int64) (*ProtectedBranch, error) {
  245. rel := &ProtectedBranch{}
  246. has, err := x.ID(id).Get(rel)
  247. if err != nil {
  248. return nil, err
  249. }
  250. if !has {
  251. return nil, nil
  252. }
  253. return rel, nil
  254. }
  255. // WhitelistOptions represent all sorts of whitelists used for protected branches
  256. type WhitelistOptions struct {
  257. UserIDs []int64
  258. TeamIDs []int64
  259. MergeUserIDs []int64
  260. MergeTeamIDs []int64
  261. ApprovalsUserIDs []int64
  262. ApprovalsTeamIDs []int64
  263. }
  264. // UpdateProtectBranch saves branch protection options of repository.
  265. // If ID is 0, it creates a new record. Otherwise, updates existing record.
  266. // This function also performs check if whitelist user and team's IDs have been changed
  267. // to avoid unnecessary whitelist delete and regenerate.
  268. func UpdateProtectBranch(repo *Repository, protectBranch *ProtectedBranch, opts WhitelistOptions) (err error) {
  269. if err = repo.GetOwner(); err != nil {
  270. return fmt.Errorf("GetOwner: %v", err)
  271. }
  272. whitelist, err := updateUserWhitelist(repo, protectBranch.WhitelistUserIDs, opts.UserIDs)
  273. if err != nil {
  274. return err
  275. }
  276. protectBranch.WhitelistUserIDs = whitelist
  277. whitelist, err = updateUserWhitelist(repo, protectBranch.MergeWhitelistUserIDs, opts.MergeUserIDs)
  278. if err != nil {
  279. return err
  280. }
  281. protectBranch.MergeWhitelistUserIDs = whitelist
  282. whitelist, err = updateApprovalWhitelist(repo, protectBranch.ApprovalsWhitelistUserIDs, opts.ApprovalsUserIDs)
  283. if err != nil {
  284. return err
  285. }
  286. protectBranch.ApprovalsWhitelistUserIDs = whitelist
  287. // if the repo is in an organization
  288. whitelist, err = updateTeamWhitelist(repo, protectBranch.WhitelistTeamIDs, opts.TeamIDs)
  289. if err != nil {
  290. return err
  291. }
  292. protectBranch.WhitelistTeamIDs = whitelist
  293. whitelist, err = updateTeamWhitelist(repo, protectBranch.MergeWhitelistTeamIDs, opts.MergeTeamIDs)
  294. if err != nil {
  295. return err
  296. }
  297. protectBranch.MergeWhitelistTeamIDs = whitelist
  298. whitelist, err = updateTeamWhitelist(repo, protectBranch.ApprovalsWhitelistTeamIDs, opts.ApprovalsTeamIDs)
  299. if err != nil {
  300. return err
  301. }
  302. protectBranch.ApprovalsWhitelistTeamIDs = whitelist
  303. // Make sure protectBranch.ID is not 0 for whitelists
  304. if protectBranch.ID == 0 {
  305. if _, err = x.Insert(protectBranch); err != nil {
  306. return fmt.Errorf("Insert: %v", err)
  307. }
  308. return nil
  309. }
  310. if _, err = x.ID(protectBranch.ID).AllCols().Update(protectBranch); err != nil {
  311. return fmt.Errorf("Update: %v", err)
  312. }
  313. return nil
  314. }
  315. // GetProtectedBranches get all protected branches
  316. func (repo *Repository) GetProtectedBranches() ([]*ProtectedBranch, error) {
  317. protectedBranches := make([]*ProtectedBranch, 0)
  318. return protectedBranches, x.Find(&protectedBranches, &ProtectedBranch{RepoID: repo.ID})
  319. }
  320. // GetBranchProtection get the branch protection of a branch
  321. func (repo *Repository) GetBranchProtection(branchName string) (*ProtectedBranch, error) {
  322. return GetProtectedBranchBy(repo.ID, branchName)
  323. }
  324. // IsProtectedBranch checks if branch is protected
  325. func (repo *Repository) IsProtectedBranch(branchName string, doer *User) (bool, error) {
  326. if doer == nil {
  327. return true, nil
  328. }
  329. protectedBranch := &ProtectedBranch{
  330. RepoID: repo.ID,
  331. BranchName: branchName,
  332. }
  333. has, err := x.Exist(protectedBranch)
  334. if err != nil {
  335. return true, err
  336. }
  337. return has, nil
  338. }
  339. // IsProtectedBranchForPush checks if branch is protected for push
  340. func (repo *Repository) IsProtectedBranchForPush(branchName string, doer *User) (bool, error) {
  341. if doer == nil {
  342. return true, nil
  343. }
  344. protectedBranch := &ProtectedBranch{
  345. RepoID: repo.ID,
  346. BranchName: branchName,
  347. }
  348. has, err := x.Get(protectedBranch)
  349. if err != nil {
  350. return true, err
  351. } else if has {
  352. return !protectedBranch.CanUserPush(doer.ID), nil
  353. }
  354. return false, nil
  355. }
  356. // updateApprovalWhitelist checks whether the user whitelist changed and returns a whitelist with
  357. // the users from newWhitelist which have explicit read or write access to the repo.
  358. func updateApprovalWhitelist(repo *Repository, currentWhitelist, newWhitelist []int64) (whitelist []int64, err error) {
  359. hasUsersChanged := !util.IsSliceInt64Eq(currentWhitelist, newWhitelist)
  360. if !hasUsersChanged {
  361. return currentWhitelist, nil
  362. }
  363. whitelist = make([]int64, 0, len(newWhitelist))
  364. for _, userID := range newWhitelist {
  365. if reader, err := repo.IsReader(userID); err != nil {
  366. return nil, err
  367. } else if !reader {
  368. continue
  369. }
  370. whitelist = append(whitelist, userID)
  371. }
  372. return
  373. }
  374. // updateUserWhitelist checks whether the user whitelist changed and returns a whitelist with
  375. // the users from newWhitelist which have write access to the repo.
  376. func updateUserWhitelist(repo *Repository, currentWhitelist, newWhitelist []int64) (whitelist []int64, err error) {
  377. hasUsersChanged := !util.IsSliceInt64Eq(currentWhitelist, newWhitelist)
  378. if !hasUsersChanged {
  379. return currentWhitelist, nil
  380. }
  381. whitelist = make([]int64, 0, len(newWhitelist))
  382. for _, userID := range newWhitelist {
  383. user, err := GetUserByID(userID)
  384. if err != nil {
  385. return nil, fmt.Errorf("GetUserByID [user_id: %d, repo_id: %d]: %v", userID, repo.ID, err)
  386. }
  387. perm, err := GetUserRepoPermission(repo, user)
  388. if err != nil {
  389. return nil, fmt.Errorf("GetUserRepoPermission [user_id: %d, repo_id: %d]: %v", userID, repo.ID, err)
  390. }
  391. if !perm.CanWrite(UnitTypeCode) {
  392. continue // Drop invalid user ID
  393. }
  394. whitelist = append(whitelist, userID)
  395. }
  396. return
  397. }
  398. // updateTeamWhitelist checks whether the team whitelist changed and returns a whitelist with
  399. // the teams from newWhitelist which have write access to the repo.
  400. func updateTeamWhitelist(repo *Repository, currentWhitelist, newWhitelist []int64) (whitelist []int64, err error) {
  401. hasTeamsChanged := !util.IsSliceInt64Eq(currentWhitelist, newWhitelist)
  402. if !hasTeamsChanged {
  403. return currentWhitelist, nil
  404. }
  405. teams, err := GetTeamsWithAccessToRepo(repo.OwnerID, repo.ID, AccessModeRead)
  406. if err != nil {
  407. return nil, fmt.Errorf("GetTeamsWithAccessToRepo [org_id: %d, repo_id: %d]: %v", repo.OwnerID, repo.ID, err)
  408. }
  409. whitelist = make([]int64, 0, len(teams))
  410. for i := range teams {
  411. if util.IsInt64InSlice(teams[i].ID, newWhitelist) {
  412. whitelist = append(whitelist, teams[i].ID)
  413. }
  414. }
  415. return
  416. }
  417. // DeleteProtectedBranch removes ProtectedBranch relation between the user and repository.
  418. func (repo *Repository) DeleteProtectedBranch(id int64) (err error) {
  419. protectedBranch := &ProtectedBranch{
  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(protectedBranch); err != nil {
  429. return err
  430. } else if affected != 1 {
  431. return fmt.Errorf("delete protected branch ID(%v) failed", id)
  432. }
  433. return sess.Commit()
  434. }
  435. // DeletedBranch struct
  436. type DeletedBranch struct {
  437. ID int64 `xorm:"pk autoincr"`
  438. RepoID int64 `xorm:"UNIQUE(s) INDEX NOT NULL"`
  439. Name string `xorm:"UNIQUE(s) NOT NULL"`
  440. Commit string `xorm:"UNIQUE(s) NOT NULL"`
  441. DeletedByID int64 `xorm:"INDEX"`
  442. DeletedBy *User `xorm:"-"`
  443. DeletedUnix timeutil.TimeStamp `xorm:"INDEX created"`
  444. }
  445. // AddDeletedBranch adds a deleted branch to the database
  446. func (repo *Repository) AddDeletedBranch(branchName, commit string, deletedByID int64) error {
  447. deletedBranch := &DeletedBranch{
  448. RepoID: repo.ID,
  449. Name: branchName,
  450. Commit: commit,
  451. DeletedByID: deletedByID,
  452. }
  453. sess := x.NewSession()
  454. defer sess.Close()
  455. if err := sess.Begin(); err != nil {
  456. return err
  457. }
  458. if _, err := sess.InsertOne(deletedBranch); err != nil {
  459. return err
  460. }
  461. return sess.Commit()
  462. }
  463. // GetDeletedBranches returns all the deleted branches
  464. func (repo *Repository) GetDeletedBranches() ([]*DeletedBranch, error) {
  465. deletedBranches := make([]*DeletedBranch, 0)
  466. return deletedBranches, x.Where("repo_id = ?", repo.ID).Desc("deleted_unix").Find(&deletedBranches)
  467. }
  468. // GetDeletedBranchByID get a deleted branch by its ID
  469. func (repo *Repository) GetDeletedBranchByID(id int64) (*DeletedBranch, error) {
  470. deletedBranch := &DeletedBranch{}
  471. has, err := x.ID(id).Get(deletedBranch)
  472. if err != nil {
  473. return nil, err
  474. }
  475. if !has {
  476. return nil, nil
  477. }
  478. return deletedBranch, nil
  479. }
  480. // RemoveDeletedBranch removes a deleted branch from the database
  481. func (repo *Repository) RemoveDeletedBranch(id int64) (err error) {
  482. deletedBranch := &DeletedBranch{
  483. RepoID: repo.ID,
  484. ID: id,
  485. }
  486. sess := x.NewSession()
  487. defer sess.Close()
  488. if err = sess.Begin(); err != nil {
  489. return err
  490. }
  491. if affected, err := sess.Delete(deletedBranch); err != nil {
  492. return err
  493. } else if affected != 1 {
  494. return fmt.Errorf("remove deleted branch ID(%v) failed", id)
  495. }
  496. return sess.Commit()
  497. }
  498. // LoadUser loads the user that deleted the branch
  499. // When there's no user found it returns a NewGhostUser
  500. func (deletedBranch *DeletedBranch) LoadUser() {
  501. user, err := GetUserByID(deletedBranch.DeletedByID)
  502. if err != nil {
  503. user = NewGhostUser()
  504. }
  505. deletedBranch.DeletedBy = user
  506. }
  507. // RemoveDeletedBranch removes all deleted branches
  508. func RemoveDeletedBranch(repoID int64, branch string) error {
  509. _, err := x.Where("repo_id=? AND name=?", repoID, branch).Delete(new(DeletedBranch))
  510. return err
  511. }
  512. // RemoveOldDeletedBranches removes old deleted branches
  513. func RemoveOldDeletedBranches(ctx context.Context, olderThan time.Duration) {
  514. // Nothing to do for shutdown or terminate
  515. log.Trace("Doing: DeletedBranchesCleanup")
  516. deleteBefore := time.Now().Add(-olderThan)
  517. _, err := x.Where("deleted_unix < ?", deleteBefore.Unix()).Delete(new(DeletedBranch))
  518. if err != nil {
  519. log.Error("DeletedBranchesCleanup: %v", err)
  520. }
  521. }