You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

branches.go 21KB

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