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.

branch.go 11KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404
  1. // Copyright 2016 The Gitea Authors. All rights reserved.
  2. // SPDX-License-Identifier: MIT
  3. package git
  4. import (
  5. "context"
  6. "fmt"
  7. "time"
  8. "code.gitea.io/gitea/models/db"
  9. repo_model "code.gitea.io/gitea/models/repo"
  10. user_model "code.gitea.io/gitea/models/user"
  11. "code.gitea.io/gitea/modules/git"
  12. "code.gitea.io/gitea/modules/log"
  13. "code.gitea.io/gitea/modules/timeutil"
  14. "code.gitea.io/gitea/modules/util"
  15. "xorm.io/builder"
  16. )
  17. // ErrBranchNotExist represents an error that branch with such name does not exist.
  18. type ErrBranchNotExist struct {
  19. RepoID int64
  20. BranchName string
  21. }
  22. // IsErrBranchNotExist checks if an error is an ErrBranchDoesNotExist.
  23. func IsErrBranchNotExist(err error) bool {
  24. _, ok := err.(ErrBranchNotExist)
  25. return ok
  26. }
  27. func (err ErrBranchNotExist) Error() string {
  28. return fmt.Sprintf("branch does not exist [repo_id: %d name: %s]", err.RepoID, err.BranchName)
  29. }
  30. func (err ErrBranchNotExist) Unwrap() error {
  31. return util.ErrNotExist
  32. }
  33. // ErrBranchAlreadyExists represents an error that branch with such name already exists.
  34. type ErrBranchAlreadyExists struct {
  35. BranchName string
  36. }
  37. // IsErrBranchAlreadyExists checks if an error is an ErrBranchAlreadyExists.
  38. func IsErrBranchAlreadyExists(err error) bool {
  39. _, ok := err.(ErrBranchAlreadyExists)
  40. return ok
  41. }
  42. func (err ErrBranchAlreadyExists) Error() string {
  43. return fmt.Sprintf("branch already exists [name: %s]", err.BranchName)
  44. }
  45. func (err ErrBranchAlreadyExists) Unwrap() error {
  46. return util.ErrAlreadyExist
  47. }
  48. // ErrBranchNameConflict represents an error that branch name conflicts with other branch.
  49. type ErrBranchNameConflict struct {
  50. BranchName string
  51. }
  52. // IsErrBranchNameConflict checks if an error is an ErrBranchNameConflict.
  53. func IsErrBranchNameConflict(err error) bool {
  54. _, ok := err.(ErrBranchNameConflict)
  55. return ok
  56. }
  57. func (err ErrBranchNameConflict) Error() string {
  58. return fmt.Sprintf("branch conflicts with existing branch [name: %s]", err.BranchName)
  59. }
  60. func (err ErrBranchNameConflict) Unwrap() error {
  61. return util.ErrAlreadyExist
  62. }
  63. // ErrBranchesEqual represents an error that base branch is equal to the head branch.
  64. type ErrBranchesEqual struct {
  65. BaseBranchName string
  66. HeadBranchName string
  67. }
  68. // IsErrBranchesEqual checks if an error is an ErrBranchesEqual.
  69. func IsErrBranchesEqual(err error) bool {
  70. _, ok := err.(ErrBranchesEqual)
  71. return ok
  72. }
  73. func (err ErrBranchesEqual) Error() string {
  74. return fmt.Sprintf("branches are equal [head: %sm base: %s]", err.HeadBranchName, err.BaseBranchName)
  75. }
  76. func (err ErrBranchesEqual) Unwrap() error {
  77. return util.ErrInvalidArgument
  78. }
  79. // Branch represents a branch of a repository
  80. // For those repository who have many branches, stored into database is a good choice
  81. // for pagination, keyword search and filtering
  82. type Branch struct {
  83. ID int64
  84. RepoID int64 `xorm:"UNIQUE(s)"`
  85. Name string `xorm:"UNIQUE(s) NOT NULL"` // git's ref-name is case-sensitive internally, however, in some databases (mssql, mysql, by default), it's case-insensitive at the moment
  86. CommitID string
  87. CommitMessage string `xorm:"TEXT"` // it only stores the message summary (the first line)
  88. PusherID int64
  89. Pusher *user_model.User `xorm:"-"`
  90. IsDeleted bool `xorm:"index"`
  91. DeletedByID int64
  92. DeletedBy *user_model.User `xorm:"-"`
  93. DeletedUnix timeutil.TimeStamp `xorm:"index"`
  94. CommitTime timeutil.TimeStamp // The commit
  95. CreatedUnix timeutil.TimeStamp `xorm:"created"`
  96. UpdatedUnix timeutil.TimeStamp `xorm:"updated"`
  97. }
  98. func (b *Branch) LoadDeletedBy(ctx context.Context) (err error) {
  99. if b.DeletedBy == nil {
  100. b.DeletedBy, err = user_model.GetUserByID(ctx, b.DeletedByID)
  101. if user_model.IsErrUserNotExist(err) {
  102. b.DeletedBy = user_model.NewGhostUser()
  103. err = nil
  104. }
  105. }
  106. return err
  107. }
  108. func (b *Branch) LoadPusher(ctx context.Context) (err error) {
  109. if b.Pusher == nil && b.PusherID > 0 {
  110. b.Pusher, err = user_model.GetUserByID(ctx, b.PusherID)
  111. if user_model.IsErrUserNotExist(err) {
  112. b.Pusher = user_model.NewGhostUser()
  113. err = nil
  114. }
  115. }
  116. return err
  117. }
  118. func init() {
  119. db.RegisterModel(new(Branch))
  120. db.RegisterModel(new(RenamedBranch))
  121. }
  122. func GetBranch(ctx context.Context, repoID int64, branchName string) (*Branch, error) {
  123. var branch Branch
  124. has, err := db.GetEngine(ctx).Where("repo_id=?", repoID).And("name=?", branchName).Get(&branch)
  125. if err != nil {
  126. return nil, err
  127. } else if !has {
  128. return nil, ErrBranchNotExist{
  129. RepoID: repoID,
  130. BranchName: branchName,
  131. }
  132. }
  133. return &branch, nil
  134. }
  135. func GetBranches(ctx context.Context, repoID int64, branchNames []string) ([]*Branch, error) {
  136. branches := make([]*Branch, 0, len(branchNames))
  137. return branches, db.GetEngine(ctx).Where("repo_id=?", repoID).In("name", branchNames).Find(&branches)
  138. }
  139. func AddBranches(ctx context.Context, branches []*Branch) error {
  140. for _, branch := range branches {
  141. if _, err := db.GetEngine(ctx).Insert(branch); err != nil {
  142. return err
  143. }
  144. }
  145. return nil
  146. }
  147. func GetDeletedBranchByID(ctx context.Context, repoID, branchID int64) (*Branch, error) {
  148. var branch Branch
  149. has, err := db.GetEngine(ctx).ID(branchID).Get(&branch)
  150. if err != nil {
  151. return nil, err
  152. } else if !has {
  153. return nil, ErrBranchNotExist{
  154. RepoID: repoID,
  155. }
  156. }
  157. if branch.RepoID != repoID {
  158. return nil, ErrBranchNotExist{
  159. RepoID: repoID,
  160. }
  161. }
  162. if !branch.IsDeleted {
  163. return nil, ErrBranchNotExist{
  164. RepoID: repoID,
  165. }
  166. }
  167. return &branch, nil
  168. }
  169. func DeleteBranches(ctx context.Context, repoID, doerID int64, branchIDs []int64) error {
  170. return db.WithTx(ctx, func(ctx context.Context) error {
  171. branches := make([]*Branch, 0, len(branchIDs))
  172. if err := db.GetEngine(ctx).In("id", branchIDs).Find(&branches); err != nil {
  173. return err
  174. }
  175. for _, branch := range branches {
  176. if err := AddDeletedBranch(ctx, repoID, branch.Name, doerID); err != nil {
  177. return err
  178. }
  179. }
  180. return nil
  181. })
  182. }
  183. // UpdateBranch updates the branch information in the database.
  184. func UpdateBranch(ctx context.Context, repoID, pusherID int64, branchName string, commit *git.Commit) (int64, error) {
  185. return db.GetEngine(ctx).Where("repo_id=? AND name=?", repoID, branchName).
  186. Cols("commit_id, commit_message, pusher_id, commit_time, is_deleted, updated_unix").
  187. Update(&Branch{
  188. CommitID: commit.ID.String(),
  189. CommitMessage: commit.Summary(),
  190. PusherID: pusherID,
  191. CommitTime: timeutil.TimeStamp(commit.Committer.When.Unix()),
  192. IsDeleted: false,
  193. })
  194. }
  195. // AddDeletedBranch adds a deleted branch to the database
  196. func AddDeletedBranch(ctx context.Context, repoID int64, branchName string, deletedByID int64) error {
  197. branch, err := GetBranch(ctx, repoID, branchName)
  198. if err != nil {
  199. return err
  200. }
  201. if branch.IsDeleted {
  202. return nil
  203. }
  204. cnt, err := db.GetEngine(ctx).Where("repo_id=? AND name=? AND is_deleted=?", repoID, branchName, false).
  205. Cols("is_deleted, deleted_by_id, deleted_unix").
  206. Update(&Branch{
  207. IsDeleted: true,
  208. DeletedByID: deletedByID,
  209. DeletedUnix: timeutil.TimeStampNow(),
  210. })
  211. if err != nil {
  212. return err
  213. }
  214. if cnt == 0 {
  215. return fmt.Errorf("branch %s not found or has been deleted", branchName)
  216. }
  217. return err
  218. }
  219. func RemoveDeletedBranchByID(ctx context.Context, repoID, branchID int64) error {
  220. _, err := db.GetEngine(ctx).Where("repo_id=? AND id=? AND is_deleted = ?", repoID, branchID, true).Delete(new(Branch))
  221. return err
  222. }
  223. // RemoveOldDeletedBranches removes old deleted branches
  224. func RemoveOldDeletedBranches(ctx context.Context, olderThan time.Duration) {
  225. // Nothing to do for shutdown or terminate
  226. log.Trace("Doing: DeletedBranchesCleanup")
  227. deleteBefore := time.Now().Add(-olderThan)
  228. _, err := db.GetEngine(ctx).Where("is_deleted=? AND deleted_unix < ?", true, deleteBefore.Unix()).Delete(new(Branch))
  229. if err != nil {
  230. log.Error("DeletedBranchesCleanup: %v", err)
  231. }
  232. }
  233. // RenamedBranch provide renamed branch log
  234. // will check it when a branch can't be found
  235. type RenamedBranch struct {
  236. ID int64 `xorm:"pk autoincr"`
  237. RepoID int64 `xorm:"INDEX NOT NULL"`
  238. From string
  239. To string
  240. CreatedUnix timeutil.TimeStamp `xorm:"created"`
  241. }
  242. // FindRenamedBranch check if a branch was renamed
  243. func FindRenamedBranch(ctx context.Context, repoID int64, from string) (branch *RenamedBranch, exist bool, err error) {
  244. branch = &RenamedBranch{
  245. RepoID: repoID,
  246. From: from,
  247. }
  248. exist, err = db.GetEngine(ctx).Get(branch)
  249. return branch, exist, err
  250. }
  251. // RenameBranch rename a branch
  252. func RenameBranch(ctx context.Context, repo *repo_model.Repository, from, to string, gitAction func(ctx context.Context, isDefault bool) error) (err error) {
  253. ctx, committer, err := db.TxContext(ctx)
  254. if err != nil {
  255. return err
  256. }
  257. defer committer.Close()
  258. sess := db.GetEngine(ctx)
  259. var branch Branch
  260. exist, err := db.GetEngine(ctx).Where("repo_id=? AND name=?", repo.ID, from).Get(&branch)
  261. if err != nil {
  262. return err
  263. } else if !exist || branch.IsDeleted {
  264. return ErrBranchNotExist{
  265. RepoID: repo.ID,
  266. BranchName: from,
  267. }
  268. }
  269. // 1. update branch in database
  270. if n, err := sess.Where("repo_id=? AND name=?", repo.ID, from).Update(&Branch{
  271. Name: to,
  272. }); err != nil {
  273. return err
  274. } else if n <= 0 {
  275. return ErrBranchNotExist{
  276. RepoID: repo.ID,
  277. BranchName: from,
  278. }
  279. }
  280. // 2. update default branch if needed
  281. isDefault := repo.DefaultBranch == from
  282. if isDefault {
  283. repo.DefaultBranch = to
  284. _, err = sess.ID(repo.ID).Cols("default_branch").Update(repo)
  285. if err != nil {
  286. return err
  287. }
  288. }
  289. // 3. Update protected branch if needed
  290. protectedBranch, err := GetProtectedBranchRuleByName(ctx, repo.ID, from)
  291. if err != nil {
  292. return err
  293. }
  294. if protectedBranch != nil {
  295. // there is a protect rule for this branch
  296. protectedBranch.RuleName = to
  297. _, err = sess.ID(protectedBranch.ID).Cols("branch_name").Update(protectedBranch)
  298. if err != nil {
  299. return err
  300. }
  301. } else {
  302. // some glob protect rules may match this branch
  303. protected, err := IsBranchProtected(ctx, repo.ID, from)
  304. if err != nil {
  305. return err
  306. }
  307. if protected {
  308. return ErrBranchIsProtected
  309. }
  310. }
  311. // 4. Update all not merged pull request base branch name
  312. _, err = sess.Table("pull_request").Where("base_repo_id=? AND base_branch=? AND has_merged=?",
  313. repo.ID, from, false).
  314. Update(map[string]any{"base_branch": to})
  315. if err != nil {
  316. return err
  317. }
  318. // 5. do git action
  319. if err = gitAction(ctx, isDefault); err != nil {
  320. return err
  321. }
  322. // 6. insert renamed branch record
  323. renamedBranch := &RenamedBranch{
  324. RepoID: repo.ID,
  325. From: from,
  326. To: to,
  327. }
  328. err = db.Insert(ctx, renamedBranch)
  329. if err != nil {
  330. return err
  331. }
  332. return committer.Commit()
  333. }
  334. // FindRecentlyPushedNewBranches return at most 2 new branches pushed by the user in 6 hours which has no opened PRs created
  335. // except the indicate branch
  336. func FindRecentlyPushedNewBranches(ctx context.Context, repoID, userID int64, excludeBranchName string) (BranchList, error) {
  337. branches := make(BranchList, 0, 2)
  338. subQuery := builder.Select("head_branch").From("pull_request").
  339. InnerJoin("issue", "issue.id = pull_request.issue_id").
  340. Where(builder.Eq{
  341. "pull_request.head_repo_id": repoID,
  342. "issue.is_closed": false,
  343. })
  344. err := db.GetEngine(ctx).
  345. Where("pusher_id=? AND is_deleted=?", userID, false).
  346. And("name <> ?", excludeBranchName).
  347. And("repo_id = ?", repoID).
  348. And("commit_time >= ?", time.Now().Add(-time.Hour*6).Unix()).
  349. NotIn("name", subQuery).
  350. OrderBy("branch.commit_time DESC").
  351. Limit(2).
  352. Find(&branches)
  353. return branches, err
  354. }