gitea源码

protected_branch.go 20KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611
  1. // Copyright 2022 The Gitea Authors. All rights reserved.
  2. // SPDX-License-Identifier: MIT
  3. package git
  4. import (
  5. "context"
  6. "errors"
  7. "fmt"
  8. "slices"
  9. "strings"
  10. "code.gitea.io/gitea/models/db"
  11. "code.gitea.io/gitea/models/organization"
  12. "code.gitea.io/gitea/models/perm"
  13. access_model "code.gitea.io/gitea/models/perm/access"
  14. repo_model "code.gitea.io/gitea/models/repo"
  15. "code.gitea.io/gitea/models/unit"
  16. user_model "code.gitea.io/gitea/models/user"
  17. "code.gitea.io/gitea/modules/glob"
  18. "code.gitea.io/gitea/modules/log"
  19. "code.gitea.io/gitea/modules/timeutil"
  20. "code.gitea.io/gitea/modules/util"
  21. "xorm.io/builder"
  22. )
  23. var ErrBranchIsProtected = errors.New("branch is protected")
  24. // ProtectedBranch struct
  25. type ProtectedBranch struct {
  26. ID int64 `xorm:"pk autoincr"`
  27. RepoID int64 `xorm:"UNIQUE(s)"`
  28. Repo *repo_model.Repository `xorm:"-"`
  29. RuleName string `xorm:"'branch_name' UNIQUE(s)"` // a branch name or a glob match to branch name
  30. Priority int64 `xorm:"NOT NULL DEFAULT 0"`
  31. globRule glob.Glob `xorm:"-"`
  32. isPlainName bool `xorm:"-"`
  33. CanPush bool `xorm:"NOT NULL DEFAULT false"`
  34. EnableWhitelist bool
  35. WhitelistUserIDs []int64 `xorm:"JSON TEXT"`
  36. WhitelistTeamIDs []int64 `xorm:"JSON TEXT"`
  37. EnableMergeWhitelist bool `xorm:"NOT NULL DEFAULT false"`
  38. WhitelistDeployKeys bool `xorm:"NOT NULL DEFAULT false"`
  39. MergeWhitelistUserIDs []int64 `xorm:"JSON TEXT"`
  40. MergeWhitelistTeamIDs []int64 `xorm:"JSON TEXT"`
  41. CanForcePush bool `xorm:"NOT NULL DEFAULT false"`
  42. EnableForcePushAllowlist bool `xorm:"NOT NULL DEFAULT false"`
  43. ForcePushAllowlistUserIDs []int64 `xorm:"JSON TEXT"`
  44. ForcePushAllowlistTeamIDs []int64 `xorm:"JSON TEXT"`
  45. ForcePushAllowlistDeployKeys bool `xorm:"NOT NULL DEFAULT false"`
  46. EnableStatusCheck bool `xorm:"NOT NULL DEFAULT false"`
  47. StatusCheckContexts []string `xorm:"JSON TEXT"`
  48. EnableApprovalsWhitelist bool `xorm:"NOT NULL DEFAULT false"`
  49. ApprovalsWhitelistUserIDs []int64 `xorm:"JSON TEXT"`
  50. ApprovalsWhitelistTeamIDs []int64 `xorm:"JSON TEXT"`
  51. RequiredApprovals int64 `xorm:"NOT NULL DEFAULT 0"`
  52. BlockOnRejectedReviews bool `xorm:"NOT NULL DEFAULT false"`
  53. BlockOnOfficialReviewRequests bool `xorm:"NOT NULL DEFAULT false"`
  54. BlockOnOutdatedBranch bool `xorm:"NOT NULL DEFAULT false"`
  55. DismissStaleApprovals bool `xorm:"NOT NULL DEFAULT false"`
  56. IgnoreStaleApprovals bool `xorm:"NOT NULL DEFAULT false"`
  57. RequireSignedCommits bool `xorm:"NOT NULL DEFAULT false"`
  58. ProtectedFilePatterns string `xorm:"TEXT"`
  59. UnprotectedFilePatterns string `xorm:"TEXT"`
  60. BlockAdminMergeOverride bool `xorm:"NOT NULL DEFAULT false"`
  61. CreatedUnix timeutil.TimeStamp `xorm:"created"`
  62. UpdatedUnix timeutil.TimeStamp `xorm:"updated"`
  63. }
  64. func init() {
  65. db.RegisterModel(new(ProtectedBranch))
  66. }
  67. // IsRuleNameSpecial return true if it contains special character
  68. func IsRuleNameSpecial(ruleName string) bool {
  69. for i := 0; i < len(ruleName); i++ {
  70. if glob.IsSpecialByte(ruleName[i]) {
  71. return true
  72. }
  73. }
  74. return false
  75. }
  76. func (protectBranch *ProtectedBranch) loadGlob() {
  77. if protectBranch.isPlainName || protectBranch.globRule != nil {
  78. return
  79. }
  80. // detect if it is not glob
  81. if !IsRuleNameSpecial(protectBranch.RuleName) {
  82. protectBranch.isPlainName = true
  83. return
  84. }
  85. // now we load the glob
  86. var err error
  87. protectBranch.globRule, err = glob.Compile(protectBranch.RuleName, '/')
  88. if err != nil {
  89. log.Warn("Invalid glob rule for ProtectedBranch[%d]: %s %v", protectBranch.ID, protectBranch.RuleName, err)
  90. protectBranch.globRule = glob.MustCompile(glob.QuoteMeta(protectBranch.RuleName), '/')
  91. }
  92. }
  93. // Match tests if branchName matches the rule
  94. func (protectBranch *ProtectedBranch) Match(branchName string) bool {
  95. protectBranch.loadGlob()
  96. if protectBranch.isPlainName {
  97. return strings.EqualFold(protectBranch.RuleName, branchName)
  98. }
  99. return protectBranch.globRule.Match(branchName)
  100. }
  101. func (protectBranch *ProtectedBranch) LoadRepo(ctx context.Context) (err error) {
  102. if protectBranch.Repo != nil {
  103. return nil
  104. }
  105. protectBranch.Repo, err = repo_model.GetRepositoryByID(ctx, protectBranch.RepoID)
  106. return err
  107. }
  108. // CanUserPush returns if some user could push to this protected branch
  109. func (protectBranch *ProtectedBranch) CanUserPush(ctx context.Context, user *user_model.User) bool {
  110. if !protectBranch.CanPush {
  111. return false
  112. }
  113. if !protectBranch.EnableWhitelist {
  114. if err := protectBranch.LoadRepo(ctx); err != nil {
  115. log.Error("LoadRepo: %v", err)
  116. return false
  117. }
  118. writeAccess, err := access_model.HasAccessUnit(ctx, user, protectBranch.Repo, unit.TypeCode, perm.AccessModeWrite)
  119. if err != nil {
  120. log.Error("HasAccessUnit: %v", err)
  121. return false
  122. }
  123. return writeAccess
  124. }
  125. if slices.Contains(protectBranch.WhitelistUserIDs, user.ID) {
  126. return true
  127. }
  128. if len(protectBranch.WhitelistTeamIDs) == 0 {
  129. return false
  130. }
  131. in, err := organization.IsUserInTeams(ctx, user.ID, protectBranch.WhitelistTeamIDs)
  132. if err != nil {
  133. log.Error("IsUserInTeams: %v", err)
  134. return false
  135. }
  136. return in
  137. }
  138. // CanUserForcePush returns if some user could force push to this protected branch
  139. // Since force-push extends normal push, we also check if user has regular push access
  140. func (protectBranch *ProtectedBranch) CanUserForcePush(ctx context.Context, user *user_model.User) bool {
  141. if !protectBranch.CanForcePush {
  142. return false
  143. }
  144. if !protectBranch.EnableForcePushAllowlist {
  145. return protectBranch.CanUserPush(ctx, user)
  146. }
  147. if slices.Contains(protectBranch.ForcePushAllowlistUserIDs, user.ID) {
  148. return protectBranch.CanUserPush(ctx, user)
  149. }
  150. if len(protectBranch.ForcePushAllowlistTeamIDs) == 0 {
  151. return false
  152. }
  153. in, err := organization.IsUserInTeams(ctx, user.ID, protectBranch.ForcePushAllowlistTeamIDs)
  154. if err != nil {
  155. log.Error("IsUserInTeams: %v", err)
  156. return false
  157. }
  158. return in && protectBranch.CanUserPush(ctx, user)
  159. }
  160. // IsUserMergeWhitelisted checks if some user is whitelisted to merge to this branch
  161. func IsUserMergeWhitelisted(ctx context.Context, protectBranch *ProtectedBranch, userID int64, permissionInRepo access_model.Permission) bool {
  162. if !protectBranch.EnableMergeWhitelist {
  163. // Then we need to fall back on whether the user has write permission
  164. return permissionInRepo.CanWrite(unit.TypeCode)
  165. }
  166. if slices.Contains(protectBranch.MergeWhitelistUserIDs, userID) {
  167. return true
  168. }
  169. if len(protectBranch.MergeWhitelistTeamIDs) == 0 {
  170. return false
  171. }
  172. in, err := organization.IsUserInTeams(ctx, userID, protectBranch.MergeWhitelistTeamIDs)
  173. if err != nil {
  174. log.Error("IsUserInTeams: %v", err)
  175. return false
  176. }
  177. return in
  178. }
  179. // IsUserOfficialReviewer check if user is official reviewer for the branch (counts towards required approvals)
  180. func IsUserOfficialReviewer(ctx context.Context, protectBranch *ProtectedBranch, user *user_model.User) (bool, error) {
  181. repo, err := repo_model.GetRepositoryByID(ctx, protectBranch.RepoID)
  182. if err != nil {
  183. return false, err
  184. }
  185. if !protectBranch.EnableApprovalsWhitelist {
  186. // Anyone with write access is considered official reviewer
  187. writeAccess, err := access_model.HasAccessUnit(ctx, user, repo, unit.TypeCode, perm.AccessModeWrite)
  188. if err != nil {
  189. return false, err
  190. }
  191. return writeAccess, nil
  192. }
  193. if slices.Contains(protectBranch.ApprovalsWhitelistUserIDs, user.ID) {
  194. return true, nil
  195. }
  196. inTeam, err := organization.IsUserInTeams(ctx, user.ID, protectBranch.ApprovalsWhitelistTeamIDs)
  197. if err != nil {
  198. return false, err
  199. }
  200. return inTeam, nil
  201. }
  202. // GetProtectedFilePatterns parses a semicolon separated list of protected file patterns and returns a glob.Glob slice
  203. func (protectBranch *ProtectedBranch) GetProtectedFilePatterns() []glob.Glob {
  204. return getFilePatterns(protectBranch.ProtectedFilePatterns)
  205. }
  206. // GetUnprotectedFilePatterns parses a semicolon separated list of unprotected file patterns and returns a glob.Glob slice
  207. func (protectBranch *ProtectedBranch) GetUnprotectedFilePatterns() []glob.Glob {
  208. return getFilePatterns(protectBranch.UnprotectedFilePatterns)
  209. }
  210. func getFilePatterns(filePatterns string) []glob.Glob {
  211. extarr := make([]glob.Glob, 0, 10)
  212. for expr := range strings.SplitSeq(strings.ToLower(filePatterns), ";") {
  213. expr = strings.TrimSpace(expr)
  214. if expr != "" {
  215. if g, err := glob.Compile(expr, '.', '/'); err != nil {
  216. log.Info("Invalid glob expression '%s' (skipped): %v", expr, err)
  217. } else {
  218. extarr = append(extarr, g)
  219. }
  220. }
  221. }
  222. return extarr
  223. }
  224. // MergeBlockedByProtectedFiles returns true if merge is blocked by protected files change
  225. func (protectBranch *ProtectedBranch) MergeBlockedByProtectedFiles(changedProtectedFiles []string) bool {
  226. glob := protectBranch.GetProtectedFilePatterns()
  227. if len(glob) == 0 {
  228. return false
  229. }
  230. return len(changedProtectedFiles) > 0
  231. }
  232. // IsProtectedFile return if path is protected
  233. func (protectBranch *ProtectedBranch) IsProtectedFile(patterns []glob.Glob, path string) bool {
  234. if len(patterns) == 0 {
  235. patterns = protectBranch.GetProtectedFilePatterns()
  236. if len(patterns) == 0 {
  237. return false
  238. }
  239. }
  240. lpath := strings.ToLower(strings.TrimSpace(path))
  241. r := false
  242. for _, pat := range patterns {
  243. if pat.Match(lpath) {
  244. r = true
  245. break
  246. }
  247. }
  248. return r
  249. }
  250. // IsUnprotectedFile return if path is unprotected
  251. func (protectBranch *ProtectedBranch) IsUnprotectedFile(patterns []glob.Glob, path string) bool {
  252. if len(patterns) == 0 {
  253. patterns = protectBranch.GetUnprotectedFilePatterns()
  254. if len(patterns) == 0 {
  255. return false
  256. }
  257. }
  258. lpath := strings.ToLower(strings.TrimSpace(path))
  259. r := false
  260. for _, pat := range patterns {
  261. if pat.Match(lpath) {
  262. r = true
  263. break
  264. }
  265. }
  266. return r
  267. }
  268. // GetProtectedBranchRuleByName getting protected branch rule by name
  269. func GetProtectedBranchRuleByName(ctx context.Context, repoID int64, ruleName string) (*ProtectedBranch, error) {
  270. // branch_name is legacy name, it actually is rule name
  271. rel, exist, err := db.Get[ProtectedBranch](ctx, builder.Eq{"repo_id": repoID, "branch_name": ruleName})
  272. if err != nil {
  273. return nil, err
  274. } else if !exist {
  275. return nil, nil
  276. }
  277. return rel, nil
  278. }
  279. // GetProtectedBranchRuleByID getting protected branch rule by rule ID
  280. func GetProtectedBranchRuleByID(ctx context.Context, repoID, ruleID int64) (*ProtectedBranch, error) {
  281. rel, exist, err := db.Get[ProtectedBranch](ctx, builder.Eq{"repo_id": repoID, "id": ruleID})
  282. if err != nil {
  283. return nil, err
  284. } else if !exist {
  285. return nil, nil
  286. }
  287. return rel, nil
  288. }
  289. // WhitelistOptions represent all sorts of whitelists used for protected branches
  290. type WhitelistOptions struct {
  291. UserIDs []int64
  292. TeamIDs []int64
  293. ForcePushUserIDs []int64
  294. ForcePushTeamIDs []int64
  295. MergeUserIDs []int64
  296. MergeTeamIDs []int64
  297. ApprovalsUserIDs []int64
  298. ApprovalsTeamIDs []int64
  299. }
  300. // UpdateProtectBranch saves branch protection options of repository.
  301. // If ID is 0, it creates a new record. Otherwise, updates existing record.
  302. // This function also performs check if whitelist user and team's IDs have been changed
  303. // to avoid unnecessary whitelist delete and regenerate.
  304. func UpdateProtectBranch(ctx context.Context, repo *repo_model.Repository, protectBranch *ProtectedBranch, opts WhitelistOptions) (err error) {
  305. err = repo.MustNotBeArchived()
  306. if err != nil {
  307. return err
  308. }
  309. if err = repo.LoadOwner(ctx); err != nil {
  310. return fmt.Errorf("LoadOwner: %v", err)
  311. }
  312. whitelist, err := updateUserWhitelist(ctx, repo, protectBranch.WhitelistUserIDs, opts.UserIDs)
  313. if err != nil {
  314. return err
  315. }
  316. protectBranch.WhitelistUserIDs = whitelist
  317. whitelist, err = updateUserWhitelist(ctx, repo, protectBranch.ForcePushAllowlistUserIDs, opts.ForcePushUserIDs)
  318. if err != nil {
  319. return err
  320. }
  321. protectBranch.ForcePushAllowlistUserIDs = whitelist
  322. whitelist, err = updateUserWhitelist(ctx, repo, protectBranch.MergeWhitelistUserIDs, opts.MergeUserIDs)
  323. if err != nil {
  324. return err
  325. }
  326. protectBranch.MergeWhitelistUserIDs = whitelist
  327. whitelist, err = updateApprovalWhitelist(ctx, repo, protectBranch.ApprovalsWhitelistUserIDs, opts.ApprovalsUserIDs)
  328. if err != nil {
  329. return err
  330. }
  331. protectBranch.ApprovalsWhitelistUserIDs = whitelist
  332. // if the repo is in an organization
  333. whitelist, err = updateTeamWhitelist(ctx, repo, protectBranch.WhitelistTeamIDs, opts.TeamIDs)
  334. if err != nil {
  335. return err
  336. }
  337. protectBranch.WhitelistTeamIDs = whitelist
  338. whitelist, err = updateTeamWhitelist(ctx, repo, protectBranch.ForcePushAllowlistTeamIDs, opts.ForcePushTeamIDs)
  339. if err != nil {
  340. return err
  341. }
  342. protectBranch.ForcePushAllowlistTeamIDs = whitelist
  343. whitelist, err = updateTeamWhitelist(ctx, repo, protectBranch.MergeWhitelistTeamIDs, opts.MergeTeamIDs)
  344. if err != nil {
  345. return err
  346. }
  347. protectBranch.MergeWhitelistTeamIDs = whitelist
  348. whitelist, err = updateTeamWhitelist(ctx, repo, protectBranch.ApprovalsWhitelistTeamIDs, opts.ApprovalsTeamIDs)
  349. if err != nil {
  350. return err
  351. }
  352. protectBranch.ApprovalsWhitelistTeamIDs = whitelist
  353. // Looks like it's a new rule
  354. if protectBranch.ID == 0 {
  355. // as it's a new rule and if priority was not set, we need to calc it.
  356. if protectBranch.Priority == 0 {
  357. var lowestPrio int64
  358. // because of mssql we can not use builder or save xorm syntax, so raw sql it is
  359. if _, err := db.GetEngine(ctx).SQL(`SELECT MAX(priority) FROM protected_branch WHERE repo_id = ?`, protectBranch.RepoID).
  360. Get(&lowestPrio); err != nil {
  361. return err
  362. }
  363. log.Trace("Create new ProtectedBranch at repo[%d] and detect current lowest priority '%d'", protectBranch.RepoID, lowestPrio)
  364. protectBranch.Priority = lowestPrio + 1
  365. }
  366. if _, err = db.GetEngine(ctx).Insert(protectBranch); err != nil {
  367. return fmt.Errorf("Insert: %v", err)
  368. }
  369. return nil
  370. }
  371. // update the rule
  372. if _, err = db.GetEngine(ctx).ID(protectBranch.ID).AllCols().Update(protectBranch); err != nil {
  373. return fmt.Errorf("Update: %v", err)
  374. }
  375. return nil
  376. }
  377. func UpdateProtectBranchPriorities(ctx context.Context, repo *repo_model.Repository, ids []int64) error {
  378. prio := int64(1)
  379. return db.WithTx(ctx, func(ctx context.Context) error {
  380. for _, id := range ids {
  381. if _, err := db.GetEngine(ctx).
  382. ID(id).Where("repo_id = ?", repo.ID).
  383. Cols("priority").
  384. Update(&ProtectedBranch{
  385. Priority: prio,
  386. }); err != nil {
  387. return err
  388. }
  389. prio++
  390. }
  391. return nil
  392. })
  393. }
  394. // updateApprovalWhitelist checks whether the user whitelist changed and returns a whitelist with
  395. // the users from newWhitelist which have explicit read or write access to the repo.
  396. func updateApprovalWhitelist(ctx context.Context, repo *repo_model.Repository, currentWhitelist, newWhitelist []int64) (whitelist []int64, err error) {
  397. hasUsersChanged := !util.SliceSortedEqual(currentWhitelist, newWhitelist)
  398. if !hasUsersChanged {
  399. return currentWhitelist, nil
  400. }
  401. whitelist = make([]int64, 0, len(newWhitelist))
  402. for _, userID := range newWhitelist {
  403. if reader, err := access_model.IsRepoReader(ctx, repo, userID); err != nil {
  404. return nil, err
  405. } else if !reader {
  406. continue
  407. }
  408. whitelist = append(whitelist, userID)
  409. }
  410. return whitelist, err
  411. }
  412. // updateUserWhitelist checks whether the user whitelist changed and returns a whitelist with
  413. // the users from newWhitelist which have write access to the repo.
  414. func updateUserWhitelist(ctx context.Context, repo *repo_model.Repository, currentWhitelist, newWhitelist []int64) (whitelist []int64, err error) {
  415. hasUsersChanged := !util.SliceSortedEqual(currentWhitelist, newWhitelist)
  416. if !hasUsersChanged {
  417. return currentWhitelist, nil
  418. }
  419. whitelist = make([]int64, 0, len(newWhitelist))
  420. for _, userID := range newWhitelist {
  421. user, err := user_model.GetUserByID(ctx, userID)
  422. if err != nil {
  423. return nil, fmt.Errorf("GetUserByID [user_id: %d, repo_id: %d]: %v", userID, repo.ID, err)
  424. }
  425. perm, err := access_model.GetUserRepoPermission(ctx, repo, user)
  426. if err != nil {
  427. return nil, fmt.Errorf("GetUserRepoPermission [user_id: %d, repo_id: %d]: %v", userID, repo.ID, err)
  428. }
  429. if !perm.CanWrite(unit.TypeCode) {
  430. continue // Drop invalid user ID
  431. }
  432. whitelist = append(whitelist, userID)
  433. }
  434. return whitelist, err
  435. }
  436. // updateTeamWhitelist checks whether the team whitelist changed and returns a whitelist with
  437. // the teams from newWhitelist which have write access to the repo.
  438. func updateTeamWhitelist(ctx context.Context, repo *repo_model.Repository, currentWhitelist, newWhitelist []int64) (whitelist []int64, err error) {
  439. hasTeamsChanged := !util.SliceSortedEqual(currentWhitelist, newWhitelist)
  440. if !hasTeamsChanged {
  441. return currentWhitelist, nil
  442. }
  443. teams, err := organization.GetTeamsWithAccessToAnyRepoUnit(ctx, repo.OwnerID, repo.ID, perm.AccessModeRead, unit.TypeCode, unit.TypePullRequests)
  444. if err != nil {
  445. return nil, fmt.Errorf("GetTeamsWithAccessToRepo [org_id: %d, repo_id: %d]: %v", repo.OwnerID, repo.ID, err)
  446. }
  447. whitelist = make([]int64, 0, len(teams))
  448. for i := range teams {
  449. if slices.Contains(newWhitelist, teams[i].ID) {
  450. whitelist = append(whitelist, teams[i].ID)
  451. }
  452. }
  453. return whitelist, err
  454. }
  455. // DeleteProtectedBranch removes ProtectedBranch relation between the user and repository.
  456. func DeleteProtectedBranch(ctx context.Context, repo *repo_model.Repository, id int64) (err error) {
  457. err = repo.MustNotBeArchived()
  458. if err != nil {
  459. return err
  460. }
  461. protectedBranch := &ProtectedBranch{
  462. RepoID: repo.ID,
  463. ID: id,
  464. }
  465. if affected, err := db.GetEngine(ctx).Delete(protectedBranch); err != nil {
  466. return err
  467. } else if affected != 1 {
  468. return fmt.Errorf("delete protected branch ID(%v) failed", id)
  469. }
  470. return nil
  471. }
  472. // removeIDsFromProtectedBranch is a helper function to remove IDs from protected branch options
  473. func removeIDsFromProtectedBranch(ctx context.Context, p *ProtectedBranch, userID, teamID int64, columnNames []string) error {
  474. lenUserIDs, lenForcePushIDs, lenApprovalIDs, lenMergeIDs := len(p.WhitelistUserIDs), len(p.ForcePushAllowlistUserIDs), len(p.ApprovalsWhitelistUserIDs), len(p.MergeWhitelistUserIDs)
  475. lenTeamIDs, lenForcePushTeamIDs, lenApprovalTeamIDs, lenMergeTeamIDs := len(p.WhitelistTeamIDs), len(p.ForcePushAllowlistTeamIDs), len(p.ApprovalsWhitelistTeamIDs), len(p.MergeWhitelistTeamIDs)
  476. if userID > 0 {
  477. p.WhitelistUserIDs = util.SliceRemoveAll(p.WhitelistUserIDs, userID)
  478. p.ForcePushAllowlistUserIDs = util.SliceRemoveAll(p.ForcePushAllowlistUserIDs, userID)
  479. p.ApprovalsWhitelistUserIDs = util.SliceRemoveAll(p.ApprovalsWhitelistUserIDs, userID)
  480. p.MergeWhitelistUserIDs = util.SliceRemoveAll(p.MergeWhitelistUserIDs, userID)
  481. }
  482. if teamID > 0 {
  483. p.WhitelistTeamIDs = util.SliceRemoveAll(p.WhitelistTeamIDs, teamID)
  484. p.ForcePushAllowlistTeamIDs = util.SliceRemoveAll(p.ForcePushAllowlistTeamIDs, teamID)
  485. p.ApprovalsWhitelistTeamIDs = util.SliceRemoveAll(p.ApprovalsWhitelistTeamIDs, teamID)
  486. p.MergeWhitelistTeamIDs = util.SliceRemoveAll(p.MergeWhitelistTeamIDs, teamID)
  487. }
  488. if (lenUserIDs != len(p.WhitelistUserIDs) ||
  489. lenForcePushIDs != len(p.ForcePushAllowlistUserIDs) ||
  490. lenApprovalIDs != len(p.ApprovalsWhitelistUserIDs) ||
  491. lenMergeIDs != len(p.MergeWhitelistUserIDs)) ||
  492. (lenTeamIDs != len(p.WhitelistTeamIDs) ||
  493. lenForcePushTeamIDs != len(p.ForcePushAllowlistTeamIDs) ||
  494. lenApprovalTeamIDs != len(p.ApprovalsWhitelistTeamIDs) ||
  495. lenMergeTeamIDs != len(p.MergeWhitelistTeamIDs)) {
  496. if _, err := db.GetEngine(ctx).ID(p.ID).Cols(columnNames...).Update(p); err != nil {
  497. return fmt.Errorf("updateProtectedBranches: %v", err)
  498. }
  499. }
  500. return nil
  501. }
  502. // RemoveUserIDFromProtectedBranch removes all user ids from protected branch options
  503. func RemoveUserIDFromProtectedBranch(ctx context.Context, p *ProtectedBranch, userID int64) error {
  504. columnNames := []string{
  505. "whitelist_user_i_ds",
  506. "force_push_allowlist_user_i_ds",
  507. "merge_whitelist_user_i_ds",
  508. "approvals_whitelist_user_i_ds",
  509. }
  510. return removeIDsFromProtectedBranch(ctx, p, userID, 0, columnNames)
  511. }
  512. // RemoveTeamIDFromProtectedBranch removes all team ids from protected branch options
  513. func RemoveTeamIDFromProtectedBranch(ctx context.Context, p *ProtectedBranch, teamID int64) error {
  514. columnNames := []string{
  515. "whitelist_team_i_ds",
  516. "force_push_allowlist_team_i_ds",
  517. "merge_whitelist_team_i_ds",
  518. "approvals_whitelist_team_i_ds",
  519. }
  520. return removeIDsFromProtectedBranch(ctx, p, 0, teamID, columnNames)
  521. }