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

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399
  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 AddBranches(ctx context.Context, branches []*Branch) error {
  136. for _, branch := range branches {
  137. if _, err := db.GetEngine(ctx).Insert(branch); err != nil {
  138. return err
  139. }
  140. }
  141. return nil
  142. }
  143. func GetDeletedBranchByID(ctx context.Context, repoID, branchID int64) (*Branch, error) {
  144. var branch Branch
  145. has, err := db.GetEngine(ctx).ID(branchID).Get(&branch)
  146. if err != nil {
  147. return nil, err
  148. } else if !has {
  149. return nil, ErrBranchNotExist{
  150. RepoID: repoID,
  151. }
  152. }
  153. if branch.RepoID != repoID {
  154. return nil, ErrBranchNotExist{
  155. RepoID: repoID,
  156. }
  157. }
  158. if !branch.IsDeleted {
  159. return nil, ErrBranchNotExist{
  160. RepoID: repoID,
  161. }
  162. }
  163. return &branch, nil
  164. }
  165. func DeleteBranches(ctx context.Context, repoID, doerID int64, branchIDs []int64) error {
  166. return db.WithTx(ctx, func(ctx context.Context) error {
  167. branches := make([]*Branch, 0, len(branchIDs))
  168. if err := db.GetEngine(ctx).In("id", branchIDs).Find(&branches); err != nil {
  169. return err
  170. }
  171. for _, branch := range branches {
  172. if err := AddDeletedBranch(ctx, repoID, branch.Name, doerID); err != nil {
  173. return err
  174. }
  175. }
  176. return nil
  177. })
  178. }
  179. // UpdateBranch updates the branch information in the database.
  180. func UpdateBranch(ctx context.Context, repoID, pusherID int64, branchName string, commit *git.Commit) (int64, error) {
  181. return db.GetEngine(ctx).Where("repo_id=? AND name=?", repoID, branchName).
  182. Cols("commit_id, commit_message, pusher_id, commit_time, is_deleted, updated_unix").
  183. Update(&Branch{
  184. CommitID: commit.ID.String(),
  185. CommitMessage: commit.Summary(),
  186. PusherID: pusherID,
  187. CommitTime: timeutil.TimeStamp(commit.Committer.When.Unix()),
  188. IsDeleted: false,
  189. })
  190. }
  191. // AddDeletedBranch adds a deleted branch to the database
  192. func AddDeletedBranch(ctx context.Context, repoID int64, branchName string, deletedByID int64) error {
  193. branch, err := GetBranch(ctx, repoID, branchName)
  194. if err != nil {
  195. return err
  196. }
  197. if branch.IsDeleted {
  198. return nil
  199. }
  200. cnt, err := db.GetEngine(ctx).Where("repo_id=? AND name=? AND is_deleted=?", repoID, branchName, false).
  201. Cols("is_deleted, deleted_by_id, deleted_unix").
  202. Update(&Branch{
  203. IsDeleted: true,
  204. DeletedByID: deletedByID,
  205. DeletedUnix: timeutil.TimeStampNow(),
  206. })
  207. if err != nil {
  208. return err
  209. }
  210. if cnt == 0 {
  211. return fmt.Errorf("branch %s not found or has been deleted", branchName)
  212. }
  213. return err
  214. }
  215. func RemoveDeletedBranchByID(ctx context.Context, repoID, branchID int64) error {
  216. _, err := db.GetEngine(ctx).Where("repo_id=? AND id=? AND is_deleted = ?", repoID, branchID, true).Delete(new(Branch))
  217. return err
  218. }
  219. // RemoveOldDeletedBranches removes old deleted branches
  220. func RemoveOldDeletedBranches(ctx context.Context, olderThan time.Duration) {
  221. // Nothing to do for shutdown or terminate
  222. log.Trace("Doing: DeletedBranchesCleanup")
  223. deleteBefore := time.Now().Add(-olderThan)
  224. _, err := db.GetEngine(ctx).Where("is_deleted=? AND deleted_unix < ?", true, deleteBefore.Unix()).Delete(new(Branch))
  225. if err != nil {
  226. log.Error("DeletedBranchesCleanup: %v", err)
  227. }
  228. }
  229. // RenamedBranch provide renamed branch log
  230. // will check it when a branch can't be found
  231. type RenamedBranch struct {
  232. ID int64 `xorm:"pk autoincr"`
  233. RepoID int64 `xorm:"INDEX NOT NULL"`
  234. From string
  235. To string
  236. CreatedUnix timeutil.TimeStamp `xorm:"created"`
  237. }
  238. // FindRenamedBranch check if a branch was renamed
  239. func FindRenamedBranch(ctx context.Context, repoID int64, from string) (branch *RenamedBranch, exist bool, err error) {
  240. branch = &RenamedBranch{
  241. RepoID: repoID,
  242. From: from,
  243. }
  244. exist, err = db.GetEngine(ctx).Get(branch)
  245. return branch, exist, err
  246. }
  247. // RenameBranch rename a branch
  248. func RenameBranch(ctx context.Context, repo *repo_model.Repository, from, to string, gitAction func(isDefault bool) error) (err error) {
  249. ctx, committer, err := db.TxContext(ctx)
  250. if err != nil {
  251. return err
  252. }
  253. defer committer.Close()
  254. sess := db.GetEngine(ctx)
  255. var branch Branch
  256. exist, err := db.GetEngine(ctx).Where("repo_id=? AND name=?", repo.ID, from).Get(&branch)
  257. if err != nil {
  258. return err
  259. } else if !exist || branch.IsDeleted {
  260. return ErrBranchNotExist{
  261. RepoID: repo.ID,
  262. BranchName: from,
  263. }
  264. }
  265. // 1. update branch in database
  266. if n, err := sess.Where("repo_id=? AND name=?", repo.ID, from).Update(&Branch{
  267. Name: to,
  268. }); err != nil {
  269. return err
  270. } else if n <= 0 {
  271. return ErrBranchNotExist{
  272. RepoID: repo.ID,
  273. BranchName: from,
  274. }
  275. }
  276. // 2. update default branch if needed
  277. isDefault := repo.DefaultBranch == from
  278. if isDefault {
  279. repo.DefaultBranch = to
  280. _, err = sess.ID(repo.ID).Cols("default_branch").Update(repo)
  281. if err != nil {
  282. return err
  283. }
  284. }
  285. // 3. Update protected branch if needed
  286. protectedBranch, err := GetProtectedBranchRuleByName(ctx, repo.ID, from)
  287. if err != nil {
  288. return err
  289. }
  290. if protectedBranch != nil {
  291. // there is a protect rule for this branch
  292. protectedBranch.RuleName = to
  293. _, err = sess.ID(protectedBranch.ID).Cols("branch_name").Update(protectedBranch)
  294. if err != nil {
  295. return err
  296. }
  297. } else {
  298. // some glob protect rules may match this branch
  299. protected, err := IsBranchProtected(ctx, repo.ID, from)
  300. if err != nil {
  301. return err
  302. }
  303. if protected {
  304. return ErrBranchIsProtected
  305. }
  306. }
  307. // 4. Update all not merged pull request base branch name
  308. _, err = sess.Table("pull_request").Where("base_repo_id=? AND base_branch=? AND has_merged=?",
  309. repo.ID, from, false).
  310. Update(map[string]any{"base_branch": to})
  311. if err != nil {
  312. return err
  313. }
  314. // 5. do git action
  315. if err = gitAction(isDefault); err != nil {
  316. return err
  317. }
  318. // 6. insert renamed branch record
  319. renamedBranch := &RenamedBranch{
  320. RepoID: repo.ID,
  321. From: from,
  322. To: to,
  323. }
  324. err = db.Insert(ctx, renamedBranch)
  325. if err != nil {
  326. return err
  327. }
  328. return committer.Commit()
  329. }
  330. // FindRecentlyPushedNewBranches return at most 2 new branches pushed by the user in 6 hours which has no opened PRs created
  331. // except the indicate branch
  332. func FindRecentlyPushedNewBranches(ctx context.Context, repoID, userID int64, excludeBranchName string) (BranchList, error) {
  333. branches := make(BranchList, 0, 2)
  334. subQuery := builder.Select("head_branch").From("pull_request").
  335. InnerJoin("issue", "issue.id = pull_request.issue_id").
  336. Where(builder.Eq{
  337. "pull_request.head_repo_id": repoID,
  338. "issue.is_closed": false,
  339. })
  340. err := db.GetEngine(ctx).
  341. Where("pusher_id=? AND is_deleted=?", userID, false).
  342. And("name <> ?", excludeBranchName).
  343. And("repo_id = ?", repoID).
  344. And("commit_time >= ?", time.Now().Add(-time.Hour*6).Unix()).
  345. NotIn("name", subQuery).
  346. OrderBy("branch.commit_time DESC").
  347. Limit(2).
  348. Find(&branches)
  349. return branches, err
  350. }