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.

121 lines
2.4 KiB

  1. // Copyright 2019 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 migrations
  5. import (
  6. "fmt"
  7. "code.gitea.io/gitea/models"
  8. "code.gitea.io/gitea/modules/git"
  9. "github.com/go-xorm/xorm"
  10. )
  11. func fixReleaseSha1OnReleaseTable(x *xorm.Engine) error {
  12. type Release struct {
  13. ID int64
  14. RepoID int64
  15. Sha1 string
  16. TagName string
  17. }
  18. type Repository struct {
  19. ID int64
  20. OwnerID int64
  21. Name string
  22. }
  23. type User struct {
  24. ID int64
  25. Name string
  26. }
  27. // Update release sha1
  28. const batchSize = 100
  29. sess := x.NewSession()
  30. defer sess.Close()
  31. var (
  32. err error
  33. count int
  34. gitRepoCache = make(map[int64]*git.Repository)
  35. repoCache = make(map[int64]*Repository)
  36. userCache = make(map[int64]*User)
  37. )
  38. if err = sess.Begin(); err != nil {
  39. return err
  40. }
  41. for start := 0; ; start += batchSize {
  42. releases := make([]*Release, 0, batchSize)
  43. if err = sess.Limit(batchSize, start).Asc("id").Where("is_tag=?", false).Find(&releases); err != nil {
  44. return err
  45. }
  46. if len(releases) == 0 {
  47. break
  48. }
  49. for _, release := range releases {
  50. gitRepo, ok := gitRepoCache[release.RepoID]
  51. if !ok {
  52. repo, ok := repoCache[release.RepoID]
  53. if !ok {
  54. repo = new(Repository)
  55. has, err := sess.ID(release.RepoID).Get(repo)
  56. if err != nil {
  57. return err
  58. } else if !has {
  59. return fmt.Errorf("Repository %d is not exist", release.RepoID)
  60. }
  61. repoCache[release.RepoID] = repo
  62. }
  63. user, ok := userCache[repo.OwnerID]
  64. if !ok {
  65. user = new(User)
  66. has, err := sess.ID(repo.OwnerID).Get(user)
  67. if err != nil {
  68. return err
  69. } else if !has {
  70. return fmt.Errorf("User %d is not exist", repo.OwnerID)
  71. }
  72. userCache[repo.OwnerID] = user
  73. }
  74. gitRepo, err = git.OpenRepository(models.RepoPath(user.Name, repo.Name))
  75. if err != nil {
  76. return err
  77. }
  78. gitRepoCache[release.RepoID] = gitRepo
  79. }
  80. release.Sha1, err = gitRepo.GetTagCommitID(release.TagName)
  81. if err != nil && !git.IsErrNotExist(err) {
  82. return err
  83. }
  84. if err == nil {
  85. if _, err = sess.ID(release.ID).Cols("sha1").Update(release); err != nil {
  86. return err
  87. }
  88. }
  89. count++
  90. if count >= 1000 {
  91. if err = sess.Commit(); err != nil {
  92. return err
  93. }
  94. if err = sess.Begin(); err != nil {
  95. return err
  96. }
  97. count = 0
  98. }
  99. }
  100. }
  101. return sess.Commit()
  102. }