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