gitea源码

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569
  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. "code.gitea.io/gitea/models/unit"
  11. user_model "code.gitea.io/gitea/models/user"
  12. "code.gitea.io/gitea/modules/container"
  13. "code.gitea.io/gitea/modules/git"
  14. "code.gitea.io/gitea/modules/log"
  15. "code.gitea.io/gitea/modules/optional"
  16. "code.gitea.io/gitea/modules/timeutil"
  17. "code.gitea.io/gitea/modules/util"
  18. "xorm.io/builder"
  19. )
  20. // ErrBranchNotExist represents an error that branch with such name does not exist.
  21. type ErrBranchNotExist struct {
  22. RepoID int64
  23. BranchName string
  24. }
  25. // IsErrBranchNotExist checks if an error is an ErrBranchDoesNotExist.
  26. func IsErrBranchNotExist(err error) bool {
  27. _, ok := err.(ErrBranchNotExist)
  28. return ok
  29. }
  30. func (err ErrBranchNotExist) Error() string {
  31. return fmt.Sprintf("branch does not exist [repo_id: %d name: %s]", err.RepoID, err.BranchName)
  32. }
  33. func (err ErrBranchNotExist) Unwrap() error {
  34. return util.ErrNotExist
  35. }
  36. // ErrBranchAlreadyExists represents an error that branch with such name already exists.
  37. type ErrBranchAlreadyExists struct {
  38. BranchName string
  39. }
  40. // IsErrBranchAlreadyExists checks if an error is an ErrBranchAlreadyExists.
  41. func IsErrBranchAlreadyExists(err error) bool {
  42. _, ok := err.(ErrBranchAlreadyExists)
  43. return ok
  44. }
  45. func (err ErrBranchAlreadyExists) Error() string {
  46. return fmt.Sprintf("branch already exists [name: %s]", err.BranchName)
  47. }
  48. func (err ErrBranchAlreadyExists) Unwrap() error {
  49. return util.ErrAlreadyExist
  50. }
  51. // ErrBranchNameConflict represents an error that branch name conflicts with other branch.
  52. type ErrBranchNameConflict struct {
  53. BranchName string
  54. }
  55. // IsErrBranchNameConflict checks if an error is an ErrBranchNameConflict.
  56. func IsErrBranchNameConflict(err error) bool {
  57. _, ok := err.(ErrBranchNameConflict)
  58. return ok
  59. }
  60. func (err ErrBranchNameConflict) Error() string {
  61. return fmt.Sprintf("branch conflicts with existing branch [name: %s]", err.BranchName)
  62. }
  63. func (err ErrBranchNameConflict) Unwrap() error {
  64. return util.ErrAlreadyExist
  65. }
  66. // ErrBranchesEqual represents an error that base branch is equal to the head branch.
  67. type ErrBranchesEqual struct {
  68. BaseBranchName string
  69. HeadBranchName string
  70. }
  71. // IsErrBranchesEqual checks if an error is an ErrBranchesEqual.
  72. func IsErrBranchesEqual(err error) bool {
  73. _, ok := err.(ErrBranchesEqual)
  74. return ok
  75. }
  76. func (err ErrBranchesEqual) Error() string {
  77. return fmt.Sprintf("branches are equal [head: %sm base: %s]", err.HeadBranchName, err.BaseBranchName)
  78. }
  79. func (err ErrBranchesEqual) Unwrap() error {
  80. return util.ErrInvalidArgument
  81. }
  82. // Branch represents a branch of a repository
  83. // For those repository who have many branches, stored into database is a good choice
  84. // for pagination, keyword search and filtering
  85. type Branch struct {
  86. ID int64
  87. RepoID int64 `xorm:"UNIQUE(s)"`
  88. Repo *repo_model.Repository `xorm:"-"`
  89. 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
  90. CommitID string
  91. CommitMessage string `xorm:"TEXT"` // it only stores the message summary (the first line)
  92. PusherID int64
  93. Pusher *user_model.User `xorm:"-"`
  94. IsDeleted bool `xorm:"index"`
  95. DeletedByID int64
  96. DeletedBy *user_model.User `xorm:"-"`
  97. DeletedUnix timeutil.TimeStamp `xorm:"index"`
  98. CommitTime timeutil.TimeStamp // The commit
  99. CreatedUnix timeutil.TimeStamp `xorm:"created"`
  100. UpdatedUnix timeutil.TimeStamp `xorm:"updated"`
  101. }
  102. func (b *Branch) LoadDeletedBy(ctx context.Context) (err error) {
  103. if b.DeletedBy == nil {
  104. b.DeletedBy, err = user_model.GetUserByID(ctx, b.DeletedByID)
  105. if user_model.IsErrUserNotExist(err) {
  106. b.DeletedBy = user_model.NewGhostUser()
  107. err = nil
  108. }
  109. }
  110. return err
  111. }
  112. func (b *Branch) LoadPusher(ctx context.Context) (err error) {
  113. if b.Pusher == nil && b.PusherID > 0 {
  114. b.Pusher, err = user_model.GetUserByID(ctx, b.PusherID)
  115. if user_model.IsErrUserNotExist(err) {
  116. b.Pusher = user_model.NewGhostUser()
  117. err = nil
  118. }
  119. }
  120. return err
  121. }
  122. func (b *Branch) LoadRepo(ctx context.Context) (err error) {
  123. if b.Repo != nil || b.RepoID == 0 {
  124. return nil
  125. }
  126. b.Repo, err = repo_model.GetRepositoryByID(ctx, b.RepoID)
  127. return err
  128. }
  129. func init() {
  130. db.RegisterModel(new(Branch))
  131. db.RegisterModel(new(RenamedBranch))
  132. }
  133. func GetBranch(ctx context.Context, repoID int64, branchName string) (*Branch, error) {
  134. var branch Branch
  135. has, err := db.GetEngine(ctx).Where("repo_id=?", repoID).And("name=?", branchName).Get(&branch)
  136. if err != nil {
  137. return nil, err
  138. } else if !has {
  139. return nil, ErrBranchNotExist{
  140. RepoID: repoID,
  141. BranchName: branchName,
  142. }
  143. }
  144. // FIXME: this design is not right: it doesn't check `branch.IsDeleted`, it doesn't make sense to make callers to check IsDeleted again and again.
  145. // It causes inconsistency with `GetBranches` and `git.GetBranch`, and will lead to strange bugs
  146. // In the future, there should be 2 functions: `GetBranchExisting` and `GetBranchWithDeleted`
  147. return &branch, nil
  148. }
  149. // IsBranchExist returns true if the branch exists in the repository.
  150. func IsBranchExist(ctx context.Context, repoID int64, branchName string) (bool, error) {
  151. var branch Branch
  152. has, err := db.GetEngine(ctx).Where("repo_id=?", repoID).And("name=?", branchName).Get(&branch)
  153. if err != nil {
  154. return false, err
  155. } else if !has {
  156. return false, nil
  157. }
  158. return !branch.IsDeleted, nil
  159. }
  160. func GetBranches(ctx context.Context, repoID int64, branchNames []string, includeDeleted bool) ([]*Branch, error) {
  161. branches := make([]*Branch, 0, len(branchNames))
  162. sess := db.GetEngine(ctx).Where("repo_id=?", repoID).In("name", branchNames)
  163. if !includeDeleted {
  164. sess.And("is_deleted=?", false)
  165. }
  166. return branches, sess.Find(&branches)
  167. }
  168. func BranchesToNamesSet(branches []*Branch) container.Set[string] {
  169. names := make(container.Set[string], len(branches))
  170. for _, branch := range branches {
  171. names.Add(branch.Name)
  172. }
  173. return names
  174. }
  175. func AddBranches(ctx context.Context, branches []*Branch) error {
  176. for _, branch := range branches {
  177. if _, err := db.GetEngine(ctx).Insert(branch); err != nil {
  178. return err
  179. }
  180. }
  181. return nil
  182. }
  183. func GetDeletedBranchByID(ctx context.Context, repoID, branchID int64) (*Branch, error) {
  184. var branch Branch
  185. has, err := db.GetEngine(ctx).ID(branchID).Get(&branch)
  186. if err != nil {
  187. return nil, err
  188. } else if !has {
  189. return nil, ErrBranchNotExist{
  190. RepoID: repoID,
  191. }
  192. }
  193. if branch.RepoID != repoID {
  194. return nil, ErrBranchNotExist{
  195. RepoID: repoID,
  196. }
  197. }
  198. if !branch.IsDeleted {
  199. return nil, ErrBranchNotExist{
  200. RepoID: repoID,
  201. }
  202. }
  203. return &branch, nil
  204. }
  205. func DeleteRepoBranches(ctx context.Context, repoID int64) error {
  206. _, err := db.GetEngine(ctx).Where("repo_id=?", repoID).Delete(new(Branch))
  207. return err
  208. }
  209. func DeleteBranches(ctx context.Context, repoID, doerID int64, branchIDs []int64) error {
  210. return db.WithTx(ctx, func(ctx context.Context) error {
  211. branches := make([]*Branch, 0, len(branchIDs))
  212. if err := db.GetEngine(ctx).In("id", branchIDs).Find(&branches); err != nil {
  213. return err
  214. }
  215. for _, branch := range branches {
  216. if err := AddDeletedBranch(ctx, repoID, branch.Name, doerID); err != nil {
  217. return err
  218. }
  219. }
  220. return nil
  221. })
  222. }
  223. // UpdateBranch updates the branch information in the database.
  224. func UpdateBranch(ctx context.Context, repoID, pusherID int64, branchName string, commit *git.Commit) (int64, error) {
  225. return db.GetEngine(ctx).Where("repo_id=? AND name=?", repoID, branchName).
  226. Cols("commit_id, commit_message, pusher_id, commit_time, is_deleted, updated_unix").
  227. Update(&Branch{
  228. CommitID: commit.ID.String(),
  229. CommitMessage: commit.Summary(),
  230. PusherID: pusherID,
  231. CommitTime: timeutil.TimeStamp(commit.Committer.When.Unix()),
  232. IsDeleted: false,
  233. })
  234. }
  235. // AddDeletedBranch adds a deleted branch to the database
  236. func AddDeletedBranch(ctx context.Context, repoID int64, branchName string, deletedByID int64) error {
  237. branch, err := GetBranch(ctx, repoID, branchName)
  238. if err != nil {
  239. return err
  240. }
  241. if branch.IsDeleted {
  242. return nil
  243. }
  244. cnt, err := db.GetEngine(ctx).Where("repo_id=? AND name=? AND is_deleted=?", repoID, branchName, false).
  245. Cols("is_deleted, deleted_by_id, deleted_unix").
  246. Update(&Branch{
  247. IsDeleted: true,
  248. DeletedByID: deletedByID,
  249. DeletedUnix: timeutil.TimeStampNow(),
  250. })
  251. if err != nil {
  252. return err
  253. }
  254. if cnt == 0 {
  255. return fmt.Errorf("branch %s not found or has been deleted", branchName)
  256. }
  257. return err
  258. }
  259. func RemoveDeletedBranchByID(ctx context.Context, repoID, branchID int64) error {
  260. _, err := db.GetEngine(ctx).Where("repo_id=? AND id=? AND is_deleted = ?", repoID, branchID, true).Delete(new(Branch))
  261. return err
  262. }
  263. // RemoveOldDeletedBranches removes old deleted branches
  264. func RemoveOldDeletedBranches(ctx context.Context, olderThan time.Duration) {
  265. // Nothing to do for shutdown or terminate
  266. log.Trace("Doing: DeletedBranchesCleanup")
  267. deleteBefore := time.Now().Add(-olderThan)
  268. _, err := db.GetEngine(ctx).Where("is_deleted=? AND deleted_unix < ?", true, deleteBefore.Unix()).Delete(new(Branch))
  269. if err != nil {
  270. log.Error("DeletedBranchesCleanup: %v", err)
  271. }
  272. }
  273. // RenamedBranch provide renamed branch log
  274. // will check it when a branch can't be found
  275. type RenamedBranch struct {
  276. ID int64 `xorm:"pk autoincr"`
  277. RepoID int64 `xorm:"INDEX NOT NULL"`
  278. From string
  279. To string
  280. CreatedUnix timeutil.TimeStamp `xorm:"created"`
  281. }
  282. // FindRenamedBranch check if a branch was renamed
  283. func FindRenamedBranch(ctx context.Context, repoID int64, from string) (branch *RenamedBranch, exist bool, err error) {
  284. branch = &RenamedBranch{
  285. RepoID: repoID,
  286. From: from,
  287. }
  288. exist, err = db.GetEngine(ctx).Get(branch)
  289. return branch, exist, err
  290. }
  291. // RenameBranch rename a branch
  292. func RenameBranch(ctx context.Context, repo *repo_model.Repository, from, to string, gitAction func(ctx context.Context, isDefault bool) error) (err error) {
  293. return db.WithTx(ctx, func(ctx context.Context) error {
  294. sess := db.GetEngine(ctx)
  295. // check whether from branch exist
  296. var branch Branch
  297. exist, err := db.GetEngine(ctx).Where("repo_id=? AND name=?", repo.ID, from).Get(&branch)
  298. if err != nil {
  299. return err
  300. } else if !exist || branch.IsDeleted {
  301. return ErrBranchNotExist{
  302. RepoID: repo.ID,
  303. BranchName: from,
  304. }
  305. }
  306. // check whether to branch exist or is_deleted
  307. var dstBranch Branch
  308. exist, err = db.GetEngine(ctx).Where("repo_id=? AND name=?", repo.ID, to).Get(&dstBranch)
  309. if err != nil {
  310. return err
  311. }
  312. if exist {
  313. if !dstBranch.IsDeleted {
  314. return ErrBranchAlreadyExists{
  315. BranchName: to,
  316. }
  317. }
  318. if _, err := db.GetEngine(ctx).ID(dstBranch.ID).NoAutoCondition().Delete(&dstBranch); err != nil {
  319. return err
  320. }
  321. }
  322. // 1. update branch in database
  323. if n, err := sess.Where("repo_id=? AND name=?", repo.ID, from).Update(&Branch{
  324. Name: to,
  325. }); err != nil {
  326. return err
  327. } else if n <= 0 {
  328. return ErrBranchNotExist{
  329. RepoID: repo.ID,
  330. BranchName: from,
  331. }
  332. }
  333. // 2. update default branch if needed
  334. isDefault := repo.DefaultBranch == from
  335. if isDefault {
  336. repo.DefaultBranch = to
  337. _, err = sess.ID(repo.ID).Cols("default_branch").Update(repo)
  338. if err != nil {
  339. return err
  340. }
  341. }
  342. // 3. Update protected branch if needed
  343. protectedBranch, err := GetProtectedBranchRuleByName(ctx, repo.ID, from)
  344. if err != nil {
  345. return err
  346. }
  347. if protectedBranch != nil {
  348. // there is a protect rule for this branch
  349. protectedBranch.RuleName = to
  350. if _, err = sess.ID(protectedBranch.ID).Cols("branch_name").Update(protectedBranch); err != nil {
  351. return err
  352. }
  353. } else {
  354. // some glob protect rules may match this branch
  355. protected, err := IsBranchProtected(ctx, repo.ID, from)
  356. if err != nil {
  357. return err
  358. }
  359. if protected {
  360. return ErrBranchIsProtected
  361. }
  362. }
  363. // 4. Update all not merged pull request base branch name
  364. _, err = sess.Table("pull_request").Where("base_repo_id=? AND base_branch=? AND has_merged=?",
  365. repo.ID, from, false).
  366. Update(map[string]any{"base_branch": to})
  367. if err != nil {
  368. return err
  369. }
  370. // 4.1 Update all not merged pull request head branch name
  371. if _, err = sess.Table("pull_request").Where("head_repo_id=? AND head_branch=? AND has_merged=?",
  372. repo.ID, from, false).
  373. Update(map[string]any{"head_branch": to}); err != nil {
  374. return err
  375. }
  376. // 5. insert renamed branch record
  377. if err = db.Insert(ctx, &RenamedBranch{
  378. RepoID: repo.ID,
  379. From: from,
  380. To: to,
  381. }); err != nil {
  382. return err
  383. }
  384. // 6. do git action
  385. return gitAction(ctx, isDefault)
  386. })
  387. }
  388. type FindRecentlyPushedNewBranchesOptions struct {
  389. Repo *repo_model.Repository
  390. BaseRepo *repo_model.Repository
  391. CommitAfterUnix int64
  392. MaxCount int
  393. }
  394. type RecentlyPushedNewBranch struct {
  395. BranchRepo *repo_model.Repository
  396. BranchName string
  397. BranchDisplayName string
  398. BranchLink string
  399. BranchCompareURL string
  400. CommitTime timeutil.TimeStamp
  401. }
  402. // FindRecentlyPushedNewBranches return at most 2 new branches pushed by the user in 2 hours which has no opened PRs created
  403. // if opts.CommitAfterUnix is 0, we will find the branches that were committed to in the last 2 hours
  404. // if opts.ListOptions is not set, we will only display top 2 latest branches.
  405. // Protected branches will be skipped since they are unlikely to be used to create new PRs.
  406. func FindRecentlyPushedNewBranches(ctx context.Context, doer *user_model.User, opts FindRecentlyPushedNewBranchesOptions) ([]*RecentlyPushedNewBranch, error) {
  407. if doer == nil {
  408. return []*RecentlyPushedNewBranch{}, nil
  409. }
  410. // find all related repo ids
  411. repoOpts := repo_model.SearchRepoOptions{
  412. Actor: doer,
  413. Private: true,
  414. AllPublic: false, // Include also all public repositories of users and public organisations
  415. AllLimited: false, // Include also all public repositories of limited organisations
  416. Fork: optional.Some(true),
  417. ForkFrom: opts.BaseRepo.ID,
  418. Archived: optional.Some(false),
  419. }
  420. repoCond := repo_model.SearchRepositoryCondition(repoOpts).And(repo_model.AccessibleRepositoryCondition(doer, unit.TypeCode))
  421. if opts.Repo.ID == opts.BaseRepo.ID {
  422. // should also include the base repo's branches
  423. repoCond = repoCond.Or(builder.Eq{"id": opts.BaseRepo.ID})
  424. } else {
  425. // in fork repo, we only detect the fork repo's branch
  426. repoCond = repoCond.And(builder.Eq{"id": opts.Repo.ID})
  427. }
  428. repoIDs := builder.Select("id").From("repository").Where(repoCond)
  429. if opts.CommitAfterUnix == 0 {
  430. opts.CommitAfterUnix = time.Now().Add(-time.Hour * 2).Unix()
  431. }
  432. baseBranch, err := GetBranch(ctx, opts.BaseRepo.ID, opts.BaseRepo.DefaultBranch)
  433. if err != nil {
  434. return nil, err
  435. }
  436. // find all related branches, these branches may already created PRs, we will check later
  437. var branches []*Branch
  438. if err := db.GetEngine(ctx).
  439. Where(builder.And(
  440. builder.Eq{
  441. "pusher_id": doer.ID,
  442. "is_deleted": false,
  443. },
  444. builder.Gte{"commit_time": opts.CommitAfterUnix},
  445. builder.In("repo_id", repoIDs),
  446. // newly created branch have no changes, so skip them
  447. builder.Neq{"commit_id": baseBranch.CommitID},
  448. )).
  449. OrderBy(db.SearchOrderByRecentUpdated.String()).
  450. Find(&branches); err != nil {
  451. return nil, err
  452. }
  453. newBranches := make([]*RecentlyPushedNewBranch, 0, len(branches))
  454. if opts.MaxCount == 0 {
  455. // by default we display 2 recently pushed new branch
  456. opts.MaxCount = 2
  457. }
  458. for _, branch := range branches {
  459. // whether the branch is protected
  460. protected, err := IsBranchProtected(ctx, branch.RepoID, branch.Name)
  461. if err != nil {
  462. return nil, fmt.Errorf("IsBranchProtected: %v", err)
  463. }
  464. if protected {
  465. // Skip protected branches,
  466. // since updates to protected branches often come from PR merges,
  467. // and they are unlikely to be used to create new PRs.
  468. continue
  469. }
  470. // whether branch have already created PR
  471. count, err := db.GetEngine(ctx).Table("pull_request").
  472. // we should not only use branch name here, because if there are branches with same name in other repos,
  473. // we can not detect them correctly
  474. Where(builder.Eq{"head_repo_id": branch.RepoID, "head_branch": branch.Name}).Count()
  475. if err != nil {
  476. return nil, err
  477. }
  478. // if no PR, we add to the result
  479. if count == 0 {
  480. if err := branch.LoadRepo(ctx); err != nil {
  481. return nil, err
  482. }
  483. branchDisplayName := branch.Name
  484. if branch.Repo.ID != opts.BaseRepo.ID && branch.Repo.ID != opts.Repo.ID {
  485. branchDisplayName = fmt.Sprintf("%s:%s", branch.Repo.FullName(), branchDisplayName)
  486. }
  487. newBranches = append(newBranches, &RecentlyPushedNewBranch{
  488. BranchRepo: branch.Repo,
  489. BranchDisplayName: branchDisplayName,
  490. BranchName: branch.Name,
  491. BranchLink: fmt.Sprintf("%s/src/branch/%s", branch.Repo.Link(), util.PathEscapeSegments(branch.Name)),
  492. BranchCompareURL: branch.Repo.ComposeBranchCompareURL(opts.BaseRepo, branch.Name),
  493. CommitTime: branch.CommitTime,
  494. })
  495. }
  496. if len(newBranches) == opts.MaxCount {
  497. break
  498. }
  499. }
  500. return newBranches, nil
  501. }