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

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