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.

70 lines
2.1 KiB

  1. // Copyright 2020 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 cache
  5. import (
  6. "crypto/sha256"
  7. "fmt"
  8. "code.gitea.io/gitea/modules/git"
  9. "code.gitea.io/gitea/modules/log"
  10. mc "gitea.com/macaron/cache"
  11. "github.com/go-git/go-git/v5/plumbing/object"
  12. )
  13. // LastCommitCache represents a cache to store last commit
  14. type LastCommitCache struct {
  15. repoPath string
  16. ttl int64
  17. repo *git.Repository
  18. commitCache map[string]*object.Commit
  19. mc.Cache
  20. }
  21. // NewLastCommitCache creates a new last commit cache for repo
  22. func NewLastCommitCache(repoPath string, gitRepo *git.Repository, ttl int64) *LastCommitCache {
  23. return &LastCommitCache{
  24. repoPath: repoPath,
  25. repo: gitRepo,
  26. commitCache: make(map[string]*object.Commit),
  27. ttl: ttl,
  28. Cache: conn,
  29. }
  30. }
  31. func (c LastCommitCache) getCacheKey(repoPath, ref, entryPath string) string {
  32. hashBytes := sha256.Sum256([]byte(fmt.Sprintf("%s:%s:%s", repoPath, ref, entryPath)))
  33. return fmt.Sprintf("last_commit:%x", hashBytes)
  34. }
  35. // Get get the last commit information by commit id and entry path
  36. func (c LastCommitCache) Get(ref, entryPath string) (*object.Commit, error) {
  37. v := c.Cache.Get(c.getCacheKey(c.repoPath, ref, entryPath))
  38. if vs, ok := v.(string); ok {
  39. log.Trace("LastCommitCache hit level 1: [%s:%s:%s]", ref, entryPath, vs)
  40. if commit, ok := c.commitCache[vs]; ok {
  41. log.Trace("LastCommitCache hit level 2: [%s:%s:%s]", ref, entryPath, vs)
  42. return commit, nil
  43. }
  44. id, err := c.repo.ConvertToSHA1(vs)
  45. if err != nil {
  46. return nil, err
  47. }
  48. commit, err := c.repo.GoGitRepo().CommitObject(id)
  49. if err != nil {
  50. return nil, err
  51. }
  52. c.commitCache[vs] = commit
  53. return commit, nil
  54. }
  55. return nil, nil
  56. }
  57. // Put put the last commit id with commit and entry path
  58. func (c LastCommitCache) Put(ref, entryPath, commitID string) error {
  59. log.Trace("LastCommitCache save: [%s:%s:%s]", ref, entryPath, commitID)
  60. return c.Cache.Put(c.getCacheKey(c.repoPath, ref, entryPath), commitID, c.ttl)
  61. }