1package cache
2
3import (
4 "fmt"
5
6 "github.com/MichaelMure/git-bug/repository"
7)
8
9const lockfile = "lock"
10const defaultRepoName = "__default"
11
12// MultiRepoCache is the root cache, holding multiple RepoCache.
13type MultiRepoCache struct {
14 repos map[string]*RepoCache
15}
16
17func NewMultiRepoCache() *MultiRepoCache {
18 return &MultiRepoCache{
19 repos: make(map[string]*RepoCache),
20 }
21}
22
23// RegisterRepository register a named repository. Use this for multi-repo setup
24func (c *MultiRepoCache) RegisterRepository(ref string, repo repository.ClockedRepo) (*RepoCache, chan BuildEvent, error) {
25 r, events, err := NewRepoCache(repo)
26 if err != nil {
27 return nil, nil, err
28 }
29
30 c.repos[ref] = r
31 return r, events, nil
32}
33
34// RegisterDefaultRepository register an unnamed repository. Use this for mono-repo setup
35func (c *MultiRepoCache) RegisterDefaultRepository(repo repository.ClockedRepo) (*RepoCache, chan BuildEvent, error) {
36 r, events, err := NewRepoCache(repo)
37 if err != nil {
38 return nil, nil, err
39 }
40
41 c.repos[defaultRepoName] = r
42 return r, events, nil
43}
44
45// DefaultRepo retrieve the default repository
46func (c *MultiRepoCache) DefaultRepo() (*RepoCache, error) {
47 if len(c.repos) != 1 {
48 return nil, fmt.Errorf("repository is not unique")
49 }
50
51 for _, r := range c.repos {
52 return r, nil
53 }
54
55 panic("unreachable")
56}
57
58// ResolveRepo retrieve a repository with a reference
59func (c *MultiRepoCache) ResolveRepo(ref string) (*RepoCache, error) {
60 r, ok := c.repos[ref]
61 if !ok {
62 return nil, fmt.Errorf("unknown repo")
63 }
64 return r, nil
65}
66
67// Close will do anything that is needed to close the cache properly
68func (c *MultiRepoCache) Close() error {
69 for _, cachedRepo := range c.repos {
70 err := cachedRepo.Close()
71 if err != nil {
72 return err
73 }
74 }
75 return nil
76}