v16.go 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778
  1. // Copyright 2017 The Gogs 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. "path/filepath"
  8. "strings"
  9. "github.com/go-xorm/xorm"
  10. log "gopkg.in/clog.v1"
  11. "github.com/gogits/git-module"
  12. "github.com/gogits/gogs/pkg/setting"
  13. )
  14. func updateRepositorySizes(x *xorm.Engine) (err error) {
  15. log.Info("This migration could take up to minutes, please be patient.")
  16. type Repository struct {
  17. ID int64
  18. OwnerID int64
  19. Name string
  20. Size int64
  21. }
  22. type User struct {
  23. ID int64
  24. Name string
  25. }
  26. if err = x.Sync2(new(Repository)); err != nil {
  27. return fmt.Errorf("Sync2: %v", err)
  28. }
  29. // For the sake of SQLite3, we can't use x.Iterate here.
  30. offset := 0
  31. for {
  32. repos := make([]*Repository, 0, 10)
  33. if err = x.Sql(fmt.Sprintf("SELECT * FROM `repository` ORDER BY id ASC LIMIT 10 OFFSET %d", offset)).
  34. Find(&repos); err != nil {
  35. return fmt.Errorf("select repos [offset: %d]: %v", offset, err)
  36. }
  37. log.Trace("Select [offset: %d, repos: %d]", offset, len(repos))
  38. if len(repos) == 0 {
  39. break
  40. }
  41. offset += 10
  42. for _, repo := range repos {
  43. if repo.Name == "." || repo.Name == ".." {
  44. continue
  45. }
  46. user := new(User)
  47. has, err := x.Where("id = ?", repo.OwnerID).Get(user)
  48. if err != nil {
  49. return fmt.Errorf("query owner of repository [repo_id: %d, owner_id: %d]: %v", repo.ID, repo.OwnerID, err)
  50. } else if !has {
  51. continue
  52. }
  53. repoPath := filepath.Join(setting.RepoRootPath, strings.ToLower(user.Name), strings.ToLower(repo.Name)) + ".git"
  54. countObject, err := git.GetRepoSize(repoPath)
  55. if err != nil {
  56. log.Warn("GetRepoSize: %v", err)
  57. continue
  58. }
  59. repo.Size = countObject.Size + countObject.SizePack
  60. if _, err = x.Id(repo.ID).Cols("size").Update(repo); err != nil {
  61. return fmt.Errorf("update size: %v", err)
  62. }
  63. }
  64. }
  65. return nil
  66. }