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

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