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.

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