this repo has no description
at main 89 lines 1.6 kB view raw
1package cache 2 3import ( 4 "sync" 5 6 "github.com/aottr/nox/internal/config" 7 "github.com/aottr/nox/internal/git" 8) 9 10type RepoKey struct { 11 Repo string 12 Branch string 13} 14 15type RepoCache struct { 16 mu sync.RWMutex 17 repos map[RepoKey]*git.ClonedRepo 18 // sf singleflight.Group TODO 19} 20 21var ( 22 GlobalCache = &RepoCache{ 23 repos: make(map[RepoKey]*git.ClonedRepo), 24 } 25) 26 27func (c *RepoCache) Get(key RepoKey) (*git.ClonedRepo, bool) { 28 c.mu.RLock() 29 defer c.mu.RUnlock() 30 tree, exists := c.repos[key] 31 return tree, exists 32} 33 34func (c *RepoCache) Set(key RepoKey, repo *git.ClonedRepo) { 35 c.mu.Lock() 36 defer c.mu.Unlock() 37 c.repos[key] = repo 38} 39 40func (c *RepoCache) FetchRepo(key RepoKey) (*git.ClonedRepo, error) { 41 r, err := git.CloneRepo(config.GitConfig{ 42 Repo: key.Repo, 43 Branch: key.Branch, 44 }) 45 if err != nil { 46 return nil, err 47 } 48 49 c.Set(key, r) 50 return r, nil 51} 52 53func (c *RepoCache) GetOrFetch(key RepoKey) (*git.ClonedRepo, error) { 54 tree, exists := c.Get(key) 55 if exists { 56 return tree, nil 57 } else { 58 return c.FetchRepo(key) 59 } 60} 61 62func (c *RepoCache) RefreshCache() error { 63 c.mu.RLock() 64 repos := make([]*git.ClonedRepo, 0, len(c.repos)) 65 for _, r := range c.repos { 66 repos = append(repos, r) 67 } 68 c.mu.RUnlock() 69 70 for _, repo := range repos { 71 if err := repo.Refresh(); err != nil { 72 return err 73 } 74 } 75 return nil 76} 77 78func (c *RepoCache) Has(key RepoKey) bool { 79 c.mu.RLock() 80 defer c.mu.RUnlock() 81 _, exists := c.repos[key] 82 return exists 83} 84 85func ClearRepoCache() { 86 GlobalCache.mu.Lock() 87 defer GlobalCache.mu.Unlock() 88 GlobalCache.repos = make(map[RepoKey]*git.ClonedRepo) 89}