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 20KB

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