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

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669
  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(ctx context.Context, repoID int64, branchName string) (*ProtectedBranch, error) {
  265. rel := &ProtectedBranch{RepoID: repoID, BranchName: branchName}
  266. has, err := db.GetByBean(ctx, rel)
  267. if err != nil {
  268. return nil, err
  269. }
  270. if !has {
  271. return nil, nil
  272. }
  273. return rel, nil
  274. }
  275. // WhitelistOptions represent all sorts of whitelists used for protected branches
  276. type WhitelistOptions struct {
  277. UserIDs []int64
  278. TeamIDs []int64
  279. MergeUserIDs []int64
  280. MergeTeamIDs []int64
  281. ApprovalsUserIDs []int64
  282. ApprovalsTeamIDs []int64
  283. }
  284. // UpdateProtectBranch saves branch protection options of repository.
  285. // If ID is 0, it creates a new record. Otherwise, updates existing record.
  286. // This function also performs check if whitelist user and team's IDs have been changed
  287. // to avoid unnecessary whitelist delete and regenerate.
  288. func UpdateProtectBranch(ctx context.Context, repo *repo_model.Repository, protectBranch *ProtectedBranch, opts WhitelistOptions) (err error) {
  289. if err = repo.GetOwner(ctx); err != nil {
  290. return fmt.Errorf("GetOwner: %v", err)
  291. }
  292. whitelist, err := updateUserWhitelist(ctx, repo, protectBranch.WhitelistUserIDs, opts.UserIDs)
  293. if err != nil {
  294. return err
  295. }
  296. protectBranch.WhitelistUserIDs = whitelist
  297. whitelist, err = updateUserWhitelist(ctx, repo, protectBranch.MergeWhitelistUserIDs, opts.MergeUserIDs)
  298. if err != nil {
  299. return err
  300. }
  301. protectBranch.MergeWhitelistUserIDs = whitelist
  302. whitelist, err = updateApprovalWhitelist(ctx, repo, protectBranch.ApprovalsWhitelistUserIDs, opts.ApprovalsUserIDs)
  303. if err != nil {
  304. return err
  305. }
  306. protectBranch.ApprovalsWhitelistUserIDs = whitelist
  307. // if the repo is in an organization
  308. whitelist, err = updateTeamWhitelist(ctx, repo, protectBranch.WhitelistTeamIDs, opts.TeamIDs)
  309. if err != nil {
  310. return err
  311. }
  312. protectBranch.WhitelistTeamIDs = whitelist
  313. whitelist, err = updateTeamWhitelist(ctx, repo, protectBranch.MergeWhitelistTeamIDs, opts.MergeTeamIDs)
  314. if err != nil {
  315. return err
  316. }
  317. protectBranch.MergeWhitelistTeamIDs = whitelist
  318. whitelist, err = updateTeamWhitelist(ctx, repo, protectBranch.ApprovalsWhitelistTeamIDs, opts.ApprovalsTeamIDs)
  319. if err != nil {
  320. return err
  321. }
  322. protectBranch.ApprovalsWhitelistTeamIDs = whitelist
  323. // Make sure protectBranch.ID is not 0 for whitelists
  324. if protectBranch.ID == 0 {
  325. if _, err = db.GetEngine(ctx).Insert(protectBranch); err != nil {
  326. return fmt.Errorf("Insert: %v", err)
  327. }
  328. return nil
  329. }
  330. if _, err = db.GetEngine(ctx).ID(protectBranch.ID).AllCols().Update(protectBranch); err != nil {
  331. return fmt.Errorf("Update: %v", err)
  332. }
  333. return nil
  334. }
  335. // GetProtectedBranches get all protected branches
  336. func GetProtectedBranches(repoID int64) ([]*ProtectedBranch, error) {
  337. protectedBranches := make([]*ProtectedBranch, 0)
  338. return protectedBranches, db.GetEngine(db.DefaultContext).Find(&protectedBranches, &ProtectedBranch{RepoID: repoID})
  339. }
  340. // IsProtectedBranch checks if branch is protected
  341. func IsProtectedBranch(repoID int64, branchName string) (bool, error) {
  342. protectedBranch := &ProtectedBranch{
  343. RepoID: repoID,
  344. BranchName: branchName,
  345. }
  346. has, err := db.GetEngine(db.DefaultContext).Exist(protectedBranch)
  347. if err != nil {
  348. return true, err
  349. }
  350. return has, nil
  351. }
  352. // updateApprovalWhitelist checks whether the user whitelist changed and returns a whitelist with
  353. // the users from newWhitelist which have explicit read or write access to the repo.
  354. func updateApprovalWhitelist(ctx context.Context, repo *repo_model.Repository, currentWhitelist, newWhitelist []int64) (whitelist []int64, err error) {
  355. hasUsersChanged := !util.IsSliceInt64Eq(currentWhitelist, newWhitelist)
  356. if !hasUsersChanged {
  357. return currentWhitelist, nil
  358. }
  359. whitelist = make([]int64, 0, len(newWhitelist))
  360. for _, userID := range newWhitelist {
  361. if reader, err := access_model.IsRepoReader(ctx, repo, userID); err != nil {
  362. return nil, err
  363. } else if !reader {
  364. continue
  365. }
  366. whitelist = append(whitelist, userID)
  367. }
  368. return
  369. }
  370. // updateUserWhitelist checks whether the user whitelist changed and returns a whitelist with
  371. // the users from newWhitelist which have write access to the repo.
  372. func updateUserWhitelist(ctx context.Context, repo *repo_model.Repository, currentWhitelist, newWhitelist []int64) (whitelist []int64, err error) {
  373. hasUsersChanged := !util.IsSliceInt64Eq(currentWhitelist, newWhitelist)
  374. if !hasUsersChanged {
  375. return currentWhitelist, nil
  376. }
  377. whitelist = make([]int64, 0, len(newWhitelist))
  378. for _, userID := range newWhitelist {
  379. user, err := user_model.GetUserByIDCtx(ctx, userID)
  380. if err != nil {
  381. return nil, fmt.Errorf("GetUserByID [user_id: %d, repo_id: %d]: %v", userID, repo.ID, err)
  382. }
  383. perm, err := access_model.GetUserRepoPermission(ctx, repo, user)
  384. if err != nil {
  385. return nil, fmt.Errorf("GetUserRepoPermission [user_id: %d, repo_id: %d]: %v", userID, repo.ID, err)
  386. }
  387. if !perm.CanWrite(unit.TypeCode) {
  388. continue // Drop invalid user ID
  389. }
  390. whitelist = append(whitelist, userID)
  391. }
  392. return
  393. }
  394. // updateTeamWhitelist checks whether the team whitelist changed and returns a whitelist with
  395. // the teams from newWhitelist which have write access to the repo.
  396. func updateTeamWhitelist(ctx context.Context, repo *repo_model.Repository, currentWhitelist, newWhitelist []int64) (whitelist []int64, err error) {
  397. hasTeamsChanged := !util.IsSliceInt64Eq(currentWhitelist, newWhitelist)
  398. if !hasTeamsChanged {
  399. return currentWhitelist, nil
  400. }
  401. teams, err := organization.GetTeamsWithAccessToRepo(ctx, repo.OwnerID, repo.ID, perm.AccessModeRead)
  402. if err != nil {
  403. return nil, fmt.Errorf("GetTeamsWithAccessToRepo [org_id: %d, repo_id: %d]: %v", repo.OwnerID, repo.ID, err)
  404. }
  405. whitelist = make([]int64, 0, len(teams))
  406. for i := range teams {
  407. if util.IsInt64InSlice(teams[i].ID, newWhitelist) {
  408. whitelist = append(whitelist, teams[i].ID)
  409. }
  410. }
  411. return
  412. }
  413. // DeleteProtectedBranch removes ProtectedBranch relation between the user and repository.
  414. func DeleteProtectedBranch(repoID, id int64) (err error) {
  415. protectedBranch := &ProtectedBranch{
  416. RepoID: repoID,
  417. ID: id,
  418. }
  419. if affected, err := db.GetEngine(db.DefaultContext).Delete(protectedBranch); err != nil {
  420. return err
  421. } else if affected != 1 {
  422. return fmt.Errorf("delete protected branch ID(%v) failed", id)
  423. }
  424. return nil
  425. }
  426. // DeletedBranch struct
  427. type DeletedBranch struct {
  428. ID int64 `xorm:"pk autoincr"`
  429. RepoID int64 `xorm:"UNIQUE(s) INDEX NOT NULL"`
  430. Name string `xorm:"UNIQUE(s) NOT NULL"`
  431. Commit string `xorm:"UNIQUE(s) NOT NULL"`
  432. DeletedByID int64 `xorm:"INDEX"`
  433. DeletedBy *user_model.User `xorm:"-"`
  434. DeletedUnix timeutil.TimeStamp `xorm:"INDEX created"`
  435. }
  436. // AddDeletedBranch adds a deleted branch to the database
  437. func AddDeletedBranch(repoID int64, branchName, commit string, deletedByID int64) error {
  438. deletedBranch := &DeletedBranch{
  439. RepoID: repoID,
  440. Name: branchName,
  441. Commit: commit,
  442. DeletedByID: deletedByID,
  443. }
  444. _, err := db.GetEngine(db.DefaultContext).Insert(deletedBranch)
  445. return err
  446. }
  447. // GetDeletedBranches returns all the deleted branches
  448. func GetDeletedBranches(repoID int64) ([]*DeletedBranch, error) {
  449. deletedBranches := make([]*DeletedBranch, 0)
  450. return deletedBranches, db.GetEngine(db.DefaultContext).Where("repo_id = ?", repoID).Desc("deleted_unix").Find(&deletedBranches)
  451. }
  452. // GetDeletedBranchByID get a deleted branch by its ID
  453. func GetDeletedBranchByID(repoID, id int64) (*DeletedBranch, error) {
  454. deletedBranch := &DeletedBranch{}
  455. has, err := db.GetEngine(db.DefaultContext).Where("repo_id = ?", repoID).And("id = ?", id).Get(deletedBranch)
  456. if err != nil {
  457. return nil, err
  458. }
  459. if !has {
  460. return nil, nil
  461. }
  462. return deletedBranch, nil
  463. }
  464. // RemoveDeletedBranchByID removes a deleted branch from the database
  465. func RemoveDeletedBranchByID(repoID, id int64) (err error) {
  466. deletedBranch := &DeletedBranch{
  467. RepoID: repoID,
  468. ID: id,
  469. }
  470. if affected, err := db.GetEngine(db.DefaultContext).Delete(deletedBranch); err != nil {
  471. return err
  472. } else if affected != 1 {
  473. return fmt.Errorf("remove deleted branch ID(%v) failed", id)
  474. }
  475. return nil
  476. }
  477. // LoadUser loads the user that deleted the branch
  478. // When there's no user found it returns a user_model.NewGhostUser
  479. func (deletedBranch *DeletedBranch) LoadUser() {
  480. user, err := user_model.GetUserByID(deletedBranch.DeletedByID)
  481. if err != nil {
  482. user = user_model.NewGhostUser()
  483. }
  484. deletedBranch.DeletedBy = user
  485. }
  486. // RemoveDeletedBranchByName removes all deleted branches
  487. func RemoveDeletedBranchByName(repoID int64, branch string) error {
  488. _, err := db.GetEngine(db.DefaultContext).Where("repo_id=? AND name=?", repoID, branch).Delete(new(DeletedBranch))
  489. return err
  490. }
  491. // RemoveOldDeletedBranches removes old deleted branches
  492. func RemoveOldDeletedBranches(ctx context.Context, olderThan time.Duration) {
  493. // Nothing to do for shutdown or terminate
  494. log.Trace("Doing: DeletedBranchesCleanup")
  495. deleteBefore := time.Now().Add(-olderThan)
  496. _, err := db.GetEngine(db.DefaultContext).Where("deleted_unix < ?", deleteBefore.Unix()).Delete(new(DeletedBranch))
  497. if err != nil {
  498. log.Error("DeletedBranchesCleanup: %v", err)
  499. }
  500. }
  501. // RenamedBranch provide renamed branch log
  502. // will check it when a branch can't be found
  503. type RenamedBranch struct {
  504. ID int64 `xorm:"pk autoincr"`
  505. RepoID int64 `xorm:"INDEX NOT NULL"`
  506. From string
  507. To string
  508. CreatedUnix timeutil.TimeStamp `xorm:"created"`
  509. }
  510. // FindRenamedBranch check if a branch was renamed
  511. func FindRenamedBranch(repoID int64, from string) (branch *RenamedBranch, exist bool, err error) {
  512. branch = &RenamedBranch{
  513. RepoID: repoID,
  514. From: from,
  515. }
  516. exist, err = db.GetEngine(db.DefaultContext).Get(branch)
  517. return
  518. }
  519. // RenameBranch rename a branch
  520. func RenameBranch(repo *repo_model.Repository, from, to string, gitAction func(isDefault bool) error) (err error) {
  521. ctx, committer, err := db.TxContext()
  522. if err != nil {
  523. return err
  524. }
  525. defer committer.Close()
  526. sess := db.GetEngine(ctx)
  527. // 1. update default branch if needed
  528. isDefault := repo.DefaultBranch == from
  529. if isDefault {
  530. repo.DefaultBranch = to
  531. _, err = sess.ID(repo.ID).Cols("default_branch").Update(repo)
  532. if err != nil {
  533. return err
  534. }
  535. }
  536. // 2. Update protected branch if needed
  537. protectedBranch, err := GetProtectedBranchBy(ctx, repo.ID, from)
  538. if err != nil {
  539. return err
  540. }
  541. if protectedBranch != nil {
  542. protectedBranch.BranchName = to
  543. _, err = sess.ID(protectedBranch.ID).Cols("branch_name").Update(protectedBranch)
  544. if err != nil {
  545. return err
  546. }
  547. }
  548. // 3. Update all not merged pull request base branch name
  549. _, err = sess.Table(new(PullRequest)).Where("base_repo_id=? AND base_branch=? AND has_merged=?",
  550. repo.ID, from, false).
  551. Update(map[string]interface{}{"base_branch": to})
  552. if err != nil {
  553. return err
  554. }
  555. // 4. do git action
  556. if err = gitAction(isDefault); err != nil {
  557. return err
  558. }
  559. // 5. insert renamed branch record
  560. renamedBranch := &RenamedBranch{
  561. RepoID: repo.ID,
  562. From: from,
  563. To: to,
  564. }
  565. err = db.Insert(ctx, renamedBranch)
  566. if err != nil {
  567. return err
  568. }
  569. return committer.Commit()
  570. }